-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathnzbmonkey.py
1736 lines (1398 loc) · 64.3 KB
/
nzbmonkey.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
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
NZB-Monkey
"""
import argparse
import base64
import io
import json
import operator
import os
import re
import sys
import webbrowser
import xml.etree.ElementTree as ET
from enum import Enum
from glob import glob
from os.path import basename, splitext, isfile, join, expandvars
from pathlib import Path
from time import sleep, time, localtime, strftime
from urllib.parse import urlparse, parse_qs, quote
from unicodedata import normalize
from nzblnkconfig import check_missing_modules
try:
import pyperclip
import requests
import urllib3
from configobj import ConfigObj, SimpleVal
from validate import Validator
from colorama import Fore, init, Style
init()
except ImportError:
check_missing_modules()
sleep(10)
sys.exit(1)
from nzblnkconfig import config_file, config_nzbmonkey
from version import __version__
from nzbmonkeyspec import getSpec
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
WAITING_TIME_LONG = 5
WAITING_TIME_SHORT = 1
REQUESTS_TIMEOUT = 20
SAVE_STDOUT = sys.stdout
SAVE_STDERR = sys.stderr
class ExeTypes(Enum):
EXECUTE = 'EXECUTE',
NZBGET = 'NZBGET',
SABNZBD = 'SABNZBD',
SYNOLOGYDLS = 'SYNOLOGYDLS'
class Col:
OK = Fore.GREEN + Style.BRIGHT
WARN = Fore.YELLOW + Style.BRIGHT
FAIL = Fore.RED + Style.BRIGHT
OFF = Fore.RESET + Style.RESET_ALL
# region NZB-Verifier
class NZBSegment(object):
def __init__(self, bytes_, number, message_id=None):
"""NZB Segment
:param int bytes_: Size in bytes
:param int number: Segment number
:param str message_id: MessageID
"""
self.bytes_ = int(bytes_)
self.number = int(number)
if message_id:
self.message_id = message_id
def set_message_id(self, message_id):
self.message_id = message_id
class NZBFile(object):
def __init__(self, poster, date, subject, groups=None, segments=None, debug=False):
"""NZB File
:param str poster: Poster name
:param str date: Unix date
:param str subject: Header/ Subject
:param list groups: List with groups
:param list segments: List with segments
:param boolean debug: Enable verbose output
"""
self.poster = poster
self.date = date
self.subject = subject
self.groups = groups or list()
self.segments = segments or list()
self.debug = debug
self.segments_total = 0
self.expected_segments = -1
self.missing_segments = None
self.regexes = {'segments_jbin': re.compile(r'.+?\.(\d{1,5})-(\d{1,5})@'),
'files_jbin': re.compile(r'.+?_(\d{1,5})o(\d{1,5})@'),
'segments_powerpost': re.compile(r'part(\d{1,4})of(\d{1,5})')}
self.guessed_segments = False
def add_group(self, group):
"""Append Group to group list"""
self.groups.append(group)
def add_segment(self, segment):
"""Append segment to segment list"""
self.segments.append(segment)
def get_segment_count(self):
"""Return segment count"""
self.segments_total = len(self.segments)
return self.segments_total
def get_expected_segments(self):
""""Return expected segments"""
if self.expected_segments > -1:
return self.expected_segments
else:
return None
def get_missing_segments(self):
"""Calculate missing segments and return the value"""
# If expected value is available calculate missing segments
if self.expected_segments > -1:
self.missing_segments = self.expected_segments - self.segments_total
return self.missing_segments
def guess_expected_segments(self):
"""Guess the expected segments from the number attribute
<segment bytes="391347" number="1">[email protected]</segment>
...
<segment bytes="247767" number="55">[email protected]</segment>
The highest number for this file is 55. So we guess we should have 55 Segments.
"""
max_number = 0
for segment in self.segments:
if int(segment.number) > max_number:
max_number = int(segment.number)
self.expected_segments = max_number
self.guessed_segments = True
def determine_expected_segments_message_id(self, skip_segment_debug):
"""Determine expected segments from message id
:param bool skip_segment_debug: Skip debug output for segment check - NZBKing removes Segment part from Header
If Upload was done by JBinDown or PowerPost it is possible to get the expected
segments from MessageID
"""
try:
counter = re.search(self.regexes['segments_jbin'], self.segments[0].message_id).groups()
except AttributeError:
counter = (0,)
if counter and len(counter) == 2:
self.expected_segments = int(counter[1])
if self.debug and not skip_segment_debug:
print(' Got expected segments from jBinDown MessageID.')
return
try:
counter = re.search(self.regexes['segments_powerpost'], self.segments[0].message_id).groups()
except AttributeError:
counter = (0,)
if counter and len(counter) == 2:
if self.debug and not skip_segment_debug:
print(' Got expected segments from PowerPost MessageID.')
self.expected_segments = int(counter[1])
return
if self.debug and not skip_segment_debug:
print(' Can\'t get expected segments from MessageID.')
print(' Try to get them from number attribute.')
self.guess_expected_segments()
def determine_expected_files_message_id(self):
"""Determine expected files from message id
If Upload was done by JBinUp, it is possible to get the expected
files from MessageID
"""
try:
counter = re.search(self.regexes['files_jbin'], self.segments[0].message_id).groups()
except AttributeError:
counter = (0,)
if counter and len(counter) == 2:
return int(counter[1])
return -1
class NZBParser(object):
"""Check NZB completion
1. Check filecount. Used the [1/10] part in Header to get the expected filecount.
If the uploader uses (1/10) instead of [1/10] as required in yEnc specs NZBindex is filtering this
and a filecount check is not possible. If the Segment Check is OK and the min age is exceeded
then the upload should be finished.
2. Check segments. Used the (1/255) part at the header end to get the expected Segment count.
For both checks is a limit until the nzb file is OK
---------
Based on pynzb by Eric Florenzano
Copyright (c) 2009, Eric Florenzano
All rights reserved.
http://github.com/ericflo/pynzb/
"""
def __init__(self, nzb_file, max_missing_files=2, max_missing_segments_percent=2.5, waiting_time=0.5, debug=False,
skip_segment_debug=False):
"""Initialize NZB Parser
:param str,byte nzb_file: nzb file
:param int max_missing_files: How many files may be missing
:param float max_missing_segments_percent: How many segments (in percentage) may be missing
:param float waiting_time: Waiting time after output
:param bool debug: Enable verbose output
:param bool skip_segment_debug: Skip debug output for segment check - NZBKing removes Segment part from Header
"""
try:
self.nzb = bytearray(nzb_file, encoding='utf-8')
except TypeError:
pass
# If a NZB download failed we receive sometimes malformed NZB Files or html.
if self.nzb.lower().find(b'does not exist') != -1 or self.nzb.lower().find(b'doctype html') != -1:
self.nzb_malformed = True
print(Col.WARN + ' Received no NZB from Indexer' + Col.OFF)
else:
self.nzb_malformed = False
self.files = list()
self.segments_total = 0
self.segments_missing = 0
self.segments_additional = 0
self.segments_missing_percent = -1.0
self.segments_expected_total = 0
self.files_total = 0
self.files_expected = -1
self.files_with_missing_segments = 0
self.files_with_too_many_segments = 0
self.files_with_unknown_segments = 0
self.files_checked = 0
self.files_missing = -1
self.files_min_upload_time = 0
self.files_max_upload_time = 0
self.files_upload_duration = 0
self.regexes = {
'file_count_subject_1': re.compile(r'.*?[(\[](\d{1,4})/(\d{1,4})[)\]].*?\((\d{1,4})/(\d{1,5})\)', re.I),
'file_count_subject_2': re.compile(r'.*?\[(\d{1,4})/(\d{1,5})\]', re.I),
'segment_count_subject': re.compile(r'.*?\((\d{1,4})/(\d{1,5})\)$', re.I)}
self.max_missing_files = int(max_missing_files)
self.max_missing_segments_percent = float(max_missing_segments_percent)
self.waiting_time = waiting_time
self.debug = debug
self.skip_segment_debug = skip_segment_debug
self.parse()
@staticmethod
def get_etree_iter(xml):
return iter(ET.iterparse(io.BytesIO(xml), events=('start', 'end')))
def get_files_missing(self):
"""Return missing files"""
return self.files_missing
def get_segments_missing_percent(self):
"""Return missing segments in percent"""
return self.segments_missing_percent
def get_upload_start_time(self):
"""Return upload start time in human readable values
:return str: Timestamp as YYYY-MM-DD HH:MM:SS if time stamp is available"""
if self.files_max_upload_time == 0:
self.determine_time_stamps()
if self.files_max_upload_time > 0:
return strftime('%Y-%m-%d', localtime(float(self.files_max_upload_time)))
else:
return 'Not available'
def get_upload_duration(self):
"""Return upload duration time in human readable values
:return str: Timestamp as [DD day(s)] HH:MM:SS if time stamp is available"""
if self.files_upload_duration == 0:
self.determine_time_stamps()
if self.files_upload_duration > 0:
return sec_to_time(self.files_upload_duration)
else:
return 'Not available'
def get_upload_age(self):
"""Return Upload age in human readable values
:return str: Upload age as [DD day(s)] HH:MM:SS if time stamp is available"""
if self.files_max_upload_time == 0:
self.determine_time_stamps()
if self.files_max_upload_time > 0:
return sec_to_time(int(time() - self.files_max_upload_time), days_only=True)
else:
return 'Not available'
def parse(self):
"""Parse NZB file"""
if self.nzb_malformed:
return
context = self.get_etree_iter(self.nzb)
current_file, current_segment = None, None
try:
for event, elem in context:
if event == 'start':
# If it's an NZBFile, create an object so that we can add the
# appropriate stuff to it.
if elem.tag == '{http://www.newzbin.com/DTD/2003/nzb}file':
current_file = NZBFile(
poster=elem.attrib['poster'],
date=elem.attrib['date'],
subject=elem.attrib['subject'],
debug=self.debug)
elif event == 'end':
if elem.tag == '{http://www.newzbin.com/DTD/2003/nzb}file':
self.files.append(current_file)
elif elem.tag == '{http://www.newzbin.com/DTD/2003/nzb}group':
current_file.add_group(elem.text)
elif elem.tag == '{http://www.newzbin.com/DTD/2003/nzb}segment':
current_file.add_segment(
NZBSegment(
bytes_=elem.attrib['bytes'],
number=elem.attrib['number'],
message_id=elem.text
)
)
# Clear the element, we don't need it any more.
elem.clear()
except Exception:
pass
def determine_expected_files(self, nzbfile):
"""Determine expected files
:param nzbfile: NZBFile Object
# Search subject for [file counter] (segment counter) or (file counter) (segment counter)
# [1/5] (1/235) or (1/5) (1/235)
"""
try:
counter = re.search(self.regexes['file_count_subject_1'], nzbfile.subject).groups()
except AttributeError:
counter = (0,)
# Regex matched
if counter and len(counter) == 4:
return int(counter[1])
# Found NZBs without segment counter
# Second regex searches only for file counter [1/5]
if self.debug and not self.skip_segment_debug:
print(' No segment counter in header - search now only for [x/y]')
try:
counter = re.search(self.regexes['file_count_subject_2'], nzbfile.subject).groups()
except AttributeError:
counter = (0,)
# Regex matched
if counter and len(counter) == 2:
return int(counter[1])
# NZBIndex removes filecount from Uploads with ($1/$2) filecount subject
# If uploaded by jBinUp, filecount is in messageID
counter = nzbfile.determine_expected_files_message_id()
if int(counter) > 0:
return int(counter)
return -1
def determine_expected_segments(self, nzbfile):
"""Determine expected segments
:param nzbfile: NZBFile Object
"""
try:
counter = re.search(self.regexes['segment_count_subject'], nzbfile.subject).groups()
except AttributeError:
counter = (0,)
# Regex matched
if counter and len(counter) == 2:
nzbfile.expected_segments = int(counter[1])
return
if self.debug and not self.skip_segment_debug:
print(
' No segment counter in header found. Check for jBinDown or Powerpost message id segment counter')
nzbfile.determine_expected_segments_message_id(self.skip_segment_debug)
return
def determine_expected_files_and_segments(self):
"""Parse file subjects to get expected file and segment count"""
if self.nzb_malformed:
return
for item in self.files:
# File count
filecount = self.determine_expected_files(item)
if self.files_expected == -1 and int(filecount) > 0:
self.files_expected = int(filecount)
# Some uploaders add additional files after download starts
# Use the highest file count
elif self.files_expected < int(filecount):
self.files_expected = int(filecount)
# Segment count
self.determine_expected_segments(item)
def determine_time_stamps(self):
"""Determine lowest and highest upload timestamp from files
self.files_max_upload_time is the oldest files
self.files_min_upload_time is the youngest file
"""
for item in self.files:
timestamp = int(item.date)
if timestamp > self.files_max_upload_time:
self.files_max_upload_time = timestamp
if self.files_min_upload_time > timestamp:
self.files_min_upload_time = timestamp
elif self.files_min_upload_time == 0:
self.files_min_upload_time = timestamp
if self.files_min_upload_time > 0 and self.files_max_upload_time > 0:
self.files_upload_duration = self.files_max_upload_time - self.files_min_upload_time
def check_completion(self):
"""Check files and segments for completion"""
# Clear counters
self.files_total = 0
self.files_expected = -1
self.files_with_missing_segments = 0
self.files_with_too_many_segments = 0
self.files_with_unknown_segments = 0
self.files_checked = 0
self.files_missing = -2
self.segments_total = 0
self.segments_missing = 0
self.segments_additional = 0
self.segments_expected_total = 0
self.segments_missing_percent = -1.0
if self.nzb_malformed:
return False, 1
print(' - Check NZB (Max. {0} missing files - Max. {1}% missing Segments)'
.format(self.max_missing_files, self.max_missing_segments_percent))
# Update counters
if self.debug:
print(' Update counter ... ')
self.files_total = len(self.files)
self.determine_expected_files_and_segments()
self.determine_time_stamps()
file_check_ok = False
segment_check_ok = False
segments_guessed = False
# Check files
print(' Check file count ... ', end='', flush=True)
if self.files_expected > -1:
self.files_missing = self.files_expected - self.files_total
# There is one extra file e.g. a nzb file as file number 000 - [000/xxx] "yyy.nzb"
if self.files_missing == -1:
self.files_missing = 0
self.files_expected += 1
if self.debug:
print(Col.WARN + 'One extra file ' + Col.OFF, end='', flush=True)
# To many missing files
if not self.files_total >= self.files_expected - self.max_missing_files:
print(Col.FAIL + 'Failed - Only {0} from {1} files'
.format(self.files_total, self.files_expected) + Col.OFF)
print_and_wait(Col.FAIL + ' Skip Segment check' + Col.OFF, self.waiting_time)
return False, 2
# More files than expected
elif self.files_missing < 0:
print(Col.WARN + 'More files than expected - {0} from {1} files'
.format(self.files_total, self.files_expected) + Col.OFF)
# Filecount is OK
else:
print(Col.OK + 'OK - {0} from {1} files'
.format(self.files_total, self.files_expected) + Col.OFF)
file_check_ok = True
else:
self.files_missing = self.files_total
print(Col.WARN + 'Skip - No information found' + Col.OFF)
# Check Segments for each file
print(' Check segments ...')
for item_count, item in enumerate(self.files, start=1):
segments = item.get_segment_count()
segments_missing = item.get_missing_segments()
if segments_missing is None:
self.files_with_unknown_segments += 1
elif segments_missing == 0:
self.files_checked += 1
elif segments_missing > 0:
self.segments_missing += segments_missing
self.files_with_missing_segments += 1
self.files_checked += 1
elif segments_missing < 0:
self.segments_additional += -segments_missing
self.files_with_too_many_segments += 1
self.files_checked += 1
if item.get_expected_segments():
self.segments_expected_total += item.get_expected_segments()
# Because we guessed the expected segments we depreciate the check
if item.guessed_segments:
segments_guessed = True
if self.segments_missing == 0:
self.segments_missing = 1
self.segments_total += 1
self.segments_total += segments
# Results
if self.files_with_unknown_segments > 0:
print(' Files with unknown segment count: ', end='', flush=True)
print(Col.WARN + '{0}'.format(self.files_with_unknown_segments) + Col.OFF)
if self.files_with_missing_segments > 0:
print(' Files with missing segments: ', end='', flush=True)
print(Col.WARN + '{0}'.format(self.files_with_missing_segments) + Col.OFF)
if self.files_with_too_many_segments > 0:
print(' Files with too many segments: ', end='', flush=True)
print(Col.WARN + '{0}'.format(self.files_with_too_many_segments) + Col.OFF)
if self.debug:
print(' Total Segments: {:6d}'.format(self.segments_total))
print(' Expected Segments: {:6d}'.format(self.segments_expected_total))
print(' Missing Segments: {:6d}'.format(self.segments_missing))
print(' Additional Segments: {:6d}'.format(self.segments_additional))
# Check if missing segments are in OK range
if self.segments_missing > 0:
missing_percent = float(self.segments_missing) / (float(self.segments_expected_total) / 100)
self.segments_missing_percent = missing_percent
if missing_percent > self.max_missing_segments_percent:
print_and_wait(Col.FAIL + ' Failed - Too many missing Segments: {0} = {1:.3f}%'
.format(self.segments_missing, missing_percent) + Col.OFF, self.waiting_time)
return False, 3
else:
print(Col.WARN + ' Warning - missing Segments: {0} = {1:.3f}%\n'
.format(self.segments_missing, missing_percent) + Col.OFF)
segment_check_ok = True
if file_check_ok and self.files_with_missing_segments == 0 and self.files_with_too_many_segments == 0 \
and self.files_with_unknown_segments == 0 and not segments_guessed:
self.segments_missing_percent = 0.0
print(Col.OK + ' OK - {0} from {1} segments\n'
.format(self.segments_total, self.segments_expected_total) + Col.OFF)
print(' Overall result: ', end='', flush=True)
print_and_wait(Col.OK + 'OK - All {0} files are complete'.format(self.files_checked) + Col.OFF,
self.waiting_time)
return True, 1
print(' Overall result: ', end='', flush=True)
# File count and Segment count are OK and no files with unknown segment count
if file_check_ok and segment_check_ok and self.files_with_unknown_segments == 0 and not segments_guessed:
print_and_wait(Col.OK + 'OK - File check: OK - Segment check: OK' + Col.OFF, self.waiting_time)
return True, 2
# File count OK. Segment check is OK, but we had to guess the expected segment count
if file_check_ok and segment_check_ok and segments_guessed:
print_and_wait(Col.WARN + 'Warning - ' + Col.OK + 'File check: OK - ' + Col.WARN
+ 'Segment check is OK, but we used a unreliable source' + Col.OFF, self.waiting_time)
return True, 3
# No check possible for file count.
# Segment check was done for more than 1 file with no missing segments or check was in OK range and
# no files without segment count
if self.files_checked > 0 and (
self.segments_missing == 0 or segment_check_ok) and self.files_with_unknown_segments == 0:
print_and_wait(Col.OK + 'OK - File count is unknown - Segment check is OK' + Col.OFF, self.waiting_time)
return True, 4
# No check possible for file count and segment count
# Segment check was done for more than 1 file and was in OK range
if self.files_checked > 0 and (self.segments_missing == 0 or segment_check_ok):
print(Col.WARN + 'Warning - File count is unknown - Segment count is unknown' + Col.OFF)
print_and_wait(Col.WARN + ' The odds are good that the download will be successful' + Col.OFF,
self.waiting_time)
return True, 5
self.segments_missing_percent = 100.0
print_and_wait(Col.FAIL + 'Skip - No information found' + Col.OFF, self.waiting_time)
return False, 4
# endregion
# region NZB-Download
class NZBDownload(object):
"""Search for NZB on one and download. Return NZB content if download was successful.
:param str search_url: Search URL
:param str regex: Regex to find NZB download data
:param download_url: Download URL
:param search_header: Header to search for
:param debug: Verbose output
:return bool, str: Status, NZB Content
"""
def __init__(self, search_url, regex, download_url, search_header, debug=False):
"""Initialize NZB Downloader"""
self.search_url = search_url
self.regex = regex
self.download_url = download_url
self.header = search_header
self.debug = debug
self.nzb_url = ''
self.nzb = ''
def search_nzb_url(self):
"""Search for NZB Download URL and return the URL
:return bool, str: """
try:
self.header = self.header.replace('_', ' ')
res = requests.get(self.search_url.format(quote(self.header, encoding='utf-8')),
timeout=REQUESTS_TIMEOUT, headers={'Cookie': 'agreed=true'}, verify=False)
except requests.exceptions.Timeout:
print(Col.WARN + ' Timeout' + Col.OFF, flush=True)
return False, None
except requests.exceptions.ConnectionError:
print(Col.WARN + ' Connection Error' + Col.OFF, flush=True)
return False, None
m = re.search(self.regex, res.text, re.DOTALL)
if m is None:
print(Col.WARN + ' NOT FOUND' + Col.OFF, flush=True)
return False, None
self.nzb_url = self.download_url.format(**m.groupdict())
return True, self.nzb_url
def download_nzb(self):
"""Download NZB and return the NZB content
:returns bool, str:"""
if not self.nzb_url:
res, _ = self.search_nzb_url()
if not res:
return False, None
try:
urlparam = self.nzb_url.split('\t')
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
if len(urlparam) > 1:
res = requests.post(urlparam[0], data=urlparam[1], headers=headers, timeout=REQUESTS_TIMEOUT,
verify=False)
else:
res = requests.get(self.nzb_url, timeout=REQUESTS_TIMEOUT, verify=False)
except requests.exceptions.Timeout:
print(Col.WARN + ' Timeout' + Col.OFF, flush=True)
return False, None
except requests.exceptions.ConnectionError:
print(Col.WARN + ' Connection Error' + Col.OFF, flush=True)
return False, None
if res.status_code != 200:
print(Col.WARN + ' NOT FOUND' + Col.OFF, flush=True)
return False, None
print(Col.OK + ' DONE' + Col.OFF)
self.nzb = res.text
return True, self.nzb
def search_nzb(header, password, search_engines, best_nzb, max_missing_files, max_missing_segments_percent,
skip_failed=True, debug=False):
"""Search for NZB file on several search engines and returns a NZB if successful
:param str header: Header to search for
:param str password: NZB password
:param dict search_engines: List with search engines and their priority
:param bool best_nzb: Search for best incomplete NZB if no complete NZB available
:param int max_missing_files: How many missing files until NZB file check failed
:param int max_missing_segments_percent: How many missing segments (in percent) until NZB segment check failed
:param bool skip_failed: Skip download for failed NZB files
:param bool debug: Enable verbose output
:returns int, str, str: Return code, NZB content, search engine name. Return code 0 is OK, return code > 0 is NOK
"""
print(' - Searching NZB{}'.format(' - Search for best NZB enabled' if best_nzb else ''))
search_defs = {
'binsearch':
{
'name': 'BinSearch',
'searchUrl': 'https://binsearch.info/?q={0}',
'regex': r'href="/details/(?P<id>[^"]+)"',
'downloadUrl': 'https://binsearch.info/nzb?{id}=on',
'skip_segment_debug': False
},
'nzbking':
{
'name': 'NZBKing',
'searchUrl': 'https://www.nzbking.com/search/?q={0}',
'regex': r'href="/nzb:(?P<id>.*?)/".*"',
'downloadUrl': 'https://www.nzbking.com/nzb:{id}/',
'skip_segment_debug': True
},
'nzbindex':
{
'name': 'NZBIndex',
'searchUrl': 'https://nzbindex.com/search/rss?q={0}&hidespam=1&sort=agedesc&complete=1',
'regex': r'<link>https:\/\/nzbindex\.com\/download\/(?P<id>\d+)\/?<\/link>',
'downloadUrl': 'https://nzbindex.com/download/{id}/',
'skip_segment_debug': False
}
}
downloaded_nzbs = list()
active_search_engines = dict()
for engine in search_engines:
if engine not in search_defs:
print(' with {}{} is no valid value for search engines{}'.format(engine, Col.FAIL, Col.OFF))
continue
priority = int(search_engines[engine])
if priority == 0:
print(' with {} ... {}Disabled{}'.format(search_defs[engine]['name'], Col.OK, Col.OFF))
continue
if priority < 0 or priority > 9:
print(' with {} ... {}Only values between 0-9 allowed!{}'.format(search_defs[engine]['name'], Col.FAIL,
Col.OFF))
continue
if priority not in active_search_engines:
active_search_engines[priority] = list()
active_search_engines[priority].append(engine)
found_complete_nzb = False
for prio in sorted(active_search_engines):
for engine in active_search_engines[prio]:
if found_complete_nzb:
continue
print(' with {} ...'.format(search_defs[engine]['name']), end='', flush=True)
result, nzb = NZBDownload(search_defs[engine]['searchUrl'],
search_defs[engine]['regex'],
search_defs[engine]['downloadUrl'],
header).download_nzb()
if not result:
continue
nzb_check = NZBParser(nzb,
max_missing_files,
max_missing_segments_percent,
WAITING_TIME_SHORT if best_nzb else WAITING_TIME_LONG,
debug,
search_defs[engine]['skip_segment_debug'])
nzb_complete, _ = nzb_check.check_completion()
tmp_nzb = [search_defs[engine]['name'],
nzb,
nzb_check.get_files_missing(),
nzb_check.get_segments_missing_percent(),
nzb_complete,
nzb_check.get_upload_start_time(),
nzb_check.get_upload_duration(),
nzb_check.get_upload_age()]
# NZB is complete
if nzb_complete:
tmp_nzb.append(True)
downloaded_nzbs.append(tmp_nzb)
# Stop downloading more NZB files
if not best_nzb or (tmp_nzb[2] == 0 and tmp_nzb[3] == 0.0):
found_complete_nzb = True
# NZB not complete. Add NZB if no complete NZB until now and we allow incomplete NZBs
elif not downloaded_nzbs and not skip_failed:
tmp_nzb.append(False)
downloaded_nzbs.append(tmp_nzb)
# No NZB download
if not downloaded_nzbs:
print(Col.FAIL + '\nNo NZB downloaded!\n' + Col.OFF, flush=True)
return 2, '', ''
res_best_nzb = get_best_nzb(downloaded_nzbs)
nzb = res_best_nzb[1]
if res_best_nzb:
print('\n use NZB from {}'.format(res_best_nzb[0]), flush=True)
print(' Upload age: {}'.format(res_best_nzb[7]))
if debug:
print(' Upload started: {}'.format(res_best_nzb[5]))
print(' Upload duration: {}'.format(res_best_nzb[6]))
# Output warning if we push a failed NZB
if not res_best_nzb[4]:
print(Col.FAIL + '\n You use a NZB with a failed completion test!\n' + Col.OFF, flush=True)
sleep(WAITING_TIME_LONG)
# inject password into nzb file, see: http://wiki.sabnzbd.org/nzb-specs
if password is not None and nzb.find('<head>') < 0:
# Check for illegal characters in xml &, <, >, " and '
if re.search('[&"\'<>]', password) is not None:
print(Col.WARN + ' - Can\'t inject password in NZB file, forbidden characters included.' + Col.OFF)
else:
nzb = nzb.replace('</nzb>', '<head><meta type="password">%s</meta></head></nzb>' % password)
return 0, nzb, res_best_nzb[0]
def get_best_nzb(nzb_downloads):
"""Sort the NZB to return the first complete or best incomplete NZB
:param nzb_downloads: NZB downloads
:returns: list with values from best NZB
"""
# Only one NZB file
if len(nzb_downloads) == 1:
return nzb_downloads[0]
sorted_nzb = sorted(nzb_downloads, key=operator.itemgetter(2, 3))
return sorted_nzb[0]
# endregion
# region Misc Tools
def clean_nzb_folder(source_path, max_age=2):
"""Delete NZB files older than max_days and returns nu,ber of deleted files
:param source_path: Folder to search for NZB files
:param max_age: Max NZB file age
:returns: number of deleted files
"""
if not os.path.exists(source_path):
return -1
current_time = time()
try:
files = list()
file_list = glob(os.path.join(source_path, '*.nzb'))
for f in file_list:
if not os.path.isfile(f):
continue
modification_time = os.path.getmtime(f)
if (current_time - modification_time) // (24 * 3600) >= int(max_age):
files.append(f)
for f in files:
os.remove(f)
return len(files)
except OSError as e:
print(Col.FAIL + ' OSError: {}'.format(e) + Col.OFF)
return -1
def check_folder(path):
""" Check if path exists. If not create it. Returns a boolean status
:param str path: Folder path to check
:returns bool: Returns True if folder exists or successful created otherwise False
"""
result = False
if Path(path).exists():
return True
try:
Path(path).mkdir(parents=True)
result = True
except OSError:
return result
return result
def print_and_wait(text, wait_time):
"""Print String and wait
:param str text: string to print
:param wait_time: Waiting time after print
:type text: str
:type wait_time: float, int
"""
print(text)
sleep(float(wait_time))
class Writers(object):
"""Writer class for redirecting output for stderr and stdout
:Example:
logfile = open('logfile.log', 'a')
sys.stdout = Writers(sys.stdout, logfile)
sys.stderr = Writers(sys.stderr, logfile)"""
def __init__(self, *writers):
self.writers = writers
self.ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]')
def write(self, string):
for w in self.writers:
w.write(self.escape_ansi(string))
def flush(self):
for w in self.writers:
w.flush()
def escape_ansi(self, string):
return self.ansi_escape.sub('', string[:])
def debug_output_open(file_name, debug, message=''):
"""Enable Debug output
:param str file_name: Path for a logfile
:param bool debug: Enable debug output if True
:param str message: A message to inform user that debug output is enabled
:return file: return a file handler
"""
if debug:
logfile = open(file_name, 'a')
sys.stdout = Writers(sys.stdout, logfile)
sys.stderr = Writers(sys.stderr, logfile)
sys.stderr.write(message)
return logfile
return None
def debug_output_close(file_handler, debug):
"""Disable debug output and set back stdout and stderr
:param file file_handler: file handler to close
:param debug: Close only if debug is enabled
"""
if debug:
sys.stdout.flush()
sys.stderr.flush()
sys.stdout = SAVE_STDOUT
sys.stderr = SAVE_STDERR
file_handler.close()