forked from nzbgetcom/Extension-Completion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
2056 lines (1983 loc) · 78.3 KB
/
main.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
#
# Completion.py script for NZBGet
#
# Copyright (C) 2014-2017 kloaknet.
# Copyright (C) 2024 Denis <[email protected]>
#
# This program 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
# any later version.
#
# This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
#
import os
import urllib.request, urllib.error, urllib.parse
import base64
import json
import time
import sys
import socket
import ssl
import traceback
import html.parser
import errno
from xmlrpc.client import ServerProxy
from operator import itemgetter
sys.stdout.reconfigure(encoding="utf-8")
# Defining constants
AGE_LIMIT = int(os.environ.get("NZBPO_AgeLimit", 4))
AGE_LIMIT_SEC = 3600 * AGE_LIMIT
AGE_SORT_LIMIT = int(os.environ.get("NZBPO_AgeSortLimit", 48))
if AGE_LIMIT > AGE_SORT_LIMIT:
AGE_SORT_LIMIT = AGE_LIMIT
AGE_SORT_LIMIT_SEC = 3600 * AGE_SORT_LIMIT
CHECK_DUPES = os.environ.get("NZBPO_CheckDupes", "No")
if CHECK_DUPES != "No" and os.environ.get("NZBOP_DUPECHECK") == "No":
print(
"[WARNING] DupeCheck should be enabled in NZBGet, otherwise "
+ "the CheckDupes option of this script that you have enabled "
+ "does not work"
)
FORCE_FAILURE = os.environ.get("NZBPO_ForceFailure", "No") == "Yes"
CATEGORIES = os.environ.get("NZBPO_Categories", "").lower().split(",")
CATEGORIES = [c.strip(" ") for c in CATEGORIES]
SERVERS = os.environ.get("NZBPO_Servers", "").lower().split(",")
SERVERS = [c.strip(" ") for c in SERVERS]
FILL_SERVERS = os.environ.get("NZBPO_FillServers", "").lower().split(",")
FILL_SERVERS = [c.strip(" ") for c in FILL_SERVERS]
MAX_FAILURE = int(os.environ.get("NZBPO_MaxFailure", 0))
CHECK_METHOD = "STAT"
VERBOSE = os.environ.get("NZBPO_Verbose", "No") == "Yes"
EXTREME = os.environ.get("NZBPO_Extreme", "No") == "Yes"
IGNORE_QUEUE_PRIORITY = os.environ.get("NZBPO_IgnoreQueuePriority", "No") == "Yes"
CHECK_LIMIT = int(os.environ.get("NZBPO_CheckLimit", 10))
MAX_ARTICLES = int(os.environ.get("NZBPO_MaxArticles", 1000))
MIN_ARTICLES = int(os.environ.get("NZBPO_MinArticles", 50))
FULL_CHECK_NO_PARS = os.environ.get("NZBPO_FullCheckNoPars", "Yes") == "Yes"
NNTP_TIME_OUT = 2 # low, but should be sufficient for connection check
SOCKET_CREATE_INTERVAL = 0.000 # optional delay to avoid handshake time outs
SOCKET_LOOP_INTERVAL = 0.200 # max delay single loop on data received
HOST = os.environ["NZBOP_CONTROLIP"] # NZBGet host
if HOST == "0.0.0.0":
HOST = "127.0.0.1" # fix to localhost
PORT = os.environ["NZBOP_CONTROLPORT"] # NZBGet port
USERNAME = os.environ["NZBOP_CONTROLUSERNAME"] # NZBGet username
PASSWORD = os.environ["NZBOP_CONTROLPASSWORD"] # NZBGet password
def unpause_nzb(nzb_id):
"""
resume the nzb with NZBid in the NZBGet queue via RPC-API
"""
NZBGet = connect_to_nzbget()
NZBGet.editqueue("GroupResume", 0, "", [int(nzb_id)]) # Resume nzb
NZBGet.editqueue("GroupPauseExtraPars", 0, "", [int(nzb_id)]) # Pause pars
def unpause_nzb_dupe(dupe_nzb_id, nzb_id):
"""
resume the nzb with NZBid in the NZBGet history via RPC-API, move the
other one to history.
"""
NZBGet = connect_to_nzbget()
# Return item from history (before deleting, to avoid NZBGet automatically
# returning a DUPE instead of the script).
NZBGet.editqueue("HistoryRedownload", 0, "", [int(dupe_nzb_id)]) # Return
NZBGet.editqueue("GroupResume", 0, "", [int(dupe_nzb_id)]) # Resume nzb
# Pause pars
NZBGet.editqueue("GroupPauseExtraPars", 0, "", [int(dupe_nzb_id)])
# Remove item in queue, send back to history as DUPE
NZBGet.editqueue("GroupDupeDelete", 0, "", [int(nzb_id)])
def mark_bad(nzb_id):
"""
mark the nzb with NZBid BAD in the NZBGet queue via RPC-API
"""
NZBGet = connect_to_nzbget()
NZBGet.editqueue("GroupDelete", 0, "", [int(nzb_id)]) # need to delete
NZBGet.editqueue("HistoryMarkBad", 0, "", [int(nzb_id)]) # mark bad
def mark_bad_dupe(dupe_nzb_id):
"""
mark the nzb with NZBid BAD in the NZBGet history via RPC-API, item is
already in history, so no moving.
"""
NZBGet = connect_to_nzbget()
NZBGet.editqueue("HistoryMarkBad", 0, "", [int(dupe_nzb_id)]) # mark bad
def force_failure(nzb_id):
"""
mark BAD doesn't do the trick for FailureLink, Sonarr, SickBeard
Forces failure, removes all files but one .par2
sending deleted nzb back to queue will restore the deleted files.
When available, the smallest par and smallest other file will be kept.
"""
if VERBOSE:
print("[V] force_failure(nzb_id=" + str(nzb_id) + ")")
NZBGet = connect_to_nzbget()
data = NZBGet.listfiles(0, 0, [int(nzb_id)])
id_list = []
file_size_low = 100000000000 # 100 Gb, file size will never occur.
par_size_low = 100000000000
for f in data: # find smallest par2 and file
file_name = f.get("Filename").lower()
if ".par2" not in file_name:
temp = f.get("FileSizeLo")
if temp < file_size_low:
file_size_low = temp
else:
temp = f.get("FileSizeLo")
if temp < par_size_low:
par_size_low = temp
for f in data: # match files on size for deletion
temp = f.get("FileSizeLo")
if temp != file_size_low and temp != par_size_low:
id = int(f.get("ID"))
id_list.append(id)
else:
if VERBOSE:
print(
"[V] Leaving file: " + str(f.get("Filename")) + " in the NZB file"
)
print("[WARNING] Forcing failure of NZB:")
sys.stdout.flush() # force message before lot of NZBGet messages
time.sleep(0.1) # create time to flush
# delete all listed files
NZBGet.editqueue("FileDelete", 0, "", id_list)
# Resume nzb in queue to download single remaining file in NZB
NZBGet.editqueue("GroupResume", 0, "", nzb_id)
def force_failure_dupe(dupe_nzb_id):
"""
mark BAD doesn't do the trick for FailureLink, Sonarr, SickBeard
Forces failure, removes all files but one .par2
sending deleted nzb back to queue will restore the deleted files.
although no dupes are expected from Sonarr and the likes, maybe a RSS
feed for movies or other stuff is used that might produce dupes.
"""
if VERBOSE:
print("[V] force_failure_dupe(nzb_id=" + str(dupe_nzb_id) + ")")
NZBGet = connect_to_nzbget()
if VERBOSE:
print("[V] Pausing failed DUPE NZB before returning to queue.")
# pause all files before returning to queue
NZBGet.editqueue("GroupPause", 0, "", dupe_nzb_id)
if VERBOSE:
print("[V] Returning failed DUPE NZB to queue.")
# return item back to queue to be able to force a failure
NZBGet.editqueue("HistoryReturn", 0, "", dupe_nzb_id)
force_failure(dupe_nzb_id)
def connect_to_nzbget():
"""
Establish connection to NZBGet via RPC-API using HTTP.
"""
# Build an URL for XML-RPC requests:
xmlRpcUrl = "http://%s:%s@%s:%s/xmlrpc" % (USERNAME, PASSWORD, HOST, PORT)
# Create remote server object
NZBGet = ServerProxy(xmlRpcUrl)
return NZBGet
def call_nzbget_direct(url_command):
"""
Connect to NZBGet and call an RPC-API-method without using of python's
XML-RPC. XML-RPC is easy to use but it is slow for large amounts of
data.
"""
# Building http-URL to call the method
http_url = "http://%s:%s/jsonrpc/%s" % (HOST, PORT, url_command)
request = urllib.request.Request(http_url)
base_64_string = (
base64.b64encode(("%s:%s" % (USERNAME, PASSWORD)).encode("utf-8"))
.decode("utf-8")
.strip()
)
request.add_header("Authorization", "Basic %s" % base_64_string)
response = urllib.request.urlopen(request) # get some data from NZBGet
# data is a JSON raw-string, contains ALL properties each NZB in queue
data = response.read().decode("utf-8")
return data
def get_nzb_filename(parameters):
"""
get the real nzb_filename from the added parameter CnpNZBFileName or from env
"""
file_name = os.environ.get("NZBNA_QUEUEDFILE")
if file_name:
return file_name
for p in parameters:
if p["Name"] == "CnpNZBFileName":
break
return p["Value"]
def get_max_failed_limit(critical_health) -> float:
return round(100 - critical_health / 10.0, 1)
def get_nzb_status(nzb):
"""
check if amount of failed articles is not too much. If too much keep
paused, if too old and too much failure mark bad / force failure,
otherwise resume. When an -1 or -2 is returned from check_nzb(), the
nzb is unpaused, hoping NZBGet can still process the file, while the
script can't.
"""
if VERBOSE:
print("[V] get_nzb_status(nzb=" + str(nzb) + ")")
print('Checking: "' + nzb[1] + '"')
# collect rar msg ids that need to be checked
rar_msg_ids = get_nzb_data(nzb[1])
if rar_msg_ids == -1: # no such NZB file
succes = True # file send back to queue
print(
"[WARNING] The NZB file "
+ str(nzb[1])
+ " does not seem to "
+ "exist, resuming NZB."
)
unpause_nzb(nzb[0]) # unpause based on NZBGet ID
elif rar_msg_ids == -2: # empty NZB or no group
succes = True # file send back to queue
print(
"[WARNING] The NZB file "
+ str(nzb[1])
+ " appears to be "
+ "invalid, resuming NZB."
)
unpause_nzb(nzb[0]) # unpause based on NZBGet ID
elif rar_msg_ids == -3: # NZB without RAR files.
succes = True # file send back to queue
print(
"[WARNING] The NZB file "
+ str(nzb[1])
+ " does not contain "
+ "any .rar files and has been moved back to the queue."
)
unpause_nzb(nzb[0]) # unpause based on NZBGet ID
else:
failed_limit = get_max_failed_limit(nzb[3])
print("Maximum failed articles limit for NZB: " + str(failed_limit) + "%")
if MAX_FAILURE > 0:
print(
"Maximum failed articles limit for highest level news server: "
+ str(MAX_FAILURE)
+ "%"
)
failed_ratio = check_failure_status(rar_msg_ids, failed_limit, nzb[2])
if VERBOSE:
print("[V] Total failed ratio: " + str(round(failed_ratio, 1)) + "%")
if (
failed_ratio < failed_limit
and (failed_ratio < MAX_FAILURE or MAX_FAILURE == 0)
) or failed_ratio == 0:
succes = True
print('Resuming: "' + nzb[1] + '"')
sys.stdout.flush()
unpause_nzb(nzb[0]) # unpause based on NZBGet ID
elif (
failed_ratio >= failed_limit
or (failed_ratio >= MAX_FAILURE and MAX_FAILURE > 0)
) and nzb[2] < (int(time.time()) - int(AGE_LIMIT_SEC)):
succes = False
if VERBOSE:
if not FORCE_FAILURE:
print('[V] Marked as BAD: "' + nzb[1] + '"')
sys.stdout.flush() # otherwise NZBGet sends message first
if FORCE_FAILURE:
force_failure(nzb[0])
else:
mark_bad(nzb[0])
else:
succes = False
# dupekey should not be '', that would mean it is not added by RSS
if CHECK_DUPES != "no" and nzb[4] != "":
if get_dupe_nzb_status(nzb):
print(
'"'
+ nzb[1]
+ '" moved to history as DUPE, '
+ "complete DUPE returned to queue."
)
else:
print(
'[WARNING] "'
+ nzb[1]
+ '", remains paused for next check, '
+ "no suitable/complete DUPEs found in history"
)
elif CHECK_DUPES != "no" and nzb[4] == "" and VERBOSE:
print(
"[V] "
+ nzb[1]
+ " is not added via RSS, therefore "
+ "the dupekey is empty and checking for DUPEs in the history "
+ "is skipped."
)
return succes
def get_dupe_nzb_status(nzb):
"""
check dupes in the history on their possible completion when the item
in the queue is not yet complete. When complete DUPE item, move it
back into the queue, and move the otherone to history.
"""
if VERBOSE:
print("[V] get_dupe_nzb_status(nzb=" + str(nzb) + ")")
# get the data from the active history
data = call_nzbget_direct("history")
jobs = json.loads(data)
duplicate = False
num_duplicates = 0
list_duplicates = []
for job in jobs["result"]:
if (
job["Status"] == "DELETED/DUPE"
and job["DupeKey"] == nzb[4]
and "CnpNZBFileName" in str(job)
):
if CHECK_DUPES == "yes":
duplicate = True
num_duplicates += 1
list_duplicates.append(job)
elif CHECK_DUPES == "SameScore" and job["DupeScore"] >= nzb[5]:
duplicate = True
num_duplicates += 1
list_duplicates.append(job)
else:
if VERBOSE:
print(
"[V] DUPE NZB found with lower dupe score, "
+ "ignored due to SameScore setting."
)
if duplicate:
# sort on nzb age, then on dupescore. Higher score items will be on
# top. Oldest file has lowest maxposttime.
if VERBOSE:
print(
"[V] "
+ str(num_duplicates)
+ " duplicate of "
+ nzb[1]
+ " found in history"
)
t = sorted(list_duplicates, key=itemgetter("MaxPostTime"))
sorted_duplicates = sorted(t, key=itemgetter("DupeScore"), reverse=True)
i = 0
# loop through all DUPE items (with optional matching DUPEscore)
for job in sorted_duplicates:
i += 1
nzb_id = job["NZBID"]
nzb_filename = get_nzb_filename(job["Parameters"])
nzb_age = job["MaxPostTime"] # nzb age
nzb_critical_health = job["CriticalHealth"]
print(
'Checking DUPE: "'
+ nzb_filename
+ '" ['
+ str(i)
+ "/"
+ str(num_duplicates)
+ "]"
)
rar_msg_ids = get_nzb_data(nzb[1])
if rar_msg_ids == -1: # no such NZB file
success = False # file marked BAD
if VERBOSE:
print("[WARNING] [V] No such DUPE NZB file, marking BAD.")
if FORCE_FAILURE:
force_failure_dupe(nzb_id) #
else:
mark_bad_dupe(nzb_id)
elif rar_msg_ids == -2: # empty NZB or no group
success = False # file marked BAD
if VERBOSE:
print("[WARNING] [V] DUPE NZB appears invalid, marking BAD.")
if FORCE_FAILURE:
force_failure_dupe(nzb_id) #
else:
mark_bad_dupe(nzb_id)
else:
failed_limit = get_max_failed_limit(nzb[3])
print("[V] Maximum failed articles limit: " + str(failed_limit) + "%")
failed_ratio = check_failure_status(rar_msg_ids, failed_limit, nzb[2])
if VERBOSE:
print(
"[V] Total failed ratio: " + str(round(failed_ratio, 1)) + "%"
)
if (
failed_ratio < failed_limit
and (failed_ratio < MAX_FAILURE or MAX_FAILURE == 0)
) or failed_ratio == 0:
success = True
print('Resuming DUPE: "' + nzb_filename + '"')
sys.stdout.flush()
unpause_nzb_dupe(nzb_id, nzb[0]) # resume on NZBGet ID
break
elif (
failed_ratio >= failed_limit
or (failed_ratio >= MAX_FAILURE and MAX_FAILURE > 0)
) and nzb_age < (int(time.time()) - int(AGE_LIMIT_SEC)):
success = False
if VERBOSE:
if not FORCE_FAILURE:
print('[V] Marked as BAD: "' + nzb[1] + '"')
else:
print('[V] Forcing failure of: "' + nzb[1] + '"')
sys.stdout.flush()
if FORCE_FAILURE:
force_failure_dupe(nzb_id)
else:
mark_bad_dupe(nzb_id)
else:
success = False
else:
if VERBOSE:
print("[V] No DUPE of " + nzb[1] + " found in history.")
success = False
return success
def is_number(s):
"""
Checks if the string can be converted to a number
"""
try:
float(s)
return True
except ValueError:
return False
def check_send_server_reply(
sock, reply: str, group: str, id, i, host, username, password
):
"""
Check NNTP server messages, send data for next recv.
After connecting, there will be a 200 message, after each message, a
reply (t) will be send to get a next message.
More info on NNTP server responses:
The first digit of the response broadly indicates the success,
failure, or progress of the previous command:
1xx - Informative message
2xx - Command completed OK
3xx - Command OK so far; send the rest of it
4xx - Command was syntactically correct but failed for some reason
5xx - Command unknown, unsupported, unavailable, or syntax error
The next digit in the code indicates the function response category:
x0x - Connection, setup, and miscellaneous messages
x1x - Newsgroup selection
x2x - Article selection
x3x - Distribution functions
x4x - Posting
x8x - Reserved for authentication and privacy extensions
x9x - Reserved for private use (non-standard extensions
"""
if EXTREME:
print(
"[E] check_send_server_reply(sock= "
+ str(sock)
+ ", t= "
+ reply
+ " ,group= "
+ str(group)
+ " , id= "
+ str(id)
+ " , i= "
+ str(i)
+ " )"
)
try:
id_used = False # is id used via HEAD / STAT request to NNTP server
msg_id_used = None
error = False
server_reply = str(reply[:3]) # only first 3 chars are relevant
# no correct NNTP server code received, most likely still propagating?
if not is_number(server_reply):
if VERBOSE:
print(
"[WARNING] [V] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", NNTP reply incorrect:"
+ str(reply.split())
)
server_reply = "NNTP reply incorrect."
error = True # pass these vars so that next article will be sent
id_used = True # pass these vars so that next article will be sent
return (error, id_used, server_reply, msg_id_used)
# checking NNTP server server_replies
if server_reply in ("411", "420", "423", "430"):
# 411 no such group
# 420 no current article has been selected
# 423 no such article number in this group
# 430 no such article found
if VERBOSE:
print(
"[WARNING] [V] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", NNTP reply: "
+ str(reply.split())
)
error = True # article is not there
elif server_reply in ("412"): # 412 no newsgroup has been selected
text = "GROUP " + group + "\r\n"
if EXTREME:
print(
"[E] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", NNTP reply: "
+ str(reply.split())
)
print("[E] Socket: " + str(i) + " " + str(host) + ", Send: " + text)
sock.send(text.encode("utf-8"))
elif server_reply in ("221"):
# 221 article retrieved - head follows (reply on HEAD)
msg_id_used = reply.split()[2][1:-1] # get msg id to identify ok article
if EXTREME:
print(
"[E] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", NNTP reply: "
+ str(reply.split())
)
elif server_reply in ("223"):
# 223 article retrieved - request text separately (reply on STAT)
msg_id_used = reply.split()[2][1:-1] # get msg id to identify ok article
if EXTREME:
print(
"[E] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", NNTP reply: "
+ str(reply.split())
)
elif server_reply in ("200", "201"):
# 200 service available, posting permitted
# 201 service available, posting prohibited
if EXTREME:
print(
"[INFO] [E] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", NNTP reply: "
+ str(reply.split())
)
text = CHECK_METHOD + " <" + id + ">\r\n" # STAT is faster than HEAD
if EXTREME:
print(
"[E] Socket: " + str(i) + " " + str(host) + ", Send: " + str(text)
)
sock.send(text.encode("utf-8"))
elif server_reply in ("381"): # 381 Password required
text = "AUTHINFO PASS %s\r\n" % (password)
if EXTREME:
print(
"[E] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", NNTP reply: "
+ str(reply.split())
)
print(
"[E] Socket: " + str(i) + " " + str(host) + ", Send: " + str(text)
)
sock.send(text.encode("utf-8"))
elif server_reply in ("281"): # 281 Authentication accepted
if EXTREME:
print(
"[E] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", NNTP reply: "
+ str(reply.split())
)
elif server_reply in ("211"): # 211 group selected (group)
if EXTREME:
print(
"[INFO] [E] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", NNTP reply: "
+ str(reply.split())
)
elif server_reply in ("480"): # 480 AUTHINFO required
text = "AUTHINFO USER %s\r\n" % (username)
if EXTREME:
print(
"[E] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", NNTP reply: "
+ str(reply.split())
)
print(
"[E] Socket: " + str(i) + " " + str(host) + ", Send: " + str(text)
)
sock.send(text.encode("utf-8"))
elif str(server_reply[:2]) in ("48", "50"):
# 48X or 50X incorrect news server account settings
print(
"[ERROR] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", Incorrect news server account settings: "
+ reply
)
elif server_reply in ("205"): # NNTP Service exits normally
sock.close()
if EXTREME:
print(
"[E] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", NNTP reply: "
+ str(reply.split())
)
if VERBOSE:
print("[V] Socket " + str(i) + " closed.")
elif server_reply in ("999"): # script code for very slow news server
if VERBOSE:
print(
"[WARNING] [V] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", NNTP reply: "
+ str(reply.split())
)
error = True # article is assumed to be not there
id_used = True
else:
if VERBOSE:
print(
"[WARNING] [V] Socket: "
+ str(i)
+ " "
+ str(host)
+ ", Not covered NNTP server reply code: "
+ str(reply.split())
)
if VERBOSE or EXTREME:
sys.stdout.flush()
if end_loop == False and server_reply in (
"211",
"221",
"223",
"281",
"411",
"420",
"423",
"430",
):
# Send next message
text = CHECK_METHOD + " <" + id + ">\r\n" # STAT is faster than HEAD
id_used = True
if EXTREME:
print(
"[E] Socket: " + str(i) + " " + str(host) + ", Send: " + str(text)
)
sock.send(text.encode("utf-8"))
elif end_loop and server_reply not in ("205"):
text = "QUIT\r\n"
sock.send(text.encode("utf-8"))
if EXTREME:
print(
"[E] Socket: " + str(i) + " " + str(host) + ", Send: " + str(text)
)
if VERBOSE or EXTREME:
sys.stdout.flush()
return (error, id_used, server_reply, msg_id_used)
except:
print(
"Exception LINE: "
+ str(traceback.print_exc())
+ ": "
+ str(sys.exc_info()[1])
)
return (False, False, server_reply, -1)
def fix_nzb(nzb_lines):
"""
some nzbs may contain all data on 1 single line, to handle this
correctly in check_nzb(), the single line is splitted on the >< mark
"""
if VERBOSE:
print("[V] fix_nzb(nzb_lines=" + str(nzb_lines) + ")")
print("[V] Splitting NZB data into separate lines.")
sys.stdout.flush()
nzb_lines = str(nzb_lines)
positions = [n for n in range(len(nzb_lines)) if nzb_lines.find("><", n) == n]
first = 0
last = 0
corrected_lines = []
for n in positions:
last = n + 1
corrected_lines.append(nzb_lines[first:last])
first = last
if VERBOSE:
print("[V] Data in NZB splitted into separate lines.")
sys.stdout.flush()
return corrected_lines
def get_nzb_data(fname):
"""
extract the nzb info from the NZB file, and return data set of articles
to be checked
"""
if VERBOSE:
print("[V] get_nzb_data(fname=" + str(fname) + ")")
sys.stdout.flush()
if os.path.isfile(fname):
file_exists = True
fd = open(fname, encoding="utf-8")
lines = fd.readlines()
fd.close()
if len(lines) == 1: # single line NZB
lines = fix_nzb(lines)
else:
file_exists = False
print("[ERROR] No such nzb file.")
return -1
if file_exists:
all_msg_ids = [] # list of message ids for NNTP server
group = None
groups = None
for line in lines:
low_line = line.lower()
if "<segment bytes" in low_line: # msg id
message_id = line.split(">")[1].split("<")[0]
ok = -1 # = no check / failed; 1,2,.. ok for server num
all_msg_ids.append([subject, par, groups, message_id, ok])
elif "<file" in low_line: # look for par2 files
subject = line.split("subject=")[1].split(">")[0]
if ".par2" in low_line:
par = 1 # found a par file, next msg_ids of par2s
else:
par = 0 # not a par file, next msg ids of files
elif "<groups>" in low_line: # set of groups
# new list of groups found
groups = []
elif "<group>" in low_line: # group name
group = line.split(">")[1].split("<")[0]
groups.append(group)
if not group:
print("[ERROR] No group found in NZB file.")
if VERBOSE:
print("[V] group: " + str(group))
return -2
if len(all_msg_ids) == 0:
print("[ERROR] No message-ids found in NZB file")
if VERBOSE:
print("[V] all_msg_ids: " + str(all_msg_ids))
return -2
rar_msg_ids = []
par_msg_ids = []
for msg_id in all_msg_ids: # split par2 from other files
if msg_id[1] == 0:
rar_msg_ids.append(msg_id)
else:
par_msg_ids.append(msg_id)
all_articles = len(all_msg_ids)
rar_articles = len(rar_msg_ids)
par_articles = len(par_msg_ids)
temp = len(rar_msg_ids)
if temp == 0:
# No .rar articles in NZB.
return -3
# check if more than 1 pars are available or not.
if FULL_CHECK_NO_PARS and par_articles < 1:
each = 1 # check each article
if VERBOSE:
print("[V] No par files in release, all articles will be " + "checked.")
elif FULL_CHECK_NO_PARS and par_articles == 1:
each = 1 # check each article
if VERBOSE:
print("[V] 1 par file in release, all articles will be " + "checked.")
else:
each = int(100 / CHECK_LIMIT) # check each Xth article only
if temp / each > MAX_ARTICLES:
each = int(temp / MAX_ARTICLES)
if VERBOSE:
print(
"[V] Amount of to be checked articles limited to about "
+ str(MAX_ARTICLES)
+ " articles."
)
elif temp / each < MIN_ARTICLES:
each = int(temp / MIN_ARTICLES)
if each == 0:
each = 1
if VERBOSE:
print(
"[V] Amount of to be checked articles increased to "
+ "about "
+ str(MIN_ARTICLES)
+ " articles."
)
t = rar_msg_ids[::each]
rar_msg_ids = t
# parsing to be used ids, skipping subject parsing
for i, rar_msg_id in enumerate(rar_msg_ids):
rar_msg_ids[i][3] = html.unescape(rar_msg_id[3])
articles_to_check = len(rar_msg_ids)
if VERBOSE:
print(
"[V] NZB contains "
+ str(all_articles)
+ " articles, "
+ str(rar_articles)
+ " rar articles, "
+ str(par_articles)
+ " par2 articles."
)
print("[V] " + str(articles_to_check) + " rar articles will be checked.")
sys.stdout.flush()
return rar_msg_ids
def get_server_settings(nzb_age):
"""
Get the settings for all the active news-servers in NZBGet, and store
them in a list. Filter out all but 1 server in same group.
"""
if VERBOSE:
print("[V] get_server_settings(nzb_age=" + str(nzb_age) + ")")
# get news server settings for each server
NZBGet = connect_to_nzbget()
nzbget_status = NZBGet.status()
servers_status = nzbget_status["NewsServers"]
temp = []
servers = []
i = 0
skip = False
for server_status in servers_status:
# extract all relevant data for each server:
s = str(server_status["ID"]) # 9
active = os.environ["NZBOP_Server" + s + ".Active"] == "yes" # 10
level = os.environ["NZBOP_Server" + s + ".Level"] # 0
group = os.environ["NZBOP_Server" + s + ".Group"] # 1
host = os.environ["NZBOP_Server" + s + ".Host"] # 2
port = os.environ["NZBOP_Server" + s + ".Port"] # 3
username = os.environ["NZBOP_Server" + s + ".Username"] # 4
password = os.environ["NZBOP_Server" + s + ".Password"] # 5
encryption = os.environ["NZBOP_Server" + s + ".Encryption"] == "yes" # 6
connections = os.environ["NZBOP_Server" + s + ".Connections"] # 7
retention = os.environ["NZBOP_Server" + s + ".Retention"] # 8
if retention == "":
retention = 0
temp.append(
[
level,
group,
host,
port,
username,
password,
encryption,
connections,
retention,
s,
active,
]
)
nzb_age_days = (int(time.time()) - nzb_age) / 3600.0 / 24.0
for server in temp:
skip = False
retention = float(server[8])
# Active or not
if server[10] == False:
skip = True
if VERBOSE:
print(
"[V] Skipping server: "
+ server[2]
+ ", disabled in "
+ "NZBGet settings."
)
# Server ID in SERVERS list
elif (
SERVERS[0] != ""
and server[9] not in SERVERS
and server[9] not in FILL_SERVERS
):
skip = True
if VERBOSE:
print(
"[V] Skipping server: "
+ server[2]
+ ", not listed "
+ "as Server or FillServer in script settings."
)
# Server ID in FILL_SERVERS list and nzb older than AGE_LIMIT
elif server[9] in FILL_SERVERS and nzb_age_days * 24.0 < AGE_LIMIT:
skip = True
if VERBOSE:
print(
"[V] Skipping Fill server: "
+ server[2]
+ ", NZB age of "
+ str(round(nzb_age_days * 24.0, 1))
+ " hours within AgeLimit of "
+ str(AGE_LIMIT)
+ " hours"
)
# Server retention lower than nzb age
if retention < nzb_age_days and retention != 0:
skip = True
if VERBOSE:
print(
"[V] Skipping server: "
+ server[2]
+ ", retention of "
+ str(retention)
+ " days is less than NZB age of "
+ str(round(nzb_age_days, 1))
+ " days."
)
# removing all to be skipped servers
if skip == False:
servers.append(server)
if VERBOSE:
print(
"[V] All news servers after filtering on Active, Servers, "
+ "FillServers + AgeLimit and Retention, "
+ " BEFORE filtering on NZBGet ServerX.Group: "
)
for server in servers:
print(
"[V] * "
+ str(server[2])
+ ":"
+ str(server[3])
+ ", SSL: "
+ str(server[6])
+ ", connections: "
+ str(server[7])
)
# sort on groups, followed by lvl, so that all identical group numbers > 0
# can be removed
servers.sort(key=itemgetter(1, 0))