Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
1693 lines (1441 loc) · 68.9 KB
/
Copy pathserver.py
File metadata and controls
1693 lines (1441 loc) · 68.9 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
"""
GWI BlogLab — Flask backend
Supabase-backed: templates, folders, and image uploads stored in Supabase.
Auth: Supabase JWT validated on every /api/ route.
"""
import os
import sys
import uuid
import time
import datetime
import tempfile
import traceback
from functools import wraps
import requests as _requests
import jwt as _pyjwt
from flask import Flask, request, send_file, send_from_directory, jsonify, g
from flask_cors import CORS
# ── Load .env ─────────────────────────────────────────────────────────────────
from dotenv import load_dotenv
load_dotenv()
# ── Flask app ─────────────────────────────────────────────────────────────────
app = Flask(__name__)
# Auth is JWT via Authorization header — no credentials mode needed, allow all origins.
CORS(app, resources={r"/api/*": {"origins": "*"}},
allow_headers=["Content-Type", "Authorization"])
# ── Supabase client ───────────────────────────────────────────────────────────
from supabase import create_client, Client as SupabaseClient
SUPABASE_URL = os.environ["SUPABASE_URL"]
SUPABASE_KEY = os.environ["SUPABASE_KEY"] # anon/public key
SUPABASE_SERVICE_KEY = os.environ.get("SUPABASE_SERVICE_KEY", "") # service role (bypasses RLS)
SUPABASE_JWT_SECRET = os.environ.get("SUPABASE_JWT_SECRET", "")
_sb: SupabaseClient = create_client(SUPABASE_URL, SUPABASE_KEY)
# ── Supabase storage helpers ───────────────────────────────────────────────────
def _signed_url(url_res) -> str | None:
"""Extract signed URL from supabase-py v1 (dict) or v2 (response object)."""
if url_res is None:
return None
# supabase-py v2+: response object with .data dict
if hasattr(url_res, 'data'):
data = url_res.data or {}
return data.get("signedUrl") or data.get("signedURL")
# supabase-py v1: plain dict
if isinstance(url_res, dict):
return (url_res.get("signedURL")
or (url_res.get("data") or {}).get("signedUrl")
or (url_res.get("data") or {}).get("signedURL"))
return None
# ── Auth middleware ────────────────────────────────────────────────────────────
def require_auth(f):
"""Decorator: verify Supabase JWT (local if secret available, else API), set g.user_id."""
@wraps(f)
def wrapper(*args, **kwargs):
auth = request.headers.get("Authorization", "")
if not auth.startswith("Bearer "):
return jsonify({"error": "Unauthorized"}), 401
token = auth.split(" ", 1)[1]
try:
if SUPABASE_JWT_SECRET:
# Fast path: verify locally, zero network round-trip
payload = _pyjwt.decode(
token,
SUPABASE_JWT_SECRET,
algorithms=["HS256"],
options={"verify_aud": False},
)
g.user_id = payload["sub"]
else:
# Fallback: validate via Supabase API (slower but always works)
user_resp = _sb.auth.get_user(token)
g.user_id = user_resp.user.id
g.token = token
except Exception as e:
return jsonify({"error": f"Invalid token: {e}"}), 401
return f(*args, **kwargs)
return wrapper
def _sb_user():
"""Return a Supabase client scoped to the current user's JWT (RLS applies)."""
from supabase import create_client
client = create_client(SUPABASE_URL, SUPABASE_KEY)
client.postgrest.auth(g.token)
client.storage._client.headers["Authorization"] = f"Bearer {g.token}"
return client
def _sb_admin():
"""Return a Supabase client using the service role key (bypasses RLS).
Use only for reads that intentionally cross user boundaries — never for writes.
Falls back to the user-scoped client if SUPABASE_SERVICE_KEY is not set.
"""
from supabase import create_client
key = SUPABASE_SERVICE_KEY or SUPABASE_KEY
return create_client(SUPABASE_URL, key)
# ── Static asset dirs (icons + fonts stay local on the server) ────────────────
ICONS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets", "icons", "Icongraphy", "Icongraphy")
IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets", "images")
DIST_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dist")
ALLOWED_EXTS = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg'}
# ── Templates list cache (global — all users see all templates) ───────────────
_templates_cache = {} # key -> {'data': {...}, 'ts': float}
TEMPLATES_CACHE_TTL = 60 # seconds
_GLOBAL_CACHE_KEY = '__global__'
def _templates_cache_get(user_id):
entry = _templates_cache.get(_GLOBAL_CACHE_KEY)
if entry and time.time() - entry['ts'] < TEMPLATES_CACHE_TTL:
return entry['data']
return None
def _templates_cache_set(user_id, data):
_templates_cache[_GLOBAL_CACHE_KEY] = {'data': data, 'ts': time.time()}
def _templates_cache_invalidate(user_id):
_templates_cache.pop(_GLOBAL_CACHE_KEY, None)
# ── Figma illustration library ─────────────────────────────────────────────────
FIGMA_FILE_KEY = 'JZR9yXgaHwwQVvFgPfDnxn'
_figma_cache = {'data': None, 'ts': 0}
FIGMA_CACHE_TTL = 86400 # 24 hours
ILLUSTRATIONS = [
{'node_id': '8376:462', 'name': 'Illustration 1', 'category': 'Illustrations'},
{'node_id': '8399:1140', 'name': 'Illustration 2', 'category': 'Illustrations'},
{'node_id': '8399:1141', 'name': 'Illustration 3', 'category': 'Illustrations'},
{'node_id': '8399:1142', 'name': 'Illustration 4', 'category': 'Illustrations'},
{'node_id': '8399:1143', 'name': 'Illustration 5', 'category': 'Illustrations'},
{'node_id': '8399:1144', 'name': 'Illustration 6', 'category': 'Illustrations'},
{'node_id': '8399:1148', 'name': 'Illustration 7', 'category': 'Illustrations'},
{'node_id': '8399:1149', 'name': 'Illustration 8', 'category': 'Illustrations'},
{'node_id': '8399:1150', 'name': 'Illustration 9', 'category': 'Illustrations'},
{'node_id': '8399:1151', 'name': 'Illustration 10', 'category': 'Illustrations'},
{'node_id': '8399:1152', 'name': 'Illustration 11', 'category': 'Illustrations'},
{'node_id': '8399:1153', 'name': 'Illustration 12', 'category': 'Illustrations'},
{'node_id': '8399:1154', 'name': 'Illustration 13', 'category': 'Illustrations'},
{'node_id': '8399:1155', 'name': 'Illustration 14', 'category': 'Illustrations'},
{'node_id': '8399:1156', 'name': 'Illustration 15', 'category': 'Illustrations'},
]
# In-memory SVG URL cache — keyed by node_id, value = signed URL string
_svg_url_cache = {}
def _prewarm_illustrations():
"""On startup: fetch SVGs, upload to shared Supabase path, cache signed URLs."""
import time as _time
_time.sleep(5) # wait for server to fully start
token = os.environ.get('FIGMA_TOKEN')
if not token:
print('[prewarm] no FIGMA_TOKEN, skipping', flush=True)
return
headers = {'X-Figma-Token': token}
# Fetch thumbnails for picker
node_ids = ','.join(i['node_id'] for i in ILLUSTRATIONS)
try:
r = _requests.get(
f'https://api.figma.com/v1/images/{FIGMA_FILE_KEY}?ids={node_ids}&format=png&scale=0.5',
headers=headers, timeout=30
)
thumbs = r.json().get('images', {}) if r.ok else {}
except Exception as e:
print(f'[prewarm] thumbnail error: {e}', flush=True)
thumbs = {}
# Fetch real node names from Figma (e.g. "Research/Woman with lightbulb")
figma_names = {}
try:
# Use params= so requests properly URL-encodes colons in node IDs (%3A)
rn = _requests.get(
f'https://api.figma.com/v1/files/{FIGMA_FILE_KEY}/nodes',
params={'ids': node_ids},
headers=headers, timeout=30
)
print(f'[prewarm] nodes API status: {rn.status_code}', flush=True)
print(f'[prewarm] nodes API url: {rn.url}', flush=True)
if rn.ok:
nodes_data = rn.json().get('nodes') or {}
print(f'[prewarm] nodes keys: {list(nodes_data.keys())}', flush=True)
for nid, node_data in nodes_data.items():
doc = (node_data or {}).get('document', {})
name = doc.get('name', '')
print(f'[prewarm] node {nid!r} → name: {name!r}', flush=True)
if name:
# Normalise key to colon format so lookup works against item['node_id']
figma_names[nid.replace('-', ':')] = name
else:
print(f'[prewarm] nodes API error body: {rn.text[:500]}', flush=True)
except Exception as e:
print(f'[prewarm] node name error: {e}', flush=True)
result = []
for item in ILLUSTRATIONS:
nid = item['node_id']
safe = nid.replace(':', '-').replace('/', '-')
storage_path = f"shared/figma/{safe}.svg"
# Check if SVG already in shared Supabase storage
svg_url = None
try:
files = _sb.storage.from_("abx-images").list("shared/figma")
if any(f.get('name') == f"{safe}.svg" for f in (files or [])):
url_res = _sb.storage.from_("abx-images").create_signed_url(storage_path, 60 * 60 * 24 * 365)
svg_url = _signed_url(url_res)
print(f'[prewarm] SVG cache hit: {nid}', flush=True)
except Exception as e:
print(f'[prewarm] cache check error: {e}', flush=True)
if not svg_url:
# Fetch SVG from Figma and upload to shared storage
try:
r2 = _requests.get(
f'https://api.figma.com/v1/images/{FIGMA_FILE_KEY}?ids={nid}&format=svg',
headers=headers, timeout=30
)
svg_export_url = (r2.json().get('images') or {}).get(nid) if r2.ok else None
if svg_export_url:
svg_bytes = _requests.get(svg_export_url, timeout=30).content
_sb.storage.from_("abx-images").upload(
path=storage_path,
file=svg_bytes,
file_options={"content-type": "image/svg+xml", "upsert": "true"},
)
url_res = _sb.storage.from_("abx-images").create_signed_url(storage_path, 60 * 60 * 24 * 365)
svg_url = _signed_url(url_res)
print(f'[prewarm] SVG uploaded and cached: {nid}', flush=True)
except Exception as e:
print(f'[prewarm] SVG upload error: {e}', flush=True)
if svg_url:
_svg_url_cache[nid] = svg_url
result.append({
'name': figma_names.get(nid) or item['name'],
'node_id': nid,
'url': thumbs.get(nid, ''),
'svg_url': svg_url or '',
'category': item['category'],
})
_figma_cache['data'] = result
import time as _time2
_figma_cache['ts'] = _time2.time()
print(f'[prewarm] done — {len(result)} illustrations ready', flush=True)
import threading as _threading
_threading.Thread(target=_prewarm_illustrations, daemon=True).start()
# ── Default template IDs (set via Railway env vars) ───────────────────────────
# Maps template_type slug -> env var name that holds the default template UUID
_DEFAULT_TEMPLATE_ENV = {
'insight-report': 'DEFAULT_INSIGHT_REPORT_ID',
'infographic': 'DEFAULT_INFOGRAPHIC_ID',
}
# ── Template routes ───────────────────────────────────────────────────────────
@app.route("/api/template-default/<tmpl_type>", methods=["GET"])
@require_auth
def get_template_default(tmpl_type):
"""Return blocks from the configured default template for a type, or empty."""
env_key = _DEFAULT_TEMPLATE_ENV.get(tmpl_type)
default_id = os.environ.get(env_key, '') if env_key else ''
if not default_id:
return jsonify({"blocks": None})
# Fetch using service key so we can read any user's template (it's a global default)
res = _sb.table("templates") \
.select("doc") \
.eq("id", default_id) \
.maybe_single() \
.execute()
if not res.data or not res.data.get("doc"):
return jsonify({"blocks": None})
blocks = res.data["doc"].get("blocks") or []
return jsonify({"blocks": blocks})
@app.route("/api/templates", methods=["GET"])
@require_auth
def list_templates():
cached = _templates_cache_get(g.user_id)
if cached:
return jsonify(cached)
try:
sb = _sb_user()
res = sb.table("templates") \
.select("id,user_id,name,status,folder_id,template_type,created_at,updated_at,block_count,block_types,thumb,doc") \
.order("updated_at", desc=True) \
.execute()
print(f'[templates] fetched {len(res.data)} rows for user {g.user_id}', flush=True)
except Exception as e:
print(f'[templates] query error: {e}', flush=True)
traceback.print_exc()
return jsonify({'templates': [], 'folders': [], 'error': str(e)}), 200
try:
folders_res = sb.table("folders") \
.select("*") \
.eq("user_id", g.user_id) \
.order("created_at") \
.execute()
except Exception as e:
print(f'[templates] folders query error: {e}', flush=True)
folders_res_data = []
else:
folders_res_data = folders_res.data
templates = []
for t in res.data:
doc = t.pop("doc", None) or {}
t["doc_author"] = doc.get("docAuthor", "")
t["doc_author_avatar"] = doc.get("docAuthorAvatar", "")
t["doc_image_url"] = doc.get("previewJpeg") or doc.get("imageUrl", "")
t["doc_source_url"] = doc.get("imageUrl", "") # original Pexels/Unsplash URL for recompose
t["doc_composed_url"] = doc.get("composedUrl", "") # full-res PNG in Supabase Storage
t["doc_adjust_params"] = doc.get("adjustParams") # {scale, offsetX, offsetY} from user crop
t["doc_category"] = (doc.get("blogMeta") or {}).get("category", "")
templates.append(t)
data = {"templates": templates, "folders": folders_res_data}
_templates_cache_set(g.user_id, data)
return jsonify(data)
@app.route("/api/templates", methods=["POST"])
@require_auth
def create_template():
data = request.get_json(force=True)
doc = data.get("doc", {"filename": "untitled.pdf", "docTitle": "", "docAuthor": "", "blocks": []})
blocks = doc.get("blocks", [])
payload = {
"user_id": g.user_id,
"name": data.get("name", "Untitled"),
"status": data.get("status", "draft"),
"folder_id": data.get("folder_id") or None,
"template_type": data.get("template_type") or None,
"doc": doc,
"block_count": len(blocks),
"block_types": [b.get("type", "text") for b in blocks],
}
sb = _sb_user()
res = sb.table("templates").insert(payload).execute()
_templates_cache_invalidate(g.user_id)
return jsonify(res.data[0]), 201
@app.route("/api/templates/<tid>", methods=["GET"])
@require_auth
def get_template(tid):
sb = _sb_user()
res = sb.table("templates") \
.select("*") \
.eq("id", tid) \
.maybe_single() \
.execute()
if not res.data:
return jsonify({"error": "Not found"}), 404
return jsonify(res.data)
@app.route("/api/templates/<tid>/copy", methods=["POST"])
@require_auth
def copy_template(tid):
"""Duplicate any template into the current user's own files."""
sb = _sb_user()
src = sb.table("templates") \
.select("*") \
.eq("id", tid) \
.maybe_single() \
.execute()
if not src.data:
return jsonify({"error": "Not found"}), 404
orig = src.data
doc = orig.get("doc") or {}
payload = {
"user_id": g.user_id,
"name": "Copy of " + orig.get("name", "Untitled"),
"status": "draft",
"folder_id": None,
"template_type": orig.get("template_type"),
"doc": doc,
"block_count": orig.get("block_count", 0),
"block_types": orig.get("block_types", []),
}
res = sb.table("templates").insert(payload).execute()
_templates_cache_invalidate(g.user_id)
return jsonify(res.data[0]), 201
@app.route("/api/templates/<tid>", methods=["PUT"])
@require_auth
def update_template(tid):
data = request.get_json(force=True)
patch = {}
if "name" in data: patch["name"] = data["name"]
if "status" in data: patch["status"] = data["status"]
if "folder_id" in data: patch["folder_id"] = data["folder_id"] or None
if "template_type" in data: patch["template_type"] = data["template_type"] or None
if "thumb" in data: patch["thumb"] = data["thumb"]
if "doc" in data:
patch["doc"] = data["doc"]
blocks = data["doc"].get("blocks", [])
patch["block_count"] = len(blocks)
patch["block_types"] = [b.get("type", "text") for b in blocks]
sb = _sb_user()
res = sb.table("templates") \
.update(patch) \
.eq("id", tid) \
.eq("user_id", g.user_id) \
.execute()
if not res.data:
return jsonify({"error": "Not found"}), 404
_templates_cache_invalidate(g.user_id)
return jsonify(res.data[0])
@app.route("/api/templates/<tid>", methods=["DELETE"])
@require_auth
def delete_template(tid):
sb = _sb_user()
sb.table("templates") \
.delete() \
.eq("id", tid) \
.eq("user_id", g.user_id) \
.execute()
_templates_cache_invalidate(g.user_id)
return jsonify({"ok": True})
# ── Folder routes ─────────────────────────────────────────────────────────────
@app.route("/api/folders", methods=["GET"])
@require_auth
def list_folders():
sb = _sb_user()
res = sb.table("folders") \
.select("*") \
.eq("user_id", g.user_id) \
.order("created_at") \
.execute()
return jsonify(res.data)
@app.route("/api/folders", methods=["POST"])
@require_auth
def create_folder():
data = request.get_json(force=True)
sb = _sb_user()
res = sb.table("folders").insert({
"user_id": g.user_id,
"name": data.get("name", "New Folder"),
}).execute()
_templates_cache_invalidate(g.user_id)
return jsonify(res.data[0]), 201
@app.route("/api/folders/<fid>", methods=["PUT"])
@require_auth
def rename_folder(fid):
data = request.get_json(force=True)
sb = _sb_user()
sb.table("folders") \
.update({"name": data.get("name", "Folder")}) \
.eq("id", fid) \
.eq("user_id", g.user_id) \
.execute()
_templates_cache_invalidate(g.user_id)
return jsonify({"ok": True})
@app.route("/api/folders/<fid>", methods=["DELETE"])
@require_auth
def delete_folder(fid):
sb = _sb_user()
# Orphan templates in this folder
sb.table("templates") \
.update({"folder_id": None}) \
.eq("folder_id", fid) \
.eq("user_id", g.user_id) \
.execute()
sb.table("folders") \
.delete() \
.eq("id", fid) \
.eq("user_id", g.user_id) \
.execute()
_templates_cache_invalidate(g.user_id)
return jsonify({"ok": True})
# ── Icon routes (served from local assets — read-only library) ────────────────
@app.route("/api/icons", methods=["GET"])
@require_auth
def list_icons():
if not os.path.exists(ICONS_DIR):
return jsonify([])
files = sorted(
f for f in os.listdir(ICONS_DIR)
if os.path.splitext(f)[1].lower() in {'.png', '.svg', '.jpg', '.webp'}
)
return jsonify(files)
@app.route("/api/icon-file/<path:filename>", methods=["GET"])
def serve_icon_file(filename):
return send_from_directory(ICONS_DIR, filename)
# ── Image routes (stored in Supabase Storage) ─────────────────────────────────
@app.route("/api/images", methods=["GET"])
@require_auth
def list_images():
"""List images uploaded by this user from Supabase Storage."""
try:
prefix = f"{g.user_id}/"
res = _sb.storage.from_("abx-images").list(prefix)
files = [f["name"] for f in (res or []) if f.get("name")]
result = []
for name in files:
storage_path = f"{g.user_id}/{name}"
url_res = _sb.storage.from_("abx-images").create_signed_url(storage_path, 60 * 60 * 24 * 365)
result.append({"name": name, "url": _signed_url(url_res)})
return jsonify(result)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/images", methods=["POST"])
@require_auth
def upload_image():
"""Upload image to Supabase Storage under user's prefix."""
if 'file' not in request.files:
return jsonify({"error": "No file provided"}), 400
f = request.files['file']
if not f.filename:
return jsonify({"error": "Empty filename"}), 400
ext = os.path.splitext(f.filename)[1].lower()
if ext not in ALLOWED_EXTS:
return jsonify({"error": f"File type {ext} not allowed"}), 400
safe_name = "".join(c for c in f.filename if c.isalnum() or c in '._- ').strip() or f"upload{ext}"
storage_path = f"{g.user_id}/{safe_name}"
file_bytes = f.read()
try:
_sb.storage.from_("abx-images").upload(
path=storage_path,
file=file_bytes,
file_options={"content-type": f.content_type or "application/octet-stream", "upsert": "true"},
)
# Return a signed URL valid for 1 year
url_res = _sb.storage.from_("abx-images").create_signed_url(storage_path, 60 * 60 * 24 * 365)
return jsonify({"filename": safe_name, "url": _signed_url(url_res)})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/image-url/<path:filename>", methods=["GET"])
@require_auth
def image_url(filename):
"""Get a fresh signed URL for an image."""
storage_path = f"{g.user_id}/{filename}"
try:
url_res = _sb.storage.from_("abx-images").create_signed_url(storage_path, 60 * 60 * 24)
return jsonify({"url": _signed_url(url_res)})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ── Figma illustration library ────────────────────────────────────────────────
@app.route("/api/figma-names-debug", methods=["GET"])
@require_auth
def figma_names_debug():
"""Live test: hit the Figma nodes API right now and return raw name results."""
token = os.environ.get('FIGMA_TOKEN')
if not token:
return jsonify({"error": "no FIGMA_TOKEN"})
node_ids = ','.join(i['node_id'] for i in ILLUSTRATIONS)
headers = {'X-Figma-Token': token}
try:
rn = _requests.get(
f'https://api.figma.com/v1/files/{FIGMA_FILE_KEY}/nodes',
params={'ids': node_ids},
headers=headers, timeout=30
)
raw = rn.json() if rn.ok else {'status': rn.status_code, 'body': rn.text[:500]}
names = {}
if rn.ok:
for nid, node_data in (raw.get('nodes') or {}).items():
doc = (node_data or {}).get('document', {})
names[nid] = doc.get('name', '(no name)')
return jsonify({
'request_url': rn.url,
'status': rn.status_code,
'names': names,
'cache': _figma_cache['data'],
})
except Exception as e:
return jsonify({"error": str(e)})
@app.route("/api/figma-assets", methods=["GET"])
@require_auth
def figma_assets():
# Serve from pre-warmed in-memory cache — instant response
if _figma_cache['data']:
return jsonify(_figma_cache['data'])
# Still warming up — return skeleton so picker isn't empty
return jsonify([{
'name': item['name'],
'node_id': item['node_id'],
'url': '',
'svg_url': _svg_url_cache.get(item['node_id'], ''),
'category': item['category'],
} for item in ILLUSTRATIONS])
def _trim_svg_with_figma_bounds(svg_bytes, node_id, token):
"""Use Figma nodes API absoluteBoundingBox to trim SVG viewBox accurately."""
import xml.etree.ElementTree as ET
SVG_NS = 'http://www.w3.org/2000/svg'
try:
resp = _requests.get(
f'https://api.figma.com/v1/files/{FIGMA_FILE_KEY}/nodes?ids={node_id}',
headers={'X-Figma-Token': token},
timeout=15
)
print(f'[trim] nodes API status={resp.status_code} node={node_id}', flush=True)
if not resp.ok:
return svg_bytes
data = resp.json()
nodes = data.get('nodes') or {}
node_data = nodes.get(node_id) or nodes.get(node_id.replace('-', ':'))
if not node_data:
print(f'[trim] node not found in response, keys={list(nodes.keys())}', flush=True)
return svg_bytes
doc = node_data.get('document', {})
frame_box = doc.get('absoluteBoundingBox')
if not frame_box:
print(f'[trim] no absoluteBoundingBox on frame', flush=True)
return svg_bytes
frame_x = frame_box['x']
frame_y = frame_box['y']
frame_w = frame_box['width']
frame_h = frame_box['height']
print(f'[trim] frame={frame_w}x{frame_h}', flush=True)
# Collect LEAF node bounding boxes only (actual shapes, not containers).
# Skip: invisible nodes, and any leaf spanning ≥95% of the frame in both
# dimensions (almost certainly a background rectangle).
content_boxes = []
def collect_boxes(node):
if node.get('visible') is False:
return
children = node.get('children', [])
if children:
for child in children:
collect_boxes(child)
else:
bb = node.get('absoluteBoundingBox')
if not bb or bb.get('width', 0) <= 0 or bb.get('height', 0) <= 0:
return
# Skip full-frame background nodes
if bb['width'] >= frame_w * 0.95 and bb['height'] >= frame_h * 0.95:
print(f'[trim] skip full-frame leaf type={node.get("type")} name={node.get("name")} bb={bb["width"]}x{bb["height"]}', flush=True)
return
content_boxes.append(bb)
for child in doc.get('children', []):
collect_boxes(child)
print(f'[trim] leaf boxes found: {len(content_boxes)}', flush=True)
if not content_boxes:
return svg_bytes
min_ax = min(b['x'] for b in content_boxes)
min_ay = min(b['y'] for b in content_boxes)
max_ax = max(b['x'] + b['width'] for b in content_boxes)
max_ay = max(b['y'] + b['height'] for b in content_boxes)
min_x = max(0.0, min_ax - frame_x)
min_y = max(0.0, min_ay - frame_y)
max_x = min(frame_w, max_ax - frame_x)
max_y = min(frame_h, max_ay - frame_y)
new_w = max_x - min_x
new_h = max_y - min_y
print(f'[trim] content bounds: x={min_x:.1f} y={min_y:.1f} w={new_w:.1f} h={new_h:.1f} (frame {frame_w}x{frame_h})', flush=True)
if new_w <= 0 or new_h <= 0:
return svg_bytes
# Only trim if we're removing at least 1% in either dimension
if new_w >= frame_w * 0.99 and new_h >= frame_h * 0.99:
print(f'[trim] already tight, skipping', flush=True)
return svg_bytes
svg_text = svg_bytes.decode('utf-8')
ET.register_namespace('', SVG_NS)
ET.register_namespace('xlink', 'http://www.w3.org/1999/xlink')
root = ET.fromstring(svg_text)
root.set('viewBox', f'{min_x:.2f} {min_y:.2f} {new_w:.2f} {new_h:.2f}')
root.set('width', f'{new_w:.2f}')
root.set('height', f'{new_h:.2f}')
print(f'[trim] viewBox updated to {min_x:.2f} {min_y:.2f} {new_w:.2f} {new_h:.2f}', flush=True)
return ET.tostring(root, encoding='unicode').encode('utf-8')
except Exception as e:
print(f'[trim] EXCEPTION: {e}', flush=True)
return svg_bytes
@app.route("/api/figma-svg", methods=["GET"])
@require_auth
def figma_svg():
"""Fetch SVG for a Figma node, upload to Supabase, return persistent URL."""
node_id = request.args.get('node_id')
if not node_id:
return jsonify({"error": "node_id required"}), 400
token = os.environ.get('FIGMA_TOKEN')
if not token:
return jsonify({"error": "FIGMA_TOKEN not configured"}), 500
# Instant return from pre-warmed in-memory cache
if node_id in _svg_url_cache:
return jsonify({"url": _svg_url_cache[node_id]})
safe_node = node_id.replace(':', '-').replace('/', '-')
storage_path = f"{g.user_id}/figma/t9/{safe_node}.svg"
# Check cache — verify file actually exists before returning URL
try:
folder = f"{g.user_id}/figma/t9"
files = _sb.storage.from_("abx-images").list(folder)
if any(f.get('name') == f"{safe_node}.svg" for f in (files or [])):
url_res = _sb.storage.from_("abx-images").create_signed_url(storage_path, 60 * 60 * 24 * 365)
existing_url = _signed_url(url_res)
if existing_url:
print(f'[figma-svg] cache hit for {safe_node}', flush=True)
return jsonify({"url": existing_url})
except Exception as cache_err:
print(f'[figma-svg] cache check error: {cache_err}', flush=True)
# Fetch SVG export URL from Figma
headers = {'X-Figma-Token': token}
resp = _requests.get(
f'https://api.figma.com/v1/images/{FIGMA_FILE_KEY}?ids={node_id}&format=svg',
headers=headers, timeout=30
)
if not resp.ok:
return jsonify({"error": f"Figma API error: {resp.status_code}"}), 500
svg_url = (resp.json().get('images') or {}).get(node_id)
if not svg_url:
return jsonify({"error": "No SVG returned"}), 500
# Download raw SVG — no trimming, serve as-is from Figma
svg_resp = _requests.get(svg_url, timeout=30)
if not svg_resp.ok:
return jsonify({"error": "Could not download SVG"}), 500
svg_bytes = svg_resp.content
# Upload to Supabase storage
try:
_sb.storage.from_("abx-images").upload(
path=storage_path,
file=svg_bytes,
file_options={"content-type": "image/svg+xml", "upsert": "true"},
)
url_res = _sb.storage.from_("abx-images").create_signed_url(storage_path, 60 * 60 * 24 * 365)
signed_url = _signed_url(url_res)
return jsonify({"url": signed_url})
except Exception as e:
print(f'[figma-svg] upload error: {e}', flush=True)
# Fallback: return base64 data URL so client JSON parse succeeds
import base64
data_url = 'data:image/svg+xml;base64,' + base64.b64encode(svg_bytes).decode()
return jsonify({"url": data_url})
@app.route("/api/figma-svg-debug", methods=["GET"])
@require_auth
def figma_svg_debug():
"""Return SVG + Figma nodes API info for debugging padding issues."""
import xml.etree.ElementTree as ET
node_id = request.args.get('node_id')
if not node_id:
return jsonify({"error": "node_id required"}), 400
token = os.environ.get('FIGMA_TOKEN')
headers = {'X-Figma-Token': token}
# SVG structure
resp = _requests.get(
f'https://api.figma.com/v1/images/{FIGMA_FILE_KEY}?ids={node_id}&format=svg',
headers=headers, timeout=30
)
svg_url = (resp.json().get('images') or {}).get(node_id)
svg_resp = _requests.get(svg_url, timeout=30)
svg_text = svg_resp.content.decode('utf-8')
root = ET.fromstring(svg_text)
def elem_info(e, depth=0):
tag = e.tag.split('}')[-1] if '}' in e.tag else e.tag
attrs = {k: v for k, v in e.attrib.items()}
info = {'tag': tag, 'attrs': attrs}
children = [elem_info(c, depth+1) for c in e if depth < 3]
if children:
info['children'] = children
return info
# Figma nodes API — shows absoluteBoundingBox for all nodes
nodes_resp = _requests.get(
f'https://api.figma.com/v1/files/{FIGMA_FILE_KEY}/nodes?ids={node_id}',
headers=headers, timeout=15
)
nodes_data = nodes_resp.json() if nodes_resp.ok else {'error': nodes_resp.status_code}
# Collect leaf bounding boxes (same logic as _trim_svg_with_figma_bounds)
leaf_boxes = []
try:
doc = (nodes_data.get('nodes') or {}).get(node_id, {}).get('document', {})
frame_box = doc.get('absoluteBoundingBox', {})
def collect_leaves(node):
children = node.get('children', [])
if children:
for child in children:
collect_leaves(child)
else:
bb = node.get('absoluteBoundingBox')
if bb:
leaf_boxes.append({'type': node.get('type'), 'name': node.get('name'), 'bb': bb})
except Exception as e:
leaf_boxes = [{'error': str(e)}]
for child in doc.get('children', []) if isinstance(doc, dict) else []:
collect_leaves(child)
return jsonify({
'viewBox': root.get('viewBox'),
'width': root.get('width'),
'height': root.get('height'),
'svg_structure': elem_info(root),
'frame_box': frame_box if isinstance(doc, dict) else None,
'leaf_boxes': leaf_boxes,
'raw_svg_start': svg_text[:1000],
})
# ── Feedback ──────────────────────────────────────────────────────────────────
@app.route("/api/feedback", methods=["GET"])
@require_auth
def list_feedback():
try:
sb = _sb_user()
res = sb.table("feedback").select("*").order("created_at", desc=True).execute()
return jsonify(res.data or [])
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/feedback", methods=["POST"])
@require_auth
def create_feedback():
body = request.get_json(force=True) or {}
try:
sb = _sb_user()
res = sb.table("feedback").insert({
"user_id": g.user_id,
"user_name": body.get("user_name", ""),
"user_email": body.get("user_email", ""),
"rating": body.get("rating"),
"feedback_text": body.get("feedback_text", ""),
}).execute()
return jsonify(res.data[0] if res.data else {}), 201
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/feedback/<fid>", methods=["PUT"])
@require_auth
def update_feedback(fid):
body = request.get_json(force=True) or {}
try:
sb = _sb_user()
res = sb.table("feedback").update({
"user_name": body.get("user_name", ""),
"user_email": body.get("user_email", ""),
"rating": body.get("rating"),
"feedback_text": body.get("feedback_text", ""),
}).eq("id", fid).eq("user_id", g.user_id).execute()
return jsonify(res.data[0] if res.data else {})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/feedback/<fid>", methods=["DELETE"])
@require_auth
def delete_feedback(fid):
try:
sb = _sb_user()
sb.table("feedback").delete().eq("id", fid).eq("user_id", g.user_id).execute()
return jsonify({"ok": True})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ── Frontend (production) ─────────────────────────────────────────────────────
@app.route("/", defaults={"p": ""})
@app.route("/<path:p>")
def serve_frontend(p):
if not os.path.exists(DIST_DIR):
return "Frontend not built — run: npm run build", 503
target = os.path.join(DIST_DIR, p)
if p and os.path.isfile(target):
return send_from_directory(DIST_DIR, p)
return send_from_directory(DIST_DIR, "index.html")
@app.route("/health")
def health():
return jsonify({"ok": True})
@app.route("/api/config")
def public_config():
"""Public endpoint — returns Supabase credentials for the frontend to initialise its client."""
return jsonify({
"supabaseUrl": SUPABASE_URL,
"supabaseAnonKey": SUPABASE_KEY,
})
@app.route("/api/test/pexels")
def test_pexels():
api_key = os.environ.get("PEXELS_API_KEY", "")
if not api_key:
return jsonify({"ok": False, "error": "PEXELS_API_KEY not set"}), 500
try:
res = _requests.get(
"https://api.pexels.com/v1/search",
headers={"Authorization": api_key},
params={"query": "data analytics", "per_page": 1, "orientation": "landscape"},
timeout=10
)
data = res.json()
photo = data.get("photos", [{}])[0]
return jsonify({"ok": True, "total_results": data.get("total_results"), "sample_image": photo.get("src", {}).get("medium")})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.route("/api/test/figma")
def test_figma():
token = os.environ.get("FIGMA_TOKEN", "")
if not token:
return jsonify({"ok": False, "error": "FIGMA_TOKEN not set"}), 500
try:
file_key = "0b47ipE59eoQ72I7ceHkPd"
res = _requests.get(
f"https://api.figma.com/v1/files/{file_key}",
headers={"X-Figma-Token": token},
timeout=15
)
data = res.json()
if "err" in data:
return jsonify({"ok": False, "error": data["err"]}), 500
return jsonify({"ok": True, "file_name": data.get("name"), "last_modified": data.get("lastModified")})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
# ── Thumbnail generation pipeline ─────────────────────────────────────────────