bstkchat 2.4.2__tar.gz → 2.5.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.
- {bstkchat-2.4.2 → bstkchat-2.5.0}/PKG-INFO +2 -1
- {bstkchat-2.4.2 → bstkchat-2.5.0}/README.md +1 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/bstkchat/chain.py +7 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/bstkchat/cli.py +239 -19
- {bstkchat-2.4.2 → bstkchat-2.5.0}/bstkchat/config.py +17 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/bstkchat/web.py +39 -3
- bstkchat-2.5.0/bstkchat/web_ui.html +884 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/bstkchat.egg-info/PKG-INFO +2 -1
- {bstkchat-2.4.2 → bstkchat-2.5.0}/pyproject.toml +1 -1
- {bstkchat-2.4.2 → bstkchat-2.5.0}/setup.py +1 -1
- {bstkchat-2.4.2 → bstkchat-2.5.0}/tests/test_chain.py +15 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/tests/test_web.py +39 -0
- bstkchat-2.4.2/bstkchat/web_ui.html +0 -662
- {bstkchat-2.4.2 → bstkchat-2.5.0}/bstkchat/__init__.py +0 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/bstkchat/crypto.py +0 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/bstkchat.egg-info/SOURCES.txt +0 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/bstkchat.egg-info/dependency_links.txt +0 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/bstkchat.egg-info/entry_points.txt +0 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/bstkchat.egg-info/requires.txt +0 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/bstkchat.egg-info/top_level.txt +0 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/setup.cfg +0 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/tests/test_cli.py +0 -0
- {bstkchat-2.4.2 → bstkchat-2.5.0}/tests/test_crypto.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: bstkchat
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.5.0
|
|
4
4
|
Summary: A real-time Terminal-based Chatting Application using unique room IDs.
|
|
5
5
|
Author: BSTK Developers
|
|
6
6
|
Project-URL: Homepage, https://github.com/BTKcreations/BSTKCHAT
|
|
@@ -25,6 +25,7 @@ Dynamic: requires-python
|
|
|
25
25
|
|
|
26
26
|
## Features
|
|
27
27
|
|
|
28
|
+
- **Mobile & Browser Web App (PWA on GitHub Pages):** Open **https://btkcreations.github.io/BSTKCHAT/** on any phone or browser and tap **Install to Home Screen**—connects via MQTT over Secure WebSockets (`wss://broker.hivemq.com:8884/mqtt`) with compatible AES-256-GCM E2EE so mobile and terminal users chat in the same rooms.
|
|
28
29
|
- **Browser Web UI (`--web` / `/web`):** Launch a local, token-authenticated browser interface (`bstkchat --web`) with Dark/Light themes, live peer sidebar, file drag-and-drop, and SSE real-time updates—while keeping all E2EE and decentralized chain storage locally on your machine.
|
|
29
30
|
- **Zero Configuration + CLI Flags:** Connects automatically over MQTT (`broker.hivemq.com`) with TLS (`8883`) enabled by default, or use `--nick`, `--room`, `--password`, `--broker`, `--port`, `--no-tls`, `--web`, and `--web-port`.
|
|
30
31
|
- **End-to-End Encryption (E2EE):** Protect rooms with a password using `scrypt` key derivation, per-message random 96-bit nonces, **AES-256-GCM** authenticated encryption, and topic-bound AAD.
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
## Features
|
|
8
8
|
|
|
9
|
+
- **Mobile & Browser Web App (PWA on GitHub Pages):** Open **https://btkcreations.github.io/BSTKCHAT/** on any phone or browser and tap **Install to Home Screen**—connects via MQTT over Secure WebSockets (`wss://broker.hivemq.com:8884/mqtt`) with compatible AES-256-GCM E2EE so mobile and terminal users chat in the same rooms.
|
|
9
10
|
- **Browser Web UI (`--web` / `/web`):** Launch a local, token-authenticated browser interface (`bstkchat --web`) with Dark/Light themes, live peer sidebar, file drag-and-drop, and SSE real-time updates—while keeping all E2EE and decentralized chain storage locally on your machine.
|
|
10
11
|
- **Zero Configuration + CLI Flags:** Connects automatically over MQTT (`broker.hivemq.com`) with TLS (`8883`) enabled by default, or use `--nick`, `--room`, `--password`, `--broker`, `--port`, `--no-tls`, `--web`, and `--web-port`.
|
|
11
12
|
- **End-to-End Encryption (E2EE):** Protect rooms with a password using `scrypt` key derivation, per-message random 96-bit nonces, **AES-256-GCM** authenticated encryption, and topic-bound AAD.
|
|
@@ -143,6 +143,13 @@ class RoomChain:
|
|
|
143
143
|
with self._lock:
|
|
144
144
|
return list(self.blocks[-limit:])
|
|
145
145
|
|
|
146
|
+
def get_block(self, msg_id: str) -> Optional[dict]:
|
|
147
|
+
with self._lock:
|
|
148
|
+
for block in self.blocks:
|
|
149
|
+
if str(block.get("id")) == msg_id:
|
|
150
|
+
return dict(block)
|
|
151
|
+
return None
|
|
152
|
+
|
|
146
153
|
def verify_integrity(self) -> Tuple[bool, int]:
|
|
147
154
|
"""Verifies every block's SHA-256 hash in the local chain."""
|
|
148
155
|
with self._lock:
|
|
@@ -45,6 +45,7 @@ from bstkchat.config import (
|
|
|
45
45
|
MAX_FILE_BYTES,
|
|
46
46
|
VALID_THEMES,
|
|
47
47
|
load_config,
|
|
48
|
+
record_recent_room,
|
|
48
49
|
save_config,
|
|
49
50
|
save_received_file,
|
|
50
51
|
search_log,
|
|
@@ -57,7 +58,7 @@ from bstkchat.crypto import (
|
|
|
57
58
|
sanitize_room_id,
|
|
58
59
|
)
|
|
59
60
|
|
|
60
|
-
APP_VERSION = "2.
|
|
61
|
+
APP_VERSION = "2.5.0"
|
|
61
62
|
AUTO_AWAY_SECONDS = 300
|
|
62
63
|
TYPING_TTL_SECONDS = 5.0
|
|
63
64
|
TYPING_THROTTLE_SECONDS = 3.0
|
|
@@ -96,6 +97,9 @@ COMMANDS = [
|
|
|
96
97
|
("/room", "Switch room: /room <id> [password|--lock]"),
|
|
97
98
|
("/nick", "Change nickname: /nick <name>"),
|
|
98
99
|
("/msg", "Send private DM: /msg <user> <message>"),
|
|
100
|
+
("/reply", "Reply to last message: /reply <text>"),
|
|
101
|
+
("/react", "React to last message: /react <emoji>"),
|
|
102
|
+
("/delete", "Delete your last sent message"),
|
|
99
103
|
("/send", "Send encrypted file: /send <filepath>"),
|
|
100
104
|
("/accept", "Accept pending file: /accept [id]"),
|
|
101
105
|
("/status", "Set status: /status <text>"),
|
|
@@ -268,6 +272,13 @@ class ChatClient:
|
|
|
268
272
|
self.pending_files: Dict[str, Dict[str, object]] = {}
|
|
269
273
|
self.shared_files: Dict[str, Dict[str, object]] = {}
|
|
270
274
|
self._file_seq = 0
|
|
275
|
+
self.reactions: Dict[str, Dict[str, List[str]]] = {}
|
|
276
|
+
self.edited_msgs: Dict[str, str] = {}
|
|
277
|
+
self.deleted_msgs: set = set()
|
|
278
|
+
self.msg_acks: Dict[str, str] = {}
|
|
279
|
+
self.msg_owners: Dict[str, str] = {}
|
|
280
|
+
self._last_msg_info: Optional[Dict[str, str]] = None
|
|
281
|
+
self._last_own_msg_id: Optional[str] = None
|
|
271
282
|
|
|
272
283
|
self.running = True
|
|
273
284
|
self.connected = False
|
|
@@ -286,6 +297,8 @@ class ChatClient:
|
|
|
286
297
|
self.console = Console(force_terminal=True)
|
|
287
298
|
self.client: Optional[mqtt.Client] = None
|
|
288
299
|
self.chain = RoomChain(self.room_id, enabled=store_chain)
|
|
300
|
+
if store_chain:
|
|
301
|
+
record_recent_room(self.room_id, self.nickname, bool(self.password))
|
|
289
302
|
self._update_topics(self.room_id)
|
|
290
303
|
|
|
291
304
|
def _update_topics(self, room_id: str) -> None:
|
|
@@ -340,6 +353,9 @@ class ChatClient:
|
|
|
340
353
|
for fid, info in self.pending_files.items()
|
|
341
354
|
]
|
|
342
355
|
recent = list(self._recent_events)
|
|
356
|
+
recent_rooms = load_config().get("recent_rooms", [])
|
|
357
|
+
if not isinstance(recent_rooms, list):
|
|
358
|
+
recent_rooms = []
|
|
343
359
|
return {
|
|
344
360
|
"version": APP_VERSION,
|
|
345
361
|
"nickname": self.nickname,
|
|
@@ -358,6 +374,11 @@ class ChatClient:
|
|
|
358
374
|
},
|
|
359
375
|
"pending_files": pending,
|
|
360
376
|
"recent_events": recent,
|
|
377
|
+
"recent_rooms": recent_rooms,
|
|
378
|
+
"reactions": {k: dict(v) for k, v in self.reactions.items()},
|
|
379
|
+
"msg_acks": dict(self.msg_acks),
|
|
380
|
+
"edited_msgs": dict(self.edited_msgs),
|
|
381
|
+
"deleted_msgs": list(self.deleted_msgs),
|
|
361
382
|
}
|
|
362
383
|
|
|
363
384
|
def record_activity(self) -> None:
|
|
@@ -488,7 +509,9 @@ class ChatClient:
|
|
|
488
509
|
self.client.subscribe(presence_topic)
|
|
489
510
|
self.client.subscribe(sync_topic)
|
|
490
511
|
self.send_presence("join")
|
|
491
|
-
self.request_sync
|
|
512
|
+
t = threading.Timer(0.6, self.request_sync)
|
|
513
|
+
t.daemon = True
|
|
514
|
+
t.start()
|
|
492
515
|
self._emit_event("state_update", self.get_web_state())
|
|
493
516
|
|
|
494
517
|
def on_disconnect(self, client, userdata, rc, *args, **kwargs) -> None:
|
|
@@ -547,6 +570,9 @@ class ChatClient:
|
|
|
547
570
|
)
|
|
548
571
|
self.send_presence("heartbeat")
|
|
549
572
|
self._emit_event("system", {"text": f"{sender} joined the room.", "time": datetime.now().strftime("%H:%M:%S")}, record_history=True)
|
|
573
|
+
t = threading.Timer(0.4, self.request_sync)
|
|
574
|
+
t.daemon = True
|
|
575
|
+
t.start()
|
|
550
576
|
self._emit_event("state_update", self.get_web_state())
|
|
551
577
|
|
|
552
578
|
elif msg_type == "leave":
|
|
@@ -659,6 +685,32 @@ class ChatClient:
|
|
|
659
685
|
self._handle_incoming_file(sender, decrypted_text)
|
|
660
686
|
return
|
|
661
687
|
|
|
688
|
+
if msg_type == "reaction":
|
|
689
|
+
target_id = str(payload.get("target_id", ""))
|
|
690
|
+
if target_id:
|
|
691
|
+
self._apply_reaction(target_id, decrypted_text, sender)
|
|
692
|
+
return
|
|
693
|
+
|
|
694
|
+
if msg_type == "edit":
|
|
695
|
+
target_id = str(payload.get("target_id", ""))
|
|
696
|
+
if target_id and self.msg_owners.get(target_id, sender) == sender:
|
|
697
|
+
with self._lock:
|
|
698
|
+
self.edited_msgs[target_id] = decrypted_text
|
|
699
|
+
self.print_system(
|
|
700
|
+
f"✏️ [bold {color}]{safe_sender}[/] edited a message: {escape_markup(decrypted_text)}"
|
|
701
|
+
)
|
|
702
|
+
self._emit_event("message_edit", {"id": target_id, "text": decrypted_text, "sender": sender})
|
|
703
|
+
return
|
|
704
|
+
|
|
705
|
+
if msg_type == "delete":
|
|
706
|
+
target_id = str(payload.get("target_id", ""))
|
|
707
|
+
if target_id and self.msg_owners.get(target_id, sender) == sender:
|
|
708
|
+
with self._lock:
|
|
709
|
+
self.deleted_msgs.add(target_id)
|
|
710
|
+
self.print_system(f"🗑️ [bold {color}]{safe_sender}[/] deleted a message.")
|
|
711
|
+
self._emit_event("message_delete", {"id": target_id, "sender": sender})
|
|
712
|
+
return
|
|
713
|
+
|
|
662
714
|
if msg_type == "dm":
|
|
663
715
|
target = str(payload.get("target", ""))
|
|
664
716
|
if target == self.nickname:
|
|
@@ -667,6 +719,7 @@ class ChatClient:
|
|
|
667
719
|
self._emit_event(
|
|
668
720
|
"message",
|
|
669
721
|
{
|
|
722
|
+
"id": str(payload.get("id") or uuid.uuid4().hex),
|
|
670
723
|
"sender": sender,
|
|
671
724
|
"color": color,
|
|
672
725
|
"text": decrypted_text,
|
|
@@ -680,7 +733,22 @@ class ChatClient:
|
|
|
680
733
|
self._ring_bell()
|
|
681
734
|
return
|
|
682
735
|
|
|
736
|
+
msg_id = str(
|
|
737
|
+
payload.get("id")
|
|
738
|
+
or hashlib.sha256(f"{sender}:{timestamp}:{encrypted_text}".encode("utf-8")).hexdigest()
|
|
739
|
+
)
|
|
740
|
+
reply_info = self._decrypt_reply_meta(payload.get("reply_to"), key, topic.encode("utf-8"))
|
|
741
|
+
|
|
742
|
+
with self._lock:
|
|
743
|
+
self.msg_owners[msg_id] = sender
|
|
744
|
+
self._last_msg_info = {"id": msg_id, "sender": sender, "preview": decrypted_text[:80]}
|
|
745
|
+
|
|
683
746
|
mentioned = is_user_mentioned(decrypted_text, self.nickname)
|
|
747
|
+
if reply_info:
|
|
748
|
+
self.safe_print(
|
|
749
|
+
f"[dim italic] ↪ Replying to {escape_markup(reply_info['sender'])}: "
|
|
750
|
+
f"{escape_markup(reply_info['preview'])}[/]"
|
|
751
|
+
)
|
|
684
752
|
self._render_incoming_text(timestamp, sender, decrypted_text, is_mention=mentioned)
|
|
685
753
|
if mentioned:
|
|
686
754
|
self.write_to_log(f"Mentioned by {sender}: {decrypted_text}")
|
|
@@ -691,23 +759,22 @@ class ChatClient:
|
|
|
691
759
|
self._emit_event(
|
|
692
760
|
"message",
|
|
693
761
|
{
|
|
762
|
+
"id": msg_id,
|
|
694
763
|
"sender": sender,
|
|
695
764
|
"color": color,
|
|
696
765
|
"text": decrypted_text,
|
|
697
766
|
"time": timestamp,
|
|
698
767
|
"mention": mentioned,
|
|
768
|
+
"reply_to": reply_info,
|
|
699
769
|
"own": False,
|
|
700
770
|
},
|
|
701
771
|
record_history=True,
|
|
702
772
|
)
|
|
703
773
|
|
|
704
774
|
if msg_type == "message":
|
|
705
|
-
msg_id = str(
|
|
706
|
-
payload.get("id")
|
|
707
|
-
or hashlib.sha256(f"{sender}:{timestamp}:{encrypted_text}".encode("utf-8")).hexdigest()
|
|
708
|
-
)
|
|
709
775
|
ts = float(payload.get("ts") or time.time())
|
|
710
776
|
self.chain.append_message(msg_id, ts, timestamp, sender, "message", encrypted_text)
|
|
777
|
+
self.send_ack(msg_id, "delivered")
|
|
711
778
|
self._emit_event("state_update", self.get_web_state())
|
|
712
779
|
|
|
713
780
|
def request_sync(self, limit: int = 100) -> None:
|
|
@@ -729,6 +796,17 @@ class ChatClient:
|
|
|
729
796
|
|
|
730
797
|
def handle_sync(self, sender: str, msg_type: str, payload: dict, sync_topic: str) -> None:
|
|
731
798
|
"""Handles decentralized peer-to-peer room chain sync requests and responses."""
|
|
799
|
+
if msg_type == "ack":
|
|
800
|
+
target_id = str(payload.get("target_id", ""))
|
|
801
|
+
ack_status = str(payload.get("status", "delivered"))
|
|
802
|
+
if target_id and ack_status in ("delivered", "read"):
|
|
803
|
+
with self._lock:
|
|
804
|
+
cur = self.msg_acks.get(target_id, "sent")
|
|
805
|
+
if cur != "read":
|
|
806
|
+
self.msg_acks[target_id] = ack_status
|
|
807
|
+
self._emit_event("ack_update", {"id": target_id, "status": ack_status})
|
|
808
|
+
return
|
|
809
|
+
|
|
732
810
|
if not self.chain.enabled:
|
|
733
811
|
return
|
|
734
812
|
|
|
@@ -794,7 +872,7 @@ class ChatClient:
|
|
|
794
872
|
)
|
|
795
873
|
self._emit_event("state_update", self.get_web_state())
|
|
796
874
|
|
|
797
|
-
def replay_recent_chain(self, limit: int =
|
|
875
|
+
def replay_recent_chain(self, limit: int = 25) -> None:
|
|
798
876
|
"""Displays recent decrypted blocks from the local room chain on join."""
|
|
799
877
|
if not self.chain.enabled:
|
|
800
878
|
return
|
|
@@ -810,11 +888,25 @@ class ChatClient:
|
|
|
810
888
|
if ok:
|
|
811
889
|
if rendered == 0:
|
|
812
890
|
self.print_system(f"⛓️ Loaded {len(recent)} recent block(s) from local room chain:")
|
|
891
|
+
b_sender = str(block.get("sender", "Peer"))
|
|
892
|
+
b_time = str(block.get("time", "--:--:--"))
|
|
813
893
|
self._render_incoming_text(
|
|
814
|
-
escape_markup(
|
|
815
|
-
|
|
894
|
+
escape_markup(b_time),
|
|
895
|
+
b_sender,
|
|
816
896
|
text,
|
|
817
897
|
)
|
|
898
|
+
self._emit_event(
|
|
899
|
+
"message",
|
|
900
|
+
{
|
|
901
|
+
"sender": b_sender,
|
|
902
|
+
"color": get_user_color(b_sender),
|
|
903
|
+
"text": text,
|
|
904
|
+
"time": b_time,
|
|
905
|
+
"synced": True,
|
|
906
|
+
"own": b_sender == self.nickname,
|
|
907
|
+
},
|
|
908
|
+
record_history=True,
|
|
909
|
+
)
|
|
818
910
|
rendered += 1
|
|
819
911
|
|
|
820
912
|
def _handle_incoming_file(self, sender: str, decrypted_json: str) -> None:
|
|
@@ -989,12 +1081,80 @@ class ChatClient:
|
|
|
989
1081
|
except Exception:
|
|
990
1082
|
pass
|
|
991
1083
|
|
|
1084
|
+
def _decrypt_reply_meta(
|
|
1085
|
+
self, raw_reply: Any, key: bytes, aad: bytes
|
|
1086
|
+
) -> Optional[Dict[str, str]]:
|
|
1087
|
+
if not isinstance(raw_reply, dict):
|
|
1088
|
+
return None
|
|
1089
|
+
rid = str(raw_reply.get("id", ""))
|
|
1090
|
+
rsender = str(raw_reply.get("sender", ""))
|
|
1091
|
+
enc_prev = str(raw_reply.get("preview", ""))
|
|
1092
|
+
ok, prev = decrypt_message(enc_prev, key, aad=aad)
|
|
1093
|
+
if not ok:
|
|
1094
|
+
prev = str(raw_reply.get("plain_preview", ""))
|
|
1095
|
+
return {"id": rid, "sender": rsender, "preview": prev[:80]}
|
|
1096
|
+
|
|
1097
|
+
def _apply_reaction(self, target_id: str, emoji: str, sender: str) -> None:
|
|
1098
|
+
with self._lock:
|
|
1099
|
+
by_emoji = self.reactions.setdefault(target_id, {})
|
|
1100
|
+
users = by_emoji.setdefault(emoji, [])
|
|
1101
|
+
if sender in users:
|
|
1102
|
+
users.remove(sender)
|
|
1103
|
+
if not users:
|
|
1104
|
+
del by_emoji[emoji]
|
|
1105
|
+
else:
|
|
1106
|
+
users.append(sender)
|
|
1107
|
+
snapshot = {k: list(v) for k, v in by_emoji.items()}
|
|
1108
|
+
self._emit_event("reaction_update", {"id": target_id, "reactions": snapshot})
|
|
1109
|
+
|
|
1110
|
+
def send_ack(self, target_id: str, status: str = "delivered") -> None:
|
|
1111
|
+
if not self.client or not target_id:
|
|
1112
|
+
return
|
|
1113
|
+
with self._lock:
|
|
1114
|
+
topic = self.sync_topic
|
|
1115
|
+
try:
|
|
1116
|
+
self.client.publish(
|
|
1117
|
+
topic,
|
|
1118
|
+
json.dumps({"sender": self.nickname, "type": "ack", "target_id": target_id, "status": status}),
|
|
1119
|
+
qos=0,
|
|
1120
|
+
)
|
|
1121
|
+
except Exception:
|
|
1122
|
+
pass
|
|
1123
|
+
|
|
1124
|
+
def send_reaction(self, target_id: str, emoji: str) -> bool:
|
|
1125
|
+
if not target_id or not emoji.strip():
|
|
1126
|
+
return False
|
|
1127
|
+
if self._publish_encrypted("reaction", emoji.strip(), extra={"target_id": target_id}):
|
|
1128
|
+
self._apply_reaction(target_id, emoji.strip(), self.nickname)
|
|
1129
|
+
return True
|
|
1130
|
+
return False
|
|
1131
|
+
|
|
1132
|
+
def send_edit(self, target_id: str, new_text: str) -> bool:
|
|
1133
|
+
if not target_id or not new_text.strip():
|
|
1134
|
+
return False
|
|
1135
|
+
if self._publish_encrypted("edit", new_text.strip(), extra={"target_id": target_id}):
|
|
1136
|
+
with self._lock:
|
|
1137
|
+
self.edited_msgs[target_id] = new_text.strip()
|
|
1138
|
+
self._emit_event("message_edit", {"id": target_id, "text": new_text.strip(), "sender": self.nickname})
|
|
1139
|
+
return True
|
|
1140
|
+
return False
|
|
1141
|
+
|
|
1142
|
+
def send_delete(self, target_id: str) -> bool:
|
|
1143
|
+
if not target_id:
|
|
1144
|
+
return False
|
|
1145
|
+
if self._publish_encrypted("delete", "[deleted]", extra={"target_id": target_id}):
|
|
1146
|
+
with self._lock:
|
|
1147
|
+
self.deleted_msgs.add(target_id)
|
|
1148
|
+
self._emit_event("message_delete", {"id": target_id, "sender": self.nickname})
|
|
1149
|
+
return True
|
|
1150
|
+
return False
|
|
1151
|
+
|
|
992
1152
|
def _publish_encrypted(
|
|
993
1153
|
self, msg_type: str, text: str, extra: Optional[dict] = None
|
|
994
|
-
) ->
|
|
1154
|
+
) -> Optional[str]:
|
|
995
1155
|
"""Encrypts text with AES-256-GCM and publishes to the room's message topic."""
|
|
996
1156
|
if not self.client:
|
|
997
|
-
return
|
|
1157
|
+
return None
|
|
998
1158
|
|
|
999
1159
|
with self._lock:
|
|
1000
1160
|
key = self.secret_key
|
|
@@ -1004,7 +1164,7 @@ class ChatClient:
|
|
|
1004
1164
|
now_str = datetime.now().strftime("%H:%M:%S")
|
|
1005
1165
|
msg_id = uuid.uuid4().hex
|
|
1006
1166
|
encrypted_text = encrypt_payload(text, key, aad=topic.encode("utf-8"))
|
|
1007
|
-
payload = {
|
|
1167
|
+
payload: Dict[str, Any] = {
|
|
1008
1168
|
"id": msg_id,
|
|
1009
1169
|
"ts": now_ts,
|
|
1010
1170
|
"sender": self.nickname,
|
|
@@ -1013,22 +1173,42 @@ class ChatClient:
|
|
|
1013
1173
|
"time": now_str,
|
|
1014
1174
|
}
|
|
1015
1175
|
if extra:
|
|
1176
|
+
if isinstance(extra.get("reply_to"), dict):
|
|
1177
|
+
r = extra["reply_to"]
|
|
1178
|
+
extra = dict(extra)
|
|
1179
|
+
extra["reply_to"] = {
|
|
1180
|
+
"id": str(r.get("id", "")),
|
|
1181
|
+
"sender": str(r.get("sender", "")),
|
|
1182
|
+
"preview": encrypt_payload(str(r.get("preview", ""))[:80], key, aad=topic.encode("utf-8")),
|
|
1183
|
+
}
|
|
1016
1184
|
payload.update(extra)
|
|
1017
1185
|
|
|
1018
1186
|
try:
|
|
1019
1187
|
self.client.publish(topic, json.dumps(payload), qos=1)
|
|
1020
1188
|
if msg_type == "message":
|
|
1021
1189
|
self.chain.append_message(msg_id, now_ts, now_str, self.nickname, "message", encrypted_text)
|
|
1022
|
-
return
|
|
1190
|
+
return msg_id
|
|
1023
1191
|
except Exception as exc:
|
|
1024
1192
|
self.print_system(f"Error sending message: {escape_markup(str(exc))}")
|
|
1025
|
-
return
|
|
1193
|
+
return None
|
|
1026
1194
|
|
|
1027
|
-
def send_chat_message(self, text: str) ->
|
|
1195
|
+
def send_chat_message(self, text: str, reply_to: Optional[Dict[str, str]] = None) -> Optional[str]:
|
|
1028
1196
|
"""Broadcasts an encrypted text chat message."""
|
|
1029
1197
|
self.record_activity()
|
|
1030
|
-
|
|
1198
|
+
extra = {"reply_to": reply_to} if reply_to else None
|
|
1199
|
+
msg_id = self._publish_encrypted("message", text, extra=extra)
|
|
1200
|
+
if msg_id:
|
|
1031
1201
|
timestamp = datetime.now().strftime("%H:%M:%S")
|
|
1202
|
+
with self._lock:
|
|
1203
|
+
self.msg_acks[msg_id] = "sent"
|
|
1204
|
+
self.msg_owners[msg_id] = self.nickname
|
|
1205
|
+
self._last_own_msg_id = msg_id
|
|
1206
|
+
self._last_msg_info = {"id": msg_id, "sender": self.nickname, "preview": text[:80]}
|
|
1207
|
+
if reply_to:
|
|
1208
|
+
self.safe_print(
|
|
1209
|
+
f"[dim italic] ↪ Replying to {escape_markup(str(reply_to.get('sender', '')))}: "
|
|
1210
|
+
f"{escape_markup(str(reply_to.get('preview', '')))}[/]"
|
|
1211
|
+
)
|
|
1032
1212
|
if self.compact_mode:
|
|
1033
1213
|
self.safe_print(
|
|
1034
1214
|
f"[dim gray][{timestamp}][/] [bold green]<You>[/] {escape_markup(text)}"
|
|
@@ -1042,15 +1222,19 @@ class ChatClient:
|
|
|
1042
1222
|
self._emit_event(
|
|
1043
1223
|
"message",
|
|
1044
1224
|
{
|
|
1225
|
+
"id": msg_id,
|
|
1045
1226
|
"sender": self.nickname,
|
|
1046
1227
|
"color": get_user_color(self.nickname),
|
|
1047
1228
|
"text": text,
|
|
1048
1229
|
"time": timestamp,
|
|
1230
|
+
"reply_to": reply_to,
|
|
1231
|
+
"ack": "sent",
|
|
1049
1232
|
"own": True,
|
|
1050
1233
|
},
|
|
1051
1234
|
record_history=True,
|
|
1052
1235
|
)
|
|
1053
1236
|
self._emit_event("state_update", self.get_web_state())
|
|
1237
|
+
return msg_id
|
|
1054
1238
|
|
|
1055
1239
|
def send_private_message(self, target: str, text: str) -> None:
|
|
1056
1240
|
"""Sends an encrypted Direct Message to a specific user in the room."""
|
|
@@ -1113,6 +1297,16 @@ class ChatClient:
|
|
|
1113
1297
|
self.typing_peers.clear()
|
|
1114
1298
|
self.pending_files.clear()
|
|
1115
1299
|
self.shared_files.clear()
|
|
1300
|
+
self.reactions.clear()
|
|
1301
|
+
self.edited_msgs.clear()
|
|
1302
|
+
self.deleted_msgs.clear()
|
|
1303
|
+
self.msg_acks.clear()
|
|
1304
|
+
self.msg_owners.clear()
|
|
1305
|
+
self._last_msg_info = None
|
|
1306
|
+
self._last_own_msg_id = None
|
|
1307
|
+
self._recent_events.clear()
|
|
1308
|
+
if self.chain.enabled:
|
|
1309
|
+
record_recent_room(sanitized_room, self.nickname, bool(new_password))
|
|
1116
1310
|
new_msg_topic = self.msg_topic
|
|
1117
1311
|
new_presence_topic = self.presence_topic
|
|
1118
1312
|
new_sync_topic = self.sync_topic
|
|
@@ -1125,8 +1319,10 @@ class ChatClient:
|
|
|
1125
1319
|
|
|
1126
1320
|
self.clear_screen()
|
|
1127
1321
|
self.print_room_banner()
|
|
1128
|
-
self.replay_recent_chain(
|
|
1129
|
-
self.request_sync
|
|
1322
|
+
self.replay_recent_chain(25)
|
|
1323
|
+
t = threading.Timer(0.6, self.request_sync)
|
|
1324
|
+
t.daemon = True
|
|
1325
|
+
t.start()
|
|
1130
1326
|
self._emit_event("state_update", self.get_web_state())
|
|
1131
1327
|
|
|
1132
1328
|
def print_room_banner(self) -> None:
|
|
@@ -1455,6 +1651,7 @@ def main(argv: Optional[List[str]] = None) -> None:
|
|
|
1455
1651
|
if args.web:
|
|
1456
1652
|
from bstkchat.web import WebServer
|
|
1457
1653
|
|
|
1654
|
+
chat.replay_recent_chain(25)
|
|
1458
1655
|
web_server = WebServer(chat, port=args.web_port)
|
|
1459
1656
|
url = web_server.start()
|
|
1460
1657
|
chat.safe_print(
|
|
@@ -1483,7 +1680,7 @@ def main(argv: Optional[List[str]] = None) -> None:
|
|
|
1483
1680
|
|
|
1484
1681
|
chat.clear_screen()
|
|
1485
1682
|
chat.print_room_banner()
|
|
1486
|
-
chat.replay_recent_chain(
|
|
1683
|
+
chat.replay_recent_chain(25)
|
|
1487
1684
|
|
|
1488
1685
|
dynamic_style = DynamicStyle(
|
|
1489
1686
|
lambda: PromptStyle.from_dict(THEME_STYLES.get(chat.theme, THEME_STYLES["dark"]))
|
|
@@ -1558,6 +1755,29 @@ def main(argv: Optional[List[str]] = None) -> None:
|
|
|
1558
1755
|
else:
|
|
1559
1756
|
chat.send_private_message(parts[1], " ".join(parts[2:]))
|
|
1560
1757
|
|
|
1758
|
+
elif cmd == "/reply":
|
|
1759
|
+
if len(parts) < 2:
|
|
1760
|
+
chat.print_system("Usage: /reply <message>")
|
|
1761
|
+
elif not chat._last_msg_info:
|
|
1762
|
+
chat.print_system("No recent message to reply to.")
|
|
1763
|
+
else:
|
|
1764
|
+
chat.send_chat_message(" ".join(parts[1:]), reply_to=chat._last_msg_info)
|
|
1765
|
+
|
|
1766
|
+
elif cmd == "/react":
|
|
1767
|
+
if len(parts) < 2:
|
|
1768
|
+
chat.print_system("Usage: /react <emoji>")
|
|
1769
|
+
elif not chat._last_msg_info:
|
|
1770
|
+
chat.print_system("No recent message to react to.")
|
|
1771
|
+
else:
|
|
1772
|
+
chat.send_reaction(chat._last_msg_info["id"], parts[1])
|
|
1773
|
+
|
|
1774
|
+
elif cmd == "/delete":
|
|
1775
|
+
if not chat._last_own_msg_id:
|
|
1776
|
+
chat.print_system("No recent message of yours to delete.")
|
|
1777
|
+
else:
|
|
1778
|
+
chat.send_delete(chat._last_own_msg_id)
|
|
1779
|
+
chat.print_system("🗑️ Deleted your last message.")
|
|
1780
|
+
|
|
1561
1781
|
elif cmd == "/send":
|
|
1562
1782
|
if len(parts) < 2:
|
|
1563
1783
|
chat.print_system("Usage: /send <filepath>")
|
|
@@ -39,6 +39,23 @@ def save_config(config: Dict[str, Any]) -> None:
|
|
|
39
39
|
pass
|
|
40
40
|
|
|
41
41
|
|
|
42
|
+
def record_recent_room(room_id: str, nickname: str, has_password: bool) -> List[Dict[str, Any]]:
|
|
43
|
+
"""Updates the recent rooms list in config.json (never stores passwords)."""
|
|
44
|
+
cfg = load_config()
|
|
45
|
+
recent = cfg.get("recent_rooms", [])
|
|
46
|
+
if not isinstance(recent, list):
|
|
47
|
+
recent = []
|
|
48
|
+
recent = [r for r in recent if isinstance(r, dict) and r.get("room_id") != room_id]
|
|
49
|
+
recent.insert(0, {
|
|
50
|
+
"room_id": room_id,
|
|
51
|
+
"nickname": nickname,
|
|
52
|
+
"has_password": bool(has_password),
|
|
53
|
+
})
|
|
54
|
+
cfg["recent_rooms"] = recent[:10]
|
|
55
|
+
save_config(cfg)
|
|
56
|
+
return cfg["recent_rooms"]
|
|
57
|
+
|
|
58
|
+
|
|
42
59
|
def sanitize_filename(filename: str) -> str:
|
|
43
60
|
"""Strips directory components and unsafe characters from an incoming filename."""
|
|
44
61
|
base = os.path.basename(filename.strip())
|
|
@@ -24,6 +24,13 @@ SAFE_INLINE_IMAGES = {
|
|
|
24
24
|
".gif": "image/gif",
|
|
25
25
|
".webp": "image/webp",
|
|
26
26
|
}
|
|
27
|
+
SAFE_INLINE_AUDIO = {
|
|
28
|
+
".webm": "audio/webm",
|
|
29
|
+
".ogg": "audio/ogg",
|
|
30
|
+
".mp3": "audio/mpeg",
|
|
31
|
+
".wav": "audio/wav",
|
|
32
|
+
".m4a": "audio/mp4",
|
|
33
|
+
}
|
|
27
34
|
|
|
28
35
|
|
|
29
36
|
def _load_web_html() -> bytes:
|
|
@@ -154,8 +161,9 @@ class WebServer:
|
|
|
154
161
|
filename = sanitize_filename(str(entry["filename"]))
|
|
155
162
|
ext = os.path.splitext(filename)[1].lower()
|
|
156
163
|
raw_bytes = bytes(entry["data"])
|
|
157
|
-
|
|
158
|
-
|
|
164
|
+
safe_media = {**SAFE_INLINE_IMAGES, **SAFE_INLINE_AUDIO}
|
|
165
|
+
mime = safe_media.get(ext, "application/octet-stream")
|
|
166
|
+
is_inline = (ext in safe_media) and not force_download
|
|
159
167
|
disp = f'inline; filename="{filename}"' if is_inline else f'attachment; filename="{filename}"'
|
|
160
168
|
|
|
161
169
|
self.send_response(HTTPStatus.OK)
|
|
@@ -214,13 +222,41 @@ class WebServer:
|
|
|
214
222
|
if parsed.path == "/api/send":
|
|
215
223
|
text = str(data.get("text", "")).strip()
|
|
216
224
|
target = str(data.get("target", "")).strip()
|
|
225
|
+
reply_to = data.get("reply_to") if isinstance(data.get("reply_to"), dict) else None
|
|
217
226
|
if not text:
|
|
218
227
|
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "Empty message"})
|
|
219
228
|
return
|
|
220
229
|
if target:
|
|
221
230
|
chat.send_private_message(target, text)
|
|
222
231
|
else:
|
|
223
|
-
chat.send_chat_message(text)
|
|
232
|
+
chat.send_chat_message(text, reply_to=reply_to)
|
|
233
|
+
self._send_json(HTTPStatus.OK, {"ok": True})
|
|
234
|
+
return
|
|
235
|
+
|
|
236
|
+
if parsed.path == "/api/react":
|
|
237
|
+
target_id = str(data.get("target_id", "")).strip()
|
|
238
|
+
emoji = str(data.get("emoji", "")).strip()
|
|
239
|
+
ok = chat.send_reaction(target_id, emoji)
|
|
240
|
+
self._send_json(HTTPStatus.OK, {"ok": ok})
|
|
241
|
+
return
|
|
242
|
+
|
|
243
|
+
if parsed.path == "/api/edit":
|
|
244
|
+
target_id = str(data.get("target_id", "")).strip()
|
|
245
|
+
text = str(data.get("text", "")).strip()
|
|
246
|
+
ok = chat.send_edit(target_id, text)
|
|
247
|
+
self._send_json(HTTPStatus.OK, {"ok": ok})
|
|
248
|
+
return
|
|
249
|
+
|
|
250
|
+
if parsed.path == "/api/delete":
|
|
251
|
+
target_id = str(data.get("target_id", "")).strip()
|
|
252
|
+
ok = chat.send_delete(target_id)
|
|
253
|
+
self._send_json(HTTPStatus.OK, {"ok": ok})
|
|
254
|
+
return
|
|
255
|
+
|
|
256
|
+
if parsed.path == "/api/ack":
|
|
257
|
+
target_id = str(data.get("target_id", "")).strip()
|
|
258
|
+
status = str(data.get("status", "read"))
|
|
259
|
+
chat.send_ack(target_id, status)
|
|
224
260
|
self._send_json(HTTPStatus.OK, {"ok": True})
|
|
225
261
|
return
|
|
226
262
|
|