Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
2209 lines (1907 loc) · 89.2 KB
/
Copy pathapp.py
File metadata and controls
2209 lines (1907 loc) · 89.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
"""Jaika v2 — Main Flask application."""
import base64
import datetime
import functools
import json
import logging
import os
import secrets
import threading
import time
import urllib.request
import urllib.error
from dotenv import load_dotenv
load_dotenv()
from flask import (
Flask, Response, g, jsonify, request, send_file,
send_from_directory, render_template,
)
from flask_cors import CORS
from auth import auth_bp, login_required, _get_user_id, is_admin, is_pro, get_admin_emails, save_admin_emails, get_pro_emails, save_pro_emails, get_contacts, load_token
from api_compat import compat_bp
from gemini import generate, stream_generate, transcribe_audio, get_user_tier, generate_image as gemini_generate_image, generate_tts as gemini_generate_tts
import files as file_store
from sessions import (
list_sessions, get_session, create_session, update_session,
delete_session, add_message, clear_messages, get_conversation_history,
session_count, enforce_session_limit, delete_all_sessions,
)
from skills import list_skills, get_skill, save_skill, delete_skill, build_system_instruction
from pdf import markdown_to_pdf
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
from werkzeug.middleware.proxy_fix import ProxyFix
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import ipaddress
from urllib.parse import urlparse
import socket
app = Flask(__name__)
CORS(
app,
resources={
r"/api/*": {"origins": "*"},
r"/v1/*": {"origins": "*"},
r"/v1beta/*": {"origins": "*"},
},
)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
app.secret_key = os.environ.get("SECRET_KEY", "dev-secret-change-me")
app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024 # 50 MB upload limit
app.config["PREFERRED_URL_SCHEME"] = "https"
DATA_DIR = os.environ.get("JAIKA_DATA_DIR", "./data")
# ── Rate Limiting ────────────────────────────────────────────────────────────
def _rate_limit_key():
"""Rate limit by user ID if authenticated, else by IP."""
uid = _get_user_id()
return uid if uid else get_remote_address()
limiter = Limiter(
app=app,
key_func=_rate_limit_key,
default_limits=["200 per minute"], # global default for all routes
storage_uri="memory://",
)
# ── Bot page session tokens ───────────────────────────────────────────────────
# Public bot pages embed a short-lived token (not a real user ID) so the actual
# Google user ID is never exposed in HTML source. The bot borrows a real user's
# OAuth credentials to call Gemini. _get_bot_uid() auto-picks a user whose
# token is still valid, so the bot page keeps working even if one account's
# refresh token gets revoked.
_bot_sessions = {} # token -> expires_at (float)
_cached_bot_uid = None
_cached_bot_uid_ts = 0
_BOT_ALLOWED_UIDS = [
"112750385266622618824", # goyaljai.020796@gmail.com
"116542085266142929154", # jaipriyanka.y24@gmail.com
"115574333177630037718", # goyaljai.y14@gmail.com
]
def _get_bot_uid():
"""Return a UID from the allowed list that has a valid access token."""
global _cached_bot_uid, _cached_bot_uid_ts
if _cached_bot_uid and time.time() - _cached_bot_uid_ts < 300:
return _cached_bot_uid
from auth import get_access_token
for uid in _BOT_ALLOWED_UIDS:
if get_access_token(uid):
_cached_bot_uid = uid
_cached_bot_uid_ts = time.time()
log.info("[BOT] Using UID %s for bot page API calls", uid)
return uid
log.warning("[BOT] No allowed user with valid token found for bot page")
return None
@app.before_request
def _resolve_bot_token():
"""Resolve a bot-page session token to a real UID with a valid OAuth token."""
raw = request.headers.get("X-User-Id", "")
if not raw:
return
entry = _bot_sessions.get(raw)
if entry is not None:
if entry > time.time():
bot_uid = _get_bot_uid()
if bot_uid:
g.resolved_uid = bot_uid
g.is_bot_session = True
else:
g.resolved_uid = None
else:
_bot_sessions.pop(raw, None)
# ── SSRF Protection ──────────────────────────────────────────────────────────
_BLOCKED_NETWORKS = [
ipaddress.ip_network("127.0.0.0/8"), # loopback
ipaddress.ip_network("10.0.0.0/8"), # private
ipaddress.ip_network("172.16.0.0/12"), # private
ipaddress.ip_network("192.168.0.0/16"), # private
ipaddress.ip_network("169.254.0.0/16"), # link-local / cloud metadata
ipaddress.ip_network("0.0.0.0/8"), # unspecified
ipaddress.ip_network("::1/128"), # IPv6 loopback
ipaddress.ip_network("fc00::/7"), # IPv6 private
ipaddress.ip_network("fe80::/10"), # IPv6 link-local
]
def is_safe_url(url):
"""Block SSRF: reject URLs that resolve to private/internal IPs."""
parsed = urlparse(url)
hostname = parsed.hostname
if not hostname:
return False
# Block common dangerous hostnames
if hostname in ("localhost", "metadata.google.internal"):
return False
try:
# Resolve hostname and check all IPs
for info in socket.getaddrinfo(hostname, parsed.port or 80):
ip = ipaddress.ip_address(info[4][0])
for net in _BLOCKED_NETWORKS:
if ip in net:
return False
except (socket.gaierror, ValueError):
return False # can't resolve = block
return True
# Register blueprints
app.register_blueprint(auth_bp)
app.register_blueprint(compat_bp)
# ── Background token refresh ──────────────────────────────────────────────────
# Proactively refresh OAuth tokens for all known users every 30 minutes.
# Prevents stale tokens from causing auth failures on the first request after
# a long idle period (access tokens expire after ~1hr; we refresh at 54min).
def _token_refresh_worker():
"""Background thread: proactively refresh OAuth tokens before they expire.
Checks every 5 minutes. For each user, get_access_token() decides whether
a refresh is actually needed (it refreshes when within 5 minutes of expiry —
i.e. at ~55 minutes after the token was issued for a 3600s token).
Timeline example for a user who logged in at T=0 (token expires_in=3600):
T+0 login: access_token saved, expires at T+3600
T+55m worker calls get_access_token → T+3300 < T+3600-300 → no refresh
T+55m (next check after 5min): T+3600 > T+3600-300 → REFRESH triggered
T+55m: new access_token obtained, saved_at reset to now, cycle repeats
"""
import time as _time
from auth import get_access_token
_CHECK_INTERVAL = 5 * 60 # check every 5 minutes
_time.sleep(30) # brief startup delay
while True:
try:
users_dir = os.path.join(DATA_DIR, "users")
if os.path.isdir(users_dir):
for uid in os.listdir(users_dir):
try:
tok = get_access_token(uid) # refreshes internally if needed
if tok:
log.debug("[TOKEN-REFRESH] uid=%s OK", uid)
else:
log.warning("[TOKEN-REFRESH] uid=%s refresh failed (re-login required)", uid)
except Exception as e:
log.warning("[TOKEN-REFRESH] uid=%s error: %s", uid, e)
except Exception as e:
log.error("[TOKEN-REFRESH] worker error: %s", e)
_time.sleep(_CHECK_INTERVAL)
_refresh_thread = threading.Thread(target=_token_refresh_worker, daemon=True, name="token-refresh")
_refresh_thread.start()
@app.errorhandler(429)
def ratelimit_handler(e):
uid = _get_user_id() or "anon"
log.warning("[RATELIMIT] uid=%s path=%s limit=%s", uid, request.path, getattr(e, "description", ""))
return jsonify({"error": "Rate limit exceeded. Please slow down."}), 429
# ── Helpers ─────────────────────────────────────────────────────────────────
def _user_id():
return _get_user_id()
def _user_dir(sub=""):
uid = _user_id()
d = os.path.join(DATA_DIR, "users", uid, sub) if sub else os.path.join(DATA_DIR, "users", uid)
os.makedirs(d, exist_ok=True)
return d
def admin_required(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
uid = _user_id()
if not uid or not is_admin(uid):
log.warning("[AUTH] uid=%s route=%s admin_required denied", uid, request.path)
return jsonify({"error": "Admin access required"}), 403
return f(*args, **kwargs)
return wrapper
# ── Pages ───────────────────────────────────────────────────────────────────
@app.route("/")
def index():
return render_template("index.html")
@app.route("/static/<path:filename>")
def static_files(filename):
return send_from_directory(os.path.join(os.path.dirname(__file__), "static"), filename)
@app.route("/privacy-policy")
@app.route("/pro") # keep old route working
def privacy_policy_page():
return render_template("privacy_policy.html")
# ── Public Bot Page ──────────────────────────────────────────────────────────
@app.route("/goyaljai")
def bot_goyaljai():
token = secrets.token_urlsafe(32)
_bot_sessions[token] = time.time() + 3600 # 1-hour TTL
# Lazy cleanup: drop any tokens older than 2 hours
cutoff = time.time() - 7200
expired = [k for k, v in _bot_sessions.items() if v < cutoff]
for k in expired:
_bot_sessions.pop(k, None)
resp = render_template("bot_goyaljai.html", bot_token=token)
from flask import make_response
r = make_response(resp)
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
return r
@app.route("/slides")
@login_required
def slides():
uid = _get_user_id()
if not is_admin(uid):
return jsonify({"error": "Admin only"}), 403
return render_template("slides.html")
@app.route("/login")
def login_shortcut():
"""Shortcut: curl -sL https://server/login | bash"""
from auth import _pending_logins, login_script as _script_fn
import secrets as _secrets, time as _time
token = request.args.get("token", "")
if not token:
token = _secrets.token_urlsafe(32)
if token not in _pending_logins:
_pending_logins[token] = {"status": "pending", "created": _time.time()}
# Build script directly instead of redirect
return _script_fn(override_token=token)
# ── User Info ───────────────────────────────────────────────────────────────
@app.route("/api/me")
@login_required
def me():
uid = _user_id()
# Email lookup: ?email=foo@bar.com (admin only — returns minimal public info)
lookup_email = request.args.get("email", "").strip().lower()
if lookup_email:
if not is_admin(uid):
return jsonify({"error": "Admin only"}), 403
from auth import get_contacts
contacts = get_contacts()
for contact_uid, info in contacts.items():
if info.get("email", "").lower() == lookup_email:
return jsonify({
"user_id": contact_uid,
"email": info.get("email", ""),
"name": info.get("name", ""),
"picture": info.get("picture", ""),
"first_login": info.get("first_login"),
"last_login": info.get("last_login"),
})
return jsonify({"error": "User not found"}), 404
user_meta_path = os.path.join(_user_dir(), "user.json")
if os.path.exists(user_meta_path):
try:
with open(user_meta_path) as f:
info = json.load(f)
except (json.JSONDecodeError, IOError):
info = {}
else:
info = {}
admin = is_admin(uid)
pro = is_pro(uid)
tier = get_user_tier(uid)
storage_used = _user_storage_used(uid)
storage_cap = None if admin else (PRO_STORAGE_CAP if pro else USER_STORAGE_CAP)
# Map internal tier names to Jaika branding
raw_tier = tier.get("tier_name", "Unknown")
if "code assist" in raw_tier.lower() or "gemini" in raw_tier.lower():
display_tier = "Jaika (Powered by Gemini)"
else:
display_tier = raw_tier
info.update({
"user_id": uid,
"is_admin": admin,
"is_pro": pro or admin,
"tier_id": tier.get("tier_id", "unknown"),
"tier_name": display_tier,
"storage_used_bytes": storage_used,
"storage_cap_bytes": storage_cap,
"session_limit": None if admin else (25 if pro else 10),
"file_gen_limit": None if admin else (None if pro else 5),
})
return jsonify(info)
# ── Prompt ──────────────────────────────────────────────────────────────────
@app.route("/api/prompt", methods=["POST"])
@limiter.limit("30 per minute")
@login_required
def prompt():
"""Chat with Gemini. Supports text + file attachments via file_ids."""
uid = _user_id()
data = request.get_json(force=True)
prompt_text = data.get("prompt", "").strip()
session_id = data.get("session_id")
stream = data.get("stream", False)
file_ids = data.get("file_ids", []) # list of file_ids from /api/upload
thinking = data.get("thinking", False)
thinking_budget = int(data.get("thinking_budget", 8192))
grounding = data.get("grounding", False)
response_format = data.get("response_format") # "json" or None
if not prompt_text and not file_ids:
return jsonify({"error": "Empty prompt"}), 400
# Input guardrails — block injection attempts
if prompt_text:
from prompt_engine import check_input_guardrails
is_safe, safety_msg = check_input_guardrails(prompt_text)
if not is_safe:
return jsonify({"error": safety_msg}), 400
# Pro-only features
if thinking and not is_admin(uid) and not is_pro(uid):
log.warning("[TIER] uid=%s feature=thinking blocked", uid)
return jsonify({"error": "Thinking mode is a Pro feature. Upgrade at /pro"}), 403
if grounding and not is_admin(uid) and not is_pro(uid):
log.warning("[TIER] uid=%s feature=grounding blocked", uid)
return jsonify({"error": "Web grounding is a Pro feature. Upgrade at /pro"}), 403
# Get or create session
if session_id:
sess = get_session(uid, session_id)
if not sess:
return jsonify({"error": "Session not found"}), 404
else:
sess = create_session(uid)
session_id = sess["id"]
# Load file inline data
file_data = []
file_metas = []
for fid in file_ids:
inline = file_store.load_file_inline(fid, uid)
if inline:
file_data.append(inline)
file_metas.append({"name": inline["name"], "mime_type": inline["mime_type"],
"converted": inline.get("converted", False)})
else:
log.warning("File %s not found for user %s", fid, uid)
# Build conversation history from past messages (before persisting the current user message)
history = get_conversation_history(uid, session_id)
system_instruction = build_system_instruction(uid)
# Sliding window: keep only the last 20 turn-pairs (40 messages) to save tokens
MAX_HISTORY_TURNS = 20
history = history[-(MAX_HISTORY_TURNS * 2):]
# Inject intent-based hints (code, math, creative writing, etc.)
if prompt_text:
from prompt_engine import detect_intent_hints, detect_search_intent
hints = detect_intent_hints(prompt_text)
if hints:
system_instruction = (system_instruction + "\n\n" + hints).strip() if system_instruction else hints
# Detect whether this prompt would benefit from web search grounding
suggest_grounding = not grounding and detect_search_intent(prompt_text)
else:
suggest_grounding = False
# Inject per-user memory as a pinned first exchange (not in system instruction)
facts = _load_memory(uid)
if facts:
mem_msg = [
{"role": "user", "text": "[Memory context]\n" + "\n".join(f"- {f}" for f in facts), "files": []},
{"role": "model", "text": "Noted.", "files": []},
]
history = mem_msg + history
# Append current user message in-memory for the API call (not persisted yet)
api_messages = history + [{"role": "user", "text": prompt_text, "files": file_metas or []}]
resp_mime = "application/json" if response_format == "json" else None
if stream:
def event_stream():
# First event: session_id so client can continue the conversation
yield f"data: {json.dumps({'type': 'session', 'session_id': session_id})}\n\n"
full_text = []
for chunk in stream_generate(uid, api_messages, files=file_data,
system_instruction=system_instruction,
thinking=thinking, thinking_budget=thinking_budget,
grounding=grounding):
yield chunk
if chunk.startswith("data: "):
try:
d = json.loads(chunk[6:])
if "text" in d:
full_text.append(d["text"])
except (json.JSONDecodeError, KeyError):
pass
# Persist only if we got a response (no orphaned user messages on failure)
if full_text:
add_message(uid, session_id, "user", prompt_text, files=file_metas if file_metas else None)
add_message(uid, session_id, "model", "".join(full_text))
# Signal whether web search grounding would improve this response
if suggest_grounding:
yield f"data: {json.dumps({'type': 'suggest_grounding', 'prompt': prompt_text, 'session_id': session_id})}\n\n"
return Response(event_stream(), mimetype="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
result = generate(uid, api_messages, files=file_data, system_instruction=system_instruction,
thinking=thinking, thinking_budget=thinking_budget,
grounding=grounding, response_mime_type=resp_mime)
if "error" in result:
return jsonify({"error": result["error"], "session_id": session_id}), 502
# Persist user + model messages only after a successful API response
add_message(uid, session_id, "user", prompt_text, files=file_metas if file_metas else None)
add_message(uid, session_id, "model", result["text"])
resp = {
"type": "text",
"text": result["text"],
"session_id": session_id,
}
if result.get("grounding"):
resp["grounding"] = result["grounding"]
if suggest_grounding:
resp["suggest_grounding"] = True
return jsonify(resp)
# ── File Upload ─────────────────────────────────────────────────────────────
USER_STORAGE_CAP = 50 * 1024 * 1024 # 50MB per regular user
PRO_STORAGE_CAP = 500 * 1024 * 1024 # 500MB per pro user
FILE_TTL = 3600 # uploaded files expire after 1 hour
ALLOWED_EXTENSIONS = file_store.EXT_MIME.keys()
def _user_storage_used(uid):
"""Total bytes used by a user across uploads and outputs."""
total = 0
for sub in ("uploads", "outputs"):
d = os.path.join(DATA_DIR, "users", uid, sub)
if os.path.exists(d):
for f in os.listdir(d):
fp = os.path.join(d, f)
if os.path.isfile(fp):
total += os.path.getsize(fp)
return total
def _schedule_file_delete(file_id, uid, delay=FILE_TTL):
def _cleanup():
file_store.delete_file(file_id, uid)
log.info("Auto-deleted file %s for user %s", file_id, uid)
threading.Timer(delay, _cleanup).start()
@app.route("/api/upload", methods=["POST"])
@login_required
def upload():
"""Upload a file for use in prompts. Supports images, PDFs, DOCX, XLSX, PPTX, audio, video, code."""
uid = _user_id()
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
# Storage cap check (skip for admin)
if not is_admin(uid):
used = _user_storage_used(uid)
cap = PRO_STORAGE_CAP if is_pro(uid) else USER_STORAGE_CAP
if used >= cap:
cap_mb = cap // (1024 * 1024)
return jsonify({"error": f"Storage limit reached ({cap_mb}MB). Delete old files or upgrade."}), 429
try:
meta = file_store.save_upload(uid, f, f.filename)
except Exception as e:
log.exception("Upload failed for user %s", uid)
return jsonify({"error": f"Upload failed: {e}"}), 500
_schedule_file_delete(meta["file_id"], uid, FILE_TTL)
return jsonify({
"file_id": meta["file_id"],
"name": meta["name"],
"mime_type": meta["mime_type"],
"original_type": meta["original_type"],
"converted": meta["converted"],
"size": meta["size"],
})
# ── Files ────────────────────────────────────────────────────────────────────
@app.route("/api/files", methods=["GET"])
@login_required
def list_files():
"""List uploaded files for the current user."""
uid = _user_id()
return jsonify({"files": file_store.list_user_files(uid)})
@app.route("/api/files/<file_id>", methods=["GET"])
@login_required
def get_file_meta(file_id):
"""Get metadata for a specific uploaded file."""
uid = _user_id()
meta = file_store.get_file_meta(file_id, uid)
if not meta:
return jsonify({"error": "File not found"}), 404
return jsonify(meta)
@app.route("/api/files/<file_id>", methods=["DELETE"])
@login_required
def delete_file(file_id):
"""Delete an uploaded file."""
uid = _user_id()
if file_store.delete_file(file_id, uid):
return jsonify({"ok": True})
return jsonify({"error": "File not found"}), 404
@app.route("/api/files/<file_id>/download", methods=["GET"])
@login_required
def download_uploaded_file(file_id):
"""Download a raw uploaded file by file_id."""
uid = _user_id()
meta = file_store.get_file_meta(file_id, uid)
if not meta:
return jsonify({"error": "File not found"}), 404
path = meta.get("path", "")
if not path or not os.path.exists(path):
return jsonify({"error": "File data not found"}), 404
return send_file(path, as_attachment=True, download_name=meta["name"])
# ── STT ─────────────────────────────────────────────────────────────────────
@app.route("/api/stt", methods=["POST"])
@limiter.limit("20 per minute")
@login_required
def stt():
"""Speech-to-text. POST audio file as multipart 'file' field.
Supports: mp3, wav, webm, ogg, m4a, flac, aac, aiff.
Returns: {text}
"""
uid = _user_id()
if not is_admin(uid) and not is_pro(uid):
return jsonify({"error": "Speech-to-text is a Pro feature. Upgrade at /pro"}), 403
if "file" not in request.files:
return jsonify({"error": "No audio file provided"}), 400
f = request.files["file"]
if not f.filename:
return jsonify({"error": "Empty filename"}), 400
ext = f.filename.rsplit(".", 1)[-1].lower() if "." in f.filename else "webm"
mime_type = file_store.get_mime(f.filename)
upload_dir = _user_dir("uploads")
audio_path = os.path.join(upload_dir, f"stt_{os.urandom(4).hex()}.{ext}")
f.save(audio_path)
try:
text, error = transcribe_audio(uid, audio_path, mime_type)
finally:
try:
os.remove(audio_path)
except Exception:
pass
if error:
return jsonify({"error": error}), 502
return jsonify({"text": text})
@app.route("/api/voice-prompt", methods=["POST"])
@limiter.limit("20 per minute")
@login_required
def voice_prompt():
"""Audio → transcript → Gemini → response.
Upload audio as multipart 'file' field.
Optional JSON fields (as form data or query params):
session_id, stream
Returns: {transcript, text, session_id}
Or SSE stream with events: {type: transcript, text: ...} then {text: ...} chunks
"""
uid = _user_id()
if not is_admin(uid) and not is_pro(uid):
return jsonify({"error": "Voice prompt is a Pro feature. Upgrade at /pro"}), 403
if "file" not in request.files:
return jsonify({"error": "No audio file provided"}), 400
f = request.files["file"]
if not f.filename:
return jsonify({"error": "Empty filename"}), 400
session_id = request.form.get("session_id") or request.args.get("session_id")
do_stream = request.form.get("stream", "false").lower() == "true"
ext = f.filename.rsplit(".", 1)[-1].lower() if "." in f.filename else "webm"
mime_type = file_store.get_mime(f.filename)
upload_dir = _user_dir("uploads")
audio_path = os.path.join(upload_dir, f"voice_{os.urandom(4).hex()}.{ext}")
f.save(audio_path)
try:
transcript, error = transcribe_audio(uid, audio_path, mime_type)
finally:
try:
os.remove(audio_path)
except Exception:
pass
if error:
return jsonify({"error": f"Transcription failed: {error}"}), 502
transcript = transcript.strip()
if not transcript:
return jsonify({"error": "No speech detected"}), 400
# Get or create session
if session_id:
sess = get_session(uid, session_id)
if not sess:
return jsonify({"error": "Session not found"}), 404
else:
sess = create_session(uid)
session_id = sess["id"]
history = get_conversation_history(uid, session_id)
system_instruction = build_system_instruction(uid)
# Sliding window: keep only the last 20 turn-pairs
MAX_HISTORY_TURNS = 20
history = history[-(MAX_HISTORY_TURNS * 2):]
# Inject per-user memory as a pinned first exchange
facts = _load_memory(uid)
if facts:
mem_msg = [
{"role": "user", "text": "[Memory context]\n" + "\n".join(f"- {f}" for f in facts), "files": []},
{"role": "model", "text": "Noted.", "files": []},
]
history = mem_msg + history
# Append transcript as the current user message in-memory (not persisted yet)
api_messages = history + [{"role": "user", "text": transcript, "files": []}]
if do_stream:
def event_stream():
# First event: the transcript
yield f"data: {json.dumps({'type': 'transcript', 'text': transcript})}\n\n"
full_text = []
for chunk in stream_generate(uid, api_messages, system_instruction=system_instruction):
yield chunk
if chunk.startswith("data: "):
try:
d = json.loads(chunk[6:])
if "text" in d:
full_text.append(d["text"])
except (json.JSONDecodeError, KeyError):
pass
if full_text:
add_message(uid, session_id, "user", transcript)
add_message(uid, session_id, "model", "".join(full_text))
return Response(event_stream(), mimetype="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
result = generate(uid, api_messages, system_instruction=system_instruction)
if "error" in result:
return jsonify({"error": result["error"], "transcript": transcript, "session_id": session_id}), 502
add_message(uid, session_id, "user", transcript)
add_message(uid, session_id, "model", result["text"])
return jsonify({
"transcript": transcript,
"text": result["text"],
"session_id": session_id,
})
# ── Output Download ──────────────────────────────────────────────────────────
@app.route("/api/download/<uid>/<path:filename>")
@login_required
def download(uid, filename):
"""Download a generated output file.
Requires X-User-Id header. Caller must own the file or be an admin.
"""
caller_uid = _user_id()
if caller_uid != uid and not is_admin(caller_uid):
return jsonify({"error": "Forbidden"}), 403
# Prevent path traversal
filename = os.path.basename(filename)
if not uid or not filename:
return jsonify({"error": "Invalid"}), 400
output_dir = os.path.join(DATA_DIR, "users", uid, "outputs")
return send_from_directory(output_dir, filename, as_attachment=False)
# ── PDF Generation ──────────────────────────────────────────────────────────
@app.route("/api/pdf", methods=["POST"])
@login_required
def generate_pdf():
uid = _user_id()
if not is_admin(uid) and not is_pro(uid):
return jsonify({"error": "PDF generation is a Pro feature. Upgrade at /pro"}), 403
data = request.get_json(force=True)
markdown_text = data.get("markdown", "")
if not markdown_text:
return jsonify({"error": "No markdown provided"}), 400
output_dir = _user_dir("outputs")
path, error = markdown_to_pdf(markdown_text, output_dir)
if error:
return jsonify({"error": error}), 500
filename = os.path.basename(path)
uid = _user_id()
return jsonify({"path": f"/api/download/{uid}/{filename}", "filename": filename})
# ── Sessions ────────────────────────────────────────────────────────────────
@app.route("/api/sessions", methods=["GET"])
@login_required
def sessions_list():
return jsonify(list_sessions(_user_id()))
@app.route("/api/sessions", methods=["POST"])
@login_required
def sessions_create():
uid = _user_id()
# Session limits: regular=10, pro=25 (FIFO), admin=unlimited
if not is_admin(uid):
if is_pro(uid):
enforce_session_limit(uid, 24) # make room for new one
else:
count = session_count(uid)
if count >= 10:
return jsonify({"error": "Session limit reached (10). Delete old sessions or upgrade to Pro."}), 429
data = request.get_json(silent=True) or {}
sess = create_session(uid, title=data.get("title"))
return jsonify(sess), 201
@app.route("/api/sessions/<session_id>", methods=["GET"])
@login_required
def sessions_get(session_id):
sess = get_session(_user_id(), session_id)
if not sess:
return jsonify({"error": "Not found"}), 404
return jsonify(sess)
@app.route("/api/sessions/<session_id>", methods=["PUT"])
@login_required
def sessions_update(session_id):
data = request.get_json(force=True)
sess = update_session(_user_id(), session_id, title=data.get("title"))
if not sess:
return jsonify({"error": "Not found"}), 404
return jsonify(sess)
@app.route("/api/sessions/<session_id>", methods=["DELETE"])
@login_required
def sessions_delete(session_id):
if delete_session(_user_id(), session_id):
return jsonify({"ok": True})
return jsonify({"error": "Not found"}), 404
@app.route("/api/sessions/<session_id>/messages", methods=["POST"])
@login_required
def sessions_add_message(session_id):
data = request.get_json(force=True)
msg = add_message(_user_id(), session_id, data.get("role", "user"), data.get("text", ""))
if not msg:
return jsonify({"error": "Session not found"}), 404
return jsonify(msg), 201
@app.route("/api/sessions/<session_id>/messages", methods=["DELETE"])
@login_required
def sessions_clear_messages(session_id):
if clear_messages(_user_id(), session_id):
return jsonify({"ok": True})
return jsonify({"error": "Session not found"}), 404
# ── Skills ──────────────────────────────────────────────────────────────────
@app.route("/api/skills", methods=["GET"])
@login_required
def skills_list():
uid = _user_id()
return jsonify(list_skills(uid))
@app.route("/api/skills/<name>", methods=["GET"])
@login_required
def skills_get(name):
uid = _user_id()
content = get_skill(uid, name)
if content is None:
return jsonify({"error": "Skill not found"}), 404
return jsonify({"name": name, "content": content})
@app.route("/api/skills/upload", methods=["POST"])
@login_required
def skills_upload():
uid = _user_id()
if not is_admin(uid) and not is_pro(uid):
return jsonify({"error": "Creating skills is a Pro feature. Upgrade at /pro"}), 403
if "file" in request.files:
f = request.files["file"]
name = os.path.basename(os.path.splitext(f.filename)[0]).replace("..", "").strip()
content = f.read().decode("utf-8")
else:
data = request.get_json(force=True)
name = os.path.basename(data.get("name", "")).replace("..", "").strip()
content = data.get("content", "")
name = os.path.basename(name).replace('..', '').strip()
if not name or not content:
return jsonify({"error": "Name and content required"}), 400
if not save_skill(uid, name, content):
return jsonify({"error": "Invalid skill name. Use only letters, numbers, hyphens, underscores."}), 400
return jsonify({"name": name, "ok": True}), 201
@app.route("/api/skills/<name>", methods=["DELETE"])
@login_required
def skills_delete(name):
uid = _user_id()
if not is_admin(uid) and not is_pro(uid):
return jsonify({"error": "Deleting skills is a Pro feature. Upgrade at /pro"}), 403
if delete_skill(uid, name):
return jsonify({"ok": True})
return jsonify({"error": "Not found"}), 404
# ── Image & Video Generation ───────────────────────────────────────────────
# Rate limiting for file generation: 5 per user, unlimited for admin
# Structure: {uid: {"count": N, "date": "YYYY-MM-DD"}} — resets daily
_file_gen_counts = {}
def _get_file_gen_count(uid):
"""Return today's file generation count for a user, resetting if date changed."""
today = datetime.date.today().isoformat()
entry = _file_gen_counts.get(uid)
if entry is None or entry.get("date") != today:
_file_gen_counts[uid] = {"count": 0, "date": today}
return 0
return entry["count"]
def _inc_file_gen_count(uid):
"""Increment today's file generation count for a user."""
today = datetime.date.today().isoformat()
entry = _file_gen_counts.get(uid)
if entry is None or entry.get("date") != today:
_file_gen_counts[uid] = {"count": 1, "date": today}
else:
entry["count"] += 1
@app.route("/api/generate/file", methods=["POST"])
@limiter.limit("10 per minute")
@login_required
def generate_file():
"""Generate a file (HTML, SVG, CSV, JSON, Python) using Gemini API."""
uid = _user_id()
data = request.get_json(force=True)
prompt_text = data.get("prompt", "").strip()
file_type = data.get("type", "html").strip().lower()
if not prompt_text:
return jsonify({"error": "Prompt required"}), 400
valid_types = ["html", "svg", "csv", "json", "py", "image", "video"]
if file_type not in valid_types:
return jsonify({"error": f"Invalid type. Use: {', '.join(valid_types)}"}), 400
# Rate limit + storage cap
if not is_admin(uid):
if not is_pro(uid):
count = _get_file_gen_count(uid)
if count >= 5:
return jsonify({
"error": "File generation limit reached (5 per user). Upgrade at /pro"
}), 429
_inc_file_gen_count(uid)
cap = PRO_STORAGE_CAP if is_pro(uid) else USER_STORAGE_CAP
if _user_storage_used(uid) >= cap:
return jsonify({"error": "Storage limit reached. Files auto-delete after 3 minutes."}), 429
from gemini import gemini_generate_file
content, error = gemini_generate_file(uid, prompt_text, file_type)
if error:
return jsonify({"error": error}), 502
# Determine extension and mime type
ext_map = {"html": ("html", "text/html"), "svg": ("svg", "image/svg+xml"),
"csv": ("csv", "text/csv"), "json": ("json", "application/json"),
"py": ("py", "text/x-python"), "image": ("svg", "image/svg+xml"),
"video": ("html", "text/html")}
ext, mime = ext_map.get(file_type, ("html", "text/html"))
fname = f"generated_{os.urandom(4).hex()}.{ext}"
out_dir = os.path.join(DATA_DIR, "users", uid, "outputs")
os.makedirs(out_dir, exist_ok=True)
out_path = os.path.join(out_dir, fname)