-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdomain.py
More file actions
987 lines (803 loc) · 30.9 KB
/
Copy pathdomain.py
File metadata and controls
987 lines (803 loc) · 30.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
import base64
import dataclasses
import datetime
import enum
import typing as t
from ._utils import _parse_iso
from .enums import (
ProcessState,
WebhookEvent,
WebhookDelivery,
MessagePriority,
LimitPeriod,
SimSelectionMode,
MessagesProcessingOrder,
HealthStatus,
LogEntryPriority,
)
from .webhooks import ( # noqa: F401 re-exported for backward compatibility
MmsDownloadedAttachment,
MmsDownloadedPayload,
MmsReceivedPayload,
)
def snake_to_camel(snake_str):
components = snake_str.split("_")
return components[0] + "".join(x.title() for x in components[1:])
@dataclasses.dataclass(frozen=True, kw_only=True)
class Message:
"""
Represents an SMS message.
Attributes:
phone_numbers (List[str]): Recipients (phone numbers).
text_message (Optional[TextMessage]): Text message.
data_message (Optional[DataMessage]): Data message.
priority (Optional[MessagePriority]): Priority.
sim_number (Optional[int]): SIM card number (1-3), if not set - default SIM will be used.
with_delivery_report (bool): With delivery report.
is_encrypted (bool): Is encrypted.
ttl (Optional[int]): Time to live in seconds (conflicts with `validUntil`).
valid_until (Optional[datetime.datetime]): Valid until (conflicts with `ttl`).
id (Optional[str]): ID (if not set - will be generated).
device_id (Optional[str]): Optional device ID for explicit selection.
"""
phone_numbers: t.List[str]
text_message: t.Optional["TextMessage"] = None
data_message: t.Optional["DataMessage"] = None
priority: t.Optional[MessagePriority] = None
sim_number: t.Optional[int] = None
with_delivery_report: bool = True
is_encrypted: bool = False
ttl: t.Optional[int] = None
valid_until: t.Optional[datetime.datetime] = None
id: t.Optional[str] = None
device_id: t.Optional[str] = None
def __post_init__(self):
if self.ttl is not None and self.valid_until is not None:
raise ValueError("ttl and valid_until are mutually exclusive")
@property
def content(self) -> str:
if self.text_message:
return self.text_message.text
if self.data_message:
return self.data_message.data
raise ValueError("Message has no content")
def asdict(self) -> t.Dict[str, t.Any]:
"""
Returns a dictionary representation of the message.
Returns:
Dict[str, Any]: A dictionary representation of the message.
"""
def _serialize(value: t.Any) -> t.Any:
if hasattr(value, "asdict"):
return value.asdict()
if isinstance(value, datetime.datetime):
return value.isoformat()
if isinstance(value, enum.Enum):
return value.value
return value
return {
snake_to_camel(f.name): _serialize(getattr(self, f.name))
for f in dataclasses.fields(self)
if getattr(self, f.name) is not None
}
@dataclasses.dataclass(frozen=True)
class DataMessage:
"""
Represents a data message.
Attributes:
data (str): Base64-encoded payload.
port (int): Destination port.
"""
data: str
port: int
def asdict(self) -> t.Dict[str, t.Any]:
return {
"data": self.data,
"port": self.port,
}
@classmethod
def with_bytes(cls, data: bytes, port: int) -> "DataMessage":
return cls(
data=base64.b64encode(data).decode("utf-8"),
port=port,
)
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "DataMessage":
"""Creates a DataMessage instance from a dictionary.
Args:
payload: A dictionary containing the data message's data.
Returns:
A DataMessage instance.
"""
return cls(
data=payload["data"],
port=payload["port"],
)
@dataclasses.dataclass(frozen=True)
class TextMessage:
"""
Represents a text message.
Attributes:
text (str): Message text.
"""
text: str
def asdict(self) -> t.Dict[str, t.Any]:
return {
"text": self.text,
}
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "TextMessage":
"""Creates a TextMessage instance from a dictionary.
Args:
payload: A dictionary containing the text message's data.
Returns:
A TextMessage instance.
"""
return cls(
text=payload["text"],
)
@dataclasses.dataclass(frozen=True)
class RecipientState:
phone_number: str
state: ProcessState
error: t.Optional[str]
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "RecipientState":
return cls(
phone_number=payload["phoneNumber"],
state=ProcessState(payload["state"]),
error=payload.get("error"),
)
@dataclasses.dataclass(frozen=True)
class MessageState:
id: str
state: ProcessState
recipients: t.List[RecipientState]
is_hashed: bool
is_encrypted: bool
device_id: t.Optional[str] = None
states: t.Optional[t.Dict[str, str]] = None
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "MessageState":
return cls(
id=payload["id"],
device_id=payload.get("deviceId"),
state=ProcessState(payload["state"]),
recipients=[
RecipientState.from_dict(recipient)
for recipient in payload["recipients"]
],
is_hashed=payload.get("isHashed", False),
is_encrypted=payload.get("isEncrypted", False),
states=payload.get("states"),
)
@dataclasses.dataclass(frozen=True)
class Webhook:
"""A webhook configuration."""
id: t.Optional[str]
"""The unique identifier of the webhook."""
url: str
"""The URL the webhook will be sent to."""
event: WebhookEvent
"""The type of event the webhook is triggered for."""
device_id: t.Optional[str] = None
"""The unique identifier of the device the webhook is associated with."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "Webhook":
"""Creates a Webhook instance from a dictionary.
Args:
payload: A dictionary containing the webhook's data.
Returns:
A Webhook instance.
"""
return cls(
id=payload.get("id"),
url=payload["url"],
event=WebhookEvent(payload["event"]),
device_id=payload.get("deviceId"),
)
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the webhook.
Returns:
A dictionary containing the webhook's data.
"""
result: t.Dict[str, t.Any] = {
"id": self.id,
"url": self.url,
"event": self.event.value,
}
if self.device_id is not None:
result["deviceId"] = self.device_id
return result
@dataclasses.dataclass(frozen=True)
class Device:
"""Represents a device."""
id: str
"""The unique identifier of the device."""
name: str
"""The name of the device."""
created_at: t.Optional[datetime.datetime] = None
"""The timestamp when the device was created."""
updated_at: t.Optional[datetime.datetime] = None
"""The timestamp when the device was last updated."""
deleted_at: t.Optional[datetime.datetime] = None
"""The timestamp when the device was deleted."""
last_seen: t.Optional[datetime.datetime] = None
"""The timestamp when the device was last seen."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "Device":
"""Creates a Device instance from a dictionary."""
return cls(
id=payload["id"],
name=payload["name"],
created_at=_parse_iso(payload.get("createdAt")),
updated_at=_parse_iso(payload.get("updatedAt")),
deleted_at=_parse_iso(payload.get("deletedAt")),
last_seen=_parse_iso(payload.get("lastSeen")),
)
@dataclasses.dataclass(frozen=True)
class ErrorResponse:
"""Represents an error response from the API."""
code: int
"""The error code."""
message: str
"""The error message."""
data: t.Optional[t.Any] = None
"""Additional error context."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "ErrorResponse":
"""Creates an ErrorResponse instance from a dictionary."""
return cls(
code=payload["code"],
message=payload["message"],
data=payload.get("data"),
)
@dataclasses.dataclass(frozen=True)
class TokenRequest:
"""Represents a request to generate a new JWT token."""
scopes: t.List[str]
"""List of scopes for the token."""
ttl: t.Optional[int] = None
"""Time to live for the token in seconds."""
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the token request.
Returns:
A dictionary containing the token request data.
"""
result: t.Dict[str, t.Any] = {
"scopes": self.scopes,
}
if self.ttl is not None:
result["ttl"] = self.ttl
return result
@dataclasses.dataclass(frozen=True)
class TokenResponse:
"""Represents a response when generating a new JWT token."""
access_token: str
"""The JWT access token."""
token_type: str
"""The type of the token (e.g., 'Bearer')."""
id: str
"""The unique identifier of the token (jti)."""
expires_at: str
"""The expiration time of the token in ISO format."""
refresh_token: t.Optional[str] = None
"""The refresh token."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "TokenResponse":
"""Creates a TokenResponse instance from a dictionary.
Args:
payload: A dictionary containing the token response data.
Returns:
A TokenResponse instance.
"""
return cls(
access_token=payload["accessToken"],
token_type=payload["tokenType"],
id=payload["id"],
expires_at=payload["expiresAt"],
refresh_token=payload.get("refreshToken"),
)
# Settings classes
@dataclasses.dataclass(frozen=True)
class SettingsGateway:
"""Gateway settings."""
cloud_url: t.Optional[str] = None
"""The URL of the cloud server."""
private_token: t.Optional[str] = None
"""The auth token for the private server."""
notification_channel: t.Optional[str] = None
"""The way device receives notifications (AUTO, SSE_ONLY)."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "SettingsGateway":
"""Creates a SettingsGateway instance from a dictionary."""
return cls(
cloud_url=payload.get("cloud_url"),
private_token=payload.get("private_token"),
notification_channel=payload.get("notification_channel"),
)
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the settings."""
result: t.Dict[str, t.Any] = {}
if self.cloud_url is not None:
result["cloud_url"] = self.cloud_url
if self.private_token is not None:
result["private_token"] = self.private_token
if self.notification_channel is not None:
result["notification_channel"] = self.notification_channel
return result
@dataclasses.dataclass(frozen=True)
class SettingsEncryption:
"""Encryption settings."""
passphrase: t.Optional[str] = None
"""The encryption passphrase."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "SettingsEncryption":
"""Creates a SettingsEncryption instance from a dictionary."""
return cls(
passphrase=payload.get("passphrase"),
)
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the settings."""
result: t.Dict[str, t.Any] = {}
if self.passphrase is not None:
result["passphrase"] = self.passphrase
return result
@dataclasses.dataclass(frozen=True)
class SettingsMessages:
"""Message handling settings."""
limit_period: t.Optional[LimitPeriod] = None
"""The period for message sending limits."""
limit_value: t.Optional[int] = None
"""The maximum number of messages allowed per limit period."""
log_lifetime_days: t.Optional[int] = None
"""The number of days to retain message logs."""
processing_order: t.Optional[MessagesProcessingOrder] = None
"""The order in which messages are processed."""
send_interval_max: t.Optional[int] = None
"""The maximum interval between message sends (in seconds)."""
send_interval_min: t.Optional[int] = None
"""The minimum interval between message sends (in seconds)."""
sim_selection_mode: t.Optional[SimSelectionMode] = None
"""How SIM cards are selected for sending messages."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "SettingsMessages":
"""Creates a SettingsMessages instance from a dictionary.
Args:
payload: A dictionary containing the settings data.
Returns:
A SettingsMessages instance.
"""
# Convert enum fields from strings to enum members
limit_period = payload.get("limit_period")
if limit_period is not None and isinstance(limit_period, str):
limit_period = LimitPeriod(limit_period)
processing_order = payload.get("processing_order")
if processing_order is not None and isinstance(processing_order, str):
processing_order = MessagesProcessingOrder(processing_order)
sim_selection_mode = payload.get("sim_selection_mode")
if sim_selection_mode is not None and isinstance(sim_selection_mode, str):
sim_selection_mode = SimSelectionMode(sim_selection_mode)
return cls(
limit_period=limit_period,
limit_value=payload.get("limit_value"),
log_lifetime_days=payload.get("log_lifetime_days"),
processing_order=processing_order,
send_interval_max=payload.get("send_interval_max"),
send_interval_min=payload.get("send_interval_min"),
sim_selection_mode=sim_selection_mode,
)
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the settings."""
result: t.Dict[str, t.Any] = {}
if self.limit_period is not None:
result["limit_period"] = self.limit_period.value
if self.limit_value is not None:
result["limit_value"] = self.limit_value
if self.log_lifetime_days is not None:
result["log_lifetime_days"] = self.log_lifetime_days
if self.processing_order is not None:
result["processing_order"] = self.processing_order.value
if self.send_interval_max is not None:
result["send_interval_max"] = self.send_interval_max
if self.send_interval_min is not None:
result["send_interval_min"] = self.send_interval_min
if self.sim_selection_mode is not None:
result["sim_selection_mode"] = self.sim_selection_mode.value
return result
@dataclasses.dataclass(frozen=True)
class SettingsLogs:
"""Logging settings."""
lifetime_days: t.Optional[int] = None
"""The number of days to retain logs."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "SettingsLogs":
"""Creates a SettingsLogs instance from a dictionary."""
return cls(
lifetime_days=payload.get("lifetime_days"),
)
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the settings."""
result: t.Dict[str, t.Any] = {}
if self.lifetime_days is not None:
result["lifetime_days"] = self.lifetime_days
return result
@dataclasses.dataclass(frozen=True)
class SettingsPing:
"""Ping settings."""
interval_seconds: t.Optional[int] = None
"""The interval between ping requests (in seconds)."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "SettingsPing":
"""Creates a SettingsPing instance from a dictionary."""
return cls(
interval_seconds=payload.get("interval_seconds"),
)
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the settings."""
result: t.Dict[str, t.Any] = {}
if self.interval_seconds is not None:
result["interval_seconds"] = self.interval_seconds
return result
@dataclasses.dataclass(frozen=True)
class SettingsWebhooks:
"""Webhook settings."""
retry_count: t.Optional[int] = None
"""The number of times to retry failed webhook deliveries."""
signing_key: t.Optional[str] = None
"""The secret key used for signing webhook payloads."""
internet_required: t.Optional[bool] = None
"""Whether internet access is required for webhooks."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "SettingsWebhooks":
"""Creates a SettingsWebhooks instance from a dictionary."""
return cls(
retry_count=payload.get("retry_count"),
signing_key=payload.get("signing_key"),
internet_required=payload.get("internet_required"),
)
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the settings."""
result: t.Dict[str, t.Any] = {}
if self.retry_count is not None:
result["retry_count"] = self.retry_count
if self.signing_key is not None:
result["signing_key"] = self.signing_key
if self.internet_required is not None:
result["internet_required"] = self.internet_required
return result
@dataclasses.dataclass(frozen=True)
class DeviceSettings:
"""Device settings."""
gateway: t.Optional[SettingsGateway] = None
"""Gateway settings."""
encryption: t.Optional[SettingsEncryption] = None
"""Encryption settings."""
messages: t.Optional[SettingsMessages] = None
"""Message handling settings."""
logs: t.Optional[SettingsLogs] = None
"""Logging settings."""
ping: t.Optional[SettingsPing] = None
"""Ping settings."""
webhooks: t.Optional[SettingsWebhooks] = None
"""Webhook settings."""
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the settings."""
result: t.Dict[str, t.Any] = {}
if self.gateway is not None:
result["gateway"] = self.gateway.asdict()
if self.encryption is not None:
result["encryption"] = self.encryption.asdict()
if self.messages is not None:
result["messages"] = self.messages.asdict()
if self.logs is not None:
result["logs"] = self.logs.asdict()
if self.ping is not None:
result["ping"] = self.ping.asdict()
if self.webhooks is not None:
result["webhooks"] = self.webhooks.asdict()
return result
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "DeviceSettings":
"""Creates a DeviceSettings instance from a dictionary.
Args:
payload: A dictionary containing the settings data.
Returns:
A DeviceSettings instance.
"""
gateway = None
if "gateway" in payload:
gateway = SettingsGateway.from_dict(payload["gateway"])
encryption = None
if "encryption" in payload:
encryption = SettingsEncryption.from_dict(payload["encryption"])
messages = None
if "messages" in payload:
messages = SettingsMessages.from_dict(payload["messages"])
logs = None
if "logs" in payload:
logs = SettingsLogs.from_dict(payload["logs"])
ping = None
if "ping" in payload:
ping = SettingsPing.from_dict(payload["ping"])
webhooks = None
if "webhooks" in payload:
webhooks = SettingsWebhooks.from_dict(payload["webhooks"])
return cls(
gateway=gateway,
encryption=encryption,
messages=messages,
logs=logs,
ping=ping,
webhooks=webhooks,
)
# Health check classes
@dataclasses.dataclass(frozen=True)
class HealthCheck:
"""Represents a health check."""
status: HealthStatus
"""The status of the check."""
description: t.Optional[str] = None
"""A human-readable description of the check."""
observed_value: t.Optional[int] = None
"""The observed value of the check."""
observed_unit: t.Optional[str] = None
"""The unit of measurement for the observed value."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "HealthCheck":
"""Creates a HealthCheck instance from a dictionary.
Args:
payload: A dictionary containing the health check data.
Returns:
A HealthCheck instance.
"""
return cls(
status=HealthStatus(payload["status"]),
description=payload.get("description"),
observed_value=payload.get("observedValue"),
observed_unit=payload.get("observedUnit"),
)
@dataclasses.dataclass(frozen=True)
class HealthResponse:
"""Represents a health check response."""
status: HealthStatus
"""The overall status of the application."""
version: t.Optional[str] = None
"""Version of the application."""
release_id: t.Optional[int] = None
"""Release ID of the application."""
checks: t.Optional[t.Dict[str, HealthCheck]] = None
"""A map of check names to their respective details."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "HealthResponse":
"""Creates a HealthResponse instance from a dictionary.
Args:
payload: A dictionary containing the health response data.
Returns:
A HealthResponse instance.
"""
checks = None
if "checks" in payload:
checks = {
name: HealthCheck.from_dict(check_data)
for name, check_data in payload["checks"].items()
}
return cls(
status=HealthStatus(payload["status"]),
version=payload.get("version"),
release_id=payload.get("releaseId"),
checks=checks,
)
# Log entry class
@dataclasses.dataclass(frozen=True)
class LogEntry:
"""Represents a log entry."""
id: int
"""A unique identifier for the log entry."""
created_at: datetime.datetime
"""The timestamp when this log entry was created."""
message: str
"""A message describing the log event."""
priority: LogEntryPriority
"""The priority level of the log entry."""
module: t.Optional[str] = None
"""The module or component of the system that generated the log entry."""
context: t.Optional[t.Dict[str, t.Any]] = None
"""Additional context information related to the log entry."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "LogEntry":
"""Creates a LogEntry instance from a dictionary.
Args:
payload: A dictionary containing the log entry data.
Returns:
A LogEntry instance.
"""
return cls(
id=payload["id"],
created_at=_parse_iso(payload["createdAt"]),
message=payload["message"],
priority=LogEntryPriority(payload["priority"]),
module=payload.get("module"),
context=payload.get("context"),
)
# Messages export request
@dataclasses.dataclass(frozen=True)
class MessagesExportRequest:
"""Represents a request to export inbox messages."""
device_id: str
"""The ID of the device to export messages for."""
since: datetime.datetime
"""The start of the time range to export."""
until: datetime.datetime
"""The end of the time range to export."""
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the request.
Returns:
A dictionary containing the request data.
"""
return {
"deviceId": self.device_id,
"since": self.since.isoformat(),
"until": self.until.isoformat(),
}
# Messages query request
@dataclasses.dataclass(frozen=True, kw_only=True)
class MessagesQueryFilter:
"""Filter parameters for message queries."""
from_: t.Optional[datetime.datetime] = None
"""Start date in RFC3339 format."""
to: t.Optional[datetime.datetime] = None
"""End date in RFC3339 format."""
state: t.Optional[str] = None
"""Filter messages by processing state."""
device_id: t.Optional[str] = None
"""Filter by device ID."""
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the query parameters.
Returns:
A dictionary containing the query parameters.
"""
params: t.Dict[str, t.Any] = {}
if self.from_ is not None:
params["from"] = self.from_.isoformat()
if self.to is not None:
params["to"] = self.to.isoformat()
if self.state is not None:
params["state"] = self.state
if self.device_id is not None:
params["deviceId"] = self.device_id
return params
@dataclasses.dataclass(frozen=True, kw_only=True)
class QueryPagination:
"""Pagination parameters for queries."""
limit: t.Optional[int] = None
"""Pagination limit."""
offset: t.Optional[int] = None
"""Pagination offset."""
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the query parameters.
Returns:
A dictionary containing the query parameters.
"""
params: t.Dict[str, t.Any] = {}
# Add pagination parameters
if self.limit is not None:
params["limit"] = self.limit
if self.offset is not None:
params["offset"] = self.offset
return params
# Inbox types
@dataclasses.dataclass(frozen=True)
class IncomingMessageAttachment:
"""Metadata for an MMS attachment returned by the inbox API."""
part_id: int
"""Part ID of the attachment, corresponding to the _id in content://mms/part."""
name: str
"""Display name of the attachment file."""
size: int
"""Size of the attachment in bytes."""
content_type: str
"""MIME type of the attachment (e.g. image/jpeg)."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "IncomingMessageAttachment":
"""Creates an IncomingMessageAttachment instance from a dictionary."""
return cls(
part_id=payload["partId"],
name=payload["name"],
size=payload["size"],
content_type=payload["contentType"],
)
@dataclasses.dataclass(frozen=True)
class IncomingMessage:
"""An incoming (received) message from the inbox."""
id: str
"""The unique identifier of the message."""
message_type: str
"""Message type (SMS, DATA_SMS, MMS, MMS_DOWNLOADED)."""
sender: str
"""Sender phone number."""
content_preview: str
"""A preview of the message content."""
created_at: datetime.datetime
"""When the message was received."""
recipient: t.Optional[str] = None
"""Recipient phone number (the device's number)."""
sim_number: t.Optional[int] = None
"""SIM card number that received the message."""
attachments: t.Optional[t.List[IncomingMessageAttachment]] = None
"""MMS attachment metadata (only present when include_attachments is true)."""
@classmethod
def from_dict(cls, payload: t.Dict[str, t.Any]) -> "IncomingMessage":
"""Creates an IncomingMessage instance from a dictionary."""
attachments = None
if "attachments" in payload and payload["attachments"] is not None:
attachments = [
IncomingMessageAttachment.from_dict(a) for a in payload["attachments"]
]
return cls(
id=payload["id"],
message_type=payload["type"],
sender=payload["sender"],
content_preview=payload["contentPreview"],
created_at=_parse_iso(payload["createdAt"]),
recipient=payload.get("recipient"),
sim_number=payload.get("simNumber"),
attachments=attachments,
)
@dataclasses.dataclass(frozen=True)
class InboxQueryFilter:
"""Filter parameters for inbox message queries."""
message_type: t.Optional[str] = None
"""Filter by message type (SMS, DATA_SMS, MMS, MMS_DOWNLOADED)."""
from_: t.Optional[datetime.datetime] = None
"""Start date in RFC3339 format."""
to: t.Optional[datetime.datetime] = None
"""End date in RFC3339 format."""
device_id: t.Optional[str] = None
"""Filter by device ID."""
include_attachments: t.Optional[bool] = None
"""Include attachment metadata in response (for MMS messages)."""
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the query parameters."""
params: t.Dict[str, t.Any] = {}
if self.message_type is not None:
params["type"] = self.message_type
if self.from_ is not None:
params["from"] = self.from_.isoformat()
if self.to is not None:
params["to"] = self.to.isoformat()
if self.device_id is not None:
params["deviceId"] = self.device_id
if self.include_attachments is not None:
params["includeAttachments"] = self.include_attachments
return params
# Inbox refresh request
@dataclasses.dataclass(frozen=True)
class InboxRefreshRequest:
"""Represents a request to refresh messages from the device inbox."""
since: datetime.datetime
"""The start of the time range to refresh."""
until: datetime.datetime
"""The end of the time range to refresh."""
device_id: t.Optional[str] = None
"""The ID of the device to refresh messages for."""
message_types: t.Optional[t.List[str]] = None
"""List of message types to refresh (SMS, DATA_SMS, MMS, MMS_DOWNLOADED)."""
webhook_delivery: t.Optional[WebhookDelivery] = None
"""Delivery mode for webhooks."""
def asdict(self) -> t.Dict[str, t.Any]:
"""Returns a dictionary representation of the request.
Returns:
A dictionary containing the request data.
"""
result: t.Dict[str, t.Any] = {
"since": self.since.isoformat(),
"until": self.until.isoformat(),
}
if self.device_id is not None:
result["deviceId"] = self.device_id
if self.message_types is not None:
result["messageTypes"] = self.message_types
if self.webhook_delivery is not None:
result["webhookDelivery"] = self.webhook_delivery.value
return result