/
nzbstuff.py
2174 lines (1864 loc) · 81.4 KB
/
nzbstuff.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/python3 -OO
# Copyright 2007-2023 The SABnzbd-Team <team@sabnzbd.org>
#
# 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 2
# of the License, or (at your option) 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
sabnzbd.nzbstuff - misc
"""
import os
import time
import re
import logging
import datetime
import threading
import functools
import difflib
from typing import List, Dict, Any, Tuple, Optional, Union, BinaryIO
# SABnzbd modules
import sabnzbd
import sabctools
from sabnzbd.constants import (
GIGI,
ATTRIB_FILE,
JOB_ADMIN,
REPAIR_PRIORITY,
FORCE_PRIORITY,
HIGH_PRIORITY,
NORMAL_PRIORITY,
LOW_PRIORITY,
DEFAULT_PRIORITY,
PAUSED_PRIORITY,
DUP_PRIORITY,
STOP_PRIORITY,
RENAMES_FILE,
MAX_BAD_ARTICLES,
Status,
)
from sabnzbd.misc import (
to_units,
cat_to_opts,
cat_convert,
int_conv,
format_time_string,
calc_age,
cmp,
caller_name,
opts_to_pp,
pp_to_opts,
)
from sabnzbd.filesystem import (
sanitize_foldername,
get_unique_dir,
get_admin_path,
remove_all,
sanitize_filename,
set_permissions,
long_path,
fix_unix_encoding,
get_ext,
get_filename,
get_unique_filename,
renamer,
remove_file,
make_script_path,
globber,
is_valid_script,
has_unwanted_extension,
create_all_dirs,
)
from sabnzbd.par2file import FilePar2Info
from sabnzbd.decorators import synchronized
import sabnzbd.config as config
import sabnzbd.cfg as cfg
import sabnzbd.nzbparser
from sabnzbd.downloader import Server
from sabnzbd.database import HistoryDB
from sabnzbd.deobfuscate_filenames import is_probably_obfuscated
# Name patterns
# In the subject, we expect the filename within double quotes
RE_SUBJECT_FILENAME_QUOTES = re.compile(r'"([^"]*)"')
# Otherwise something that looks like a filename
RE_SUBJECT_BASIC_FILENAME = re.compile(r"([\w\-+()'\s.,]+\.[A-Za-z0-9]{2,4})[^A-Za-z0-9]")
RE_RAR = re.compile(r"(\.rar|\.r\d\d|\.s\d\d|\.t\d\d|\.u\d\d|\.v\d\d)$", re.I)
##############################################################################
# Trylist
##############################################################################
TRYLIST_LOCK = threading.Lock()
class TryList:
"""TryList keeps track of which servers have been tried for a specific article"""
# Pre-define attributes to save memory
__slots__ = ("try_list",)
def __init__(self):
self.try_list: List[Server] = []
def server_in_try_list(self, server: Server) -> bool:
"""Return whether specified server has been tried"""
with TRYLIST_LOCK:
return server in self.try_list
def all_servers_in_try_list(self, servers: List[Server]) -> bool:
"""Check if all servers have been tried"""
with TRYLIST_LOCK:
for server in servers:
if not server in self.try_list:
return False
return True
def add_to_try_list(self, server: Server):
"""Register server as having been tried already"""
with TRYLIST_LOCK:
if server not in self.try_list:
self.try_list.append(server)
def remove_from_try_list(self, server: Server):
"""Remove server from list of tried servers"""
with TRYLIST_LOCK:
if server in self.try_list:
self.try_list.remove(server)
def reset_try_list(self):
"""Clean the list"""
with TRYLIST_LOCK:
self.try_list = []
def __getstate__(self):
"""Save the servers"""
return [server.id for server in self.try_list]
def __setstate__(self, servers_ids: List[str]):
self.try_list = []
for server in sabnzbd.Downloader.servers:
if server.id in servers_ids:
self.add_to_try_list(server)
##############################################################################
# Article
##############################################################################
ArticleSaver = (
"article",
"art_id",
"bytes",
"lowest_partnum",
"decoded",
"file_size",
"data_begin",
"data_size",
"on_disk",
"nzf",
"crc32",
)
class Article(TryList):
"""Representation of one article"""
# Pre-define attributes to save memory
__slots__ = ArticleSaver + ("fetcher", "fetcher_priority", "tries")
def __init__(self, article, article_bytes, nzf):
super().__init__()
self.article: str = article
self.art_id: Optional[str] = None
self.bytes: int = article_bytes
self.lowest_partnum: bool = False
self.fetcher: Optional[Server] = None
self.fetcher_priority: int = 0
self.tries: int = 0 # Try count
self.decoded: bool = False
self.file_size: Optional[int] = None
self.data_begin: Optional[int] = None
self.data_size: Optional[int] = None
self.on_disk: bool = False
self.crc32: Optional[int] = None
self.nzf: NzbFile = nzf
def reset_try_list(self):
"""In addition to resetting the try list, also reset fetcher so all servers are tried again"""
self.fetcher = None
self.fetcher_priority = 0
super().reset_try_list()
def get_article(self, server: Server, servers: List[Server]):
"""Return article when appropriate for specified server"""
if self.fetcher or self.server_in_try_list(server):
return None
if server.priority > self.fetcher_priority:
# Check for higher priority server, taking advantage of servers list being sorted by priority
for server_check in servers:
if server_check.priority < server.priority:
if server_check.active and not self.server_in_try_list(server_check):
# There is a higher priority server, so set article priority and return
self.fetcher_priority = server_check.priority
return None
else:
# All servers with a higher priority have been checked
break
# If no higher priority servers, use this server
self.fetcher_priority = server.priority
self.fetcher = server
self.tries += 1
return self
def get_art_id(self):
"""Return unique article storage name, create if needed"""
if not self.art_id:
self.art_id = sabnzbd.filesystem.get_new_id("article", self.nzf.nzo.admin_path)
return self.art_id
def search_new_server(self):
"""Search for a new server for this article"""
# Since we need a new server, this one can be listed as failed
sabnzbd.BPSMeter.register_server_article_failed(self.fetcher.id)
self.add_to_try_list(self.fetcher)
# Servers-list could be modified during iteration, so we need a copy
for server in sabnzbd.Downloader.servers[:]:
if server.active and not self.server_in_try_list(server):
if server.priority >= self.fetcher.priority:
self.tries = 0
# Allow all servers for this nzo and nzf again (but not this fetcher for this article)
sabnzbd.NzbQueue.reset_try_lists(self, remove_fetcher_from_trylist=False)
return True
logging.info("Article %s unavailable on all servers, discarding", self.article)
return False
def __getstate__(self):
"""Save to pickle file, selecting attributes"""
dict_ = {}
for item in ArticleSaver:
dict_[item] = getattr(self, item)
dict_["try_list"] = super().__getstate__()
return dict_
def __setstate__(self, dict_):
"""Load from pickle file, selecting attributes"""
for item in ArticleSaver:
try:
setattr(self, item, dict_[item])
except KeyError:
# Handle new attributes
setattr(self, item, None)
super().__setstate__(dict_.get("try_list", []))
self.fetcher = None
self.fetcher_priority = 0
self.tries = 0
def __eq__(self, other):
"""Articles with the same usenet address are the same"""
return self.article == other.article
def __hash__(self):
"""Required because we implement eq. Articles with the same
usenet address can appear in different NZF's. So we make every
article object unique, even though it is bad practice.
"""
return id(self)
def __repr__(self):
return "<Article: article=%s, bytes=%s, art_id=%s>" % (self.article, self.bytes, self.art_id)
##############################################################################
# NzbFile
##############################################################################
NzbFileSaver = (
"date",
"filename",
"filename_checked",
"filepath",
"type",
"is_par2",
"vol",
"blocks",
"setname",
"articles",
"decodetable",
"bytes",
"bytes_left",
"nzo",
"nzf_id",
"deleted",
"valid",
"import_finished",
"crc32",
"assembled",
"md5of16k",
)
class NzbFile(TryList):
"""Representation of one file consisting of multiple articles"""
# Pre-define attributes to save memory
__slots__ = NzbFileSaver + ("first_article",)
def __init__(self, date, subject, raw_article_db, file_bytes, nzo):
"""Setup object"""
super().__init__()
self.date: datetime.datetime = date
self.type: Optional[str] = None
self.filename: str = sanitize_filename(name_extractor(subject))
self.filename_checked = False
self.filepath: Optional[str] = None
# Identifiers for par2 files
self.is_par2: bool = False
self.vol: Optional[int] = None
self.blocks: Optional[int] = None
self.setname: Optional[str] = None
# Articles are removed from "articles" after being fetched
self.articles: List[Article] = []
self.decodetable: List[Article] = []
self.bytes: int = file_bytes
self.bytes_left: int = file_bytes
self.nzo: NzbObject = nzo
self.nzf_id: str = sabnzbd.filesystem.get_new_id("nzf", nzo.admin_path)
self.deleted = False
self.import_finished = False
self.crc32: Optional[int] = 0
self.assembled: bool = False
self.md5of16k: Optional[bytes] = None
self.valid: bool = bool(raw_article_db)
# Temporarily hold the first article during import
self.first_article: Optional[Article] = None
if self.valid and self.nzf_id:
# Save first article separate, so we can deobfuscate-during-download
# We process the first_file in nzo.add_nzf because if this NZF turns
# out to be a duplicate file inside the NZB, the first article would
# otherwise become a ghost article.
self.first_article = self.add_article(raw_article_db.pop(0))
self.first_article.lowest_partnum = True
# Any articles left?
if raw_article_db:
# Save the rest
sabnzbd.filesystem.save_data(raw_article_db, self.nzf_id, nzo.admin_path)
else:
# All imported
self.import_finished = True
def finish_import(self):
"""Load the article objects from disk"""
logging.debug("Finishing import on %s", self.filename)
raw_article_db = sabnzbd.filesystem.load_data(self.nzf_id, self.nzo.admin_path, remove=False)
if raw_article_db:
# Convert 2.x.x jobs
if isinstance(raw_article_db, dict):
raw_article_db = [raw_article_db[partnum] for partnum in sorted(raw_article_db)]
for raw_article in raw_article_db:
self.add_article(raw_article)
# Make sure we have labeled the lowest part number
# Also when DirectUnpack is disabled we need to know
self.decodetable[0].lowest_partnum = True
# Mark safe to continue
self.import_finished = True
def add_article(self, article_info):
"""Add article to object database and return article object"""
article = Article(article_info[0], article_info[1], self)
self.articles.append(article)
self.decodetable.append(article)
return article
def remove_article(self, article: Article, success: bool) -> int:
"""Handle completed article, possibly end of file"""
if article in self.articles:
self.articles.remove(article)
if success:
self.bytes_left -= article.bytes
return len(self.articles)
def set_par2(self, setname, vol, blocks):
"""Designate this this file as a par2 file"""
self.is_par2 = True
self.setname = setname
self.vol = vol
self.blocks = int_conv(blocks)
def update_crc32(self, crc32: Optional[int], length: int) -> None:
if self.crc32 is None or crc32 is None:
self.crc32 = None
else:
self.crc32 = sabctools.crc32_combine(self.crc32, crc32, length)
def get_articles(self, server: Server, servers: List[Server], fetch_limit: int) -> List[Article]:
"""Get next articles to be downloaded"""
articles = []
for article in self.articles:
article = article.get_article(server, servers)
if article:
articles.append(article)
if len(articles) >= fetch_limit:
return articles
self.add_to_try_list(server)
return articles
def reset_all_try_lists(self):
"""Clear all lists of visited servers"""
for art in self.articles:
art.reset_try_list()
self.reset_try_list()
def prepare_filepath(self):
"""Do all checks before making the final path"""
if not self.filepath:
self.nzo.verify_nzf_filename(self)
filename = sanitize_filename(self.filename)
self.filepath = get_unique_filename(os.path.join(self.nzo.download_path, filename))
self.filename = get_filename(self.filepath)
return self.filepath
@property
def completed(self):
"""Is this file completed?"""
return self.import_finished and not bool(self.articles)
def remove_admin(self):
"""Remove article database from disk (sabnzbd_nzf_<id>)"""
try:
logging.debug("Removing article database for %s", self.nzf_id)
remove_file(os.path.join(self.nzo.admin_path, self.nzf_id))
except:
pass
def __getstate__(self):
"""Save to pickle file, selecting attributes"""
dict_ = {}
for item in NzbFileSaver:
dict_[item] = getattr(self, item)
dict_["try_list"] = super().__getstate__()
return dict_
def __setstate__(self, dict_):
"""Load from pickle file, selecting attributes"""
for item in NzbFileSaver:
try:
setattr(self, item, dict_[item])
except KeyError:
# Handle new attributes
setattr(self, item, None)
super().__setstate__(dict_.get("try_list", []))
# Convert 2.x.x jobs
if isinstance(self.decodetable, dict):
self.decodetable = [self.decodetable[partnum] for partnum in sorted(self.decodetable)]
def __eq__(self, other: "NzbFile"):
"""Assume it's the same file if the number bytes and first article
are the same or if there are no articles left, use the filenames.
Some NZB's are just a mess and report different sizes for the same article.
"""
if other and (self.bytes == other.bytes or len(self.decodetable) == len(other.decodetable)):
if self.decodetable and other.decodetable:
return self.decodetable[0] == other.decodetable[0]
# Fallback to filename comparison
return self.filename == other.filename
return False
def __hash__(self):
"""Required because we implement eq. The same file can be spread
over multiple NZO's so we make every NZF unique. Even though
it's considered bad practice.
"""
return id(self)
def __repr__(self):
return "<NzbFile: filename=%s, bytes=%s, nzf_id=%s>" % (self.filename, self.bytes, self.nzf_id)
##############################################################################
# NzbObject
##############################################################################
class NzbEmpty(Exception):
pass
class NzbRejected(Exception):
pass
class NzbRejectedToHistory(Exception):
def __init__(self, nzo_id: str):
self.nzo_id = nzo_id
super().__init__()
NzbObjectSaver = (
"filename",
"work_name",
"final_name",
"bytes",
"bytes_downloaded",
"bytes_tried",
"bytes_missing",
"bytes_par2",
"repair",
"unpack",
"delete",
"script",
"cat",
"url",
"groups",
"avg_date",
"md5of16k",
"extrapars",
"md5packs",
"par2packs",
"files",
"files_table",
"finished_files",
"status",
"avg_bps_freq",
"avg_bps_total",
"priority",
"saved_articles",
"nzo_id",
"futuretype",
"removed_from_queue",
"action_line",
"unpack_info",
"fail_msg",
"nzo_info",
"custom_name",
"password",
"correct_password",
"next_save",
"save_timeout",
"encrypted",
"bad_articles",
"duplicate",
"oversized",
"precheck",
"incomplete",
"reuse",
"meta",
"first_articles",
"first_articles_count",
"md5sum",
"download_path",
"servercount",
"unwanted_ext",
"renames",
)
NzoAttributeSaver = ("cat", "pp", "script", "priority", "final_name", "password", "url")
# Lock to prevent errors when saving the NZO data
NZO_LOCK = threading.RLock()
class NzbObject(TryList):
def __init__(
self,
filename: str,
pp: Optional[int] = None,
script: Optional[str] = None,
nzb_fp: Optional[BinaryIO] = None,
futuretype: bool = False,
cat: Optional[str] = None,
url: Optional[str] = None,
priority: Optional[Union[int, str]] = DEFAULT_PRIORITY,
nzbname: Optional[str] = None,
status: str = Status.QUEUED,
nzo_info: Optional[Dict[str, Any]] = None,
reuse: Optional[str] = None,
nzo_id: Optional[str] = None,
dup_check: bool = True,
):
super().__init__()
self.filename = filename # Original filename
if nzbname and nzb_fp:
self.work_name = nzbname # Use nzbname if set and only for non-future slot
else:
self.work_name = filename
# For future-slots we keep the name given by URLGrabber
if nzb_fp is None:
self.final_name = self.work_name = filename
else:
# Remove trailing .nzb and .par(2)
self.work_name = create_work_name(self.work_name)
# Extract password
self.work_name, self.password = scan_password(self.work_name)
if not self.work_name:
# In case only /password was entered for nzbname
self.work_name = filename
self.final_name = self.work_name
# Check for password also in filename
if not self.password:
_, self.password = scan_password(os.path.splitext(filename)[0])
# Create a record of the input for pp, script, and priority
input_pp = pp
input_script = script
input_priority = priority if priority != DEFAULT_PRIORITY else None
# Determine category and find pp/script values based on input
# Later will be re-evaluated based on import steps
if pp is None:
r = u = d = None
else:
r, u, d = pp_to_opts(pp)
self.priority: int = NORMAL_PRIORITY
self.set_priority(priority) # Parse priority of input
self.repair: bool = r # True if we want to repair this set
self.unpack: bool = u # True if we want to unpack this set
self.delete: bool = d # True if we want to delete this set
self.cat = cat # User-set category
self.script: Optional[str] = None # External script for this set
if is_valid_script(script):
self.script = script
# Information fields
self.url = url
self.groups = []
self.avg_date = datetime.datetime(1970, 1, 1, 1, 0)
self.avg_stamp = 0.0 # Avg age in seconds (calculated from avg_age)
self.correct_password: Optional[str] = None
# Bookkeeping values
self.meta = {}
self.servercount: Dict[str, int] = {} # Dict to keep bytes per server
self.direct_unpacker: Optional[sabnzbd.directunpacker.DirectUnpacker] = None # The DirectUnpacker instance
self.bytes: int = 0 # Original bytesize
self.bytes_par2: int = 0 # Bytes available for repair
self.bytes_downloaded: int = 0 # Downloaded byte
self.bytes_tried: int = 0 # Which bytes did we try
self.bytes_missing: int = 0 # Bytes missing
self.bad_articles: int = 0 # How many bad (non-recoverable) articles
self.extrapars: Dict[str, List[NzbFile]] = {} # Holds the extra parfile names for all sets
self.md5packs = {} # TODO: Remove in 4.0.0. Kept for backwards compatibility
self.par2packs: Dict[str, Dict[str, FilePar2Info]] = {} # Holds the par2info for each file in each set
self.md5of16k: Dict[bytes, str] = {} # Holds the md5s of the first-16k of all files in the NZB (hash: name)
self.files: List[NzbFile] = [] # List of all NZFs
self.files_table: Dict[str, NzbFile] = {} # Dictionary of NZFs indexed using NZF_ID
self.renames: Dict[str, str] = {} # Dictionary of all renamed files
self.finished_files: List[NzbFile] = [] # List of all finished NZFs
# The current status of the nzo eg:
# Queued, Downloading, Repairing, Unpacking, Failed, Complete
self.status: str = status
self.avg_bps_freq = 0
self.avg_bps_total = 0
self.first_articles: List[Article] = []
self.first_articles_count = 0
self.saved_articles: List[Article] = []
self.nzo_id: Optional[str] = None
self.futuretype = futuretype
self.removed_from_queue = False
self.to_be_removed = False
self.duplicate = False
self.oversized = False
self.precheck = False
self.incomplete = False
self.unwanted_ext = 0
self.reuse = reuse
if self.status == Status.QUEUED and not reuse:
self.precheck = cfg.pre_check()
if self.precheck:
self.status = Status.CHECKING
# Store one line responses for filejoin/par2/unrar/unzip here for history display
self.action_line = ""
# Store the results from various filejoin/par2/unrar/unzip stages
self.unpack_info: Dict[str, List[str]] = {}
# Stores one line containing the last failure
self.fail_msg = ""
# Stores various info about the nzo to be
self.nzo_info: Dict[str, Any] = nzo_info or {}
# Temporary store for custom foldername - needs to be stored because of url fetching
self.custom_name = nzbname
self.next_save = None
self.save_timeout = None
self.encrypted = 0
self.url_wait: Optional[float] = None
self.url_tries = 0
self.pp_active = False
self.md5sum: Optional[str] = None
# Path is empty in case of a future NZB
self.download_path = ""
if nzb_fp is None and not reuse:
# This is a slot for a future NZB, ready now
# It can also be a retry of a failed job with no extra NZB-file
return
# Re-use existing nzo_id, when a "future" job gets it payload
if nzo_id:
self.nzo_id = nzo_id
sabnzbd.NzbQueue.remove(nzo_id, delete_all_data=False)
# To be updated later if it's a duplicate
duplicate = series_duplicate = False
# Apply conversion option to final folder
if cfg.replace_spaces():
logging.info("Replacing spaces with underscores in %s", self.final_name)
self.final_name = self.final_name.replace(" ", "_")
if cfg.replace_underscores():
logging.info("Replacing underscores with dots in %s", self.final_name)
self.final_name = self.final_name.replace("_", ".")
if cfg.replace_dots():
logging.info("Replacing dots with spaces in %s", self.final_name)
self.final_name = self.final_name.replace(".", " ")
# Reuse the existing directory
if reuse and os.path.exists(reuse):
self.download_path = long_path(reuse)
else:
# Determine "incomplete" folder
self.download_path = os.path.join(cfg.download_dir.get_path(), self.work_name)
self.download_path = get_unique_dir(self.download_path, create_dir=True)
if not self.download_path:
raise NzbEmpty
self.download_path = long_path(self.download_path)
set_permissions(self.download_path)
# Always create the admin-directory, just to be sure
admin_dir = os.path.join(self.download_path, JOB_ADMIN)
if not os.path.exists(admin_dir):
create_all_dirs(admin_dir)
_, self.work_name = os.path.split(self.download_path)
# When doing a retry or repair, remove old cache-files
if reuse:
remove_all(admin_dir, "SABnzbd_nz?_*", keep_folder=True)
remove_all(admin_dir, "SABnzbd_article_*", keep_folder=True)
if nzb_fp:
full_nzb_path = sabnzbd.filesystem.save_compressed(admin_dir, filename, nzb_fp)
try:
sabnzbd.nzbparser.nzbfile_parser(full_nzb_path, self)
except Exception as err:
self.incomplete = True
logging.warning(T("Invalid NZB file %s, skipping (error: %s)"), filename, err)
logging.info("Traceback: ", exc_info=True)
# Some people want to keep the broken files
if cfg.allow_incomplete_nzb():
self.pause()
else:
self.purge_data()
raise NzbEmpty
# Check against identical checksum or series/season/episode if not repair
# Have to check for duplicate before saving the backup, as it will
# trigger the duplicate-detection based on the backup
if not reuse and dup_check and self.priority != REPAIR_PRIORITY:
duplicate, series_duplicate = self.has_duplicates()
# Copy to backup
sabnzbd.filesystem.backup_nzb(full_nzb_path)
if not self.files and not reuse:
self.purge_data()
if self.url:
logging.warning(T("Empty NZB file %s") + " [%s]", filename, self.url)
else:
logging.warning(T("Empty NZB file %s"), filename)
raise NzbEmpty
if cat is None:
for metacat in self.meta.get("category", ()):
metacat = cat_convert(metacat)
if metacat:
cat = metacat
break
if cat is None:
for grp in self.groups:
cat = cat_convert(grp)
if cat:
break
# Pickup backed-up attributes when re-using
if reuse:
cat, pp, script = self.load_attribs()
# Determine category and find pp/script values
self.cat, pp_tmp, self.script, priority = cat_to_opts(cat, pp, script, self.priority)
self.set_priority(priority)
self.repair, self.unpack, self.delete = pp_to_opts(pp_tmp)
# Show first meta-password (if any), when there's no explicit password
if not self.password and self.meta.get("password"):
self.password = self.meta.get("password", [None])[0]
# Run user pre-queue script if set and valid
if not reuse and make_script_path(cfg.pre_script()):
# Call the script
accept, name, pp, cat_pp, script_pp, priority, group = sabnzbd.newsunpack.pre_queue(self, pp, cat)
if cat_pp:
# An explicit pp/script/priority set upon adding the job takes precedence
# over an implicit setting based on the category set by pre-queue
if input_priority and not priority:
priority = input_priority
if input_pp and not pp:
pp = input_pp
if input_script and not script_pp:
script_pp = input_script
# Accept or reject
accept = int_conv(accept)
if accept < 1:
self.purge_data()
raise NzbRejected
if accept == 2:
self.fail_msg = T("Pre-queue script marked job as failed")
# Process all options, only over-write if set by script
# Beware that cannot do "if priority/pp", because those can
# also have a valid value of 0, which shouldn't be ignored
if name:
self.set_final_name_and_scan_password(name)
try:
pp = int(pp)
except:
pp = None
if cat_pp:
cat = cat_pp
try:
priority = int(priority)
except:
priority = DEFAULT_PRIORITY
if script_pp and is_valid_script(script_pp):
script = script_pp
if group:
self.groups = [str(group)]
# Re-evaluate results from pre-queue script
self.cat, pp, self.script, priority = cat_to_opts(cat, pp, script, priority)
self.set_priority(priority)
self.repair, self.unpack, self.delete = pp_to_opts(pp)
else:
accept = 1
# Pause if requested by the NZB-adding or the pre-queue script
if self.priority == PAUSED_PRIORITY:
self.pause()
self.set_stateless_priority(self.cat)
# Pause job when above size limit
limit = cfg.size_limit.get_int()
if not reuse and abs(limit) > 0.5 and self.bytes > limit:
logging.info("Job too large, forcing low prio and paused (%s)", self.final_name)
self.pause()
self.oversized = True
self.priority = LOW_PRIORITY
# If the job is forced in any way, skip duplicate check
if self.priority == FORCE_PRIORITY:
duplicate = series_duplicate = False
# Handle duplicates
if duplicate and (
(not series_duplicate and cfg.no_dupes() == 1) or (series_duplicate and cfg.no_series_dupes() == 1)
):
if cfg.warn_dupl_jobs():
logging.warning(T('Ignoring duplicate NZB "%s"'), filename)
self.purge_data()
raise NzbRejected
if duplicate and (
(not series_duplicate and cfg.no_dupes() == 3) or (series_duplicate and cfg.no_series_dupes() == 3)
):
if cfg.warn_dupl_jobs():
logging.warning(T('Failing duplicate NZB "%s"'), filename)
# Move to history, utilizing the same code as accept&fail from pre-queue script
self.fail_msg = T("Duplicate NZB")
accept = 2
duplicate = False
if duplicate or self.priority == DUP_PRIORITY:
self.duplicate = True
if cfg.no_dupes() == 4 or cfg.no_series_dupes() == 4:
if cfg.warn_dupl_jobs():
logging.warning('%s: "%s"', T("Duplicate NZB"), filename)
else:
if cfg.warn_dupl_jobs():
logging.warning(T('Pausing duplicate NZB "%s"'), filename)
self.pause()
# Only change priority if it's currently set to duplicate, otherwise keep original one
if self.priority == DUP_PRIORITY:
self.set_stateless_priority(self.cat)
# Check if there is any unwanted extension in plain sight in the NZB itself
for nzf in self.files:
if cfg.action_on_unwanted_extensions() and has_unwanted_extension(nzf.filename):
# ... we found an unwanted extension
logging.warning(T("Unwanted Extension in file %s (%s)"), nzf.filename, self.final_name)
# Pause, or Abort:
if cfg.action_on_unwanted_extensions() == 1:
logging.debug("Unwanted extension ... pausing")
self.unwanted_ext = 1
self.pause()
if cfg.action_on_unwanted_extensions() == 2:
logging.debug("Unwanted extension ... aborting")
self.fail_msg = T("Aborted, unwanted extension detected")
accept = 2
if reuse:
self.check_existing_files(self.download_path)
# Sort the files in the queue
self.sort_nzfs()
# Copy meta fields to nzo_info, if not already set
for kw in self.meta:
if not self.nzo_info.get(kw):
self.nzo_info[kw] = self.meta[kw][0]
logging.debug("NZB nzo-info = %s", self.nzo_info)
# Set nzo save-delay to minimum 120 seconds
self.save_timeout = max(120, min(6.0 * self.bytes / GIGI, 300.0))
# In case pre-queue script or duplicate check want to move
# to history we first need a nzo_id by entering the NzbQueue
if accept == 2:
sabnzbd.NzbQueue.add(self, quiet=True)
sabnzbd.NzbQueue.end_job(self)
# Raise error, so it's not added
raise NzbRejectedToHistory(nzo_id=self.nzo_id)
def update_download_stats(self, bps, serverid, bytes_received):
if bps:
self.avg_bps_total += bps / 1024
self.avg_bps_freq += 1
if serverid in self.servercount:
self.servercount[serverid] += bytes_received
else:
self.servercount[serverid] = bytes_received
def add_nzf(self, nzf: NzbFile):
"""Bookkeeping when adding new files
Only used during import, so not locked"""
self.files.append(nzf)
self.files_table[nzf.nzf_id] = nzf
self.bytes += nzf.bytes
# Only now add first article to the list
self.first_articles.append(nzf.first_article)
self.first_articles_count += 1
nzf.first_article = None
# Count how many bytes are available for repair
if sabnzbd.par2file.is_parfile(nzf.filename):
self.bytes_par2 += nzf.bytes
logging.info("File %s added to queue", nzf.filename)