session-python 1.0.0__py3-none-any.whl

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.
@@ -0,0 +1,222 @@
1
+ import time
2
+ import binascii
3
+ import json
4
+ from typing import List, Dict, Any, Optional
5
+ from .client import Session
6
+ from .crypto import (
7
+ remove_message_padding,
8
+ decrypt_with_session_protocol,
9
+ remove_prefix_if_needed
10
+ )
11
+ from .protobuf.signalservice_pb2 import WebSocketMessage, Envelope, Content
12
+
13
+ def namespace_priority(namespace: int) -> int:
14
+ if namespace == 0:
15
+ return 10
16
+ return 1
17
+
18
+ def max_size_map(namespaces: List[int]) -> List[Dict[str, Any]]:
19
+ priorities = {}
20
+ for ns in namespaces:
21
+ p = namespace_priority(ns)
22
+ if p not in priorities:
23
+ priorities[p] = []
24
+ priorities[p].append(ns)
25
+
26
+ sorted_priorities = sorted(priorities.keys(), reverse=True)
27
+ if not sorted_priorities:
28
+ return []
29
+ lowest_priority = sorted_priorities[-1]
30
+
31
+ size_map = []
32
+ last_split = 1
33
+ for p in sorted_priorities:
34
+ padding = 0 if p == lowest_priority else 1
35
+ splits = padding + len(priorities[p])
36
+ last_split *= splits
37
+ for ns in priorities[p]:
38
+ size_map.append({"namespace": ns, "maxSize": -last_split})
39
+
40
+ return size_map
41
+
42
+ def get_snode_signature_params(keys, method: str, namespace: int) -> dict:
43
+ timestamp = int(time.time() * 1000)
44
+ if namespace == 0:
45
+ msg = f"{method}{timestamp}"
46
+ else:
47
+ msg = f"{method}{namespace}{timestamp}"
48
+
49
+ signature = keys.signing_key.sign(msg.encode('utf-8')).signature
50
+ signature_b64 = binascii.b2a_base64(signature, newline=False).decode('utf-8')
51
+ pubkey_ed25519 = binascii.hexlify(keys.ed25519.public_key).decode('utf-8')
52
+
53
+ return {
54
+ "timestamp": timestamp,
55
+ "signature": signature_b64,
56
+ "pubkey_ed25519": pubkey_ed25519
57
+ }
58
+
59
+ class Poller:
60
+ def __init__(self, session: Session, namespaces: Optional[List[int]] = None):
61
+ self.session = session
62
+ self.namespaces = namespaces if namespaces is not None else [0, 2, 3, 4, 5]
63
+
64
+ def poll(self) -> List[Dict[str, Any]]:
65
+ if not self.session.keys or not self.session.session_id:
66
+ raise ValueError("Session client not initialized.")
67
+
68
+ our_swarm = self.session.get_our_swarm()
69
+ snode = {
70
+ "public_ip": our_swarm["ip"],
71
+ "storage_port": int(our_swarm["port"])
72
+ }
73
+
74
+ size_mappings = max_size_map(self.namespaces)
75
+
76
+ # Prepare retrieve subrequests
77
+ subrequests = []
78
+ for ns in self.namespaces:
79
+ last_hash = self.session.last_hashes.get(ns, "")
80
+
81
+ # Signature for authenticate retrieve
82
+ sig = get_snode_signature_params(self.session.keys, "retrieve", ns)
83
+
84
+ # Find maxSize
85
+ max_size = -1
86
+ for mapping in size_mappings:
87
+ if mapping["namespace"] == ns:
88
+ max_size = mapping["maxSize"]
89
+ break
90
+
91
+ subrequests.append({
92
+ "method": "retrieve",
93
+ "params": {
94
+ "pubkey": self.session.session_id,
95
+ "lastHash": last_hash,
96
+ "namespace": ns,
97
+ "maxSize": max_size,
98
+ "timestamp": sig["timestamp"],
99
+ "signature": sig["signature"],
100
+ "pubkey_ed25519": sig["pubkey_ed25519"]
101
+ }
102
+ })
103
+
104
+ results = self.session.network.snode_batch_request(
105
+ snode=snode,
106
+ requests_list=subrequests
107
+ )
108
+
109
+ decrypted_messages = []
110
+
111
+ for idx, result in enumerate(results):
112
+ ns = self.namespaces[idx]
113
+ if result.get("code") != 200:
114
+ continue
115
+
116
+ body_val = result.get("body", "{}")
117
+ if isinstance(body_val, str):
118
+ try:
119
+ body_data = json.loads(body_val)
120
+ except Exception:
121
+ body_data = {}
122
+ else:
123
+ body_data = body_val
124
+
125
+ if isinstance(body_data, dict):
126
+ messages_list = body_data.get("messages", [])
127
+ else:
128
+ messages_list = []
129
+
130
+ if not messages_list:
131
+ continue
132
+
133
+ for m in messages_list:
134
+ msg_hash = m.get("hash")
135
+ data_b64 = m.get("data")
136
+ if not data_b64:
137
+ continue
138
+
139
+ try:
140
+ # Extract envelope
141
+ data_bytes = binascii.a2b_base64(data_b64)
142
+ ws_msg = WebSocketMessage.FromString(data_bytes)
143
+
144
+ if ws_msg.type != WebSocketMessage.Type.REQUEST or not ws_msg.request.body:
145
+ continue
146
+
147
+ envelope_bytes = ws_msg.request.body
148
+ envelope = Envelope.FromString(envelope_bytes)
149
+
150
+ if not envelope.content:
151
+ continue
152
+
153
+ # Decrypt Envelope
154
+ plaintext_padded, sender_id = decrypt_with_session_protocol(
155
+ self.session.keys,
156
+ envelope.content
157
+ )
158
+
159
+ # Unpad plaintext
160
+ plaintext = remove_message_padding(plaintext_padded)
161
+
162
+ # Parse Content protobuf
163
+ content = Content.FromString(plaintext)
164
+
165
+ # Map to friendly dict
166
+ mapped_msg = {
167
+ "hash": msg_hash,
168
+ "namespace": ns,
169
+ "timestamp": envelope.timestamp,
170
+ "from": sender_id,
171
+ "type": "unknown",
172
+ "body": None,
173
+ "attachments": [],
174
+ "syncTarget": None
175
+ }
176
+
177
+ if content.HasField("dataMessage"):
178
+ mapped_msg["type"] = "data"
179
+ mapped_msg["body"] = content.dataMessage.body
180
+ if content.dataMessage.syncTarget:
181
+ mapped_msg["syncTarget"] = content.dataMessage.syncTarget
182
+
183
+ # Parse attachments
184
+ for att in content.dataMessage.attachments:
185
+ mapped_msg["attachments"].append({
186
+ "id": att.id,
187
+ "url": att.url,
188
+ "key": att.key,
189
+ "digest": att.digest,
190
+ "name": att.fileName,
191
+ "contentType": att.contentType,
192
+ "size": att.size
193
+ })
194
+
195
+ elif content.HasField("typingMessage"):
196
+ mapped_msg["type"] = "typing"
197
+ mapped_msg["isTyping"] = (content.typingMessage.action == 0) # STARTED = 0
198
+
199
+ elif content.HasField("unsendMessage"):
200
+ mapped_msg["type"] = "unsend"
201
+ mapped_msg["targetTimestamp"] = content.unsendMessage.timestamp
202
+ mapped_msg["author"] = content.unsendMessage.author
203
+
204
+ elif content.HasField("receiptMessage"):
205
+ mapped_msg["type"] = "receipt"
206
+ mapped_msg["targetTimestamps"] = list(content.receiptMessage.timestamp)
207
+
208
+ elif content.HasField("messageRequestResponse"):
209
+ mapped_msg["type"] = "request_response"
210
+ mapped_msg["isApproved"] = content.messageRequestResponse.isApproved
211
+
212
+ decrypted_messages.append(mapped_msg)
213
+
214
+ except Exception as e:
215
+ # Decryption or parsing error for a single message shouldn't crash the loop
216
+ continue
217
+
218
+ # Update lastHash for this namespace to the hash of the last message
219
+ if messages_list:
220
+ self.session.last_hashes[ns] = messages_list[-1]["hash"]
221
+
222
+ return decrypted_messages
@@ -0,0 +1 @@
1
+ # Protobuf package
@@ -0,0 +1,112 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: signalservice.proto
5
+ # Protobuf Python Version: 7.35.0
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 7,
15
+ 35,
16
+ 0,
17
+ '',
18
+ 'signalservice.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+
26
+
27
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x13signalservice.proto\x12\rsignalservice\"\xa1\x01\n\x08\x45nvelope\x12*\n\x04type\x18\x01 \x02(\x0e\x32\x1c.signalservice.Envelope.Type\x12\x0e\n\x06source\x18\x02 \x01(\t\x12\x11\n\ttimestamp\x18\x05 \x02(\x04\x12\x0f\n\x07\x63ontent\x18\x08 \x01(\x0c\"5\n\x04Type\x12\x13\n\x0fSESSION_MESSAGE\x10\x06\x12\x18\n\x14\x43LOSED_GROUP_MESSAGE\x10\x07\"{\n\rTypingMessage\x12\x11\n\ttimestamp\x18\x01 \x02(\x04\x12\x33\n\x06\x61\x63tion\x18\x02 \x02(\x0e\x32#.signalservice.TypingMessage.Action\"\"\n\x06\x41\x63tion\x12\x0b\n\x07STARTED\x10\x00\x12\x0b\n\x07STOPPED\x10\x01\"+\n\x06Unsend\x12\x11\n\ttimestamp\x18\x01 \x02(\x04\x12\x0e\n\x06\x61uthor\x18\x02 \x02(\t\"y\n\x16MessageRequestResponse\x12\x12\n\nisApproved\x18\x01 \x02(\x08\x12\x12\n\nprofileKey\x18\x02 \x01(\x0c\x12\x37\n\x07profile\x18\x03 \x01(\x0b\x32&.signalservice.DataMessage.LokiProfile\"\xbb\x01\n\x13SharedConfigMessage\x12\x35\n\x04kind\x18\x01 \x02(\x0e\x32\'.signalservice.SharedConfigMessage.Kind\x12\r\n\x05seqno\x18\x02 \x02(\x03\x12\x0c\n\x04\x64\x61ta\x18\x03 \x02(\x0c\"P\n\x04Kind\x12\x10\n\x0cUSER_PROFILE\x10\x01\x12\x0c\n\x08\x43ONTACTS\x10\x02\x12\x17\n\x13\x43ONVO_INFO_VOLATILE\x10\x03\x12\x0f\n\x0bUSER_GROUPS\x10\x04\"\xc4\x05\n\x07\x43ontent\x12/\n\x0b\x64\x61taMessage\x18\x01 \x01(\x0b\x32\x1a.signalservice.DataMessage\x12/\n\x0b\x63\x61llMessage\x18\x03 \x01(\x0b\x32\x1a.signalservice.CallMessage\x12\x35\n\x0ereceiptMessage\x18\x05 \x01(\x0b\x32\x1d.signalservice.ReceiptMessage\x12\x33\n\rtypingMessage\x18\x06 \x01(\x0b\x32\x1c.signalservice.TypingMessage\x12\x41\n\x14\x63onfigurationMessage\x18\x07 \x01(\x0b\x32#.signalservice.ConfigurationMessage\x12M\n\x1a\x64\x61taExtractionNotification\x18\x08 \x01(\x0b\x32).signalservice.DataExtractionNotification\x12,\n\runsendMessage\x18\t \x01(\x0b\x32\x15.signalservice.Unsend\x12\x45\n\x16messageRequestResponse\x18\n \x01(\x0b\x32%.signalservice.MessageRequestResponse\x12?\n\x13sharedConfigMessage\x18\x0b \x01(\x0b\x32\".signalservice.SharedConfigMessage\x12=\n\x0e\x65xpirationType\x18\x0c \x01(\x0e\x32%.signalservice.Content.ExpirationType\x12\x17\n\x0f\x65xpirationTimer\x18\r \x01(\r\"K\n\x0e\x45xpirationType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x15\n\x11\x44\x45LETE_AFTER_READ\x10\x01\x12\x15\n\x11\x44\x45LETE_AFTER_SEND\x10\x02\"0\n\x07KeyPair\x12\x11\n\tpublicKey\x18\x01 \x02(\x0c\x12\x12\n\nprivateKey\x18\x02 \x02(\x0c\"\x96\x01\n\x1a\x44\x61taExtractionNotification\x12<\n\x04type\x18\x01 \x02(\x0e\x32..signalservice.DataExtractionNotification.Type\x12\x11\n\ttimestamp\x18\x02 \x01(\x04\"\'\n\x04Type\x12\x0e\n\nSCREENSHOT\x10\x01\x12\x0f\n\x0bMEDIA_SAVED\x10\x02\"\x8f\x0e\n\x0b\x44\x61taMessage\x12\x0c\n\x04\x62ody\x18\x01 \x01(\t\x12\x35\n\x0b\x61ttachments\x18\x02 \x03(\x0b\x32 .signalservice.AttachmentPointer\x12*\n\x05group\x18\x03 \x01(\x0b\x32\x1b.signalservice.GroupContext\x12\r\n\x05\x66lags\x18\x04 \x01(\r\x12\x13\n\x0b\x65xpireTimer\x18\x05 \x01(\r\x12\x12\n\nprofileKey\x18\x06 \x01(\x0c\x12\x11\n\ttimestamp\x18\x07 \x01(\x04\x12/\n\x05quote\x18\x08 \x01(\x0b\x32 .signalservice.DataMessage.Quote\x12\x33\n\x07preview\x18\n \x03(\x0b\x32\".signalservice.DataMessage.Preview\x12\x35\n\x08reaction\x18\x0b \x01(\x0b\x32#.signalservice.DataMessage.Reaction\x12\x37\n\x07profile\x18\x65 \x01(\x0b\x32&.signalservice.DataMessage.LokiProfile\x12K\n\x13openGroupInvitation\x18\x66 \x01(\x0b\x32..signalservice.DataMessage.OpenGroupInvitation\x12W\n\x19\x63losedGroupControlMessage\x18h \x01(\x0b\x32\x34.signalservice.DataMessage.ClosedGroupControlMessage\x12\x12\n\nsyncTarget\x18i \x01(\t\x12&\n\x1e\x62locksCommunityMessageRequests\x18j \x01(\x08\x1a\x92\x01\n\x08Reaction\x12\n\n\x02id\x18\x01 \x02(\x04\x12\x0e\n\x06\x61uthor\x18\x02 \x02(\t\x12\r\n\x05\x65moji\x18\x03 \x01(\t\x12:\n\x06\x61\x63tion\x18\x04 \x02(\x0e\x32*.signalservice.DataMessage.Reaction.Action\"\x1f\n\x06\x41\x63tion\x12\t\n\x05REACT\x10\x00\x12\n\n\x06REMOVE\x10\x01\x1a\xe9\x01\n\x05Quote\x12\n\n\x02id\x18\x01 \x02(\x04\x12\x0e\n\x06\x61uthor\x18\x02 \x02(\t\x12\x0c\n\x04text\x18\x03 \x01(\t\x12\x46\n\x0b\x61ttachments\x18\x04 \x03(\x0b\x32\x31.signalservice.DataMessage.Quote.QuotedAttachment\x1an\n\x10QuotedAttachment\x12\x13\n\x0b\x63ontentType\x18\x01 \x01(\t\x12\x10\n\x08\x66ileName\x18\x02 \x01(\t\x12\x33\n\tthumbnail\x18\x03 \x01(\x0b\x32 .signalservice.AttachmentPointer\x1aV\n\x07Preview\x12\x0b\n\x03url\x18\x01 \x02(\t\x12\r\n\x05title\x18\x02 \x01(\t\x12/\n\x05image\x18\x03 \x01(\x0b\x32 .signalservice.AttachmentPointer\x1a:\n\x0bLokiProfile\x12\x13\n\x0b\x64isplayName\x18\x01 \x01(\t\x12\x16\n\x0eprofilePicture\x18\x02 \x01(\t\x1a\x30\n\x13OpenGroupInvitation\x12\x0b\n\x03url\x18\x01 \x02(\t\x12\x0c\n\x04name\x18\x03 \x02(\t\x1a\x9e\x04\n\x19\x43losedGroupControlMessage\x12G\n\x04type\x18\x01 \x02(\x0e\x32\x39.signalservice.DataMessage.ClosedGroupControlMessage.Type\x12\x11\n\tpublicKey\x18\x02 \x01(\x0c\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x31\n\x11\x65ncryptionKeyPair\x18\x04 \x01(\x0b\x32\x16.signalservice.KeyPair\x12\x0f\n\x07members\x18\x05 \x03(\x0c\x12\x0e\n\x06\x61\x64mins\x18\x06 \x03(\x0c\x12U\n\x08wrappers\x18\x07 \x03(\x0b\x32\x43.signalservice.DataMessage.ClosedGroupControlMessage.KeyPairWrapper\x12\x17\n\x0f\x65xpirationTimer\x18\x08 \x01(\r\x1a=\n\x0eKeyPairWrapper\x12\x11\n\tpublicKey\x18\x01 \x02(\x0c\x12\x18\n\x10\x65ncryptedKeyPair\x18\x02 \x02(\x0c\"\x93\x01\n\x04Type\x12\x07\n\x03NEW\x10\x01\x12\x17\n\x13\x45NCRYPTION_KEY_PAIR\x10\x03\x12\x0f\n\x0bNAME_CHANGE\x10\x04\x12\x11\n\rMEMBERS_ADDED\x10\x05\x12\x13\n\x0fMEMBERS_REMOVED\x10\x06\x12\x0f\n\x0bMEMBER_LEFT\x10\x07\x12\x1f\n\x1b\x45NCRYPTION_KEY_PAIR_REQUEST\x10\x08\"$\n\x05\x46lags\x12\x1b\n\x17\x45XPIRATION_TIMER_UPDATE\x10\x02\"\xea\x01\n\x0b\x43\x61llMessage\x12-\n\x04type\x18\x01 \x02(\x0e\x32\x1f.signalservice.CallMessage.Type\x12\x0c\n\x04sdps\x18\x02 \x03(\t\x12\x17\n\x0fsdpMLineIndexes\x18\x03 \x03(\r\x12\x0f\n\x07sdpMids\x18\x04 \x03(\t\x12\x0c\n\x04uuid\x18\x05 \x02(\t\"f\n\x04Type\x12\r\n\tPRE_OFFER\x10\x06\x12\t\n\x05OFFER\x10\x01\x12\n\n\x06\x41NSWER\x10\x02\x12\x16\n\x12PROVISIONAL_ANSWER\x10\x03\x12\x12\n\x0eICE_CANDIDATES\x10\x04\x12\x0c\n\x08\x45ND_CALL\x10\x05\"\x8c\x04\n\x14\x43onfigurationMessage\x12\x45\n\x0c\x63losedGroups\x18\x01 \x03(\x0b\x32/.signalservice.ConfigurationMessage.ClosedGroup\x12\x12\n\nopenGroups\x18\x02 \x03(\t\x12\x13\n\x0b\x64isplayName\x18\x03 \x01(\t\x12\x16\n\x0eprofilePicture\x18\x04 \x01(\t\x12\x12\n\nprofileKey\x18\x05 \x01(\x0c\x12=\n\x08\x63ontacts\x18\x06 \x03(\x0b\x32+.signalservice.ConfigurationMessage.Contact\x1a\x82\x01\n\x0b\x43losedGroup\x12\x11\n\tpublicKey\x18\x01 \x01(\x0c\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x31\n\x11\x65ncryptionKeyPair\x18\x03 \x01(\x0b\x32\x16.signalservice.KeyPair\x12\x0f\n\x07members\x18\x04 \x03(\x0c\x12\x0e\n\x06\x61\x64mins\x18\x05 \x03(\x0c\x1a\x93\x01\n\x07\x43ontact\x12\x11\n\tpublicKey\x18\x01 \x02(\x0c\x12\x0c\n\x04name\x18\x02 \x02(\t\x12\x16\n\x0eprofilePicture\x18\x03 \x01(\t\x12\x12\n\nprofileKey\x18\x04 \x01(\x0c\x12\x12\n\nisApproved\x18\x05 \x01(\x08\x12\x11\n\tisBlocked\x18\x06 \x01(\x08\x12\x14\n\x0c\x64idApproveMe\x18\x07 \x01(\x08\"g\n\x0eReceiptMessage\x12\x30\n\x04type\x18\x01 \x02(\x0e\x32\".signalservice.ReceiptMessage.Type\x12\x11\n\ttimestamp\x18\x02 \x03(\x04\"\x10\n\x04Type\x12\x08\n\x04READ\x10\x01\"\xd9\x01\n\x11\x41ttachmentPointer\x12\n\n\x02id\x18\x01 \x02(\x06\x12\x13\n\x0b\x63ontentType\x18\x02 \x01(\t\x12\x0b\n\x03key\x18\x03 \x01(\x0c\x12\x0c\n\x04size\x18\x04 \x01(\r\x12\x0e\n\x06\x64igest\x18\x06 \x01(\x0c\x12\x10\n\x08\x66ileName\x18\x07 \x01(\t\x12\r\n\x05\x66lags\x18\x08 \x01(\r\x12\r\n\x05width\x18\t \x01(\r\x12\x0e\n\x06height\x18\n \x01(\r\x12\x0f\n\x07\x63\x61ption\x18\x0b \x01(\t\x12\x0b\n\x03url\x18\x65 \x01(\t\"\x1a\n\x05\x46lags\x12\x11\n\rVOICE_MESSAGE\x10\x01\"\xf5\x01\n\x0cGroupContext\x12\n\n\x02id\x18\x01 \x01(\x0c\x12.\n\x04type\x18\x02 \x01(\x0e\x32 .signalservice.GroupContext.Type\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x0f\n\x07members\x18\x04 \x03(\t\x12\x30\n\x06\x61vatar\x18\x05 \x01(\x0b\x32 .signalservice.AttachmentPointer\x12\x0e\n\x06\x61\x64mins\x18\x06 \x03(\t\"H\n\x04Type\x12\x0b\n\x07UNKNOWN\x10\x00\x12\n\n\x06UPDATE\x10\x01\x12\x0b\n\x07\x44\x45LIVER\x10\x02\x12\x08\n\x04QUIT\x10\x03\x12\x10\n\x0cREQUEST_INFO\x10\x04\"`\n\x17WebSocketRequestMessage\x12\x0c\n\x04verb\x18\x01 \x01(\t\x12\x0c\n\x04path\x18\x02 \x01(\t\x12\x0c\n\x04\x62ody\x18\x03 \x01(\x0c\x12\x0f\n\x07headers\x18\x05 \x03(\t\x12\n\n\x02id\x18\x04 \x01(\x04\"\xaf\x01\n\x10WebSocketMessage\x12\x32\n\x04type\x18\x01 \x01(\x0e\x32$.signalservice.WebSocketMessage.Type\x12\x37\n\x07request\x18\x02 \x01(\x0b\x32&.signalservice.WebSocketRequestMessage\".\n\x04Type\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x0b\n\x07REQUEST\x10\x01\x12\x0c\n\x08RESPONSE\x10\x02')
28
+
29
+ _globals = globals()
30
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
31
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'signalservice_pb2', _globals)
32
+ if not _descriptor._USE_C_DESCRIPTORS:
33
+ DESCRIPTOR._loaded_options = None
34
+ _globals['_ENVELOPE']._serialized_start=39
35
+ _globals['_ENVELOPE']._serialized_end=200
36
+ _globals['_ENVELOPE_TYPE']._serialized_start=147
37
+ _globals['_ENVELOPE_TYPE']._serialized_end=200
38
+ _globals['_TYPINGMESSAGE']._serialized_start=202
39
+ _globals['_TYPINGMESSAGE']._serialized_end=325
40
+ _globals['_TYPINGMESSAGE_ACTION']._serialized_start=291
41
+ _globals['_TYPINGMESSAGE_ACTION']._serialized_end=325
42
+ _globals['_UNSEND']._serialized_start=327
43
+ _globals['_UNSEND']._serialized_end=370
44
+ _globals['_MESSAGEREQUESTRESPONSE']._serialized_start=372
45
+ _globals['_MESSAGEREQUESTRESPONSE']._serialized_end=493
46
+ _globals['_SHAREDCONFIGMESSAGE']._serialized_start=496
47
+ _globals['_SHAREDCONFIGMESSAGE']._serialized_end=683
48
+ _globals['_SHAREDCONFIGMESSAGE_KIND']._serialized_start=603
49
+ _globals['_SHAREDCONFIGMESSAGE_KIND']._serialized_end=683
50
+ _globals['_CONTENT']._serialized_start=686
51
+ _globals['_CONTENT']._serialized_end=1394
52
+ _globals['_CONTENT_EXPIRATIONTYPE']._serialized_start=1319
53
+ _globals['_CONTENT_EXPIRATIONTYPE']._serialized_end=1394
54
+ _globals['_KEYPAIR']._serialized_start=1396
55
+ _globals['_KEYPAIR']._serialized_end=1444
56
+ _globals['_DATAEXTRACTIONNOTIFICATION']._serialized_start=1447
57
+ _globals['_DATAEXTRACTIONNOTIFICATION']._serialized_end=1597
58
+ _globals['_DATAEXTRACTIONNOTIFICATION_TYPE']._serialized_start=1558
59
+ _globals['_DATAEXTRACTIONNOTIFICATION_TYPE']._serialized_end=1597
60
+ _globals['_DATAMESSAGE']._serialized_start=1600
61
+ _globals['_DATAMESSAGE']._serialized_end=3407
62
+ _globals['_DATAMESSAGE_REACTION']._serialized_start=2244
63
+ _globals['_DATAMESSAGE_REACTION']._serialized_end=2390
64
+ _globals['_DATAMESSAGE_REACTION_ACTION']._serialized_start=2359
65
+ _globals['_DATAMESSAGE_REACTION_ACTION']._serialized_end=2390
66
+ _globals['_DATAMESSAGE_QUOTE']._serialized_start=2393
67
+ _globals['_DATAMESSAGE_QUOTE']._serialized_end=2626
68
+ _globals['_DATAMESSAGE_QUOTE_QUOTEDATTACHMENT']._serialized_start=2516
69
+ _globals['_DATAMESSAGE_QUOTE_QUOTEDATTACHMENT']._serialized_end=2626
70
+ _globals['_DATAMESSAGE_PREVIEW']._serialized_start=2628
71
+ _globals['_DATAMESSAGE_PREVIEW']._serialized_end=2714
72
+ _globals['_DATAMESSAGE_LOKIPROFILE']._serialized_start=2716
73
+ _globals['_DATAMESSAGE_LOKIPROFILE']._serialized_end=2774
74
+ _globals['_DATAMESSAGE_OPENGROUPINVITATION']._serialized_start=2776
75
+ _globals['_DATAMESSAGE_OPENGROUPINVITATION']._serialized_end=2824
76
+ _globals['_DATAMESSAGE_CLOSEDGROUPCONTROLMESSAGE']._serialized_start=2827
77
+ _globals['_DATAMESSAGE_CLOSEDGROUPCONTROLMESSAGE']._serialized_end=3369
78
+ _globals['_DATAMESSAGE_CLOSEDGROUPCONTROLMESSAGE_KEYPAIRWRAPPER']._serialized_start=3158
79
+ _globals['_DATAMESSAGE_CLOSEDGROUPCONTROLMESSAGE_KEYPAIRWRAPPER']._serialized_end=3219
80
+ _globals['_DATAMESSAGE_CLOSEDGROUPCONTROLMESSAGE_TYPE']._serialized_start=3222
81
+ _globals['_DATAMESSAGE_CLOSEDGROUPCONTROLMESSAGE_TYPE']._serialized_end=3369
82
+ _globals['_DATAMESSAGE_FLAGS']._serialized_start=3371
83
+ _globals['_DATAMESSAGE_FLAGS']._serialized_end=3407
84
+ _globals['_CALLMESSAGE']._serialized_start=3410
85
+ _globals['_CALLMESSAGE']._serialized_end=3644
86
+ _globals['_CALLMESSAGE_TYPE']._serialized_start=3542
87
+ _globals['_CALLMESSAGE_TYPE']._serialized_end=3644
88
+ _globals['_CONFIGURATIONMESSAGE']._serialized_start=3647
89
+ _globals['_CONFIGURATIONMESSAGE']._serialized_end=4171
90
+ _globals['_CONFIGURATIONMESSAGE_CLOSEDGROUP']._serialized_start=3891
91
+ _globals['_CONFIGURATIONMESSAGE_CLOSEDGROUP']._serialized_end=4021
92
+ _globals['_CONFIGURATIONMESSAGE_CONTACT']._serialized_start=4024
93
+ _globals['_CONFIGURATIONMESSAGE_CONTACT']._serialized_end=4171
94
+ _globals['_RECEIPTMESSAGE']._serialized_start=4173
95
+ _globals['_RECEIPTMESSAGE']._serialized_end=4276
96
+ _globals['_RECEIPTMESSAGE_TYPE']._serialized_start=4260
97
+ _globals['_RECEIPTMESSAGE_TYPE']._serialized_end=4276
98
+ _globals['_ATTACHMENTPOINTER']._serialized_start=4279
99
+ _globals['_ATTACHMENTPOINTER']._serialized_end=4496
100
+ _globals['_ATTACHMENTPOINTER_FLAGS']._serialized_start=4470
101
+ _globals['_ATTACHMENTPOINTER_FLAGS']._serialized_end=4496
102
+ _globals['_GROUPCONTEXT']._serialized_start=4499
103
+ _globals['_GROUPCONTEXT']._serialized_end=4744
104
+ _globals['_GROUPCONTEXT_TYPE']._serialized_start=4672
105
+ _globals['_GROUPCONTEXT_TYPE']._serialized_end=4744
106
+ _globals['_WEBSOCKETREQUESTMESSAGE']._serialized_start=4746
107
+ _globals['_WEBSOCKETREQUESTMESSAGE']._serialized_end=4842
108
+ _globals['_WEBSOCKETMESSAGE']._serialized_start=4845
109
+ _globals['_WEBSOCKETMESSAGE']._serialized_end=5020
110
+ _globals['_WEBSOCKETMESSAGE_TYPE']._serialized_start=4974
111
+ _globals['_WEBSOCKETMESSAGE_TYPE']._serialized_end=5020
112
+ # @@protoc_insertion_point(module_scope)
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.4
2
+ Name: session-python
3
+ Version: 1.0.0
4
+ Summary: A pure Python implementation of the Session Messenger protocol client
5
+ Author-email: Towux <towux@users.noreply.github.com>
6
+ Project-URL: Homepage, https://github.com/towux/session-python
7
+ Project-URL: Bug Tracker, https://github.com/towux/session-python/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: Communications :: Chat
12
+ Classifier: Intended Audience :: Developers
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: pynacl>=1.5.0
17
+ Requires-Dist: cryptography>=41.0.0
18
+ Requires-Dist: protobuf>=4.21.0
19
+ Requires-Dist: requests>=2.31.0
20
+ Requires-Dist: pysocks>=1.7.1
21
+ Dynamic: license-file
22
+
23
+ # session-python
24
+
25
+ [![PyPI version](https://img.shields.io/pypi/v/session-python.svg)](https://pypi.org/project/session-python/)
26
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
27
+
28
+ A pure Python implementation of the **Session Messenger** programmatic client protocol.
29
+
30
+ This library is a 1-to-1 port of the official `@session.js` (Bun) client modules to Python, allowing you to build Session bots, send encrypted messages, upload/download attachments, handle read receipts, typing indicators, message reactions, and unsends natively in Python, **without** wrapping any Node/Bun subprocesses.
31
+
32
+ ---
33
+
34
+ ## 🚀 Features
35
+
36
+ * **Zero JS Subprocesses**: Natively implemented in Python using PyNaCl, Cryptography, and Protobuf.
37
+ * **Oxen Mnemonics**: Ported 13-word Electrum/Monero style mnemonic decoder & encoder (Oxen standard) with CRC32 checksums.
38
+ * **Session Protocol Encryption**: SealedBox encryption, sender identity signatures, envelope wrapping, and 160-byte block size padding.
39
+ * **Proxy Support**: SOCKS5 and HTTP proxy support out of the box (uses `socks5h://` to perform remote DNS resolution for high privacy).
40
+ * **Redundant Node Routing**: Swarm lookup and node rotation (automatically retries other nodes in the swarm if a connection fails).
41
+ * **In-Memory Swarm Cache**: Caches resolved swarms to reduce network calls and decrease message sending latency by up to 4x.
42
+ * **Attachments Support**: Encrypts (AES-CBC + HMAC-SHA256) and uploads/downloads attachments to the Session file server.
43
+ * **Typing Indicators**: Show or hide typing indicators (`show_typing_indicator`, `hide_typing_indicator`).
44
+ * **Message Reactions**: React to messages with emojis (`add_reaction`, `remove_reaction`).
45
+ * **Read Receipts**: Mark messages as read (`mark_messages_as_read`).
46
+ * **Message Deletion (Unsend)**: Delete messages locally and propagate deletion commands (`delete_message`, `delete_messages`).
47
+ * **SOGS Support**: Sign and send requests to SOGS (Open Groups) (`send_sogs_request`, `sign_sogs_request`).
48
+ * **Pythonic Interface**: Exposes context managers (`with Session() as s:`) and static generators (`Session.generate_mnemonic()`).
49
+
50
+ ---
51
+
52
+ ## 📦 Installation
53
+
54
+ To install `session-python` along with its dependencies:
55
+
56
+ ```bash
57
+ pip install pynacl cryptography protobuf requests pysocks
58
+ ```
59
+
60
+ ---
61
+
62
+ ## 🛠️ Quick Start
63
+
64
+ ### 1. Basic Send Message
65
+
66
+ ```python
67
+ from session_python import Session
68
+
69
+ # Initialize with SOCKS5 proxy
70
+ PROXY = "socks5h://user:pass@host:port"
71
+ RECIPIENT_ID = "059ce57868de2b93dc56e3bce3780db7a7aadc91d8e236f4a8f972f92e609ab609"
72
+
73
+ with Session(proxy=PROXY) as session:
74
+ # Set your account mnemonic or generate a new one
75
+ mnemonic = Session.generate_mnemonic()
76
+ print(f"Generated new mnemonic: {mnemonic}")
77
+
78
+ session.set_mnemonic(mnemonic, display_name="Python Bot")
79
+ print(f"Your Session ID: {session.get_session_id()}")
80
+
81
+ # Send a text message
82
+ result = session.send_message(to=RECIPIENT_ID, text="Hello from Python!")
83
+ print(f"Message Hash: {result['messageHash']}")
84
+ ```
85
+
86
+ ### 2. Polling for Messages
87
+
88
+ ```python
89
+ from session_python import Session, Poller
90
+
91
+ with Session(proxy=PROXY) as session:
92
+ session.set_mnemonic("your 13 word mnemonic here...")
93
+
94
+ poller = Poller(session)
95
+ print("Listening for messages...")
96
+
97
+ while True:
98
+ messages = poller.poll()
99
+ for msg in messages:
100
+ if msg["type"] == "data":
101
+ print(f"Received from {msg['from']}: {msg['body']}")
102
+ time.sleep(5)
103
+ ```
104
+
105
+ ### 3. File Attachments
106
+
107
+ ```python
108
+ with Session(proxy=PROXY) as session:
109
+ session.set_mnemonic(mnemonic)
110
+
111
+ # 1. Send file attachment
112
+ with open("photo.jpg", "rb") as f:
113
+ file_bytes = f.read()
114
+
115
+ attachments = [{
116
+ "data": file_bytes,
117
+ "name": "photo.jpg",
118
+ "content_type": "image/jpeg"
119
+ }]
120
+ session.send_message(to=RECIPIENT_ID, text="Here is a file!", attachments=attachments)
121
+
122
+ # 2. Download and decrypt attachment from a polled message pointer
123
+ # file_ptr is extracted from incoming messages: msg["attachments"][0]
124
+ decrypted_file = session.get_file(file_ptr)
125
+ with open("downloaded_photo.jpg", "wb") as f:
126
+ f.write(decrypted_file)
127
+ ```
128
+
129
+ ### 4. Advanced Chat Operations
130
+
131
+ ```python
132
+ with Session(proxy=PROXY) as session:
133
+ session.set_mnemonic(mnemonic)
134
+
135
+ # Typing Indicators
136
+ session.show_typing_indicator(RECIPIENT_ID)
137
+ time.sleep(2)
138
+ session.hide_typing_indicator(RECIPIENT_ID)
139
+
140
+ # Message Reactions
141
+ session.add_reaction(message_timestamp=1783586415070, message_author=RECIPIENT_ID, emoji="🔥")
142
+ session.remove_reaction(message_timestamp=1783586415070, message_author=RECIPIENT_ID, emoji="🔥")
143
+
144
+ # Read Receipts
145
+ session.mark_messages_as_read(conversation=RECIPIENT_ID, timestamps=[1783586415070])
146
+
147
+ # Delete / Unsend Messages
148
+ session.delete_message(conversation=RECIPIENT_ID, timestamp=1783586415070, hash_val="IXFgLeoj...")
149
+ ```
150
+
151
+ ---
152
+
153
+ ## ⚖️ License
154
+
155
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,13 @@
1
+ session_python/__init__.py,sha256=pUE3WQUcc1QEaI58Xa5qBRwSpGcOSwo8CbBbmB34OmM,89
2
+ session_python/client.py,sha256=HLqt_Zk2MZidNnIVhUcmC9yVWSJ_5YbCWvVYlbIk5sk,28729
3
+ session_python/crypto.py,sha256=eouNI6lfXIFd7AqL8GOakLMMTeVvrDdZvIJvEHygc90,10527
4
+ session_python/mnemonic.py,sha256=9j3r2KVawok1sZ3LuY8ThOfvpNTgLz0zTM8unXOhL3M,18952
5
+ session_python/network.py,sha256=50Usnv08R2TgqGq4VURivIzaFhVBOajAt8zaNsXhiL4,6716
6
+ session_python/polling.py,sha256=IaggPaEzMtxSD6gryaiimmW7OFFcDy1Wmqk0GByAPcU,8615
7
+ session_python/protobuf/__init__.py,sha256=4rb44gL-mJV1hlfw6s7bgND1OHr8YlN-jTM-SzgchVY,19
8
+ session_python/protobuf/signalservice_pb2.py,sha256=iBBjC0dBWlBS2gQe7mLkY_YlyjOaWlCaHl0rZyghR0c,14465
9
+ session_python-1.0.0.dist-info/licenses/LICENSE,sha256=1EF7fItXLWrIq-VFUyWGfkNILQebdb_LS5CiT6B-qu4,1062
10
+ session_python-1.0.0.dist-info/METADATA,sha256=JV1kJxZ6eIw_6O9hH3hqeQe0tbtLcEsclWjsuraQjvw,6125
11
+ session_python-1.0.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
12
+ session_python-1.0.0.dist-info/top_level.txt,sha256=ud9usATeSN6ArJTxpZ_d19Gid7FAGR4kHubtN2-By9g,15
13
+ session_python-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Towux
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ session_python