soffex commited on
Commit
de2f8a3
Β·
unverified Β·
1 Parent(s): b8fe50f

feat: add /scan, /channels, /stats, /search, /dbcheck commands (#40)

Browse files

- /scan: index existing channel content via get_messages batching (bot-only)
- /channels, /addchannel, /removechannel: runtime channel management persisted to MongoDB
- /stats: database dashboard with content counts and system info
- /search: regex title search across all storage DBs
- /dbcheck: integrity checker for orphaned stream entries
- /exportchannels, /importchannels: channel config backup/restore

Closes #39

Backend/__main__.py CHANGED
@@ -91,3 +91,6 @@ if __name__ == '__main__':
91
  loop.run_until_complete(stop_services())
92
  loop.stop()
93
  logging.shutdown()
 
 
 
 
91
  loop.run_until_complete(stop_services())
92
  loop.stop()
93
  logging.shutdown()
94
+ # Load persisted AUTH_CHANNELs from DB (merged with env var channels)
95
+ from Backend.pyrofork.plugins.channels import _load_channels_from_db
96
+ await _load_channels_from_db()
Backend/helper/pyro.py CHANGED
@@ -145,6 +145,13 @@ async def restart_notification():
145
  commands = [
146
  BotCommand("start", "πŸš€ Start the bot"),
147
  BotCommand("set", "🎬 Manually add IMDb metadata"),
 
 
 
 
 
 
 
148
  # BotCommand("fixmetadata", "βš™οΈ Fix empty fields of Metadata"),
149
  BotCommand("log", "πŸ“„ Send the log file"),
150
  BotCommand("restart", "♻️ Restart the bot"),
 
145
  commands = [
146
  BotCommand("start", "πŸš€ Start the bot"),
147
  BotCommand("set", "🎬 Manually add IMDb metadata"),
148
+ BotCommand("channels", "πŸ“‘ List AUTH channels"),
149
+ BotCommand("addchannel", "βž• Add a channel"),
150
+ BotCommand("removechannel", "βž– Remove a channel"),
151
+ BotCommand("scan", "πŸ” Scan channel content"),
152
+ BotCommand("search", "πŸ”Ž Search DB by title"),
153
+ BotCommand("stats", "πŸ“Š DB and system stats"),
154
+ BotCommand("dbcheck", "🩺 Check DB integrity"),
155
  # BotCommand("fixmetadata", "βš™οΈ Fix empty fields of Metadata"),
156
  BotCommand("log", "πŸ“„ Send the log file"),
157
  BotCommand("restart", "♻️ Restart the bot"),
Backend/pyrofork/plugins/channels.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Channel Manager Plugin β€” add, remove, and list AUTH_CHANNELs via the bot.
3
+
4
+ Commands (owner-only, private chat):
5
+ /channels β€” List all active AUTH_CHANNELs with names
6
+ /addchannel <id> β€” Add a channel (validates bot access first)
7
+ /removechannel <id> β€” Remove a channel
8
+
9
+ Changes take effect immediately (no restart needed) and are persisted to MongoDB.
10
+
11
+ Drop this file into Backend/pyrofork/plugins/channels.py
12
+ """
13
+
14
+ from pyrogram import filters, Client, enums
15
+ from pyrogram.types import Message
16
+ from pyrogram.errors import ChannelPrivate, ChatAdminRequired, PeerIdInvalid
17
+
18
+ from Backend.helper.custom_filter import CustomFilters
19
+ from Backend.logger import LOGGER
20
+ from Backend import db
21
+ from Backend.config import Telegram
22
+
23
+
24
+ # ── DB persistence helpers ───────────────────────────────────────────────
25
+
26
+ CHANNEL_DOC_ID = "auth_channels"
27
+
28
+
29
+ async def _load_channels_from_db():
30
+ """Load persisted channels from tracking DB and merge with env var channels."""
31
+ try:
32
+ doc = await db.dbs["tracking"]["config"].find_one({"_id": CHANNEL_DOC_ID})
33
+ if doc and "channels" in doc:
34
+ db_channels = doc["channels"]
35
+ for ch in db_channels:
36
+ if ch not in Telegram.AUTH_CHANNEL:
37
+ Telegram.AUTH_CHANNEL.append(ch)
38
+ LOGGER.info(
39
+ f"[ChannelMgr] Loaded {len(db_channels)} channels from DB, "
40
+ f"total active: {len(Telegram.AUTH_CHANNEL)}"
41
+ )
42
+ except Exception as e:
43
+ LOGGER.error(f"[ChannelMgr] Failed to load channels from DB: {e}")
44
+
45
+
46
+ async def _save_channels_to_db():
47
+ """Persist the current AUTH_CHANNEL list to tracking DB."""
48
+ try:
49
+ await db.dbs["tracking"]["config"].update_one(
50
+ {"_id": CHANNEL_DOC_ID},
51
+ {"$set": {"channels": list(Telegram.AUTH_CHANNEL)}},
52
+ upsert=True,
53
+ )
54
+ except Exception as e:
55
+ LOGGER.error(f"[ChannelMgr] Failed to save channels to DB: {e}")
56
+
57
+
58
+ # ── Bot Commands ─────────────────────────────────────────────────────────
59
+
60
+ @Client.on_message(filters.command('channels') & filters.private & CustomFilters.owner, group=10)
61
+ async def list_channels(client: Client, message: Message):
62
+ """List all active AUTH_CHANNELs with their names."""
63
+ if not Telegram.AUTH_CHANNEL:
64
+ await message.reply_text(
65
+ "πŸ“­ No AUTH_CHANNELs configured.\n\n"
66
+ "Use /addchannel <code>&lt;channel_id&gt;</code> to add one.",
67
+ quote=True,
68
+ parse_mode=enums.ParseMode.HTML,
69
+ )
70
+ return
71
+
72
+ lines = []
73
+ for i, ch_id in enumerate(Telegram.AUTH_CHANNEL, 1):
74
+ name = ch_id # fallback
75
+ try:
76
+ chat = await client.get_chat(int(ch_id))
77
+ name = getattr(chat, "title", ch_id)
78
+ members = getattr(chat, "members_count", "?")
79
+ lines.append(f"{i}. <b>{name}</b>\n ID: <code>{ch_id}</code> | Members: {members}")
80
+ except Exception:
81
+ lines.append(f"{i}. <b>[inaccessible]</b>\n ID: <code>{ch_id}</code>")
82
+
83
+ text = (
84
+ "<blockquote>πŸ“‘ <b>Active AUTH_CHANNELs</b></blockquote>\n\n"
85
+ + "\n\n".join(lines)
86
+ + "\n\n<i>Use /addchannel or /removechannel to manage.</i>"
87
+ )
88
+ await message.reply_text(text, quote=True, parse_mode=enums.ParseMode.HTML)
89
+
90
+
91
+ @Client.on_message(filters.command('addchannel') & filters.private & CustomFilters.owner, group=10)
92
+ async def add_channel(client: Client, message: Message):
93
+ """Add a channel to AUTH_CHANNELs. Bot must be admin in the channel."""
94
+ args = message.text.split(maxsplit=1)
95
+ if len(args) < 2:
96
+ await message.reply_text(
97
+ "Usage: /addchannel <code>&lt;channel_id&gt;</code>\n\n"
98
+ "Example: <code>/addchannel -1001234567890</code>\n\n"
99
+ "πŸ’‘ <i>To find a channel ID, forward a message from it to "
100
+ "@userinfobot or check the channel's invite link.</i>",
101
+ quote=True,
102
+ parse_mode=enums.ParseMode.HTML,
103
+ )
104
+ return
105
+
106
+ ch_id = args[1].strip()
107
+
108
+ # Validate it's a number
109
+ try:
110
+ int(ch_id)
111
+ except ValueError:
112
+ await message.reply_text(
113
+ f"❌ <code>{ch_id}</code> is not a valid channel ID.\n"
114
+ "Channel IDs are numeric, usually starting with <code>-100</code>.",
115
+ quote=True,
116
+ parse_mode=enums.ParseMode.HTML,
117
+ )
118
+ return
119
+
120
+ # Check if already added
121
+ if ch_id in Telegram.AUTH_CHANNEL:
122
+ await message.reply_text(
123
+ f"ℹ️ Channel <code>{ch_id}</code> is already in AUTH_CHANNELs.",
124
+ quote=True,
125
+ parse_mode=enums.ParseMode.HTML,
126
+ )
127
+ return
128
+
129
+ # Validate bot has access
130
+ status_msg = await message.reply_text(
131
+ "πŸ” Validating channel access…",
132
+ quote=True,
133
+ parse_mode=enums.ParseMode.HTML,
134
+ )
135
+
136
+ try:
137
+ chat = await client.get_chat(int(ch_id))
138
+ ch_name = getattr(chat, "title", ch_id)
139
+ except (ChannelPrivate, ChatAdminRequired):
140
+ await status_msg.edit_text(
141
+ f"❌ <b>Access denied</b> to channel <code>{ch_id}</code>.\n\n"
142
+ "Make sure the bot is added as an <b>admin</b> in the channel first.",
143
+ parse_mode=enums.ParseMode.HTML,
144
+ )
145
+ return
146
+ except PeerIdInvalid:
147
+ await status_msg.edit_text(
148
+ f"❌ Channel <code>{ch_id}</code> not found.\n"
149
+ "Double-check the ID.",
150
+ parse_mode=enums.ParseMode.HTML,
151
+ )
152
+ return
153
+ except Exception as e:
154
+ await status_msg.edit_text(
155
+ f"❌ Error accessing channel: <code>{e}</code>",
156
+ parse_mode=enums.ParseMode.HTML,
157
+ )
158
+ return
159
+
160
+ # Add to runtime list and persist
161
+ Telegram.AUTH_CHANNEL.append(ch_id)
162
+ await _save_channels_to_db()
163
+
164
+ LOGGER.info(f"[ChannelMgr] Added channel {ch_id} ({ch_name})")
165
+
166
+ await status_msg.edit_text(
167
+ f"βœ… <b>Channel added!</b>\n\n"
168
+ f"πŸ“‘ <b>{ch_name}</b>\n"
169
+ f"ID: <code>{ch_id}</code>\n\n"
170
+ f"The bot will now index new videos from this channel.\n"
171
+ f"Use /scan <code>{ch_id}</code> to index existing content.",
172
+ parse_mode=enums.ParseMode.HTML,
173
+ )
174
+
175
+
176
+ @Client.on_message(filters.command('removechannel') & filters.private & CustomFilters.owner, group=10)
177
+ async def remove_channel(client: Client, message: Message):
178
+ """Remove a channel from AUTH_CHANNELs."""
179
+ args = message.text.split(maxsplit=1)
180
+ if len(args) < 2:
181
+ # Show current channels for easy selection
182
+ if Telegram.AUTH_CHANNEL:
183
+ lines = []
184
+ for ch_id in Telegram.AUTH_CHANNEL:
185
+ try:
186
+ chat = await client.get_chat(int(ch_id))
187
+ name = getattr(chat, "title", ch_id)
188
+ except Exception:
189
+ name = "[inaccessible]"
190
+ lines.append(f"β€’ <code>{ch_id}</code> β€” {name}")
191
+
192
+ await message.reply_text(
193
+ "Usage: /removechannel <code>&lt;channel_id&gt;</code>\n\n"
194
+ "<b>Current channels:</b>\n" + "\n".join(lines),
195
+ quote=True,
196
+ parse_mode=enums.ParseMode.HTML,
197
+ )
198
+ else:
199
+ await message.reply_text(
200
+ "πŸ“­ No channels to remove.",
201
+ quote=True,
202
+ )
203
+ return
204
+
205
+ ch_id = args[1].strip()
206
+
207
+ if ch_id not in Telegram.AUTH_CHANNEL:
208
+ await message.reply_text(
209
+ f"❌ Channel <code>{ch_id}</code> is not in AUTH_CHANNELs.",
210
+ quote=True,
211
+ parse_mode=enums.ParseMode.HTML,
212
+ )
213
+ return
214
+
215
+ # Get channel name before removing
216
+ ch_name = ch_id
217
+ try:
218
+ chat = await client.get_chat(int(ch_id))
219
+ ch_name = getattr(chat, "title", ch_id)
220
+ except Exception:
221
+ pass
222
+
223
+ Telegram.AUTH_CHANNEL.remove(ch_id)
224
+ await _save_channels_to_db()
225
+
226
+ LOGGER.info(f"[ChannelMgr] Removed channel {ch_id} ({ch_name})")
227
+
228
+ await message.reply_text(
229
+ f"βœ… <b>Channel removed!</b>\n\n"
230
+ f"πŸ“‘ <b>{ch_name}</b> (<code>{ch_id}</code>)\n\n"
231
+ f"⚠️ Existing DB entries from this channel are <b>not</b> deleted.\n"
232
+ f"Videos already indexed will still be streamable.\n"
233
+ f"New videos in this channel will no longer be indexed.",
234
+ quote=True,
235
+ parse_mode=enums.ParseMode.HTML,
236
+ )
237
+
238
+
Backend/pyrofork/plugins/scanner.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Channel Scanner Plugin β€” indexes existing channel content into the database.
3
+
4
+ Commands (owner-only, private chat):
5
+ /scan β€” Scan all AUTH_CHANNELs, skip already-indexed messages
6
+ /scan <id> β€” Scan a specific channel by numeric ID
7
+ /rescan β€” Wipe DB entries for AUTH_CHANNELs, then full re-index
8
+ /scanstatus β€” Show progress of any running scan
9
+ /cancelscan β€” Abort a running scan gracefully
10
+
11
+ Drop this file into Backend/pyrofork/plugins/scanner.py
12
+ """
13
+
14
+ import asyncio
15
+ import time
16
+ from pyrogram import filters, Client, enums
17
+ from pyrogram.types import Message
18
+ from pyrogram.errors import FloodWait, ChannelPrivate, ChatAdminRequired
19
+
20
+ from Backend.helper.custom_filter import CustomFilters
21
+ from Backend.logger import LOGGER
22
+ from Backend import db
23
+ from Backend.config import Telegram
24
+ from Backend.helper.pyro import clean_filename, get_readable_file_size, remove_urls
25
+ from Backend.helper.metadata import metadata
26
+ from Backend.helper.encrypt import encode_string
27
+
28
+
29
+ # ── Scan state (singleton β€” only one scan at a time) ────────────────────
30
+ class _ScanState:
31
+ def __init__(self):
32
+ self.reset()
33
+
34
+ def reset(self):
35
+ self.running = False
36
+ self.cancelled = False
37
+ self.channel_id = None
38
+ self.channel_name = ""
39
+ self.total_found = 0
40
+ self.processed = 0
41
+ self.indexed = 0
42
+ self.skipped_dup = 0
43
+ self.skipped_meta = 0
44
+ self.skipped_nonvid = 0
45
+ self.errors = 0
46
+ self.started_at = 0.0
47
+ self.status_msg: Message | None = None
48
+
49
+ @property
50
+ def elapsed(self) -> str:
51
+ s = int(time.time() - self.started_at) if self.started_at else 0
52
+ m, s = divmod(s, 60)
53
+ h, m = divmod(m, 60)
54
+ return f"{h}h {m}m {s}s" if h else f"{m}m {s}s"
55
+
56
+
57
+ scan_state = _ScanState()
58
+
59
+ # How often we edit the progress message (avoid FloodWait on edits)
60
+ PROGRESS_EVERY = 15 # messages processed between edits
61
+ RATE_LIMIT_DELAY = 0.3 # seconds between get_messages calls
62
+
63
+
64
+ # ── Helpers ──────────────────────────────────────────────────────────────
65
+
66
+ async def _stream_id_exists(channel: int, msg_id: int) -> bool:
67
+ """Check if this (channel, msg_id) combo is already in the DB."""
68
+ try:
69
+ stream_hash = await encode_string({"chat_id": channel, "msg_id": msg_id})
70
+ except Exception:
71
+ return False
72
+
73
+ # Check across all storage DBs
74
+ for i in range(1, db.current_db_index + 1):
75
+ storage = db.dbs.get(f"storage_{i}")
76
+ if storage is None:
77
+ continue
78
+ if await storage["movie"].find_one({"telegram.id": stream_hash}):
79
+ return True
80
+ if await storage["tv"].find_one({"seasons.episodes.telegram.id": stream_hash}):
81
+ return True
82
+ return False
83
+
84
+
85
+ async def _update_progress(force: bool = False):
86
+ """Edit the status message with current scan progress."""
87
+ s = scan_state
88
+ if not s.status_msg:
89
+ return
90
+ if not force and s.processed % PROGRESS_EVERY != 0:
91
+ return
92
+ try:
93
+ text = (
94
+ f"<blockquote>πŸ“‘ <b>Scanning:</b> {s.channel_name}</blockquote>\n\n"
95
+ f"⏱ Elapsed: <code>{s.elapsed}</code>\n"
96
+ f"πŸ“¨ Processed: <code>{s.processed}</code>\n"
97
+ f"βœ… Indexed: <code>{s.indexed}</code>\n"
98
+ f"⏭ Skipped (duplicate): <code>{s.skipped_dup}</code>\n"
99
+ f"⚠️ Skipped (metadata fail): <code>{s.skipped_meta}</code>\n"
100
+ f"πŸ“Ž Skipped (non-video): <code>{s.skipped_nonvid}</code>\n"
101
+ f"❌ Errors: <code>{s.errors}</code>"
102
+ )
103
+ await s.status_msg.edit_text(text, parse_mode=enums.ParseMode.HTML)
104
+ except FloodWait as e:
105
+ await asyncio.sleep(e.value)
106
+ except Exception:
107
+ pass # non-critical
108
+
109
+
110
+ async def _scan_channel(client: Client, chat_id: int):
111
+ """Iterate all video messages in a channel and index them.
112
+
113
+ Bots cannot use get_chat_history or search_messages (both user-only).
114
+ The only reliable bot method is get_messages with explicit IDs.
115
+
116
+ Strategy: walk forward from ID 1 in batches of 200. Keep going even
117
+ through empty batches (deleted messages / gaps). Stop after 5
118
+ consecutive all-empty batches, which tolerates gaps of up to ~1000 IDs.
119
+ Hard cap at 500,000 to prevent infinite loops.
120
+ """
121
+ s = scan_state
122
+
123
+ try:
124
+ chat = await client.get_chat(chat_id)
125
+ s.channel_name = getattr(chat, "title", str(chat_id))
126
+ except (ChannelPrivate, ChatAdminRequired) as e:
127
+ LOGGER.error(f"Cannot access channel {chat_id}: {e}")
128
+ raise
129
+ except Exception as e:
130
+ s.channel_name = str(chat_id)
131
+ LOGGER.warning(f"Could not resolve channel name for {chat_id}: {e}")
132
+
133
+ s.channel_id = chat_id
134
+ LOGGER.info(f"[Scanner] Starting scan of {s.channel_name} ({chat_id})")
135
+
136
+ BATCH_SIZE = 200
137
+ MAX_EMPTY_BATCHES = 5 # stop after 5 consecutive empty batches
138
+ MAX_ID_CAP = 500_000 # hard safety cap
139
+ empty_streak = 0
140
+ current = 1
141
+
142
+ while empty_streak < MAX_EMPTY_BATCHES and current < MAX_ID_CAP:
143
+ if s.cancelled:
144
+ LOGGER.info("[Scanner] Scan cancelled by user.")
145
+ break
146
+
147
+ batch_ids = list(range(current, min(current + BATCH_SIZE, MAX_ID_CAP)))
148
+
149
+ try:
150
+ messages = await client.get_messages(chat_id, batch_ids)
151
+ except FloodWait as e:
152
+ LOGGER.info(f"[Scanner] FloodWait {e.value}s, sleeping…")
153
+ await asyncio.sleep(e.value)
154
+ try:
155
+ messages = await client.get_messages(chat_id, batch_ids)
156
+ except Exception as ex:
157
+ LOGGER.error(f"[Scanner] Retry failed at {current}: {ex}")
158
+ s.errors += 1
159
+ current += BATCH_SIZE
160
+ empty_streak += 1
161
+ continue
162
+ except Exception as e:
163
+ LOGGER.error(f"[Scanner] Batch fetch error at {current}: {e}")
164
+ s.errors += 1
165
+ current += BATCH_SIZE
166
+ empty_streak += 1
167
+ continue
168
+
169
+ if not isinstance(messages, list):
170
+ messages = [messages]
171
+
172
+ batch_had_content = False
173
+
174
+ for message in messages:
175
+ if s.cancelled:
176
+ break
177
+
178
+ if message.empty:
179
+ continue
180
+
181
+ batch_had_content = True
182
+ s.total_found += 1
183
+
184
+ # Only process videos / video documents
185
+ is_video = bool(message.video)
186
+ is_video_doc = False
187
+ if message.document and not is_video:
188
+ mime = getattr(message.document, "mime_type", "") or ""
189
+ is_video_doc = mime.startswith("video/")
190
+
191
+ if not (is_video or is_video_doc):
192
+ s.skipped_nonvid += 1
193
+ s.processed += 1
194
+ await _update_progress()
195
+ continue
196
+
197
+ file = message.video or message.document
198
+ title = message.caption or file.file_name
199
+ msg_id = message.id
200
+ size = get_readable_file_size(file.file_size)
201
+ channel = str(chat_id).replace("-100", "")
202
+ channel_int = int(channel)
203
+
204
+ # ── Duplicate check ──────────────────────────────────
205
+ try:
206
+ if await _stream_id_exists(channel_int, msg_id):
207
+ s.skipped_dup += 1
208
+ s.processed += 1
209
+ await _update_progress()
210
+ continue
211
+ except Exception as e:
212
+ LOGGER.warning(f"[Scanner] Dup-check error msg {msg_id}: {e}")
213
+
214
+ # ── Metadata extraction (same pipeline as receiver) ──
215
+ try:
216
+ metadata_info = await metadata(clean_filename(title), channel_int, msg_id)
217
+ except Exception as e:
218
+ LOGGER.warning(f"[Scanner] Metadata exception for msg {msg_id}: {e}")
219
+ metadata_info = None
220
+
221
+ if metadata_info is None:
222
+ s.skipped_meta += 1
223
+ s.processed += 1
224
+ await _update_progress()
225
+ continue
226
+
227
+ title_clean = remove_urls(title)
228
+ if not title_clean.endswith(('.mkv', '.mp4')):
229
+ title_clean += '.mkv'
230
+
231
+ # ── Insert into DB ───────────────────────────────────
232
+ try:
233
+ updated_id = await db.insert_media(
234
+ metadata_info,
235
+ channel=channel_int,
236
+ msg_id=msg_id,
237
+ size=size,
238
+ name=title_clean,
239
+ )
240
+ if updated_id:
241
+ s.indexed += 1
242
+ LOGGER.info(f"[Scanner] Indexed msg {msg_id}: {title_clean}")
243
+ else:
244
+ s.skipped_meta += 1
245
+ except Exception as e:
246
+ LOGGER.error(f"[Scanner] DB insert error msg {msg_id}: {e}")
247
+ s.errors += 1
248
+
249
+ s.processed += 1
250
+ await _update_progress()
251
+
252
+ # Track empty batches to know when to stop
253
+ if batch_had_content:
254
+ empty_streak = 0
255
+ else:
256
+ empty_streak += 1
257
+
258
+ current += BATCH_SIZE
259
+ # Small delay between batches
260
+ await asyncio.sleep(RATE_LIMIT_DELAY)
261
+
262
+ LOGGER.info(f"[Scanner] Finished {s.channel_name}: scanned up to ID {current}, "
263
+ f"{s.total_found} messages found, {s.indexed} indexed")
264
+
265
+
266
+ # ── Bot Commands ─────────────────────────────────────────────────────────
267
+
268
+ @Client.on_message(filters.command('scan') & filters.private & CustomFilters.owner, group=10)
269
+ async def scan_command(client: Client, message: Message):
270
+ """Scan AUTH_CHANNELs for existing content. Skips already-indexed messages."""
271
+ if scan_state.running:
272
+ await message.reply_text(
273
+ "⚠️ A scan is already running. Use /scanstatus to check progress, "
274
+ "or /cancelscan to abort it.",
275
+ quote=True,
276
+ )
277
+ return
278
+
279
+ # Optional: /scan -1001234567890 to scan a single channel
280
+ args = message.text.split(maxsplit=1)
281
+ if len(args) > 1:
282
+ target_channels = [args[1].strip()]
283
+ else:
284
+ target_channels = list(Telegram.AUTH_CHANNEL)
285
+
286
+ if not target_channels:
287
+ await message.reply_text("❌ No AUTH_CHANNELs configured.", quote=True)
288
+ return
289
+
290
+ scan_state.reset()
291
+ scan_state.running = True
292
+ scan_state.started_at = time.time()
293
+ scan_state.status_msg = await message.reply_text(
294
+ "πŸ“‘ <b>Channel scan starting…</b>",
295
+ quote=True,
296
+ parse_mode=enums.ParseMode.HTML,
297
+ )
298
+
299
+ try:
300
+ for ch_id_str in target_channels:
301
+ if scan_state.cancelled:
302
+ break
303
+ try:
304
+ ch_id = int(ch_id_str)
305
+ except ValueError:
306
+ LOGGER.warning(f"[Scanner] Invalid channel ID: {ch_id_str}")
307
+ continue
308
+
309
+ await _scan_channel(client, ch_id)
310
+
311
+ # Final summary
312
+ s = scan_state
313
+ status = "πŸ›‘ Cancelled" if s.cancelled else "βœ… Complete"
314
+ summary = (
315
+ f"<blockquote>πŸ“‘ <b>Scan {status}</b></blockquote>\n\n"
316
+ f"⏱ Duration: <code>{s.elapsed}</code>\n"
317
+ f"πŸ“¨ Total messages seen: <code>{s.total_found}</code>\n"
318
+ f"βœ… Newly indexed: <code>{s.indexed}</code>\n"
319
+ f"⏭ Skipped (already in DB): <code>{s.skipped_dup}</code>\n"
320
+ f"⚠️ Skipped (metadata fail): <code>{s.skipped_meta}</code>\n"
321
+ f"πŸ“Ž Skipped (non-video): <code>{s.skipped_nonvid}</code>\n"
322
+ f"❌ Errors: <code>{s.errors}</code>"
323
+ )
324
+ try:
325
+ await s.status_msg.edit_text(summary, parse_mode=enums.ParseMode.HTML)
326
+ except Exception:
327
+ await message.reply_text(summary, parse_mode=enums.ParseMode.HTML)
328
+
329
+ # Send a separate notification so the user gets a Telegram ping
330
+ # (editing a message doesn't trigger a notification)
331
+ if s.processed > 20:
332
+ notify = (
333
+ f"{'πŸ›‘ Scan cancelled' if s.cancelled else 'βœ… Scan complete'} β€” "
334
+ f"{s.indexed} indexed, {s.skipped_dup} skipped, "
335
+ f"{s.errors} errors ({s.elapsed})"
336
+ )
337
+ await message.reply_text(notify)
338
+
339
+ except (ChannelPrivate, ChatAdminRequired) as e:
340
+ await message.reply_text(
341
+ f"❌ <b>Access denied</b> to channel.\n\n"
342
+ f"Make sure the bot is an admin in the channel.\n"
343
+ f"<code>{e}</code>",
344
+ parse_mode=enums.ParseMode.HTML,
345
+ )
346
+ except Exception as e:
347
+ LOGGER.error(f"[Scanner] Unexpected error: {e}")
348
+ await message.reply_text(f"❌ Scan failed: <code>{e}</code>",
349
+ parse_mode=enums.ParseMode.HTML)
350
+ finally:
351
+ scan_state.running = False
352
+
353
+
354
+ @Client.on_message(filters.command('rescan') & filters.private & CustomFilters.owner, group=10)
355
+ async def rescan_command(client: Client, message: Message):
356
+ """Wipe all DB entries that belong to AUTH_CHANNELs, then do a full scan.
357
+
358
+ This is the nuclear option β€” it re-indexes everything from scratch.
359
+ """
360
+ if scan_state.running:
361
+ await message.reply_text(
362
+ "⚠️ A scan is already running. Cancel it first with /cancelscan.",
363
+ quote=True,
364
+ )
365
+ return
366
+
367
+ channels = list(Telegram.AUTH_CHANNEL)
368
+ if not channels:
369
+ await message.reply_text("❌ No AUTH_CHANNELs configured.", quote=True)
370
+ return
371
+
372
+ confirm_msg = await message.reply_text(
373
+ "⚠️ <b>RESCAN</b> will <u>delete all existing DB entries</u> "
374
+ "for your AUTH_CHANNELs and re-index from scratch.\n\n"
375
+ "Send <code>/rescan confirm</code> to proceed.",
376
+ quote=True,
377
+ parse_mode=enums.ParseMode.HTML,
378
+ )
379
+
380
+ args = message.text.split()
381
+ if len(args) < 2 or args[1].lower() != "confirm":
382
+ return
383
+
384
+ # Purge existing entries for these channels
385
+ purge_msg = await message.reply_text(
386
+ "πŸ—‘ Purging existing entries…", parse_mode=enums.ParseMode.HTML
387
+ )
388
+ purged = 0
389
+ for ch_id_str in channels:
390
+ channel_int = int(ch_id_str.replace("-100", ""))
391
+ purged += await _purge_channel_entries(channel_int)
392
+
393
+ await purge_msg.edit_text(
394
+ f"πŸ—‘ Purged <code>{purged}</code> stream entries. Starting full scan…",
395
+ parse_mode=enums.ParseMode.HTML,
396
+ )
397
+
398
+ # Now run a normal scan
399
+ message.text = "/scan" # trick to reuse scan_command logic
400
+ await scan_command(client, message)
401
+
402
+
403
+ async def _purge_channel_entries(channel_int: int) -> int:
404
+ """Delete all movie/tv stream entries whose encoded chat_id matches this channel."""
405
+ from Backend.helper.encrypt import decode_string
406
+
407
+ purged = 0
408
+ for i in range(1, db.current_db_index + 1):
409
+ storage = db.dbs.get(f"storage_{i}")
410
+ if storage is None:
411
+ continue
412
+
413
+ # Purge movies
414
+ async for movie in storage["movie"].find({}):
415
+ remaining = []
416
+ changed = False
417
+ for q in movie.get("telegram", []):
418
+ try:
419
+ decoded = await decode_string(q["id"])
420
+ if int(decoded["chat_id"]) == channel_int:
421
+ purged += 1
422
+ changed = True
423
+ continue
424
+ except Exception:
425
+ pass
426
+ remaining.append(q)
427
+ if changed:
428
+ if remaining:
429
+ movie["telegram"] = remaining
430
+ await storage["movie"].replace_one({"_id": movie["_id"]}, movie)
431
+ else:
432
+ await storage["movie"].delete_one({"_id": movie["_id"]})
433
+
434
+ # Purge TV
435
+ async for tv in storage["tv"].find({}):
436
+ tv_changed = False
437
+ for season in tv.get("seasons", []):
438
+ for episode in season.get("episodes", []):
439
+ remaining = []
440
+ for q in episode.get("telegram", []):
441
+ try:
442
+ decoded = await decode_string(q["id"])
443
+ if int(decoded["chat_id"]) == channel_int:
444
+ purged += 1
445
+ tv_changed = True
446
+ continue
447
+ except Exception:
448
+ pass
449
+ remaining.append(q)
450
+ episode["telegram"] = remaining
451
+ # Remove empty episodes
452
+ season["episodes"] = [
453
+ ep for ep in season["episodes"] if ep.get("telegram")
454
+ ]
455
+ # Remove empty seasons
456
+ tv["seasons"] = [s for s in tv["seasons"] if s.get("episodes")]
457
+ if tv_changed:
458
+ if tv["seasons"]:
459
+ await storage["tv"].replace_one({"_id": tv["_id"]}, tv)
460
+ else:
461
+ await storage["tv"].delete_one({"_id": tv["_id"]})
462
+
463
+ return purged
464
+
465
+
466
+ @Client.on_message(filters.command('scanstatus') & filters.private & CustomFilters.owner, group=10)
467
+ async def scan_status_command(client: Client, message: Message):
468
+ """Show current scan progress."""
469
+ s = scan_state
470
+ if not s.running:
471
+ await message.reply_text("ℹ️ No scan is currently running.", quote=True)
472
+ return
473
+
474
+ text = (
475
+ f"<blockquote>πŸ“‘ <b>Scan in progress:</b> {s.channel_name}</blockquote>\n\n"
476
+ f"⏱ Elapsed: <code>{s.elapsed}</code>\n"
477
+ f"πŸ“¨ Processed: <code>{s.processed}</code>\n"
478
+ f"βœ… Indexed: <code>{s.indexed}</code>\n"
479
+ f"⏭ Skipped (duplicate): <code>{s.skipped_dup}</code>\n"
480
+ f"⚠️ Skipped (metadata fail): <code>{s.skipped_meta}</code>\n"
481
+ f"πŸ“Ž Skipped (non-video): <code>{s.skipped_nonvid}</code>\n"
482
+ f"❌ Errors: <code>{s.errors}</code>"
483
+ )
484
+ await message.reply_text(text, quote=True, parse_mode=enums.ParseMode.HTML)
485
+
486
+
487
+ @Client.on_message(filters.command('cancelscan') & filters.private & CustomFilters.owner, group=10)
488
+ async def cancel_scan_command(client: Client, message: Message):
489
+ """Abort a running scan gracefully."""
490
+ if not scan_state.running:
491
+ await message.reply_text("ℹ️ No scan is currently running.", quote=True)
492
+ return
493
+
494
+ scan_state.cancelled = True
495
+ await message.reply_text(
496
+ "πŸ›‘ Scan cancellation requested. Will stop after current message.",
497
+ quote=True,
498
+ )
Backend/pyrofork/plugins/utilities.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utilities Plugin β€” stats, search, DB integrity check, channel backup/restore.
3
+
4
+ Commands (owner-only, private chat):
5
+ /stats β€” DB dashboard (counts, sizes, uptime)
6
+ /search <title> β€” Search your DB for a movie or show
7
+ /dbcheck β€” Find orphaned stream entries (dead Telegram messages)
8
+ /dbcheck purge β€” Find and delete orphaned entries
9
+ /exportchannels β€” Export AUTH_CHANNEL list as JSON
10
+ /importchannels <json> β€” Import channels from JSON
11
+
12
+ Drop this file into Backend/pyrofork/plugins/utilities.py
13
+ """
14
+
15
+ import asyncio
16
+ import json
17
+ import time
18
+ from pyrogram import filters, Client, enums
19
+ from pyrogram.types import Message
20
+ from pyrogram.errors import FloodWait
21
+
22
+ from Backend.helper.custom_filter import CustomFilters
23
+ from Backend.logger import LOGGER
24
+ from Backend import db, StartTime, __version__
25
+ from Backend.config import Telegram
26
+ from Backend.helper.encrypt import decode_string
27
+
28
+
29
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
30
+ # /stats β€” Quick dashboard
31
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
32
+
33
+ def _format_uptime(seconds: int) -> str:
34
+ d, seconds = divmod(seconds, 86400)
35
+ h, seconds = divmod(seconds, 3600)
36
+ m, s = divmod(seconds, 60)
37
+ parts = []
38
+ if d:
39
+ parts.append(f"{d}d")
40
+ if h:
41
+ parts.append(f"{h}h")
42
+ if m:
43
+ parts.append(f"{m}m")
44
+ parts.append(f"{s}s")
45
+ return " ".join(parts)
46
+
47
+
48
+ def _format_bytes(size_bytes: int) -> str:
49
+ for unit in ["B", "KB", "MB", "GB"]:
50
+ if size_bytes < 1024:
51
+ return f"{size_bytes:.1f} {unit}"
52
+ size_bytes /= 1024
53
+ return f"{size_bytes:.1f} TB"
54
+
55
+
56
+ @Client.on_message(filters.command('stats') & filters.private & CustomFilters.owner, group=10)
57
+ async def stats_command(client: Client, message: Message):
58
+ """Show a DB and system dashboard."""
59
+ status_msg = await message.reply_text(
60
+ "πŸ“Š Gathering stats…", quote=True
61
+ )
62
+
63
+ try:
64
+ total_movies = 0
65
+ total_tv = 0
66
+ total_episodes = 0
67
+ total_streams = 0
68
+ total_db_size = 0
69
+
70
+ for i in range(1, db.current_db_index + 1):
71
+ storage = db.dbs.get(f"storage_{i}")
72
+ if storage is None:
73
+ continue
74
+
75
+ # Movie counts
76
+ movie_count = await storage["movie"].count_documents({})
77
+ total_movies += movie_count
78
+
79
+ # Count movie streams
80
+ async for movie in storage["movie"].find({}, {"telegram": 1}):
81
+ total_streams += len(movie.get("telegram", []))
82
+
83
+ # TV counts
84
+ tv_count = await storage["tv"].count_documents({})
85
+ total_tv += tv_count
86
+
87
+ # Count episodes and TV streams
88
+ async for show in storage["tv"].find({}, {"seasons": 1}):
89
+ for season in show.get("seasons", []):
90
+ for episode in season.get("episodes", []):
91
+ total_episodes += 1
92
+ total_streams += len(episode.get("telegram", []))
93
+
94
+ # DB size
95
+ try:
96
+ db_stats = await storage.command("dbStats")
97
+ total_db_size += db_stats.get("dataSize", 0)
98
+ except Exception:
99
+ pass
100
+
101
+ uptime_sec = int(time.time() - StartTime)
102
+ channels_count = len(Telegram.AUTH_CHANNEL)
103
+
104
+ text = (
105
+ f"<blockquote>πŸ“Š <b>Telegram-Stremio v{__version__}</b></blockquote>\n\n"
106
+ f"<b>Content</b>\n"
107
+ f" 🎬 Movies: <code>{total_movies}</code>\n"
108
+ f" πŸ“Ί TV Shows: <code>{total_tv}</code>\n"
109
+ f" 🎞 Episodes: <code>{total_episodes}</code>\n"
110
+ f" πŸ“ Total streams: <code>{total_streams}</code>\n\n"
111
+ f"<b>System</b>\n"
112
+ f" ⏱ Uptime: <code>{_format_uptime(uptime_sec)}</code>\n"
113
+ f" πŸ’Ύ DB size: <code>{_format_bytes(total_db_size)}</code>\n"
114
+ f" πŸ—„ Storage DBs: <code>{db.current_db_index}</code>\n"
115
+ f" πŸ“‘ AUTH channels: <code>{channels_count}</code>\n"
116
+ )
117
+ await status_msg.edit_text(text, parse_mode=enums.ParseMode.HTML)
118
+
119
+ except Exception as e:
120
+ LOGGER.error(f"[Stats] Error: {e}")
121
+ await status_msg.edit_text(f"❌ Error gathering stats: <code>{e}</code>",
122
+ parse_mode=enums.ParseMode.HTML)
123
+
124
+
125
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
126
+ # /search <title> β€” Search own DB
127
+ # ━━━━━━━━━━━━━━━━━━��━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
128
+
129
+ @Client.on_message(filters.command('search') & filters.private & CustomFilters.owner, group=10)
130
+ async def search_command(client: Client, message: Message):
131
+ """Search the DB for movies or TV shows by title."""
132
+ args = message.text.split(maxsplit=1)
133
+ if len(args) < 2:
134
+ await message.reply_text(
135
+ "Usage: /search <code>&lt;title&gt;</code>\n\n"
136
+ "Example: <code>/search Breaking Bad</code>",
137
+ quote=True,
138
+ parse_mode=enums.ParseMode.HTML,
139
+ )
140
+ return
141
+
142
+ query = args[1].strip()
143
+ import re
144
+ pattern = re.compile(re.escape(query), re.IGNORECASE)
145
+ regex_filter = {"title": {"$regex": pattern.pattern, "$options": "i"}}
146
+ results = []
147
+
148
+ for i in range(1, db.current_db_index + 1):
149
+ storage = db.dbs.get(f"storage_{i}")
150
+ if storage is None:
151
+ continue
152
+
153
+ # Search movies
154
+ try:
155
+ movies = await storage["movie"].find(regex_filter).to_list(length=10)
156
+ for movie in movies:
157
+ qualities = movie.get("telegram", [])
158
+ q_list = ", ".join(q.get("quality", "?") for q in qualities) or "none"
159
+ results.append(
160
+ f"🎬 <b>{movie.get('title', '?')}</b> ({movie.get('release_year', '?')})\n"
161
+ f" TMDB: <code>{movie.get('tmdb_id', '?')}</code> | "
162
+ f"IMDb: <code>{movie.get('imdb_id', '?')}</code>\n"
163
+ f" Qualities: {q_list} | DB: storage_{i}"
164
+ )
165
+ except Exception as e:
166
+ LOGGER.error(f"[Search] Movie search error in storage_{i}: {e}")
167
+
168
+ # Search TV shows
169
+ try:
170
+ shows = await storage["tv"].find(regex_filter).to_list(length=10)
171
+ for show in shows:
172
+ seasons = show.get("seasons", [])
173
+ ep_count = sum(len(s.get("episodes", [])) for s in seasons)
174
+ stream_count = sum(
175
+ len(ep.get("telegram", []))
176
+ for s in seasons for ep in s.get("episodes", [])
177
+ )
178
+ season_nums = sorted(s.get("season_number", 0) for s in seasons)
179
+ s_range = f"S{season_nums[0]}–S{season_nums[-1]}" if season_nums else "?"
180
+ results.append(
181
+ f"πŸ“Ί <b>{show.get('title', '?')}</b> ({show.get('release_year', '?')})\n"
182
+ f" TMDB: <code>{show.get('tmdb_id', '?')}</code> | "
183
+ f"IMDb: <code>{show.get('imdb_id', '?')}</code>\n"
184
+ f" {s_range} | {ep_count} episodes | {stream_count} streams | DB: storage_{i}"
185
+ )
186
+ except Exception as e:
187
+ LOGGER.error(f"[Search] TV search error in storage_{i}: {e}")
188
+
189
+ if not results:
190
+ # Debug: check if DB has any data at all
191
+ debug = ""
192
+ try:
193
+ for i in range(1, db.current_db_index + 1):
194
+ storage = db.dbs.get(f"storage_{i}")
195
+ if storage is None:
196
+ continue
197
+ mc = await storage["movie"].count_documents({})
198
+ tc = await storage["tv"].count_documents({})
199
+ # Grab a sample title to confirm data exists
200
+ sample = await storage["movie"].find_one({}, {"title": 1})
201
+ sample_title = sample.get("title", "?") if sample else "empty"
202
+ debug = f"\n\n<i>Debug: storage_{i} has {mc} movies, {tc} tv. Sample: {sample_title}</i>"
203
+ except Exception:
204
+ pass
205
+
206
+ await message.reply_text(
207
+ f"πŸ” No results for <b>{query}</b>{debug}",
208
+ quote=True,
209
+ parse_mode=enums.ParseMode.HTML,
210
+ )
211
+ return
212
+
213
+ header = f"<blockquote>πŸ” <b>Search results for:</b> {query}</blockquote>\n\n"
214
+ body = "\n\n".join(results[:15]) # cap at 15 results
215
+ footer = ""
216
+ if len(results) > 15:
217
+ footer = f"\n\n<i>…and {len(results) - 15} more. Try a more specific query.</i>"
218
+
219
+ await message.reply_text(
220
+ header + body + footer,
221
+ quote=True,
222
+ parse_mode=enums.ParseMode.HTML,
223
+ )
224
+
225
+
226
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
227
+ # /dbcheck β€” Integrity checker (find orphaned streams)
228
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
229
+
230
+ @Client.on_message(filters.command('dbcheck') & filters.private & CustomFilters.owner, group=10)
231
+ async def dbcheck_command(client: Client, message: Message):
232
+ """Check for orphaned DB entries where the Telegram message no longer exists."""
233
+ args = message.text.split()
234
+ purge_mode = len(args) > 1 and args[1].lower() == "purge"
235
+
236
+ mode_label = "πŸ—‘ Purge" if purge_mode else "πŸ” Check"
237
+ status_msg = await message.reply_text(
238
+ f"<blockquote>{mode_label} mode β€” scanning all stream entries…</blockquote>\n\n"
239
+ f"This may take a while for large databases.",
240
+ quote=True,
241
+ parse_mode=enums.ParseMode.HTML,
242
+ )
243
+
244
+ checked = 0
245
+ dead = 0
246
+ alive = 0
247
+ errors = 0
248
+ purged = 0
249
+ dead_entries = [] # list of (collection, doc_id, stream_hash, title)
250
+
251
+ try:
252
+ for i in range(1, db.current_db_index + 1):
253
+ storage = db.dbs.get(f"storage_{i}")
254
+ if storage is None:
255
+ continue
256
+
257
+ # Check movies
258
+ async for movie in storage["movie"].find({}):
259
+ title = movie.get("title", "Unknown")
260
+ for q in movie.get("telegram", []):
261
+ stream_hash = q.get("id")
262
+ if not stream_hash:
263
+ continue
264
+ try:
265
+ decoded = await decode_string(stream_hash)
266
+ chat_id = int(f"-100{decoded['chat_id']}")
267
+ msg_id = int(decoded['msg_id'])
268
+ msg = await client.get_messages(chat_id, msg_id)
269
+ checked += 1
270
+ if msg.empty:
271
+ dead += 1
272
+ dead_entries.append(("movie", stream_hash, title, q.get("quality", "?")))
273
+ else:
274
+ alive += 1
275
+ except FloodWait as e:
276
+ await asyncio.sleep(e.value)
277
+ except Exception as e:
278
+ errors += 1
279
+ LOGGER.warning(f"[DBCheck] Error checking {stream_hash}: {e}")
280
+
281
+ # Rate limit
282
+ await asyncio.sleep(0.3)
283
+
284
+ # Progress update every 25 checks
285
+ if checked % 25 == 0:
286
+ try:
287
+ await status_msg.edit_text(
288
+ f"<blockquote>{mode_label} β€” in progress…</blockquote>\n\n"
289
+ f"Checked: <code>{checked}</code> | "
290
+ f"Dead: <code>{dead}</code> | "
291
+ f"Alive: <code>{alive}</code> | "
292
+ f"Errors: <code>{errors}</code>",
293
+ parse_mode=enums.ParseMode.HTML,
294
+ )
295
+ except Exception:
296
+ pass
297
+
298
+ # Check TV shows
299
+ async for show in storage["tv"].find({}):
300
+ title = show.get("title", "Unknown")
301
+ for season in show.get("seasons", []):
302
+ for episode in season.get("episodes", []):
303
+ for q in episode.get("telegram", []):
304
+ stream_hash = q.get("id")
305
+ if not stream_hash:
306
+ continue
307
+ try:
308
+ decoded = await decode_string(stream_hash)
309
+ chat_id = int(f"-100{decoded['chat_id']}")
310
+ msg_id = int(decoded['msg_id'])
311
+ msg = await client.get_messages(chat_id, msg_id)
312
+ checked += 1
313
+ if msg.empty:
314
+ dead += 1
315
+ ep_label = f"S{season.get('season_number','?')}E{episode.get('episode_number','?')}"
316
+ dead_entries.append(("tv", stream_hash, f"{title} {ep_label}", q.get("quality", "?")))
317
+ else:
318
+ alive += 1
319
+ except FloodWait as e:
320
+ await asyncio.sleep(e.value)
321
+ except Exception as e:
322
+ errors += 1
323
+
324
+ await asyncio.sleep(0.3)
325
+
326
+ if checked % 25 == 0:
327
+ try:
328
+ await status_msg.edit_text(
329
+ f"<blockquote>{mode_label} β€” in progress…</blockquote>\n\n"
330
+ f"Checked: <code>{checked}</code> | "
331
+ f"Dead: <code>{dead}</code> | "
332
+ f"Alive: <code>{alive}</code> | "
333
+ f"Errors: <code>{errors}</code>",
334
+ parse_mode=enums.ParseMode.HTML,
335
+ )
336
+ except Exception:
337
+ pass
338
+
339
+ # Purge dead entries if requested
340
+ if purge_mode and dead_entries:
341
+ for _, stream_hash, _, _ in dead_entries:
342
+ try:
343
+ deleted = await db.delete_media_by_stream_id(stream_hash)
344
+ if deleted:
345
+ purged += 1
346
+ except Exception as e:
347
+ LOGGER.error(f"[DBCheck] Purge failed for {stream_hash}: {e}")
348
+
349
+ # Final summary
350
+ summary = (
351
+ f"<blockquote>{'πŸ—‘' if purge_mode else 'πŸ”'} <b>DB Integrity Check Complete</b></blockquote>\n\n"
352
+ f"βœ… Alive: <code>{alive}</code>\n"
353
+ f"πŸ’€ Dead (orphaned): <code>{dead}</code>\n"
354
+ f"❌ Errors: <code>{errors}</code>\n"
355
+ f"πŸ“ Total checked: <code>{checked}</code>\n"
356
+ )
357
+
358
+ if purge_mode:
359
+ summary += f"\nπŸ—‘ Purged: <code>{purged}</code> / {dead}"
360
+ elif dead > 0:
361
+ summary += f"\nπŸ’‘ Run <code>/dbcheck purge</code> to clean up the {dead} dead entries."
362
+
363
+ # Show sample of dead entries (first 10)
364
+ if dead_entries and not purge_mode:
365
+ summary += "\n\n<b>Sample dead entries:</b>\n"
366
+ for _, _, title, quality in dead_entries[:10]:
367
+ summary += f" β€’ {title} [{quality}]\n"
368
+ if len(dead_entries) > 10:
369
+ summary += f" <i>…and {len(dead_entries) - 10} more</i>"
370
+
371
+ await status_msg.edit_text(summary, parse_mode=enums.ParseMode.HTML)
372
+
373
+ # Send a separate notification so the user gets a ping
374
+ if checked > 50:
375
+ await message.reply_text(
376
+ f"βœ… DB check finished β€” {dead} dead entries found out of {checked} checked.",
377
+ parse_mode=enums.ParseMode.HTML,
378
+ )
379
+
380
+ except Exception as e:
381
+ LOGGER.error(f"[DBCheck] Error: {e}")
382
+ await status_msg.edit_text(
383
+ f"❌ DB check failed: <code>{e}</code>",
384
+ parse_mode=enums.ParseMode.HTML,
385
+ )
386
+
387
+
388
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
389
+ # /exportchannels & /importchannels β€” Backup/restore channel config
390
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
391
+
392
+ @Client.on_message(filters.command('exportchannels') & filters.private & CustomFilters.owner, group=10)
393
+ async def export_channels(client: Client, message: Message):
394
+ """Export current AUTH_CHANNEL list as a copyable JSON block."""
395
+ channels_data = []
396
+ for ch_id in Telegram.AUTH_CHANNEL:
397
+ entry = {"id": ch_id}
398
+ try:
399
+ chat = await client.get_chat(int(ch_id))
400
+ entry["name"] = getattr(chat, "title", "")
401
+ entry["members"] = getattr(chat, "members_count", 0)
402
+ except Exception:
403
+ entry["name"] = "[inaccessible]"
404
+ channels_data.append(entry)
405
+
406
+ export = {
407
+ "version": __version__,
408
+ "exported_at": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
409
+ "channels": channels_data,
410
+ }
411
+
412
+ json_str = json.dumps(export, indent=2, ensure_ascii=False)
413
+
414
+ await message.reply_text(
415
+ f"<blockquote>πŸ“€ <b>Channel Export</b></blockquote>\n\n"
416
+ f"<pre>{json_str}</pre>\n\n"
417
+ f"<i>Use /importchannels to restore this on another instance.</i>",
418
+ quote=True,
419
+ parse_mode=enums.ParseMode.HTML,
420
+ )
421
+
422
+
423
+ @Client.on_message(filters.command('importchannels') & filters.private & CustomFilters.owner, group=10)
424
+ async def import_channels(client: Client, message: Message):
425
+ """Import channels from a JSON export block."""
426
+ args = message.text.split(maxsplit=1)
427
+ if len(args) < 2:
428
+ await message.reply_text(
429
+ "Usage: /importchannels <code>&lt;json&gt;</code>\n\n"
430
+ "Paste the JSON output from /exportchannels after the command.",
431
+ quote=True,
432
+ parse_mode=enums.ParseMode.HTML,
433
+ )
434
+ return
435
+
436
+ raw = args[1].strip()
437
+ try:
438
+ data = json.loads(raw)
439
+ except json.JSONDecodeError as e:
440
+ await message.reply_text(
441
+ f"❌ Invalid JSON: <code>{e}</code>",
442
+ quote=True,
443
+ parse_mode=enums.ParseMode.HTML,
444
+ )
445
+ return
446
+
447
+ channels = data.get("channels", [])
448
+ if not channels:
449
+ await message.reply_text("❌ No channels found in the JSON.", quote=True)
450
+ return
451
+
452
+ added = 0
453
+ skipped = 0
454
+ failed = 0
455
+
456
+ for entry in channels:
457
+ ch_id = str(entry.get("id", "")).strip()
458
+ if not ch_id:
459
+ continue
460
+
461
+ if ch_id in Telegram.AUTH_CHANNEL:
462
+ skipped += 1
463
+ continue
464
+
465
+ # Validate access
466
+ try:
467
+ await client.get_chat(int(ch_id))
468
+ Telegram.AUTH_CHANNEL.append(ch_id)
469
+ added += 1
470
+ except Exception:
471
+ failed += 1
472
+
473
+ # Persist
474
+ if added > 0:
475
+ from Backend.pyrofork.plugins.channels import _save_channels_to_db
476
+ await _save_channels_to_db()
477
+
478
+ await message.reply_text(
479
+ f"<blockquote>πŸ“₯ <b>Channel Import Complete</b></blockquote>\n\n"
480
+ f"βœ… Added: <code>{added}</code>\n"
481
+ f"⏭ Skipped (already exists): <code>{skipped}</code>\n"
482
+ f"❌ Failed (no access): <code>{failed}</code>\n\n"
483
+ f"Total AUTH_CHANNELs: <code>{len(Telegram.AUTH_CHANNEL)}</code>",
484
+ quote=True,
485
+ parse_mode=enums.ParseMode.HTML,
486
+ )