Spaces:
Running
Running
File size: 10,995 Bytes
e6b1320 0cfa5c0 e6b1320 dbfb8ea e6b1320 080713a 0cfa5c0 dbfb8ea e6b1320 0cfa5c0 080713a 4f95823 be03b51 e6b1320 0cfa5c0 e6b1320 be03b51 0cfa5c0 e6b1320 dbfb8ea 0cfa5c0 e6b1320 0cfa5c0 e6b1320 0cfa5c0 e6b1320 0cfa5c0 e6b1320 be03b51 dbfb8ea 080713a 0cfa5c0 dbfb8ea 080713a 0cfa5c0 e6b1320 0cfa5c0 e6b1320 0cfa5c0 e6b1320 0cfa5c0 e6b1320 0cfa5c0 e6b1320 0cfa5c0 e6b1320 0cfa5c0 080713a 0cfa5c0 080713a e6b1320 0cfa5c0 e6b1320 080713a dbfb8ea 080713a dbfb8ea 4f95823 dbfb8ea 4f95823 dbfb8ea 4f95823 dbfb8ea 4f95823 dbfb8ea be03b51 0cfa5c0 686ce75 e6b1320 0cfa5c0 | 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 | """
app.py — B24 Browser AI backend.
Accounts are NOT owned here. Signup/login are proxied to the messenger
backend (Messenger_back_database) so B24 Meet and B24 Browser share one
account system. Every other route verifies the JWT locally using the
shared JWT_SECRET (see auth.py) — no network round-trip needed.
"""
import os
import time
from functools import wraps
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
from flask import Flask, request, jsonify, Response, send_from_directory
from flask_cors import CORS
import auth
import search
import ai
import scraper
import video
import keepalive
import ota
import ota_db
app = Flask(__name__)
CORS(app)
ota_db.init_db()
ADMIN_PASSKEY = os.environ.get("ADMIN_PASSKEY")
MESSENGER_BACKEND_URL = os.environ.get(
"MESSENGER_BACKEND_URL", "https://brighton233j-messenger-back-database.hf.space"
)
GNEWS_API_KEY = os.environ.get("GNEWS_API_KEY")
_news_cache = {"data": None, "fetched_at": 0}
NEWS_CACHE_SECONDS = 1200 # 20 minutes
def get_auth_user():
header = request.headers.get("Authorization", "")
token = header.replace("Bearer ", "").strip()
if not token:
return None
return auth.verify_token(token)
def require_auth(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
payload = get_auth_user()
if not payload:
return jsonify({"error": "Unauthorized"}), 401
request.user = payload
return fn(*args, **kwargs)
return wrapper
def require_admin(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
key = request.headers.get("X-Admin-Key")
if not ADMIN_PASSKEY or key != ADMIN_PASSKEY:
return jsonify({"error": "Forbidden"}), 403
return fn(*args, **kwargs)
return wrapper
def get_identity():
"""Auth'd users are identified by their account id; guests are scoped by
IP so per-identity limits (e.g. keep-alive session caps) still apply
without requiring login."""
payload = get_auth_user()
if payload:
return payload["sub"]
return f"guest:{request.remote_addr}"
# ---------------------------------------------------------------------------
# Auth — proxied to messenger backend, accounts live there only
# ---------------------------------------------------------------------------
@app.route("/auth/signup", methods=["POST"])
def signup():
try:
resp = requests.post(
f"{MESSENGER_BACKEND_URL}/auth/signup",
json=request.get_json(silent=True) or {},
timeout=10,
)
except requests.RequestException:
return jsonify({"error": "Could not reach account server"}), 502
return (resp.text, resp.status_code, {"Content-Type": "application/json"})
@app.route("/auth/login", methods=["POST"])
def login():
try:
resp = requests.post(
f"{MESSENGER_BACKEND_URL}/auth/login",
json=request.get_json(silent=True) or {},
timeout=10,
)
except requests.RequestException:
return jsonify({"error": "Could not reach account server"}), 502
return (resp.text, resp.status_code, {"Content-Type": "application/json"})
@app.route("/login")
def login_page():
return send_from_directory(".", "login.html")
# ---------------------------------------------------------------------------
# AI features
# ---------------------------------------------------------------------------
@app.route("/summarize", methods=["POST"])
@require_auth
def summarize():
data = request.get_json(silent=True) or {}
url = data.get("url", "")
text = data.get("text", "")
if not text:
return jsonify({"error": "text is required"}), 400
summary = ai.summarize_page(url, text)
return jsonify({"summary": summary})
@app.route("/smart-search", methods=["POST"])
@require_auth
def smart_search():
data = request.get_json(silent=True) or {}
query = data.get("query", "").strip()
if not query:
return jsonify({"error": "query is required"}), 400
results = search.ddg_search(query)
if isinstance(results, dict) and "error" in results:
return jsonify(results), 502
answer = ai.synthesize_search(query, results)
return jsonify({"answer": answer, "results": results})
@app.route("/related", methods=["POST"])
@require_auth
def related():
data = request.get_json(silent=True) or {}
url = data.get("url", "")
text = data.get("text", "")
if not text:
return jsonify({"error": "text is required"}), 400
queries = ai.suggest_related(url, text)
def _search_one(q):
results = search.ddg_search(q, max_results=1)
if isinstance(results, list) and results:
return {"query": q, **results[0]}
return {"query": q, "title": q, "url": "", "snippet": ""}
links = []
with ThreadPoolExecutor(max_workers=5) as pool:
futures = {pool.submit(_search_one, q): q for q in queries}
for fut in as_completed(futures):
links.append(fut.result())
return jsonify({"related": links})
@app.route("/scrape", methods=["POST"])
@require_auth
def scrape():
data = request.get_json(silent=True) or {}
url = data.get("url", "")
if not url:
return jsonify({"error": "url is required"}), 400
result = scraper.fetch_page(url)
if "error" in result:
return jsonify(result), 502
return jsonify(result)
# ---------------------------------------------------------------------------
# Video (yt-dlp)
# ---------------------------------------------------------------------------
@app.route("/video/info", methods=["POST"])
@require_auth
def video_info():
data = request.get_json(silent=True) or {}
url = data.get("url", "")
if not url:
return jsonify({"error": "url is required"}), 400
result = video.get_video_info(url)
if "error" in result:
return jsonify(result), 502
return jsonify(result)
@app.route("/video/download", methods=["GET"])
@require_auth
def video_download():
url = request.args.get("url", "")
format_id = request.args.get("format_id")
if not url:
return jsonify({"error": "url is required"}), 400
return Response(
video.stream_download(url, format_id),
mimetype="video/x-matroska",
headers={"Content-Disposition": "attachment; filename=video.mkv"},
)
# ---------------------------------------------------------------------------
# Keep Alive — open to guests (scoped by IP instead of account when signed out)
# ---------------------------------------------------------------------------
@app.route("/keepalive/start", methods=["POST"])
def keepalive_start():
data = request.get_json(silent=True) or {}
url = data.get("url", "")
interval = data.get("interval", 60)
if not url:
return jsonify({"error": "url is required"}), 400
result = keepalive.start(get_identity(), url, interval)
if "error" in result:
return jsonify(result), 429
return jsonify(result)
@app.route("/keepalive/stop", methods=["POST"])
def keepalive_stop():
data = request.get_json(silent=True) or {}
session_id = data.get("session_id", "")
result = keepalive.stop(get_identity(), session_id)
if "error" in result:
return jsonify(result), 404
return jsonify(result)
@app.route("/keepalive/status", methods=["GET"])
def keepalive_status():
return jsonify({"sessions": keepalive.status(get_identity())})
# ---------------------------------------------------------------------------
# News (GNews.io, cached)
# ---------------------------------------------------------------------------
def fetch_news(query="Uganda technology"):
if not GNEWS_API_KEY:
return []
try:
resp = requests.get(
"https://gnews.io/api/v4/search",
params={"q": query, "lang": "en", "max": 10, "token": GNEWS_API_KEY},
timeout=10,
)
data = resp.json()
except Exception:
return []
items = []
for a in data.get("articles", []):
items.append({
"title": a.get("title", ""),
"link": a.get("url", ""),
"source": (a.get("source") or {}).get("name", ""),
"published": a.get("publishedAt", ""),
"image": a.get("image"),
})
return items
@app.route("/news", methods=["GET"])
def get_news():
query = request.args.get("q", "Uganda technology")
now = time.time()
if _news_cache["data"] and (now - _news_cache["fetched_at"] < NEWS_CACHE_SECONDS):
return jsonify({"cached": True, "articles": _news_cache["data"]})
articles = fetch_news(query)
_news_cache["data"] = articles
_news_cache["fetched_at"] = now
return jsonify({"cached": False, "articles": articles})
# ---------------------------------------------------------------------------
# Admin / OTA
# ---------------------------------------------------------------------------
@app.route("/admin/upload-ota", methods=["POST"])
@require_admin
def admin_upload_ota():
"""Admin uploads a zip of the dist/ folder from
`npx expo export --platform android --output-dir dist` (multipart
'file' + form fields 'runtime_version', optional 'notes')."""
if "file" not in request.files:
return jsonify({"error": "No file provided"}), 400
file = request.files["file"]
runtime_version = (request.form.get("runtime_version") or "").strip()
notes = request.form.get("notes")
if not runtime_version:
return jsonify({"error": "runtime_version is required"}), 400
result, error = ota.process_upload(file, runtime_version, notes)
if error:
body, status = error
return jsonify(body), status
return jsonify(result)
@app.route("/api/manifest", methods=["GET"])
def api_manifest():
"""The endpoint expo-updates itself calls (set as `updates.url` in
app.json). Implements the Expo Updates protocol's plain-JSON response
path (no code signing; protocol version 1's 'no update' case is a 406,
per spec)."""
protocol_version = request.headers.get("expo-protocol-version", "0")
platform = request.headers.get("expo-platform") or request.args.get("platform")
runtime_version = request.headers.get("expo-runtime-version") or request.args.get("runtime-version")
current_update_id = request.headers.get("expo-current-update-id")
manifest, error = ota.build_manifest(protocol_version, platform, runtime_version, current_update_id)
if error:
body, status = error
return jsonify(body), status
resp = jsonify(manifest)
resp.headers["expo-protocol-version"] = protocol_version
resp.headers["expo-sfv-version"] = "0"
resp.headers["cache-control"] = "private, max-age=0"
return resp
@app.route("/health", methods=["GET"])
def health():
return jsonify({"status": "ok"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860)
|