tarjim 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tarjim/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Tarjim — Arabic-first video + subtitle downloader."""
2
+
3
+ __version__ = "2.0.0"
tarjim/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import app
2
+
3
+ if __name__ == "__main__":
4
+ app()
tarjim/api/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Local Web API (FastAPI) — 127.0.0.1 only by default, token + Origin/Host
2
+ checks + strict CSP (audit finding M1)."""
3
+
4
+ from .server import create_app
5
+
6
+ __all__ = ["create_app"]
tarjim/api/page.py ADDED
@@ -0,0 +1,116 @@
1
+ """Served HTML page + external JS (no inline script, for a strict CSP)."""
2
+ from __future__ import annotations
3
+
4
+ import html
5
+
6
+ _CSS = """
7
+ :root{--bg:#0E1420;--surface:#161E2E;--line:#2A3346;--text:#ECE7DD;--muted:#9AA3B2;
8
+ --accent:#C9A227;--accent2:#E3C66B;--ink:#0E1420;--danger:#E06C6C}
9
+ @media (prefers-color-scheme:light){:root{--bg:#F6F1E7;--surface:#FBF7EF;--line:#E3D9C6;
10
+ --text:#1E1B16;--muted:#6B6252;--accent:#9C6B2E;--accent2:#B5832E;--ink:#F6F1E7}}
11
+ *{box-sizing:border-box;margin:0;padding:0}
12
+ body{font-family:-apple-system,"Segoe UI",system-ui,sans-serif;background:var(--bg);color:var(--text);
13
+ padding:32px;line-height:1.5;min-height:100vh}
14
+ .wrap{max-width:760px;margin:0 auto}
15
+ header{display:flex;align-items:center;gap:14px;margin-bottom:6px}
16
+ .mono{width:46px;height:46px;border-radius:11px;background:var(--accent);display:grid;place-items:center}
17
+ .mono svg{display:block}
18
+ h1{font-family:"Hoefler Text",Georgia,serif;font-size:30px;font-weight:600}
19
+ .tag{color:var(--muted);font-size:14px;margin:0 0 24px 60px}
20
+ .bar{display:flex;gap:10px;margin-bottom:22px}
21
+ #url{flex:1;background:var(--surface);border:1px solid var(--line);border-radius:10px;
22
+ padding:12px 14px;color:var(--text);font-size:14px;direction:ltr}
23
+ #go{background:var(--accent);color:var(--ink);border:none;border-radius:10px;padding:0 22px;
24
+ font-weight:600;font-size:14px;cursor:pointer}
25
+ .job{background:var(--surface);border:1px solid var(--line);border-radius:12px;padding:14px 16px;margin-bottom:12px}
26
+ .jtop{display:flex;justify-content:space-between;align-items:center;font-size:13px;margin-bottom:8px}
27
+ .jtop .u{color:var(--muted);direction:ltr;max-width:62%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
28
+ .state{font-weight:600}
29
+ .pbar{height:7px;background:var(--line);border-radius:999px;overflow:hidden}
30
+ .pbar i{display:block;height:100%;background:linear-gradient(90deg,var(--accent),var(--accent2));transition:width .3s}
31
+ .x{color:var(--muted);cursor:pointer;background:none;border:1px solid var(--line);border-radius:8px;
32
+ padding:3px 10px;font-size:12px}
33
+ .empty{color:var(--muted);text-align:center;padding:30px}
34
+ .err{color:var(--danger);font-size:12px;margin-top:6px}
35
+ :focus-visible{outline:2px solid var(--accent2);outline-offset:2px}
36
+ /* High-contrast: follows the OS "increase contrast" setting (no toggle, no JS). */
37
+ @media (prefers-contrast:more){
38
+ :root{--muted:var(--text);--line:var(--text)}
39
+ #url,.job,.x{border-width:2px}
40
+ #go,.x{outline:1px solid currentColor}
41
+ }
42
+ """
43
+
44
+ _MARK = ('<svg width="26" height="26" viewBox="0 0 64 64">'
45
+ '<rect x="18" y="17" width="28" height="6.4" rx="1" fill="#0E1420"/>'
46
+ '<rect x="28.8" y="17" width="6.4" height="22" rx="1" fill="#0E1420"/>'
47
+ '<rect x="23" y="36.4" width="18" height="3.2" rx="1.4" fill="#0E1420"/>'
48
+ '<rect x="20" y="46" width="15" height="3.2" rx="1.6" fill="#0E1420" opacity=".5"/>'
49
+ '<circle cx="40" cy="47.6" r="2.1" fill="#0E1420" opacity=".5"/>'
50
+ '<circle cx="46" cy="47.6" r="2.1" fill="#0E1420" opacity=".5"/></svg>')
51
+
52
+
53
+ def render_index(token: str) -> str:
54
+ tok = html.escape(token, quote=True)
55
+ return f"""<!DOCTYPE html>
56
+ <html lang="ar" dir="rtl"><head><meta charset="utf-8">
57
+ <meta name="viewport" content="width=device-width,initial-scale=1">
58
+ <meta name="tarjim-token" content="{tok}">
59
+ <title>Tarjim — ترجِم</title>
60
+ <style>{_CSS}</style></head>
61
+ <body><div class="wrap">
62
+ <header><div class="mono">{_MARK}</div><h1>Tarjim&nbsp;<span style="font-family:'Geeza Pro'">ترجِم</span></h1></header>
63
+ <p class="tag">نزّل الفيديو مع ترجماته — بإتقان · Download video with subtitles</p>
64
+ <div class="bar">
65
+ <input id="url" type="text" placeholder="ألصق رابط فيديو… / Paste a URL…" dir="ltr">
66
+ <button id="go">تنزيل</button>
67
+ </div>
68
+ <div id="jobs"><div class="empty">لا تنزيلات بعد · No downloads yet</div></div>
69
+ </div>
70
+ <script src="/app.js"></script></body></html>"""
71
+
72
+
73
+ APP_JS = r"""
74
+ 'use strict';
75
+ const TOKEN = document.querySelector('meta[name=tarjim-token]').content;
76
+ const H = {'X-Tarjim-Token': TOKEN, 'Content-Type': 'application/json'};
77
+ const $ = (id) => document.getElementById(id);
78
+ const STATE_AR = {queued:'في الانتظار',probing:'جارٍ الفحص',ready:'جاهز',downloading:'يُنزّل',
79
+ paused:'متوقّف',postprocessing:'المعالجة النهائية',completed:'اكتمل',failed:'فشل',canceled:'أُلغي'};
80
+
81
+ async function jget(p){ const r = await fetch(p,{headers:H}); return r.json(); }
82
+ async function jpost(p,b){ const r = await fetch(p,{method:'POST',headers:H,body:JSON.stringify(b||{})}); return r.json(); }
83
+
84
+ function esc(s){ const d=document.createElement('div'); d.textContent=s==null?'':s; return d.innerHTML; }
85
+
86
+ function render(jobs){
87
+ const box = $('jobs');
88
+ if(!jobs.length){ box.innerHTML='<div class="empty">لا تنزيلات بعد · No downloads yet</div>'; return; }
89
+ box.innerHTML = jobs.map(j=>{
90
+ const st = STATE_AR[j.state]||j.state;
91
+ const pct = Math.round(j.progress||0);
92
+ const active = ['downloading','probing','ready','paused','queued'].includes(j.state);
93
+ return `<div class="job">
94
+ <div class="jtop"><span class="u">${esc(j.url)}</span>
95
+ <span><span class="state">${st}</span> ${active?`<button class="x" data-id="${esc(j.id)}">إلغاء</button>`:''}</span></div>
96
+ <div class="pbar"><i style="width:${pct}%"></i></div>
97
+ ${j.error?`<div class="err">${esc(j.error)}</div>`:''}
98
+ </div>`;
99
+ }).join('');
100
+ box.querySelectorAll('.x').forEach(b=> b.onclick=()=> jpost('/api/jobs/'+b.dataset.id+'/cancel'));
101
+ }
102
+
103
+ async function tick(){ try{ const d = await jget('/api/jobs'); render(d.jobs||[]); }catch(e){} }
104
+
105
+ $('go').onclick = async ()=>{
106
+ const url = $('url').value.trim(); if(!url) return;
107
+ $('url').value='';
108
+ try{ await jpost('/api/jobs',{url}); }catch(e){}
109
+ tick();
110
+ };
111
+ $('url').addEventListener('keydown', e=>{ if(e.key==='Enter') $('go').click(); });
112
+ // live updates via Server-Sent Events (EventSource can't set headers -> token in query)
113
+ const es = new EventSource('/api/events?token=' + encodeURIComponent(TOKEN));
114
+ es.onmessage = (e)=>{ try{ render(JSON.parse(e.data).jobs||[]); }catch(_){} };
115
+ tick(); // instant first paint while the stream connects
116
+ """
tarjim/api/server.py ADDED
@@ -0,0 +1,138 @@
1
+ """FastAPI app for the local Web UI.
2
+
3
+ Security (audit M1):
4
+ * bound to 127.0.0.1 by default (see the `web` CLI command);
5
+ * every /api/* call needs the per-session token (constant-time compare);
6
+ * Host and Origin must be loopback — DNS-rebinding / cross-site defense;
7
+ * strict Content-Security-Policy (no inline scripts) + hardening headers.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import json
13
+ import secrets
14
+ import threading
15
+ from urllib.parse import urlsplit
16
+
17
+ from fastapi import FastAPI, HTTPException, Request
18
+ from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, StreamingResponse
19
+
20
+ from ..core.orchestrator import Orchestrator
21
+ from ..store import Store, default_db_path
22
+ from .page import APP_JS, render_index
23
+
24
+ _CSP = ("default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
25
+ "img-src 'self' data:; connect-src 'self'; base-uri 'none'; "
26
+ "form-action 'none'; frame-ancestors 'none'")
27
+ _LOOPBACK = {"127.0.0.1", "localhost", "::1"}
28
+
29
+
30
+ def _is_local(hostvalue: str) -> bool:
31
+ if not hostvalue:
32
+ return False
33
+ hn = hostvalue.rsplit(":", 1)[0].strip("[]") if ":" in hostvalue else hostvalue
34
+ return hn in _LOOPBACK
35
+
36
+
37
+ def _events_payload(db_path) -> str:
38
+ """One Server-Sent-Events frame: the current job list."""
39
+ with Store(db_path) as st:
40
+ jobs = [j.to_dict() for j in st.list()]
41
+ return "data: " + json.dumps({"jobs": jobs}, ensure_ascii=False) + "\n\n"
42
+
43
+
44
+ def create_app(out_dir: str = ".", token: str | None = None,
45
+ db_path=None, port: int = 8770) -> FastAPI:
46
+ token = token or secrets.token_urlsafe(24)
47
+ db_path = db_path if db_path is not None else default_db_path()
48
+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
49
+ cancels: dict[str, threading.Event] = {}
50
+
51
+ def check_host_origin(request: Request) -> None:
52
+ if not _is_local(request.headers.get("host", "")):
53
+ raise HTTPException(403, "non-local Host rejected")
54
+ origin = request.headers.get("origin")
55
+ if origin and not _is_local(urlsplit(origin).netloc):
56
+ raise HTTPException(403, "cross-origin rejected")
57
+
58
+ def require_auth(request: Request) -> None:
59
+ check_host_origin(request)
60
+ tok = request.headers.get("x-tarjim-token") or request.query_params.get("token")
61
+ if not tok or not secrets.compare_digest(tok, token):
62
+ raise HTTPException(401, "unauthorized")
63
+
64
+ @app.middleware("http")
65
+ async def _headers(request: Request, call_next):
66
+ resp = await call_next(request)
67
+ resp.headers["Content-Security-Policy"] = _CSP
68
+ resp.headers["X-Content-Type-Options"] = "nosniff"
69
+ resp.headers["Referrer-Policy"] = "no-referrer"
70
+ resp.headers["X-Frame-Options"] = "DENY"
71
+ return resp
72
+
73
+ @app.get("/", response_class=HTMLResponse)
74
+ def index(request: Request):
75
+ check_host_origin(request)
76
+ return HTMLResponse(render_index(token))
77
+
78
+ @app.get("/app.js")
79
+ def appjs(request: Request):
80
+ check_host_origin(request)
81
+ return PlainTextResponse(APP_JS, media_type="application/javascript")
82
+
83
+ @app.get("/api/jobs")
84
+ def list_jobs(request: Request):
85
+ require_auth(request)
86
+ with Store(db_path) as st:
87
+ return {"jobs": [j.to_dict() for j in st.list()]}
88
+
89
+ @app.get("/api/events")
90
+ def events(request: Request):
91
+ require_auth(request) # EventSource sends the token via ?token=
92
+
93
+ async def gen():
94
+ while not await request.is_disconnected():
95
+ yield _events_payload(db_path)
96
+ await asyncio.sleep(1.0)
97
+ return StreamingResponse(gen(), media_type="text/event-stream")
98
+
99
+ @app.post("/api/jobs")
100
+ async def create_job(request: Request):
101
+ require_auth(request)
102
+ data = await request.json()
103
+ url = (data or {}).get("url", "")
104
+ with Store(db_path) as st:
105
+ orch = Orchestrator(st, out_dir)
106
+ try:
107
+ job = orch.add(url)
108
+ except Exception as e: # noqa: BLE001 (unsafe/invalid url)
109
+ raise HTTPException(400, str(e)) from e
110
+ opts = {}
111
+ if data.get("format"):
112
+ opts["format_sel"] = data["format"]
113
+ if data.get("audio"):
114
+ opts["audio_only"] = True
115
+ for k in ("cookies", "proxy", "name"):
116
+ if data.get(k):
117
+ opts[k] = data[k]
118
+ ev = threading.Event()
119
+ cancels[job.id] = ev
120
+
121
+ def _work():
122
+ with Store(db_path) as st2:
123
+ Orchestrator(st2, out_dir).run(job, opts, cancel=ev)
124
+
125
+ threading.Thread(target=_work, daemon=True).start()
126
+ return JSONResponse(job.to_dict())
127
+
128
+ @app.post("/api/jobs/{job_id}/cancel")
129
+ def cancel_job(job_id: str, request: Request):
130
+ require_auth(request)
131
+ ev = cancels.get(job_id)
132
+ if ev:
133
+ ev.set()
134
+ return {"ok": True}
135
+
136
+ app.state.token = token
137
+ app.state.port = port
138
+ return app