-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch.py
More file actions
executable file
·4605 lines (4266 loc) · 197 KB
/
Copy pathsearch.py
File metadata and controls
executable file
·4605 lines (4266 loc) · 197 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
# Copyright (C) 2012–2024 Mylar3 contributors
# Copyright (C) 2025–2026 Comicarr contributors
#
# This file is part of Comicarr.
# Originally based on Mylar3 (https://github.com/mylar3/mylar3).
#
# Comicarr is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Comicarr is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Comicarr. If not, see <http://www.gnu.org/licenses/>.
import datetime
import os
import pathlib
import re
import shutil
import sys
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from operator import itemgetter
from urllib.parse import unquote, urljoin, urlparse
import feedparser
import requests
from requests.adapters import HTTPAdapter
from sqlalchemy import or_, select
from urllib3.util.retry import Retry
import comicarr
from comicarr import (
db,
failed,
filechecker,
findcomicfeed,
getcomics,
helpers,
logger,
notifiers,
nzbget,
rsscheck,
sabnzbd,
search_filer,
updater,
)
from comicarr.app.common.redaction import redact_sensitive_text
from comicarr.app.common.remote_artifacts import (
resolve_remote_artifact_path,
safe_remote_filename,
write_chunks_atomically,
)
from comicarr.app.core.workers import submit_background_future
from comicarr.app.downloads import handoff
from comicarr.downloaders import external_server as exs
from comicarr.tables import (
annuals,
comics,
issues,
provider_searches,
storyarcs,
weekly,
)
from comicarr.torrent import monitor as torrent_monitor
# ThreadPoolExecutor for parallel provider searches
# Using a module-level executor allows connection reuse across searches
_search_executor = None
def get_search_executor():
"""
Get the module-level ThreadPoolExecutor for parallel searches.
Creates the executor lazily on first use.
"""
global _search_executor
if _search_executor is None:
# Use a reasonable number of workers - not too many to avoid
# overwhelming providers, but enough to see parallelization benefit
_search_executor = ThreadPoolExecutor(max_workers=5, thread_name_prefix="search_worker")
return _search_executor
def _wanted_candidate_rows(table, statuses, *extra_conditions):
"""Load candidate and series state together for bulk eligibility checks."""
stmt = (
select(table, comics.c.Status.label("SeriesStatus"))
.select_from(table.outerjoin(comics, comics.c.ComicID == table.c.ComicID))
.where(table.c.Status.in_(statuses), *extra_conditions)
)
return db.select_all(stmt)
def parallel_search_providers(scarios_list, timeout=120):
"""
Search multiple providers in parallel and return the first successful result.
Args:
scarios_list: List of scarios dicts, each containing parameters for one provider
timeout: Maximum time to wait for all searches (seconds)
Returns:
The first successful findit result, or {'status': False} if none succeed
"""
if not scarios_list:
return {"status": False}
# If only one provider, skip parallelization overhead
if len(scarios_list) == 1:
try:
return search_the_matrix(scarios_list[0])
except Exception as e:
logger.warn("Search error: %s" % redact_sensitive_text(e))
return {"status": False}
executor = get_search_executor()
futures = {}
# Submit all searches
for scarios in scarios_list:
provider_name = list(scarios.get("current_prov", {}).keys())[0] if scarios.get("current_prov") else "unknown"
future = submit_background_future(
executor,
search_the_matrix,
args=(scarios,),
name="provider-search:%s" % provider_name,
)
futures[future] = provider_name
logger.fdebug(f"[PARALLEL-SEARCH] Submitted {len(futures)} provider searches in parallel")
# Wait for results, return first success
try:
for future in as_completed(futures, timeout=timeout):
provider_name = futures[future]
try:
result = future.result()
if result.get("status") is True:
logger.info(f"[PARALLEL-SEARCH] Found result from {provider_name}")
# Cancel remaining futures
for f in futures:
if f != future and not f.done():
f.cancel()
return result
except Exception as e:
logger.warn("[PARALLEL-SEARCH] Error from %s: %s" % (provider_name, redact_sensitive_text(e)))
continue
except TimeoutError:
logger.warn("[PARALLEL-SEARCH] Search timeout exceeded")
# No successful results
return {"status": False}
# Module-level HTTP session for connection pooling
# This reuses TCP connections across multiple requests, significantly
# improving performance when making many requests to the same hosts
_http_session = None
def _rss_result_log_summary(result):
"""Return useful RSS metadata without retaining provider-signed links."""
return "rss result: site=%s title=%s" % (
redact_sensitive_text(result.get("site", "unknown")),
redact_sensitive_text(result.get("title", "unknown")),
)
def get_http_session():
"""
Get the module-level HTTP session with connection pooling.
Creates the session lazily on first use.
"""
global _http_session
if _http_session is None:
_http_session = requests.Session()
# Configure retry strategy for resilience
retry_strategy = Retry(
total=3,
backoff_factor=0.5,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["HEAD", "GET", "OPTIONS"],
)
# Mount adapters with connection pool settings
# pool_connections: number of connection pools to cache
# pool_maxsize: max connections per pool
adapter = HTTPAdapter(max_retries=retry_strategy, pool_connections=10, pool_maxsize=20)
_http_session.mount("http://", adapter)
_http_session.mount("https://", adapter)
return _http_session
def search_init(
ComicName,
IssueNumber,
ComicYear,
SeriesYear,
Publisher,
IssueDate,
StoreDate,
IssueID,
AlternateSearch=None,
UseFuzzy=None,
ComicVersion=None,
SARC=None,
IssueArcID=None,
smode=None,
rsschecker=None,
ComicID=None,
manualsearch=None,
filesafe=None,
allow_packs=None,
oneoff=False,
manual=False,
torrentid_32p=None,
digitaldate=None,
booktype=None,
ignore_booktype=False,
_ai_expanded=False,
content_type=None,
chapter_number=None,
volume_number=None,
):
comicarr.COMICINFO = []
# unaltered_ComicName = None
# if filesafe:
# if filesafe != ComicName and smode != 'want_ann':
# logger.info(
# '[SEARCH] Special Characters exist within Series Title. Enabling'
# ' search-safe Name : %s' % filesafe
# )
# if AlternateSearch is None or AlternateSearch == 'None':
# AlternateSearch = filesafe
# else:
# AlternateSearch += '##' + filesafe
# unaltered_ComicName = ComicName
if ComicYear is None:
ComicYear = str(datetime.datetime.now().year)
else:
ComicYear = str(ComicYear)[:4]
if Publisher:
if Publisher == "IDW Publishing":
Publisher = "IDW"
logger.fdebug("Publisher is : %s" % Publisher)
if IssueArcID and not IssueID:
issuetitle = helpers.get_issue_title(IssueArcID)
else:
issuetitle = helpers.get_issue_title(IssueID)
if issuetitle:
logger.fdebug("Issue Title given as : %s" % issuetitle)
else:
logger.fdebug("Issue Title not found. Setting to None.")
if smode == "pullwant" or IssueID is None:
# one-off the download.
logger.fdebug("One-Off Search parameters:")
logger.fdebug("ComicName: %s" % ComicName)
logger.fdebug("Issue: %s" % IssueNumber)
logger.fdebug("Year: %s" % ComicYear)
logger.fdebug("IssueDate: %s" % IssueDate)
oneoff = True
if SARC:
logger.fdebug("Story-ARC Search parameters:")
logger.fdebug("Story-ARC: %s" % SARC)
logger.fdebug("IssueArcID: %s" % IssueArcID)
# --- Manga content-type branch ---
# When searching for manga chapters, construct manga-specific query terms
# and inject them as AlternateSearch patterns. The rest of the search pipeline
# (providers, matching, snatching) works unchanged.
if content_type == "manga":
logger.fdebug("[SEARCH-MANGA] Manga content detected for %s" % ComicName)
manga_terms = _build_manga_search_terms(ComicName, chapter_number, volume_number)
if manga_terms:
manga_alt_str = "##".join(manga_terms)
logger.fdebug("[SEARCH-MANGA] Generated %d search variations: %s" % (len(manga_terms), manga_terms))
if AlternateSearch and AlternateSearch != "None":
AlternateSearch = manga_alt_str + "##" + AlternateSearch
else:
AlternateSearch = manga_alt_str
provider_list = provider_order(initial_run=True)
findit = {}
findit["status"] = False
if provider_list["totalproviders"] == 0:
logger.error(
"[WARNING] You have %s search providers enabled. I need at least ONE"
" provider to work. Aborting search." % provider_list["totalproviders"]
)
findit["status"] = False
nzbprov = None
return findit, nzbprov
logger.fdebug("search provider order is %s" % provider_list["prov_order"])
# fix for issue dates between Nov-Dec/(Jan-Feb-Mar)
IssDateFix = "no"
if StoreDate is not None:
StDt = str(StoreDate)[5:7]
if any(
[
StDt == "10",
StDt == "12",
StDt == "11",
StDt == "01",
StDt == "02",
StDt == "03",
]
):
IssDateFix = StDt
else:
IssDt = str(IssueDate)[5:7]
if any([IssDt == "12", IssDt == "11", IssDt == "01", IssDt == "02", IssDt == "03"]):
IssDateFix = IssDt
searchcnt = 0
srchloop = 1
if rsschecker:
if comicarr.CONFIG.ENABLE_RSS:
searchcnt = 1 # rss-only
else:
searchcnt = 1 # if it's not enabled, don't even bother.
else:
if comicarr.CONFIG.ENABLE_RSS:
searchcnt = 2 # rss first, then api on non-matches
else:
searchcnt = 2 # set the searchcnt to 2 (api)
srchloop = 2 # start the counter at API, so itll exit without running RSS
findcomiciss, c_number = get_findcomiciss(IssueNumber)
while srchloop <= searchcnt:
"""searchmodes:
rss - will run through the built-cached db of entries
api - will run through the providers via api (or non-api in the case of
Experimental) the trick is if the search is done during an rss compare,
it needs to exit when done. Ootherwise, the order of operations is rss
feed check first, followed by api on non-results.
"""
if srchloop == 1:
searchmode = "rss" # order of ops - this will be used first.
elif srchloop == 2:
searchmode = "api"
if "0-Day" in ComicName:
cmloopit = 1
else:
cmloopit = None
if any([booktype == "One-Shot", "annual" in ComicName.lower()]):
cmloopit = 4
if "annual" in ComicName.lower():
if IssueNumber is not None:
if helpers.issuedigits(IssueNumber) != 1000:
cmloopit = None
if cmloopit is None:
if len(c_number) == 1:
cmloopit = 3
elif len(c_number) == 2:
cmloopit = 2
else:
cmloopit = 1
logger.info("cmloopit: %s" % cmloopit)
chktpb = 0
if any([booktype == "TPB", booktype == "HC", booktype == "GN"]):
chktpb = 1
if findit["status"] is True:
logger.fdebug("Found result on first run, exiting search module now.")
break
logger.fdebug("Initiating Search via : %s" % searchmode)
if len(provider_list["prov_order"]) == 1:
tmp_prov_count = 1
else:
tmp_prov_count = len(provider_list["prov_order"])
checked_once = []
prov_count = 0
while tmp_prov_count > prov_count:
logger.info("tmp_prov_count: %s / prov_count: %s" % (tmp_prov_count, prov_count))
tmp_cmloopit = cmloopit
while tmp_cmloopit >= 1:
if tmp_cmloopit == 4:
tmp_IssueNumber = None
else:
tmp_IssueNumber = IssueNumber
prov_order = provider_list["prov_order"]
logger.info("checked_once: %s" % (checked_once,))
if checked_once:
if prov_order[prov_count] in checked_once:
break
provider_blocked = helpers.block_provider_check(prov_order[prov_count])
if provider_blocked:
logger.warn("provider blocked. Ignoring search on this provider.")
break
send_prov_count = tmp_prov_count - prov_count
newznab_host = None
torznab_host = None
logger.info("prov_order[prov_count]: %s" % (prov_order[prov_count],))
# this loads the previous runs from the db to ensure we're always persistant
searchprov = last_run_check(check=True)
# logger.fdebug('searchprov: %s' % (searchprov,))
# should be DDL(GetComics)
if (
prov_order[prov_count] == "DDL(GetComics)"
and not provider_blocked
and "DDL(GetComics)" not in checked_once
):
if "DDL(GetComics)" not in searchprov.keys():
searchprov["DDL(GetComics)"] = {
"id": 200,
"type": "DDL",
"lastrun": 0,
"active": True,
"hits": 0,
}
else:
searchprov["DDL(GetComics)"]["active"] = True
elif (
prov_order[prov_count] == "DDL(External)"
and not provider_blocked
and "DDL(External)" not in checked_once
):
if "DDL(External)" not in searchprov.keys():
searchprov["DDL(External)"] = {
"id": 201,
"type": "DDL(External)",
"lastrun": 0,
"active": True,
"hits": 0,
}
else:
searchprov["DDL(External)"]["active"] = True
elif prov_order[prov_count] == "32p" and not provider_blocked:
searchprov["32P"] = {"type": "torrent", "lastrun": 0, "active": True, "hits": 0}
elif (
prov_order[prov_count].lower() == "experimental"
and not provider_blocked
and "experimental" not in checked_once
):
if all(["experimental" not in searchprov.keys(), "Experimental" not in searchprov.keys()]):
prov_order[prov_count] = "experimental" # cause it's Experimental for display
logger.info("resetting searchprov - last run here..")
searchprov["experimental"] = {
"id": 101,
"type": "experimental",
"lastrun": 0,
"active": True,
"hits": 0,
}
else:
searchprov["experimental"]["active"] = True
elif prov_order[prov_count] == "public torrents" and not provider_blocked:
if "Public Torrents" not in searchprov.keys():
searchprov["Public Torrents"] = {
"id": comicarr.PROVIDER_START_ID + 1,
"type": "torrent",
"lastrun": 0,
"active": True,
"hits": 0,
}
else:
searchprov["Public Torrents"]["active"] = True
elif "torznab" in prov_order[prov_count]:
fnd = False
for nninfo in provider_list["torznab_info"]:
torznab_host = nninfo["info"]
if torznab_host is None:
logger.fdebug("there was an error - torznab information was blank and it should not be.")
break
if all(
[
nninfo["provider"] == prov_order[prov_count],
not provider_blocked,
torznab_host[0] not in searchprov.keys(),
]
):
searchprov[torznab_host[0]] = {
"id": comicarr.PROVIDER_START_ID + 1,
"type": "torznab",
"lastrun": 0,
"active": True,
"hits": 0,
}
fnd = True
elif all(
[
nninfo["provider"] == prov_order[prov_count],
not provider_blocked,
torznab_host[0] in searchprov.keys(),
]
):
searchprov[torznab_host[0]]["active"] = True
fnd = True
if fnd is True:
break
elif "newznab" in prov_order[prov_count]:
fnd = False
for nninfo in provider_list["newznab_info"]:
newznab_host = nninfo["info"]
if newznab_host is None:
logger.fdebug("there was an error - newznab information was blank and it should not be.")
break
if all(
[
nninfo["provider"] == prov_order[prov_count],
not provider_blocked,
newznab_host[0] not in searchprov.keys(),
]
):
searchprov[newznab_host[0]] = {
"id": comicarr.PROVIDER_START_ID + 1,
"type": "newznab",
"lastrun": 0,
"active": True,
"hits": 0,
}
fnd = True
elif all(
[
nninfo["provider"] == prov_order[prov_count],
not provider_blocked,
newznab_host[0] in searchprov.keys(),
]
):
searchprov[newznab_host[0]]["active"] = True
fnd = True
if fnd is True:
break
else:
logger.info("why here? resetting searchprov - last run here..")
newznab_host = None
torznab_host = None
if prov_order[prov_count].lower() not in searchprov.keys():
searchprov[prov_order[prov_count].lower()] = {
"id": comicarr.PROVIDER_START_ID + 1,
"type": prov_order[prov_count].lower(),
"lastrun": 0,
"active": True,
"hits": 0,
}
else:
searchprov[prov_order[prov_count].lower()]["active"] = True
# logger.fdebug('searchprov: %s' % (searchprov,))
# mark the currently active provider here.
current_prov = get_current_prov(searchprov)
logger.info("current_prov: %s" % (current_prov))
if all(
[
not provider_blocked,
"".join(current_prov.keys()) in checked_once,
]
):
break
logger.info("tmp_cmloopit: %s [Issue #:%s]" % (tmp_cmloopit, tmp_IssueNumber))
scarios = {
"tmp_IssueNumber": tmp_IssueNumber,
"ComicYear": ComicYear,
"SeriesYear": SeriesYear,
"Publisher": Publisher,
"IssueDate": IssueDate,
"StoreDate": StoreDate,
"current_prov": current_prov,
"send_prov_count": send_prov_count,
"IssDateFix": IssDateFix,
"IssueID": IssueID,
"UseFuzzy": UseFuzzy,
"newznab_host": newznab_host,
"ComicVersion": ComicVersion,
"SARC": SARC,
"IssueArcID": IssueArcID,
"ComicID": ComicID,
"issuetitle": issuetitle,
"oneoff": oneoff,
"cmloopit": tmp_cmloopit,
"manual": manual,
"torznab_host": torznab_host,
"digitaldate": digitaldate,
"booktype": booktype,
"chktpb": chktpb,
"ignore_booktype": ignore_booktype,
"smode": smode,
"findit": findit,
}
if searchmode == "rss":
logger.info("RSS searchmode enabled for %s" % ComicName)
scarios["RSS"] = "yes"
for xx in gen_altnames(ComicName, AlternateSearch, filesafe, smode):
logger.info("comicname searched for: %s" % ComicName)
if all([findit["status"] is False, not provider_blocked]):
scarios["ComicName"] = xx["ComicName"]
scarios["unaltered_ComicName"] = xx["unaltered_ComicName"]
findit = search_the_matrix(scarios)
if findit["status"] is True:
logger.fdebug("findit = found!")
break
else:
logger.info("API searchmode enabled for %s" % ComicName)
scarios["RSS"] = "no"
for xx in gen_altnames(ComicName, AlternateSearch, filesafe, smode):
logger.info("comicname searched for: %s" % ComicName)
if all([findit["status"] is False, not provider_blocked]):
scarios["ComicName"] = xx["ComicName"]
scarios["unaltered_ComicName"] = xx["unaltered_ComicName"]
findit = search_the_matrix(scarios)
logger.info("findit: %s" % (findit,))
if findit["status"] is True:
logger.fdebug("findit = found!")
break
if findit["status"] is True:
# logger.fdebug("findit = found!")
break
if all(
[
not provider_blocked,
"".join(current_prov.keys()) not in checked_once,
]
) and "".join(current_prov.keys()) in (
"32P",
"DDL(GetComics)",
"DDL(External)",
"Public Torrents",
"experimental",
):
logger.info("check_once check.")
checked_once.append("".join(current_prov.keys()))
if current_prov.get("newznab"):
current_prov[newznab_host[0].rstrip()] = current_prov.pop("newznab")
elif current_prov.get("torznab"):
current_prov[torznab_host[0].rstrip()] = current_prov.pop("torznab")
if manual is not True:
if tmp_IssueNumber is not None:
issuedisplay = tmp_IssueNumber
else:
if any([booktype == "One-Shot", booktype == "TPB", booktype == "HC", booktype == "GC"]):
issuedisplay = None
else:
issuedisplay = StoreDate[5:]
if "annual" in ComicName.lower():
if re.findall(r"(?:19|20)\d{2}", ComicName):
issuedisplay = None
if issuedisplay is None:
logger.info(
"Could not find %s (%s) using %s [%s]"
% (ComicName, SeriesYear, list(current_prov.keys())[0], searchmode)
)
else:
logger.info(
"Could not find Issue %s of %s (%s) using %s [%s]"
% (
issuedisplay,
ComicName,
SeriesYear,
list(current_prov.keys())[0],
searchmode,
)
)
if findit["status"] is True:
if current_prov.get("newznab"):
current_prov[newznab_host[0].rstrip() + " (newznab)"] = current_prov.pop("newznab")
elif current_prov.get("torznab"):
current_prov[torznab_host[0].rstrip() + " (torznab)"] = current_prov.pop("torznab")
srchloop = 4
break
elif srchloop == 2 and (tmp_cmloopit - 1 >= 1) and "".join(current_prov.keys()) not in checked_once:
# don't think this is needed as we do the check_time btwn searches now
pass
tmp_cmloopit -= 1
prov_count += 1
logger.info("attempting to set %s to not being the active provider." % (list(current_prov.keys())[0]))
if findit["lastrun"] != 0:
logger.info("setting last run to: %s" % (findit["lastrun"]))
last_run_check(
write={
"".join(current_prov.keys()): {
"active": False,
"lastrun": findit["lastrun"],
"type": current_prov[list(current_prov.keys())[0]]["type"],
"hits": current_prov[list(current_prov.keys())[0]]["hits"],
"id": current_prov[list(current_prov.keys())[0]]["id"],
}
}
)
# current_prov[list(current_prov.keys())[0]]['lastrun'] = findit['lastrun']
current_prov[list(current_prov.keys())[0]]["active"] = False
logger.info("setting took. Current provider is: %s" % (current_prov,))
srchloop += 1
if manual is True:
logger.info("I have matched %s files: %s" % (len(comicarr.COMICINFO), comicarr.COMICINFO))
return comicarr.COMICINFO, "None"
if findit["status"] is True:
# check for snatched_havetotal being enabled here and adjust counts now.
# IssueID being the catch/check for one-offs as they won't exist on the
# watchlist and error out otherwise.
if comicarr.CONFIG.SNATCHED_HAVETOTAL and any([oneoff is False, IssueID is not None]):
logger.fdebug("Adding this to the HAVE total for the series.")
helpers.incr_snatched(ComicID)
return findit, list(current_prov.keys())[0]
else:
logger.fdebug("findit: %s" % findit)
if manualsearch is None:
logger.info("Finished searching via : %s. Issue not found - status kept as Wanted." % searchmode)
else:
logger.fdebug("Could not find issue doing a manual search via : %s" % searchmode)
if current_prov.get("32P"):
if comicarr.CONFIG.MODE_32P == 0:
return findit, "None"
elif comicarr.CONFIG.MODE_32P == 1 and searchmode == "api":
return findit, "None"
# AI search expansion: generate alternate queries when all providers fail
if not _ai_expanded and ComicID is not None:
try:
from comicarr.app.ai.search_expansion import (
expand_search_queries,
persist_successful_expansion,
)
ai_alternates = expand_search_queries(
comic_id=ComicID,
series_name=ComicName,
publisher=Publisher,
year=SeriesYear,
)
if ai_alternates:
logger.fdebug(
"[AI-SEARCH] Retrying search with %d AI-generated alternates for %s"
% (len(ai_alternates), ComicName)
)
# Append AI alternates to existing AlternateSearch
ai_alt_str = "##".join(ai_alternates)
if AlternateSearch and AlternateSearch != "None":
expanded_alt = AlternateSearch + "##" + ai_alt_str
else:
expanded_alt = ai_alt_str
ai_findit, ai_prov = search_init(
ComicName,
IssueNumber,
ComicYear,
SeriesYear,
Publisher,
IssueDate,
StoreDate,
IssueID,
AlternateSearch=expanded_alt,
UseFuzzy=UseFuzzy,
ComicVersion=ComicVersion,
SARC=SARC,
IssueArcID=IssueArcID,
smode=smode,
rsschecker=rsschecker,
ComicID=ComicID,
manualsearch=manualsearch,
filesafe=filesafe,
allow_packs=allow_packs,
oneoff=oneoff,
manual=manual,
torrentid_32p=torrentid_32p,
digitaldate=digitaldate,
booktype=booktype,
ignore_booktype=ignore_booktype,
_ai_expanded=True,
content_type=content_type,
chapter_number=chapter_number,
volume_number=volume_number,
)
if ai_findit.get("status") is True:
# Determine which alternate worked by checking the result
for alt in ai_alternates:
persist_successful_expansion(ComicID, alt)
break
return ai_findit, ai_prov
except Exception as e:
logger.error("[AI-SEARCH] Expansion fallback error: %s" % e)
return findit, "None"
def provider_order(initial_run=False):
from comicarr.app.search.providers import effective_provider_plan, runtime_provider_entry
plan = effective_provider_plan(comicarr.CONFIG, is_blocked=helpers.block_provider_check)
tor_candidates = [
candidate for candidate in plan if candidate.kind in {"torznab", "torrent"} and not candidate.blocked
]
nzb_candidates = [
candidate for candidate in plan if candidate.kind in {"newznab", "experimental"} and not candidate.blocked
]
ddl_candidates = [candidate for candidate in plan if candidate.kind == "ddl" and not candidate.blocked]
torp = sum(1 for candidate in tor_candidates if candidate.kind == "torrent")
torznabs = sum(1 for candidate in tor_candidates if candidate.kind == "torznab")
nzbp = sum(1 for candidate in nzb_candidates if candidate.kind == "experimental")
newznabs = sum(1 for candidate in nzb_candidates if candidate.kind == "newznab")
ddls = len(ddl_candidates)
if initial_run:
logger.fdebug("nzbprovider(s): %s" % [candidate.execution_name for candidate in nzb_candidates])
torproviders = torp + torznabs
if initial_run:
logger.fdebug("There are %s torrent providers you have selected." % torproviders)
providercount = int(nzbp + newznabs)
if initial_run:
logger.fdebug("There are : %s nzb providers you have selected" % providercount)
if providercount > 0:
logger.fdebug("Usenet Retention : %s days" % comicarr.CONFIG.USENET_RETENTION)
if ddls > 0 and initial_run:
logger.fdebug("there are %s Direct Download providers that are currently enabled." % ddls)
totalproviders = providercount + torproviders + ddls
active_plan = [candidate for candidate in plan if not candidate.blocked]
prov_order = [candidate.execution_name for candidate in active_plan]
torznab_info = [
{"provider": candidate.execution_name, "info": runtime_provider_entry(candidate)}
for candidate in active_plan
if candidate.kind == "torznab"
]
newznab_info = [
{"provider": candidate.execution_name, "info": runtime_provider_entry(candidate)}
for candidate in active_plan
if candidate.kind == "newznab"
]
# if initial_run:
# logger.fdebug('search provider order is %s' % prov_order)
return {
"prov_order": prov_order,
"torznab_info": torznab_info,
"newznab_info": newznab_info,
"totalproviders": totalproviders,
}
def NZB_SEARCH(
ComicName,
IssueNumber,
ComicYear,
SeriesYear,
Publisher,
IssueDate,
StoreDate,
nzbprov,
prov_count,
IssDateFix,
IssueID,
UseFuzzy,
newznab_host=None,
ComicVersion=None,
SARC=None,
IssueArcID=None,
RSS=None,
ComicID=None,
issuetitle=None,
unaltered_ComicName=None,
allow_packs=None,
oneoff=False,
cmloopit=None,
manual=False,
torznab_host=None,
torrentid_32p=None,
digitaldate=None,
booktype=None,
chktpb=0,
ignore_booktype=False,
smode=None,
):
# Pack eligibility only requires torrent search to be enabled; historically it
# was also gated behind ENABLE_32P, which blocked packs from every other
# torrent/Torznab provider (#632).
if any([allow_packs == 1, allow_packs == "1", allow_packs is True]) and comicarr.CONFIG.ENABLE_TORRENT_SEARCH:
allow_packs = True
else:
allow_packs = False
newznab_local = False
untouched_name = None
provider_stat = nzbprov
# logger.fdebug('provider_stat_before: %s' % (provider_stat))
if type(nzbprov) != str:
nzbprov = list(nzbprov.keys())[0]
provider_stat = provider_stat.get(list(provider_stat.keys())[0])
# logger.info('nzbprov: %s' % (nzbprov))
# logger.fdebug('provider_stat_after: %s' % (provider_stat))
if nzbprov == "experimental":
apikey = "none"
verify = False
elif provider_stat["type"] == "torznab":
name_torznab = torznab_host[0].rstrip()
host_torznab = torznab_host[1].rstrip()
verify = bool(int(torznab_host[2]))
apikey = torznab_host[3].rstrip()
category_torznab = torznab_host[4]
if any([category_torznab is None, category_torznab == "None"]):
category_torznab = "8020"
if "#" in category_torznab:
t_cats = category_torznab.split("#")
category_torznab = ",".join(t_cats)
logger.fdebug("Using Torznab host of : %s" % name_torznab)
elif provider_stat["type"] == "newznab":
# updated to include Newznab Name now
name_newznab = newznab_host[0].rstrip()
host_newznab = newznab_host[1].rstrip()
untouched_name = name_newznab
if name_newznab[-7:] == "[local]":
name_newznab = name_newznab[:-7].strip()
newznab_local = True
elif name_newznab[-10:] == "[nzbhydra]":
name_newznab = name_newznab[:-10].strip()
newznab_local = False
apikey = newznab_host[3].rstrip()
verify = bool(int(newznab_host[2]))
if "#" in newznab_host[4].rstrip():
catstart = newznab_host[4].find("#")
category_newznab = re.sub("#", ",", newznab_host[4][catstart + 1 :]).strip()
logger.fdebug("Non-default Newznab category set to : %s" % category_newznab)
else:
category_newznab = "7030"
logger.fdebug("Using Newznab host of : %s" % name_newznab)
if RSS == "yes":
if provider_stat["type"] == "newznab":
tmpprov = "%s (%s) [RSS]" % (name_newznab, provider_stat["type"])
elif provider_stat["type"] == "torznab":
tmpprov = "%s (%s) [RSS]" % (name_torznab, provider_stat["type"])
else:
tmpprov = "%s [RSS]" % nzbprov
else:
if provider_stat["type"] == "newznab":
tmpprov = "%s (%s)" % (name_newznab, provider_stat["type"])
elif provider_stat["type"] == "torznab":
tmpprov = "%s (%s)" % (name_torznab, provider_stat["type"])
else:
tmpprov = nzbprov
if cmloopit == 4:
issuedisplay = None
logger.info("Shhh be very quiet...I'm looking for %s (%s) using %s." % (ComicName, ComicYear, tmpprov))
elif IssueNumber is not None:
issuedisplay = IssueNumber
else:
issuedisplay = StoreDate[5:]
if "0-Day Comics Pack" in ComicName:
logger.info("Shhh be very quiet...I'm looking for %s using %s." % (ComicName, tmpprov))
elif cmloopit != 4:
logger.info(
"Shhh be very quiet...I'm looking for %s issue: %s (%s) using %s."
% (ComicName, issuedisplay, ComicYear, tmpprov)
)
comsearch = []
isssearch = []
comyear = str(ComicYear)
findcomic = ComicName
cm1 = re.sub(r"[\/\-]", " ", findcomic)
# remove 'and' & '&' from the search pattern entirely