-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
2937 lines (2427 loc) · 109 KB
/
app.py
File metadata and controls
2937 lines (2427 loc) · 109 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
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import base64
from collections import deque
from datetime import datetime
from functools import wraps
import re
import unicodedata
from google.protobuf import text_format
from flask import Flask, render_template, request, jsonify, session, redirect, url_for, has_request_context, flash, send_from_directory
from flask_socketio import SocketIO, emit, join_room, leave_room, rooms
import uuid
import os
import socketio as py_socketio
import engineio
import meshtastic
from pubsub import pub
from werkzeug.security import generate_password_hash, check_password_hash
from meshtastic.protobuf import mesh_pb2, portnums_pb2
from mudp import node
from mudp.reliability import is_ack, is_nak, parse_routing
from database import Database
from encryption import generate_hash
from firefly_logging import configure_logging, get_logger, make_log_print
from mesh_runtime import (
MeshNodeStore,
SharedPacketReceiver,
VirtualNodeManager,
count_nodes_for_profiles,
find_meshdb_node_id_conflict,
)
from vnode.crypto import b64_decode
configure_logging()
logger = get_logger("firefly.app")
print = make_log_print(logger)
MCAST_GRP = os.getenv("FIREFLY_MCAST_GRP", "224.0.0.69")
MCAST_PORT = int(os.getenv("FIREFLY_UDP_PORT", "4403"))
SOCKETIO_CLIENT_VERSION = "4.7.5"
BROADCAST_NODE_NUM = 0xFFFFFFFF
DEFAULT_SECRET_KEY = "dev-secret-key-change-in-production"
NODE_ID_PATTERN = re.compile(r"^![0-9a-f]{8}$")
SHORT_NAME_ALNUM_PATTERN = re.compile(r"^[A-Za-z0-9]{1,4}$")
# Cross-source de-duplication cache for user-visible packet handling.
_DEDUP_CACHE = set()
_DEDUP_QUEUE = deque(maxlen=500)
# Initialize database with environment variable path for Docker persistence
db_path = os.getenv('FIREFLY_DATABASE_FILE', 'firefly.db')
print(f"[DATABASE] Initializing database at: {db_path}")
# Ensure database directory exists
db_dir = os.path.dirname(db_path)
if db_dir and not os.path.exists(db_dir):
os.makedirs(db_dir, exist_ok=True)
print(f"[DATABASE] Created database directory: {db_dir}")
db = Database(db_path)
# Map WebSocket session IDs to Flask session IDs for cleanup
websocket_to_flask_sessions = {}
def _get_session_profile():
"""Get the current profile from session storage"""
if not has_request_context():
return None
profile = session.get("current_profile")
current_user = _get_session_user()
if profile and current_user and profile.get("user_id") == current_user.get("id"):
return profile
return None
def _set_session_profile(profile):
"""Set the current profile in session storage"""
if not has_request_context():
return
session["current_profile"] = profile
def _clear_session_profile():
"""Clear the current profile from session storage"""
if not has_request_context():
return
session.pop("current_profile", None)
session.pop("current_channel_index", None)
def _get_session_channel_index():
if not has_request_context():
return 0
try:
return int(session.get("current_channel_index", 0))
except (TypeError, ValueError):
return 0
def _set_session_channel_index(channel_index):
if not has_request_context():
return
try:
session["current_channel_index"] = max(0, int(channel_index))
except (TypeError, ValueError):
session["current_channel_index"] = 0
def _get_session_user():
if not has_request_context():
return None
user_id = session.get("user_id")
if not user_id:
return None
return db.get_user_by_id(user_id)
def _set_session_user(user):
if not has_request_context():
return
session["user_id"] = user["id"]
def _clear_session_user():
if not has_request_context():
return
session.pop("user_id", None)
_clear_session_profile()
def _unregister_current_session_transport():
if not has_request_context():
return
if not session.get("current_profile"):
return
session_id = f"flask_session_{id(session)}"
try:
udp_server.unregister_session(session_id)
except Exception as e:
print(f"[SESSION] Failed to unregister UDP session {session_id}: {e}")
def _wants_json_response():
if not has_request_context():
return False
if request.path.startswith("/api/"):
return True
best = request.accept_mimetypes.best
return best == "application/json" and request.accept_mimetypes[best] >= request.accept_mimetypes["text/html"]
def login_required(view):
@wraps(view)
def wrapped(*args, **kwargs):
if _get_session_user():
return view(*args, **kwargs)
if _wants_json_response():
return jsonify({"error": "Authentication required"}), 401
return redirect(url_for("index"))
return wrapped
def _normalize_node_id(node_id):
value = (node_id or "").strip()
return value.lower() if value.startswith("!") else value
def _normalize_text_field(value):
return value.strip() if isinstance(value, str) else ""
def _is_valid_short_name(short_name):
value = _normalize_text_field(short_name)
if not value:
return False
if SHORT_NAME_ALNUM_PATTERN.fullmatch(value):
return len(value.encode("utf-8")) <= 4
return (
len(value) == 1
and len(value.encode("utf-8")) <= 4
and unicodedata.category(value) == "So"
)
def _is_valid_channel_key(channel_key):
value = _normalize_text_field(channel_key).replace("-", "+").replace("_", "/")
if not value:
return False
try:
decoded = base64.b64decode(value.encode("ascii"), validate=True)
except Exception:
return False
return len(decoded) in {1, 16, 32}
def _validate_profile_request_payload(data):
normalized_node_id = _normalize_node_id(_normalize_text_field((data or {}).get("node_id")))
long_name = _normalize_text_field((data or {}).get("long_name"))
short_name = _normalize_text_field((data or {}).get("short_name"))
channels = _profile_channels(data)
if not normalized_node_id or not long_name or not short_name or not channels:
return None, "node_id, long_name, short_name, and at least one channel are required"
if not NODE_ID_PATTERN.fullmatch(normalized_node_id):
return None, "node_id must be ! followed by 8 hexadecimal characters"
if len(long_name) >= 32:
return None, "long_name must be fewer than 32 characters"
if not _is_valid_short_name(short_name):
return None, "short_name must be 1 emoji without modifiers or 1-4 alphanumeric characters"
hop_limit = (data or {}).get("hop_limit", 3)
if not isinstance(hop_limit, int) or hop_limit < 0 or hop_limit > 7:
return None, "hop_limit must be an integer between 0 and 7"
return {
"node_id": normalized_node_id,
"long_name": long_name,
"short_name": short_name,
"channels": channels,
"hop_limit": hop_limit,
}, None
def _profile_channels(profile):
if not profile:
return []
channels = profile.get("channels")
if isinstance(channels, list) and channels:
return [
{
"name": (channel.get("name") or "").strip(),
"key": (channel.get("key") or "").strip(),
}
for channel in channels
if isinstance(channel, dict) and (channel.get("name") or "").strip() and (channel.get("key") or "").strip()
]
channel_name = (profile.get("channel") or "").strip()
channel_key = (profile.get("key") or "").strip()
if channel_name and channel_key:
return [{"name": channel_name, "key": channel_key}]
return []
def _profile_node_id_conflict_error(node_id, exclude_profile_id=None):
if db.node_id_in_use(node_id, exclude_profile_id=exclude_profile_id):
return "Node ID is already in use by another profile."
conflict = find_meshdb_node_id_conflict(
profile_manager.get_all_profiles(),
node_id,
exclude_profile_id=exclude_profile_id,
)
if conflict:
print(
f"[PROFILES] Rejected node_id {node_id} because it already exists in meshdb "
f"for profile {conflict.get('owner_profile_id')} at {conflict.get('meshdb_file')}"
)
return "Node ID is already in use by another node in the mesh database."
return None
def _selected_channel_index(profile=None):
channels = _profile_channels(profile or _get_session_profile())
if not channels:
return 0
if profile is not None:
try:
selected_index = int(profile.get("selected_channel_index", 0) or 0)
except (AttributeError, TypeError, ValueError):
selected_index = 0
if "selected_channel_index" in profile or not has_request_context():
return min(max(selected_index, 0), len(channels) - 1)
return min(_get_session_channel_index(), len(channels) - 1)
def _selected_channel(profile=None):
channels = _profile_channels(profile or _get_session_profile())
if not channels:
return None
return channels[_selected_channel_index(profile)]
def _effective_profile(profile=None, channel_index=None):
profile = profile or _get_session_profile()
if not profile:
return None
effective = dict(profile)
channels = _profile_channels(profile)
effective["channels"] = channels
if channels:
if channel_index is None:
selected_index = _selected_channel_index(profile)
else:
selected_index = max(0, min(int(channel_index), len(channels) - 1))
selected = channels[selected_index]
effective["channel"] = selected["name"]
effective["key"] = selected["key"]
effective["selected_channel_index"] = selected_index
else:
effective["selected_channel_index"] = 0
return effective
def _current_profile_channel_num():
"""Compute the expected channel number for the current profile using name+key hash.
Returns an int channel number or None if unavailable.
"""
try:
current_profile = _effective_profile()
if not current_profile:
return None
ch_name = current_profile.get("channel")
key = current_profile.get("key")
if not ch_name or not key:
return None
return generate_hash(ch_name, key)
except Exception:
return None
def _profile_channel_num(profile):
try:
profile = _effective_profile(profile)
if not profile:
return None
ch_name = profile.get("channel")
key = profile.get("key")
if not ch_name or not key:
return None
return generate_hash(ch_name, key)
except Exception:
return None
def _channel_number_for_config(channel):
if not isinstance(channel, dict):
return None
name = (channel.get("name") or "").strip()
key = (channel.get("key") or "").strip()
if not name or not key:
return None
try:
return generate_hash(name, key)
except Exception:
return None
def _profile_channels_with_numbers(profile):
channels = []
for channel in _profile_channels(profile):
channel_data = dict(channel)
channel_data["channel_number"] = _channel_number_for_config(channel)
channels.append(channel_data)
return channels
def _serialize_profile_for_client(profile, interface_status=None):
if not profile:
return None
channels = _profile_channels_with_numbers(profile)
response_data = dict(profile)
response_data["channels"] = channels
if channels:
selected_channel_index = min(max(_selected_channel_index(profile), 0), len(channels) - 1)
response_data["selected_channel_index"] = selected_channel_index
response_data["selected_channel"] = channels[selected_channel_index]
response_data["channel_number"] = channels[selected_channel_index].get("channel_number")
else:
response_data["selected_channel_index"] = 0
response_data["selected_channel"] = None
response_data["channel_number"] = None
if interface_status is not None:
response_data["interface_status"] = interface_status
return response_data
def _profile_node_num(profile):
try:
node_id = profile.get("node_id") if profile else None
if isinstance(node_id, str) and node_id.startswith("!"):
return int(node_id[1:], 16)
except Exception:
pass
return None
def _node_id_from_num(node_num):
if node_num is None:
return None
return f"!{int(node_num):08x}"
def _is_direct_message(packet, profile=None):
packet_to = getattr(packet, "to", None)
if packet_to in (None, 0, BROADCAST_NODE_NUM):
return False
profile = profile or udp_server.get_active_profile()
my_num = _profile_node_num(profile) if profile else None
if my_num is None:
return True
return int(packet_to) == int(my_num)
def _already_seen(key):
"""Return True if we've already processed a packet with this key."""
if key in _DEDUP_CACHE:
return True
_DEDUP_CACHE.add(key)
_DEDUP_QUEUE.append(key)
if len(_DEDUP_CACHE) > _DEDUP_QUEUE.maxlen:
old = _DEDUP_QUEUE.popleft()
_DEDUP_CACHE.discard(old)
return False
def _routing_error_name(error_reason):
if error_reason is None:
return None
try:
return mesh_pb2.Routing.Error.Name(int(error_reason))
except Exception:
return str(error_reason)
def _emit_message_update(message):
if not message:
return
room_name = None
if (message.get("message_type") or "channel") == "dm" and message.get("owner_profile_id"):
room_name = f"profile_{message['owner_profile_id']}"
elif message.get("channel") is not None:
room_name = f"channel_{message['channel']}"
if not room_name:
return
try:
socketio.emit("message_update", message, room=room_name)
except Exception as e:
print(f"[ACK] Failed to broadcast message update for packet {message.get('packet_id')}: {e}")
def _apply_ack_update(packet_id, ack_status, ack_error=None):
updated_messages = db.update_message_ack_status(packet_id, ack_status, ack_error)
if not updated_messages:
return
for message in updated_messages:
_emit_message_update(message)
def _emit_node_update(profile_id, node):
if not profile_id or not node:
return
try:
socketio.emit("node_update", {"profile_id": profile_id, "node": node}, room=f"profile_{profile_id}")
except Exception as e:
print(f"[NODEINFO] Failed to broadcast node update for profile {profile_id}: {e}")
shared_packet_receiver = SharedPacketReceiver(MCAST_GRP, MCAST_PORT)
virtual_node_manager = VirtualNodeManager(MCAST_GRP, MCAST_PORT, shared_receiver=shared_packet_receiver)
shared_packet_receiver.start()
def _get_mesh_store(profile=None):
profile = _effective_profile(profile)
if not profile or not profile.get("node_id"):
return None
normalized_node_num = _profile_node_num(profile)
if normalized_node_num is None:
print(
f"[MESHDB] Skipping node store for profile {profile.get('id')!r}: "
f"invalid node_id {profile.get('node_id')!r}"
)
return None
try:
return MeshNodeStore(profile)
except Exception as e:
print(
f"[MESHDB] Failed to create node store for profile {profile.get('id')!r} "
f"with node_id {profile.get('node_id')!r}: {e}"
)
return None
def _seed_profile_mesh_identity(profile):
mesh_store = _get_mesh_store(profile)
if not mesh_store:
return False
try:
mesh_store.ensure_owner_node()
return True
except Exception as e:
print(f"[MESHDB] Failed to seed owner node for profile {profile.get('id')}: {e}")
return False
def _mesh_stores_for_profiles(profiles):
stores = []
seen_profile_ids = set()
for profile in profiles or []:
if not isinstance(profile, dict):
continue
profile_id = profile.get("id")
if not profile_id or profile_id in seen_profile_ids:
continue
mesh_store = _get_mesh_store(profile)
if mesh_store:
stores.append((profile, mesh_store))
seen_profile_ids.add(profile_id)
return stores
def _generated_node_long_name(node_num):
try:
suffix = f"{int(node_num):08x}"[-4:]
return f"Meshtastic {suffix}"
except (TypeError, ValueError):
return None
def _generated_node_short_name(node_num):
try:
return f"{int(node_num):08x}"[-4:]
except (TypeError, ValueError):
return None
def _is_fallback_node_label(value, node_num):
normalized_value = str(value or "").strip()
if not normalized_value:
return True
normalized_value_lower = normalized_value.lower()
fallback_candidates = {
"unknown",
str(_node_id_from_num(node_num) or "").lower(),
str(_generated_node_long_name(node_num) or "").lower(),
str(_generated_node_short_name(node_num) or "").lower(),
}
return normalized_value_lower in fallback_candidates
def _merge_node_records(existing, incoming):
if not incoming:
return existing
if not existing:
return dict(incoming)
merged = dict(existing)
node_num = incoming.get("node_num") or existing.get("node_num")
def prefer(preferred_key, *, treat_fallback=False, fallback_values=None):
current_value = merged.get(preferred_key)
incoming_value = incoming.get(preferred_key)
if incoming_value in (None, ""):
return
if current_value in (None, ""):
merged[preferred_key] = incoming_value
return
if treat_fallback and _is_fallback_node_label(current_value, node_num) and not _is_fallback_node_label(incoming_value, node_num):
merged[preferred_key] = incoming_value
return
if fallback_values and current_value in fallback_values and incoming_value not in fallback_values:
merged[preferred_key] = incoming_value
prefer("node_id")
prefer("long_name", treat_fallback=True)
prefer("short_name", treat_fallback=True)
prefer("hw_model", fallback_values={"UNSET"})
prefer("role", fallback_values={"CLIENT"})
prefer("public_key")
prefer("macaddr")
prefer("raw_nodeinfo")
prefer("hops_away")
prefer("snr")
prefer("latitude")
prefer("longitude")
prefer("altitude")
prefer("position_timestamp")
prefer("first_seen")
prefer("last_seen")
prefer("packet_count")
return merged
def _channel_numbers_for_profile(profile):
effective_profile = _effective_profile(profile)
return [
channel.get("channel_number")
for channel in _profile_channels_with_numbers(effective_profile)
if channel.get("channel_number") is not None
]
def _nodes_for_profile(profile):
effective_profile = _effective_profile(profile)
if not effective_profile:
return []
mesh_store = _get_mesh_store(effective_profile)
if not mesh_store:
return []
try:
return mesh_store.list_nodes()
except Exception:
return []
def _node_for_profile(profile, node_num):
effective_profile = _effective_profile(profile)
if not effective_profile:
return None
mesh_store = _get_mesh_store(effective_profile)
if not mesh_store:
return None
try:
return mesh_store.get_node(int(node_num))
except Exception:
return None
def _profiles_matching_packet(packet):
matched_profiles = []
seen_profile_ids = set()
packet_to = getattr(packet, "to", None)
if packet_to not in (None, 0, BROADCAST_NODE_NUM):
owner_profile = db.get_profile_by_node_num(packet_to)
if owner_profile and owner_profile.get("id") not in seen_profile_ids:
matched_profiles.append(owner_profile)
seen_profile_ids.add(owner_profile.get("id"))
try:
packet_channel = int(getattr(packet, "channel", 0) or 0)
except Exception:
packet_channel = 0
if packet_channel <= 0:
return matched_profiles
try:
all_profiles = db.get_all_profiles()
except Exception:
return matched_profiles
for profile in all_profiles.values():
profile_id = profile.get("id")
if profile_id in seen_profile_ids:
continue
for channel in _profile_channels(profile):
if _channel_number_for_config(channel) == packet_channel:
matched_profiles.append(profile)
seen_profile_ids.add(profile_id)
break
return matched_profiles
def _matching_mesh_stores_for_packet(packet):
return _mesh_stores_for_profiles(_profiles_matching_packet(packet))
def _storage_mesh_stores_for_packet(packet):
packet_channel = getattr(packet, "channel", None)
try:
normalized_channel = int(packet_channel or 0)
except (TypeError, ValueError):
normalized_channel = 0
unique_stores = []
seen_keys = set()
for profile, mesh_store in _matching_mesh_stores_for_packet(packet):
if normalized_channel > 0:
key = ("channel", normalized_channel)
else:
key = ("profile", profile.get("id"))
if key in seen_keys:
continue
seen_keys.add(key)
unique_stores.append((profile, mesh_store))
return unique_stores
def _find_sender_node_for_packet(packet, sender_num):
if sender_num in (None, 0):
return None
local_sender_profile = db.get_profile_by_node_num(sender_num)
if local_sender_profile:
return {
"long_name": local_sender_profile.get("long_name"),
"short_name": local_sender_profile.get("short_name"),
}
merged_node = None
for _profile, mesh_store in _matching_mesh_stores_for_packet(packet):
try:
found_node = mesh_store.get_node(sender_num)
except Exception:
found_node = None
merged_node = _merge_node_records(merged_node, found_node)
if merged_node and not _is_fallback_node_label(merged_node.get("long_name"), sender_num):
return merged_node
active_profile = udp_server.get_active_profile()
if active_profile:
mesh_store = _get_mesh_store(active_profile)
if mesh_store:
try:
merged_node = _merge_node_records(merged_node, mesh_store.get_node(sender_num))
except Exception:
pass
return merged_node
def _emit_message_to_profile_rooms(message, profiles):
if not message:
return
emitted_profile_ids = set()
for profile in profiles or []:
profile_id = profile.get("id") if isinstance(profile, dict) else None
if not profile_id or profile_id in emitted_profile_ids:
continue
socketio.emit("new_message", message, room=f"profile_{profile_id}")
emitted_profile_ids.add(profile_id)
def _display_name_for_node_num(node_num):
if node_num in (None, 0):
return None
local_profile = db.get_profile_by_node_num(node_num)
if local_profile:
return local_profile.get("short_name") or local_profile.get("long_name") or local_profile.get("node_id")
try:
all_profiles = db.get_all_profiles()
except Exception:
all_profiles = {}
for profile in all_profiles.values():
mesh_store = _get_mesh_store(profile)
if not mesh_store:
continue
try:
found_node = mesh_store.get_node(node_num)
except Exception:
found_node = None
if found_node:
return found_node.get("short_name") or found_node.get("long_name") or found_node.get("node_id")
return _node_id_from_num(node_num)
def _message_has_fallback_sender_display(message):
if not message:
return True
sender_display = (message.get("sender_display") or "").strip()
sender_id = (message.get("sender") or "").strip()
sender_display_lower = sender_display.lower()
sender_id_lower = sender_id.lower()
if not sender_display or sender_display_lower == "unknown" or (sender_id and sender_display_lower == sender_id_lower):
return True
sender_num = message.get("sender_num")
try:
suffix = f"{int(sender_num):08x}"[-4:]
generated_display = f"Meshtastic {suffix}"
except (TypeError, ValueError):
generated_display = None
return bool(generated_display and sender_display_lower == generated_display.lower())
def _hydrate_message_sender_labels(messages, profile):
mesh_store = _get_mesh_store(profile)
if not mesh_store:
mesh_store = None
for message in messages or []:
sender_num = message.get("sender_num")
if sender_num in (None, 0):
continue
try:
found_node = mesh_store.get_node(int(sender_num)) if mesh_store else None
except Exception:
found_node = None
if not found_node:
continue
preferred_display = found_node.get("long_name") or found_node.get("short_name") or found_node.get("node_id")
if preferred_display and _message_has_fallback_sender_display(message):
message["sender_display"] = preferred_display
if message.get("direction") == "received" and message.get("channel") is not None:
db.update_received_message_sender_display(message.get("channel"), int(sender_num), preferred_display)
if found_node.get("short_name"):
message["sender_short_name"] = found_node.get("short_name")
return messages
def _get_chat_payload(profile):
effective_profile = _effective_profile(profile)
channel_number = _profile_channel_num(effective_profile)
channel_messages = []
if effective_profile and channel_number is not None:
channel_messages = db.get_messages_for_channel(channel_number, profile_id=effective_profile["id"])
dm_messages = db.get_dm_messages_for_profile(effective_profile["id"]) if effective_profile else []
_hydrate_message_sender_labels(channel_messages, effective_profile)
_hydrate_message_sender_labels(dm_messages, effective_profile)
return {
"channel_messages": channel_messages,
"dm_messages": dm_messages,
"channel_number": channel_number,
"selected_channel_index": effective_profile.get("selected_channel_index", 0) if effective_profile else 0,
}
def _interface_status_for_profile(profile) -> str:
if shared_packet_receiver.running:
return "started"
effective_profile = _effective_profile(profile)
if not effective_profile:
return "stopped"
profile_channel_hash = generate_hash(effective_profile.get("channel", ""), effective_profile.get("key", ""))
if (
udp_server.running
and udp_server.current_profile_id == effective_profile.get("id")
and udp_server.current_channel_hash == profile_channel_hash
):
return "started"
return "stopped"
def _dm_owner_profile_for_packet(packet: mesh_pb2.MeshPacket):
"""Resolve which local profile should own a received DM."""
target_node_num = getattr(packet, "to", None)
if target_node_num in (None, 0, BROADCAST_NODE_NUM):
return None
return db.get_profile_by_node_num(target_node_num)
def _ensure_local_dm_ack(packet: mesh_pb2.MeshPacket, owner_profile) -> None:
if not owner_profile:
return
if not getattr(packet, "want_ack", False):
return
if is_ack(packet) or is_nak(packet):
return
try:
ack_packet_id = udp_server.send_ack_for_profile(owner_profile, packet)
print(
f"[ACK] Sent routing ACK for local DM packet {getattr(packet, 'id', None)} "
f"as profile {owner_profile.get('id')} (ack packet {ack_packet_id})"
)
except Exception as e:
print(
f"[ACK] Failed to send routing ACK for local DM packet {getattr(packet, 'id', None)} "
f"as profile {owner_profile.get('id')}: {e}"
)
def _coerce_public_key_bytes(value):
if not value:
return None
if isinstance(value, (bytes, bytearray)):
return bytes(value)
if isinstance(value, str):
try:
return b64_decode(value.strip())
except Exception:
return None
return None
def _sender_public_key_for_local_packet(owner_profile, sender_num):
if sender_num in (None, 0):
return None
local_sender_profile = db.get_profile_by_node_num(sender_num)
if local_sender_profile:
local_public_key = virtual_node_manager.get_profile_public_key(local_sender_profile)
if local_public_key is not None:
return local_public_key
mesh_store = _get_mesh_store(owner_profile) if owner_profile else None
if not mesh_store:
return None
sender_node = mesh_store.get_node(sender_num)
if not sender_node:
return None
return _coerce_public_key_bytes(sender_node.get("public_key"))
def _maybe_ack_local_direct_packet(packet: mesh_pb2.MeshPacket) -> None:
owner_profile = _dm_owner_profile_for_packet(packet)
if not owner_profile:
return
pkt_id = int(getattr(packet, "id", 0) or 0)
if pkt_id > 0 and _already_seen(("local-direct-ack", owner_profile.get("id"), pkt_id)):
return
if packet.HasField("decoded"):
if is_ack(packet) or is_nak(packet):
return
if int(getattr(packet.decoded, "portnum", 0) or 0) not in (
int(portnums_pb2.PortNum.TEXT_MESSAGE_APP),
int(portnums_pb2.PortNum.TEXT_MESSAGE_COMPRESSED_APP),
):
return
_ensure_local_dm_ack(packet, owner_profile)
def _decode_local_direct_packet(packet: mesh_pb2.MeshPacket):
owner_profile = _dm_owner_profile_for_packet(packet)
if not owner_profile:
return None, None
if packet.HasField("decoded"):
return packet, owner_profile
sender_public_key = _sender_public_key_for_local_packet(
owner_profile,
getattr(packet, "from", None),
)
decoded_packet = udp_server.decode_packet_for_profile(
owner_profile,
packet,
sender_public_key=sender_public_key,
)
return decoded_packet, owner_profile
def _decode_packet_for_service(packet: mesh_pb2.MeshPacket):
if packet.HasField("decoded"):
return packet
decoded_packet, owner_profile = _decode_local_direct_packet(packet)
if decoded_packet is not None:
return decoded_packet
packet_channel = int(getattr(packet, "channel", 0) or 0)
if packet_channel == 0:
return None
try:
all_profiles = db.get_all_profiles()
except Exception:
return None
for profile in all_profiles.values():
for channel in _profile_channels(profile):
try:
if generate_hash(channel["name"], channel["key"]) != packet_channel:
continue
except Exception:
continue
decoded_packet = udp_server.decode_packet_for_profile(profile, packet)
if decoded_packet is not None:
return decoded_packet
return None
def _unread_state_for_profile(profile):
effective_profile = _effective_profile(profile)
if not effective_profile:
return {"unread_channel_counts": {}, "unread_dm_counts": {}}
channel_numbers = [
channel.get("channel_number")
for channel in _profile_channels_with_numbers(effective_profile)
if channel.get("channel_number") is not None
]
unread_channel_counts = db.get_unread_channel_counts(effective_profile["id"], channel_numbers)
unread_dm_counts = db.get_unread_dm_counts(effective_profile["id"])
return {
"unread_channel_counts": unread_channel_counts,
"unread_dm_counts": unread_dm_counts,
}