Download bot/command/subtitle.py from nexus33rd/myapp: direct link, hf CLI and curl.
- Browser
- Download file 63.8 kB
-
https://huggingface.co/spaces/nexus33rd/myapp/resolve/main/bot/command/subtitle.py
- Command line
-
hf download hf://spaces/nexus33rd/myapp/bot/command/subtitle.py
-
curl -L -o subtitle.py https://huggingface.co/spaces/nexus33rd/myapp/resolve/main/bot/command/subtitle.py
63.8 kB
"""
SubSource Subtitle Downloader Module for Telegram Bot.
Provides:
- Movie and TV series search with automatic Season grouping (Season 1, 2, etc.)
- Interactive Season selection sub-menu for TV series
- Interactive subtitle pagination with continuous numbering across pages
- Per-language country flag emojis for all SubSource languages (including 'All' mode)
- Automatic ZIP cleanup (leaves only extracted subtitle files in /downloads)
- Multi-file series pack handling (sends all episode subtitle files to Telegram)
- Post-download confirmation prompt (choice to send to chat or keep on server)
"""
import asyncio
import html
import io
import math
import os
import re
import tempfile
import time
import zipfile
from pathlib import Path
from typing import Any
import requests
from pyrogram import Client, filters
from pyrogram.enums import ParseMode
from pyrogram.errors import FloodWait, MessageNotModified
from pyrogram.types import (
CallbackQuery,
InlineKeyboardButton,
InlineKeyboardMarkup,
LinkPreviewOptions,
Message,
)
from .. import LOGGER
from ..helper.ext_utils.bot_utils import new_task
try:
from app import DOWNLOAD_PATH
except ImportError:
DOWNLOAD_PATH = os.getenv("QBITTORRENT_SAVE_PATH", "/downloads")
# ==============================================================================
# KONFIGURASI SUBSOURCE API & BAHASA
# ==============================================================================
API_KEY = os.getenv(
"SUBSOURCE_API_KEY",
"sk_e643a06714b5b587c9fac35d263499df0729c68471ebb848576072228ba52c9b",
)
BASE_URL = os.getenv("SUBSOURCE_BASE_URL", "https://api.subsource.net/api/v1")
HEADERS = {
"X-API-Key": API_KEY,
"Accept": "application/json",
"User-Agent": "TelegramBot-SubSource/1.0",
}
# Bahasa yang didukung untuk filter cepat tombol navigasi
LANGUAGE_OPTIONS = [
("id", "indonesian", "๐ฎ๐ฉ Indo"),
("en", "english", "๐ฌ๐ง Eng"),
("all", "all", "๐ Semua"),
]
LANG_CODE_TO_NAME = {code: name for code, name, _ in LANGUAGE_OPTIONS}
LANG_NAME_TO_CODE = {name: code for code, name, _ in LANGUAGE_OPTIONS}
# Pemetaan lengkap bahasa ke emoji bendera negara dari API SubSource
LANGUAGE_FLAG_MAP: dict[str, str] = {
"indonesian": "๐ฎ๐ฉ",
"id": "๐ฎ๐ฉ",
"english": "๐ฌ๐ง",
"en": "๐ฌ๐ง",
"arabic": "๐ธ๐ฆ",
"ar": "๐ธ๐ฆ",
"spanish": "๐ช๐ธ",
"es": "๐ช๐ธ",
"french": "๐ซ๐ท",
"fr": "๐ซ๐ท",
"german": "๐ฉ๐ช",
"de": "๐ฉ๐ช",
"italian": "๐ฎ๐น",
"it": "๐ฎ๐น",
"portuguese": "๐ต๐น",
"pt": "๐ต๐น",
"portuguese-br": "๐ง๐ท",
"brazilian": "๐ง๐ท",
"russian": "๐ท๐บ",
"ru": "๐ท๐บ",
"japanese": "๐ฏ๐ต",
"ja": "๐ฏ๐ต",
"korean": "๐ฐ๐ท",
"ko": "๐ฐ๐ท",
"chinese": "๐จ๐ณ",
"zh": "๐จ๐ณ",
"chinese-traditional": "๐น๐ผ",
"turkish": "๐น๐ท",
"tr": "๐น๐ท",
"vietnamese": "๐ป๐ณ",
"vi": "๐ป๐ณ",
"thai": "๐น๐ญ",
"th": "๐น๐ญ",
"hindi": "๐ฎ๐ณ",
"hi": "๐ฎ๐ณ",
"bengali": "๐ง๐ฉ",
"bn": "๐ง๐ฉ",
"malay": "๐ฒ๐พ",
"ms": "๐ฒ๐พ",
"dutch": "๐ณ๐ฑ",
"nl": "๐ณ๐ฑ",
"polish": "๐ต๐ฑ",
"pl": "๐ต๐ฑ",
"swedish": "๐ธ๐ช",
"sv": "๐ธ๐ช",
"norwegian": "๐ณ๐ด",
"no": "๐ณ๐ด",
"danish": "๐ฉ๐ฐ",
"da": "๐ฉ๐ฐ",
"finnish": "๐ซ๐ฎ",
"fi": "๐ซ๐ฎ",
"greek": "๐ฌ๐ท",
"el": "๐ฌ๐ท",
"hebrew": "๐ฎ๐ฑ",
"he": "๐ฎ๐ฑ",
"romanian": "๐ท๐ด",
"ro": "๐ท๐ด",
"hungarian": "๐ญ๐บ",
"hu": "๐ญ๐บ",
"czech": "๐จ๐ฟ",
"cs": "๐จ๐ฟ",
"slovak": "๐ธ๐ฐ",
"sk": "๐ธ๐ฐ",
"ukrainian": "๐บ๐ฆ",
"uk": "๐บ๐ฆ",
"bulgarian": "๐ง๐ฌ",
"bg": "๐ง๐ฌ",
"croatian": "๐ญ๐ท",
"hr": "๐ญ๐ท",
"serbian": "๐ท๐ธ",
"sr": "๐ท๐ธ",
"bosnian": "๐ง๐ฆ",
"bs": "๐ง๐ฆ",
"slovenian": "๐ธ๐ฎ",
"sl": "๐ธ๐ฎ",
"tagalog": "๐ต๐ญ",
"filipino": "๐ต๐ญ",
"tl": "๐ต๐ญ",
"persian": "๐ฎ๐ท",
"farsi": "๐ฎ๐ท",
"farsi_persian": "๐ฎ๐ท",
"fa": "๐ฎ๐ท",
"urdu": "๐ต๐ฐ",
"ur": "๐ต๐ฐ",
"tamil": "๐ฎ๐ณ",
"ta": "๐ฎ๐ณ",
"telugu": "๐ฎ๐ณ",
"te": "๐ฎ๐ณ",
"malayalam": "๐ฎ๐ณ",
"ml": "๐ฎ๐ณ",
"kannada": "๐ฎ๐ณ",
"kn": "๐ฎ๐ณ",
"marathi": "๐ฎ๐ณ",
"mr": "๐ฎ๐ณ",
"estonian": "๐ช๐ช",
"et": "๐ช๐ช",
"latvian": "๐ฑ๐ป",
"lv": "๐ฑ๐ป",
"lithuanian": "๐ฑ๐น",
"lt": "๐ฑ๐น",
"albanian": "๐ฆ๐ฑ",
"sq": "๐ฆ๐ฑ",
"macedonian": "๐ฒ๐ฐ",
"mk": "๐ฒ๐ฐ",
"icelandic": "๐ฎ๐ธ",
"is": "๐ฎ๐ธ",
"georgian": "๐ฌ๐ช",
"ka": "๐ฌ๐ช",
"armenian": "๐ฆ๐ฒ",
"hy": "๐ฆ๐ฒ",
"azerbaijani": "๐ฆ๐ฟ",
"az": "๐ฆ๐ฟ",
"kazakh": "๐ฐ๐ฟ",
"kk": "๐ฐ๐ฟ",
"uzbek": "๐บ๐ฟ",
"uz": "๐บ๐ฟ",
"mongolian": "๐ฒ๐ณ",
"mn": "๐ฒ๐ณ",
"burmese": "๐ฒ๐ฒ",
"my": "๐ฒ๐ฒ",
"khmer": "๐ฐ๐ญ",
"km": "๐ฐ๐ญ",
"lao": "๐ฑ๐ฆ",
"lo": "๐ฑ๐ฆ",
"sinhala": "๐ฑ๐ฐ",
"si": "๐ฑ๐ฐ",
"nepali": "๐ณ๐ต",
"ne": "๐ณ๐ต",
"swahili": "๐น๐ฟ",
"sw": "๐น๐ฟ",
"afrikaans": "๐ฟ๐ฆ",
"af": "๐ฟ๐ฆ",
}
SUB_EXTENSIONS = (".srt", ".ass", ".vtt", ".sub")
ITEMS_PER_PAGE = 5
MOVIE_ITEMS_PER_PAGE = 6
SESSION_TTL_SECONDS = 3600 # 1 jam
AUTO_CLOSE_SECONDS = 120 # 2 menit batas auto-close jika tidak ada aktivitas
# Penyimpanan sesi pencarian: key = f"{chat_id}_{message_id}"
SEARCH_SESSIONS: dict[str, dict[str, Any]] = {}
# Cache subtitle per film & bahasa: key = f"{movie_id}_{lang}"
SUBTITLE_CACHE: dict[str, dict[str, Any]] = {}
# Cache file subtitle yang telah diunduh: key = str(sub_id)
DOWNLOADED_SUBS: dict[str, dict[str, Any]] = {}
# Task auto-close pesan subtitle per session: key = f"{chat_id}_{message_id}"
AUTO_CLOSE_TASKS: dict[str, asyncio.Task] = {}
def cancel_auto_close(chat_id: int, message_id: int) -> None:
"""Membatalkan task auto-close jika ada interaksi baru atau pesan ditutup."""
key = f"{chat_id}_{message_id}"
task = AUTO_CLOSE_TASKS.pop(key, None)
if task and not task.done():
task.cancel()
def schedule_auto_close(
client: Client,
chat_id: int,
message_id: int,
delay: int = AUTO_CLOSE_SECONDS,
temp_zip_to_clean: str | None = None,
) -> None:
"""Menjadwalkan penutupan otomatis (hapus pesan) setelah delay detik tanpa aktivitas."""
key = f"{chat_id}_{message_id}"
cancel_auto_close(chat_id, message_id)
async def _auto_close_worker():
try:
await asyncio.sleep(delay)
# Bersihkan sesi dari memori
SEARCH_SESSIONS.pop(key, None)
AUTO_CLOSE_TASKS.pop(key, None)
# Hapus file temporary zip jika ada
if temp_zip_to_clean and os.path.exists(temp_zip_to_clean):
try:
os.remove(temp_zip_to_clean)
except Exception:
pass
# Hapus pesan dari chat Telegram agar chat tetap bersih
try:
await client.delete_messages(chat_id=chat_id, message_ids=message_id)
LOGGER.info("Pesan %s berhasil ditutup otomatis setelah %s detik tanpa aktivitas.", key, delay)
except Exception as del_err:
LOGGER.debug("Gagal auto-delete pesan %s: %s", key, del_err)
except asyncio.CancelledError:
pass
except Exception as exc:
LOGGER.debug("Exception di auto_close_worker (%s): %s", key, exc)
AUTO_CLOSE_TASKS[key] = asyncio.create_task(_auto_close_worker())
def get_language_flag(lang_str: str | None) -> str:
"""Mengembalikan emoji bendera negara berdasarkan nama atau kode bahasa SubSource."""
if not lang_str:
return "๐"
cleaned = lang_str.strip().lower()
return LANGUAGE_FLAG_MAP.get(cleaned, "๐")
def natural_sort_key(s: str) -> list[Any]:
"""Sort key untuk mengurutkan file episode secara alami (misal ep 1, ep 2, ep 10)."""
return [int(text) if text.isdigit() else text.lower() for text in re.split(r"(\d+)", s)]
def get_download_dir() -> str:
"""Mendapatkan direktori tujuan penyimpanan unduhan subtitle."""
target = os.getenv("SUB_DOWNLOAD_DIR") or DOWNLOAD_PATH or "/downloads"
try:
os.makedirs(target, exist_ok=True)
return target
except Exception as exc:
LOGGER.warning("Gagal membuat direktori %s: %s. Fallback ke downloads lokal.", target, exc)
fallback = os.path.abspath("downloads")
os.makedirs(fallback, exist_ok=True)
return fallback
def clean_filename(filename: str) -> str:
"""Membersihkan karakter terlarang dari nama file."""
return re.sub(r'[\\/*?:"<>|]', "", filename).strip()
def extract_imdb_id(user_input: str) -> str | None:
"""Mengekstrak ID IMDb (misal: tt1375666) dari teks atau URL IMDb."""
match = re.search(r"(tt\d{7,8})", user_input.strip())
return match.group(1) if match else None
def format_bytes(size: int | float | None) -> str:
"""Format ukuran byte ke satuan yang mudah dibaca manusia."""
if size is None or size <= 0:
return "0 B"
power = 1024
n = 0
labels = {0: "B", 1: "KiB", 2: "MiB", 3: "GiB"}
val = float(size)
while val >= power and n < len(labels) - 1:
val /= power
n += 1
return f"{val:.2f} {labels[n]}"
def clean_html_text(text: str) -> str:
"""
Membersihkan teks dari entitas HTML ganda/karakter ilegal bawaan API,
dan meng-escape untuk Telegram HTML parser agar tidak menyebabkan 400 Bad Request.
"""
if not text:
return ""
unescaped = html.unescape(str(text))
stripped = re.sub(r"<[^>]+>", "", unescaped)
return html.escape(stripped.strip())
def cleanup_old_sessions() -> None:
"""Membersihkan sesi lama yang sudah kadaluarsa dari memori."""
now = time.time()
expired_keys = [
k for k, v in SEARCH_SESSIONS.items() if now - v.get("timestamp", 0) > SESSION_TTL_SECONDS
]
for k in expired_keys:
SEARCH_SESSIONS.pop(k, None)
expired_dl = [
k for k, v in DOWNLOADED_SUBS.items() if now - v.get("timestamp", 0) > SESSION_TTL_SECONDS
]
for k in expired_dl:
item = DOWNLOADED_SUBS.pop(k, None)
if item and item.get("zip_path") and os.path.exists(item["zip_path"]):
try:
os.remove(item["zip_path"])
except Exception:
pass
async def safe_edit_message(
target: Message | CallbackQuery,
text: str,
reply_markup: InlineKeyboardMarkup | None = None,
auto_close: bool = True,
) -> bool:
"""Mengubah teks pesan Telegram secara aman dengan fallback ke plain text jika HTML error."""
msg = target.message if isinstance(target, CallbackQuery) else target
if len(text) > 4000:
text = text[:3850] + "\n... [Teks dipotong karena melebihi batas Telegram]"
try:
await msg.edit_text(
text,
reply_markup=reply_markup,
link_preview_options=LinkPreviewOptions(is_disabled=True),
parse_mode=ParseMode.HTML,
)
if auto_close and hasattr(msg, "_client") and msg._client:
schedule_auto_close(msg._client, msg.chat.id, msg.id)
return True
except MessageNotModified:
if auto_close and hasattr(msg, "_client") and msg._client:
schedule_auto_close(msg._client, msg.chat.id, msg.id)
return True
except FloodWait as exc:
await asyncio.sleep(int(exc.value) + 1)
return await safe_edit_message(target, text, reply_markup=reply_markup, auto_close=auto_close)
except Exception as exc:
LOGGER.warning("safe_edit_message: gagal kirim HTML (%s), mencoba plain text...", exc)
try:
plain_text = re.sub(r"<[^>]+>", "", text)
await msg.edit_text(
plain_text,
reply_markup=reply_markup,
link_preview_options=LinkPreviewOptions(is_disabled=True),
parse_mode=None,
)
if auto_close and hasattr(msg, "_client") and msg._client:
schedule_auto_close(msg._client, msg.chat.id, msg.id)
return True
except MessageNotModified:
if auto_close and hasattr(msg, "_client") and msg._client:
schedule_auto_close(msg._client, msg.chat.id, msg.id)
return True
except Exception as fallback_exc:
LOGGER.error("safe_edit_message fallback juga gagal: %s", fallback_exc)
return False
# ==============================================================================
# API & DATA STRUCTURING (SERIES & SEASON GROUPING)
# ==============================================================================
def search_movies(query: str, imdb_id: str | None = None) -> list[dict[str, Any]]:
"""Mencari film/serial di API SubSource berdasarkan judul atau IMDb ID."""
url = f"{BASE_URL}/movies/search"
if imdb_id:
params = {"searchType": "imdb", "imdb": imdb_id}
else:
params = {"searchType": "text", "q": query}
try:
response = requests.get(url, headers=HEADERS, params=params, timeout=15)
if response.status_code == 400 and not imdb_id:
for fallback_key in ["query", "search", "title"]:
res_fallback = requests.get(
url, headers=HEADERS, params={"searchType": "text", fallback_key: query}, timeout=15
)
if res_fallback.status_code == 200:
response = res_fallback
break
if response.status_code != 200:
LOGGER.error("SubSource movie search error status %s: %s", response.status_code, response.text)
return []
data = response.json()
if isinstance(data, dict):
items = data.get("data", data.get("results", []))
elif isinstance(data, list):
items = data
else:
items = []
return items if isinstance(items, list) else [items]
except Exception as exc:
LOGGER.error("Exception in search_movies: %s", exc)
return []
def group_movies_and_series(raw_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""
Mengelompokkan hasil pencarian SubSource:
- Serial TV dengan musim berbeda digabungkan ke 1 entri judul dengan sub-daftar seasons.
- Film biasa tetap sebagai entri tersendiri.
"""
grouped: list[dict[str, Any]] = []
series_map: dict[str, dict[str, Any]] = {}
for m in raw_items:
m_type = (m.get("type") or "movie").lower()
season = m.get("season")
is_tv = (m_type in ("tvseries", "tv", "show")) or (season is not None)
if is_tv:
imdb_id = m.get("imdbId")
clean_title = (m.get("title") or "").strip().lower()
year = m.get("releaseYear") or m.get("year", "")
key = f"imdb_{imdb_id}" if imdb_id else f"title_{clean_title}_{year}"
if key in series_map:
series_map[key]["seasons"].append(m)
else:
entry = {
"is_series": True,
"group_id": key,
"title": m.get("title") or m.get("name", "Unknown"),
"releaseYear": year,
"imdbId": imdb_id,
"type": "tvseries",
"seasons": [m],
}
series_map[key] = entry
grouped.append(entry)
else:
m_copy = dict(m)
m_copy["is_series"] = False
grouped.append(m_copy)
# Urutkan season untuk setiap series (Season 1, 2, ...) dan abaikan Season 0 jika ada season > 0
for g in grouped:
if g.get("is_series"):
valid_seasons = [
s for s in g["seasons"]
if s.get("season") not in (0, "0", None) and int(s.get("season", 0)) > 0
]
if valid_seasons:
g["seasons"] = valid_seasons
def season_sort_key(s: dict[str, Any]) -> int:
s_val = s.get("season")
try:
return int(s_val) if s_val is not None else 999
except Exception:
return 999
g["seasons"].sort(key=season_sort_key)
return grouped
def get_subtitles(movie_id: int, language: str = "indonesian") -> list[dict[str, Any]]:
"""Mengambil daftar subtitle dari API SubSource untuk movie_id tertentu."""
cache_key = f"{movie_id}_{language.lower()}"
cached = SUBTITLE_CACHE.get(cache_key)
if cached and time.time() - cached.get("timestamp", 0) < 600:
return cached.get("subtitles", [])
url = f"{BASE_URL}/subtitles"
params: dict[str, Any] = {
"movieId": movie_id,
"limit": 100,
"sort": "popular",
}
if language.lower() != "all":
params["language"] = language.lower()
try:
response = requests.get(url, headers=HEADERS, params=params, timeout=15)
if response.status_code != 200:
LOGGER.error("SubSource get_subtitles error status %s: %s", response.status_code, response.text)
return []
data = response.json()
subs = data.get("data", []) if isinstance(data, dict) else data
if not isinstance(subs, list):
subs = []
if language.lower() != "all":
subs = [
s for s in subs
if (s.get("language") or "").strip().lower() == language.lower()
]
SUBTITLE_CACHE[cache_key] = {"subtitles": subs, "timestamp": time.time()}
return subs
except Exception as exc:
LOGGER.error("Exception in get_subtitles: %s", exc)
return []
def download_subtitle_file(subtitle_id: int, movie_title: str = "movie") -> dict[str, Any]:
"""
Mengunduh file arsip ZIP subtitle dari SubSource API:
- Mengekstrak semua file subtitle (.srt, .ass, dll) ke /downloads
- File ZIP diunduh ke folder temporary OS (bukan di /downloads)
- Mengurutkan file episode secara alami (Episode 1, 2, ... 25)
- Jika series pack (> 1 file), path file ZIP disimpan sementara untuk dikirim langsung ke Telegram jika diminta
- Jika single movie (1 file), file ZIP temporary langsung dihapus
- Mengembalikan daftar seluruh file subtitle yang diekstrak.
"""
url = f"{BASE_URL}/subtitles/{subtitle_id}/download"
try:
response = requests.get(url, headers=HEADERS, stream=True, timeout=40)
except Exception as exc:
return {"ok": False, "error": f"Koneksi ke SubSource gagal: {exc}"}
if response.status_code != 200:
LOGGER.error("SubSource download error status %s: %s", response.status_code, response.text)
return {"ok": False, "error": f"API mengembalikan status {response.status_code}: {response.text[:200]}"}
content_disposition = response.headers.get("content-disposition", "")
filename = f"{clean_filename(movie_title)}_{subtitle_id}.zip"
if "filename=" in content_disposition:
matched = re.findall(r'filename=["\']?([^"\';]+)["\']?', content_disposition)
if matched:
filename = matched[0]
filename = clean_filename(filename)
if not filename.endswith(".zip"):
filename += ".zip"
# Simpan arsip ZIP di folder temporary OS agar tidak mengotori /downloads
temp_dir = tempfile.gettempdir()
temp_zip_path = os.path.join(temp_dir, filename)
try:
with open(temp_zip_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
except Exception as exc:
LOGGER.error("Gagal menulis file subtitle ke disk: %s", exc)
return {"ok": False, "error": f"Gagal menyimpan file ke temporary disk: {exc}"}
download_dir = get_download_dir()
all_extracted: list[str] = []
# Ekstraksi seluruh isi zip langsung ke download_dir (/downloads)
try:
if zipfile.is_zipfile(temp_zip_path):
with zipfile.ZipFile(temp_zip_path, "r") as zip_ref:
for member in zip_ref.namelist():
member_name = os.path.basename(member)
if not member_name:
continue
extracted_path = os.path.join(download_dir, clean_filename(member_name))
with zip_ref.open(member) as source, open(extracted_path, "wb") as target:
target.write(source.read())
all_extracted.append(extracted_path)
except Exception as exc:
LOGGER.warning("Gagal mengekstrak isi zip subtitle: %s", exc)
# Filter khusus file subtitle asli
subtitle_files = [f for f in all_extracted if f.lower().endswith(SUB_EXTENSIONS)]
if not subtitle_files:
subtitle_files = all_extracted
# Urutkan episode secara alami
subtitle_files.sort(key=lambda p: natural_sort_key(os.path.basename(p)))
# Jika hanya 1 file (film), hapus zip temp sekarang karena cukup kirim file subtitle langsung
if len(subtitle_files) <= 1:
try:
if os.path.exists(temp_zip_path):
os.remove(temp_zip_path)
except Exception:
pass
zip_for_sending = None
else:
# Jika series (> 1 file), simpan path temp zip untuk dikirim langsung ke Telegram chat
zip_for_sending = temp_zip_path
# Hitung total ukuran file subtitle
total_size = sum(os.path.getsize(f) for f in subtitle_files if os.path.exists(f))
primary_file = subtitle_files[0] if subtitle_files else ""
return {
"ok": True,
"filename": os.path.basename(primary_file) if primary_file else filename,
"primary_file": primary_file,
"files": subtitle_files,
"total_files": len(subtitle_files),
"size": total_size,
"download_dir": download_dir,
"zip_path": zip_for_sending,
"zip_name": filename,
}
# ==============================================================================
# UI & KEYBOARD BUILDERS
# ==============================================================================
def build_movies_keyboard(grouped_items: list[dict[str, Any]], page: int = 1) -> InlineKeyboardMarkup:
"""Membuat keyboard daftar hasil pencarian film & serial (dengan label rapi anti overflow)."""
total_items = len(grouped_items)
total_pages = max(1, math.ceil(total_items / MOVIE_ITEMS_PER_PAGE))
page = max(1, min(page, total_pages))
start_idx = (page - 1) * MOVIE_ITEMS_PER_PAGE
end_idx = min(start_idx + MOVIE_ITEMS_PER_PAGE, total_items)
page_items = grouped_items[start_idx:end_idx]
rows: list[list[InlineKeyboardButton]] = []
for idx, item in enumerate(page_items, start=start_idx + 1):
title = item.get("title") or item.get("name", "Unknown")
year = item.get("releaseYear") or item.get("year", "")
year_str = f" ({year})" if year else ""
# Format judul bersih tanpa label season di samping judul (contoh: Attack on Titan (2013))
raw_label = f"๐ฌ {idx}. {title}{year_str}"
if len(raw_label) > 34:
button_label = raw_label[:31] + "..."
else:
button_label = raw_label
if item.get("is_series"):
rows.append([InlineKeyboardButton(button_label, callback_data=f"sub_series:{idx - 1}")])
else:
m_id = item.get("movieId") or item.get("id")
rows.append([InlineKeyboardButton(button_label, callback_data=f"sub_m:{m_id}")])
# Baris navigasi jika lebih dari 1 halaman
if total_pages > 1:
nav_row: list[InlineKeyboardButton] = []
if page > 1:
nav_row.append(InlineKeyboardButton("โ๏ธ Prev", callback_data=f"sub_mp:{page - 1}"))
nav_row.append(InlineKeyboardButton(f"๐ {page}/{total_pages}", callback_data="sub_noop"))
if page < total_pages:
nav_row.append(InlineKeyboardButton("Next โถ๏ธ", callback_data=f"sub_mp:{page + 1}"))
rows.append(nav_row)
rows.append([InlineKeyboardButton("โ Tutup", callback_data="sub_close")])
return InlineKeyboardMarkup(rows)
def build_seasons_keyboard(series: dict[str, Any]) -> InlineKeyboardMarkup:
"""Membuat keyboard sub-pemilihan Season untuk serial TV (tanpa Season 0)."""
raw_seasons = series.get("seasons", [])
seasons = [s for s in raw_seasons if s.get("season") not in (0, "0", None) and int(s.get("season", 0)) > 0]
if not seasons:
seasons = raw_seasons
rows: list[list[InlineKeyboardButton]] = []
current_row: list[InlineKeyboardButton] = []
for s in seasons:
s_num = s.get("season")
m_id = s.get("movieId") or s.get("id")
if s_num is not None and int(s_num) != 0:
label = f"๐บ Season {s_num}"
current_row.append(InlineKeyboardButton(label, callback_data=f"sub_m:{m_id}"))
if len(current_row) == 2:
rows.append(current_row)
current_row = []
if current_row:
rows.append(current_row)
rows.append([
InlineKeyboardButton("๐ Daftar Judul", callback_data="sub_back"),
InlineKeyboardButton("โ Tutup", callback_data="sub_close"),
])
return InlineKeyboardMarkup(rows)
def format_seasons_message(series: dict[str, Any]) -> str:
"""Format teks pesan menu pemilihan Season serial TV (tanpa Specials / Season 0)."""
title = series.get("title") or series.get("name", "Unknown")
year = series.get("releaseYear") or series.get("year", "")
year_str = f" ({year})" if year else ""
imdb_id = series.get("imdbId")
raw_seasons = series.get("seasons", [])
seasons = [s for s in raw_seasons if s.get("season") not in (0, "0", None) and int(s.get("season", 0)) > 0]
if not seasons:
seasons = raw_seasons
lines = [
f"๐ฌ <b>{clean_html_text(title)}{year_str}</b>",
f"๐ญ Tipe: <code>TV Series</code>" + (f" | โญ IMDb: <code>{imdb_id}</code>" if imdb_id else ""),
"",
f"๐บ <b>Daftar Season ({len(seasons)}):</b>",
]
for s in seasons:
s_num = s.get("season")
if s_num in (0, "0", None) or int(s_num) == 0:
continue
sub_cnt = s.get("subtitleCount")
cnt_info = f" <i>({sub_cnt} subs)</i>" if sub_cnt else ""
lines.append(f" โข Season {s_num}{cnt_info}")
lines.append("")
lines.append("<i>Silakan pilih Season di bawah untuk melihat daftar subtitle:</i>")
return "\n".join(lines)
def build_subtitles_keyboard(
subtitles: list[dict[str, Any]],
current_lang: str,
page: int = 1,
has_seasons: bool = False,
has_multiple_movies: bool = False,
) -> InlineKeyboardMarkup:
"""
Membuat keyboard interaktif pemilihan subtitle:
- Tombol filter bahasa (Indo / English / Semua)
- Tombol nomor download berkelanjutan (#1, #2 ... #6, dst.)
- Tombol paginasi (Prev / Page / Next)
- Tombol kembali (Ganti Season / Daftar Judul) dan Tutup
"""
total_items = len(subtitles)
total_pages = max(1, math.ceil(total_items / ITEMS_PER_PAGE))
page = max(1, min(page, total_pages))
start_idx = (page - 1) * ITEMS_PER_PAGE
end_idx = min(start_idx + ITEMS_PER_PAGE, total_items)
page_subtitles = subtitles[start_idx:end_idx]
rows: list[list[InlineKeyboardButton]] = []
# Row 1: Filter Bahasa
lang_row: list[InlineKeyboardButton] = []
for code, name, label in LANGUAGE_OPTIONS:
active_mark = "โ
" if current_lang == code or current_lang == name else ""
lang_row.append(
InlineKeyboardButton(
f"{active_mark}{label}",
callback_data=f"sub_l:{code}",
)
)
rows.append(lang_row)
# Row 2: Tombol nomor subtitle berurutan sesuai nomor di pesan
if page_subtitles:
select_row: list[InlineKeyboardButton] = []
for idx, sub in enumerate(page_subtitles, start=start_idx + 1):
sub_id = sub.get("subtitleId") or sub.get("id")
select_row.append(
InlineKeyboardButton(
f"#{idx}",
callback_data=f"sub_dl:{sub_id}",
)
)
rows.append(select_row)
# Row 3: Navigasi Paginasi
nav_row: list[InlineKeyboardButton] = []
if page > 1:
nav_row.append(InlineKeyboardButton("โ๏ธ Prev", callback_data=f"sub_p:{page - 1}:{current_lang}"))
nav_row.append(InlineKeyboardButton(f"๐ {page}/{total_pages}", callback_data="sub_noop"))
if page < total_pages:
nav_row.append(InlineKeyboardButton("Next โถ๏ธ", callback_data=f"sub_p:{page + 1}:{current_lang}"))
rows.append(nav_row)
# Row 4: Kontrol Bawah (Kembali ke Season / Film, dan Tutup)
bottom_row: list[InlineKeyboardButton] = []
if has_seasons:
bottom_row.append(InlineKeyboardButton("๐ Ganti Season", callback_data="sub_seasons"))
elif has_multiple_movies:
bottom_row.append(InlineKeyboardButton("๐ Daftar Judul", callback_data="sub_back"))
bottom_row.append(InlineKeyboardButton("โ Tutup", callback_data="sub_close"))
rows.append(bottom_row)
return InlineKeyboardMarkup(rows)
def format_subtitles_message(
movie: dict[str, Any],
subtitles: list[dict[str, Any]],
current_lang: str,
page: int = 1,
) -> str:
"""Format teks pesan daftar subtitle dengan emoji bendera negara per bahasa."""
title = movie.get("title") or movie.get("name", "Unknown Title")
year = movie.get("releaseYear") or movie.get("year", "")
year_str = f" ({year})" if year else ""
imdb_id = movie.get("imdbId") or movie.get("imdb", "")
m_type = movie.get("type", "movie").capitalize()
season = movie.get("season")
season_str = f" - Season {season}" if (season is not None and season != 0) else (" - Specials" if season == 0 else "")
total_items = len(subtitles)
total_pages = max(1, math.ceil(total_items / ITEMS_PER_PAGE))
page = max(1, min(page, total_pages))
lang_display = {
"id": "Bahasa Indonesia ๐ฎ๐ฉ",
"indonesian": "Bahasa Indonesia ๐ฎ๐ฉ",
"en": "English ๐ฌ๐ง",
"english": "English ๐ฌ๐ง",
"all": "Semua Bahasa ๐",
}.get(current_lang.lower(), f"{current_lang.capitalize()} {get_language_flag(current_lang)}")
lines = [
f"๐ฌ <b>{clean_html_text(title)}{year_str}{season_str}</b>",
f"๐ญ Tipe: <code>{m_type}</code>" + (f" | โญ IMDb: <code>{imdb_id}</code>" if imdb_id else ""),
f"๐ Filter: <b>{lang_display}</b> | Total: <b>{total_items} subtitle</b>",
f"๐ Halaman: <b>{page} / {total_pages}</b>",
"",
]
if not subtitles:
lines.append("<i>โ Tidak ada subtitle yang ditemukan untuk filter bahasa ini.</i>")
lines.append("<i>Silakan klik tombol filter bahasa lain di bawah (misal: English atau Semua).</i>")
return "\n".join(lines)
start_idx = (page - 1) * ITEMS_PER_PAGE
end_idx = min(start_idx + ITEMS_PER_PAGE, total_items)
page_subtitles = subtitles[start_idx:end_idx]
for idx, sub in enumerate(page_subtitles, start=start_idx + 1):
sub_lang = (sub.get("language") or "").strip().lower()
flag = get_language_flag(sub_lang)
downloads = sub.get("downloads", 0)
rating = sub.get("rating") or {}
good_votes = rating.get("good", 0)
bad_votes = rating.get("bad", 0)
release_info = sub.get("releaseInfo")
if isinstance(release_info, list) and release_info:
rel_str = ", ".join(release_info)
else:
rel_str = str(release_info) if release_info else "Standard Release"
if len(rel_str) > 130:
rel_str = rel_str[:127] + "..."
commentary = (sub.get("commentary") or "").strip()
if not commentary:
commentary = "-"
elif len(commentary) > 150:
commentary = commentary[:147] + "..."
lines.extend([
f"#{idx} {flag}",
f"<b>Release Name:</b> <code>{clean_html_text(rel_str)}</code>",
f"<b>Deskripsi:</b> <code>{clean_html_text(commentary)}</code>",
f"<b>Total unduhan:</b> <code>{downloads}</code>",
f"<b>Vote:</b> Good {good_votes} | Bad {bad_votes}",
"",
])
lines.append("<i>Pilih nomor subtitle di bawah untuk mengunduh:</i>")
return "\n".join(lines)
# ==============================================================================
# TELEGRAM HANDLERS (MESSAGE & CALLBACK)
# ==============================================================================
@new_task
async def subtitle_command(client: Client, message: Message):
"""
Handler perintah /subtitle <keyword atau IMDb link/ID>.
Mencari film/serial di SubSource dan menampilkan menu interaktif.
"""
text = message.text or message.caption or ""
parts = text.split(maxsplit=1)
query = parts[1].strip() if len(parts) > 1 else ""
if not query and message.reply_to_message:
reply_text = message.reply_to_message.text or message.reply_to_message.caption or ""
query = reply_text.strip()
if not query:
cmd_prefix = parts[0].lstrip("/") if parts else "subtitle"
return await message.reply_text(
f"๐ฌ <b>SubSource Subtitle Downloader</b>\n\n"
f"Gunakan perintah ini untuk mencari dan mendownload subtitle film/serial dari SubSource.\n\n"
f"<b>Format Penggunaan:</b>\n"
f"โข <code>/{cmd_prefix} <judul film / show></code>\n"
f"โข <code>/{cmd_prefix} <IMDb ID></code> (misal: <code>tt1375666</code>)\n"
f"โข <code>/{cmd_prefix} <link IMDb></code>\n\n"
f"<b>Contoh:</b>\n"
f"โข <code>/{cmd_prefix} Attack on Titan</code>\n"
f"โข <code>/{cmd_prefix} Inception</code>\n"
f"โข <code>/{cmd_prefix} tt0848228</code>\n\n"
f"<i>Output file akan otomatis diekstrak dan disimpan ke folder <code>/downloads</code>.</i>",
parse_mode=ParseMode.HTML,
)
status_msg = await message.reply_text(
f"๐ <b>Mencari film/serial:</b> <code>{html.escape(query)}</code>...",
parse_mode=ParseMode.HTML,
)
detected_imdb = extract_imdb_id(query)
try:
if detected_imdb:
raw_movies = await asyncio.to_thread(search_movies, query, imdb_id=detected_imdb)
else:
raw_movies = await asyncio.to_thread(search_movies, query)
except Exception as exc:
LOGGER.error("Error search_movies in command: %s", exc)
return await safe_edit_message(
status_msg,
f"โ <b>Gagal mencari film:</b> {html.escape(str(exc))}",
)
if not raw_movies:
return await safe_edit_message(
status_msg,
f"โ <b>Tidak ada hasil ditemukan</b> untuk: <code>{html.escape(query)}</code>\n\n"
f"Pastikan ejaan benar atau gunakan IMDb ID (contoh: <code>tt1375666</code>).",
)
grouped_items = group_movies_and_series(raw_movies)
session_key = f"{status_msg.chat.id}_{status_msg.id}"
cleanup_old_sessions()
# 1. Jika ditemukan lebih dari 1 grup judul
if len(grouped_items) > 1:
SEARCH_SESSIONS[session_key] = {
"query": query,
"raw_movies": raw_movies,
"grouped_items": grouped_items,
"current_series": None,
"current_movie": None,
"current_lang": "id",
"page": 1,
"movie_page": 1,
"user_id": message.from_user.id if message.from_user else 0,
"timestamp": time.time(),
}
text_content = (
f"๐ฌ <b>Hasil Pencarian SubSource</b>\n"
f"Query: <code>{clean_html_text(query)}</code>\n"
f"Ditemukan <b>{len(grouped_items)}</b> judul film/series.\n\n"
f"<i>Silakan pilih judul di bawah ini:</i>"
)
keyboard = build_movies_keyboard(grouped_items, page=1)
return await safe_edit_message(status_msg, text_content, reply_markup=keyboard)
# 2. Hanya 1 grup judul ditemukan
single_item = grouped_items[0]
# 2A. Jika serial TV dengan banyak Season -> Buka menu pemilihan Season
if single_item.get("is_series") and len(single_item.get("seasons", [])) > 1:
SEARCH_SESSIONS[session_key] = {
"query": query,
"raw_movies": raw_movies,
"grouped_items": grouped_items,
"current_series": single_item,
"current_movie": None,
"current_lang": "id",
"page": 1,
"movie_page": 1,
"user_id": message.from_user.id if message.from_user else 0,
"timestamp": time.time(),
}
text_content = format_seasons_message(single_item)
keyboard = build_seasons_keyboard(single_item)
return await safe_edit_message(status_msg, text_content, reply_markup=keyboard)
# 2B. Jika film biasa atau series dengan 1 season -> Langsung buka daftar subtitle
if single_item.get("is_series"):
selected_movie = single_item["seasons"][0]
else:
selected_movie = single_item
movie_id = selected_movie.get("movieId") or selected_movie.get("id")
if not movie_id:
return await safe_edit_message(status_msg, "โ Data tidak memiliki ID yang valid dari SubSource.")
current_lang = "id"
api_lang = LANG_CODE_TO_NAME.get(current_lang, "indonesian")
await safe_edit_message(
status_msg,
f"โณ <b>Mengambil daftar subtitle untuk:</b> <i>{clean_html_text(selected_movie.get('title', ''))}</i>...",
)
try:
subtitles = await asyncio.to_thread(get_subtitles, int(movie_id), language=api_lang)
if not subtitles:
subtitles = await asyncio.to_thread(get_subtitles, int(movie_id), language="english")
if subtitles:
current_lang = "en"
else:
subtitles = await asyncio.to_thread(get_subtitles, int(movie_id), language="all")
if subtitles:
current_lang = "all"
except Exception as exc:
LOGGER.error("Gagal mengambil subtitle: %s", exc)
return await safe_edit_message(
status_msg,
f"โ <b>Gagal mengambil subtitle:</b> {html.escape(str(exc))}",
)
SEARCH_SESSIONS[session_key] = {
"query": query,
"raw_movies": raw_movies,
"grouped_items": grouped_items,
"current_series": None,
"current_movie": selected_movie,
"current_lang": current_lang,
"subtitles": subtitles,
"page": 1,
"movie_page": 1,
"user_id": message.from_user.id if message.from_user else 0,
"timestamp": time.time(),
}
text_content = format_subtitles_message(selected_movie, subtitles, current_lang, page=1)
keyboard = build_subtitles_keyboard(
subtitles,
current_lang,
page=1,
has_seasons=False,
has_multiple_movies=False,
)
await safe_edit_message(status_msg, text_content, reply_markup=keyboard)
async def handle_subtitle_callback(client: Client, query: CallbackQuery):
"""
Handler utama untuk seluruh callback query sub_*:
- sub_series:<idx> : Memilih serial TV dan menampilkan daftar Season
- sub_seasons : Kembali ke menu pemilihan Season
- sub_m:<movie_id> : Memilih Season / Film dan memuat daftar subtitle
- sub_mp:<page> : Paginasi daftar judul film/series
- sub_l:<lang> : Mengubah filter bahasa
- sub_p:<page>:<lang> : Paginasi daftar subtitle
- sub_dl:<sub_id> : Mengunduh subtitle (otomatis ekstrak & bersihkan zip)
- sub_send:<sub_id>: Mengirimkan semua file subtitle ke chat Telegram
- sub_nosend:<sub_id>: Tetap menyimpan di server tanpa kirim ke chat
- sub_back : Kembali ke daftar judul film/series
- sub_close : Menutup tampilan
"""
data = query.data or ""
if not data.startswith("sub_"):
return
if data == "sub_noop":
return await query.answer()
if data == "sub_close":
cancel_auto_close(query.message.chat.id, query.message.id)
try:
await query.message.delete()
except Exception:
try:
await query.edit_message_reply_markup(reply_markup=None)
except Exception:
pass
return await query.answer("Ditutup.")
session_key = f"{query.message.chat.id}_{query.message.id}"
session = SEARCH_SESSIONS.get(session_key)
try:
# ----------------------------------------------------------------------
# 1. DOWNLOAD SUBTITLE & KONFIRMASI (sub_dl:<sub_id>)
# ----------------------------------------------------------------------
if data.startswith("sub_dl:"):
sub_id_str = data.split(":", 1)[1]
try:
sub_id = int(sub_id_str)
except ValueError:
return await query.answer("ID subtitle tidak valid.", show_alert=True)
await query.answer("โณ Mengunduh subtitle...", show_alert=False)
movie_info = session.get("current_movie", {}) if session else {}
movie_title = movie_info.get("title") or movie_info.get("name", "subtitle")
season = movie_info.get("season")
if season is not None:
season_label = f"Season {season}" if season != 0 else "Specials"
full_title = f"{movie_title} - {season_label}"
else:
full_title = movie_title
try:
res = await asyncio.to_thread(download_subtitle_file, sub_id, movie_title=movie_title)
except Exception as dl_exc:
res = {"ok": False, "error": str(dl_exc)}
if not res.get("ok"):
err_msg = res.get("error", "Gagal mengunduh subtitle.")
LOGGER.error("Gagal download subtitle #%s: %s", sub_id, err_msg)
try:
await query.answer(f"โ Gagal: {err_msg[:100]}", show_alert=True)
except Exception:
pass
return await query.message.reply_text(
f"โ <b>Gagal Mengunduh Subtitle #{sub_id}</b>\n\n"
f"Detail error: <code>{html.escape(str(err_msg))}</code>\n\n"
f"<i>Silakan coba pilih subtitle lain atau ganti bahasa.</i>",
parse_mode=ParseMode.HTML,
)
files = res.get("files", [])
total_files = len(files)
download_dir = res.get("download_dir", "/downloads")
size_str = format_bytes(res.get("size"))
# Simpan data unduhan untuk penanganan tombol konfirmasi kirim
DOWNLOADED_SUBS[str(sub_id)] = {
"files": files,
"primary_file": res.get("primary_file", ""),
"primary_name": res.get("filename", ""),
"total_files": total_files,
"movie_title": full_title,
"size_str": size_str,
"download_dir": download_dir,
"zip_path": res.get("zip_path"),
"timestamp": time.time(),
}
if total_files > 1:
confirm_text = (
f"โ
<b>Subtitle Series Berhasil Diunduh!</b>\n\n"
f"๐ฌ <b>Series:</b> <i>{clean_html_text(full_title)}</i>\n"
f"๐ฆ <b>Total Episode:</b> <code>{total_files} file subtitle</code>\n"
f"๐ <b>Tersimpan di:</b> <code>{html.escape(download_dir)}</code>\n"
f"๐พ <b>Total Ukuran:</b> <code>{size_str}</code>\n\n"
f"<i>File subtitle telah diekstrak ke server lokal. Apakah Anda ingin mengirimkan "
f"file ZIP ini ke chat Telegram?</i>"
)
button_send_label = f"๐ค Ya, Kirim File ZIP ({total_files} Episode)"
else:
primary_name = res.get("filename", "")
confirm_text = (
f"โ
<b>Subtitle Berhasil Diunduh!</b>\n\n"
f"๐ฌ <b>Judul:</b> <i>{clean_html_text(full_title)}</i>\n"
f"๐ <b>File:</b> <code>{clean_html_text(primary_name)}</code>\n"
f"๐ <b>Lokasi:</b> <code>{html.escape(res.get('primary_file', ''))}</code>\n"
f"๐พ <b>Ukuran:</b> <code>{size_str}</code>\n\n"
f"<i>Apakah Anda ingin mengirimkan file subtitle ini ke chat Telegram?</i>"
)
button_send_label = "๐ค Ya, Kirim ke Chat"
# Pisahkan ke baris masing-masing agar tidak melebihi lebar card UI Telegram
confirm_keyboard = InlineKeyboardMarkup([
[InlineKeyboardButton(button_send_label, callback_data=f"sub_send:{sub_id}")],
[InlineKeyboardButton("๐ Tidak, Cukup Simpan di Server", callback_data=f"sub_nosend:{sub_id}")],
])
confirm_msg = await query.message.reply_text(
confirm_text,
reply_markup=confirm_keyboard,
parse_mode=ParseMode.HTML,
)
schedule_auto_close(
client,
confirm_msg.chat.id,
confirm_msg.id,
delay=120,
temp_zip_to_clean=res.get("zip_path"),
)
try:
await query.answer(f"โ
Berhasil diekstrak ({total_files} file di /downloads)!", show_alert=False)
except Exception:
pass
return
# ----------------------------------------------------------------------
# 1A. PENGGUNA MEMILIH KIRIM KE CHAT (sub_send:<sub_id>)
# ----------------------------------------------------------------------
if data.startswith("sub_send:"):
sub_id = data.split(":", 1)[1]
item = DOWNLOADED_SUBS.get(sub_id)
if not item or not item.get("files"):
return await query.answer("File tidak ditemukan atau sesi telah kadaluarsa.", show_alert=True)
files = item["files"]
movie_title = item["movie_title"]
total_files = len(files)
download_dir = item.get("download_dir", "/downloads")
zip_path = item.get("zip_path")
cancel_auto_close(query.message.chat.id, query.message.id)
await query.answer("Mengirim subtitle ke chat...", show_alert=False)
if total_files > 1:
# Format satu pesan caption bersih sesuai instruksi:
# ๐ฆ {total_files} File Subtitle Telah Dikirim dan disimpan di lokal!
caption = (
f"๐ฆ <b>{total_files} File Subtitle Telah Dikirim dan disimpan di lokal!</b>\n\n"
f"๐ฌ <b>Series:</b> <i>{clean_html_text(movie_title)}</i>\n"
f"๐ <b>Tersimpan di:</b> <code>{html.escape(download_dir)}</code>"
)
# Jika zip_path tidak ditemukan, bungkus ulang dari file yang ada di /downloads
if not zip_path or not os.path.exists(zip_path):
temp_zip = os.path.join(tempfile.gettempdir(), f"{clean_filename(movie_title)}_{sub_id}.zip")
with zipfile.ZipFile(temp_zip, "w", zipfile.ZIP_DEFLATED) as zf:
for f in files:
if os.path.exists(f):
zf.write(f, os.path.basename(f))
zip_path = temp_zip
try:
await client.send_document(
chat_id=query.message.chat.id,
document=zip_path,
caption=caption,
parse_mode=ParseMode.HTML,
)
except FloodWait as f_err:
await asyncio.sleep(int(f_err.value) + 1)
await client.send_document(
chat_id=query.message.chat.id,
document=zip_path,
caption=caption,
parse_mode=ParseMode.HTML,
)
except Exception as send_err:
LOGGER.error("Gagal mengirim file zip subtitle: %s", send_err)
return await query.answer(f"Gagal mengirim ZIP: {send_err}", show_alert=True)
finally:
# Bersihkan file ZIP dari temporary agar tidak tersisa di disk manapun
try:
if zip_path and os.path.exists(zip_path):
os.remove(zip_path)
except Exception:
pass
# Hapus pesan konfirmasi agar hanya tersisa 1 pesan dokumen yang rapi di Telegram
try:
await query.message.delete()
except Exception:
try:
await query.edit_message_reply_markup(reply_markup=None)
except Exception:
pass
return
# Jika film biasa (1 file subtitle)
single_file = files[0]
caption = (
f"๐ <b>File Subtitle Telah Dikirim dan disimpan di lokal!</b>\n\n"
f"๐ฌ <b>Judul:</b> <i>{clean_html_text(movie_title)}</i>\n"
f"๐ <b>Tersimpan di:</b> <code>{html.escape(single_file)}</code>"
)
try:
await client.send_document(
chat_id=query.message.chat.id,
document=single_file,
caption=caption,
parse_mode=ParseMode.HTML,
)
except FloodWait as f_err:
await asyncio.sleep(int(f_err.value) + 1)
await client.send_document(
chat_id=query.message.chat.id,
document=single_file,
caption=caption,
parse_mode=ParseMode.HTML,
)
except Exception as send_err:
LOGGER.error("Gagal mengirim dokumen subtitle: %s", send_err)
return await query.answer(f"Gagal mengirim subtitle: {send_err}", show_alert=True)
# Hapus pesan konfirmasi agar hanya ada 1 pesan
try:
await query.message.delete()
except Exception:
try:
await query.edit_message_reply_markup(reply_markup=None)
except Exception:
pass
return
# ----------------------------------------------------------------------
# 1B. PENGGUNA MEMILIH TIDAK KIRIM KE CHAT (sub_nosend:<sub_id>)
# ----------------------------------------------------------------------
if data.startswith("sub_nosend:"):
sub_id = data.split(":", 1)[1]
item = DOWNLOADED_SUBS.get(sub_id)
movie_title = item.get("movie_title", "") if item else ""
download_dir = item.get("download_dir", "/downloads") if item else "/downloads"
total_files = item.get("total_files", 1) if item else 1
zip_path = item.get("zip_path") if item else None
# Hapus temporary zip jika ada
if zip_path and os.path.exists(zip_path):
try:
os.remove(zip_path)
except Exception:
pass
cancel_auto_close(query.message.chat.id, query.message.id)
updated_text = (
f"๐ <b>Subtitle Tetap Tersimpan di Server</b>\n\n"
f"๐ฌ <b>Judul/Series:</b> <i>{clean_html_text(movie_title)}</i>\n"
f"๐ฆ <b>Jumlah File:</b> <code>{total_files} file</code>\n"
f"๐ <b>Lokasi:</b> <code>{html.escape(download_dir)}</code>\n\n"
f"<i>File subtitle tetap tersimpan di folder <code>/downloads</code> untuk media server (tanpa file ZIP).</i>"
)
await safe_edit_message(query, updated_text, reply_markup=None, auto_close=False)
return await query.answer("Subtitle tetap disimpan di /downloads!")
# Jika sesi pencarian sudah tidak ada di memori
if not session:
return await query.answer(
"Sesi pencarian telah kadaluarsa. Silakan ketik perintah /subtitle kembali.",
show_alert=True,
)
# ----------------------------------------------------------------------
# 2. NAVIGASI DAFTAR JUDUL FILM/SERIES (sub_mp:<page>)
# ----------------------------------------------------------------------
if data.startswith("sub_mp:"):
page = int(data.split(":", 1)[1])
session["movie_page"] = page
grouped_items = session.get("grouped_items", [])
text_content = (
f"๐ฌ <b>Hasil Pencarian SubSource</b>\n"
f"Query: <code>{clean_html_text(session.get('query', ''))}</code>\n"
f"Ditemukan <b>{len(grouped_items)}</b> judul film/series.\n\n"
f"<i>Silakan pilih judul di bawah ini:</i>"
)
keyboard = build_movies_keyboard(grouped_items, page=page)
await safe_edit_message(query, text_content, reply_markup=keyboard)
return await query.answer()
# ----------------------------------------------------------------------
# 3. KEMBALI KE DAFTAR JUDUL (sub_back)
# ----------------------------------------------------------------------
if data == "sub_back":
grouped_items = session.get("grouped_items", [])
page = session.get("movie_page", 1)
session["current_series"] = None
text_content = (
f"๐ฌ <b>Hasil Pencarian SubSource</b>\n"
f"Query: <code>{clean_html_text(session.get('query', ''))}</code>\n"
f"Ditemukan <b>{len(grouped_items)}</b> judul film/series.\n\n"
f"<i>Silakan pilih judul di bawah ini:</i>"
)
keyboard = build_movies_keyboard(grouped_items, page=page)
await safe_edit_message(query, text_content, reply_markup=keyboard)
return await query.answer()
# ----------------------------------------------------------------------
# 4. MEMILIH SERIAL TV -> SUB-PEMILIHAN SEASON (sub_series:<idx>)
# ----------------------------------------------------------------------
if data.startswith("sub_series:"):
idx = int(data.split(":", 1)[1])
grouped_items = session.get("grouped_items", [])
if not (0 <= idx < len(grouped_items)):
return await query.answer("Series tidak ditemukan.", show_alert=True)
series = grouped_items[idx]
session["current_series"] = series
text_content = format_seasons_message(series)
keyboard = build_seasons_keyboard(series)
await safe_edit_message(query, text_content, reply_markup=keyboard)
return await query.answer()
# ----------------------------------------------------------------------
# 5. KEMBALI KE MENU SEASON SERIAL TV (sub_seasons)
# ----------------------------------------------------------------------
if data == "sub_seasons":
series = session.get("current_series")
if not series:
return await query.answer("Data series tidak ditemukan.", show_alert=True)
text_content = format_seasons_message(series)
keyboard = build_seasons_keyboard(series)
await safe_edit_message(query, text_content, reply_markup=keyboard)
return await query.answer()
# ----------------------------------------------------------------------
# 6. MEMILIH SEASON / FILM (sub_m:<movie_id>)
# ----------------------------------------------------------------------
if data.startswith("sub_m:"):
movie_id_str = data.split(":", 1)[1]
try:
movie_id = int(movie_id_str)
except ValueError:
return await query.answer("Movie ID tidak valid.", show_alert=True)
# Cari movie object baik dari raw_movies atau dari seasons dalam series
raw_movies = session.get("raw_movies", [])
selected_movie = next(
(m for m in raw_movies if (m.get("movieId") or m.get("id")) == movie_id),
None,
)
if not selected_movie and session.get("current_series"):
seasons = session["current_series"].get("seasons", [])
selected_movie = next(
(s for s in seasons if (s.get("movieId") or s.get("id")) == movie_id),
None,
)
if not selected_movie:
return await query.answer("Judul tidak ditemukan dalam sesi.", show_alert=True)
await query.answer("Memuat subtitle...")
current_lang = session.get("current_lang", "id")
api_lang = LANG_CODE_TO_NAME.get(current_lang, "indonesian")
try:
subtitles = await asyncio.to_thread(get_subtitles, movie_id, language=api_lang)
if not subtitles and current_lang == "id":
subtitles_en = await asyncio.to_thread(get_subtitles, movie_id, language="english")
if subtitles_en:
current_lang = "en"
subtitles = subtitles_en
except Exception as fetch_err:
LOGGER.error("Gagal mengambil subtitle untuk movie %s: %s", movie_id, fetch_err)
return await safe_edit_message(
query,
f"โ <b>Gagal memuat subtitle untuk:</b> <i>{clean_html_text(selected_movie.get('title', ''))}</i>\n\n"
f"Detail error: <code>{html.escape(str(fetch_err))}</code>",
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("๐ Kembali", callback_data="sub_seasons" if session.get("current_series") else "sub_back")],
[InlineKeyboardButton("โ Tutup", callback_data="sub_close")],
]),
)
session["current_movie"] = selected_movie
session["current_lang"] = current_lang
session["subtitles"] = subtitles
session["page"] = 1
has_seasons = bool(session.get("current_series") and len(session["current_series"].get("seasons", [])) > 1)
has_multiple_movies = len(session.get("grouped_items", [])) > 1
text_content = format_subtitles_message(selected_movie, subtitles, current_lang, page=1)
keyboard = build_subtitles_keyboard(
subtitles,
current_lang,
page=1,
has_seasons=has_seasons,
has_multiple_movies=has_multiple_movies,
)
await safe_edit_message(query, text_content, reply_markup=keyboard)
return
# ----------------------------------------------------------------------
# 7. GANTI FILTER BAHASA (sub_l:<lang_code>)
# ----------------------------------------------------------------------
if data.startswith("sub_l:"):
lang_code = data.split(":", 1)[1]
if lang_code == session.get("current_lang"):
return await query.answer("Filter bahasa ini sudah aktif.")
movie = session.get("current_movie")
if not movie:
return await query.answer("Film/Season belum dipilih.", show_alert=True)
movie_id = movie.get("movieId") or movie.get("id")
api_lang = LANG_CODE_TO_NAME.get(lang_code, "indonesian")
await query.answer("Mengambil subtitle...")
try:
subtitles = await asyncio.to_thread(get_subtitles, int(movie_id), language=api_lang)
except Exception as fetch_err:
LOGGER.error("Gagal ganti bahasa: %s", fetch_err)
return await query.answer(f"โ Gagal memuat subtitle: {fetch_err}", show_alert=True)
session["current_lang"] = lang_code
session["subtitles"] = subtitles
session["page"] = 1
has_seasons = bool(session.get("current_series") and len(session["current_series"].get("seasons", [])) > 1)
has_multiple_movies = len(session.get("grouped_items", [])) > 1
text_content = format_subtitles_message(movie, subtitles, lang_code, page=1)
keyboard = build_subtitles_keyboard(
subtitles,
lang_code,
page=1,
has_seasons=has_seasons,
has_multiple_movies=has_multiple_movies,
)
await safe_edit_message(query, text_content, reply_markup=keyboard)
return
# ----------------------------------------------------------------------
# 8. PAGINASI DAFTAR SUBTITLE (sub_p:<page>:<lang_code>)
# ----------------------------------------------------------------------
if data.startswith("sub_p:"):
parts = data.split(":")
page = int(parts[1])
lang_code = parts[2] if len(parts) > 2 else session.get("current_lang", "id")
movie = session.get("current_movie")
if not movie:
return await query.answer("Film/Season belum dipilih.", show_alert=True)
session["page"] = page
subtitles = session.get("subtitles", [])
has_seasons = bool(session.get("current_series") and len(session["current_series"].get("seasons", [])) > 1)
has_multiple_movies = len(session.get("grouped_items", [])) > 1
text_content = format_subtitles_message(movie, subtitles, lang_code, page=page)
keyboard = build_subtitles_keyboard(
subtitles,
lang_code,
page=page,
has_seasons=has_seasons,
has_multiple_movies=has_multiple_movies,
)
await safe_edit_message(query, text_content, reply_markup=keyboard)
return await query.answer()
except Exception as exc:
LOGGER.error("Exception in handle_subtitle_callback (data=%s): %s", data, exc, exc_info=True)
try:
await query.answer(f"โ Terjadi kesalahan: {str(exc)[:100]}", show_alert=True)
except Exception:
pass
try:
await query.message.reply_text(
f"โ <b>Terjadi kesalahan saat memproses permintaan subtitle:</b>\n"
f"<code>{html.escape(str(exc))}</code>",
parse_mode=ParseMode.HTML,
)
except Exception:
pass
"""
SubSource Subtitle Downloader Module for Telegram Bot.
Provides:
- Movie and TV series search with automatic Season grouping (Season 1, 2, etc.)
- Interactive Season selection sub-menu for TV series
- Interactive subtitle pagination with continuous numbering across pages
- Per-language country flag emojis for all SubSource languages (including 'All' mode)
- Automatic ZIP cleanup (leaves only extracted subtitle files in /downloads)
- Multi-file series pack handling (sends all episode subtitle files to Telegram)
- Post-download confirmation prompt (choice to send to chat or keep on server)
"""
import asyncio
import html
import io
import math
import os
import re
import tempfile
import time
import zipfile
from pathlib import Path
from typing import Any
import requests
from pyrogram import Client, filters
from pyrogram.enums import ParseMode
from pyrogram.errors import FloodWait, MessageNotModified
from pyrogram.types import (
CallbackQuery,
InlineKeyboardButton,
InlineKeyboardMarkup,
LinkPreviewOptions,
Message,
)
from .. import LOGGER
from ..helper.ext_utils.bot_utils import new_task
try:
from app import DOWNLOAD_PATH
except ImportError:
DOWNLOAD_PATH = os.getenv("QBITTORRENT_SAVE_PATH", "/downloads")
# ==============================================================================
# KONFIGURASI SUBSOURCE API & BAHASA
# ==============================================================================
API_KEY = os.getenv(
"SUBSOURCE_API_KEY",
"sk_e643a06714b5b587c9fac35d263499df0729c68471ebb848576072228ba52c9b",
)
BASE_URL = os.getenv("SUBSOURCE_BASE_URL", "https://api.subsource.net/api/v1")
HEADERS = {
"X-API-Key": API_KEY,
"Accept": "application/json",
"User-Agent": "TelegramBot-SubSource/1.0",
}
# Bahasa yang didukung untuk filter cepat tombol navigasi
LANGUAGE_OPTIONS = [
("id", "indonesian", "๐ฎ๐ฉ Indo"),
("en", "english", "๐ฌ๐ง Eng"),
("all", "all", "๐ Semua"),
]
LANG_CODE_TO_NAME = {code: name for code, name, _ in LANGUAGE_OPTIONS}
LANG_NAME_TO_CODE = {name: code for code, name, _ in LANGUAGE_OPTIONS}
# Pemetaan lengkap bahasa ke emoji bendera negara dari API SubSource
LANGUAGE_FLAG_MAP: dict[str, str] = {
"indonesian": "๐ฎ๐ฉ",
"id": "๐ฎ๐ฉ",
"english": "๐ฌ๐ง",
"en": "๐ฌ๐ง",
"arabic": "๐ธ๐ฆ",
"ar": "๐ธ๐ฆ",
"spanish": "๐ช๐ธ",
"es": "๐ช๐ธ",
"french": "๐ซ๐ท",
"fr": "๐ซ๐ท",
"german": "๐ฉ๐ช",
"de": "๐ฉ๐ช",
"italian": "๐ฎ๐น",
"it": "๐ฎ๐น",
"portuguese": "๐ต๐น",
"pt": "๐ต๐น",
"portuguese-br": "๐ง๐ท",
"brazilian": "๐ง๐ท",
"russian": "๐ท๐บ",
"ru": "๐ท๐บ",
"japanese": "๐ฏ๐ต",
"ja": "๐ฏ๐ต",
"korean": "๐ฐ๐ท",
"ko": "๐ฐ๐ท",
"chinese": "๐จ๐ณ",
"zh": "๐จ๐ณ",
"chinese-traditional": "๐น๐ผ",
"turkish": "๐น๐ท",
"tr": "๐น๐ท",