-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathtelegram_bot.py
More file actions
2987 lines (2474 loc) · 92.9 KB
/
Copy pathtelegram_bot.py
File metadata and controls
2987 lines (2474 loc) · 92.9 KB
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import os
import re
import signal
import shutil
import sqlite3
import subprocess
import sys
import time
import uuid
from html import escape
from pathlib import Path
from urllib.parse import unquote, urlparse
from dotenv import load_dotenv
from pyrogram import Client, enums, filters, idle
from pyrogram.types import (
BotCommand,
CallbackQuery,
InlineKeyboardButton,
InlineKeyboardMarkup,
KeyboardButton,
Message,
ReplyKeyboardMarkup,
)
from rubpy import Client as RubikaClient
import requests
from task_store import (
DOWNLOAD_DIR,
SESSION_DIR,
apply_runtime_settings,
append_task,
build_status_text,
clear_processing,
cleanup_local_file,
ensure_storage_dirs,
find_failed_entry,
has_rubika_session,
human_size,
human_duration,
human_speed,
find_queued_task,
is_cancelled,
load_processing,
load_runtime_settings,
load_worker_pid,
ltr_code,
mark_cancelled,
normalize_upload_filename,
pop_telegram_events,
processing_task_is_active,
queue_size,
read_failed_entries,
read_queue_tasks,
remove_queued_task,
runtime_path,
safe_filename,
save_runtime_settings,
split_name,
write_failed_entries,
)
load_dotenv()
def env_int(name: str, default: int = 0) -> int:
raw = os.getenv(name, "").strip()
if not raw:
return default
try:
return int(raw)
except ValueError:
print(
f"Warning: ignoring invalid integer value for {name}: {raw!r}",
flush=True,
)
return default
API_ID = env_int("API_ID")
API_HASH = os.getenv("API_HASH", "").strip()
BOT_TOKEN = os.getenv("BOT_TOKEN", "").strip()
OWNER_TELEGRAM_ID = env_int("OWNER_TELEGRAM_ID")
RUBIKA_CONNECT_TIMEOUT = env_int("RUBIKA_CONNECT_TIMEOUT", 25)
TELEGRAM_SESSION = str(
runtime_path(
os.getenv("TELEGRAM_SESSION", "walrus").strip() or "walrus",
SESSION_DIR,
)
)
MAX_FILE_BYTES = env_int("WALRUS_MAX_FILE_BYTES", 8 * 1024 * 1024 * 1024)
MIN_FREE_BYTES = env_int("WALRUS_MIN_FREE_BYTES", 512 * 1024 * 1024)
ALLOW_FILE_URLS = os.getenv("WALRUS_ALLOW_FILE_URLS", "").strip().lower() in {"1", "true", "yes"}
ensure_storage_dirs()
if not API_ID or not API_HASH or not BOT_TOKEN:
raise RuntimeError("Please set API_ID, API_HASH and BOT_TOKEN as Space secrets.")
def telegram_session_files() -> list[Path]:
path = Path(TELEGRAM_SESSION)
candidates = [path]
if path.suffix == "":
candidates.append(Path(f"{path}.session"))
else:
candidates.append(path.with_suffix(".session"))
for session_path in list(candidates):
candidates.extend(
[
Path(f"{session_path}-journal"),
Path(f"{session_path}-shm"),
Path(f"{session_path}-wal"),
]
)
unique_candidates = []
for candidate in candidates:
if candidate not in unique_candidates:
unique_candidates.append(candidate)
return unique_candidates
def clear_telegram_session_files(reason: str) -> None:
removed = []
for path in telegram_session_files():
try:
if path.exists():
path.unlink()
removed.append(path.name)
except OSError as error:
print(f"Failed to remove Telegram session file {path}: {error}", flush=True)
if removed:
print(
f"Cleared Telegram session files after {reason}: {', '.join(removed)}",
flush=True,
)
else:
print(f"No Telegram session files found to clear after {reason}.", flush=True)
def is_auth_key_duplicated(error: Exception) -> bool:
text = str(error)
return (
type(error).__name__ == "AuthKeyDuplicated"
or "AUTH_KEY_DUPLICATED" in text
or "AuthKeyDuplicated" in text
)
app = Client(
TELEGRAM_SESSION,
api_id=API_ID,
api_hash=API_HASH,
bot_token=BOT_TOKEN,
in_memory=True,
)
ACTIVE_DOWNLOADS: dict[str, dict] = {}
COMMANDS_READY = False
AUTH_SETUPS: dict[int, dict] = {}
CHANNEL_CHOICES: dict[int, dict[str, dict]] = {}
BASE_DIR = Path(__file__).resolve().parent
RUBIKA_AUTH_HELPER = BASE_DIR / "rubika_auth_helper.py"
BTN_STATUS = "📊 Status"
BTN_TRANSFERS = "📋 Transfers"
BTN_CLEANUP = "🧹 Cleanup"
BTN_CANCEL = "🛑 Cancel"
BTN_SETTINGS = "⚙️ Settings"
MENU_BUTTONS = {BTN_STATUS, BTN_TRANSFERS, BTN_CLEANUP, BTN_CANCEL, BTN_SETTINGS}
VIDEO_EXTENSIONS = {
".mp4",
".mkv",
".avi",
".mov",
".webm",
".flv",
".m4v",
}
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp"}
AUDIO_EXTENSIONS = {".mp3", ".wav", ".ogg", ".m4a", ".flac", ".aac"}
DOCUMENT_EXTENSIONS = {
".pdf",
".txt",
".csv",
".json",
".doc",
".docx",
".xls",
".xlsx",
".ppt",
".pptx",
}
ARCHIVE_EXTENSIONS = {".zip", ".rar", ".7z", ".tar", ".gz", ".bz2", ".xz"}
DIRECT_FILE_EXTENSIONS = (
VIDEO_EXTENSIONS
| IMAGE_EXTENSIONS
| AUDIO_EXTENSIONS
| DOCUMENT_EXTENSIONS
| ARCHIVE_EXTENSIONS
)
DIRECT_FILE_CONTENT_TYPES = {
"application/pdf",
"application/zip",
"application/x-zip-compressed",
"application/x-rar-compressed",
"application/x-7z-compressed",
"application/x-tar",
"application/gzip",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/msword",
"application/vnd.ms-excel",
"application/vnd.ms-powerpoint",
}
URL_PATTERN = re.compile(r"(?P<url>(?:https?|file)://\S+)", re.IGNORECASE)
DIRECT_DOWNLOAD_MAX_RETRIES = 5
DIRECT_DOWNLOAD_RETRY_DELAY = 3
MENU_KEYBOARD = ReplyKeyboardMarkup(
[
[KeyboardButton(BTN_STATUS), KeyboardButton(BTN_TRANSFERS)],
[KeyboardButton(BTN_CLEANUP), KeyboardButton(BTN_CANCEL)],
[KeyboardButton(BTN_SETTINGS)],
],
resize_keyboard=True,
)
BOT_COMMANDS = [
BotCommand("start", "Open the main menu"),
BotCommand("settings", "View Rubika upload settings"),
BotCommand("status", "Show queue and storage status"),
BotCommand("transfers", "List active and queued transfers"),
BotCommand("set_rubika", "Start Rubika number setup"),
BotCommand("retry", "Retry a failed transfer"),
BotCommand("retry_all", "Retry all failed transfers"),
BotCommand("cleanup", "Clean safe download leftovers"),
BotCommand("cancel", "Cancel a transfer"),
]
MENU_BUTTON_FILTER = filters.create(
lambda _filter, _client, message: (message.text or "").strip() in MENU_BUTTONS
)
async def ensure_bot_commands(client: Client) -> None:
global COMMANDS_READY
if COMMANDS_READY:
return
try:
await client.set_bot_commands(BOT_COMMANDS)
COMMANDS_READY = True
except Exception:
pass
def is_owner(user_id: int | None) -> bool:
if not OWNER_TELEGRAM_ID:
return True
return bool(user_id and user_id == OWNER_TELEGRAM_ID)
async def ensure_authorized_message(message: Message) -> bool:
user_id = getattr(message.from_user, "id", None)
if is_owner(user_id):
return True
print(
"Ignoring unauthorized message "
f"user_id={user_id} owner_id={OWNER_TELEGRAM_ID} "
f"text={(message.text or message.caption or '')[:80]!r}",
flush=True,
)
return False
async def ensure_authorized_callback(callback_query: CallbackQuery) -> bool:
if is_owner(getattr(callback_query.from_user, "id", None)):
return True
print(
"Ignoring unauthorized callback "
f"user_id={getattr(callback_query.from_user, 'id', None)} "
f"owner_id={OWNER_TELEGRAM_ID} data={(callback_query.data or '')[:80]!r}",
flush=True,
)
try:
await callback_query.answer()
except Exception:
pass
return False
def build_menu_text() -> str:
settings = load_settings_with_phone()
return "\n".join(
[
"<b>⛵️ WalrusHF</b>",
"📤 <b>Send a file or direct file link</b> and I will upload it to Rubika.",
"",
f"📱 <b>Rubika Session:</b> {ltr_code(settings['rubika_session'])}",
f"📬 <b>Destination:</b> {ltr_code(format_destination_label(settings))}",
]
)
def main_action_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup(
[
[
InlineKeyboardButton("📊 Status", callback_data="menu:status"),
InlineKeyboardButton("📋 Transfers", callback_data="menu:transfers"),
],
[
InlineKeyboardButton("🧹 Cleanup", callback_data="menu:cleanup"),
InlineKeyboardButton("🛑 Cancel", callback_data="menu:cancel"),
],
[InlineKeyboardButton("⚙️ Settings", callback_data="menu:settings")],
]
)
def status_summary_keyboard(has_cleanup: bool) -> InlineKeyboardMarkup:
rows = [[InlineKeyboardButton("📋 Details", callback_data="menu:transfers")]]
if has_cleanup:
rows.append([InlineKeyboardButton("🧹 Confirm Cleanup", callback_data="cleanup:confirm")])
rows.append([InlineKeyboardButton("⚙️ Settings", callback_data="menu:settings")])
return InlineKeyboardMarkup(rows)
def cleanup_keyboard(has_candidates: bool) -> InlineKeyboardMarkup | None:
if not has_candidates:
return None
return InlineKeyboardMarkup(
[[InlineKeyboardButton("✅ Confirm cleanup", callback_data="cleanup:confirm")]]
)
def format_destination_label(settings: dict) -> str:
return str(settings.get("rubika_target_title") or "Saved Messages")
def rubika_session_exists() -> bool:
return has_rubika_session(load_runtime_settings()["rubika_session"])
def rubika_session_phone(session_name: str) -> str | None:
candidates = [runtime_path(session_name, SESSION_DIR)]
candidates.append(Path(f"{candidates[0]}.rp"))
for path in candidates:
if not path.exists() or not path.is_file():
continue
try:
with sqlite3.connect(path) as connection:
row = connection.execute("select phone from session limit 1").fetchone()
except sqlite3.Error:
continue
if row and row[0]:
return normalize_phone_number(str(row[0]))
return None
def load_settings_with_phone() -> dict:
settings = load_runtime_settings()
if settings.get("rubika_phone"):
try:
normalized_phone = normalize_phone_number(settings["rubika_phone"])
except ValueError:
return settings
if normalized_phone != settings["rubika_phone"]:
settings["rubika_phone"] = normalized_phone
return save_runtime_settings(settings)
return settings
phone = rubika_session_phone(settings["rubika_session"])
if not phone:
return settings
settings["rubika_phone"] = phone
return save_runtime_settings(settings)
def settings_action_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup(
[
[InlineKeyboardButton("📱 Change Account", callback_data="settings:session")],
[InlineKeyboardButton("📬 Destination", callback_data="settings:destination")],
]
)
def destination_action_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup(
[
[InlineKeyboardButton("☁️ Saved Messages", callback_data="destination:saved")],
[InlineKeyboardButton("📣 Choose Channel", callback_data="destination:channels")],
[InlineKeyboardButton("↩️ Back", callback_data="destination:back")],
]
)
def channel_picker_keyboard(chat_id: int, channels: list[dict]) -> InlineKeyboardMarkup:
choices: dict[str, dict] = {}
rows = []
for channel in channels[:8]:
token = uuid.uuid4().hex[:8]
choices[token] = channel
title = truncate_button_label(channel.get("title") or "Untitled Channel")
rows.append(
[InlineKeyboardButton(f"📣 {title}", callback_data=f"destination:set:{token}")]
)
CHANNEL_CHOICES[chat_id] = choices
rows.append([InlineKeyboardButton("↩️ Back", callback_data="destination:menu")])
return InlineKeyboardMarkup(rows)
def auth_setup_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup(
[[InlineKeyboardButton("✖️ Cancel Setup", callback_data="auth:cancel")]]
)
def build_settings_text(note: str | None = None) -> str:
settings = load_settings_with_phone()
active_phone = settings.get("rubika_phone") or "Not set"
lines = [
"<b>⚙️ Rubika Settings</b>",
"",
"Control which Rubika account receives uploads.",
"",
f"📱 <b>Current Account:</b> {ltr_code(settings['rubika_session'])}",
f"☎️ <b>Active Phone:</b> {ltr_code(active_phone)}",
f"📬 <b>Upload Destination:</b> {ltr_code(format_destination_label(settings))}",
]
lines.extend(
[
"",
"Use the buttons below to change the Rubika account or upload destination.",
"Already queued transfers keep the destination they were queued with.",
]
)
if note:
lines.extend(["", note])
return "\n".join(lines)
async def send_settings_panel(message: Message, note: str | None = None) -> None:
await message.reply_text(
build_settings_text(note),
parse_mode=enums.ParseMode.HTML,
reply_markup=settings_action_keyboard(),
)
async def send_settings_panel_to_chat(chat_id: int, note: str | None = None) -> None:
await app.send_message(
chat_id,
build_settings_text(note),
parse_mode=enums.ParseMode.HTML,
reply_markup=settings_action_keyboard(),
)
def truncate_button_label(text: str, max_length: int = 38) -> str:
text = " ".join(str(text or "").split()).strip() or "Untitled"
if len(text) <= max_length:
return text
return f"{text[: max_length - 1].rstrip()}…"
def build_destination_text(note: str | None = None) -> str:
settings = load_runtime_settings()
lines = [
"<b>📬 Upload Destination</b>",
"",
f"Current: {ltr_code(format_destination_label(settings))}",
"",
"Choose where future uploads should go.",
"Already queued transfers will not be changed.",
]
if note:
lines.extend(["", note])
return "\n".join(lines)
async def send_destination_panel(message: Message, note: str | None = None) -> None:
await message.reply_text(
build_destination_text(note),
parse_mode=enums.ParseMode.HTML,
reply_markup=destination_action_keyboard(),
)
def reset_destination_settings() -> dict:
settings = load_runtime_settings()
settings["rubika_target"] = "me"
settings["rubika_target_title"] = "Saved Messages"
settings["rubika_target_type"] = "saved"
return save_runtime_settings(settings)
def rubika_update_to_plain(value):
if isinstance(value, dict):
return {key: rubika_update_to_plain(item) for key, item in value.items()}
if isinstance(value, list):
return [rubika_update_to_plain(item) for item in value]
for attr in ("to_dict", "original_update"):
try:
data = getattr(value, attr)
except Exception:
data = None
if isinstance(data, dict):
return rubika_update_to_plain(data)
return value
def nested_text_value(payload: dict, keys: tuple[str, ...]) -> str | None:
for key in keys:
value = payload.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
for value in payload.values():
if isinstance(value, dict):
found = nested_text_value(value, keys)
if found:
return found
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
found = nested_text_value(item, keys)
if found:
return found
return None
def collect_channel_destinations(payload) -> list[dict]:
channels: list[dict] = []
seen: set[str] = set()
def visit(value) -> None:
if isinstance(value, list):
for item in value:
visit(item)
return
if not isinstance(value, dict):
return
guid = value.get("channel_guid") or value.get("object_guid")
if isinstance(guid, str) and guid.startswith("c0") and guid not in seen:
seen.add(guid)
title = nested_text_value(
value,
("title", "channel_title", "name", "first_name", "username"),
)
channels.append(
{
"guid": guid,
"title": title or f"Channel {len(channels) + 1}",
"type": "channel",
}
)
for item in value.values():
if isinstance(item, (dict, list)):
visit(item)
visit(rubika_update_to_plain(payload))
return channels
async def load_rubika_channels(session_name: str) -> list[dict]:
client = RubikaClient(name=session_name)
entered = False
try:
await asyncio.wait_for(client.__aenter__(), timeout=RUBIKA_CONNECT_TIMEOUT)
entered = True
chats = await client.get_chats()
return collect_channel_destinations(chats)
finally:
if entered:
await client.__aexit__(None, None, None)
def auth_state(chat_id: int) -> dict | None:
return AUTH_SETUPS.get(chat_id)
def track_auth_temp_message(chat_id: int, message_id: int) -> None:
state = auth_state(chat_id)
if not state:
return
temp_message_ids = state.setdefault("temp_message_ids", [])
if message_id not in temp_message_ids:
temp_message_ids.append(message_id)
async def cleanup_auth_temp_messages(chat_id: int) -> None:
state = auth_state(chat_id)
if not state:
return
temp_message_ids = state.get("temp_message_ids", [])
if not temp_message_ids:
return
state["temp_message_ids"] = []
try:
await app.delete_messages(chat_id, temp_message_ids)
except Exception:
pass
async def cleanup_auth_input_message(message: Message) -> None:
try:
await message.delete()
except Exception:
pass
async def send_auth_temp_message(
message: Message,
text: str,
reply_markup: InlineKeyboardMarkup | ReplyKeyboardMarkup | None,
) -> Message:
sent = await message.reply_text(text, reply_markup=reply_markup)
track_auth_temp_message(message.chat.id, sent.id)
return sent
async def send_auth_temp_message_to_chat(
chat_id: int,
text: str,
reply_markup: InlineKeyboardMarkup | ReplyKeyboardMarkup | None,
) -> Message | None:
try:
sent = await app.send_message(chat_id, text, reply_markup=reply_markup)
except Exception:
return None
track_auth_temp_message(chat_id, sent.id)
return sent
def clear_auth_setup(chat_id: int) -> None:
AUTH_SETUPS.pop(chat_id, None)
def stop_auth_process(chat_id: int) -> None:
state = AUTH_SETUPS.get(chat_id)
process = state.get("process") if state else None
if process and process.poll() is None:
process.terminate()
def normalize_phone_number(phone_number: str) -> str:
phone = re.sub(r"[^\d+]", "", phone_number.strip())
if phone.startswith("00"):
phone = phone[2:]
elif phone.startswith("+"):
phone = phone[1:]
if phone.startswith("0"):
phone = f"98{phone[1:]}"
elif phone.startswith("9") and len(phone) == 10:
phone = f"98{phone}"
if not re.fullmatch(r"\d{7,15}", phone):
raise ValueError("Invalid phone number.")
return phone
async def prompt_rubika_phone_setup(message: Message, first_setup: bool = False) -> None:
stop_auth_process(message.chat.id)
await cleanup_auth_temp_messages(message.chat.id)
clear_auth_setup(message.chat.id)
setup_id = uuid.uuid4().hex
AUTH_SETUPS[message.chat.id] = {
"setup_id": setup_id,
"stage": "await_phone",
"session_name": load_runtime_settings()["rubika_session"],
}
lines = []
if first_setup:
lines.extend(
[
"⚠️ First setup: no Rubika account session exists yet.",
"We need to create the Rubika session before uploads can work.",
"",
]
)
lines.extend(
[
"1. Send the Rubika phone number you want to log in with.",
"2. I will request the Rubika OTP.",
"3. Send the OTP code here when it arrives.",
"",
"If Rubika asks for an account password first, I will ask for that before the OTP.",
"The stored Rubika session is replaced only after successful login.",
]
)
await send_auth_temp_message(message, "\n".join(lines), auth_setup_keyboard())
async def cancel_auth_setup(message: Message) -> None:
state = AUTH_SETUPS.get(message.chat.id)
if not state:
await send_settings_panel(message, note="⚪️ No Rubika setup is in progress.")
return
stop_auth_process(message.chat.id)
await cleanup_auth_temp_messages(message.chat.id)
clear_auth_setup(message.chat.id)
await send_settings_panel(message, note="⚪️ Rubika number setup cancelled.")
async def start_rubika_auth_process(message: Message, phone_number: str) -> None:
existing_state = AUTH_SETUPS.get(message.chat.id, {})
setup_id = existing_state.get("setup_id") or uuid.uuid4().hex
temp_message_ids = list(existing_state.get("temp_message_ids", []))
normalized_phone = normalize_phone_number(phone_number)
digits_only = normalized_phone[1:] if normalized_phone.startswith("+") else normalized_phone
if not digits_only.isdigit() or len(digits_only) < 10:
await cleanup_auth_input_message(message)
await cleanup_auth_temp_messages(message.chat.id)
await send_auth_temp_message(
message,
"⚠️ Please send a valid Rubika phone number.",
auth_setup_keyboard(),
)
return
session_name = load_runtime_settings()["rubika_session"]
processing_task = load_processing()
if processing_task_is_active(processing_task) and has_rubika_session(session_name):
await cleanup_auth_input_message(message)
await cleanup_auth_temp_messages(message.chat.id)
await send_settings_panel(
message,
note="⚠️ Wait for the current upload to finish before changing the Rubika number.",
)
clear_auth_setup(message.chat.id)
return
stop_auth_process(message.chat.id)
try:
process = subprocess.Popen(
[sys.executable, str(RUBIKA_AUTH_HELPER), session_name, normalized_phone],
cwd=str(BASE_DIR),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
except OSError as error:
await cleanup_auth_temp_messages(message.chat.id)
clear_auth_setup(message.chat.id)
await send_settings_panel(
message,
note=f"❌ Could not start Rubika login helper: {error}",
)
return
AUTH_SETUPS[message.chat.id] = {
"setup_id": setup_id,
"stage": "waiting_for_otp",
"session_name": session_name,
"phone_number": normalized_phone,
"process": process,
"log_tail": [],
"temp_message_ids": temp_message_ids,
}
asyncio.create_task(monitor_rubika_auth_process(message.chat.id, setup_id, process))
await cleanup_auth_input_message(message)
await cleanup_auth_temp_messages(message.chat.id)
await send_auth_temp_message(
message,
"📨 Requesting Rubika OTP now...",
auth_setup_keyboard(),
)
async def monitor_rubika_auth_process(chat_id: int, setup_id: str, process) -> None:
state = AUTH_SETUPS.get(chat_id)
if not state or state.get("setup_id") != setup_id or state.get("process") is not process:
return
if not process or not process.stdout:
current = AUTH_SETUPS.get(chat_id)
if current and current.get("setup_id") == setup_id:
await cleanup_auth_temp_messages(chat_id)
clear_auth_setup(chat_id)
await send_settings_panel_to_chat(
chat_id,
note="❌ Rubika setup could not start.",
)
return
success = False
cancelled = False
error_text: str | None = None
while True:
line = await asyncio.to_thread(process.stdout.readline)
if not line:
if process.poll() is not None:
break
continue
text = line.strip()
if not text:
continue
if text.startswith("__AUTH_PASSKEY_PROMPT__:"):
hint = text.split(":", 1)[1].strip()
current = AUTH_SETUPS.get(chat_id)
if (
not current
or current.get("setup_id") != setup_id
or current.get("process") is not process
):
return
current["stage"] = "await_passkey"
await cleanup_auth_temp_messages(chat_id)
lines = [
"🔑 Rubika requires the account password before it can send the OTP.",
]
if hint:
lines.append(f"Hint: {hint}")
lines.extend(["", "Send the Rubika account password here."])
await send_auth_temp_message_to_chat(
chat_id,
"\n".join(lines),
auth_setup_keyboard(),
)
continue
if text == "__AUTH_OTP_PROMPT__":
current = AUTH_SETUPS.get(chat_id)
if (
not current
or current.get("setup_id") != setup_id
or current.get("process") is not process
):
return
current["stage"] = "await_otp"
await cleanup_auth_temp_messages(chat_id)
await send_auth_temp_message_to_chat(
chat_id,
"🔐 Rubika OTP request was sent. Send the verification code here.",
auth_setup_keyboard(),
)
continue
if text.startswith("__AUTH_PROMPT__:"):
prompt_text = text.split(":", 1)[1].strip() or "Rubika requested verification input."
current = AUTH_SETUPS.get(chat_id)
if (
not current
or current.get("setup_id") != setup_id
or current.get("process") is not process
):
return
current["stage"] = "await_extra_input"
await cleanup_auth_temp_messages(chat_id)
await send_auth_temp_message_to_chat(
chat_id,
"\n".join(
[
"🔐 Rubika is waiting for verification input.",
prompt_text,
"",
"Send the requested code here.",
]
),
auth_setup_keyboard(),
)
continue
if text == "__AUTH_SUCCESS__":
success = True
break
if text == "__AUTH_CANCELLED__":
cancelled = True
break
if text.startswith("__AUTH_ERROR__:"):
error_text = text.split(":", 1)[1].strip()
break
current = AUTH_SETUPS.get(chat_id)
if (
current is not None
and current.get("setup_id") == setup_id
and current.get("process") is process
):
log_tail = current.setdefault("log_tail", [])
log_tail.append(text)
del log_tail[:-5]
current = AUTH_SETUPS.get(chat_id)
active_phone = current.get("phone_number") if current else None
if current and current.get("setup_id") == setup_id and current.get("process") is process:
await cleanup_auth_temp_messages(chat_id)
clear_auth_setup(chat_id)
else:
return
if success:
if active_phone:
settings = load_runtime_settings()
settings["rubika_phone"] = active_phone
save_runtime_settings(settings)
await send_settings_panel_to_chat(
chat_id,
note="✅ Rubika number updated and the current session was replaced successfully.",
)
return
if cancelled:
await send_settings_panel_to_chat(
chat_id,
note="⚪️ Rubika number setup cancelled.",
)
return
if not error_text:
error_text = "Rubika setup failed."
await send_settings_panel_to_chat(
chat_id,
note=f"❌ Rubika login failed: {error_text}",
)
async def submit_rubika_auth_input(message: Message, value: str, next_text: str) -> None:
state = AUTH_SETUPS.get(message.chat.id)
process = state.get("process") if state else None
if not state or not process or not process.stdin:
return
process.stdin.write(value.strip() + "\n")
process.stdin.flush()
state["stage"] = "waiting_for_helper"
await cleanup_auth_input_message(message)
await cleanup_auth_temp_messages(message.chat.id)
await send_auth_temp_message(
message,
next_text,
auth_setup_keyboard(),
)
async def maybe_handle_auth_input(message: Message) -> bool:
state = AUTH_SETUPS.get(message.chat.id)
if not state:
return False
text = (message.text or "").strip()
if not text or text.startswith("/") or text in MENU_BUTTONS:
return False
if state.get("stage") == "await_phone":
await start_rubika_auth_process(message, text)
return True
if state.get("stage") == "await_passkey":
await submit_rubika_auth_input(
message,
text,
"⏳ Checking the Rubika password and requesting OTP...",
)
return True