forked from toddrob99/searcharr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
searcharr.py
2186 lines (2101 loc) · 93.2 KB
/
searcharr.py
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
"""
Searcharr
Sonarr, Radarr & Readarr Telegram Bot
By Todd Roberts
https://github.com/toddrob99/searcharr
"""
import argparse
import json
import os
import yaml
import sqlite3
from threading import Lock
from urllib.parse import parse_qsl
import uuid
import arrow
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, InputMediaPhoto
from telegram.error import BadRequest
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
from log import set_up_logger
import radarr
import sonarr
import readarr
import settings
__version__ = "2.2"
DBPATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data")
DBFILE = "searcharr.db"
DBLOCK = Lock()
def parse_args():
parser = argparse.ArgumentParser(
prog="Searcharr", description="Start the Searcharr Bot."
)
parser.add_argument(
"--verbose",
"-v",
action="store_true",
dest="verbose",
help="Enable debug logging.",
)
parser.add_argument(
"--console-logging",
"-c",
action="store_true",
dest="console_logging",
help="Enable console logging.",
)
parser.add_argument(
"--dev",
"-d",
action="store_true",
dest="dev_mode",
help="Enable developer mode, which will result in more exceptions being raised instead of handled.",
)
return parser.parse_args()
class Searcharr(object):
def __init__(self, token):
self.DEV_MODE = True if args.dev_mode else False
self.token = token
logger.info(f"Searcharr v{__version__} - Logging started!")
self._lang = self._load_language()
if self._lang.get("language_ietf") != "en-us":
self._lang_default = self._load_language("en-us")
self.sonarr = (
sonarr.Sonarr(settings.sonarr_url, settings.sonarr_api_key, args.verbose)
if settings.sonarr_enabled
else None
)
if self.sonarr:
quality_profiles = []
if not isinstance(settings.sonarr_quality_profile_id, list):
settings.sonarr_quality_profile_id = [
settings.sonarr_quality_profile_id
]
for i in settings.sonarr_quality_profile_id:
logger.debug(
f"Looking up/validating Sonarr quality profile id for [{i}]..."
)
foundProfile = self.sonarr.lookup_quality_profile(i)
if not foundProfile:
logger.error(f"Sonarr quality profile id/name [{i}] is invalid!")
else:
logger.debug(
f"Found Sonarr quality profile for [{i}]: [{foundProfile}]"
)
quality_profiles.append(foundProfile)
if not len(quality_profiles):
logger.warning(
f"No valid Sonarr quality profile(s) provided! Using all of the quality profiles I found in Sonarr: {self.sonarr._quality_profiles}"
)
else:
logger.debug(
f"Using the following Sonarr quality profile(s): {[(x['id'], x['name']) for x in quality_profiles]}"
)
self.sonarr._quality_profiles = quality_profiles
language_profiles = []
if not isinstance(settings.sonarr_language_profile_id, list):
settings.sonarr_language_profile_id = [
settings.sonarr_language_profile_id
]
for i in settings.sonarr_language_profile_id:
logger.debug(
f"Looking up/validating Sonarr language profile id for [{i}]..."
)
foundProfile = self.sonarr.lookup_language_profile(i)
if not foundProfile:
logger.error(f"Sonarr language profile id/name [{i}] is invalid!")
else:
logger.debug(
f"Found Sonarr language profile for [{i}]: [{foundProfile}]"
)
language_profiles.append(foundProfile)
if not len(language_profiles):
logger.warning(
f"No valid Sonarr language profile(s) provided! Using all of the language profiles I found in Sonarr: {self.sonarr._language_profiles}"
)
else:
logger.debug(
f"Using the following Sonarr language profile(s): {[(x['id'], x['name']) for x in language_profiles]}"
)
self.sonarr._language_profiles = language_profiles
root_folders = []
if not hasattr(settings, "sonarr_series_paths"):
settings.sonarr_series_paths = []
logger.warning(
'No sonarr_series_paths setting detected. Please set one in settings.py (sonarr_series_paths=["/path/1", "/path/2"]). Proceeding with all root folders configured in Sonarr.'
)
if not isinstance(settings.sonarr_series_paths, list):
settings.sonarr_series_paths = [settings.sonarr_series_paths]
for i in settings.sonarr_series_paths:
logger.debug(f"Looking up/validating Sonarr root folder for [{i}]...")
foundPath = self.sonarr.lookup_root_folder(i)
if not foundPath:
logger.error(f"Sonarr root folder path/id [{i}] is invalid!")
else:
logger.debug(f"Found Sonarr root folder for [{i}]: [{foundPath}]")
root_folders.append(foundPath)
if not len(root_folders):
logger.warning(
f"No valid Sonarr root folder(s) provided! Using all of the root folders I found in Sonarr: {self.sonarr._root_folders}"
)
else:
logger.debug(
f"Using the following Sonarr root folder(s): {[(x['id'], x['path']) for x in root_folders]}"
)
self.sonarr._root_folders = root_folders
if not hasattr(settings, "sonarr_tag_with_username"):
settings.sonarr_tag_with_username = True
logger.warning(
"No sonarr_tag_with_username setting found. Please add sonarr_tag_with_username to settings.py (sonarr_tag_with_username=True or sonarr_tag_with_username=False). Defaulting to True."
)
if not hasattr(settings, "sonarr_series_command_aliases"):
settings.sonarr_series_command_aliases = ["series"]
logger.warning(
'No sonarr_series_command_aliases setting found. Please add sonarr_series_command_aliases to settings.py (e.g. sonarr_series_command_aliases=["series", "tv"]. Defaulting to ["series"].'
)
if not hasattr(settings, "sonarr_season_monitor_prompt"):
settings.sonarr_season_monitor_prompt = False
logger.warning(
"No sonarr_season_monitor_prompt setting found. Please add sonarr_season_monitor_prompt to settings.py (e.g. sonarr_season_monitor_prompt=True if you want users to choose whether to monitor all/first/latest season(s). Defaulting to False."
)
if not hasattr(settings, "sonarr_forced_tags"):
settings.sonarr_forced_tags = []
logger.warning(
'No sonarr_forced_tags setting found. Please add sonarr_forced_tags to settings.py (e.g. sonarr_forced_tags=["tag-1", "tag-2"]) if you want specific tags added to each series. Defaulting to empty list ([]).'
)
if not hasattr(settings, "sonarr_allow_user_to_select_tags"):
settings.sonarr_allow_user_to_select_tags = False
logger.warning(
"No sonarr_allow_user_to_select_tags setting found. Please add sonarr_allow_user_to_select_tags to settings.py (e.g. sonarr_allow_user_to_select_tags=True) if you want users to be able to select tags when adding a series. Defaulting to False."
)
if not hasattr(settings, "sonarr_user_selectable_tags"):
settings.sonarr_user_selectable_tags = []
logger.warning(
'No sonarr_user_selectable_tags setting found. Please add sonarr_user_selectable_tags to settings.py (e.g. sonarr_user_selectable_tags=["tag-1", "tag-2"]) if you want to limit the tags a user can select. Defaulting to empty list ([]), which will present the user with all tags.'
)
for t in settings.sonarr_user_selectable_tags:
if t_id := self.sonarr.get_tag_id(t):
logger.debug(
f"Tag id [{t_id}] for user-selectable Sonarr tag [{t}]"
)
for t in settings.sonarr_forced_tags:
if t_id := self.sonarr.get_tag_id(t):
logger.debug(f"Tag id [{t_id}] for forced Sonarr tag [{t}]")
self.radarr = (
radarr.Radarr(settings.radarr_url, settings.radarr_api_key, args.verbose)
if settings.radarr_enabled
else None
)
if self.radarr:
quality_profiles = []
if not isinstance(settings.radarr_quality_profile_id, list):
settings.radarr_quality_profile_id = [
settings.radarr_quality_profile_id
]
for i in settings.radarr_quality_profile_id:
logger.debug(
f"Looking up/validating Radarr quality profile id for [{i}]..."
)
foundProfile = self.radarr.lookup_quality_profile(i)
if not foundProfile:
logger.error(f"Radarr quality profile id/name [{i}] is invalid!")
else:
logger.debug(
f"Found Radarr quality profile for [{i}]: [{foundProfile}]"
)
quality_profiles.append(foundProfile)
if not len(quality_profiles):
logger.warning(
f"No valid Radarr quality profile(s) provided! Using all of the quality profiles I found in Radarr: {self.radarr._quality_profiles}"
)
else:
logger.debug(
f"Using the following Radarr quality profile(s): {[(x['id'], x['name']) for x in quality_profiles]}"
)
self.radarr._quality_profiles = quality_profiles
root_folders = []
if not hasattr(settings, "radarr_movie_paths"):
settings.radarr_movie_paths = []
logger.warning(
'No radarr_movie_paths setting detected. Please set one in settings.py (radarr_movie_paths=["/path/1", "/path/2"]). Proceeding with all root folders configured in Radarr.'
)
if not isinstance(settings.radarr_movie_paths, list):
settings.radarr_movie_paths = [settings.radarr_movie_paths]
for i in settings.radarr_movie_paths:
logger.debug(f"Looking up/validating Radarr root folder for [{i}]...")
foundPath = self.radarr.lookup_root_folder(i)
if not foundPath:
logger.error(f"Radarr root folder path/id [{i}] is invalid!")
else:
logger.debug(f"Found Radarr root folder for [{i}]: [{foundPath}]")
root_folders.append(foundPath)
if not len(root_folders):
logger.warning(
f"No valid Radarr root folder(s) provided! Using all of the root folders I found in Radarr: {self.radarr._root_folders}"
)
else:
logger.debug(
f"Using the following Radarr root folder(s): {[(x['id'], x['path']) for x in root_folders]}"
)
self.radarr._root_folders = root_folders
if not hasattr(settings, "radarr_tag_with_username"):
settings.radarr_tag_with_username = True
logger.warning(
"No radarr_tag_with_username setting found. Please add radarr_tag_with_username to settings.py (radarr_tag_with_username=True or radarr_tag_with_username=False). Defaulting to True."
)
if not hasattr(settings, "radarr_min_availability"):
settings.radarr_min_availability = "released"
logger.warning(
'No radarr_min_availability setting found. Please add radarr_min_availability to settings.py (options: "released", "announced", "inCinema"). Defaulting to "released".'
)
if not hasattr(settings, "radarr_movie_command_aliases"):
settings.radarr_movie_command_aliases = ["movie"]
logger.warning(
'No radarr_movie_command_aliases setting found. Please add radarr_movie_command_aliases to settings.py (e.g. radarr_movie_command_aliases=["movie", "mv"]. Defaulting to ["movie"].'
)
if not hasattr(settings, "radarr_forced_tags"):
settings.radarr_forced_tags = []
logger.warning(
'No radarr_forced_tags setting found. Please add radarr_forced_tags to settings.py (e.g. radarr_forced_tags=["tag-1", "tag-2"]) if you want specific tags added to each movie. Defaulting to empty list ([]).'
)
if not hasattr(settings, "radarr_allow_user_to_select_tags"):
settings.radarr_allow_user_to_select_tags = True
logger.warning(
"No radarr_allow_user_to_select_tags setting found. Please add radarr_allow_user_to_select_tags to settings.py (e.g. radarr_allow_user_to_select_tags=False) if you do not want users to be able to select tags when adding a movie. Defaulting to True."
)
if not hasattr(settings, "radarr_user_selectable_tags"):
settings.radarr_user_selectable_tags = []
logger.warning(
'No radarr_user_selectable_tags setting found. Please add radarr_user_selectable_tags to settings.py (e.g. radarr_user_selectable_tags=["tag-1", "tag-2"]) if you want to limit the tags a user can select. Defaulting to empty list ([]), which will present the user with all tags.'
)
for t in settings.radarr_user_selectable_tags:
if t_id := self.radarr.get_tag_id(t):
logger.debug(
f"Tag id [{t_id}] for user-selectable Radarr tag [{t}]"
)
for t in settings.radarr_forced_tags:
if t_id := self.radarr.get_tag_id(t):
logger.debug(f"Tag id [{t_id}] for forced Radarr tag [{t}]")
self.readarr = (
readarr.Readarr(settings.readarr_url, settings.readarr_api_key, args.verbose)
if settings.readarr_enabled
else None
)
if self.readarr:
quality_profiles = []
if not isinstance(settings.readarr_quality_profile_id, list):
settings.readarr_quality_profile_id = [
settings.readarr_quality_profile_id
]
for i in settings.readarr_quality_profile_id:
logger.debug(
f"Looking up/validating readarr quality profile id for [{i}]..."
)
foundProfile = self.readarr.lookup_quality_profile(i)
if not foundProfile:
logger.error(f"readarr quality profile id/name [{i}] is invalid!")
else:
logger.debug(
f"Found readarr quality profile for [{i}]: [{foundProfile}]"
)
quality_profiles.append(foundProfile)
if not len(quality_profiles):
logger.warning(
f"No valid readarr quality profile(s) provided! Using all of the quality profiles I found in readarr: {self.readarr._quality_profiles}"
)
else:
logger.debug(
f"Using the following readarr quality profile(s): {[(x['id'], x['name']) for x in quality_profiles]}"
)
self.readarr._quality_profiles = quality_profiles
metadata_profiles = []
if not isinstance(settings.readarr_metadata_profile_id, list):
settings.readarr_metadata_profile_id = [
settings.readarr_metadata_profile_id
]
for i in settings.readarr_metadata_profile_id:
logger.debug(
f"Looking up/validating readarr metadata profile id for [{i}]..."
)
foundProfile = self.readarr.lookup_metadata_profile(i)
if not foundProfile:
logger.error(f"readarr metadata profile id/name [{i}] is invalid!")
else:
logger.debug(
f"Found readarr metadata profile for [{i}]: [{foundProfile}]"
)
metadata_profiles.append(foundProfile)
if not len(metadata_profiles):
logger.warning(
f"No valid readarr metadata profile(s) provided! Using all of the metadata profiles I found in readarr: {self.readarr._metadata_profiles}"
)
else:
logger.debug(
f"Using the following readarr metadata profile(s): {[(x['id'], x['name']) for x in metadata_profiles]}"
)
self.readarr._metadata_profiles = metadata_profiles
root_folders = []
if not hasattr(settings, "readarr_book_paths"):
settings.readarr_book_paths = []
logger.warning(
'No readarr_movie_paths setting detected. Please set one in settings.py (readarr_movie_paths=["/path/1", "/path/2"]). Proceeding with all root folders configured in readarr.'
)
if not isinstance(settings.readarr_book_paths, list):
settings.readarr_book_paths = [settings.readarr_book_paths]
for i in settings.readarr_book_paths:
logger.debug(f"Looking up/validating readarr root folder for [{i}]...")
foundPath = self.readarr.lookup_root_folder(i)
if not foundPath:
logger.error(f"readarr root folder path/id [{i}] is invalid!")
else:
logger.debug(f"Found readarr root folder for [{i}]: [{foundPath}]")
root_folders.append(foundPath)
if not len(root_folders):
logger.warning(
f"No valid readarr root folder(s) provided! Using all of the root folders I found in readarr: {self.readarr._root_folders}"
)
else:
logger.debug(
f"Using the following readarr root folder(s): {[(x['id'], x['path']) for x in root_folders]}"
)
self.readarr._root_folders = root_folders
if not hasattr(settings, "readarr_tag_with_username"):
settings.readarr_tag_with_username = True
logger.warning(
"No readarr_tag_with_username setting found. Please add readarr_tag_with_username to settings.py (readarr_tag_with_username=True or readarr_tag_with_username=False). Defaulting to True."
)
if not hasattr(settings, "readarr_movie_command_aliases"):
settings.readarr_book_command_aliases = ["book"]
logger.warning(
'No readarr_book_command_aliases setting found. Please add readarr_movie_command_aliases to settings.py (e.g. readarr_book_command_aliases=["book", "bk"]. Defaulting to ["book"].'
)
if not hasattr(settings, "readarr_forced_tags"):
settings.readarr_forced_tags = []
logger.warning(
'No readarr_forced_tags setting found. Please add readarr_forced_tags to settings.py (e.g. readarr_forced_tags=["tag-1", "tag-2"]) if you want specific tags added to each movie. Defaulting to empty list ([]).'
)
if not hasattr(settings, "readarr_allow_user_to_select_tags"):
settings.readarr_allow_user_to_select_tags = True
logger.warning(
"No readarr_allow_user_to_select_tags setting found. Please add readarr_allow_user_to_select_tags to settings.py (e.g. readarr_allow_user_to_select_tags=False) if you do not want users to be able to select tags when adding a movie. Defaulting to True."
)
if not hasattr(settings, "readarr_user_selectable_tags"):
settings.readarr_user_selectable_tags = []
logger.warning(
'No readarr_user_selectable_tags setting found. Please add readarr_user_selectable_tags to settings.py (e.g. readarr_user_selectable_tags=["tag-1", "tag-2"]) if you want to limit the tags a user can select. Defaulting to empty list ([]), which will present the user with all tags.'
)
for t in settings.readarr_user_selectable_tags:
if t_id := self.readarr.get_tag_id(t):
logger.debug(
f"Tag id [{t_id}] for user-selectable readarr tag [{t}]"
)
for t in settings.readarr_forced_tags:
if t_id := self.readarr.get_tag_id(t):
logger.debug(f"Tag id [{t_id}] for forced readarr tag [{t}]")
self.conversations = {}
if not hasattr(settings, "searcharr_admin_password"):
settings.searcharr_admin_password = uuid.uuid4().hex
logger.warning(
f'No admin password detected. Please set one in settings.py (searcharr_admin_password="your admin password"). Using {settings.searcharr_admin_password} as the admin password for this session.'
)
if settings.searcharr_password == "":
logger.warning(
'Password is blank. This will allow anyone to add series/movies using your bot. If this is unexpected, set a password in settings.py (searcharr_password="your password").'
)
if not hasattr(settings, "searcharr_start_command_aliases"):
settings.searcharr_start_command_aliases = ["start"]
logger.warning(
'No searcharr_start_command_aliases setting found. Please add searcharr_start_command_aliases to settings.py (e.g. searcharr_start_command_aliases=["start"]. Defaulting to ["start"].'
)
if not hasattr(settings, "searcharr_help_command_aliases"):
settings.searcharr_help_command_aliases = ["help"]
logger.warning(
'No searcharr_help_command_aliases setting found. Please add searcharr_help_command_aliases to settings.py (e.g. searcharr_help_command_aliases=["help"]. Defaulting to ["help"].'
)
if not hasattr(settings, "searcharr_users_command_aliases"):
settings.searcharr_users_command_aliases = ["users"]
logger.warning(
'No searcharr_users_command_aliases setting found. Please add searcharr_users_command_aliases to settings.py (e.g. searcharr_users_command_aliases=["users"]. Defaulting to ["users"].'
)
def cmd_start(self, update, context):
logger.debug(f"Received start cmd from [{update.message.from_user.username}]")
password = self._strip_entities(update.message)
if password and password == settings.searcharr_admin_password:
self._add_user(
id=update.message.from_user.id,
username=str(update.message.from_user.username),
admin=1,
)
update.message.reply_text(
self._xlate(
"admin_auth_success",
commands=" OR ".join(
[f"`/{c}`" for c in settings.searcharr_help_command_aliases]
),
)
)
elif self._authenticated(update.message.from_user.id):
update.message.reply_text(
self._xlate(
"already_authenticated",
commands=" OR ".join(
[f"`/{c}`" for c in settings.searcharr_help_command_aliases]
),
)
)
elif password == settings.searcharr_password:
self._add_user(
id=update.message.from_user.id,
username=str(update.message.from_user.username),
)
update.message.reply_text(
self._xlate(
"auth_successful",
commands=" OR ".join(
[f"`/{c}`" for c in settings.searcharr_help_command_aliases]
),
)
)
else:
update.message.reply_text(self._xlate("incorrect_pw"))
def cmd_book(self, update, context):
logger.debug(f"Received book cmd from [{update.message.from_user.username}]")
if not self._authenticated(update.message.from_user.id):
update.message.reply_text(
self._xlate(
"auth_required",
commands=" OR ".join(
[
f"`/{c} <{self._xlate('password')}>`"
for c in settings.searcharr_start_command_aliases
]
),
)
)
return
if not settings.radarr_enabled:
update.message.reply_text(self._xlate("readarr_disabled"))
return
title = self._strip_entities(update.message)
if not len(title):
x_title = self._xlate("title").title()
update.message.reply_text(
self._xlate(
"include_book_title_in_cmd",
commands=" OR ".join(
[
f"`/{c} {x_title}`"
for c in settings.readarr_book_command_aliases
]
),
)
)
return
results = self.readarr.lookup_book(title)
cid = self._generate_cid()
# self.conversations.update({cid: {"cid": cid, "type": "book", "results": results}})
self._create_conversation(
id=cid,
username=str(update.message.from_user.username),
kind="book",
results=results,
)
if not len(results):
update.message.reply_text(self._xlate("no_matching_books"))
else:
r = results[0]
reply_message, reply_markup = self._prepare_response(
"book", r, cid, 0, len(results)
)
try:
context.bot.sendPhoto(
chat_id=update.message.chat.id,
photo=r["remotePoster"],
caption=reply_message,
reply_markup=reply_markup,
)
except BadRequest as e:
if str(e) in self._bad_request_poster_error_messages:
logger.error(
f"Error sending photo [{r['remotePoster']}]: BadRequest: {e}. Attempting to send with default poster..."
)
context.bot.sendPhoto(
chat_id=update.message.chat.id,
photo="https://artworks.thetvdb.com/banners/images/missing/movie.jpg",
caption=reply_message,
reply_markup=reply_markup,
)
else:
raise
def cmd_movie(self, update, context):
logger.debug(f"Received movie cmd from [{update.message.from_user.username}]")
if not self._authenticated(update.message.from_user.id):
update.message.reply_text(
self._xlate(
"auth_required",
commands=" OR ".join(
[
f"`/{c} <{self._xlate('password')}>`"
for c in settings.searcharr_start_command_aliases
]
),
)
)
return
if not settings.radarr_enabled:
update.message.reply_text(self._xlate("radarr_disabled"))
return
title = self._strip_entities(update.message)
if not len(title):
x_title = self._xlate("title").title()
update.message.reply_text(
self._xlate(
"include_movie_title_in_cmd",
commands=" OR ".join(
[
f"`/{c} {x_title}`"
for c in settings.radarr_movie_command_aliases
]
),
)
)
return
results = self.radarr.lookup_movie(title)
cid = self._generate_cid()
# self.conversations.update({cid: {"cid": cid, "type": "movie", "results": results}})
self._create_conversation(
id=cid,
username=str(update.message.from_user.username),
kind="movie",
results=results,
)
if not len(results):
update.message.reply_text(self._xlate("no_matching_movies"))
else:
r = results[0]
reply_message, reply_markup = self._prepare_response(
"movie", r, cid, 0, len(results)
)
try:
context.bot.sendPhoto(
chat_id=update.message.chat.id,
photo=r["remotePoster"],
caption=reply_message,
reply_markup=reply_markup,
)
except BadRequest as e:
if str(e) in self._bad_request_poster_error_messages:
logger.error(
f"Error sending photo [{r['remotePoster']}]: BadRequest: {e}. Attempting to send with default poster..."
)
context.bot.sendPhoto(
chat_id=update.message.chat.id,
photo="https://artworks.thetvdb.com/banners/images/missing/movie.jpg",
caption=reply_message,
reply_markup=reply_markup,
)
else:
raise
def cmd_series(self, update, context):
logger.debug(f"Received series cmd from [{update.message.from_user.username}]")
if not self._authenticated(update.message.from_user.id):
update.message.reply_text(
self._xlate(
"auth_required",
commands=" OR ".join(
[
f"`/{c} <{self._xlate('password')}>`"
for c in settings.searcharr_start_command_aliases
]
),
)
)
return
if not settings.sonarr_enabled:
update.message.reply_text(self._xlate("sonarr_disabled"))
return
title = self._strip_entities(update.message)
if not len(title):
x_title = self._xlate("title").title()
update.message.reply_text(
self._xlate(
"include_series_title_in_cmd",
commands=" OR ".join(
[
f"`/{c} {x_title}`"
for c in settings.sonarr_series_command_aliases
]
),
)
)
return
results = self.sonarr.lookup_series(title)
cid = self._generate_cid()
# self.conversations.update({cid: {"cid": cid, "type": "series", "results": results}})
self._create_conversation(
id=cid,
username=str(update.message.from_user.username),
kind="series",
results=results,
)
if not len(results):
update.message.reply_text(self._xlate("no_matching_series"))
else:
r = results[0]
reply_message, reply_markup = self._prepare_response(
"series", r, cid, 0, len(results)
)
try:
context.bot.sendPhoto(
chat_id=update.message.chat.id,
photo=r["remotePoster"],
caption=reply_message,
reply_markup=reply_markup,
)
except BadRequest as e:
if str(e) in self._bad_request_poster_error_messages:
logger.error(
f"Error sending photo [{r['remotePoster']}]: BadRequest: {e}. Attempting to send with default poster..."
)
context.bot.sendPhoto(
chat_id=update.message.chat.id,
photo="https://artworks.thetvdb.com/banners/images/missing/movie.jpg",
caption=reply_message,
reply_markup=reply_markup,
)
else:
raise
def cmd_users(self, update, context):
logger.debug(f"Received users cmd from [{update.message.from_user.username}]")
auth_level = self._authenticated(update.message.from_user.id)
if not auth_level:
update.message.reply_text(
self._xlate(
"auth_required",
commands=" OR ".join(
[
f"`/{c} <{self._xlate('password')}>`"
for c in settings.searcharr_start_command_aliases
]
),
)
)
return
elif auth_level != 2:
update.message.reply_text(
self._xlate(
"admin_auth_required",
commands=" OR ".join(
[
f"`/{c} <{self._xlate('admin_password')}>`"
for c in settings.searcharr_start_command_aliases
]
),
)
)
return
results = self._get_users()
cid = self._generate_cid()
# self.conversations.update({cid: {"cid": cid, "type": "users", "results": results}})
self._create_conversation(
id=cid,
username=str(update.message.from_user.username),
kind="users",
results=results,
)
if not len(results):
update.message.reply_text(self._xlate("no_users_found"))
else:
reply_message, reply_markup = self._prepare_response_users(
cid,
results,
0,
5,
len(results),
)
context.bot.sendMessage(
chat_id=update.message.chat.id,
text=reply_message,
reply_markup=reply_markup,
)
def callback(self, update, context):
query = update.callback_query
logger.debug(
f"Received callback from [{query.from_user.username}]: [{query.data}]"
)
auth_level = self._authenticated(query.from_user.id)
if not auth_level:
query.message.reply_text(
self._xlate(
"auth_required",
commands=" OR ".join(
[
f"`/{c} <{self._xlate('password')}>`"
for c in settings.searcharr_start_command_aliases
]
),
)
)
query.message.delete()
query.answer()
return
if not query.data or not len(query.data):
query.answer()
return
convo = self._get_conversation(query.data.split("^^^")[0])
# convo = self.conversations.get(query.data.split("^^^")[0])
if not convo:
query.message.reply_text(self._xlate("convo_not_found"))
query.message.delete()
query.answer()
return
cid, i, op = query.data.split("^^^")
if "^^" in op:
op, op_flags = op.split("^^")
op_flags = dict(parse_qsl(op_flags))
for k, v in op_flags.items():
logger.debug(
f"Adding/Updating additional data for cid=[{cid}], key=[{k}], value=[{v}]..."
)
self._update_add_data(cid, k, v)
i = int(i)
if op == "noop":
pass
elif op == "cancel":
self._delete_conversation(cid)
# self.conversations.pop(cid)
query.message.reply_text(self._xlate("search_canceled"))
query.message.delete()
elif op == "done":
self._delete_conversation(cid)
# self.conversations.pop(cid)
query.message.delete()
elif op == "prev":
if convo["type"] in ["series", "movie", "book"]:
if i <= 0:
query.answer()
return
r = convo["results"][i - 1]
reply_message, reply_markup = self._prepare_response(
convo["type"], r, cid, i - 1, len(convo["results"])
)
try:
query.message.edit_media(
media=InputMediaPhoto(r["remotePoster"]),
reply_markup=reply_markup,
)
except BadRequest as e:
if str(e) in self._bad_request_poster_error_messages:
logger.error(
f"Error sending photo [{r['remotePoster']}]: BadRequest: {e}. Attempting to send with default poster..."
)
query.message.edit_media(
media=InputMediaPhoto(
"https://artworks.thetvdb.com/banners/images/missing/movie.jpg"
),
reply_markup=reply_markup,
)
else:
raise
query.bot.edit_message_caption(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
caption=reply_message,
reply_markup=reply_markup,
)
elif convo["type"] == "users":
if i <= 0:
i = 0
reply_message, reply_markup = self._prepare_response_users(
cid,
convo["results"],
i,
5,
len(convo["results"]),
)
context.bot.edit_message_text(
chat_id=query.message.chat.id,
message_id=query.message.message_id,
text=reply_message,
reply_markup=reply_markup,
)
elif op == "next":
if convo["type"] in ["series", "movie", "book"]:
if i >= len(convo["results"]):
query.answer()
return
r = convo["results"][i + 1]
logger.debug(f"{r=}")
reply_message, reply_markup = self._prepare_response(
convo["type"], r, cid, i + 1, len(convo["results"])
)
try:
query.message.edit_media(
media=InputMediaPhoto(r["remotePoster"]),
reply_markup=reply_markup,
)
except BadRequest as e:
if str(e) in self._bad_request_poster_error_messages:
logger.error(
f"Error sending photo [{r['remotePoster']}]: BadRequest: {e}. Attempting to send with default poster..."
)
query.message.edit_media(
media=InputMediaPhoto(
"https://artworks.thetvdb.com/banners/images/missing/movie.jpg"
),
reply_markup=reply_markup,
)
else:
raise
query.bot.edit_message_caption(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
caption=reply_message,
reply_markup=reply_markup,
)
elif convo["type"] == "users":
if i > len(convo["results"]):
query.answer()
return
reply_message, reply_markup = self._prepare_response_users(
cid,
convo["results"],
i,
5,
len(convo["results"]),
)
context.bot.edit_message_text(
chat_id=query.message.chat.id,
message_id=query.message.message_id,
text=reply_message,
reply_markup=reply_markup,
)
elif op == "add":
r = convo["results"][i]
additional_data = self._get_add_data(cid)
logger.debug(f"{additional_data=}")
paths = (
self.sonarr._root_folders
if convo["type"] == "series"
else self.radarr._root_folders
if convo["type"] == "movie"
else self.readarr._root_folders
if convo["type"] == "book"
else []
)
if not additional_data.get("p"):
if len(paths) > 1:
reply_message, reply_markup = self._prepare_response(
convo["type"],
r,
cid,
i,
len(convo["results"]),
add=True,
paths=paths,
)
try:
query.message.edit_media(
media=InputMediaPhoto(r["remotePoster"]),
reply_markup=reply_markup,
)
except BadRequest as e:
if str(e) in self._bad_request_poster_error_messages:
logger.error(
f"Error sending photo [{r['remotePoster']}]: BadRequest: {e}. Attempting to send with default poster..."
)
query.message.edit_media(
media=InputMediaPhoto(
"https://artworks.thetvdb.com/banners/images/missing/movie.jpg"
),
reply_markup=reply_markup,
)
else:
raise
query.bot.edit_message_caption(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
caption=reply_message,
reply_markup=reply_markup,
)
query.answer()
return
elif len(paths) == 1:
logger.debug(
f"Only one root folder enabled. Adding/Updating additional data for cid=[{cid}], key=[p], value=[{paths[0]['id']}]..."
)
self._update_add_data(cid, "p", paths[0]["path"])
else:
self._delete_conversation(cid)
query.message.reply_text(
self._xlate(
"no_root_folders",
kind=self._xlate(convo["type"]),
app="Sonarr" if convo["type"] == "series" else "Radarr" if convo['type'] == 'movie' else 'Readarr',
)
)
query.message.delete()
query.answer()
return
else:
try:
int(additional_data.get("p"))
except ValueError:
# Value is already the full path
pass
else:
# Translate id to actual path
path = next(
(
p["path"]
for p in paths
if p["id"] == int(additional_data["p"])
),
None,
)
logger.debug(
f"Path id [{additional_data['p']}] lookup result: [{path}]"
)
if path:
self._update_add_data(cid, "p", path)
if not additional_data.get("q"):
quality_profiles = (
self.sonarr._quality_profiles
if convo["type"] == "series"
else self.radarr._quality_profiles
if convo["type"] == "movie"
else self.readarr._quality_profiles
)
if len(quality_profiles) > 1:
# prepare response to prompt user to select quality profile, and return
reply_message, reply_markup = self._prepare_response(
convo["type"],