-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker_core.py
More file actions
2134 lines (1837 loc) · 84.7 KB
/
Copy pathtracker_core.py
File metadata and controls
2134 lines (1837 loc) · 84.7 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
import json
import mimetypes
import os
import secrets
import shutil
import string
import urllib.parse
import urllib.request
import random
from base64 import urlsafe_b64encode
from datetime import date, datetime, timezone
from hashlib import sha256
from pathlib import Path
try:
import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
except ImportError: # pragma: no cover
boto3 = None
Config = None
BotoCoreError = Exception
ClientError = Exception
try:
from cryptography.fernet import Fernet, InvalidToken
except ImportError: # pragma: no cover
Fernet = None
InvalidToken = Exception
DATA_FILE = "relationship_data.json"
HASH_FILE = "saved_hashes.json"
USER_FILE = "users.json"
AFFILIATION_PREFIX_FILE = "affiliation_prefixes.json"
STORAGE_SETTINGS_FILE = "storage_settings.json"
SITE_SETTINGS_FILE = "site_settings.json"
DEFAULT_RELATION_TAGS = ["NONE", "Sibling", "Friend", "Partner", "Spouse"]
DEFAULT_SPECIAL_RELATION_TAGS = {"Parent": "Child", "Child": "Parent"}
DEFAULT_ALTER_PREFIXES = ["UFA-"]
DEFAULT_AFFILIATION_PREFIXES = ["AFF-"]
LOCATION_PREFIX = "LOC-"
DOCUMENT_PREFIX = "DOC-"
WHEEL_PREFIX = "WHL-"
LEGACY_VALUE = "LEGACY"
STATUS_OPTIONS = ["Current", "Formerly", "Independent"]
ROLE_OPTIONS = ["user", "mod", "admin"]
GENDER_OPTIONS = ["Cisgender", "Transgender", "Nonbinary"]
ORGAN_OPTIONS = ["Penis", "Vagina", "Mixed", "Varies"]
RELATIONSHIP_STYLE_OPTIONS = ["Polyamorous", "Monogamous", "Harem (Center)", "Harem (Member)"]
MONTH_OPTIONS = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December",
]
HASH_LENGTH = 24
ALPHABET = string.ascii_letters + string.digits
class StorageError(RuntimeError):
pass
class LocalStorage:
def __init__(self, root):
self.root = Path(root)
def read_json(self, name, default):
path = self.root / name
if not path.exists():
return default
try:
with path.open("r", encoding="utf-8") as file:
return json.load(file)
except (json.JSONDecodeError, OSError):
return default
def write_json(self, name, data):
path = self.root / name
try:
with path.open("w", encoding="utf-8") as file:
json.dump(data, file, indent=2)
except OSError as exc:
raise StorageError(f"Unable to save {name}.") from exc
def read_bytes(self, name):
path = self.root / name
if not path.exists():
return None
try:
return path.read_bytes()
except OSError:
return None
def write_bytes(self, name, payload):
path = self.root / name
try:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(payload)
except OSError as exc:
raise StorageError(f"Unable to save {name}.") from exc
def delete_bytes(self, name):
path = self.root / name
try:
if path.exists():
path.unlink()
except OSError:
return False
return True
def iter_files(self, prefix):
root = self.root / prefix
if not root.exists():
return []
return [str(path.relative_to(self.root)).replace("\\", "/") for path in root.rglob("*") if path.is_file()]
def get_download_url(self, name, expires_in=300):
return None
class S3Storage:
def __init__(self, bucket, prefix="", endpoint="", region="", access_key="", secret_key="", path_style=False):
if boto3 is None:
raise RuntimeError("boto3 is required for S3 storage.")
self.bucket = bucket
self.prefix = prefix.strip("/")
client_kwargs = {}
if endpoint:
client_kwargs["endpoint_url"] = endpoint
if region and region.lower() != "auto":
client_kwargs["region_name"] = region
if access_key:
client_kwargs["aws_access_key_id"] = access_key
if secret_key:
client_kwargs["aws_secret_access_key"] = secret_key
if path_style and Config is not None:
client_kwargs["config"] = Config(s3={"addressing_style": "path"})
self.client = boto3.client("s3", **client_kwargs)
def _key(self, name):
return f"{self.prefix}/{name}" if self.prefix else name
def read_json(self, name, default):
try:
response = self.client.get_object(Bucket=self.bucket, Key=self._key(name))
return json.loads(response["Body"].read().decode("utf-8"))
except (ClientError, json.JSONDecodeError):
return default
def write_json(self, name, data):
body = json.dumps(data, indent=2).encode("utf-8")
try:
self.client.put_object(Bucket=self.bucket, Key=self._key(name), Body=body, ContentType="application/json")
except (ClientError, BotoCoreError) as exc:
raise StorageError(f"Unable to save {name} to S3.") from exc
def read_bytes(self, name):
try:
response = self.client.get_object(Bucket=self.bucket, Key=self._key(name))
return response["Body"].read()
except ClientError:
return None
def write_bytes(self, name, payload):
content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
try:
self.client.put_object(Bucket=self.bucket, Key=self._key(name), Body=payload, ContentType=content_type)
except (ClientError, BotoCoreError) as exc:
raise StorageError(f"Unable to save {name} to S3.") from exc
def delete_bytes(self, name):
try:
self.client.delete_object(Bucket=self.bucket, Key=self._key(name))
except ClientError:
return False
return True
def iter_files(self, prefix):
paginator = self.client.get_paginator("list_objects_v2")
keys = []
for page in paginator.paginate(Bucket=self.bucket, Prefix=self._key(prefix)):
for item in page.get("Contents", []):
key = item["Key"]
if self.prefix:
key = key[len(self.prefix) + 1 :]
keys.append(key)
return keys
def get_download_url(self, name, expires_in=300):
try:
return self.client.generate_presigned_url(
"get_object",
Params={"Bucket": self.bucket, "Key": self._key(name)},
ExpiresIn=expires_in,
)
except (ClientError, BotoCoreError):
return None
def get_storage(root):
settings = load_storage_settings(root)
backend = os.getenv("STORAGE_BACKEND", settings.get("backend", "local")).lower()
if backend == "s3":
endpoint = os.getenv("S3_ENDPOINT", settings.get("s3_endpoint", "")).strip()
bucket = os.getenv("S3_BUCKET", settings.get("s3_bucket", "")).strip()
region = os.getenv("S3_REGION", settings.get("s3_region", "auto")).strip()
access_key = os.getenv("S3_ACCESS_KEY", settings.get("s3_access_key", "")).strip()
secret_key = os.getenv("S3_SECRET_KEY", settings.get("s3_secret_key", "")).strip()
prefix = os.getenv("S3_PREFIX", settings.get("s3_prefix", ""))
path_style = os.getenv("S3_PATH_STYLE", str(settings.get("s3_path_style", False))).strip().lower() in {"1", "true", "yes", "on"}
if not bucket:
raise RuntimeError("S3_BUCKET is required when STORAGE_BACKEND=s3.")
return S3Storage(bucket, prefix, endpoint, region, access_key, secret_key, path_style)
return LocalStorage(root)
def unique_items(items):
seen = set()
ordered = []
for item in items:
if item not in seen:
seen.add(item)
ordered.append(item)
return ordered
def tracker_default():
return {
"alters": {},
"locations": {},
"affiliations": {},
"documents": {},
"wheels": {},
"relations": [],
"location_bindings": {},
"last_modified": {"alters": {}, "locations": {}, "affiliations": {}, "documents": {}, "wheels": {}},
"relation_tags": list(DEFAULT_RELATION_TAGS),
"special_relation_tags": dict(DEFAULT_SPECIAL_RELATION_TAGS),
"alter_prefixes": list(DEFAULT_ALTER_PREFIXES),
"affiliation_prefixes": list(DEFAULT_AFFILIATION_PREFIXES),
"alter_profiles": {},
"location_galleries": {},
"document_records": {},
"affiliation_records": {},
"wheel_records": {},
}
def users_default():
return {"users": []}
def hashes_default():
return {"hashes": []}
def storage_settings_default():
return {
"backend": "local",
"s3_endpoint": "",
"s3_bucket": "",
"s3_region": "auto",
"s3_access_key_encrypted": "",
"s3_secret_key_encrypted": "",
"s3_prefix": "",
"s3_path_style": False,
}
def site_settings_default():
return {
"site_name": "United Front Technical Database",
"favicon_name": "",
}
def get_settings_fernet():
secret = os.getenv("STORAGE_SETTINGS_KEY") or os.getenv("SECRET_KEY", "change-me-for-production")
if Fernet is None:
raise RuntimeError("cryptography is required for secure storage settings.")
key = urlsafe_b64encode(sha256(secret.encode("utf-8")).digest())
return Fernet(key)
def encrypt_storage_value(value):
value = str(value or "").strip()
if not value:
return ""
return get_settings_fernet().encrypt(value.encode("utf-8")).decode("utf-8")
def decrypt_storage_value(value):
value = str(value or "").strip()
if not value:
return ""
try:
return get_settings_fernet().decrypt(value.encode("utf-8")).decode("utf-8")
except InvalidToken as error:
raise RuntimeError("Stored S3 credentials could not be decrypted. Check SECRET_KEY or STORAGE_SETTINGS_KEY.") from error
def load_storage_settings(root):
path = Path(root) / STORAGE_SETTINGS_FILE
if not path.exists():
return storage_settings_default()
try:
with path.open("r", encoding="utf-8") as file:
data = json.load(file)
except (json.JSONDecodeError, OSError):
return storage_settings_default()
settings = storage_settings_default()
settings.update({key: data.get(key, value) for key, value in settings.items()})
settings["s3_path_style"] = bool(settings.get("s3_path_style"))
settings["s3_access_key"] = decrypt_storage_value(settings.get("s3_access_key_encrypted", ""))
settings["s3_secret_key"] = decrypt_storage_value(settings.get("s3_secret_key_encrypted", ""))
return settings
def save_storage_settings(root, settings):
path = Path(root) / STORAGE_SETTINGS_FILE
payload = storage_settings_default()
payload.update({key: settings.get(key, value) for key, value in payload.items()})
payload["s3_path_style"] = bool(settings.get("s3_path_style", False))
payload["s3_access_key_encrypted"] = encrypt_storage_value(settings.get("s3_access_key", ""))
payload["s3_secret_key_encrypted"] = encrypt_storage_value(settings.get("s3_secret_key", ""))
payload.pop("s3_access_key", None)
payload.pop("s3_secret_key", None)
with path.open("w", encoding="utf-8") as file:
json.dump(payload, file, indent=2)
def load_site_settings(root):
path = Path(root) / SITE_SETTINGS_FILE
if not path.exists():
return site_settings_default()
try:
with path.open("r", encoding="utf-8") as file:
data = json.load(file)
except (json.JSONDecodeError, OSError):
return site_settings_default()
settings = site_settings_default()
settings.update({key: data.get(key, value) for key, value in settings.items()})
return settings
def save_site_settings(root, settings):
path = Path(root) / SITE_SETTINGS_FILE
payload = site_settings_default()
payload.update({key: settings.get(key, value) for key, value in payload.items()})
with path.open("w", encoding="utf-8") as file:
json.dump(payload, file, indent=2)
def migrate_legacy_local_files(source_root, destination_root):
source_root = Path(source_root)
destination_root = Path(destination_root)
destination_root.mkdir(parents=True, exist_ok=True)
filenames = [DATA_FILE, HASH_FILE, USER_FILE, STORAGE_SETTINGS_FILE, SITE_SETTINGS_FILE]
for filename in filenames:
source_path = source_root / filename
destination_path = destination_root / filename
if source_path.exists() and not destination_path.exists():
shutil.move(str(source_path), str(destination_path))
def media_storage_name(kind, entry_id, filename):
return f"media/{kind}/{entry_id}/{filename}"
def is_managed_media_url(value):
return str(value or "").startswith("/media/")
def media_name_from_url(value):
value = str(value or "")
if not is_managed_media_url(value):
return None
return value.removeprefix("/media/")
def managed_media_url(kind, entry_id, filename):
return f"/media/{kind}/{entry_id}/{filename}"
def ensure_storage_files(storage):
storage.write_json(DATA_FILE, storage.read_json(DATA_FILE, tracker_default()))
storage.write_json(HASH_FILE, storage.read_json(HASH_FILE, hashes_default()))
storage.write_json(USER_FILE, storage.read_json(USER_FILE, users_default()))
def legacy_profile():
return {
"aliases": [],
"species": LEGACY_VALUE,
"age": LEGACY_VALUE,
"birthday_month": None,
"birthday_day": None,
"birthday_last_processed_year": None,
"gender": LEGACY_VALUE,
"pronouns": LEGACY_VALUE,
"reproductive_organ": LEGACY_VALUE,
"sexual_romantic_attraction": LEGACY_VALUE,
"relationship_style": LEGACY_VALUE,
"height": LEGACY_VALUE,
"occupations": [],
"affiliations": [],
"memory_tree": {"pre_systemhood": [], "current": []},
"notes": [],
"gallery": [],
"gallery_locked": False,
"profile_locked": False,
"relations_locked": False,
}
def legacy_document():
return {
"format": "markdown",
"content": "",
"tags": [],
"ties": {"alters": [], "locations": [], "affiliations": [], "documents": []},
"document_locked": False,
}
def legacy_affiliation():
return {
"summary": "",
"timeline": [],
"gallery": [],
"gallery_locked": False,
}
def legacy_wheel():
return {
"entries": [],
"permissions": {"view": [], "edit": []},
"options": {
"entry_deletion": 1,
"stop_repeat_entry": 0,
"repeat_exceptions": [],
},
"used_entries": [],
}
def load_users(storage):
data = storage.read_json(USER_FILE, users_default())
data.setdefault("users", [])
changed = False
admin_assigned = False
for user in data["users"]:
role = str(user.get("role", "user")).strip().lower() or "user"
if role == "admin":
if admin_assigned:
role = "mod"
changed = True
else:
admin_assigned = True
elif role not in {"mod", "user"}:
role = "user"
changed = True
user["role"] = role
if "level" in user:
user.pop("level", None)
changed = True
if "creation_permission" not in user:
user["creation_permission"] = role in {"admin", "mod"}
changed = True
if "memory_tree_permission" not in user:
user["memory_tree_permission"] = role == "admin"
changed = True
if "profile_permission" not in user:
user["profile_permission"] = role == "admin"
changed = True
if "relation_permission" not in user:
user["relation_permission"] = role == "admin"
changed = True
if "document_permission" not in user:
user["document_permission"] = role == "admin"
changed = True
if "locked_gallery_permission" not in user:
user["locked_gallery_permission"] = user.get("gallery_permission", role == "admin")
changed = True
if "gallery_permission" in user:
user.pop("gallery_permission", None)
changed = True
user.setdefault("active", True)
if user["role"] == "admin":
user["memory_tree_permission"] = True
user["profile_permission"] = True
user["relation_permission"] = True
user["document_permission"] = True
user["locked_gallery_permission"] = True
if user["role"] == "admin" and not user["creation_permission"]:
user["creation_permission"] = True
changed = True
if data["users"] and not admin_assigned:
data["users"][0]["role"] = "admin"
data["users"][0]["creation_permission"] = True
data["users"][0]["memory_tree_permission"] = True
data["users"][0]["profile_permission"] = True
data["users"][0]["relation_permission"] = True
data["users"][0]["document_permission"] = True
data["users"][0]["locked_gallery_permission"] = True
changed = True
if changed:
save_users(storage, data)
return data
def save_users(storage, data):
storage.write_json(USER_FILE, data)
def load_saved_hashes(storage):
return set(storage.read_json(HASH_FILE, hashes_default()).get("hashes", []))
def save_saved_hashes(storage, hashes):
storage.write_json(HASH_FILE, {"hashes": sorted(hashes)})
def normalize_status_entries(entries):
normalized = []
for item in entries or []:
value = str(item.get("value", "")).strip()
status = str(item.get("status", STATUS_OPTIONS[0])).strip()
if value:
normalized.append({"value": value, "status": status if status in STATUS_OPTIONS else STATUS_OPTIONS[0]})
return normalized
def normalize_memory_entries(entries):
normalized = []
for item in entries or []:
entry_id = str(item.get("id", "")).strip() or secrets.token_hex(8)
when = str(item.get("date", "")).strip()
text = str(item.get("text", "")).strip()
if when or text:
normalized.append({"id": entry_id, "date": when, "text": text})
return normalized
def normalize_notes(entries):
normalized = []
for item in entries or []:
entry_id = str(item.get("id", "")).strip() or secrets.token_hex(8)
text = str(item.get("text", "")).strip()
if text:
normalized.append({"id": entry_id, "text": text})
return normalized
def update_profile_birthday_age(profile):
month = profile.get("birthday_month")
day = profile.get("birthday_day")
age = profile.get("age")
if month is None or day is None or not isinstance(age, int):
return False
today = date.today()
last_processed = profile.get("birthday_last_processed_year")
if (today.month, today.day) >= (month, day) and last_processed != today.year:
profile["age"] = age + 1
profile["birthday_last_processed_year"] = today.year
return True
return False
def sync_saved_hashes_with_tracker(storage, data):
hashes = load_saved_hashes(storage)
hashes.update(data["alters"].keys())
hashes.update(data["locations"].keys())
hashes.update(data["affiliations"].keys())
hashes.update(data["documents"].keys())
hashes.update(data["wheels"].keys())
save_saved_hashes(storage, hashes)
return hashes
def load_data(storage):
data = storage.read_json(DATA_FILE, tracker_default())
data.setdefault("alters", {})
data.setdefault("locations", {})
data.setdefault("affiliations", {})
data.setdefault("documents", {})
data.setdefault("wheels", {})
data.setdefault("relations", [])
data.setdefault("location_bindings", {})
data.setdefault("last_modified", {"alters": {}, "locations": {}, "affiliations": {}, "documents": {}, "wheels": {}})
data.setdefault("relation_tags", list(DEFAULT_RELATION_TAGS))
data.setdefault("special_relation_tags", dict(DEFAULT_SPECIAL_RELATION_TAGS))
data.setdefault("alter_prefixes", list(DEFAULT_ALTER_PREFIXES))
data.setdefault("affiliation_prefixes", list(DEFAULT_AFFILIATION_PREFIXES))
data.setdefault("alter_profiles", {})
data.setdefault("location_galleries", {})
data.setdefault("location_gallery_locks", {})
data.setdefault("document_records", {})
data.setdefault("affiliation_records", {})
data.setdefault("wheel_records", {})
data["last_modified"].setdefault("alters", {})
data["last_modified"].setdefault("locations", {})
data["last_modified"].setdefault("affiliations", {})
data["last_modified"].setdefault("documents", {})
data["last_modified"].setdefault("wheels", {})
data["relation_tags"] = unique_items(
list(DEFAULT_RELATION_TAGS)
+ data["relation_tags"]
+ list(data["special_relation_tags"].keys())
+ list(data["special_relation_tags"].values())
)
data["alter_prefixes"] = unique_items(list(DEFAULT_ALTER_PREFIXES) + data["alter_prefixes"])
data["affiliation_prefixes"] = unique_items(data["affiliation_prefixes"])
changed = False
migrated_relations = []
for relation in data["relations"]:
if "source_id" in relation:
migrated_relations.append(
{
"source_id": relation["source_id"],
"target_id": relation["target_id"],
"tag": relation["tag"],
"reverse_tag": relation.get("reverse_tag", relation["tag"]),
"legacy_relation": relation.get("legacy_relation"),
}
)
elif "id_one" in relation:
changed = True
migrated_relations.append(
{
"source_id": relation["id_one"],
"target_id": relation["id_two"],
"tag": "NONE",
"reverse_tag": "NONE",
"legacy_relation": relation.get("relation", "NONE"),
}
)
data["relations"] = migrated_relations
data.pop("entry_levels", None)
for alter_id in data["alters"]:
if alter_id not in data["last_modified"]["alters"]:
data["last_modified"]["alters"][alter_id] = ""
changed = True
profile = data["alter_profiles"].setdefault(alter_id, legacy_profile())
for key, default_value in legacy_profile().items():
if key not in profile:
profile[key] = default_value
changed = True
if profile.get("birthday_day") is None:
legacy_day = profile.get("birthday_year")
if isinstance(legacy_day, int) and 1 <= legacy_day <= 31:
profile["birthday_day"] = legacy_day
else:
profile["birthday_day"] = None
changed = True
if "birthday_year" in profile:
profile.pop("birthday_year", None)
changed = True
profile["occupations"] = normalize_status_entries(profile.get("occupations"))
profile["affiliations"] = normalize_status_entries(profile.get("affiliations"))
memory_tree = profile.get("memory_tree", {})
profile["memory_tree"] = {
"pre_systemhood": normalize_memory_entries(memory_tree.get("pre_systemhood", [])),
"current": normalize_memory_entries(memory_tree.get("current", [])),
}
profile["notes"] = normalize_notes(profile.get("notes", []))
profile["gallery"] = [item for item in profile.get("gallery", []) if str(item).strip()]
profile["gallery_locked"] = bool(profile.get("gallery_locked", False))
profile["profile_locked"] = bool(profile.get("profile_locked", False))
profile["relations_locked"] = bool(profile.get("relations_locked", False))
if update_profile_birthday_age(profile):
changed = True
for location_id in data["locations"]:
if location_id not in data["last_modified"]["locations"]:
data["last_modified"]["locations"][location_id] = ""
changed = True
if location_id not in data["location_galleries"]:
data["location_galleries"][location_id] = []
changed = True
else:
data["location_galleries"][location_id] = [item for item in data["location_galleries"].get(location_id, []) if str(item).strip()]
if location_id not in data["location_gallery_locks"]:
data["location_gallery_locks"][location_id] = False
changed = True
else:
data["location_gallery_locks"][location_id] = bool(data["location_gallery_locks"].get(location_id, False))
for affiliation_id in data["affiliations"]:
if affiliation_id not in data["last_modified"]["affiliations"]:
data["last_modified"]["affiliations"][affiliation_id] = ""
changed = True
record = data["affiliation_records"].setdefault(affiliation_id, legacy_affiliation())
for key, default_value in legacy_affiliation().items():
if key not in record:
record[key] = default_value
changed = True
record["timeline"] = normalize_memory_entries(record.get("timeline", []))
record["gallery"] = [item for item in record.get("gallery", []) if str(item).strip()]
record["gallery_locked"] = bool(record.get("gallery_locked", False))
for document_id in data["documents"]:
if document_id not in data["last_modified"]["documents"]:
data["last_modified"]["documents"][document_id] = ""
changed = True
record = data["document_records"].setdefault(document_id, legacy_document())
for key, default_value in legacy_document().items():
if key not in record:
record[key] = default_value
changed = True
record["format"] = "html" if str(record.get("format", "markdown")).strip().lower() == "html" else "markdown"
record["content"] = str(record.get("content", ""))
record["tags"] = [item.strip() for item in record.get("tags", []) if str(item).strip()]
ties = record.get("ties", {})
normalized_ties = {
"alters": [item for item in ties.get("alters", []) if item in data["alters"]],
"locations": [item for item in ties.get("locations", []) if item in data["locations"]],
"affiliations": [item for item in ties.get("affiliations", []) if item in data["affiliations"]],
"documents": [item for item in ties.get("documents", []) if item in data["documents"] and item != document_id],
}
if normalized_ties != ties:
changed = True
record["ties"] = normalized_ties
record["document_locked"] = bool(record.get("document_locked", False))
for wheel_id in data["wheels"]:
if wheel_id not in data["last_modified"]["wheels"]:
data["last_modified"]["wheels"][wheel_id] = ""
changed = True
record = data["wheel_records"].setdefault(wheel_id, legacy_wheel())
permissions = record.get("permissions", {})
record["permissions"] = {
"view": [str(item) for item in permissions.get("view", []) if str(item).strip()],
"edit": [str(item) for item in permissions.get("edit", []) if str(item).strip()],
}
options = record.get("options", {})
record["options"] = {
"entry_deletion": 2 if int(options.get("entry_deletion", 1)) == 2 else (0 if int(options.get("entry_deletion", 1)) == 0 else 1),
"stop_repeat_entry": 1 if int(options.get("stop_repeat_entry", 0)) == 1 else 0,
"repeat_exceptions": [str(item).strip() for item in options.get("repeat_exceptions", []) if str(item).strip()],
}
record["used_entries"] = [str(item) for item in record.get("used_entries", []) if str(item).strip()]
normalized_entries = []
for entry in record.get("entries", []):
entry_id = str(entry.get("id", "")).strip() or secrets.token_hex(8)
kind = "image" if str(entry.get("kind", "text")).strip().lower() == "image" else "text"
text = str(entry.get("text", "") or "")
media_url = str(entry.get("media_url", "") or "")
label = str(entry.get("label", "") or "")
if kind == "text" and not text.strip():
continue
if kind == "image" and not media_url.strip():
continue
normalized_entries.append({"id": entry_id, "kind": kind, "text": text, "media_url": media_url, "label": label})
record["entries"] = normalized_entries
if changed:
save_data(storage, data)
sync_saved_hashes_with_tracker(storage, data)
return data
def save_data(storage, data):
storage.write_json(DATA_FILE, data)
def get_synced_hashes(storage):
return sync_saved_hashes_with_tracker(storage, load_data(storage))
def generate_hash(prefix=""):
return prefix + "".join(secrets.choice(ALPHABET) for _ in range(HASH_LENGTH))
def generate_unique_hash(storage, prefix=""):
hashes = get_synced_hashes(storage)
while True:
candidate = generate_hash(prefix)
if candidate not in hashes:
hashes.add(candidate)
save_saved_hashes(storage, hashes)
return candidate
def export_hashes(storage, filename):
filename = filename.strip()
if not filename:
return False, "Specify a filename."
try:
with Path(filename).open("w", encoding="utf-8") as file:
for item in sorted(get_synced_hashes(storage)):
file.write(item + "\n")
except OSError as error:
return False, f"Failed to export hashes: {error}"
return True, f"Exported hashes to {filename}"
def clear_hashes(storage):
save_saved_hashes(storage, set())
hashes = get_synced_hashes(storage)
return True, f"Cleared unassigned hashes. Reserved hashes still attached: {len(hashes)}"
def get_counts(data):
return {
"alters": len(data["alters"]),
"locations": len(data["locations"]),
"affiliations": len(data["affiliations"]),
"relations": len(data["relations"]),
"bindings": len(data["location_bindings"]),
"tags": len(get_available_relation_tags(data)),
}
def get_alter_prefixes(data):
return data["alter_prefixes"]
def get_affiliation_prefixes(data):
return data["affiliation_prefixes"]
def touch_entry(data, bucket_name, entry_id):
data.setdefault("last_modified", {"alters": {}, "locations": {}, "affiliations": {}})
data["last_modified"].setdefault(bucket_name, {})
data["last_modified"][bucket_name][entry_id] = datetime.now(timezone.utc).isoformat()
def parse_timestamp(value):
if not value:
return datetime.fromtimestamp(0, tz=timezone.utc)
try:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return datetime.fromtimestamp(0, tz=timezone.utc)
def create_entry(storage, bucket_name, entity_label, name, entry_id):
return create_entry_with_level(storage, bucket_name, entity_label, name, entry_id, None)
def create_entry_with_level(storage, bucket_name, entity_label, name, entry_id, level):
data = load_data(storage)
name = name.strip()
entry_id = entry_id.strip()
if not name:
return False, f"{entity_label.title()} name is required."
if entry_id in data[bucket_name]:
return False, f'ID "{entry_id}" already exists.'
data[bucket_name][entry_id] = name
touch_entry(data, bucket_name, entry_id)
if bucket_name == "alters":
data["alter_profiles"].setdefault(entry_id, legacy_profile())
elif bucket_name == "locations":
data["location_galleries"].setdefault(entry_id, [])
data.setdefault("location_gallery_locks", {})[entry_id] = False
elif bucket_name == "documents":
data["document_records"].setdefault(entry_id, legacy_document())
elif bucket_name == "affiliations":
data["affiliation_records"].setdefault(entry_id, legacy_affiliation())
elif bucket_name == "wheels":
try:
default_wheel = legacy_wheel()
except NameError:
default_wheel = {
"entries": [],
"permissions": {"view": [], "edit": []},
"options": {"entry_deletion": 1, "stop_repeat_entry": 0, "repeat_exceptions": []},
"used_entries": [],
}
data["wheel_records"].setdefault(entry_id, default_wheel)
save_data(storage, data)
sync_saved_hashes_with_tracker(storage, data)
return True, f"Created {entity_label}: {name} ({entry_id})"
def user_can_create(user):
return bool(user and (user.get("role") == "admin" or user.get("creation_permission")))
def user_can_view_memory(user):
return bool(user and (user.get("role") == "admin" or user.get("memory_tree_permission")))
def user_can_view_profile(user):
return bool(user and (user.get("role") == "admin" or user.get("profile_permission")))
def user_can_view_relations(user):
return bool(user and (user.get("role") == "admin" or user.get("relation_permission")))
def user_can_view_documents(user):
return bool(user and (user.get("role") == "admin" or user.get("document_permission")))
def user_can_view_gallery(user):
return bool(user)
def user_can_view_locked_gallery(user):
return bool(user and (user.get("role") == "admin" or user.get("locked_gallery_permission")))
def is_gallery_locked(data, kind, entry_id):
if kind == "alter":
return bool(data["alter_profiles"].get(entry_id, {}).get("gallery_locked", False))
if kind == "location":
return bool(data.get("location_gallery_locks", {}).get(entry_id, False))
if kind == "affiliation":
return bool(data["affiliation_records"].get(entry_id, {}).get("gallery_locked", False))
return False
def can_view_gallery_for_entry(data, user, kind, entry_id):
if not user:
return False
if not is_gallery_locked(data, kind, entry_id):
return True
return user_can_view_locked_gallery(user)
def is_profile_locked(data, alter_id):
return bool(data["alter_profiles"].get(alter_id, {}).get("profile_locked", False))
def is_relations_locked(data, alter_id):
return bool(data["alter_profiles"].get(alter_id, {}).get("relations_locked", False))
def can_view_profile_for_entry(data, user, alter_id):
if not user:
return False
if not is_profile_locked(data, alter_id):
return True
return user_can_view_profile(user)
def can_view_relations_for_entry(data, user, alter_id):
if not user:
return False
if not is_relations_locked(data, alter_id):
return True
return user_can_view_relations(user)
def is_document_locked(data, document_id):
return bool(data["document_records"].get(document_id, {}).get("document_locked", False))
def can_view_document_for_entry(data, user, document_id):
if not user:
return False
if not is_document_locked(data, document_id):
return True
return user_can_view_documents(user)
def user_can_view_wheel(wheel_record, user):
if not user or not wheel_record:
return False
if user.get("role") == "admin":
return True
user_id = str(user.get("id", "")).strip()
permissions = wheel_record.get("permissions", {})
return user_id in permissions.get("view", []) or user_id in permissions.get("edit", [])
def user_can_edit_wheel(wheel_record, user):
if not user or not wheel_record:
return False
if user.get("role") == "admin":
return True
user_id = str(user.get("id", "")).strip()
return user_id in wheel_record.get("permissions", {}).get("edit", [])
def entry_is_accessible(data, kind, entry_id, user_level=None):
bucket_map = {"alter": "alters", "location": "locations", "affiliation": "affiliations", "document": "documents", "wheel": "wheels"}
bucket_name = bucket_map[kind]
return entry_id in data[bucket_name]
def visible_entries(data, kind, user_level=None):
bucket_map = {"alter": "alters", "location": "locations", "affiliation": "affiliations", "document": "documents", "wheel": "wheels"}
bucket_name = bucket_map[kind]
return [
(entry_id, name)
for entry_id, name in data[bucket_name].items()
if entry_is_accessible(data, kind, entry_id, user_level)
]
def resolve_entry_reference(data, kind, raw_value, user_level=4):
raw_value = str(raw_value or "").strip()
if not raw_value: