File size: 18,899 Bytes
07f63a8
36dde81
 
07f63a8
36dde81
 
 
 
07f63a8
 
36dde81
07f63a8
 
36dde81
07f63a8
 
 
36dde81
07f63a8
36dde81
 
07f63a8
 
36dde81
07f63a8
 
 
2ca6f44
 
07f63a8
36dde81
 
 
07f63a8
36dde81
 
 
 
07f63a8
36dde81
07f63a8
c12bb0b
36dde81
c12bb0b
e2c4766
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
36dde81
07f63a8
 
 
 
 
 
 
36dde81
07f63a8
 
 
 
36dde81
 
07f63a8
 
 
c12bb0b
07f63a8
 
 
 
 
 
 
 
36dde81
07f63a8
 
 
 
 
 
 
 
36dde81
07f63a8
 
 
 
36dde81
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
c12bb0b
 
 
 
36dde81
 
 
 
c12bb0b
 
 
 
e2c4766
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
36dde81
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
07f63a8
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ca6f44
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
36dde81
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
07f63a8
 
 
 
36dde81
07f63a8
 
 
 
36dde81
07f63a8
 
 
36dde81
07f63a8
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
07f63a8
 
36dde81
07f63a8
 
 
 
 
 
36dde81
07f63a8
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
36dde81
c12bb0b
36dde81
c12bb0b
 
36dde81
c12bb0b
36dde81
c12bb0b
36dde81
 
 
07f63a8
 
 
36dde81
07f63a8
 
36dde81
07f63a8
 
 
36dde81
07f63a8
 
 
 
36dde81
07f63a8
 
 
 
36dde81
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
07f63a8
 
 
 
 
36dde81
 
07f63a8
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e18b74
2ca6f44
07f63a8
 
 
36dde81
07f63a8
 
 
 
36dde81
c12bb0b
 
 
07f63a8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
from __future__ import annotations

import secrets
from typing import Any, Dict, List

import Backend.pyrofork.bot as botmod
from Backend.config import Telegram
from Backend.helper.passwords import hash_password
from Backend.logger import LOGGER

#----- Default values (used when nothing exists in the DB yet)
_DEFAULTS: Dict[str, Any] = {
    "replace_mode": True,
    "duplicate_protection": False,
    "hide_catalog": False,
    "auth_channels": [],
    "tmdb_api": "",
    "tvdb_api": "",
    "base_url": "",
    "upstream_repo": "https://github.com/weebzone/Telegram-Stremio",
    "upstream_branch": "master",
    "admin_username": "admin",
    "admin_password": "admin",
    "session_secret": "",
    "subscription": False,
    "subscription_group_id": 0,
    "approver_ids": [],
    "payment_instructions": "",
    "payment_qr_url": "",
    "http_proxy_url": "",
    "cf_stream_url": "",
    "cf_stream_secret": "",
    "cf_stream_mode": "off",
    "show_proxy_and_non_proxy_both": False,
    "mediaflow_proxy": False,
    "mediaflow_password": "",
    "webdav_user": "",
    "webdav_password": "",
    "multi_tokens": [],
    "helper_tokens": [],
    "extra_databases": [],
    "global_search": False,
    "default_streaming": "bots",
    "global_search_channels": [],
    "anime_channels": [],
    "manual_channels": [],
    "channel_titles": {},
    "announce_new_content": False,
    "announcement_channel": "",
    "skip_channel": "",
    "delete_on_metadata_fail": False,
    "better_poster_enabled": False,
    "better_poster": "",
    "rpdb_enabled": False,
    "rpdb_api_key": "",
    "spatial_poster_enabled": False,
    "spatial_poster": "",
    "stream_formatter": "default",
    "formatter_name": "",
    "formatter_description": "",
    "fanart_enabled": False,
    "fanart_api_key": "",
    "fanart_shuffle": False,
    "fanart_shuffle_interval": 5,
    "fanart_low_res_poster": True,
}


#----- Read legacy Telegram config env values; used only on FIRST startup
def _seed_from_env() -> Dict[str, Any]:
    seed = dict(_DEFAULTS)
    seed.update({
        "replace_mode":                 Telegram.REPLACE_MODE,
        "hide_catalog":                 Telegram.HIDE_CATALOG,
        "auth_channels":                list(Telegram.AUTH_CHANNEL),
        "tmdb_api":                     Telegram.TMDB_API,
        "tvdb_api":                     getattr(Telegram, "TVDB_API", "") or "",
        "base_url":                     Telegram.BASE_URL,
        "upstream_repo":                Telegram.UPSTREAM_REPO,
        "upstream_branch":              Telegram.UPSTREAM_BRANCH,
        "admin_username":               Telegram.ADMIN_USERNAME,
        "admin_password":               hash_password(Telegram.ADMIN_PASSWORD),
        "session_secret":               secrets.token_hex(32),
        "subscription":                 Telegram.SUBSCRIPTION,
        "subscription_group_id":        Telegram.SUBSCRIPTION_GROUP_ID,
        "approver_ids":                 list(Telegram.APPROVER_IDS),
        "global_search_channels":       [],
        "http_proxy_url":               Telegram.HTTP_PROXY_URL,
        "show_proxy_and_non_proxy_both": Telegram.SHOW_PROXY_AND_NON_PROXY_BOTH,
        "multi_tokens":                 [],
        "extra_databases":              list(Telegram.DATABASE[2:]) if len(Telegram.DATABASE) > 2 else [],
    })
    return seed


#----- Immutable settings snapshot
class Settings:
    __slots__ = ("_d",)

    def __init__(self, data: Dict[str, Any]) -> None:
        merged = dict(_DEFAULTS)
        merged.update({k: v for k, v in data.items() if k != "_id"})
        self._d = merged

    #----- Booleans
    @property
    def replace_mode(self) -> bool:
        return bool(self._d["replace_mode"])

    @property
    def duplicate_protection(self) -> bool:
        return bool(self._d.get("duplicate_protection", False))

    @property
    def hide_catalog(self) -> bool:
        return bool(self._d["hide_catalog"])

    @property
    def subscription(self) -> bool:
        return bool(self._d["subscription"])

    @property
    def show_proxy_and_non_proxy_both(self) -> bool:
        return bool(self._d["show_proxy_and_non_proxy_both"])

    @property
    def mediaflow_proxy(self) -> bool:
        return bool(self._d.get("mediaflow_proxy", False))

    @property
    def global_search(self) -> bool:
        return bool(self._d.get("global_search", False))

    @property
    def default_streaming(self) -> str:
        return "userbot" if self._d.get("default_streaming") == "userbot" else "bots"

    @property
    def global_search_channels(self):
        return list(self._d.get("global_search_channels") or [])

    @property
    def anime_channels(self) -> List[str]:
        return list(self._d.get("anime_channels") or [])

    @property
    def manual_channels(self) -> List[str]:
        return list(self._d.get("manual_channels") or [])

    @property
    def channel_titles(self) -> Dict[str, str]:
        raw = self._d.get("channel_titles") or {}
        if not isinstance(raw, dict):
            return {}
        return {str(k): str(v) for k, v in raw.items() if k and v}

    @property
    def announce_new_content(self) -> bool:
        return bool(self._d.get("announce_new_content", False))

    @property
    def delete_on_metadata_fail(self) -> bool:
        return bool(self._d.get("delete_on_metadata_fail", False))

    @property
    def announcement_channel(self) -> str:
        return str(self._d.get("announcement_channel") or "").strip()

    @property
    def skip_channel(self) -> str:
        return str(self._d.get("skip_channel") or "").strip()

    #----- Strings
    @property
    def tmdb_api(self) -> str:
        return str(self._d.get("tmdb_api") or "")

    @property
    def tvdb_api(self) -> str:
        return str(self._d.get("tvdb_api") or "").strip()

    @property
    def base_url(self) -> str:
        return str(self._d.get("base_url") or "").rstrip("/")

    @property
    def upstream_repo(self) -> str:
        return str(self._d.get("upstream_repo") or "")

    @property
    def upstream_branch(self) -> str:
        return str(self._d.get("upstream_branch") or "")

    @property
    def admin_username(self) -> str:
        return str(self._d.get("admin_username") or "admin")

    @property
    def admin_password(self) -> str:
        return str(self._d.get("admin_password") or "admin")

    @property
    def session_secret(self) -> str:
        return str(self._d.get("session_secret") or "")

    @property
    def http_proxy_url(self) -> str:
        return str(self._d.get("http_proxy_url") or "")

    @property
    def cf_stream_url(self) -> str:
        return str(self._d.get("cf_stream_url") or "").rstrip("/")

    @property
    def cf_stream_secret(self) -> str:
        return str(self._d.get("cf_stream_secret") or "")

    #----- "off", "cloudflare" (CF links only) or "both" (CF + direct links)
    @property
    def cf_stream_mode(self) -> str:
        mode = str(self._d.get("cf_stream_mode") or "off")
        return mode if mode in ("off", "cloudflare", "both") else "off"

    @property
    def mediaflow_password(self) -> str:
        return str(self._d.get("mediaflow_password") or "")

    @property
    def webdav_user(self) -> str:
        return str(self._d.get("webdav_user") or "").strip()

    @property
    def webdav_password(self) -> str:
        return str(self._d.get("webdav_password") or "")

    @property
    def payment_instructions(self) -> str:
        return str(self._d.get("payment_instructions") or "")

    @property
    def payment_qr_url(self) -> str:
        return str(self._d.get("payment_qr_url") or "")

    @property
    def better_poster_enabled(self) -> bool:
        return bool(self._d.get("better_poster_enabled", False))

    @property
    def better_poster(self) -> str:
        return str(self._d.get("better_poster") or "").strip()

    @property
    def rpdb_enabled(self) -> bool:
        return bool(self._d.get("rpdb_enabled", False))

    @property
    def rpdb_api_key(self) -> str:
        return str(self._d.get("rpdb_api_key") or "").strip()

    @property
    def stream_formatter(self) -> str:
        return str(self._d.get("stream_formatter") or "default")

    @property
    def formatter_name(self) -> str:
        return str(self._d.get("formatter_name") or "")

    @property
    def formatter_description(self) -> str:
        return str(self._d.get("formatter_description") or "")

    @property
    def spatial_poster_enabled(self) -> bool:
        return bool(self._d.get("spatial_poster_enabled", False))

    @property
    def spatial_poster(self) -> str:
        return str(self._d.get("spatial_poster") or "").strip()

    @property
    def fanart_enabled(self) -> bool:
        return bool(self._d.get("fanart_enabled", False))

    @property
    def fanart_api_key(self) -> str:
        return str(self._d.get("fanart_api_key") or "").strip()

    @property
    def fanart_shuffle(self) -> bool:
        return bool(self._d.get("fanart_shuffle", False))

    @property
    def fanart_low_res_poster(self) -> bool:
        return bool(self._d.get("fanart_low_res_poster", True))

    #----- Integers
    @property
    def subscription_group_id(self) -> int:
        return int(self._d.get("subscription_group_id") or 0)

    @property
    def fanart_shuffle_interval(self) -> int:
        try:
            return max(0, int(self._d.get("fanart_shuffle_interval", 5)))
        except (ValueError, TypeError):
            return 5

    #----- Lists
    @property
    def auth_channels(self) -> List[str]:
        return list(self._d.get("auth_channels") or [])

    @property
    def approver_ids(self) -> List[int]:
        return [int(x) for x in (self._d.get("approver_ids") or [])]

    @property
    def multi_tokens(self) -> List[str]:
        return list(self._d.get("multi_tokens") or [])

    @property
    def helper_tokens(self) -> List[str]:
        return list(self._d.get("helper_tokens") or [])

    @property
    def extra_databases(self) -> List[str]:
        return list(self._d.get("extra_databases") or [])

    #----- Serialisation
    def to_dict(self) -> Dict[str, Any]:
        return dict(self._d)


#----- Manager singleton exposing the current settings snapshot
class SettingsManager:
    _current: Settings | None = None

    #----- Bootstrap from DB, seeding from env on first run
    @classmethod
    async def initialize(cls, db) -> None:
        raw = await db.get_settings()
        if not raw:
            LOGGER.info("SettingsManager: no settings in DB — seeding from config.env.")
            seed = _seed_from_env()
            await db.save_settings(seed)
            cls._current = Settings(seed)
        else:
            cls._current = Settings(raw)

        #----- Backfill & persist a session secret for installs that predate this setting,
        #----- otherwise a new random key would be generated every restart (logging admins out)
        if not cls._current.session_secret:
            data = cls._current.to_dict()
            data["session_secret"] = secrets.token_hex(32)
            await db.save_settings(data)
            cls._current = Settings(data)
            LOGGER.info("SettingsManager: generated and stored a new persistent session secret.")

        LOGGER.info("SettingsManager: settings loaded successfully.")

    #----- Reload settings from DB (call after an external change)
    @classmethod
    async def reload(cls, db) -> None:
        raw = await db.get_settings()
        if raw:
            cls._current = Settings(raw)

    #----- Current snapshot (empty defaults if uninitialised)
    @classmethod
    def current(cls) -> Settings:
        if cls._current is None:
            return Settings({})
        return cls._current

    @staticmethod
    def _all_channel_ids(data: dict) -> set:
        ids = set()
        for key in ("auth_channels", "global_search_channels", "manual_channels", "anime_channels"):
            for c in (data.get(key) or []):
                c = str(c).strip()
                if c:
                    ids.add(c)
        for key in ("announcement_channel", "skip_channel"):
            v = str(data.get(key) or "").strip()
            if v:
                ids.add(v)
        return ids

    @classmethod
    async def _sync_channel_titles(cls, data: dict) -> dict:
        active = cls._all_channel_ids(data)
        existing = data.get("channel_titles") or {}
        if not isinstance(existing, dict):
            existing = {}
        titles = {str(k): str(v) for k, v in existing.items() if str(k) in active and v}
        missing = [cid for cid in active if cid not in titles]
        if missing:
            clients = []
            stream = getattr(botmod, "StreamBot", None)
            if stream is not None:
                clients.append(stream)
            if botmod.Userbot is not None:
                clients.append(botmod.Userbot)
            for cid in missing:
                resolved = None
                for client in clients:
                    try:
                        chat = await client.get_chat(int(cid))
                        if chat and getattr(chat, "title", None):
                            resolved = chat.title
                            break
                    except Exception:
                        continue
                if resolved:
                    titles[cid] = resolved
        data["channel_titles"] = titles
        return titles

    #----- Persist new values, flip the snapshot, and reinitialise dependents
    @classmethod
    async def update(cls, db, new_values: Dict[str, Any]) -> Dict[str, str]:
        old = cls.current().to_dict()
        merged = dict(old)
        merged.update(new_values)

        results: Dict[str, str] = {}

        #----- Global Search requires a Userbot session; enforce it server-side
        if merged.get("global_search"):
            if botmod.Userbot is None:
                merged["global_search"] = False
                LOGGER.warning(
                    "SettingsManager: rejected global_search=True — no Userbot session connected."
                )
                results["global_search"] = "rejected — connect a Telegram session in Settings first"

        await cls._sync_channel_titles(merged)

        #----- Phase 1: validate/apply changes that can abort the save
        old_extra = old.get("extra_databases") or []
        new_extra = merged.get("extra_databases") or []
        if old_extra != new_extra:
            result = await db.reload_extra_databases(new_extra)
            results["databases"] = result.get("message", "databases reloaded")

        #----- Phase 2: persist and flip the in-memory snapshot
        await db.save_settings(merged)
        cls._current = Settings(merged)

        #----- Phase 3: reinit everything that reads current()
        results.update(await cls._reinit_dependent(old, merged))

        return results

    #----- Reinit logic (runs AFTER _current has been updated)
    @classmethod
    async def _reinit_dependent(cls, old: dict, new: dict) -> Dict[str, str]:
        results: Dict[str, str] = {}

        #----- Multi-tokens changed: hot-reload Pyrogram helper clients
        old_tokens = old.get("multi_tokens") or []
        new_tokens = new.get("multi_tokens") or []
        if old_tokens != new_tokens:
            try:
                from Backend.pyrofork.clients import reload_multi_token_clients
                result = await reload_multi_token_clients()
                results["multi_tokens"] = (
                    f"{result['started']} started, {result['stopped']} stopped "
                    f"({result['total_clients']} active)"
                )
            except Exception as exc:
                LOGGER.error(f"SettingsManager reinit multi_tokens: {exc}")
                results["multi_tokens"] = f"error: {exc}"

        if (old.get("helper_tokens") or []) != (new.get("helper_tokens") or []):
            from Backend.helper.own_bots import reload_helpers
            results["helper_tokens"] = f"{await reload_helpers()} helper bot(s) active"

        #----- Auth channels changed
        old_channels = old.get("auth_channels") or []
        new_channels = new.get("auth_channels") or []
        if old_channels != new_channels:
            results["auth_channels"] = f"{len(new_channels)} channel(s) saved"

        #----- Proxy settings changed
        proxy_keys = {"http_proxy_url", "show_proxy_and_non_proxy_both", "mediaflow_proxy", "mediaflow_password"}
        if any(old.get(k) != new.get(k) for k in proxy_keys):
            results["proxy"] = "updated — applies to next outbound request"

        #----- Cloudflare streaming settings changed (read live per request)
        cf_keys = {"cf_stream_url", "cf_stream_secret", "cf_stream_mode"}
        if any(old.get(k) != new.get(k) for k in cf_keys):
            results["cloudflare"] = "updated — new stream links use it right away"

        #----- Bot tokens or Cloudflare settings changed: have the Worker reload them now
        if old_tokens != new_tokens or any(old.get(k) != new.get(k) for k in cf_keys):
            from Backend.helper.cf_stream import sync_worker_soon
            sync_worker_soon()

        #----- Subscription enabled/disabled: start or stop the checker task
        if old.get("subscription") != new.get("subscription"):
            try:
                from Backend.helper import subscription_task_manager
                from Backend.pyrofork.bot import StreamBot

                if new.get("subscription"):
                    await subscription_task_manager.start(StreamBot)
                    results["subscription"] = "checker task started"
                else:
                    await subscription_task_manager.stop()
                    results["subscription"] = "checker task stopped"
            except Exception as exc:
                LOGGER.error(f"SettingsManager reinit subscription: {exc}")
                results["subscription"] = f"error: {exc}"
        else:
            sub_keys = {"subscription_group_id", "approver_ids",
                        "payment_instructions", "payment_qr_url"}
            if any(old.get(k) != new.get(k) for k in sub_keys):
                results["subscription"] = "settings reloaded in-memory"

        #----- Admin credentials changed
        cred_keys = {"admin_username", "admin_password"}
        if any(old.get(k) != new.get(k) for k in cred_keys):
            results["admin_credentials"] = "updated — takes effect on next login"

        #----- Global Search toggle changed (module reads current() live per call)
        if old.get("global_search") != new.get("global_search") and "global_search" not in results:
            results["global_search"] = "enabled" if new.get("global_search") else "disabled"

        return results