tarjim 2.0.0rc1__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.

Potentially problematic release.


This version of tarjim might be problematic. Click here for more details.

tarjim/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Tarjim — Arabic-first video + subtitle downloader (rebuild of vidsub)."""
2
+
3
+ __version__ = "2.0.0rc1"
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,106 @@
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
+ """
36
+
37
+ _MARK = ('<svg width="26" height="26" viewBox="0 0 64 64">'
38
+ '<rect x="18" y="17" width="28" height="6.4" rx="1" fill="#0E1420"/>'
39
+ '<rect x="28.8" y="17" width="6.4" height="22" rx="1" fill="#0E1420"/>'
40
+ '<rect x="23" y="36.4" width="18" height="3.2" rx="1.4" fill="#0E1420"/>'
41
+ '<rect x="20" y="46" width="15" height="3.2" rx="1.6" fill="#0E1420" opacity=".5"/>'
42
+ '<circle cx="40" cy="47.6" r="2.1" fill="#0E1420" opacity=".5"/>'
43
+ '<circle cx="46" cy="47.6" r="2.1" fill="#0E1420" opacity=".5"/></svg>')
44
+
45
+
46
+ def render_index(token: str) -> str:
47
+ tok = html.escape(token, quote=True)
48
+ return f"""<!DOCTYPE html>
49
+ <html lang="ar" dir="rtl"><head><meta charset="utf-8">
50
+ <meta name="viewport" content="width=device-width,initial-scale=1">
51
+ <meta name="tarjim-token" content="{tok}">
52
+ <title>Tarjim — ترجِم</title>
53
+ <style>{_CSS}</style></head>
54
+ <body><div class="wrap">
55
+ <header><div class="mono">{_MARK}</div><h1>Tarjim&nbsp;<span style="font-family:'Geeza Pro'">ترجِم</span></h1></header>
56
+ <p class="tag">نزّل الفيديو مع ترجماته — بإتقان · Download video with subtitles</p>
57
+ <div class="bar">
58
+ <input id="url" type="text" placeholder="ألصق رابط فيديو… / Paste a URL…" dir="ltr">
59
+ <button id="go">تنزيل</button>
60
+ </div>
61
+ <div id="jobs"><div class="empty">لا تنزيلات بعد · No downloads yet</div></div>
62
+ </div>
63
+ <script src="/app.js"></script></body></html>"""
64
+
65
+
66
+ APP_JS = r"""
67
+ 'use strict';
68
+ const TOKEN = document.querySelector('meta[name=tarjim-token]').content;
69
+ const H = {'X-Tarjim-Token': TOKEN, 'Content-Type': 'application/json'};
70
+ const $ = (id) => document.getElementById(id);
71
+ const STATE_AR = {queued:'في الانتظار',probing:'جارٍ الفحص',ready:'جاهز',downloading:'يُنزّل',
72
+ paused:'متوقّف',postprocessing:'المعالجة النهائية',completed:'اكتمل',failed:'فشل',canceled:'أُلغي'};
73
+
74
+ async function jget(p){ const r = await fetch(p,{headers:H}); return r.json(); }
75
+ async function jpost(p,b){ const r = await fetch(p,{method:'POST',headers:H,body:JSON.stringify(b||{})}); return r.json(); }
76
+
77
+ function esc(s){ const d=document.createElement('div'); d.textContent=s==null?'':s; return d.innerHTML; }
78
+
79
+ function render(jobs){
80
+ const box = $('jobs');
81
+ if(!jobs.length){ box.innerHTML='<div class="empty">لا تنزيلات بعد · No downloads yet</div>'; return; }
82
+ box.innerHTML = jobs.map(j=>{
83
+ const st = STATE_AR[j.state]||j.state;
84
+ const pct = Math.round(j.progress||0);
85
+ const active = ['downloading','probing','ready','paused','queued'].includes(j.state);
86
+ return `<div class="job">
87
+ <div class="jtop"><span class="u">${esc(j.url)}</span>
88
+ <span><span class="state">${st}</span> ${active?`<button class="x" data-id="${esc(j.id)}">إلغاء</button>`:''}</span></div>
89
+ <div class="pbar"><i style="width:${pct}%"></i></div>
90
+ ${j.error?`<div class="err">${esc(j.error)}</div>`:''}
91
+ </div>`;
92
+ }).join('');
93
+ box.querySelectorAll('.x').forEach(b=> b.onclick=()=> jpost('/api/jobs/'+b.dataset.id+'/cancel'));
94
+ }
95
+
96
+ async function tick(){ try{ const d = await jget('/api/jobs'); render(d.jobs||[]); }catch(e){} }
97
+
98
+ $('go').onclick = async ()=>{
99
+ const url = $('url').value.trim(); if(!url) return;
100
+ $('url').value='';
101
+ try{ await jpost('/api/jobs',{url}); }catch(e){}
102
+ tick();
103
+ };
104
+ $('url').addEventListener('keydown', e=>{ if(e.key==='Enter') $('go').click(); });
105
+ setInterval(tick, 1500); tick();
106
+ """
tarjim/api/server.py ADDED
@@ -0,0 +1,119 @@
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 secrets
12
+ import threading
13
+ from urllib.parse import urlsplit
14
+
15
+ from fastapi import FastAPI, HTTPException, Request
16
+ from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
17
+
18
+ from ..core.orchestrator import Orchestrator
19
+ from ..store import Store, default_db_path
20
+ from .page import APP_JS, render_index
21
+
22
+ _CSP = ("default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
23
+ "img-src 'self' data:; connect-src 'self'; base-uri 'none'; "
24
+ "form-action 'none'; frame-ancestors 'none'")
25
+ _LOOPBACK = {"127.0.0.1", "localhost", "::1"}
26
+
27
+
28
+ def _is_local(hostvalue: str) -> bool:
29
+ if not hostvalue:
30
+ return False
31
+ hn = hostvalue.rsplit(":", 1)[0].strip("[]") if ":" in hostvalue else hostvalue
32
+ return hn in _LOOPBACK
33
+
34
+
35
+ def create_app(out_dir: str = ".", token: str | None = None,
36
+ db_path=None, port: int = 8770) -> FastAPI:
37
+ token = token or secrets.token_urlsafe(24)
38
+ db_path = db_path if db_path is not None else default_db_path()
39
+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
40
+ cancels: dict[str, threading.Event] = {}
41
+
42
+ def check_host_origin(request: Request) -> None:
43
+ if not _is_local(request.headers.get("host", "")):
44
+ raise HTTPException(403, "non-local Host rejected")
45
+ origin = request.headers.get("origin")
46
+ if origin and not _is_local(urlsplit(origin).netloc):
47
+ raise HTTPException(403, "cross-origin rejected")
48
+
49
+ def require_auth(request: Request) -> None:
50
+ check_host_origin(request)
51
+ tok = request.headers.get("x-tarjim-token") or request.query_params.get("token")
52
+ if not tok or not secrets.compare_digest(tok, token):
53
+ raise HTTPException(401, "unauthorized")
54
+
55
+ @app.middleware("http")
56
+ async def _headers(request: Request, call_next):
57
+ resp = await call_next(request)
58
+ resp.headers["Content-Security-Policy"] = _CSP
59
+ resp.headers["X-Content-Type-Options"] = "nosniff"
60
+ resp.headers["Referrer-Policy"] = "no-referrer"
61
+ resp.headers["X-Frame-Options"] = "DENY"
62
+ return resp
63
+
64
+ @app.get("/", response_class=HTMLResponse)
65
+ def index(request: Request):
66
+ check_host_origin(request)
67
+ return HTMLResponse(render_index(token))
68
+
69
+ @app.get("/app.js")
70
+ def appjs(request: Request):
71
+ check_host_origin(request)
72
+ return PlainTextResponse(APP_JS, media_type="application/javascript")
73
+
74
+ @app.get("/api/jobs")
75
+ def list_jobs(request: Request):
76
+ require_auth(request)
77
+ with Store(db_path) as st:
78
+ return {"jobs": [j.to_dict() for j in st.list()]}
79
+
80
+ @app.post("/api/jobs")
81
+ async def create_job(request: Request):
82
+ require_auth(request)
83
+ data = await request.json()
84
+ url = (data or {}).get("url", "")
85
+ with Store(db_path) as st:
86
+ orch = Orchestrator(st, out_dir)
87
+ try:
88
+ job = orch.add(url)
89
+ except Exception as e: # noqa: BLE001 (unsafe/invalid url)
90
+ raise HTTPException(400, str(e)) from e
91
+ opts = {}
92
+ if data.get("format"):
93
+ opts["format_sel"] = data["format"]
94
+ if data.get("audio"):
95
+ opts["audio_only"] = True
96
+ for k in ("cookies", "proxy", "name"):
97
+ if data.get(k):
98
+ opts[k] = data[k]
99
+ ev = threading.Event()
100
+ cancels[job.id] = ev
101
+
102
+ def _work():
103
+ with Store(db_path) as st2:
104
+ Orchestrator(st2, out_dir).run(job, opts, cancel=ev)
105
+
106
+ threading.Thread(target=_work, daemon=True).start()
107
+ return JSONResponse(job.to_dict())
108
+
109
+ @app.post("/api/jobs/{job_id}/cancel")
110
+ def cancel_job(job_id: str, request: Request):
111
+ require_auth(request)
112
+ ev = cancels.get(job_id)
113
+ if ev:
114
+ ev.set()
115
+ return {"ok": True}
116
+
117
+ app.state.token = token
118
+ app.state.port = port
119
+ return app
tarjim/cli.py ADDED
@@ -0,0 +1,332 @@
1
+ """Tarjim CLI (Typer).
2
+
3
+ Commands: get · batch · list · rm · resume · subs · doctor · web.
4
+ ``--json`` gives machine output.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import shutil
10
+ from pathlib import Path
11
+
12
+ import typer
13
+
14
+ from . import __version__
15
+ from .core.orchestrator import Orchestrator
16
+ from .core.subscriptions import SubscriptionManager
17
+ from .engines.base import ProgressEvent
18
+ from .store import Store
19
+
20
+ app = typer.Typer(add_completion=False, help="Tarjim — video + subtitles → MP4 (Arabic-first).")
21
+
22
+
23
+ def _store() -> Store:
24
+ return Store()
25
+
26
+
27
+ @app.command()
28
+ def get(
29
+ url: str = typer.Argument(..., help="Video or direct media URL"),
30
+ name: str | None = typer.Option(None, "-n", "--name"),
31
+ fmt: str | None = typer.Option(None, "-f", "--format"),
32
+ out: str = typer.Option(".", "-o", "--out", help="Output directory"),
33
+ audio: bool = typer.Option(False, "--audio", help="Audio only"),
34
+ cookies: str | None = typer.Option(None, "-c", "--cookies", help="Browser name for cookies"),
35
+ proxy: str | None = typer.Option(None, "--proxy"),
36
+ subs: bool = typer.Option(False, "--subs", help="Download subtitles"),
37
+ sub_langs: str | None = typer.Option(None, "--sub-langs", help="e.g. ar,en or all"),
38
+ embed_subs: bool = typer.Option(False, "--embed-subs", help="Burn/embed subtitles"),
39
+ auto_subs: bool = typer.Option(False, "--auto-subs", help="Include auto-generated subs"),
40
+ sponsorblock: bool = typer.Option(False, "--sponsorblock", help="Mark SponsorBlock segments"),
41
+ sponsorblock_remove: bool = typer.Option(False, "--sponsorblock-remove", help="Remove segments"),
42
+ clip: str | None = typer.Option(None, "--clip", help="Trim range START-END, e.g. 0:30-1:00"),
43
+ chapters: bool = typer.Option(False, "--chapters", help="Embed chapters"),
44
+ thumbnail: bool = typer.Option(False, "--thumbnail", help="Embed thumbnail"),
45
+ metadata: bool = typer.Option(False, "--metadata", help="Embed metadata"),
46
+ limit_rate: str | None = typer.Option(None, "--limit-rate", help="e.g. 2M"),
47
+ concurrent: int = typer.Option(0, "-N", "--concurrent", help="Concurrent fragments"),
48
+ gallery: bool = typer.Option(False, "--gallery", help="Use gallery-dl (image galleries)"),
49
+ recode: str | None = typer.Option(None, "--recode", help="Recode video to FMT (e.g. mp4)"),
50
+ remux: str | None = typer.Option(None, "--remux", help="Remux container to FMT (e.g. mp4)"),
51
+ live: bool = typer.Option(False, "--live", help="Record a live stream from start"),
52
+ hwaccel: str | None = typer.Option(None, "--hwaccel", help="videotoolbox|nvenc|qsv|vaapi"),
53
+ loudnorm: bool = typer.Option(False, "--loudnorm", help="EBU R128 loudness normalization"),
54
+ preset: str | None = typer.Option(None, "--preset", help="Apply a saved preset"),
55
+ save_preset: str | None = typer.Option(None, "--save-preset", help="Save these options as a preset"),
56
+ json_out: bool = typer.Option(False, "--json"),
57
+ ):
58
+ """Download and process a single URL."""
59
+ store = _store()
60
+ orch = Orchestrator(store, out)
61
+ raw = dict(
62
+ name=name, format_sel=fmt, audio_only=audio, cookies=cookies, proxy=proxy,
63
+ subtitles=subs, sub_langs=sub_langs, embed_subs=embed_subs, auto_subs=auto_subs,
64
+ sponsorblock_mark=(True if sponsorblock else None),
65
+ sponsorblock_remove=(True if sponsorblock_remove else None),
66
+ clip=clip, embed_chapters=chapters, thumbnail=thumbnail, metadata=metadata,
67
+ limit_rate=limit_rate, concurrent_fragments=(concurrent or None),
68
+ engine=("gallery-dl" if gallery else None), recode_video=recode, remux_video=remux,
69
+ live=live, hwaccel=hwaccel, loudnorm=loudnorm,
70
+ )
71
+ opts = {k: v for k, v in raw.items() if v}
72
+ if preset:
73
+ opts = {**(store.get_preset(preset) or {}), **opts} # explicit flags win
74
+ if save_preset:
75
+ store.save_preset(save_preset, opts)
76
+ if not json_out:
77
+ typer.secho(f"✓ saved preset '{save_preset}'", fg="green")
78
+ try:
79
+ job = orch.add(url, **opts)
80
+ except Exception as e: # noqa: BLE001
81
+ typer.secho(f"✗ {e}", fg="red", err=True)
82
+ raise typer.Exit(2) from e
83
+
84
+ def prog(ev: ProgressEvent):
85
+ if not json_out and ev.percent is not None:
86
+ typer.echo(f"\r {ev.percent:5.1f}% {ev.speed} ETA {ev.eta} ", nl=False)
87
+
88
+ orch.run(job, opts, on_progress=prog)
89
+ job = store.get(job.id)
90
+ if json_out:
91
+ typer.echo(json.dumps(job.to_dict(), ensure_ascii=False))
92
+ else:
93
+ typer.echo()
94
+ if job.state.value == "completed":
95
+ typer.secho(f"✓ {job.id[:8]} {', '.join(job.files) or '(done)'}", fg="green")
96
+ else:
97
+ typer.secho(f"✗ {job.state.value}: {job.error}", fg="red", err=True)
98
+ raise typer.Exit(1)
99
+
100
+
101
+ @app.command("list")
102
+ def list_jobs(json_out: bool = typer.Option(False, "--json")):
103
+ """List jobs (most recent first)."""
104
+ jobs = _store().list()
105
+ if json_out:
106
+ typer.echo(json.dumps([j.to_dict() for j in jobs], ensure_ascii=False))
107
+ return
108
+ if not jobs:
109
+ typer.echo("(no jobs)")
110
+ return
111
+ for j in jobs:
112
+ typer.echo(f"{j.id[:8]} {j.state.value:<13} {int(j.progress):3d}% {j.url[:60]}")
113
+
114
+
115
+ @app.command("rm")
116
+ def rm(
117
+ job_id: str = typer.Argument(..., help="Job id (or prefix)"),
118
+ files: bool = typer.Option(False, "--files", help="Also delete downloaded files (inside the job's folder)"),
119
+ ):
120
+ """Remove a job from history, optionally deleting its files."""
121
+ store = _store()
122
+ all_jobs = store.list()
123
+ match = [j for j in all_jobs if j.id == job_id or j.id.startswith(job_id)]
124
+ if not match:
125
+ typer.secho("no such job", fg="red", err=True)
126
+ raise typer.Exit(1)
127
+ orch = Orchestrator(store)
128
+ for j in match:
129
+ orch.delete(j.id, with_files=files)
130
+ typer.secho(f"removed {len(match)} job(s){' + files' if files else ''}", fg="yellow")
131
+
132
+
133
+ @app.command()
134
+ def resume(json_out: bool = typer.Option(False, "--json")):
135
+ """Resume jobs left pending by an interrupted run."""
136
+ store = _store()
137
+ orch = Orchestrator(store)
138
+ done = orch.resume_all({})
139
+ if json_out:
140
+ typer.echo(json.dumps([j.to_dict() for j in done], ensure_ascii=False))
141
+ else:
142
+ typer.echo(f"resumed {len(done)} job(s)")
143
+
144
+
145
+ @app.command()
146
+ def doctor():
147
+ """Check the environment (engines present)."""
148
+ ok = True
149
+ for tool in ("yt-dlp", "ffmpeg"):
150
+ present = shutil.which(tool) is not None
151
+ ok = ok and present
152
+ mark = typer.style("✓", fg="green") if present else typer.style("✗", fg="red")
153
+ typer.echo(f" {mark} {tool}")
154
+ typer.echo(f"\n tarjim {__version__}")
155
+ raise typer.Exit(0 if ok else 1)
156
+
157
+
158
+ @app.command()
159
+ def web(
160
+ host: str = typer.Option("127.0.0.1", "--host"),
161
+ port: int = typer.Option(0, "--port", help="0 = pick a free port"),
162
+ out: str = typer.Option(".", "-o", "--out"),
163
+ no_open: bool = typer.Option(False, "--no-open"),
164
+ allow_lan: bool = typer.Option(False, "--allow-lan"),
165
+ password: str | None = typer.Option(None, "--password"),
166
+ ):
167
+ """Launch the local Web UI (127.0.0.1 only by default)."""
168
+ import secrets as _secrets
169
+ import socket
170
+ import threading
171
+ import webbrowser
172
+
173
+ import uvicorn
174
+
175
+ from .api.server import _is_local, create_app
176
+
177
+ if not _is_local(host) and not allow_lan:
178
+ typer.secho("Refusing non-local bind. Use --allow-lan with --password.", fg="red", err=True)
179
+ raise typer.Exit(2)
180
+ if allow_lan and not password:
181
+ typer.secho("--allow-lan requires --password.", fg="red", err=True)
182
+ raise typer.Exit(2)
183
+ if not port:
184
+ s = socket.socket()
185
+ s.bind((host, 0))
186
+ port = s.getsockname()[1]
187
+ s.close()
188
+ token = _secrets.token_urlsafe(24)
189
+ application = create_app(out_dir=out, token=token, port=port)
190
+ url = f"http://{host}:{port}/?token={token}"
191
+ typer.secho(f"Tarjim web → {url}", fg="green")
192
+ typer.echo(" (token required · strict CSP · Ctrl+C to stop)")
193
+ if not no_open and _is_local(host):
194
+ threading.Timer(0.7, lambda: webbrowser.open(url)).start()
195
+ uvicorn.run(application, host=host, port=port, log_level="warning")
196
+
197
+
198
+ @app.command()
199
+ def batch(
200
+ file: str = typer.Argument(..., help="A text file of URLs, one per line (# comments ok)"),
201
+ out: str = typer.Option(".", "-o", "--out"),
202
+ json_out: bool = typer.Option(False, "--json"),
203
+ ):
204
+ """Download every URL listed in a file."""
205
+ store = _store()
206
+ orch = Orchestrator(store, out)
207
+ urls = [ln.strip() for ln in Path(file).read_text(encoding="utf-8").splitlines()
208
+ if ln.strip() and not ln.strip().startswith("#")]
209
+ results = []
210
+ for u in urls:
211
+ try:
212
+ job = orch.add(u)
213
+ orch.run(job, {})
214
+ results.append(store.get(job.id).to_dict())
215
+ except Exception as e: # noqa: BLE001
216
+ results.append({"url": u, "error": str(e)})
217
+ if json_out:
218
+ typer.echo(json.dumps(results, ensure_ascii=False))
219
+ else:
220
+ done = sum(1 for r in results if r.get("state") == "completed")
221
+ typer.secho(f"batch: {done}/{len(urls)} completed", fg="green" if done == len(urls) else "yellow")
222
+
223
+
224
+ subs_app = typer.Typer(help="Channel/playlist/RSS subscriptions (auto-download new items).")
225
+ app.add_typer(subs_app, name="subs")
226
+
227
+
228
+ @subs_app.command("add")
229
+ def subs_add(url: str, title: str = typer.Option("", "--title")):
230
+ """Subscribe to a channel/playlist/RSS URL."""
231
+ try:
232
+ s = SubscriptionManager(_store()).add(url, title)
233
+ except Exception as e: # noqa: BLE001
234
+ typer.secho(f"✗ {e}", fg="red", err=True)
235
+ raise typer.Exit(2) from e
236
+ typer.secho(f"✓ subscribed {s.id[:8]} {url}", fg="green")
237
+
238
+
239
+ @subs_app.command("list")
240
+ def subs_list(json_out: bool = typer.Option(False, "--json")):
241
+ """List subscriptions."""
242
+ subs = SubscriptionManager(_store()).list()
243
+ if json_out:
244
+ typer.echo(json.dumps([s.to_dict() for s in subs], ensure_ascii=False))
245
+ return
246
+ if not subs:
247
+ typer.echo("(no subscriptions)")
248
+ return
249
+ for s in subs:
250
+ typer.echo(f"{s.id[:8]} {s.title or s.url}")
251
+
252
+
253
+ @subs_app.command("rm")
254
+ def subs_rm(sub_id: str):
255
+ """Remove a subscription."""
256
+ ok = SubscriptionManager(_store()).remove(sub_id)
257
+ typer.secho("removed" if ok else "no such subscription",
258
+ fg="yellow" if ok else "red", err=not ok)
259
+
260
+
261
+ @subs_app.command("check")
262
+ def subs_check(
263
+ download: bool = typer.Option(False, "--download", help="Queue new items for download"),
264
+ out: str = typer.Option(".", "-o", "--out"),
265
+ json_out: bool = typer.Option(False, "--json"),
266
+ ):
267
+ """Check all subscriptions for new items."""
268
+ store = _store()
269
+ mgr = SubscriptionManager(store, Orchestrator(store, out))
270
+ res = mgr.check_all(download=download)
271
+ total = sum(len(v) for v in res.values())
272
+ if json_out:
273
+ typer.echo(json.dumps(res, ensure_ascii=False))
274
+ else:
275
+ typer.echo(f"{total} new item(s){' downloaded' if download else ''}")
276
+
277
+
278
+ @app.command()
279
+ def tui(
280
+ out: str = typer.Option(".", "-o", "--out"),
281
+ lang: str = typer.Option("en", "--lang", help="UI language (en, ar, …)"),
282
+ ):
283
+ """Launch the terminal UI (Textual)."""
284
+ from .tui.app import run as run_tui
285
+ run_tui(out_dir=out, locale=lang)
286
+
287
+
288
+ presets_app = typer.Typer(help="Saved download presets.")
289
+ app.add_typer(presets_app, name="presets")
290
+
291
+
292
+ @presets_app.command("list")
293
+ def presets_list(json_out: bool = typer.Option(False, "--json")):
294
+ """List saved presets."""
295
+ items = _store().list_presets()
296
+ if json_out:
297
+ typer.echo(json.dumps({n: o for n, o in items}, ensure_ascii=False))
298
+ return
299
+ if not items:
300
+ typer.echo("(no presets)")
301
+ return
302
+ for name, o in items:
303
+ typer.echo(f"{name}: {', '.join(f'{k}={v}' for k, v in o.items())}")
304
+
305
+
306
+ @presets_app.command("rm")
307
+ def presets_rm(name: str):
308
+ """Remove a preset."""
309
+ ok = _store().remove_preset(name)
310
+ typer.secho("removed" if ok else "no such preset", fg="yellow" if ok else "red", err=not ok)
311
+
312
+
313
+ @app.callback(invoke_without_command=True)
314
+ def _main(version: bool = typer.Option(False, "--version")):
315
+ if version:
316
+ typer.echo(f"tarjim {__version__}")
317
+ raise typer.Exit()
318
+
319
+
320
+ def main() -> None:
321
+ """Console-script entry point (`tarjim`)."""
322
+ app()
323
+
324
+
325
+ def vidsub_alias() -> None:
326
+ """Deprecated `vidsub` alias → `tarjim` (kept for one major version)."""
327
+ typer.secho("note: 'vidsub' is a deprecated alias for 'tarjim'.", fg="yellow", err=True)
328
+ app()
329
+
330
+
331
+ if __name__ == "__main__":
332
+ app()
@@ -0,0 +1,6 @@
1
+ """Tarjim core: job model, state machine, orchestration."""
2
+
3
+ from .job import InvalidTransition, Job, JobState, can_transition
4
+ from .orchestrator import Orchestrator
5
+
6
+ __all__ = ["Job", "JobState", "InvalidTransition", "can_transition", "Orchestrator"]