Metadata-Version: 2.4
Name: tg-mpv
Version: 0.3.2
Summary: Stream Telegram videos (found via a Telegram bot) directly into mpv without downloading them first
Author-email: Quillai Mohammed Eisa <quillai.dev@gmail.com>
Maintainer-email: Quillai Mohammed Eisa <quillai.dev@gmail.com>
License-Expression: GPL-3.0-or-later
Project-URL: Homepage, https://github.com/quillai-dev/tg-mpv
Project-URL: Repository, https://github.com/quillai-dev/tg-mpv
Project-URL: Issues, https://github.com/quillai-dev/tg-mpv/issues
Project-URL: Changelog, https://github.com/quillai-dev/tg-mpv/blob/main/CHANGELOG.md
Keywords: telegram,mpv,streaming,cli,telethon,video,player
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: End Users/Desktop
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Communications :: Chat
Classifier: Topic :: Multimedia :: Video
Classifier: Topic :: Utilities
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: telethon>=1.44
Requires-Dist: aiohttp>=3.9
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Dynamic: license-file

# tg-mpv

[![PyPI](https://img.shields.io/pypi/v/tg-mpv)](https://pypi.org/project/tg-mpv/)
[![Python](https://img.shields.io/pypi/pyversions/tg-mpv)](https://pypi.org/project/tg-mpv/)
[![Tests](https://github.com/quillai-dev/tg-mpv/actions/workflows/tests.yml/badge.svg)](https://github.com/quillai-dev/tg-mpv/actions/workflows/tests.yml)
[![License: GPL v3+](https://img.shields.io/badge/license-GPL--3.0--or--later-blue)](https://github.com/quillai-dev/tg-mpv/blob/main/LICENSE)

**Search for videos through a Telegram bot and play them in [mpv](https://mpv.io) — without downloading the whole file first.**

```bash
tg-mpv "movie name"
```

(or just run `tg-mpv` and type the name when asked)

tg-mpv signs in to Telegram as *your own account*, asks the bot, lets you pick a result, and starts a tiny
localhost-only HTTP server that turns mpv's `Range` requests into partial Telegram downloads. mpv plays and seeks
freely; only the bytes you actually watch are fetched.

Works on **Linux, macOS and Windows**.

## Features

- Streams straight into mpv — seeking works, nothing is saved to disk.
- Video list with **load more**, **filter** (`f 1080p`, `f S04`) and **sort by size**.
- **Next episode** offer when an episode ends; **resume** where you stopped; `--start 00:36:06`.
- `--continue` picks up the last video (or the next episode) — from your catalog, no search needed.
- **Quality preference** (`--quality 1080p`, `--max-size 2GB`, `--auto`).
- **Download** a video instead of streaming it (`--download`): resumable, with progress.
- **Subtitles** sent by the bot are loaded into mpv.
- Smarter searching: retries with reworded queries and learns how your bot behaves.
- `--doctor` diagnoses problems; `--install-mpv` installs mpv for you.
- Safe by design: localhost only, no shell, session never printed.

## Install

You need Python 3.11+, [mpv](https://mpv.io), a Telegram account and Telegram API credentials.

```bash
pipx install tg-mpv        # recommended: isolated install
# or
pip install tg-mpv
```

pip installs the Python dependencies (Telethon, aiohttp). **mpv is a native program, so pip cannot install it** —
run:

```bash
tg-mpv --install-mpv
```

It finds your package manager (Scoop/Chocolatey, Homebrew, apt/dnf/pacman/zypper), shows the exact command and runs it
only after you confirm. If you prefer to do it yourself:

| OS | Install mpv |
|---|---|
| Linux | `sudo apt install mpv` · `sudo dnf install mpv` · `sudo pacman -S mpv` |
| macOS | `brew install mpv` |
| Windows | `scoop install mpv` · `choco install mpvio` · or download from <https://mpv.io/installation> |

`tg-mpv --setup` also finds mpv if it is installed but not on `PATH`, and fixes that. Otherwise set `MPV` to its full path.

> If the `tg-mpv` command is not found (common on Windows), use `python -m tg_mpv ...`.

## Quick start

**One command does the whole setup:**

```bash
tg-mpv --setup
```

The wizard walks you through four steps (press Enter to keep a current value, `Ctrl+C` to stop; re-run any time):

1. **Telegram API credentials** — it explains how to get your own `api_id` and `api_hash` at
   <https://my.telegram.org/apps>, opens the page, and saves what you type (the hash is hidden while typing).
2. **Default bot** — which bot to ask for videos (written to `config.toml`).
3. **mpv** — installs it with your package manager if missing (asks first), finds it if it is installed but not on
   `PATH`, and on Windows adds its folder to your user `PATH`. Its full path is also recorded in `config.toml`
   (`[mpv] bin`). Open a new terminal afterwards so Windows picks up the new `PATH`.
4. **Log in** — phone number, the code Telegram sends, and your 2FA password if enabled.

Then check everything and play:

```bash
tg-mpv --doctor
tg-mpv "movie name"
```

Why your own credentials? Telegram requires every app to use the `api_id`/`api_hash` of its own developer account,
and the hash is meant to stay private, so tg-mpv does not ship one. They are stored in `credentials.json` in the
config directory (owner-only permissions on Linux/macOS; inside your user profile on Windows). **Treat that file and
`telegram.session` like SSH keys** — anyone holding the session can act as your account. They are separate from
Telegram Desktop, which tg-mpv never touches.

Prefer environment variables? Set `TG_MPV_API_ID` and `TG_MPV_API_HASH` instead (they win over the saved file), then
run `tg-mpv --login`.

## Usage

```
tg-mpv [options] "query"
```

| Option | What it does |
|---|---|
| `--bot @name` | Bot to ask (default `@weeceebot`, or `TG_MPV_BOT`) |
| `--start HH:MM:SS` / `--start begin` | Start position (otherwise you are asked) |
| `--quality 1080p` | Preferred resolution; the best match is marked, press Enter to take it |
| `--max-size 2GB` | Prefer files not bigger than this |
| `--auto` | Pick automatically when the list is just one episode in several qualities |
| `--filter TEXT` / `--sort size` | Pre-filter or sort the list |
| `--no-subs` | Do not load subtitles |
| `--download` | Save the chosen video to disk instead of playing it (resumable) |
| `--output-dir DIR` | Download folder (default `~/Downloads/tg-mpv`) |
| `--continue` | Resume the last unfinished video, or open the next episode of the last finished one |
| `--history` | Show recent videos and replay one |
| `--setup` | Guided setup: credentials, bot, mpv (install + PATH), login |
| `--doctor` | Check the setup and explain any problem |
| `--config` | Create/show `config.toml` and the effective settings |
| `--install-mpv` | Install mpv with your package manager (asks first) |
| `--login` / `--logout` / `--status` | Manage the Telegram session |
| `--debug` | Print what the bot sent (never secrets) |
| `--version` | Print the version |

Typical session:

```
$ tg-mpv "Mr Robot"
Searching @weeceebot for: Mr Robot

Available videos:
  [1] Mr.Robot S04E12   1.1 GB  (1080p, 49:30)   <- best match
  [2] Mr.Robot S04E13   1.2 GB  (1080p, 50:55)
  number = play | Enter = 1 | n = load more | f TEXT = filter | s = sort by size | q = quit
Select [1]: 2

Start playback:
  [1] From the beginning
  [2] From a specific time
Select: 1
Launching mpv...
```

In the video list: a number plays it, `n` loads more results, `f 1080p` / `f S04` filters, `f` clears the filter,
`s` toggles sorting by size, `q` quits.

## Configuration

Everything works from environment variables; a config file is optional (`tg-mpv --config` creates a commented one).

| Variable | Default | Meaning |
|---|---|---|
| `TG_MPV_API_ID`, `TG_MPV_API_HASH` | *(required)* | Telegram API credentials |
| `TG_MPV_BOT` | `@weeceebot` | Bot username |
| `TG_MPV_QUALITY` | — | Preferred resolution, e.g. `1080p` |
| `TG_MPV_MAX_SIZE` | — | Preferred maximum size, e.g. `2GB` |
| `TG_MPV_AUTO` | `false` | Auto-pick when unambiguous |
| `TG_MPV_NO_SUBS` | `false` | Never load subtitles |
| `TG_MPV_DOWNLOAD_DIR` | `~/Downloads/tg-mpv` | Where `--download` saves videos |
| `TG_MPV_HOST` / `TG_MPV_PORT` | `127.0.0.1` / `0` | Local server (host is forced to localhost) |
| `TG_MPV_CHUNK_SIZE` | `524288` | Telegram request size in bytes |
| `TG_MPV_CACHE_SECS` | `45` | mpv `--cache-secs` |
| `MPV` | `mpv` | Path to the mpv binary |
| `TG_MPV_CONFIG_DIR` | *(see below)* | Where settings and data live |

Settings, session and history are stored in:

- Linux / macOS: `~/.config/tg-mpv` (or `$XDG_CONFIG_HOME/tg-mpv`)
- Windows: `%APPDATA%\tg-mpv`

`config.toml` (all optional, environment variables win):

```toml
[telegram]
bot = "@weeceebot"

[preferences]
quality = "1080p"
max_size = "2GB"
auto = false
no_subs = false

[download]
dir = "~/Videos/telegram"

[mpv]
cache_secs = 45
# bin = "C:\\Users\\you\\scoop\\shims\\mpv.exe"   # written by --setup
```

tg-mpv also keeps small JSON files there: `history.json` (resume positions), `catalog.json` (videos it has seen, so the
next episode can be opened without a search) and `prefs.json` (what it learned about your bot and series).

## How it works

```
 Telegram ──MTProto (your account)──▶ tg-mpv ──HTTP Range, 127.0.0.1 only──▶ mpv
   bot search · partial downloads      │ bot.py        finds the video
                                       │ server.py     localhost Range server
                                       └ stream.py     Range → Telegram iter_download
```

| Module | Responsibility |
|---|---|
| `cli.py` | Arguments, menus, playback loop, next episode / resume |
| `bot.py` | Talks to the bot: bursts of messages, buttons, "load more" |
| `media.py` | Video/subtitle detection, episode and resolution helpers |
| `download.py` | `--download`: resumable save to disk |
| `server.py`, `stream.py` | Localhost Range server; Range → Telegram partial download, retries |
| `player.py` | mpv process, position tracking, cleanup |
| `state.py` | History, catalog, learned preferences, single-instance lock |
| `config.py`, `platform_utils.py` | Settings and everything OS-specific |
| `doctor.py`, `installer.py`, `setup_wizard.py` | `--doctor`, `--install-mpv`, `--setup` |

Only the one selected video is ever served, and only at `127.0.0.1`. `Range` requests are validated (`416` for
out-of-bounds, `400` for malformed); chunks are forwarded as they arrive, so memory stays flat for any file size.

## Security

- The HTTP server binds **only** to `127.0.0.1`; it serves exactly one path for exactly one media object.
- No `shell=True` / `os.system()` anywhere; mpv and the mpv installer are started with argument lists.
- Credentials and the session live only in the config directory (owner-only file permissions where supported). The Telegram session, API hash, login codes and 2FA password are never logged or printed (not even with `--debug`).
- The server and mpv are stopped when you quit, press `Ctrl+C`, or close the terminal.

## Troubleshooting

Start with `tg-mpv --doctor`: it checks Python, libraries, mpv, credentials, the session, the bot and your saved data,
and says how to fix each problem.

- **"Telegram credentials are missing"** — run `tg-mpv --setup`.
- **"Telegram session is not authorized"** — run `tg-mpv --login`.
- **"mpv was not found"** — run `tg-mpv --install-mpv`, or set `MPV`.
- **"Another tg-mpv instance is already running"** — only one tg-mpv can use the session at a time; close the other
  one (the message shows its PID).
- **"No playable video was found"** — tg-mpv already retries reworded queries; run with `--debug` to see exactly what the
  bot sent.

## Limitations

- Bots differ. tg-mpv uses generic detection of videos, buttons and "load more", and learns your bot's behaviour, but a
  bot with an unusual interface may need a small adjustment in `bot.py` (all bot-specific logic lives there).
- Telegram applies its own rate limits to downloads; very aggressive seeking can be throttled.
- On Windows, resume-position tracking talks to mpv through a named pipe; if that fails, playback still works and only
  "resume" is skipped. `Ctrl+Z` handling exists on Linux/macOS only; use `Ctrl+C` on Windows.
- Skip-intro is a remembered start time you chose earlier, not automatic intro detection.
- You are responsible for complying with Telegram's Terms of Service and the law where you live; tg-mpv only accesses
  content exposed by the bot you choose.

## Development

```bash
git clone https://github.com/quillai-dev/tg-mpv.git
cd tg-mpv
python -m pip install -e ".[dev]"
python -m pytest
```

The tests need no Telegram account or network. CI runs them on Linux, macOS and Windows.

**Releasing** (maintainers): bump `__version__` in `tg_mpv/__init__.py` and add a line to `CHANGELOG.md`, push, then
create a GitHub Release — the `publish` workflow builds the package and uploads it to PyPI.
Check a build locally with `python -m build && python -m twine check dist/*`.

## Author

**Quillai Mohammed Eisa** — <quillai.dev@gmail.com> — [github.com/quillai-dev](https://github.com/quillai-dev)

Repository: <https://github.com/quillai-dev/tg-mpv> · Issues: <https://github.com/quillai-dev/tg-mpv/issues>

## License

GPL-3.0-or-later — see [LICENSE](https://github.com/quillai-dev/tg-mpv/blob/main/LICENSE).
