feat: v3.2.0 — split-file streaming, WebUI config, smarter matching
Browse files- streaming: add support for raw byte-split releases (movie.mkv.001,
movie.mkv.002, ...). Parts are detected, grouped in the DB under one
quality entry, and streamed as a single virtual file with full
Range/seek/resume support across the combined size.
Only the numbered split convention (.001/.002) is supported: those
parts are literal byte-slices of one original file, so concatenation
reconstructs a single valid file with one header and a correct
combined timeline. "part1/cd1/disk1" style releases are separately
muxed files (each with their own header/duration) and are explicitly
NOT grouped, since byte concatenation of those only plays correctly
through part 1 — confirmed by testing. Remuxed support for that case
is a possible future addition.
- config: shorten config.env to only startup-critical variables
(Telegram credentials, DATABASE URIs, PORT); move all other
configuration to the WebUI, applied dynamically with no restart
required. Values still present in config.env remain
startup-critical and are not editable from the WebUI.
- streaming: make client parallelism/prefetch count dynamic based on
current load instead of a fixed value.
- metadata: improve movie/show matching accuracy using fuzzy-match
scoring against inconsistent/messy filenames.
- chore: general refactor across the codebase for maintainability.
- Backend/__init__.py +1 -1
- Backend/fastapi/routes/stream_routes.py +83 -0
- Backend/fastapi/routes/stremio_routes.py +5 -4
- Backend/helper/database.py +157 -18
- Backend/helper/metadata.py +21 -7
- Backend/helper/modal.py +9 -0
- Backend/helper/split_files.py +52 -0
- Backend/helper/virtual_dl.py +106 -0
- Backend/pyrofork/plugins/reciever.py +28 -13
- pyproject.toml +1 -1
- sample_config.env +1 -1
- start.sh +1 -1
|
@@ -11,4 +11,4 @@ StartTime = time()
|
|
| 11 |
USE_DEFAULT_ID: str = None
|
| 12 |
db = Database()
|
| 13 |
|
| 14 |
-
__version__ = "3.
|
|
|
|
| 11 |
USE_DEFAULT_ID: str = None
|
| 12 |
db = Database()
|
| 13 |
|
| 14 |
+
__version__ = "3.2.0"
|
|
@@ -14,6 +14,7 @@ from Backend.logger import LOGGER
|
|
| 14 |
from Backend.helper.encrypt import decode_string
|
| 15 |
from Backend.helper.utils import track_usage
|
| 16 |
from Backend.helper.custom_dl import ByteStreamer, ACTIVE_STREAMS, RECENT_STREAMS
|
|
|
|
| 17 |
from Backend.pyrofork.bot import work_loads, multi_clients, client_dc_map, client_failures, client_avg_mbps
|
| 18 |
from Backend.fastapi.security.tokens import verify_token
|
| 19 |
|
|
@@ -103,6 +104,13 @@ def get_parallel_prefetch(client_count: int) -> tuple[int, int]:
|
|
| 103 |
@router.head("/dl/{token}/{id}/{name}")
|
| 104 |
async def stream_handler(request: Request, token: str, id: str, name: str, token_data: dict = Depends(verify_token),):
|
| 105 |
decoded = await decode_string(id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
msg_id = decoded.get("msg_id")
|
| 107 |
if not msg_id:
|
| 108 |
raise HTTPException(status_code=400, detail="Missing id")
|
|
@@ -234,6 +242,81 @@ async def media_streamer(request: Request, chat_id: int, msg_id: int, token: str
|
|
| 234 |
|
| 235 |
return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type, )
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
@router.get("/stream/stats")
|
| 238 |
async def get_stream_stats():
|
| 239 |
now = time.time()
|
|
|
|
| 14 |
from Backend.helper.encrypt import decode_string
|
| 15 |
from Backend.helper.utils import track_usage
|
| 16 |
from Backend.helper.custom_dl import ByteStreamer, ACTIVE_STREAMS, RECENT_STREAMS
|
| 17 |
+
from Backend.helper.virtual_dl import resolve_virtual_parts, virtual_stream_generator
|
| 18 |
from Backend.pyrofork.bot import work_loads, multi_clients, client_dc_map, client_failures, client_avg_mbps
|
| 19 |
from Backend.fastapi.security.tokens import verify_token
|
| 20 |
|
|
|
|
| 104 |
@router.head("/dl/{token}/{id}/{name}")
|
| 105 |
async def stream_handler(request: Request, token: str, id: str, name: str, token_data: dict = Depends(verify_token),):
|
| 106 |
decoded = await decode_string(id)
|
| 107 |
+
|
| 108 |
+
if "parts" in decoded:
|
| 109 |
+
return await virtual_media_streamer(
|
| 110 |
+
request=request, parts_payload=decoded["parts"],
|
| 111 |
+
token=token, token_data=token_data, stream_id_hash=id,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
msg_id = decoded.get("msg_id")
|
| 115 |
if not msg_id:
|
| 116 |
raise HTTPException(status_code=400, detail="Missing id")
|
|
|
|
| 242 |
|
| 243 |
return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type, )
|
| 244 |
|
| 245 |
+
|
| 246 |
+
async def virtual_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None,):
|
| 247 |
+
index = select_best_client(0)
|
| 248 |
+
tg_client = multi_clients[index]
|
| 249 |
+
if tg_client not in _streamer_by_client:
|
| 250 |
+
_streamer_by_client[tg_client] = ByteStreamer(tg_client, index)
|
| 251 |
+
streamer: ByteStreamer = _streamer_by_client[tg_client]
|
| 252 |
+
|
| 253 |
+
parts, file_size = await resolve_virtual_parts(parts_payload, streamer)
|
| 254 |
+
if not parts or file_size <= 0:
|
| 255 |
+
raise HTTPException(status_code=404, detail="Split media parts not found")
|
| 256 |
+
|
| 257 |
+
range_header = request.headers.get("Range", "")
|
| 258 |
+
start, end = parse_range_header(range_header, file_size)
|
| 259 |
+
req_length = end - start + 1
|
| 260 |
+
chunk_size = 1024 * 1024
|
| 261 |
+
stream_id = secrets.token_hex(8)
|
| 262 |
+
decoded_name = unquote(request.path_params.get("name", ""))
|
| 263 |
+
|
| 264 |
+
db_title = None
|
| 265 |
+
if stream_id_hash:
|
| 266 |
+
_now = time.time()
|
| 267 |
+
_cached = _title_cache.get(stream_id_hash)
|
| 268 |
+
if _cached and _now < _cached[1]:
|
| 269 |
+
db_title = _cached[0]
|
| 270 |
+
else:
|
| 271 |
+
db_title = await db.get_title_by_stream_id(stream_id_hash)
|
| 272 |
+
_title_cache[stream_id_hash] = (db_title, _now + _TITLE_CACHE_TTL)
|
| 273 |
+
final_title = db_title if db_title else decoded_name
|
| 274 |
+
|
| 275 |
+
meta = {
|
| 276 |
+
"request_path": str(request.url.path),
|
| 277 |
+
"client_host": request.client.host if request.client else None,
|
| 278 |
+
"title": final_title,
|
| 279 |
+
"user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
|
| 280 |
+
"split_parts": len(parts),
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
token_count = len(multi_clients) - 1
|
| 284 |
+
parallelism, prefetch_count = get_parallel_prefetch(token_count)
|
| 285 |
+
|
| 286 |
+
asyncio.create_task(track_usage(stream_id, token, token_data))
|
| 287 |
+
|
| 288 |
+
first_file_id = parts[0]["file_id"]
|
| 289 |
+
file_name = first_file_id.file_name or f"{secrets.token_hex(4)}.bin"
|
| 290 |
+
mime_type = first_file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream"
|
| 291 |
+
if "." not in file_name and "/" in mime_type:
|
| 292 |
+
file_name = f"{file_name}.{mime_type.split('/')[1]}"
|
| 293 |
+
|
| 294 |
+
common_headers = {
|
| 295 |
+
"Content-Type": mime_type,
|
| 296 |
+
"Content-Disposition": f'inline; filename="{file_name}"',
|
| 297 |
+
"Accept-Ranges": "bytes",
|
| 298 |
+
"Content-Length": str(req_length),
|
| 299 |
+
"Cache-Control": "public, max-age=3600",
|
| 300 |
+
"Access-Control-Allow-Origin": "*",
|
| 301 |
+
"Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges",
|
| 302 |
+
}
|
| 303 |
+
if range_header:
|
| 304 |
+
common_headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"
|
| 305 |
+
status = 206
|
| 306 |
+
else:
|
| 307 |
+
status = 200
|
| 308 |
+
|
| 309 |
+
if request.method == "HEAD":
|
| 310 |
+
return PlainResponse(status_code=status, headers=common_headers)
|
| 311 |
+
|
| 312 |
+
body_gen = virtual_stream_generator(
|
| 313 |
+
parts=parts, start=start, end=end, chunk_size=chunk_size,
|
| 314 |
+
streamer=streamer, client_index=index, request=request, meta=meta,
|
| 315 |
+
stream_id=stream_id, parallelism=parallelism, prefetch_count=prefetch_count,
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
return StreamingResponse(body_gen, headers=common_headers, status_code=status, media_type=mime_type, )
|
| 319 |
+
|
| 320 |
@router.get("/stream/stats")
|
| 321 |
async def get_stream_stats():
|
| 322 |
now = time.time()
|
|
@@ -58,11 +58,12 @@ def format_released_date(media):
|
|
| 58 |
return None
|
| 59 |
return None
|
| 60 |
|
| 61 |
-
def format_stream_details(filename: str, quality: str, size: str) -> tuple[str, str]:
|
|
|
|
| 62 |
try:
|
| 63 |
parsed = PTN.parse(filename)
|
| 64 |
except Exception:
|
| 65 |
-
return (f"Telegram {quality}", f"📁 {filename}\n
|
| 66 |
|
| 67 |
codec_parts = []
|
| 68 |
if parsed.get("codec"):
|
|
@@ -82,7 +83,7 @@ def format_stream_details(filename: str, quality: str, size: str) -> tuple[str,
|
|
| 82 |
|
| 83 |
stream_title_parts = [
|
| 84 |
f"📁 {filename}",
|
| 85 |
-
f"
|
| 86 |
]
|
| 87 |
if codec_info:
|
| 88 |
stream_title_parts.append(codec_info)
|
|
@@ -424,7 +425,7 @@ async def get_streams(
|
|
| 424 |
size = quality.get("size", "")
|
| 425 |
|
| 426 |
stream_name, stream_title = format_stream_details(
|
| 427 |
-
filename, quality_str, size
|
| 428 |
)
|
| 429 |
|
| 430 |
original_url = f"{SettingsManager.current().base_url}/dl/{token}/{quality.get('id')}/video.mkv"
|
|
|
|
| 58 |
return None
|
| 59 |
return None
|
| 60 |
|
| 61 |
+
def format_stream_details(filename: str, quality: str, size: str, is_split: bool = False) -> tuple[str, str]:
|
| 62 |
+
size_emoji = "📦" if is_split else "💾"
|
| 63 |
try:
|
| 64 |
parsed = PTN.parse(filename)
|
| 65 |
except Exception:
|
| 66 |
+
return (f"Telegram {quality}", f"📁 {filename}\n{size_emoji} {size}")
|
| 67 |
|
| 68 |
codec_parts = []
|
| 69 |
if parsed.get("codec"):
|
|
|
|
| 83 |
|
| 84 |
stream_title_parts = [
|
| 85 |
f"📁 {filename}",
|
| 86 |
+
f"{size_emoji} {size}",
|
| 87 |
]
|
| 88 |
if codec_info:
|
| 89 |
stream_title_parts.append(codec_info)
|
|
|
|
| 425 |
size = quality.get("size", "")
|
| 426 |
|
| 427 |
stream_name, stream_title = format_stream_details(
|
| 428 |
+
filename, quality_str, size, is_split=bool(quality.get("group_key"))
|
| 429 |
)
|
| 430 |
|
| 431 |
original_url = f"{SettingsManager.current().base_url}/dl/{token}/{quality.get('id')}/video.mkv"
|
|
@@ -12,8 +12,8 @@ from Backend.logger import LOGGER
|
|
| 12 |
from Backend.config import Telegram
|
| 13 |
from Backend.helper.settings_manager import SettingsManager
|
| 14 |
import re
|
| 15 |
-
from Backend.helper.encrypt import decode_string
|
| 16 |
-
from Backend.helper.modal import Episode, MovieSchema, QualityDetail, Season, TVShowSchema
|
| 17 |
from Backend.helper.task_manager import delete_message
|
| 18 |
|
| 19 |
|
|
@@ -692,11 +692,121 @@ class Database:
|
|
| 692 |
# Multi Database Method for insert/update/delete/list
|
| 693 |
# -------------------------------
|
| 694 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 695 |
async def insert_media(
|
| 696 |
self, metadata_info: dict,
|
| 697 |
-
channel: int, msg_id: int, size: str, name: str
|
| 698 |
) -> Optional[ObjectId]:
|
| 699 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 700 |
if metadata_info['media_type'] == "movie":
|
| 701 |
media = MovieSchema(
|
| 702 |
tmdb_id=metadata_info['tmdb_id'],
|
|
@@ -713,12 +823,7 @@ class Database:
|
|
| 713 |
cast=metadata_info['cast'],
|
| 714 |
runtime=metadata_info['runtime'],
|
| 715 |
media_type=metadata_info['media_type'],
|
| 716 |
-
telegram=[
|
| 717 |
-
quality=metadata_info['quality'],
|
| 718 |
-
id=metadata_info['encoded_string'],
|
| 719 |
-
name=name,
|
| 720 |
-
size=size
|
| 721 |
-
)]
|
| 722 |
)
|
| 723 |
return await self.update_movie(media)
|
| 724 |
else:
|
|
@@ -745,17 +850,43 @@ class Database:
|
|
| 745 |
episode_backdrop=metadata_info['episode_backdrop'],
|
| 746 |
overview=metadata_info['episode_overview'],
|
| 747 |
released=metadata_info['episode_released'],
|
| 748 |
-
telegram=[
|
| 749 |
-
quality=metadata_info['quality'],
|
| 750 |
-
id=metadata_info['encoded_string'],
|
| 751 |
-
name=name,
|
| 752 |
-
size=size
|
| 753 |
-
)]
|
| 754 |
)]
|
| 755 |
)]
|
| 756 |
)
|
| 757 |
return await self.update_tv_show(tv_show)
|
| 758 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 759 |
async def update_movie(self, movie_data: MovieSchema) -> Optional[ObjectId]:
|
| 760 |
try:
|
| 761 |
movie_dict = movie_data.dict()
|
|
@@ -814,7 +945,10 @@ class Database:
|
|
| 814 |
movie_id = existing_movie["_id"]
|
| 815 |
existing_qualities = existing_movie.get("telegram", [])
|
| 816 |
|
| 817 |
-
if
|
|
|
|
|
|
|
|
|
|
| 818 |
to_delete = [q for q in existing_qualities if q.get("quality") == target_quality]
|
| 819 |
|
| 820 |
for q in to_delete:
|
|
@@ -938,7 +1072,12 @@ class Database:
|
|
| 938 |
for quality in episode["telegram"]:
|
| 939 |
target_quality = quality.get("quality")
|
| 940 |
|
| 941 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 942 |
to_delete = [
|
| 943 |
q for q in existing_episode["telegram"]
|
| 944 |
if q.get("quality") == target_quality
|
|
|
|
| 12 |
from Backend.config import Telegram
|
| 13 |
from Backend.helper.settings_manager import SettingsManager
|
| 14 |
import re
|
| 15 |
+
from Backend.helper.encrypt import decode_string, encode_string
|
| 16 |
+
from Backend.helper.modal import Episode, MovieSchema, QualityDetail, QualityPart, Season, TVShowSchema
|
| 17 |
from Backend.helper.task_manager import delete_message
|
| 18 |
|
| 19 |
|
|
|
|
| 692 |
# Multi Database Method for insert/update/delete/list
|
| 693 |
# -------------------------------
|
| 694 |
|
| 695 |
+
async def _build_part_id_and_size(self, parts: List[dict]) -> Tuple[str, str]:
|
| 696 |
+
"""Given a list of part dicts (chat_id, msg_id, part_number, size_bytes),
|
| 697 |
+
produce the aggregate opaque stream `id` (encoding all parts, ordered)
|
| 698 |
+
and the human-readable total size string."""
|
| 699 |
+
sorted_parts = sorted(parts, key=lambda p: p.get("part_number", 0))
|
| 700 |
+
payload = {"parts": [{"chat_id": p["chat_id"], "msg_id": p["msg_id"]} for p in sorted_parts]}
|
| 701 |
+
encoded = await encode_string(payload)
|
| 702 |
+
total_bytes = sum(p.get("size_bytes", 0) for p in sorted_parts)
|
| 703 |
+
from Backend.helper.pyro import get_readable_file_size
|
| 704 |
+
size_str = get_readable_file_size(total_bytes)
|
| 705 |
+
return encoded, size_str
|
| 706 |
+
|
| 707 |
+
async def remove_media_part(self, channel: int, msg_id: int) -> bool:
|
| 708 |
+
"""Remove a single Telegram message from the database, whether it was
|
| 709 |
+
stored as a standalone quality entry (legacy single-file) or as one
|
| 710 |
+
part of a multi-part split-file quality entry. Mirrors
|
| 711 |
+
delete_media_by_stream_id's cleanup-cascading behaviour."""
|
| 712 |
+
try:
|
| 713 |
+
legacy_hash = await encode_string({"chat_id": channel, "msg_id": msg_id})
|
| 714 |
+
if await self.delete_media_by_stream_id(legacy_hash):
|
| 715 |
+
return True
|
| 716 |
+
except Exception as e:
|
| 717 |
+
LOGGER.error(f"remove_media_part: legacy lookup failed: {e}")
|
| 718 |
+
|
| 719 |
+
for i in range(1, self.current_db_index + 1):
|
| 720 |
+
db = self.dbs[f"storage_{i}"]
|
| 721 |
+
|
| 722 |
+
movie = await db["movie"].find_one(
|
| 723 |
+
{"telegram.parts": {"$elemMatch": {"chat_id": channel, "msg_id": msg_id}}}
|
| 724 |
+
)
|
| 725 |
+
if movie:
|
| 726 |
+
new_telegram = []
|
| 727 |
+
for q in movie.get("telegram", []):
|
| 728 |
+
parts = q.get("parts")
|
| 729 |
+
if parts and any(p.get("chat_id") == channel and p.get("msg_id") == msg_id for p in parts):
|
| 730 |
+
remaining = [p for p in parts if not (p.get("chat_id") == channel and p.get("msg_id") == msg_id)]
|
| 731 |
+
if not remaining:
|
| 732 |
+
continue # last part removed: drop the whole quality entry
|
| 733 |
+
new_id, new_size = await self._build_part_id_and_size(remaining)
|
| 734 |
+
q["parts"] = remaining
|
| 735 |
+
q["id"] = new_id
|
| 736 |
+
q["size"] = new_size
|
| 737 |
+
new_telegram.append(q)
|
| 738 |
+
|
| 739 |
+
if len(new_telegram) == 0:
|
| 740 |
+
await db["movie"].delete_one({"_id": movie["_id"]})
|
| 741 |
+
else:
|
| 742 |
+
movie["telegram"] = new_telegram
|
| 743 |
+
movie["updated_on"] = datetime.utcnow()
|
| 744 |
+
await db["movie"].replace_one({"_id": movie["_id"]}, movie)
|
| 745 |
+
return True
|
| 746 |
+
|
| 747 |
+
tv = await db["tv"].find_one(
|
| 748 |
+
{"seasons.episodes.telegram.parts": {"$elemMatch": {"chat_id": channel, "msg_id": msg_id}}}
|
| 749 |
+
)
|
| 750 |
+
if tv:
|
| 751 |
+
for season in tv.get("seasons", []):
|
| 752 |
+
for episode in season.get("episodes", []):
|
| 753 |
+
new_telegram = []
|
| 754 |
+
for q in episode.get("telegram", []):
|
| 755 |
+
parts = q.get("parts")
|
| 756 |
+
if parts and any(p.get("chat_id") == channel and p.get("msg_id") == msg_id for p in parts):
|
| 757 |
+
remaining = [p for p in parts if not (p.get("chat_id") == channel and p.get("msg_id") == msg_id)]
|
| 758 |
+
if not remaining:
|
| 759 |
+
continue
|
| 760 |
+
new_id, new_size = await self._build_part_id_and_size(remaining)
|
| 761 |
+
q["parts"] = remaining
|
| 762 |
+
q["id"] = new_id
|
| 763 |
+
q["size"] = new_size
|
| 764 |
+
new_telegram.append(q)
|
| 765 |
+
episode["telegram"] = new_telegram
|
| 766 |
+
season["episodes"] = [e for e in season.get("episodes", []) if e.get("telegram")]
|
| 767 |
+
tv["seasons"] = [s for s in tv.get("seasons", []) if s.get("episodes")]
|
| 768 |
+
|
| 769 |
+
if len(tv["seasons"]) == 0:
|
| 770 |
+
await db["tv"].delete_one({"_id": tv["_id"]})
|
| 771 |
+
else:
|
| 772 |
+
tv["updated_on"] = datetime.utcnow()
|
| 773 |
+
await db["tv"].replace_one({"_id": tv["_id"]}, tv)
|
| 774 |
+
return True
|
| 775 |
+
|
| 776 |
+
return False
|
| 777 |
+
|
| 778 |
async def insert_media(
|
| 779 |
self, metadata_info: dict,
|
| 780 |
+
channel: int, msg_id: int, size: str, name: str, raw_size: int = 0
|
| 781 |
) -> Optional[ObjectId]:
|
| 782 |
+
|
| 783 |
+
group_key = metadata_info.get("group_key")
|
| 784 |
+
part_number = metadata_info.get("part_number")
|
| 785 |
+
|
| 786 |
+
if group_key:
|
| 787 |
+
part = {
|
| 788 |
+
"part_number": part_number or 1,
|
| 789 |
+
"chat_id": channel,
|
| 790 |
+
"msg_id": msg_id,
|
| 791 |
+
"size_bytes": raw_size,
|
| 792 |
+
}
|
| 793 |
+
part_id, part_size = await self._build_part_id_and_size([part])
|
| 794 |
+
quality_detail = QualityDetail(
|
| 795 |
+
quality=metadata_info['quality'],
|
| 796 |
+
id=part_id,
|
| 797 |
+
name=name,
|
| 798 |
+
size=part_size,
|
| 799 |
+
group_key=group_key,
|
| 800 |
+
parts=[QualityPart(**part)],
|
| 801 |
+
)
|
| 802 |
+
else:
|
| 803 |
+
quality_detail = QualityDetail(
|
| 804 |
+
quality=metadata_info['quality'],
|
| 805 |
+
id=metadata_info['encoded_string'],
|
| 806 |
+
name=name,
|
| 807 |
+
size=size,
|
| 808 |
+
)
|
| 809 |
+
|
| 810 |
if metadata_info['media_type'] == "movie":
|
| 811 |
media = MovieSchema(
|
| 812 |
tmdb_id=metadata_info['tmdb_id'],
|
|
|
|
| 823 |
cast=metadata_info['cast'],
|
| 824 |
runtime=metadata_info['runtime'],
|
| 825 |
media_type=metadata_info['media_type'],
|
| 826 |
+
telegram=[quality_detail]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 827 |
)
|
| 828 |
return await self.update_movie(media)
|
| 829 |
else:
|
|
|
|
| 850 |
episode_backdrop=metadata_info['episode_backdrop'],
|
| 851 |
overview=metadata_info['episode_overview'],
|
| 852 |
released=metadata_info['episode_released'],
|
| 853 |
+
telegram=[quality_detail]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 854 |
)]
|
| 855 |
)]
|
| 856 |
)
|
| 857 |
return await self.update_tv_show(tv_show)
|
| 858 |
|
| 859 |
+
async def _merge_split_part(self, qualities: List[dict], quality_to_update: dict) -> List[dict]:
|
| 860 |
+
"""Merge an incoming split-part QualityDetail into the matching
|
| 861 |
+
group (by group_key) within `qualities`, or append it as the first
|
| 862 |
+
part of a new group. Returns the updated qualities list."""
|
| 863 |
+
group_key = quality_to_update.get("group_key")
|
| 864 |
+
incoming_parts = quality_to_update.get("parts") or []
|
| 865 |
+
if not incoming_parts:
|
| 866 |
+
return qualities + [quality_to_update]
|
| 867 |
+
new_part = incoming_parts[0]
|
| 868 |
+
|
| 869 |
+
merged = False
|
| 870 |
+
result = []
|
| 871 |
+
for q in qualities:
|
| 872 |
+
if group_key is not None and q.get("group_key") == group_key:
|
| 873 |
+
existing_parts = q.get("parts") or []
|
| 874 |
+
existing_parts = [
|
| 875 |
+
p for p in existing_parts if p.get("part_number") != new_part.get("part_number")
|
| 876 |
+
]
|
| 877 |
+
existing_parts.append(new_part)
|
| 878 |
+
new_id, new_size = await self._build_part_id_and_size(existing_parts)
|
| 879 |
+
q["parts"] = existing_parts
|
| 880 |
+
q["id"] = new_id
|
| 881 |
+
q["size"] = new_size
|
| 882 |
+
q["name"] = quality_to_update.get("name", q.get("name"))
|
| 883 |
+
merged = True
|
| 884 |
+
result.append(q)
|
| 885 |
+
|
| 886 |
+
if not merged:
|
| 887 |
+
result.append(quality_to_update)
|
| 888 |
+
return result
|
| 889 |
+
|
| 890 |
async def update_movie(self, movie_data: MovieSchema) -> Optional[ObjectId]:
|
| 891 |
try:
|
| 892 |
movie_dict = movie_data.dict()
|
|
|
|
| 945 |
movie_id = existing_movie["_id"]
|
| 946 |
existing_qualities = existing_movie.get("telegram", [])
|
| 947 |
|
| 948 |
+
if quality_to_update.get("group_key"):
|
| 949 |
+
existing_qualities = await self._merge_split_part(existing_qualities, quality_to_update)
|
| 950 |
+
|
| 951 |
+
elif SettingsManager.current().replace_mode:
|
| 952 |
to_delete = [q for q in existing_qualities if q.get("quality") == target_quality]
|
| 953 |
|
| 954 |
for q in to_delete:
|
|
|
|
| 1072 |
for quality in episode["telegram"]:
|
| 1073 |
target_quality = quality.get("quality")
|
| 1074 |
|
| 1075 |
+
if quality.get("group_key"):
|
| 1076 |
+
existing_episode["telegram"] = await self._merge_split_part(
|
| 1077 |
+
existing_episode["telegram"], quality
|
| 1078 |
+
)
|
| 1079 |
+
|
| 1080 |
+
elif SettingsManager.current().replace_mode:
|
| 1081 |
to_delete = [
|
| 1082 |
q for q in existing_episode["telegram"]
|
| 1083 |
if q.get("quality") == target_quality
|
|
@@ -12,6 +12,7 @@ from Backend.helper.settings_manager import SettingsManager
|
|
| 12 |
import Backend
|
| 13 |
from Backend.logger import LOGGER
|
| 14 |
from Backend.helper.encrypt import encode_string
|
|
|
|
| 15 |
|
| 16 |
# ----------------- Configuration -----------------
|
| 17 |
|
|
@@ -428,16 +429,21 @@ async def metadata(filename: str, channel: int, msg_id, override_id: str = None)
|
|
| 428 |
LOGGER.error(f"PTN parsing failed for {filename}: {e}\n{traceback.format_exc()}")
|
| 429 |
return None
|
| 430 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
# Skip combined/invalid files
|
| 432 |
if "excess" in parsed and any("combined" in item.lower() for item in parsed["excess"]):
|
| 433 |
LOGGER.info(f"Skipping {filename}: contains 'combined'")
|
| 434 |
return None
|
| 435 |
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
if multipart_pattern.search(filename):
|
| 439 |
-
LOGGER.info(f"Skipping {filename}: seems to be a split/multipart file")
|
| 440 |
-
return None
|
| 441 |
|
| 442 |
title = parsed.get("title")
|
| 443 |
season = parsed.get("season")
|
|
@@ -484,13 +490,21 @@ async def metadata(filename: str, channel: int, msg_id, override_id: str = None)
|
|
| 484 |
except Exception:
|
| 485 |
encoded_string = None
|
| 486 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 487 |
try:
|
| 488 |
if season and episode:
|
| 489 |
LOGGER.info(f"Fetching TV metadata: {title} S{season:02d}E{episode:02d} (year={year})")
|
| 490 |
-
|
| 491 |
else:
|
| 492 |
LOGGER.info(f"Fetching Movie metadata: {title} (year={year})")
|
| 493 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
except Exception as e:
|
| 495 |
LOGGER.error(f"Error while fetching metadata for {filename}: {e}\n{traceback.format_exc()}")
|
| 496 |
return None
|
|
|
|
| 12 |
import Backend
|
| 13 |
from Backend.logger import LOGGER
|
| 14 |
from Backend.helper.encrypt import encode_string
|
| 15 |
+
from Backend.helper.split_files import parse_split_info
|
| 16 |
|
| 17 |
# ----------------- Configuration -----------------
|
| 18 |
|
|
|
|
| 429 |
LOGGER.error(f"PTN parsing failed for {filename}: {e}\n{traceback.format_exc()}")
|
| 430 |
return None
|
| 431 |
|
| 432 |
+
|
| 433 |
+
# Skip split files that are not supported
|
| 434 |
+
multipart_pattern = compile(r'(?:part|cd|disc|disk)[s._-]*\d+(?=\.\w+$)', IGNORECASE)
|
| 435 |
+
if multipart_pattern.search(filename):
|
| 436 |
+
LOGGER.info(f"Skipping {filename}: seems to be a split video file that is not supposed to combine in stremio use .mkv.001, .mkv.002 split files")
|
| 437 |
+
return None
|
| 438 |
+
|
| 439 |
+
|
| 440 |
# Skip combined/invalid files
|
| 441 |
if "excess" in parsed and any("combined" in item.lower() for item in parsed["excess"]):
|
| 442 |
LOGGER.info(f"Skipping {filename}: contains 'combined'")
|
| 443 |
return None
|
| 444 |
|
| 445 |
+
split_info = parse_split_info(filename)
|
| 446 |
+
part_number = split_info[1] if split_info else None
|
|
|
|
|
|
|
|
|
|
| 447 |
|
| 448 |
title = parsed.get("title")
|
| 449 |
season = parsed.get("season")
|
|
|
|
| 490 |
except Exception:
|
| 491 |
encoded_string = None
|
| 492 |
|
| 493 |
+
group_key = None
|
| 494 |
+
if split_info:
|
| 495 |
+
group_key = f"{channel}:{quality}:{split_info[0]}"
|
| 496 |
+
|
| 497 |
try:
|
| 498 |
if season and episode:
|
| 499 |
LOGGER.info(f"Fetching TV metadata: {title} S{season:02d}E{episode:02d} (year={year})")
|
| 500 |
+
result = await fetch_tv_metadata(title, season, episode, encoded_string, year, quality, default_id)
|
| 501 |
else:
|
| 502 |
LOGGER.info(f"Fetching Movie metadata: {title} (year={year})")
|
| 503 |
+
result = await fetch_movie_metadata(title, encoded_string, year, quality, default_id)
|
| 504 |
+
if result is not None:
|
| 505 |
+
result["group_key"] = group_key
|
| 506 |
+
result["part_number"] = part_number
|
| 507 |
+
return result
|
| 508 |
except Exception as e:
|
| 509 |
LOGGER.error(f"Error while fetching metadata for {filename}: {e}\n{traceback.format_exc()}")
|
| 510 |
return None
|
|
@@ -5,11 +5,20 @@ from pydantic import BaseModel, Field
|
|
| 5 |
# ---------------------------
|
| 6 |
# Quality Detail Schema
|
| 7 |
# ---------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
class QualityDetail(BaseModel):
|
| 9 |
quality: str
|
| 10 |
id: str
|
| 11 |
name: str
|
| 12 |
size: str
|
|
|
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
# ---------------------------
|
|
|
|
| 5 |
# ---------------------------
|
| 6 |
# Quality Detail Schema
|
| 7 |
# ---------------------------
|
| 8 |
+
class QualityPart(BaseModel):
|
| 9 |
+
part_number: int
|
| 10 |
+
chat_id: int
|
| 11 |
+
msg_id: int
|
| 12 |
+
size_bytes: int
|
| 13 |
+
|
| 14 |
+
|
| 15 |
class QualityDetail(BaseModel):
|
| 16 |
quality: str
|
| 17 |
id: str
|
| 18 |
name: str
|
| 19 |
size: str
|
| 20 |
+
group_key: Optional[str] = None
|
| 21 |
+
parts: Optional[List[QualityPart]] = None
|
| 22 |
|
| 23 |
|
| 24 |
# ---------------------------
|
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from typing import Optional, Tuple
|
| 3 |
+
|
| 4 |
+
_VIDEO_EXTENSIONS = r'mkv|mp4|avi|ts|m4v|mov|wmv|webm|flv'
|
| 5 |
+
_TRAILING_NUMERIC_PATTERN = re.compile(rf'(?i)\.({_VIDEO_EXTENSIONS})\.(\d{{2,3}})$')
|
| 6 |
+
_NUMERIC_PATTERN = re.compile(r'(?i)[\.\-_](\d{2,3})(?=[\.\-_][a-z0-9]{2,4}$)')
|
| 7 |
+
_NORMALIZE_RE = re.compile(r'[\.\-_ ]+')
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _normalize(base: str) -> str:
|
| 11 |
+
return _NORMALIZE_RE.sub('.', base).strip('.').lower()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _find_split_match(name: str) -> Optional[Tuple[int, int, int, Optional[str]]]:
|
| 15 |
+
m = _TRAILING_NUMERIC_PATTERN.search(name)
|
| 16 |
+
if m:
|
| 17 |
+
return m.start(), m.end(), int(m.group(2)), m.group(1)
|
| 18 |
+
|
| 19 |
+
m = _NUMERIC_PATTERN.search(name)
|
| 20 |
+
if m:
|
| 21 |
+
part_num = int(m.group(1))
|
| 22 |
+
if 1 <= part_num <= 99:
|
| 23 |
+
return m.start(), m.end(), part_num, None
|
| 24 |
+
|
| 25 |
+
return None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def parse_split_info(filename: str) -> Optional[Tuple[str, int]]:
|
| 29 |
+
if not filename:
|
| 30 |
+
return None
|
| 31 |
+
|
| 32 |
+
name = filename.strip()
|
| 33 |
+
match = _find_split_match(name)
|
| 34 |
+
if not match:
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
start, end, part_num, ext = match
|
| 38 |
+
remainder = (name[:start] + '.' + ext) if ext else (name[:start] + name[end:])
|
| 39 |
+
return _normalize(remainder), part_num
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def strip_part_suffix(filename: str) -> str:
|
| 43 |
+
if not filename:
|
| 44 |
+
return filename
|
| 45 |
+
|
| 46 |
+
name = filename.strip()
|
| 47 |
+
match = _find_split_match(name)
|
| 48 |
+
if not match:
|
| 49 |
+
return filename
|
| 50 |
+
|
| 51 |
+
start, end, _part_num, ext = match
|
| 52 |
+
return (name[:start] + '.' + ext) if ext else (name[:start] + name[end:])
|
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import time
|
| 3 |
+
from typing import Dict, List, Optional, Tuple
|
| 4 |
+
|
| 5 |
+
from fastapi import Request
|
| 6 |
+
|
| 7 |
+
from Backend.logger import LOGGER
|
| 8 |
+
from Backend.helper.custom_dl import ByteStreamer
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
async def resolve_virtual_parts(
|
| 12 |
+
parts_payload: List[dict],
|
| 13 |
+
streamer: ByteStreamer,
|
| 14 |
+
) -> Tuple[List[Dict], int]:
|
| 15 |
+
"""Fetch Telegram file metadata for every part (in order) and compute
|
| 16 |
+
cumulative virtual offsets. Returns (parts, total_size)."""
|
| 17 |
+
parts: List[Dict] = []
|
| 18 |
+
cum = 0
|
| 19 |
+
for idx, p in enumerate(parts_payload):
|
| 20 |
+
chat_id = int(f"-100{p['chat_id']}")
|
| 21 |
+
msg_id = int(p["msg_id"])
|
| 22 |
+
file_id = await streamer.get_file_properties(chat_id=chat_id, message_id=msg_id)
|
| 23 |
+
size = file_id.file_size
|
| 24 |
+
parts.append({
|
| 25 |
+
"index": idx,
|
| 26 |
+
"chat_id": chat_id,
|
| 27 |
+
"msg_id": msg_id,
|
| 28 |
+
"file_id": file_id,
|
| 29 |
+
"size": size,
|
| 30 |
+
"cum_start": cum,
|
| 31 |
+
})
|
| 32 |
+
cum += size
|
| 33 |
+
return parts, cum
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def parts_overlapping_range(parts: List[Dict], start: int, end: int) -> List[Dict]:
|
| 37 |
+
return [p for p in parts if not (p["cum_start"] + p["size"] - 1 < start or p["cum_start"] > end)]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
async def virtual_stream_generator(
|
| 41 |
+
parts: List[Dict],
|
| 42 |
+
start: int,
|
| 43 |
+
end: int,
|
| 44 |
+
chunk_size: int,
|
| 45 |
+
streamer: ByteStreamer,
|
| 46 |
+
client_index: int,
|
| 47 |
+
request: Optional[Request],
|
| 48 |
+
meta: Optional[dict],
|
| 49 |
+
stream_id: str,
|
| 50 |
+
parallelism: int,
|
| 51 |
+
prefetch_count: int,
|
| 52 |
+
):
|
| 53 |
+
"""Yields raw bytes covering the virtual range [start, end] (inclusive),
|
| 54 |
+
crossing as many underlying parts as needed, completely transparently
|
| 55 |
+
to the caller."""
|
| 56 |
+
pos = start
|
| 57 |
+
for part in parts:
|
| 58 |
+
part_start = part["cum_start"]
|
| 59 |
+
part_end = part_start + part["size"] - 1
|
| 60 |
+
if part_end < pos:
|
| 61 |
+
continue
|
| 62 |
+
if part_start > end:
|
| 63 |
+
break
|
| 64 |
+
|
| 65 |
+
local_start = max(pos, part_start) - part_start
|
| 66 |
+
local_end = min(end, part_end) - part_start
|
| 67 |
+
|
| 68 |
+
offset = local_start - (local_start % chunk_size)
|
| 69 |
+
first_part_cut = local_start - offset
|
| 70 |
+
last_part_cut = (local_end % chunk_size) + 1
|
| 71 |
+
part_count = math.ceil(local_end / chunk_size) - math.floor(offset / chunk_size)
|
| 72 |
+
|
| 73 |
+
body_gen = await streamer.prefetch_stream(
|
| 74 |
+
file_id=part["file_id"],
|
| 75 |
+
client_index=client_index,
|
| 76 |
+
offset=offset,
|
| 77 |
+
first_part_cut=first_part_cut,
|
| 78 |
+
last_part_cut=last_part_cut,
|
| 79 |
+
part_count=part_count,
|
| 80 |
+
chunk_size=chunk_size,
|
| 81 |
+
prefetch=prefetch_count,
|
| 82 |
+
stream_id=f"{stream_id}-p{part['index']}",
|
| 83 |
+
meta=meta,
|
| 84 |
+
parallelism=parallelism,
|
| 85 |
+
request=request,
|
| 86 |
+
chat_id=part["chat_id"],
|
| 87 |
+
message_id=part["msg_id"],
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
async for chunk in body_gen:
|
| 91 |
+
yield chunk
|
| 92 |
+
|
| 93 |
+
# If the client disconnected mid-part, ByteStreamer's own consumer
|
| 94 |
+
# already stopped yielding for us; don't waste bandwidth fetching
|
| 95 |
+
# the next part on a dead connection.
|
| 96 |
+
if request is not None:
|
| 97 |
+
try:
|
| 98 |
+
if await request.is_disconnected():
|
| 99 |
+
LOGGER.debug("Virtual stream %s: client gone, stopping at part %s", stream_id, part["index"])
|
| 100 |
+
return
|
| 101 |
+
except Exception:
|
| 102 |
+
pass
|
| 103 |
+
|
| 104 |
+
pos = part_end + 1
|
| 105 |
+
if pos > end:
|
| 106 |
+
break
|
|
@@ -10,20 +10,32 @@ from pyrogram import filters, Client
|
|
| 10 |
from pyrogram.types import Message
|
| 11 |
from pyrogram.errors import FloodWait
|
| 12 |
from pyrogram.enums.parse_mode import ParseMode
|
| 13 |
-
from Backend.helper.encrypt import encode_string
|
| 14 |
-
from Backend.helper.encrypt import encode_string
|
| 15 |
from Backend.helper.metadata import extract_default_id
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
file_queue = Queue()
|
| 20 |
db_lock = Lock()
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
async def process_file():
|
| 23 |
while True:
|
| 24 |
-
metadata_info, channel, msg_id, size, title = await file_queue.get()
|
| 25 |
async with db_lock:
|
| 26 |
-
updated_id = await db.insert_media(metadata_info, channel=channel, msg_id=msg_id, size=size, name=title)
|
| 27 |
if updated_id:
|
| 28 |
LOGGER.info(f"{metadata_info['media_type']} updated with ID: {updated_id}")
|
| 29 |
else:
|
|
@@ -38,10 +50,11 @@ for _ in range(1):
|
|
| 38 |
async def file_receive_handler(client: Client, message: Message):
|
| 39 |
if str(message.chat.id) in SettingsManager.current().auth_channels:
|
| 40 |
try:
|
| 41 |
-
if
|
| 42 |
file = message.video or message.document
|
| 43 |
title = message.caption or file.file_name
|
| 44 |
msg_id = message.id
|
|
|
|
| 45 |
size = get_readable_file_size(file.file_size)
|
| 46 |
channel = str(message.chat.id).replace("-100", "")
|
| 47 |
|
|
@@ -51,6 +64,8 @@ async def file_receive_handler(client: Client, message: Message):
|
|
| 51 |
return
|
| 52 |
|
| 53 |
title = remove_urls(title)
|
|
|
|
|
|
|
| 54 |
if not title.endswith(('.mkv', '.mp4')):
|
| 55 |
title += '.mkv'
|
| 56 |
|
|
@@ -62,7 +77,7 @@ async def file_receive_handler(client: Client, message: Message):
|
|
| 62 |
new_caption=new_caption
|
| 63 |
))
|
| 64 |
|
| 65 |
-
await file_queue.put((metadata_info, int(channel), msg_id, size, title))
|
| 66 |
else:
|
| 67 |
await message.reply_text("> Not supported")
|
| 68 |
except FloodWait as e:
|
|
@@ -81,10 +96,11 @@ async def file_receive_handler(client: Client, message: Message):
|
|
| 81 |
async def file_edited_handler(client: Client, message: Message):
|
| 82 |
if str(message.chat.id) in SettingsManager.current().auth_channels:
|
| 83 |
try:
|
| 84 |
-
if
|
| 85 |
file = message.video or message.document
|
| 86 |
title = message.caption or file.file_name
|
| 87 |
msg_id = message.id
|
|
|
|
| 88 |
size = get_readable_file_size(file.file_size)
|
| 89 |
channel = str(message.chat.id).replace("-100", "")
|
| 90 |
|
|
@@ -93,9 +109,7 @@ async def file_edited_handler(client: Client, message: Message):
|
|
| 93 |
if override_id:
|
| 94 |
LOGGER.info(f"Detected override ID '{override_id}' in edited message {msg_id}")
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
await db.delete_media_by_stream_id(stream_id_hash)
|
| 99 |
|
| 100 |
metadata_info = await metadata(clean_filename(title), int(channel), msg_id, override_id=override_id)
|
| 101 |
if metadata_info is None:
|
|
@@ -103,10 +117,12 @@ async def file_edited_handler(client: Client, message: Message):
|
|
| 103 |
return
|
| 104 |
|
| 105 |
title = remove_urls(title)
|
|
|
|
|
|
|
| 106 |
if not title.endswith(('.mkv', '.mp4')):
|
| 107 |
title += '.mkv'
|
| 108 |
|
| 109 |
-
await file_queue.put((metadata_info, int(channel), msg_id, size, title))
|
| 110 |
else:
|
| 111 |
pass
|
| 112 |
except Exception as e:
|
|
@@ -122,8 +138,7 @@ async def file_deleted_handler(client: Client, messages: list[Message]):
|
|
| 122 |
msg_id = message.id
|
| 123 |
|
| 124 |
try:
|
| 125 |
-
|
| 126 |
-
deleted = await db.delete_media_by_stream_id(stream_id_hash)
|
| 127 |
|
| 128 |
if deleted:
|
| 129 |
LOGGER.info(f"Automatically purged deleted message {msg_id} from database.")
|
|
|
|
| 10 |
from pyrogram.types import Message
|
| 11 |
from pyrogram.errors import FloodWait
|
| 12 |
from pyrogram.enums.parse_mode import ParseMode
|
|
|
|
|
|
|
| 13 |
from Backend.helper.metadata import extract_default_id
|
| 14 |
+
from Backend.helper.split_files import parse_split_info, strip_part_suffix
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
file_queue = Queue()
|
| 19 |
db_lock = Lock()
|
| 20 |
|
| 21 |
+
|
| 22 |
+
def _is_supported_media(message: Message) -> bool:
|
| 23 |
+
if message.video:
|
| 24 |
+
return True
|
| 25 |
+
if message.document:
|
| 26 |
+
mime_type = message.document.mime_type or ""
|
| 27 |
+
if mime_type.startswith("video/"):
|
| 28 |
+
return True
|
| 29 |
+
candidate = message.caption or message.document.file_name or ""
|
| 30 |
+
if parse_split_info(candidate):
|
| 31 |
+
return True
|
| 32 |
+
return False
|
| 33 |
+
|
| 34 |
async def process_file():
|
| 35 |
while True:
|
| 36 |
+
metadata_info, channel, msg_id, size, raw_size, title = await file_queue.get()
|
| 37 |
async with db_lock:
|
| 38 |
+
updated_id = await db.insert_media(metadata_info, channel=channel, msg_id=msg_id, size=size, raw_size=raw_size, name=title)
|
| 39 |
if updated_id:
|
| 40 |
LOGGER.info(f"{metadata_info['media_type']} updated with ID: {updated_id}")
|
| 41 |
else:
|
|
|
|
| 50 |
async def file_receive_handler(client: Client, message: Message):
|
| 51 |
if str(message.chat.id) in SettingsManager.current().auth_channels:
|
| 52 |
try:
|
| 53 |
+
if _is_supported_media(message):
|
| 54 |
file = message.video or message.document
|
| 55 |
title = message.caption or file.file_name
|
| 56 |
msg_id = message.id
|
| 57 |
+
raw_size = file.file_size
|
| 58 |
size = get_readable_file_size(file.file_size)
|
| 59 |
channel = str(message.chat.id).replace("-100", "")
|
| 60 |
|
|
|
|
| 64 |
return
|
| 65 |
|
| 66 |
title = remove_urls(title)
|
| 67 |
+
if metadata_info.get('group_key'):
|
| 68 |
+
title = strip_part_suffix(title)
|
| 69 |
if not title.endswith(('.mkv', '.mp4')):
|
| 70 |
title += '.mkv'
|
| 71 |
|
|
|
|
| 77 |
new_caption=new_caption
|
| 78 |
))
|
| 79 |
|
| 80 |
+
await file_queue.put((metadata_info, int(channel), msg_id, size, raw_size, title))
|
| 81 |
else:
|
| 82 |
await message.reply_text("> Not supported")
|
| 83 |
except FloodWait as e:
|
|
|
|
| 96 |
async def file_edited_handler(client: Client, message: Message):
|
| 97 |
if str(message.chat.id) in SettingsManager.current().auth_channels:
|
| 98 |
try:
|
| 99 |
+
if _is_supported_media(message):
|
| 100 |
file = message.video or message.document
|
| 101 |
title = message.caption or file.file_name
|
| 102 |
msg_id = message.id
|
| 103 |
+
raw_size = file.file_size
|
| 104 |
size = get_readable_file_size(file.file_size)
|
| 105 |
channel = str(message.chat.id).replace("-100", "")
|
| 106 |
|
|
|
|
| 109 |
if override_id:
|
| 110 |
LOGGER.info(f"Detected override ID '{override_id}' in edited message {msg_id}")
|
| 111 |
|
| 112 |
+
await db.remove_media_part(int(channel), msg_id)
|
|
|
|
|
|
|
| 113 |
|
| 114 |
metadata_info = await metadata(clean_filename(title), int(channel), msg_id, override_id=override_id)
|
| 115 |
if metadata_info is None:
|
|
|
|
| 117 |
return
|
| 118 |
|
| 119 |
title = remove_urls(title)
|
| 120 |
+
if metadata_info.get('group_key'):
|
| 121 |
+
title = strip_part_suffix(title)
|
| 122 |
if not title.endswith(('.mkv', '.mp4')):
|
| 123 |
title += '.mkv'
|
| 124 |
|
| 125 |
+
await file_queue.put((metadata_info, int(channel), msg_id, size, raw_size, title))
|
| 126 |
else:
|
| 127 |
pass
|
| 128 |
except Exception as e:
|
|
|
|
| 138 |
msg_id = message.id
|
| 139 |
|
| 140 |
try:
|
| 141 |
+
deleted = await db.remove_media_part(int(channel), msg_id)
|
|
|
|
| 142 |
|
| 143 |
if deleted:
|
| 144 |
LOGGER.info(f"Automatically purged deleted message {msg_id} from database.")
|
|
@@ -1,6 +1,6 @@
|
|
| 1 |
[project]
|
| 2 |
name = "Telegram-Stremio"
|
| 3 |
-
version = "3.
|
| 4 |
description = "A powerful, self-hosted Telegram Stremio Media Server built with FastAPI, MongoDB, and PyroFork seamlessly integrated with Stremio for automated media streaming and discovery."
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.11"
|
|
|
|
| 1 |
[project]
|
| 2 |
name = "Telegram-Stremio"
|
| 3 |
+
version = "3.2.0"
|
| 4 |
description = "A powerful, self-hosted Telegram Stremio Media Server built with FastAPI, MongoDB, and PyroFork seamlessly integrated with Stremio for automated media streaming and discovery."
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.11"
|
|
@@ -9,4 +9,4 @@ OWNER_ID=""
|
|
| 9 |
DATABASE=""
|
| 10 |
|
| 11 |
# Server (required)
|
| 12 |
-
PORT="8000"
|
|
|
|
| 9 |
DATABASE=""
|
| 10 |
|
| 11 |
# Server (required)
|
| 12 |
+
PORT="8000"
|
|
@@ -1 +1 @@
|
|
| 1 |
-
uv run update.py && uv run -m Backend
|
|
|
|
| 1 |
+
uv run update.py && uv run -m Backend
|