pullkin 0.12.2__tar.gz → 0.14.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. {pullkin-0.12.2 → pullkin-0.14.0}/PKG-INFO +21 -9
  2. {pullkin-0.12.2 → pullkin-0.14.0}/README.md +11 -8
  3. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin/aioclient.py +148 -142
  4. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin/client_base.py +14 -8
  5. pullkin-0.14.0/pullkin/models/credentials.py +40 -0
  6. pullkin-0.14.0/pullkin/models/message.py +101 -0
  7. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin/models/service/responses.py +3 -5
  8. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin/proto/mcs_proto.py +22 -2
  9. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin.egg-info/PKG-INFO +21 -9
  10. pullkin-0.14.0/pullkin.egg-info/requires.txt +9 -0
  11. {pullkin-0.12.2 → pullkin-0.14.0}/tests/test_login.py +2 -2
  12. {pullkin-0.12.2 → pullkin-0.14.0}/tests/test_receiving.py +2 -1
  13. {pullkin-0.12.2 → pullkin-0.14.0}/tests/test_registration.py +2 -3
  14. pullkin-0.12.2/pullkin/models/credentials.py +0 -66
  15. pullkin-0.12.2/pullkin/models/message.py +0 -43
  16. pullkin-0.12.2/pullkin.egg-info/requires.txt +0 -8
  17. {pullkin-0.12.2 → pullkin-0.14.0}/LICENSE +0 -0
  18. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin/__init__.py +0 -0
  19. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin/__main__.py +0 -0
  20. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin/models/__init__.py +0 -0
  21. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin/models/service/__init__.py +0 -0
  22. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin/proto/__init__.py +0 -0
  23. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin/proto/android_checkin_proto.py +0 -0
  24. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin/proto/checkin_proto.py +0 -0
  25. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin.egg-info/SOURCES.txt +0 -0
  26. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin.egg-info/dependency_links.txt +0 -0
  27. {pullkin-0.12.2 → pullkin-0.14.0}/pullkin.egg-info/top_level.txt +0 -0
  28. {pullkin-0.12.2 → pullkin-0.14.0}/setup.cfg +0 -0
  29. {pullkin-0.12.2 → pullkin-0.14.0}/setup.py +0 -0
  30. {pullkin-0.12.2 → pullkin-0.14.0}/tests/__init__.py +0 -0
  31. {pullkin-0.12.2 → pullkin-0.14.0}/tests/conftest.py +0 -0
  32. {pullkin-0.12.2 → pullkin-0.14.0}/tests/testdata.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pullkin
3
- Version: 0.12.2
3
+ Version: 0.14.0
4
4
  Summary: Subscribe to GCM/FCM and receive notifications like an android app
5
5
  Home-page: https://github.com/WhiteApfel/pullkin
6
6
  Author: WhiteApfel
@@ -17,6 +17,15 @@ Classifier: Intended Audience :: Developers
17
17
  Classifier: Topic :: Software Development :: Libraries
18
18
  Description-Content-Type: text/markdown
19
19
  License-File: LICENSE
20
+ Requires-Dist: betterproto~=1.2.5
21
+ Requires-Dist: cryptography~=42.0.5
22
+ Requires-Dist: http-ece~=1.2.0
23
+ Requires-Dist: httpx~=0.27.0
24
+ Requires-Dist: loguru~=0.7.2
25
+ Requires-Dist: oscrypto~=1.3.0
26
+ Requires-Dist: pydantic~=2.6.2
27
+ Requires-Dist: python-dotenv~=1.0.1
28
+ Requires-Dist: ujson~=5.9.0
20
29
 
21
30
  # Pullkin
22
31
 
@@ -66,8 +75,10 @@ import asyncio
66
75
 
67
76
  from pullkin import Pullkin
68
77
  from pullkin.models import Message, AppCredentials
78
+ from pullkin.proto.mcs_proto import DataMessageStanza
69
79
 
70
80
  SENDER_ID = '<<SENDER_ID>>' # '1234567890'
81
+ # ANOTHER_SENDER_ID = '<<SENDER_ID>>' # '1234567890'
71
82
  APP_ID = '<<APP_ID>>' # '1:1234567890:android:abcdef1234567890'
72
83
  API_ID = '<<API_ID>>' # 'AIzaSyDce4zFw4CqLqW2eCOqTbXfDx9a8mRnLpI'
73
84
  FIREBASE_NAME = '<<FIREBASE_NAME' # 'pullkin-example'
@@ -88,7 +99,7 @@ with open(".persistent_ids.txt", "r") as f:
88
99
 
89
100
 
90
101
  @pullkin.on_notification()
91
- async def on_notification(message: Message, data_message):
102
+ async def on_notification(message: Message, data_message: DataMessageStanza):
92
103
  idstr = data_message.persistent_id + "\n"
93
104
  with open(".persistent_ids.txt", "r") as f:
94
105
  if idstr in f:
@@ -102,15 +113,16 @@ async def main():
102
113
  if not os.path.exists('.pullkin_app_credentials'):
103
114
  with open('.pullkin_app_credentials', 'w+') as f:
104
115
  credentials = await pullkin.register(SENDER_ID, APP_ID, API_ID, FIREBASE_NAME, ANDROID_CERT, APP_NAME)
105
- f.write(json.dumps(credentials.dict()))
116
+ f.write(json.dumps(credentials.model_dump(mode="json")))
106
117
  else:
107
118
  with open('.pullkin_app_credentials', 'r') as f:
108
- credentials = AppCredentials(**json.loads(f.read()))
109
- await pullkin.run(
110
- sender_id=SENDER_ID,
111
- credentials=credentials,
112
- persistent_ids=received_persistent_ids,
113
- )
119
+ credentials = AppCredentials.model_validate(json.loads(f.read()))
120
+
121
+ await pullkin.add_app(sender_id=SENDER_ID, credentials=credentials, persistent_ids=received_persistent_ids)
122
+ # await pullkin.add_app(sender_id=ANOTHER_SENDER_ID, credentials=another_credentials, persistent_ids=another_received_persistent_ids)
123
+
124
+
125
+ await pullkin.run()
114
126
 
115
127
 
116
128
  asyncio.run(main())
@@ -46,8 +46,10 @@ import asyncio
46
46
 
47
47
  from pullkin import Pullkin
48
48
  from pullkin.models import Message, AppCredentials
49
+ from pullkin.proto.mcs_proto import DataMessageStanza
49
50
 
50
51
  SENDER_ID = '<<SENDER_ID>>' # '1234567890'
52
+ # ANOTHER_SENDER_ID = '<<SENDER_ID>>' # '1234567890'
51
53
  APP_ID = '<<APP_ID>>' # '1:1234567890:android:abcdef1234567890'
52
54
  API_ID = '<<API_ID>>' # 'AIzaSyDce4zFw4CqLqW2eCOqTbXfDx9a8mRnLpI'
53
55
  FIREBASE_NAME = '<<FIREBASE_NAME' # 'pullkin-example'
@@ -68,7 +70,7 @@ with open(".persistent_ids.txt", "r") as f:
68
70
 
69
71
 
70
72
  @pullkin.on_notification()
71
- async def on_notification(message: Message, data_message):
73
+ async def on_notification(message: Message, data_message: DataMessageStanza):
72
74
  idstr = data_message.persistent_id + "\n"
73
75
  with open(".persistent_ids.txt", "r") as f:
74
76
  if idstr in f:
@@ -82,15 +84,16 @@ async def main():
82
84
  if not os.path.exists('.pullkin_app_credentials'):
83
85
  with open('.pullkin_app_credentials', 'w+') as f:
84
86
  credentials = await pullkin.register(SENDER_ID, APP_ID, API_ID, FIREBASE_NAME, ANDROID_CERT, APP_NAME)
85
- f.write(json.dumps(credentials.dict()))
87
+ f.write(json.dumps(credentials.model_dump(mode="json")))
86
88
  else:
87
89
  with open('.pullkin_app_credentials', 'r') as f:
88
- credentials = AppCredentials(**json.loads(f.read()))
89
- await pullkin.run(
90
- sender_id=SENDER_ID,
91
- credentials=credentials,
92
- persistent_ids=received_persistent_ids,
93
- )
90
+ credentials = AppCredentials.model_validate(json.loads(f.read()))
91
+
92
+ await pullkin.add_app(sender_id=SENDER_ID, credentials=credentials, persistent_ids=received_persistent_ids)
93
+ # await pullkin.add_app(sender_id=ANOTHER_SENDER_ID, credentials=another_credentials, persistent_ids=another_received_persistent_ids)
94
+
95
+
96
+ await pullkin.run()
94
97
 
95
98
 
96
99
  asyncio.run(main())
@@ -4,10 +4,9 @@ import json
4
4
  import ssl
5
5
  import struct
6
6
  import uuid
7
- from asyncio import StreamReader, StreamWriter
8
7
  from base64 import urlsafe_b64decode
9
8
  from binascii import hexlify
10
- from typing import AsyncGenerator, Awaitable, Callable, Optional, Union
9
+ from typing import Any, AsyncGenerator, Awaitable, Callable, Optional, Union
11
10
 
12
11
  import cryptography.hazmat.primitives.serialization as serialization
13
12
  import http_ece
@@ -16,7 +15,7 @@ from loguru import logger
16
15
 
17
16
  from pullkin.client_base import PullkinBase
18
17
  from pullkin.models import AppCredentials
19
- from pullkin.models.message import Message
18
+ from pullkin.models.message import Message, NotificationData
20
19
  from pullkin.proto.mcs_proto import * # noqa: F403
21
20
 
22
21
  logger.disable("pullkin")
@@ -25,8 +24,6 @@ logger.disable("pullkin")
25
24
  class Pullkin(PullkinBase):
26
25
  def __init__(self):
27
26
  super().__init__()
28
- self.__reader: Optional[StreamReader] = None
29
- self.__writer: Optional[StreamWriter] = None
30
27
  self.persistent_ids: list = []
31
28
  self.callback: Optional[
32
29
  Callable[[Optional[Message], DataMessageStanza], Optional[Awaitable]]
@@ -80,52 +77,15 @@ class Pullkin(PullkinBase):
80
77
 
81
78
  return decorator
82
79
 
83
- def register_on_notification_handler(
84
- self,
85
- handler_filter: Callable[[Optional[Message], DataMessageStanza], bool] = None,
86
- callback: Callable[
87
- [Optional[Message], DataMessageStanza], Optional[Awaitable]
88
- ] = None,
89
- ) -> None:
90
- """
91
- Function
92
-
93
- Registers a new callback with filter rule to trigger this callback
94
-
95
- filter: rule for calling thit callback
96
- callback: function to be called if the filter-function returns True
97
-
98
- First param to be passed into filter and callback: some object. Now is empty dict.
99
- Later you will be able to passed your object
100
- Second param: Notification object. You can read about Notification here: TODO: add a link
101
- Third param: Message object that get from socket. With all data about message. Read hereL TODO: add a link
102
-
103
- :: python code
104
- from pullkin import Pullkin, Notification, DataMessageStanza as Message
105
- pullkin = AuiPullkin()
106
-
107
- @pullkin.on_notification(lambda o, n, m: n.title == "Moi koleni zamerzli")
108
- def on_zemfira(obj, notification, message):
109
- print(notification.notification.body)
110
-
111
- @pullkin.on_notification(lambda o, n, m: n.priority == "normal")
112
- async def on_normal(obj: dict, notification: Notification, message: Message):
113
- print(f"#{message.id} @{message.sent})
114
- print(notification")
115
- await asyncio.sleep(2)
116
- print("=-)")
117
-
118
- """
119
- self.on_notification_handlers.append(
120
- {"callback": callback, "filter": handler_filter}
121
- )
122
-
123
80
  async def __run_on_notification_callbacks(
124
81
  self, message: Message, data_message: DataMessageStanza
125
82
  ) -> None:
126
83
  x = 0
127
84
  for handler in self.on_notification_handlers:
128
85
  if handler["filter"](message, data_message):
86
+ for field, annotation in handler["callback"].__annotations__.items():
87
+ if field != "return" and issubclass(annotation, Message) and message is not None:
88
+ message = message.to_another_model(annotation)
129
89
  if inspect.iscoroutinefunction(handler["callback"]):
130
90
  await handler["callback"](message, data_message)
131
91
  else:
@@ -143,60 +103,65 @@ class Pullkin(PullkinBase):
143
103
  if not x:
144
104
  logger.debug("No one callback was called")
145
105
 
146
- async def __open_connection(self) -> None:
106
+ async def __open_connection(self, sender_id: str) -> None:
147
107
  import ssl
148
108
 
149
109
  ssl_ctx = ssl.create_default_context()
150
- self.__reader, self.__writer = await asyncio.open_connection(
110
+ reader, writer = await asyncio.open_connection(
151
111
  self.PUSH_HOST, self.PUSH_PORT, ssl=ssl_ctx
152
112
  )
113
+ self.apps[sender_id]["reader"] = reader
114
+ self.apps[sender_id]["writer"] = writer
115
+
153
116
  logger.debug(
154
117
  f"Connected to SSL socket {self.PUSH_HOST}:{self.PUSH_PORT} with default"
155
118
  " ssl_context"
156
119
  )
157
120
 
158
- async def __read(self, size) -> bytes:
121
+ async def __read(self, sender_id: str, size: int) -> bytes:
159
122
  buf = b""
160
123
  while len(buf) < size:
161
- buf += await self.__reader.read(size - len(buf))
124
+ buf += await self.apps[sender_id]["reader"].read(size - len(buf))
162
125
  return buf
163
126
 
164
- async def __read_varint32(self) -> int:
127
+ async def __read_varint32(self, sender_id: str) -> int:
165
128
  res = 0
166
129
  shift = 0
167
130
  while True:
168
- (b,) = struct.unpack("B", await self.__read(1))
131
+ (b,) = struct.unpack("B", await self.__read(sender_id, 1))
169
132
  res |= (b & 0x7F) << shift
170
133
  if (b & 0x80) == 0:
171
134
  break
172
135
  shift += 7
173
136
  return res
174
137
 
175
- async def __send(self, packet) -> None:
138
+ async def __send(self, sender_id: str, packet) -> None:
176
139
  logger.debug(f"Send #{(send_id := str(uuid.uuid4()))}")
177
140
  header = bytearray([self.MCS_VERSION, self.PACKET_BY_TAG.index(type(packet))])
178
141
  logger.debug(f"Packet:\n'{packet}' #{send_id}")
179
142
  payload = packet.SerializeToString()
180
143
  buf = bytes(header) + self._encode_varint32(len(payload)) + payload
181
144
  logger.debug(f"HEX buffer:\n`{hexlify(buf)}` #{send_id}")
182
- self.__writer.write(buf)
183
- await self.__writer.drain()
145
+ self.apps[sender_id]["writer"].write(buf)
146
+ await self.apps[sender_id]["writer"].drain()
184
147
 
185
- async def __recv(self, first=False) -> Optional[PullkinBase.packet_union]:
148
+ async def __recv(
149
+ self, sender_id: str, first=False
150
+ ) -> Optional[PullkinBase.packet_union]:
186
151
  logger.debug(f"Receive #{(recv_id := str(uuid.uuid4()))}")
187
152
  if first:
188
- version, tag = struct.unpack("BB", await self.__read(2))
153
+ version, tag = struct.unpack("BB", await self.__read(sender_id, 2))
189
154
  logger.debug(f"Version {version}")
190
155
  if version < self.MCS_VERSION and version != 38:
191
156
  logger.error(f"Protocol version {version} unsupported")
192
157
  raise RuntimeError(f"Protocol version {version} unsupported")
193
158
  else:
194
- (tag,) = struct.unpack("B", await self.__read(1))
159
+ (tag,) = struct.unpack("B", await self.__read(sender_id, 1))
195
160
  logger.debug(f"Tag {tag} ({self.PACKET_BY_TAG[tag]}) #{recv_id}")
196
- size = await self.__read_varint32()
161
+ size = await self.__read_varint32(sender_id)
197
162
  logger.debug(f"Size {size} #{recv_id}")
198
163
  if size >= 0:
199
- buf = await self.__read(size)
164
+ buf = await self.__read(sender_id, size)
200
165
  logger.debug(f"HEX buffer:\n`{hexlify(buf)}` #{recv_id}")
201
166
  packet_class = self.PACKET_BY_TAG[tag]
202
167
  payload = packet_class()
@@ -205,12 +170,10 @@ class Pullkin(PullkinBase):
205
170
  return payload
206
171
  return None
207
172
 
208
- async def __listen_once(
209
- self,
210
- ) -> Optional[Message]:
173
+ async def __listen_once(self, sender_id: str) -> Optional[Message]:
211
174
  load_der_private_key = serialization.load_der_private_key
212
175
 
213
- p = await self.__recv()
176
+ p = await self.__recv(sender_id)
214
177
  if not isinstance(p, DataMessageStanza):
215
178
  logger.warning(f"Wow: other message {type(p)=}: {p.to_dict()}")
216
179
  return
@@ -243,7 +206,8 @@ class Pullkin(PullkinBase):
243
206
  version="aesgcm",
244
207
  auth_secret=secret, # noqa
245
208
  )
246
- message = Message(json.loads(decrypted.decode("utf-8")))
209
+ data: dict[str, Any] = json.loads(decrypted.decode("utf-8"))
210
+ message = Message[NotificationData].model_validate(data)
247
211
  await self.__run_on_notification_callbacks(message, p)
248
212
  return message
249
213
 
@@ -253,23 +217,19 @@ class Pullkin(PullkinBase):
253
217
  credentials: AppCredentials | None = None,
254
218
  persistent_ids: list[str] | None = None,
255
219
  ) -> None:
256
- if persistent_ids is None:
257
- persistent_ids = []
220
+ """
221
+ Connect "device" to "app" cloud messages. After this method messages will be delivered to this app.
258
222
 
259
- if credentials is None:
260
- if sender_id is not None and str(sender_id) in self.apps:
261
- credentials = self.apps.get(str(sender_id)).get("credentials")
262
- elif len(self.apps) == 1:
263
- credentials = self.apps.get(list(self.apps.keys())[0])
264
- else:
265
- if sender_id is not None:
266
- self.apps.setdefault(
267
- str(sender_id), {"credentials": None, "persistent_ids": []}
268
- )
269
- self.apps[str(sender_id)]["credentials"] = credentials
223
+ Args:
224
+ sender_id:
225
+ credentials:
226
+ persistent_ids:
270
227
 
271
- if credentials is None:
272
- raise ValueError("Credentials is None. See docs ") # TODO: add link
228
+ Returns:
229
+
230
+ """
231
+ if not (self.apps[sender_id]["reader"] or self.apps[sender_id]["writer"]):
232
+ await self.__open_connection(sender_id)
273
233
 
274
234
  await self.gcm_check_in(credentials.gcm)
275
235
  req = LoginRequest()
@@ -281,30 +241,27 @@ class Pullkin(PullkinBase):
281
241
  req.device_id = f"android-{credentials.gcm.android_id}"
282
242
  req.network_type = 1
283
243
  req.resource = credentials.gcm.android_id
284
- print("type", type(credentials.gcm.security_token))
285
244
  req.user = credentials.gcm.android_id
286
245
  req.use_rmq2 = True
287
246
  req.setting.append(Setting(name="new_vc", value="1"))
288
247
  req.received_persistent_id.extend(persistent_ids)
289
248
  try:
290
- await self.__send(req)
291
- await self.__recv(first=True)
249
+ await self.__send(sender_id, packet=req)
250
+ await self.__recv(sender_id, first=True)
292
251
  except: # noqa
293
252
  logger.exception("Error during send login request")
294
253
  raise
295
- self._started = True
254
+ self.apps[sender_id]["is_started"] = True
296
255
 
297
- async def __listen_coroutine(self) -> AsyncGenerator:
256
+ async def __listen_coroutine(self, sender_id: str) -> AsyncGenerator:
298
257
  while True:
299
- yield await self.__listen_once()
300
- if not self._started:
258
+ yield await self.__listen_once(sender_id)
259
+ if not self.apps[sender_id]["is_started"]:
301
260
  return
302
261
 
303
262
  async def listen_coroutine(
304
263
  self,
305
264
  sender_id: int | str | None = None,
306
- credentials: AppCredentials | None = None,
307
- persistent_ids: list[str] | None = None,
308
265
  ) -> AsyncGenerator:
309
266
  """
310
267
  Return a listener-coroutine
@@ -325,92 +282,141 @@ class Pullkin(PullkinBase):
325
282
  await coroutine.asend(None)
326
283
 
327
284
  # <some code>
328
-
329
- :return: coroutine
330
285
  """
331
286
  # TODO: add docs
332
-
333
- if not (self.__reader or self.__writer):
334
- await self.__open_connection()
335
- await self._listen_start(sender_id, credentials, persistent_ids)
336
- coroutine = self.__listen_coroutine()
287
+ coroutine = self.__listen_coroutine(sender_id)
337
288
  return coroutine
338
289
 
339
- async def _wait_start(self):
340
- while not all([self._started, self.__reader, self.__writer]):
290
+ async def _wait_start(self, sender_id: str):
291
+ while not all(
292
+ self.apps[sender_id][i] for i in ["is_started", "reader", "writer"]
293
+ ):
341
294
  await asyncio.sleep(0.01)
342
295
 
343
296
  async def _run_listener(
344
297
  self,
345
- sender_id: int | str | None = None,
346
- credentials: AppCredentials | None = None,
347
- persistent_ids: list[str] | None = None,
298
+ sender_id: str,
348
299
  timer: Union[int, float] = 0.05,
349
300
  ) -> None:
350
- if not (self.__reader or self.__writer):
351
- await self.__open_connection()
301
+ if not (self.apps[sender_id]["reader"] or self.apps[sender_id]["writer"]):
302
+ await self.__open_connection(sender_id)
303
+
304
+ coroutine = self.__listen_coroutine(sender_id)
352
305
 
353
- await self._listen_start(sender_id, credentials, persistent_ids)
354
- coroutine = self.__listen_coroutine()
355
306
  try:
356
- while self.__reader and self.__writer:
307
+ while self.apps[sender_id]["reader"] and self.apps[sender_id]["writer"]:
357
308
  await coroutine.asend(None)
358
309
  await asyncio.sleep(timer)
359
310
  except (KeyboardInterrupt, asyncio.CancelledError):
360
- ...
311
+ await self.close()
361
312
  except: # noqa: E722
362
313
  logger.exception("Error while listen:")
363
314
  raise
364
315
  finally:
365
316
  await self.close()
366
317
 
367
- async def run(
368
- self,
369
- timer: Union[int, float] = 0.05,
370
- sender_id: int | str | None = None,
371
- credentials: AppCredentials | None = None,
372
- persistent_ids: list[str] | None = None,
373
- ) -> None:
318
+ async def add_app(
319
+ self, sender_id: str, credentials: AppCredentials, persistent_ids: list[str]
320
+ ):
374
321
  """
375
- Listens for push notifications
322
+ Subscribe device to app
376
323
 
377
- Runs an endless loop for reading notifications and distributing among callbacks based on filter results
324
+ Args:
325
+ sender_id:
326
+ credentials:
327
+ persistent_ids:
328
+
329
+ Returns:
378
330
 
379
- :param timer: timer in seconds between receive iteration
380
- :type timer: ``int`` or ``float``, optional, default ``0.05``
381
331
  """
382
- # TODO: add docs
332
+ if persistent_ids is None:
333
+ persistent_ids = []
334
+
335
+ if credentials is None:
336
+ if sender_id is not None and str(sender_id) in self.apps:
337
+ credentials = self.apps.get(str(sender_id)).get("credentials")
338
+ elif sender_id is None and len(self.apps) == 1:
339
+ credentials = self.apps.get(list(self.apps.keys())[0])
340
+ else:
341
+ if sender_id is not None:
342
+ self.apps.setdefault(
343
+ str(sender_id),
344
+ {
345
+ "credentials": None,
346
+ "persistent_ids": [],
347
+ "is_started": False,
348
+ "reader": None,
349
+ "writer": None,
350
+ "listener": None,
351
+ },
352
+ )
353
+ self.apps[str(sender_id)]["credentials"] = credentials
383
354
 
384
- asyncio.create_task(
385
- self._run_listener(sender_id, credentials, persistent_ids, timer)
355
+ if credentials is None:
356
+ raise ValueError("Credentials is None. See docs ") # TODO: add link
357
+
358
+ task = asyncio.create_task(
359
+ self._listen_start(sender_id, credentials, persistent_ids)
386
360
  )
387
361
  try:
388
- await asyncio.wait_for(self._wait_start(), timeout=10)
362
+ await asyncio.wait_for(self._wait_start(sender_id), timeout=10)
389
363
  except asyncio.exceptions.TimeoutError:
390
- logger.error("Timeout start listener 10s")
364
+ task.cancel()
365
+ logger.error("Timeout subscribe device to app 10s")
391
366
  except (KeyboardInterrupt, asyncio.CancelledError):
392
367
  return
393
368
  except: # noqa: E722
394
369
  logger.exception("Wait start error:")
395
370
  raise
396
371
 
397
- async def close(self):
398
- try:
399
- if self._http_client:
400
- await self._http_client.aclose()
401
- self._http_client = None
402
- if self.__writer:
403
- self.__writer.close()
404
- await asyncio.wait_for(self.__writer.wait_closed(), 5)
405
- self.__writer = None
406
- self.__reader = None
407
- self._started = False
408
- except asyncio.exceptions.TimeoutError:
409
- return
410
- except ConnectionResetError:
411
- return
412
- except ssl.SSLError:
413
- return
414
- except: # noqa: E722
415
- logger.exception("Error during close Pullkin:")
416
- raise
372
+ async def run(
373
+ self,
374
+ sender_ids: list[str] | None = None,
375
+ timer: Union[int, float] = 0.05,
376
+ ) -> None:
377
+ """
378
+ Listens for push notifications
379
+
380
+ Runs an endless loop for reading notifications and distributing among callbacks based on filter results
381
+
382
+ Args:
383
+ sender_ids: sender_ids to listening in background
384
+ timer: timer in seconds between receive iteration
385
+ """
386
+ # TODO: add docs
387
+
388
+ for sender_id in self.apps:
389
+ if sender_ids is None or sender_id in sender_ids:
390
+ self.apps[sender_id]["listener"] = asyncio.create_task(
391
+ self._run_listener(sender_id, timer)
392
+ )
393
+
394
+ async def close(self, sender_id: str | None = None):
395
+ for i_sender_id, app_data in self.apps.items():
396
+ if sender_id == i_sender_id or sender_id is None:
397
+ if app_data["listener"]:
398
+ app_data["listener"].cancel()
399
+
400
+ if app_data["writer"]:
401
+ try:
402
+ app_data["is_started"] = False
403
+ app_data["writer"].close()
404
+ try:
405
+ await asyncio.wait_for(app_data["writer"].wait_closed(), 5)
406
+ except asyncio.exceptions.TimeoutError: # noqa
407
+ ... # noqa
408
+ app_data["writer"] = None
409
+ app_data["reader"] = None
410
+ except ConnectionResetError:
411
+ continue
412
+ except ssl.SSLError:
413
+ continue
414
+ except: # noqa: E722
415
+ logger.exception("Error during close Pullkin:")
416
+ raise
417
+
418
+ del self.apps[sender_id]
419
+
420
+ if sender_id is None and self._http_client and len(self.apps) == 0:
421
+ await self._http_client.aclose()
422
+ self._http_client = None
@@ -5,8 +5,9 @@ import json
5
5
  import os
6
6
  import secrets
7
7
  import time
8
+ from asyncio import StreamReader, StreamWriter, Task
8
9
  from base64 import urlsafe_b64encode
9
- from typing import Optional, Union
10
+ from typing import Optional, TypedDict, Union
10
11
  from urllib.parse import urlencode
11
12
 
12
13
  from httpx import AsyncClient, Request
@@ -22,6 +23,15 @@ from pullkin.proto.mcs_proto import * # noqa: F403
22
23
  logger.disable("pullkin")
23
24
 
24
25
 
26
+ class AppDataDict(TypedDict):
27
+ credentials: AppCredentials | None
28
+ persistent_ids: list[str]
29
+ is_started: bool
30
+ reader: StreamReader | None
31
+ writer: StreamWriter | None
32
+ listener: Task | None
33
+
34
+
25
35
  class PullkinBase:
26
36
  unicode = str
27
37
 
@@ -77,7 +87,7 @@ class PullkinBase:
77
87
  def __init__(self):
78
88
  self._http_client = None
79
89
  self.credentials: Optional[AppCredentials] = None
80
- self.apps: dict[dict[str, AppCredentials | list[str]]] = {}
90
+ self.apps: dict[str, AppDataDict] = {}
81
91
 
82
92
  @property
83
93
  def http_client(self):
@@ -344,7 +354,7 @@ class PullkinBase:
344
354
  app_id: str,
345
355
  api_key: str,
346
356
  firebase_name: str,
347
- android_cert: str = 'da39a3ee5e6b4b0d3255bfef95601890afd80709',
357
+ android_cert: str = "da39a3ee5e6b4b0d3255bfef95601890afd80709",
348
358
  app_name: str = "org.chromium.linux",
349
359
  ) -> AppCredentials:
350
360
  """register gcm and fcm tokens for sender_id"""
@@ -362,11 +372,7 @@ class PullkinBase:
362
372
  res = {"gcm": gcm_result}
363
373
  res.update(fcm)
364
374
 
365
- self.apps.setdefault(
366
- str(sender_id), {"credentials": None, "persistent_ids": []}
367
- )
368
- self.apps[str(sender_id)]["credentials"] = AppCredentials(**res)
369
- return self.apps[str(sender_id)]["credentials"]
375
+ return AppCredentials.model_validate(res)
370
376
 
371
377
  @classmethod
372
378
  def _encode_varint32(cls, x):
@@ -0,0 +1,40 @@
1
+ from typing import Annotated
2
+
3
+ from pydantic import BaseModel, BeforeValidator
4
+
5
+
6
+ class FirebaseInstallationResponse(BaseModel):
7
+ name: str
8
+ fid: str
9
+ refresh_token: str
10
+ auth_token: str
11
+ auth_token_expires_in: int
12
+
13
+
14
+ class CheckInResponse(BaseModel):
15
+ stats_ok: bool
16
+
17
+
18
+ class AppCredentialsGcm(BaseModel):
19
+ token: str
20
+ app_id: str
21
+ android_id: Annotated[str, BeforeValidator(lambda x: str(x))]
22
+ security_token: Annotated[str, BeforeValidator(lambda x: str(x))]
23
+ installation: FirebaseInstallationResponse
24
+
25
+
26
+ class AppCredentialsFcm(BaseModel):
27
+ token: str
28
+ pushSet: str
29
+
30
+
31
+ class AppCredentialsKeys(BaseModel):
32
+ public: str
33
+ private: str
34
+ secret: str
35
+
36
+
37
+ class AppCredentials(BaseModel):
38
+ gcm: AppCredentialsGcm
39
+ fcm: AppCredentialsFcm
40
+ keys: AppCredentialsKeys
@@ -0,0 +1,101 @@
1
+ from typing import Any, Generic, TypeVar
2
+
3
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
4
+
5
+ from pullkin.proto.mcs_proto import AppData
6
+
7
+
8
+ class NotificationData(BaseModel):
9
+ """
10
+ You can create a child model that describes the fields you use in the notification.
11
+
12
+ Example:
13
+ class MyNotificationData(NotificationData):
14
+ title: str
15
+ body: str
16
+ my_field: str
17
+ my_another_field: dict[str, str]
18
+
19
+ message: Message[MyNotificationData] = ...
20
+ """
21
+
22
+ model_config = ConfigDict(extra="allow")
23
+
24
+ raw: dict[str, Any]
25
+
26
+ title: str | None = None
27
+ body: str | None = None
28
+
29
+ @model_validator(mode="before")
30
+ def add_raw(cls, values: dict[str, Any]) -> dict[str, Any]:
31
+ if "raw" not in values:
32
+ values["raw"] = dict(values)
33
+
34
+ return values
35
+
36
+ def __str__(self):
37
+ return str(self.raw)
38
+
39
+
40
+ NotificationDataType = TypeVar("NotificationDataType", bound=NotificationData)
41
+ MessageType = TypeVar("MessageType")
42
+
43
+
44
+ class Message(BaseModel, Generic[NotificationDataType]):
45
+ """
46
+ You can create a child model that describes the fields you use in the notification.
47
+
48
+ Example:
49
+ class MyMessage(Message):
50
+ my_field: str
51
+
52
+ class MyMessageWithGeneric(Message[MyNotificationData]):
53
+
54
+ """
55
+
56
+ model_config = ConfigDict(extra="allow")
57
+
58
+ raw: dict[str, Any]
59
+
60
+ data: dict[str, Any] | None = None
61
+ sender_id: str | None = Field(None, alias="from")
62
+ priority: str | None = None
63
+ notification: NotificationDataType | None = None
64
+ fcm_message_id: str | None = Field(None, alias="fcmMessageId")
65
+
66
+ @model_validator(mode="before")
67
+ def add_raw(cls, values: dict[str, Any]) -> dict[str, Any]:
68
+ if "raw" not in values:
69
+ values["raw"] = dict(values)
70
+
71
+ return values
72
+
73
+ def to_another_model(self, another_model: MessageType) -> MessageType:
74
+ """
75
+ You can use this method to convert model to your model.
76
+ A message will be converted into the another_model using another_model.model_validate(self.raw)
77
+
78
+ message: Message = ...
79
+
80
+ my_message: Message[MyNotificationData] = message.to_another_model(Message[MyNotificationData])
81
+ my_message: MyMessage[MyNotificationData] = message.to_another_model(MyMessage[MyNotificationData])
82
+ my_message: MyMessage[NotificationData] = message.to_another_model(MyMessage[NotificationData])
83
+ my_message: MyMessage = message.to_another_model(MyMessage)
84
+ # or use simple
85
+ my_message: MyMessage[MyNotificationData] = MyMessage[MyNotificationData].model_validate(message.raw)
86
+ """
87
+ generic_metadata = another_model.__pydantic_generic_metadata__
88
+
89
+ MessageModel = generic_metadata.get("origin") or Message
90
+ (NotificationModel,) = generic_metadata.get("args") or (None,)
91
+
92
+ if NotificationModel:
93
+ return MessageModel[NotificationModel].model_validate(self.raw)
94
+
95
+ return MessageModel.model_validate(self.raw)
96
+
97
+ def __getitem__(self, item):
98
+ return self.raw[item]
99
+
100
+ def __str__(self):
101
+ return str(self.raw)
@@ -1,8 +1,7 @@
1
- from dataclasses import dataclass
1
+ from pydantic import BaseModel
2
2
 
3
3
 
4
- @dataclass
5
- class CheckinResponse:
4
+ class CheckinResponse(BaseModel):
6
5
  is_ok: bool
7
6
  time_ms: int
8
7
  android_id: str
@@ -11,6 +10,5 @@ class CheckinResponse:
11
10
  device_data_version_info: str
12
11
 
13
12
 
14
- @dataclass
15
- class GcmRegisterResponse:
13
+ class GcmRegisterResponse(BaseModel):
16
14
  token: str
@@ -2,7 +2,7 @@
2
2
  # sources: mcs.proto
3
3
  # plugin: python-betterproto
4
4
  from dataclasses import dataclass
5
- from typing import List
5
+ from typing import List, Any
6
6
 
7
7
  import betterproto
8
8
 
@@ -192,6 +192,26 @@ class AppData(betterproto.Message):
192
192
  value: str = betterproto.string_field(2)
193
193
 
194
194
 
195
+ class AppDataList(list):
196
+ def __getitem__(self, item) -> AppData:
197
+ if isinstance(item, str):
198
+ for x in self:
199
+ if x.key == item:
200
+ return x.value
201
+ return super().__getitem__(item)
202
+
203
+ def __contains__(self, item) -> bool:
204
+ if isinstance(item, str):
205
+ for x in self:
206
+ if x.key == item:
207
+ return True
208
+ return False
209
+ return super().__getitem__(item)
210
+
211
+ def to_dict(self) -> dict[str, Any]:
212
+ return {i.key: i.value for i in self}
213
+
214
+
195
215
  @dataclass
196
216
  class DataMessageStanza(betterproto.Message):
197
217
  """* TAG: 8"""
@@ -207,7 +227,7 @@ class DataMessageStanza(betterproto.Message):
207
227
  # The collapsed key, DMP.3
208
228
  token: str = betterproto.string_field(6)
209
229
  # User data + GOOGLE. prefixed special entries, DMP.4
210
- app_data: List["AppData"] = betterproto.message_field(7)
230
+ app_data: AppDataList["AppData"] = betterproto.message_field(7)
211
231
  # Not used.
212
232
  from_trusted_server: bool = betterproto.bool_field(8)
213
233
  # Part of the ACK protocol, returned in DataMessageResponse on server side.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pullkin
3
- Version: 0.12.2
3
+ Version: 0.14.0
4
4
  Summary: Subscribe to GCM/FCM and receive notifications like an android app
5
5
  Home-page: https://github.com/WhiteApfel/pullkin
6
6
  Author: WhiteApfel
@@ -17,6 +17,15 @@ Classifier: Intended Audience :: Developers
17
17
  Classifier: Topic :: Software Development :: Libraries
18
18
  Description-Content-Type: text/markdown
19
19
  License-File: LICENSE
20
+ Requires-Dist: betterproto~=1.2.5
21
+ Requires-Dist: cryptography~=42.0.5
22
+ Requires-Dist: http-ece~=1.2.0
23
+ Requires-Dist: httpx~=0.27.0
24
+ Requires-Dist: loguru~=0.7.2
25
+ Requires-Dist: oscrypto~=1.3.0
26
+ Requires-Dist: pydantic~=2.6.2
27
+ Requires-Dist: python-dotenv~=1.0.1
28
+ Requires-Dist: ujson~=5.9.0
20
29
 
21
30
  # Pullkin
22
31
 
@@ -66,8 +75,10 @@ import asyncio
66
75
 
67
76
  from pullkin import Pullkin
68
77
  from pullkin.models import Message, AppCredentials
78
+ from pullkin.proto.mcs_proto import DataMessageStanza
69
79
 
70
80
  SENDER_ID = '<<SENDER_ID>>' # '1234567890'
81
+ # ANOTHER_SENDER_ID = '<<SENDER_ID>>' # '1234567890'
71
82
  APP_ID = '<<APP_ID>>' # '1:1234567890:android:abcdef1234567890'
72
83
  API_ID = '<<API_ID>>' # 'AIzaSyDce4zFw4CqLqW2eCOqTbXfDx9a8mRnLpI'
73
84
  FIREBASE_NAME = '<<FIREBASE_NAME' # 'pullkin-example'
@@ -88,7 +99,7 @@ with open(".persistent_ids.txt", "r") as f:
88
99
 
89
100
 
90
101
  @pullkin.on_notification()
91
- async def on_notification(message: Message, data_message):
102
+ async def on_notification(message: Message, data_message: DataMessageStanza):
92
103
  idstr = data_message.persistent_id + "\n"
93
104
  with open(".persistent_ids.txt", "r") as f:
94
105
  if idstr in f:
@@ -102,15 +113,16 @@ async def main():
102
113
  if not os.path.exists('.pullkin_app_credentials'):
103
114
  with open('.pullkin_app_credentials', 'w+') as f:
104
115
  credentials = await pullkin.register(SENDER_ID, APP_ID, API_ID, FIREBASE_NAME, ANDROID_CERT, APP_NAME)
105
- f.write(json.dumps(credentials.dict()))
116
+ f.write(json.dumps(credentials.model_dump(mode="json")))
106
117
  else:
107
118
  with open('.pullkin_app_credentials', 'r') as f:
108
- credentials = AppCredentials(**json.loads(f.read()))
109
- await pullkin.run(
110
- sender_id=SENDER_ID,
111
- credentials=credentials,
112
- persistent_ids=received_persistent_ids,
113
- )
119
+ credentials = AppCredentials.model_validate(json.loads(f.read()))
120
+
121
+ await pullkin.add_app(sender_id=SENDER_ID, credentials=credentials, persistent_ids=received_persistent_ids)
122
+ # await pullkin.add_app(sender_id=ANOTHER_SENDER_ID, credentials=another_credentials, persistent_ids=another_received_persistent_ids)
123
+
124
+
125
+ await pullkin.run()
114
126
 
115
127
 
116
128
  asyncio.run(main())
@@ -0,0 +1,9 @@
1
+ betterproto~=1.2.5
2
+ cryptography~=42.0.5
3
+ http-ece~=1.2.0
4
+ httpx~=0.27.0
5
+ loguru~=0.7.2
6
+ oscrypto~=1.3.0
7
+ pydantic~=2.6.2
8
+ python-dotenv~=1.0.1
9
+ ujson~=5.9.0
@@ -17,5 +17,5 @@ async def test_aio_login():
17
17
  credentials = await client.register(
18
18
  SENDER_ID, APP_ID, API_KEY, FIREBASE_NAME, ANDROID_CERT, APP_NAME
19
19
  )
20
-
21
- await client.listen_coroutine(SENDER_ID, credentials)
20
+ await client.add_app(SENDER_ID, credentials=credentials, persistent_ids=[])
21
+ await client.listen_coroutine(SENDER_ID)
@@ -27,7 +27,8 @@ async def test_aio_receive(fcm: FirebaseAdmin):
27
27
  def on_notification(message: Message, data_message):
28
28
  print(message)
29
29
 
30
- coroutine = await client.listen_coroutine(SENDER_ID, fcm_cred)
30
+ await client.add_app(SENDER_ID, fcm_cred, [])
31
+ coroutine = await client.listen_coroutine(SENDER_ID)
31
32
 
32
33
  notification_title = uuid4().hex
33
34
  notification_body = uuid4().hex
@@ -1,8 +1,7 @@
1
- from dataclasses import is_dataclass
2
-
3
1
  import pytest
4
2
 
5
3
  from pullkin import Pullkin
4
+ from pullkin.models import AppCredentials
6
5
  from tests.testdata import (
7
6
  ANDROID_CERT,
8
7
  API_KEY,
@@ -20,4 +19,4 @@ async def test_aio_registration():
20
19
  SENDER_ID, APP_ID, API_KEY, FIREBASE_NAME, ANDROID_CERT, APP_NAME
21
20
  )
22
21
 
23
- assert is_dataclass(credentials)
22
+ assert isinstance(credentials, AppCredentials)
@@ -1,66 +0,0 @@
1
- from dataclasses import asdict, dataclass
2
- from typing import Union
3
-
4
-
5
- @dataclass
6
- class FirebaseInstallationResponse:
7
- name: str
8
- fid: str
9
- refresh_token: str
10
- auth_token: str
11
- auth_token_expires_in: int
12
-
13
-
14
- @dataclass
15
- class CheckInResponse:
16
- stats_ok: bool
17
-
18
-
19
- @dataclass
20
- class AppCredentialsGcm:
21
- token: str
22
- app_id: str
23
- android_id: str
24
- security_token: str
25
- installation: FirebaseInstallationResponse
26
-
27
- def __post_init__(self):
28
- if isinstance(self.android_id, int):
29
- self.android_id = str(self.android_id)
30
-
31
- if isinstance(self.security_token, int):
32
- self.security_token = str(self.security_token)
33
-
34
-
35
- @dataclass
36
- class AppCredentialsFcm:
37
- token: str
38
- pushSet: str
39
-
40
-
41
- @dataclass
42
- class AppCredentialsKeys:
43
- public: str
44
- private: str
45
- secret: str
46
-
47
-
48
- @dataclass
49
- class AppCredentials:
50
- gcm: Union[AppCredentialsGcm, dict]
51
- fcm: Union[AppCredentialsFcm, dict]
52
- keys: Union[AppCredentialsKeys, dict]
53
-
54
- def __post_init__(self):
55
- if isinstance(self.gcm, dict):
56
- self.gcm: AppCredentialsGcm = AppCredentialsGcm(**self.gcm) # type: ignore
57
- if isinstance(self.fcm, dict):
58
- self.fcm: AppCredentialsFcm = AppCredentialsFcm(**self.fcm) # type: ignore
59
- if isinstance(self.keys, dict):
60
- self.keys: AppCredentialsKeys = AppCredentialsKeys(**self.keys) # type: ignore
61
-
62
- def __dict__(self):
63
- return asdict(self)
64
-
65
- def dict(self):
66
- return self.__dict__()
@@ -1,43 +0,0 @@
1
- from copy import deepcopy
2
- from typing import Optional
3
-
4
-
5
- class NotificationData:
6
- def __init__(self, data: dict = None):
7
- if not data:
8
- data = {}
9
- self.raw_data: dict = deepcopy(data)
10
- self.title: str = data.pop("title", None)
11
- self.body: str = data.pop("body", None)
12
- if data:
13
- for k, v in data.items():
14
- self.__setattr__(k, v)
15
-
16
- def __str__(self):
17
- export = self.__dict__.copy()
18
- del export["raw_data"]
19
- return str(export)
20
-
21
-
22
- class Message:
23
- def __init__(self, data: dict = None):
24
- if not data:
25
- data = {}
26
- self.raw_data: dict = deepcopy(data)
27
- self.sender_id: Optional[str] = data.pop("from", None)
28
- self.priority: Optional[str] = data.pop("priority", None)
29
- self.notification: NotificationData = NotificationData(
30
- data.pop("notification", None)
31
- )
32
- self.fcmMessageId: Optional[str] = data.pop("fcmMessageId", None)
33
- if data:
34
- for k, v in data.items():
35
- self.__setattr__(k, v)
36
-
37
- def __getitem__(self, item):
38
- return self.raw_data[item]
39
-
40
- def __str__(self):
41
- export = self.__dict__.copy()
42
- del export["raw_data"]
43
- return str(export)
@@ -1,8 +0,0 @@
1
- asyncio~=3.4.3
2
- betterproto~=1.2.5
3
- cryptography~=41.0.3
4
- http-ece~=1.1.0
5
- httpx~=0.24.1
6
- loguru~=0.7.0
7
- oscrypto==1.3.0
8
- python-dotenv==1.0.0
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes