-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1534 lines (1361 loc) · 63.2 KB
/
Copy pathapp.py
File metadata and controls
1534 lines (1361 loc) · 63.2 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 mimetypes
import os
import logging
import json
import threading
import time
import uuid
import zipfile
from pathlib import Path
from flask import Flask, Response, flash, g, has_request_context, jsonify, redirect, render_template, request, session, url_for
from markupsafe import Markup, escape
from werkzeug.security import check_password_hash, generate_password_hash
from werkzeug.utils import secure_filename
try:
import markdown as markdown_lib
except ImportError: # pragma: no cover
markdown_lib = None
from tracker_core import (
DATA_FILE,
DOCUMENT_PREFIX,
GENDER_OPTIONS,
HASH_FILE,
LEGACY_VALUE,
LOCATION_PREFIX,
MONTH_OPTIONS,
ORGAN_OPTIONS,
RELATIONSHIP_STYLE_OPTIONS,
STATUS_OPTIONS,
SITE_SETTINGS_FILE,
StorageError,
STORAGE_SETTINGS_FILE,
USER_FILE,
WHEEL_PREFIX,
add_gallery_item,
bind_location,
build_alter_view,
build_affiliation_view,
build_dashboard_context,
build_document_view,
build_location_view,
build_wheel_view,
build_wheels_context,
can_view_document_for_entry,
can_view_gallery_for_entry,
can_view_profile_for_entry,
can_view_relations_for_entry,
create_entry_with_level,
create_affiliation_prefix,
create_alter_prefix,
create_relation_tag,
create_special_relation_tag,
delete_entry,
delete_affiliation_prefix,
delete_alter_prefix,
entry_is_accessible,
ensure_storage_files,
generate_unique_hash,
get_affiliation_prefixes,
get_alter_prefixes,
get_storage,
import_gallery_media_from_url,
is_managed_media_url,
load_data,
load_site_settings,
load_storage_settings,
load_users,
LocalStorage,
media_name_from_url,
media_storage_name,
managed_media_url,
migrate_storage_data,
migrate_gallery_media,
migrate_legacy_local_files,
remove_affiliation_membership,
remove_affiliation_timeline_entry,
remove_gallery_item,
remove_memory_entry,
remove_note_entry,
remove_occupation_entry,
remove_relation,
resolve_entry_reference,
rename_entry,
save_alter_profile,
save_affiliation_summary,
save_document_record,
save_site_settings,
save_storage_settings,
save_uploaded_json,
save_users,
search_entries,
set_document_locked,
set_alter_section_lock,
set_gallery_locked,
set_relation_tag,
update_memory_tree,
update_notes,
update_affiliation_membership,
update_affiliation_timeline,
update_occupation_entry,
user_can_create,
user_can_view_gallery,
user_can_view_documents,
user_can_view_locked_gallery,
user_can_view_memory,
user_can_view_profile,
user_can_view_relations,
user_can_view_wheel,
user_can_edit_wheel,
save_wheel_settings,
save_wheel_permissions,
add_wheel_text_entries,
add_wheel_image_entry,
remove_wheel_entry,
clear_wheel_used_entries,
spin_wheel,
)
APP_DIR = Path(__file__).resolve().parent
DATA_DIR = Path(os.getenv("DATA_DIR", str(APP_DIR / "data"))).resolve()
DATA_DIR.mkdir(parents=True, exist_ok=True)
IMPORT_JOB_DIR = DATA_DIR / "import_jobs"
IMPORT_JOB_DIR.mkdir(parents=True, exist_ok=True)
migrate_legacy_local_files(APP_DIR, DATA_DIR)
app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY", "change-me-for-production")
logger = logging.getLogger(__name__)
def render_document_content(document_format, content):
content = str(content or "")
if document_format == "html":
return Markup(content)
if markdown_lib is not None:
return Markup(markdown_lib.markdown(content, extensions=["extra", "sane_lists"]))
return Markup(f"<pre>{escape(content)}</pre>")
def initialize_storage():
try:
current_storage = get_storage(DATA_DIR)
ensure_storage_files(current_storage)
migrate_gallery_media(current_storage, DATA_DIR)
return current_storage
except Exception as error:
logger.exception("Storage initialization failed")
raise RuntimeError(f"Storage initialization failed: {error}") from error
storage = initialize_storage()
@app.errorhandler(StorageError)
def handle_storage_error(error):
clear_request_caches()
message = str(error) or "Storage is unavailable right now."
if is_async_request():
return jsonify({"ok": False, "message": message, "category": "error"}), 503
flash(message, "error")
return redirect(request.referrer or url_for("dashboard"))
def refresh_storage():
global storage
storage = initialize_storage()
return storage
def save_gallery_upload(kind, entry_id, file_storage):
if not file_storage or not file_storage.filename:
return ""
suffix = Path(secure_filename(file_storage.filename)).suffix.lower()
if suffix not in {".jpg", ".jpeg", ".png", ".gif", ".webp"}:
raise ValueError("Uploads must be JPG, PNG, GIF, or WEBP.")
filename = f"{os.urandom(12).hex()}{suffix}"
storage.write_bytes(media_storage_name(kind, entry_id, filename), file_storage.read())
return managed_media_url(kind, entry_id, filename)
def delete_gallery_upload(image_url):
media_name = media_name_from_url(image_url)
if not media_name:
return
storage.delete_bytes(media_name)
def delete_wheel_media(entry):
media_name = media_name_from_url(entry.get("media_url", ""))
if media_name:
storage.delete_bytes(media_name)
def import_job_status_path(job_id):
return IMPORT_JOB_DIR / f"{job_id}.json"
def import_job_upload_path(job_id, suffix):
return IMPORT_JOB_DIR / f"{job_id}{suffix}"
def write_import_job_status(job_id, payload):
path = import_job_status_path(job_id)
path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
def read_import_job_status(job_id):
path = import_job_status_path(job_id)
if not path.exists():
return None
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return None
def delete_import_job_files(job_id, upload_path=None):
status_path = import_job_status_path(job_id)
try:
if upload_path and Path(upload_path).exists():
Path(upload_path).unlink()
except OSError:
pass
try:
if status_path.exists():
status_path.unlink()
except OSError:
pass
def import_wheel_upload(wheel_id, file_storage):
if not file_storage or not file_storage.filename:
return False, "Choose a .zip or .txt file.", 0
suffix = Path(secure_filename(file_storage.filename)).suffix.lower()
if suffix == ".txt":
file_storage.stream.seek(0)
lines = file_storage.stream.read().decode("utf-8", errors="replace").splitlines()
return (*add_wheel_text_entries(storage, wheel_id, lines), len([line for line in lines if line.strip() and not line.strip().startswith("#")]))
if suffix != ".zip":
return False, "Imports must be .zip or .txt.", 0
added = 0
try:
file_storage.stream.seek(0)
with zipfile.ZipFile(file_storage.stream) as archive:
for member in archive.infolist():
if member.is_dir():
continue
member_name = Path(member.filename).name
lower = member_name.lower()
if lower.endswith((".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tif", ".tiff")):
content = archive.read(member)
success, _ = add_wheel_image_entry(storage, wheel_id, member_name, content)
if success:
added += 1
elif lower.endswith(".txt"):
with archive.open(member) as text_file:
lines = text_file.read().decode("utf-8", errors="replace").splitlines()
success, message = add_wheel_text_entries(storage, wheel_id, lines)
if success:
added += len([line for line in lines if line.strip() and not line.strip().startswith("#")])
if added:
return True, f"Imported {added} wheel entr{'y' if added == 1 else 'ies'}.", added
return False, "No usable image or text entries were found in that zip.", 0
except zipfile.BadZipFile:
return False, "That zip file could not be read.", 0
def process_wheel_import_job(job_id, wheel_id, upload_path):
status = read_import_job_status(job_id)
if not status:
return
suffix = Path(upload_path).suffix.lower()
try:
status["state"] = "processing"
status["message"] = "Importing entries..."
write_import_job_status(job_id, status)
added = 0
if suffix == ".txt":
lines = Path(upload_path).read_text(encoding="utf-8", errors="replace").splitlines()
valid_lines = [line for line in lines if line.strip() and not line.strip().startswith("#")]
status["total"] = len(valid_lines)
status["processed"] = 0
write_import_job_status(job_id, status)
success, message = add_wheel_text_entries(storage, wheel_id, lines)
status["processed"] = len(valid_lines)
status["added"] = len(valid_lines) if success else 0
status["state"] = "complete" if success else "error"
status["message"] = message
write_import_job_status(job_id, status)
return
with zipfile.ZipFile(upload_path) as archive:
members = [member for member in archive.infolist() if not member.is_dir()]
usable = []
for member in members:
lower = Path(member.filename).name.lower()
if lower.endswith((".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tif", ".tiff", ".txt")):
usable.append(member)
status["total"] = len(usable)
status["processed"] = 0
status["added"] = 0
write_import_job_status(job_id, status)
for member in usable:
member_name = Path(member.filename).name
lower = member_name.lower()
if lower.endswith((".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tif", ".tiff")):
with archive.open(member) as image_file:
content = image_file.read()
success, _ = add_wheel_image_entry(storage, wheel_id, member_name, content)
if success:
added += 1
elif lower.endswith(".txt"):
with archive.open(member) as text_file:
lines = text_file.read().decode("utf-8", errors="replace").splitlines()
success, _ = add_wheel_text_entries(storage, wheel_id, lines)
if success:
added += len([line for line in lines if line.strip() and not line.strip().startswith("#")])
status["processed"] += 1
status["added"] = added
status["message"] = f"Processed {status['processed']} of {status['total']} files."
write_import_job_status(job_id, status)
if added:
status["state"] = "complete"
status["message"] = f"Imported {added} wheel entr{'y' if added == 1 else 'ies'}."
status["added"] = added
else:
status["state"] = "error"
status["message"] = "No usable image or text entries were found in that zip."
write_import_job_status(job_id, status)
except zipfile.BadZipFile:
status["state"] = "error"
status["message"] = "That zip file could not be read."
write_import_job_status(job_id, status)
except StorageError as error:
status["state"] = "error"
status["message"] = str(error) or "Storage is unavailable right now."
write_import_job_status(job_id, status)
except Exception as error: # pragma: no cover
logger.exception("Wheel import job failed")
status["state"] = "error"
status["message"] = f"Import failed: {error}"
write_import_job_status(job_id, status)
finally:
clear_request_caches()
try:
Path(upload_path).unlink(missing_ok=True)
except OSError:
pass
def start_wheel_import_job(wheel_id, file_storage, user):
if not file_storage or not file_storage.filename:
return False, {"message": "Choose a .zip or .txt file."}
suffix = Path(secure_filename(file_storage.filename)).suffix.lower()
if suffix not in {".zip", ".txt"}:
return False, {"message": "Imports must be .zip or .txt."}
job_id = uuid.uuid4().hex
upload_path = import_job_upload_path(job_id, suffix)
file_storage.save(upload_path)
payload = {
"job_id": job_id,
"wheel_id": wheel_id,
"filename": secure_filename(file_storage.filename),
"state": "queued",
"message": "Upload received. Preparing import...",
"processed": 0,
"total": 0,
"added": 0,
"created_at": int(time.time()),
"created_by": user["id"] if user else "",
}
write_import_job_status(job_id, payload)
thread = threading.Thread(target=process_wheel_import_job, args=(job_id, wheel_id, str(upload_path)), daemon=True)
thread.start()
return True, payload
def get_users_data():
if has_request_context():
if not hasattr(g, "users_data_cache"):
g.users_data_cache = load_users(storage)
return g.users_data_cache
return load_users(storage)
def get_tracker_data():
if has_request_context():
if not hasattr(g, "tracker_data_cache"):
g.tracker_data_cache = load_data(storage)
return g.tracker_data_cache
return load_data(storage)
def get_storage_settings_data():
if has_request_context():
if not hasattr(g, "storage_settings_cache"):
g.storage_settings_cache = load_storage_settings(DATA_DIR)
return g.storage_settings_cache
return load_storage_settings(DATA_DIR)
def get_site_settings_data():
if has_request_context():
if not hasattr(g, "site_settings_cache"):
g.site_settings_cache = load_site_settings(DATA_DIR)
return g.site_settings_cache
return load_site_settings(DATA_DIR)
def clear_request_caches():
if has_request_context():
for attr in ("users_data_cache", "tracker_data_cache", "storage_settings_cache", "site_settings_cache", "current_user_cache"):
if hasattr(g, attr):
delattr(g, attr)
def is_async_request():
return request.headers.get("X-Requested-With") == "XMLHttpRequest"
def current_user():
if has_request_context() and hasattr(g, "current_user_cache"):
return g.current_user_cache
user_id = session.get("user_id")
if not user_id:
if has_request_context():
g.current_user_cache = None
return None
for user in get_users_data()["users"]:
if user["id"] == user_id and user.get("active", True):
if has_request_context():
g.current_user_cache = user
return user
if has_request_context():
g.current_user_cache = None
return None
def current_user_level():
return 0
def can_manage_tracker():
return user_can_create(current_user())
def login_required(view):
def wrapped(*args, **kwargs):
if not current_user():
flash("Please log in first.", "error")
return redirect(url_for("login"))
return view(*args, **kwargs)
wrapped.__name__ = view.__name__
return wrapped
def roles_required(*roles):
def decorator(view):
def wrapped(*args, **kwargs):
user = current_user()
if not user or user["role"] not in roles:
flash("You do not have access to that page.", "error")
return redirect(url_for("dashboard"))
return view(*args, **kwargs)
wrapped.__name__ = view.__name__
return wrapped
return decorator
def tracker_write_required(view):
def wrapped(*args, **kwargs):
if not can_manage_tracker():
flash("You do not have creation permission.", "error")
return redirect(url_for("dashboard"))
return view(*args, **kwargs)
wrapped.__name__ = view.__name__
return wrapped
@app.context_processor
def inject_globals():
user = current_user()
storage_settings = get_storage_settings_data()
site_settings = get_site_settings_data()
favicon_name = site_settings.get("favicon_name", "").strip()
return {
"current_user": user,
"current_role": user["role"] if user else None,
"can_manage_tracker": can_manage_tracker(),
"can_create_records": can_manage_tracker(),
"can_view_memory": user_can_view_memory(user),
"can_view_documents": user_can_view_documents(user),
"can_view_profile": user_can_view_profile(user),
"can_view_relations": user_can_view_relations(user),
"can_view_gallery": user_can_view_gallery(user),
"can_view_locked_gallery": user_can_view_locked_gallery(user),
"status_options": STATUS_OPTIONS,
"month_options": MONTH_OPTIONS,
"gender_options": GENDER_OPTIONS,
"organ_options": ORGAN_OPTIONS,
"relationship_style_options": RELATIONSHIP_STYLE_OPTIONS,
"legacy_value": LEGACY_VALUE,
"storage_settings": storage_settings,
"site_settings": site_settings,
"site_name": site_settings.get("site_name", "United Front Technical Database"),
"favicon_url": url_for("site_favicon", v=favicon_name) if favicon_name else "",
"data_dir": str(DATA_DIR),
}
@app.route("/")
def index():
return redirect(url_for("dashboard" if current_user() else "login"))
@app.route("/media/<kind>/<entry_id>/<path:filename>")
@login_required
def media_file(kind, entry_id, filename):
if kind not in {"alter", "location", "affiliation", "wheel"}:
flash("Unknown media type.", "error")
return redirect(url_for("dashboard"))
data = get_tracker_data()
if kind == "wheel":
if not user_can_view_wheel(data.get("wheel_records", {}).get(entry_id), current_user()):
flash("You do not have access to that wheel media.", "error")
return redirect(url_for("wheels"))
else:
if not can_view_gallery_for_entry(data, current_user(), kind, entry_id):
flash("You do not have permission to view that locked gallery.", "error")
return redirect(url_for("dashboard"))
if not entry_is_accessible(data, kind, entry_id, current_user_level()):
flash("You do not have access to that media.", "error")
return redirect(url_for("dashboard"))
media_name = media_storage_name(kind, entry_id, filename)
if os.getenv("MEDIA_REDIRECTS", "").strip().lower() in {"1", "true", "yes", "on"}:
download_url = storage.get_download_url(media_name, expires_in=300)
if download_url:
return redirect(download_url)
payload = storage.read_bytes(media_name)
if payload is None:
flash("Media file not found.", "error")
return redirect(url_for("dashboard"))
return Response(payload, mimetype=Path(filename).suffix and ({".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp"}.get(Path(filename).suffix.lower(), "application/octet-stream")) or "application/octet-stream")
@app.route("/favicon.ico")
def site_favicon():
settings = get_site_settings_data()
favicon_name = settings.get("favicon_name", "").strip()
if not favicon_name:
return ("", 204)
path = DATA_DIR / "branding" / favicon_name
if not path.exists():
return ("", 204)
return Response(path.read_bytes(), mimetype=mimetypes.guess_type(path.name)[0] or "image/x-icon")
@app.route("/admin")
@login_required
@roles_required("admin")
def admin_options():
return render_template("admin_options.html")
@app.route("/admin/branding", methods=["GET", "POST"])
@login_required
@roles_required("admin")
def admin_branding():
settings = get_site_settings_data()
if request.method == "POST":
updated = {
"site_name": request.form.get("site_name", "").strip() or settings.get("site_name", "United Front Technical Database"),
"favicon_name": settings.get("favicon_name", ""),
}
favicon = request.files.get("favicon_file")
if favicon and favicon.filename:
suffix = Path(secure_filename(favicon.filename)).suffix.lower()
if suffix not in {".ico", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"}:
flash("Favicon must be ICO, PNG, JPG, GIF, WEBP, or SVG.", "error")
return redirect(url_for("admin_branding"))
branding_dir = DATA_DIR / "branding"
branding_dir.mkdir(parents=True, exist_ok=True)
if updated["favicon_name"]:
old_path = branding_dir / updated["favicon_name"]
if old_path.exists():
old_path.unlink()
filename = f"favicon-{os.urandom(8).hex()}{suffix}"
(branding_dir / filename).write_bytes(favicon.read())
updated["favicon_name"] = filename
save_site_settings(DATA_DIR, updated)
clear_request_caches()
flash("Branding updated.", "success")
return redirect(url_for("admin_branding"))
return render_template("admin_branding.html", settings=settings)
@app.route("/admin/entries", methods=["GET", "POST"])
@login_required
@roles_required("admin")
def admin_entries():
if request.method == "POST":
kind = request.form.get("kind", "")
entry_id = request.form.get("entry_id", "").strip()
query = request.form.get("q", "").strip()
data = get_tracker_data()
gallery_urls = []
if kind == "alter":
gallery_urls = list(data.get("alter_profiles", {}).get(entry_id, {}).get("gallery", []))
elif kind == "location":
gallery_urls = list(data.get("location_galleries", {}).get(entry_id, []))
elif kind == "affiliation":
gallery_urls = list(data.get("affiliation_records", {}).get(entry_id, {}).get("gallery", []))
elif kind == "wheel":
gallery_urls = [item.get("media_url", "") for item in data.get("wheel_records", {}).get(entry_id, {}).get("entries", []) if item.get("kind") == "image"]
success, message = delete_entry(storage, kind, entry_id)
if success:
for image_url in gallery_urls:
delete_gallery_upload(image_url)
clear_request_caches()
flash(message, "success" if success else "error")
return redirect(url_for("admin_entries", kind=kind or "alter", q=query))
kind = request.args.get("kind", "alter")
query = request.args.get("q", "").strip()
results = search_entries(get_tracker_data(), kind, query, 4)
return render_template("admin_entries.html", kind=kind, query=query, results=results)
@app.route("/register", methods=["GET", "POST"])
def register():
users_data = get_users_data()
if request.method == "POST":
username = request.form.get("username", "").strip()
password = request.form.get("password", "")
if not username or not password:
flash("Username and password are required.", "error")
return redirect(url_for("register"))
if any(user["username"].lower() == username.lower() for user in users_data["users"]):
flash("That username already exists.", "error")
return redirect(url_for("register"))
role = "admin" if not users_data["users"] else "user"
user = {
"id": os.urandom(12).hex(),
"username": username,
"password_hash": generate_password_hash(password),
"role": role,
"creation_permission": role == "admin",
"memory_tree_permission": role == "admin",
"profile_permission": role == "admin",
"relation_permission": role == "admin",
"document_permission": role == "admin",
"locked_gallery_permission": role == "admin",
"active": True,
}
users_data["users"].append(user)
save_users(storage, users_data)
clear_request_caches()
session["user_id"] = user["id"]
flash(f"Account created. Logged in as {role}.", "success")
return redirect(url_for("dashboard"))
return render_template("register.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
username = request.form.get("username", "").strip()
password = request.form.get("password", "")
for user in get_users_data()["users"]:
if user["username"].lower() == username.lower() and user.get("active", True):
if check_password_hash(user["password_hash"], password):
session["user_id"] = user["id"]
flash("Logged in successfully.", "success")
return redirect(url_for("dashboard"))
flash("Invalid username or password.", "error")
return redirect(url_for("login"))
return render_template("login.html")
@app.route("/logout")
@login_required
def logout():
session.clear()
flash("Logged out.", "success")
return redirect(url_for("login"))
@app.route("/dashboard")
@login_required
def dashboard():
data = get_tracker_data()
context = build_dashboard_context(data, current_user_level())
return render_template(
"dashboard.html",
counts={
"alters": len(context["alters"]),
"locations": len(context["locations"]),
"affiliations": len(context["affiliations"]),
"documents": len(context["documents"]),
"relations": len(context["relations"]),
"tags": len(context["tags"]),
},
context=context,
alter_prefixes=get_alter_prefixes(data),
affiliation_prefixes=get_affiliation_prefixes(data),
)
@app.route("/generate-id/<kind>", methods=["POST"])
@login_required
@tracker_write_required
def generate_id(kind):
data = get_tracker_data()
prefix = request.form.get("prefix", "")
if kind == "alter":
if prefix and prefix not in get_alter_prefixes(data):
if is_async_request():
return jsonify({"ok": False, "message": "Unknown alter prefix.", "category": "error"}), 400
flash("Unknown alter prefix.", "error")
return redirect(url_for("dashboard"))
elif kind == "location":
prefix = LOCATION_PREFIX if prefix != "" else ""
elif kind == "affiliation":
if prefix and prefix not in get_affiliation_prefixes(data):
if is_async_request():
return jsonify({"ok": False, "message": "Unknown affiliation prefix.", "category": "error"}), 400
flash("Unknown affiliation prefix.", "error")
return redirect(url_for("dashboard"))
elif kind == "document":
prefix = DOCUMENT_PREFIX if prefix != "" else ""
elif kind == "wheel":
prefix = WHEEL_PREFIX if prefix != "" else ""
else:
if is_async_request():
return jsonify({"ok": False, "message": "Unknown ID type.", "category": "error"}), 400
flash("Unknown ID type.", "error")
return redirect(url_for("dashboard"))
generated_id = generate_unique_hash(storage, prefix)
if is_async_request():
return jsonify({"ok": True, "message": f"Generated ID: {generated_id}", "category": "success", "generated_id": generated_id})
flash(f"Generated ID: {generated_id}", "success")
return redirect(url_for("dashboard"))
@app.route("/create/<kind>", methods=["POST"])
@login_required
@tracker_write_required
def create_record(kind):
data = get_tracker_data()
name = request.form.get("name", "")
entry_id = request.form.get("entry_id", "").strip()
if kind == "alter" and not entry_id:
entry_id = generate_unique_hash(storage, data["alter_prefixes"][0])
elif kind == "location" and not entry_id:
entry_id = generate_unique_hash(storage, LOCATION_PREFIX)
elif kind == "affiliation" and not entry_id:
entry_id = generate_unique_hash(storage, data["affiliation_prefixes"][0] if data["affiliation_prefixes"] else "")
elif kind == "document" and not entry_id:
entry_id = generate_unique_hash(storage, DOCUMENT_PREFIX)
elif kind == "wheel" and not entry_id:
entry_id = generate_unique_hash(storage, WHEEL_PREFIX)
bucket_map = {"alter": ("alters", "alter"), "location": ("locations", "location"), "affiliation": ("affiliations", "affiliation"), "document": ("documents", "document"), "wheel": ("wheels", "wheel")}
success, message = create_entry_with_level(storage, bucket_map[kind][0], bucket_map[kind][1], name, entry_id, None)
if success and kind == "document":
save_document_record(storage, entry_id, request.form)
flash(message, "success" if success else "error")
return redirect(url_for("dashboard"))
@app.route("/prefix/<kind>", methods=["POST"])
@login_required
@tracker_write_required
def add_prefix(kind):
if kind == "alter":
success, message = create_alter_prefix(storage, request.form.get("prefix", ""))
else:
success, message = create_affiliation_prefix(storage, request.form.get("prefix", ""))
flash(message, "success" if success else "error")
return redirect(url_for("dashboard"))
@app.route("/prefix/<kind>/delete", methods=["POST"])
@login_required
@roles_required("admin")
def remove_prefix(kind):
prefix = request.form.get("prefix", "")
if kind == "alter":
success, message = delete_alter_prefix(storage, prefix)
else:
success, message = delete_affiliation_prefix(storage, prefix)
flash(message, "success" if success else "error")
return redirect(url_for("dashboard"))
@app.route("/tags/standard", methods=["POST"])
@login_required
@tracker_write_required
def add_standard_tag():
success, message = create_relation_tag(storage, request.form.get("tag_name", ""))
flash(message, "success" if success else "error")
return redirect(url_for("dashboard"))
@app.route("/tags/special", methods=["POST"])
@login_required
@tracker_write_required
def add_special_tag():
success, message = create_special_relation_tag(storage, request.form.get("forward_tag", ""), request.form.get("reverse_tag", ""))
flash(message, "success" if success else "error")
return redirect(url_for("dashboard"))
@app.route("/search")
@login_required
def search():
query = request.args.get("q", "")
data = get_tracker_data()
grouped_results = {
"alters": search_entries(data, "alter", query, current_user_level()),
"locations": search_entries(data, "location", query, current_user_level()),
"affiliations": search_entries(data, "affiliation", query, current_user_level()),
"documents": search_entries(data, "document", query, current_user_level()),
}
total_results = sum(len(items) for items in grouped_results.values())
return render_template("search_results.html", query=query, grouped_results=grouped_results, total_results=total_results)
@app.route("/wheels")
@login_required
def wheels():
data = get_tracker_data()
return render_template("wheels.html", wheels=build_wheels_context(data, current_user()))
@app.route("/wheels/create", methods=["POST"])
@login_required
@roles_required("admin")
def create_wheel_route():
name = request.form.get("name", "")
entry_id = request.form.get("entry_id", "").strip() or generate_unique_hash(storage, WHEEL_PREFIX)
success, message = create_entry_with_level(storage, "wheels", "wheel", name, entry_id, None)
flash(message, "success" if success else "error")
return redirect(url_for("wheels"))
@app.route("/wheel/<wheel_id>", methods=["GET", "POST"])
@login_required
def wheel_detail(wheel_id):
data = get_tracker_data()
view = build_wheel_view(data, wheel_id, current_user(), get_users_data())
if not view:
flash("Unknown or inaccessible wheel.", "error")
return redirect(url_for("wheels"))
return render_template("wheel_detail.html", view=view, spin_result=None)
@app.route("/wheel/<wheel_id>/spin", methods=["POST"])
@login_required
def spin_wheel_route(wheel_id):
data = get_tracker_data()
record = data.get("wheel_records", {}).get(wheel_id)
if not user_can_view_wheel(record, current_user()):
flash("You do not have access to that wheel.", "error")
return redirect(url_for("wheels"))
success, message, result = spin_wheel(storage, wheel_id)
clear_request_caches()
data = get_tracker_data()
view = build_wheel_view(data, wheel_id, current_user(), get_users_data())
if not success or not view:
flash(message, "error")
return redirect(url_for("wheels"))
return render_template("wheel_detail.html", view=view, spin_result=result)
@app.route("/wheel/<wheel_id>/settings", methods=["POST"])
@login_required
@roles_required("admin")
def update_wheel_settings(wheel_id):
if not entry_is_accessible(get_tracker_data(), "wheel", wheel_id, current_user_level()):
flash("Unknown wheel.", "error")
return redirect(url_for("wheels"))
repeat_exceptions = [item.strip() for item in request.form.get("repeat_exceptions", "").split(",") if item.strip()]
success, message = save_wheel_settings(
storage,
wheel_id,
{
"entry_deletion": request.form.get("entry_deletion", "1"),
"stop_repeat_entry": "1" if request.form.get("stop_repeat_entry") == "on" else "0",
"repeat_exceptions": repeat_exceptions,
},
)
flash(message, "success" if success else "error")
clear_request_caches()
return redirect(url_for("wheel_detail", wheel_id=wheel_id))
@app.route("/wheel/<wheel_id>/permissions", methods=["POST"])
@login_required
@roles_required("admin")
def update_wheel_permissions_route(wheel_id):
if not entry_is_accessible(get_tracker_data(), "wheel", wheel_id, current_user_level()):
flash("Unknown wheel.", "error")
return redirect(url_for("wheels"))
success, message = save_wheel_permissions(storage, wheel_id, request.form.getlist("view_user_ids"), request.form.getlist("edit_user_ids"))
flash(message, "success" if success else "error")
clear_request_caches()
return redirect(url_for("wheel_detail", wheel_id=wheel_id))
@app.route("/wheel/<wheel_id>/entries/text", methods=["POST"])
@login_required
def add_wheel_text_entries_route(wheel_id):
data = get_tracker_data()
record = data.get("wheel_records", {}).get(wheel_id)
if not user_can_edit_wheel(record, current_user()):
flash("You do not have edit access to that wheel.", "error")
return redirect(url_for("wheels"))
success, message = add_wheel_text_entries(storage, wheel_id, request.form.get("entries_text", "").splitlines())
flash(message, "success" if success else "error")
clear_request_caches()
return redirect(url_for("wheel_detail", wheel_id=wheel_id))
@app.route("/wheel/<wheel_id>/entries/import", methods=["POST"])
@login_required
def import_wheel_entries_route(wheel_id):
data = get_tracker_data()
record = data.get("wheel_records", {}).get(wheel_id)
if not user_can_edit_wheel(record, current_user()):
if is_async_request():
return jsonify({"ok": False, "message": "You do not have edit access to that wheel.", "category": "error"}), 403
flash("You do not have edit access to that wheel.", "error")
return redirect(url_for("wheels"))
success, payload = start_wheel_import_job(wheel_id, request.files.get("bundle"), current_user())
if is_async_request():
if success:
return jsonify(
{
"ok": True,
"message": "Import started.",
"category": "success",
"job_id": payload["job_id"],
"status_url": url_for("wheel_import_status_route", wheel_id=wheel_id, job_id=payload["job_id"]),
}
)
return jsonify({"ok": False, "message": payload["message"], "category": "error"}), 400
flash(payload["message"] if not success else "Import started.", "success" if success else "error")
return redirect(url_for("wheel_detail", wheel_id=wheel_id))
@app.route("/wheel/<wheel_id>/import-status/<job_id>")
@login_required
def wheel_import_status_route(wheel_id, job_id):
data = get_tracker_data()
record = data.get("wheel_records", {}).get(wheel_id)
if not user_can_edit_wheel(record, current_user()):
return jsonify({"ok": False, "message": "You do not have edit access to that wheel.", "category": "error"}), 403
payload = read_import_job_status(job_id)
if not payload or payload.get("wheel_id") != wheel_id:
return jsonify({"ok": False, "message": "That import job was not found.", "category": "error"}), 404
if payload.get("created_by") and payload.get("created_by") != current_user()["id"] and current_user()["role"] != "admin":
return jsonify({"ok": False, "message": "You do not have access to that import job.", "category": "error"}), 403
if payload.get("state") in {"complete", "error"}:
clear_request_caches()
return jsonify({"ok": True, "job": payload})
@app.route("/wheel/<wheel_id>/entries/<entry_id>/delete", methods=["POST"])
@login_required
def delete_wheel_entry_route(wheel_id, entry_id):
data = get_tracker_data()
record = data.get("wheel_records", {}).get(wheel_id)
if not user_can_edit_wheel(record, current_user()):
flash("You do not have edit access to that wheel.", "error")
return redirect(url_for("wheels"))
success, payload = remove_wheel_entry(storage, wheel_id, entry_id)
if success:
if payload.get("kind") == "image":
delete_wheel_media(payload)
flash("Removed wheel entry.", "success")
else:
flash(payload, "error")
clear_request_caches()
return redirect(url_for("wheel_detail", wheel_id=wheel_id))
@app.route("/wheel/<wheel_id>/cache-clear", methods=["POST"])
@login_required
def clear_wheel_cache_route(wheel_id):
data = get_tracker_data()
record = data.get("wheel_records", {}).get(wheel_id)
if not user_can_edit_wheel(record, current_user()):