-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.py
2367 lines (1894 loc) · 71 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
#!/usr/bin/env python
# coding: utf-8
# Leechr
# http://ashysoft.wordpress.com
#
# Copyright 2008-2015 Paul Ashton <[email protected]>
#
# This file is part of Leechr.
#
# Leechr is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Leechr 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 Leechr. If not, see <http://www.gnu.org/licenses/>.
#
# With contributions from:
# Rick Pass <[email protected]>
# Stalksta
# DaSchug
# ...Thanks guys :)
__author__ = "Paul Ashton ([email protected])"
__version__ = "0.8"
__copyright__ = "Copyright (c) 2008-2015 Paul Ashton"
__license__ = "GNU GPL v3+"
import hashlib
import nntplibssl as nntplib
import os
import pickle
import random
import re
import socket
import struct
import sys
import time
import urllib
import urllib2
import zipfile
from datetime import datetime
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
# Defines
LEECHR_VERSION = u'0.8'
DEBUG = False
RETRY_TIME = 5 # don't want to flood search engines :)
RETRY_LIMIT = 2 # retry 2 times, if its still not working then the site is down and pointless to keep trying :)
MINIMUM_POST_SIZE = 100 # MB
MINIMUM_POST_SIZE_720P = 200 # MB
#ALLOWED_GROUPS = ["alt.binaries.tv", "alt.binaries.tvseries", "alt.binaries.multimedia", "alt.binaries.hdtv", "alt.binaries.hdtv.x264", "alt.binaries.teevee"]
BANNED_GROUPS = []
SEARCH_MODULES = ["LOCALNEWZNAB", "NZBCLUBCOM"]#, "NZBXCO", "NEWSHOSTCOZA", "SICKBEARDCOM", "NZBSORG", "NZBNDXCOM"]#, "NZBINDEXNL", "BINSEARCHINFO"] # In order of preference
SEARCH_MODULES_OFFLINE = []
EPISODE_FORMATS = ["S%.2dE%.2d", "%dx%.2d"]
EPISODE_TIMEOUTS = [] #[show_name, season_num, episode_num, attempts]
RETRIEVE_TIMES = {}
BAD_NZBS = {} # 'urlhash':'reason'
DMCA_REMOVED = []
DIDNT_FIND = []
LEECHR_STATS = {}
_PERSISTENT = ['BAD_NZBS', 'DMCA_REMOVED', 'RETRIEVE_TIMES', 'DIDNT_FIND', 'LEECHR_STATS']
# Default Config (don't change these, change the ones in leechr.conf)
USENET_USESSL = False
USENET_HOST = ""
USENET_PORT = 119
USENET_USERNAME = ""
USENET_PASSWORD = ""
ME_USERNAME = ""
ME_PASSWORD = ""
NZBSORG_APIKEY = ""
NZBNDXCOM_APIKEY = ""
USENETCRAWLERCOM_APIKEY = ""
LOCALNEWZNAB_URL = ""
LOCALNEWZNAB_APIKEY = ""
NZBDir = ""
NZB_SUBDIRS = False
NZBprefix = ""
NZBsuffix = ""
ME_RETRY = True
LOGGING = False
IGNORE_SHOWS = []
RETENTION_LIMIT = 0
FILESIZE_LIMIT = 5000
DAYS_EARLY = 2.0
DONT_STRIP_NZBS = False
NZB_UNWANTED_FILES = ["sample"]
AUTO_UPGRADE = True
IGNORE_EPISODES_OLDER_THAN = 0
GET_HD_VIDEO = True
SD_OVERRIDE = []
HD_OVERRIDE = []
TIMEOUT_DAYS = 6.0
TIMEOUT_ATTEMPTS = 0
AUTOMARK_ACQUIRE = True
USE_SCENE_NAMES = False
LOGDIR = ""
# Defaults for helpers.dat (don't change these, please report any
# changes and they will be incorporated into helpers.dat for everyone)
SEARCH_HELPERS = {}
LOCAL_FILTERS = {}
ALT_SHOW_NAMES = {}
BANNED_WORDS = []
SEASON_EP_SHIFT = {}
DAILY_SHOWS = []
NAMED_SHOWS = []
HELPERS_DAT_VERSION = 0
LEECHR_REQ_VERSION = "0"
REMATCH = {}
SD_SHOWS = []
HD_SHOWS = []
# Have a random Browser User Agent just incase :)
USERAGENT = random.choice(("Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)",
"Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.1) Gecko/20090718 Firefox/3.5.1",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.1 (KHTML, like Gecko) Chrome/4.0.219.6 Safari/532.1",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.2)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30729)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Win64; x64; Trident/4.0)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; .NET CLR 2.0.50727; InfoPath.2)Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)",
"Mozilla/4.0 (compatible; MSIE 6.1; Windows XP)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"))
########################################################################
def printl(text, wrap=True):
""" Print to screen and save text to log file (if needed) """
text = to_utf8(text)
if not wrap and len(text)>80:
text = "%s.." % text[:77]
print(text)
if LOGGING:
fout = open(os.path.join(LOGDIR, "leechr.log"), "a")
if fout:
fout.write(time.asctime() + ": " + text + "\n")
fout.close()
return True
def debug(text):
""" Prints debug info """
if not DEBUG:
return False
import inspect
caller = inspect.stack()[1][3]
text = to_utf8(text)
ts = time.strftime("%H:%M:%S", time.localtime()) + " (%s)" % caller
# Multi-line output
linelength = 145-len(ts)
t = str(text)
while(len(t)>linelength):
printl("%s: %s..." % (ts, t[:linelength]))
t = t[linelength:]
else:
printl("%s: %s" % (ts, t))
fout = open(os.path.join(LOGDIR, "debug.log"), "a")
if fout:
fout.write("%s (%s): %s" % (ts, caller, to_utf8(text)))
fout.close()
return True
def getMyEpsAge(when):
""" Calculate myepisodes age from date """
if len(when) > 11:
delta = datetime.now() - datetime.strptime(when, "%a-%d-%b-%Y") # Mon-09-Jul-2001
else:
delta = datetime.now() - datetime.strptime(when, "%d-%b-%Y") # "18-Feb-2008"
return float("%.1f" % (delta.days + (delta.seconds / 86400.0))) # divide secs into days
def to_unicode(obj, encoding='utf-8'):
if isinstance(obj, basestring):
if not isinstance(obj, unicode):
obj = unicode(obj, encoding)
return obj
def to_utf8(obj, encoding='utf-8'):
if isinstance(obj, basestring):
if isinstance(obj, unicode):
obj = obj.encode(encoding)
return obj
def openURL(url):
""" Open an url and return it """
debug("Opening URL '%s' (%s)" % (url, USERAGENT))
try:
req = urllib2.Request(url, None, {"User-Agent":USERAGENT, "Pragma":"no-cache", "Cache-Control":"no-cache", 'Accept-encoding':'gzip'})
response = urllib2.urlopen(req)
# Check if gzipped..
if response.info().get('Content-Encoding') == 'gzip':
debug("gzipped content")
from StringIO import StringIO
import gzip
buf = StringIO(response.read())
data = gzip.GzipFile(fileobj=buf)
else:
debug("not gzipped content")
data = response
except urllib2.HTTPError, e:
printl("[!] HTTP Error: %s" % e.code)
return False
except urllib2.URLError, e:
printl("[!] URL Error: %s" % e.reason)
return False
except KeyboardInterrupt:
raise
except:
printl("[!] Error: Unknown error while retrieving url")
return False
return data
def retrieve_url(url, friendly_name="server", retries=RETRY_LIMIT):
""" Download the file at url and return it """
debug("retrieve_url(): '%s'" % url)
for retry in range(retries+1):
h = openURL(url)
if not h:
if retry+1 <= retries:
printl("[!] Error: Could not contact %s, retrying in %s seconds.." % (friendly_name, RETRY_TIME * (retry+1)))
time.sleep(RETRY_TIME * (retry+1))
printl("Retrying (attempt %s of %s)..." % (retry+1, retries))
else:
break
if not h:
printl("[!] Error: Failed to contact %s after %s retries, giving up." % (friendly_name, RETRY_LIMIT))
return ''
try:
data = h.read()
except:
printl("[!] Error: Failed to read from %s." % friendly_name)
return ''
return data
def save_timeouts(data):
""" Write the episode timeouts to timeout.dat """
filename = os.path.join(SCRIPTDIR, "%s_timeout.dat" % ME_USERNAME.lower())
try:
f = open(filename, "wb")
pickle.dump(data, f)
f.close()
except:
debug("Couldn't save '%s'" % filename)
return False
debug("Wrote '%s'" % filename)
return True
def load_timeouts():
""" Read the episode timeouts from timeout.dat """
filename = os.path.join(SCRIPTDIR, "%s_timeout.dat" % ME_USERNAME.lower())
try:
f = open(filename, "rb")
data = pickle.load(f)
f.close()
except:
debug("Couldn't load '%s'" % filename)
return []
debug("Loaded '%s'" % filename)
return data
def write_file(data, filename, rename=True):
""" Write the file data to disk """
if not data:
return False
debug("About to write %s bytes to '%s'" % (len(data), filename))
c = 1
tmpfilename = filename
if rename:
while True:
if not os.path.exists(tmpfilename):
break;
s = os.path.splitext(filename)
tmpfilename = "%s (%s)%s" % (s[0], c, s[1])
c=c+1
try:
n = open(tmpfilename, "wb") # TODO: Make sure theres not already a file by this name.
n.write(data)
n.close()
except:
return False
return tmpfilename
def nntpDownloadArticle(articleid):
""" Download an article from usenet """
debug("nntpDownloadArticle(): %s" % articleid)
# Make sure we have our brackety things
if articleid[:1] != '<':
articleid = "<%s>" % articleid
returnFalse = None
nntp = None
for retry in range(RETRY_LIMIT+1):
data = False
try:
if USENET_USESSL:
nntp = nntplib.NNTP_SSL(host=USENET_HOST, port=USENET_PORT, user=USENET_USERNAME, password=USENET_PASSWORD)
else:
nntp = nntplib.NNTP(host=USENET_HOST, port=USENET_PORT, user=USENET_USERNAME, password=USENET_PASSWORD)
debug("nntp connected")
data = nntp.article(articleid)
except nntplib.NNTPTemporaryError:
extype, exvalue = sys.exc_info()[:2]
if "430 No such article" in exvalue:
printl("[!] Error: No such article. Your news server does not have this article, it is probably too old, check your retention settings.")
else:
printl("[!] Error: Unexpected error grabbing article. %s" % exvalue)
returnFalse = True
break
except KeyboardInterrupt:
raise
except:
extype, exvalue = sys.exc_info()[:2]
printl("[!] Error: Exception while grabbing article (%s (%s))" % (extype, exvalue))
data = False
if not data:
if retry+1 <= RETRY_LIMIT:
printl("[!] Error grabbing article: %s (%s), retrying in %s seconds.." % (extype, exvalue, RETRY_TIME*(retry+1)))
time.sleep(RETRY_TIME*(retry+1))
printl("Retrying (attempt %s of %s)..." % (retry+1, RETRY_LIMIT))
else:
printl("[!] Error grabbing article: %s (%s), giving up." % (extype, exvalue))
returnFalse = True
break
else:
break
if data and " not found" in str(data[3]).lower():
debug(str(data[3]))
printl("[!] Warning: Empty article, it is probably too old, check your retention settings.")
returnFalse = True
try:
if nntp:
nntp.quit()
except EOFError: #Seems this is produced when nntp.quit() is used.
debug("Exception EOFError - Usenet connection closed (this appears to be normal)")
except:
extype, exvalue = sys.exc_info()[:2]
debug("Unknown Exception (%s %s) while closing nntp connection." % (extype, exvalue))
if returnFalse:
return False
return data[3]
#def yDecodeLine(line):
# """ yDecode one line """
# data = ""
# pos = 0
# while pos < len(line):
# if line[pos] == "=": # Escape char
# pos += 1
# num = (ord(line[pos]) - 64 - 42) % 256
# else:
# num = (ord(line[pos]) - 42) % 256
# data += chr(num)
# pos += 1
# return data
def yDecode(lines):
""" Decode a yEnc encoded list """
debug("yDecode() called with %s lines" % len(lines))
decoded = ""
linenum = 0
ybegin = False
while True:
line = lines[linenum]
if line[:8] == "=ybegin " and "line=" in line and "size=" in line and "name=" in line:
ybegin = True
obj = line.split()
for o in obj:
if "line=" in o: yline = o[5:]
if "size=" in o: ysize = o[5:]
if "name=" in o: yname = o[5:]
elif line[:7] == "=ypart ":
pass
elif line[:6] == "=yend ":
pass
elif ybegin:
data = ""
pos = 0
while pos < len(line):
if line[pos] == "=": # Escape char
pos += 1
num = (ord(line[pos]) - 64 - 42) % 256
else:
num = (ord(line[pos]) - 42) % 256
data += chr(num)
pos += 1
decoded += data
else:
pass
linenum += 1
if len(decoded) >= 5000: break;
if linenum >= len(lines): break;
debug("decoded data len: %s" % len(decoded))
return decoded
def extractRarInfo(rardata):
""" Grab filenames and file headers from within the rar data """
if DEBUG:
write_file(rardata, "debug.seg", rename=False)
infos = []
rarpos = 0
while (rarpos+7 <= len(rardata)):
HEAD_CRC, HEAD_TYPE, HEAD_FLAGS, HEAD_SIZE = struct.unpack("<HBHH", rardata[rarpos:rarpos+7])
debug("HEAD_FLAGS='%s'" % HEAD_FLAGS)
HEAD = rardata[rarpos:rarpos+HEAD_SIZE]
rarpos += HEAD_SIZE
if HEAD_TYPE == 0x74: # File Header Block
PACK_SIZE, UNP_SIZE, HOST_OS, FILE_CRC, FTIME, UNP_VER, METHOD, NAME_SIZE, ATTR = struct.unpack("<IIBIIBBHI", HEAD[7:7+25])
namepos = 32
if METHOD != 0x30: #(0x30=STORED, 0x31-35=FASTEST-BEST)
printl("[!] Warning: Compressed archive detected, Leechr can not check content.")
# Skip zero-bytes, dunno why they're sometimes there (YET! anyone know?)
while ord(HEAD[namepos])<2: # \x00 and \x01
namepos += 1
name = HEAD[namepos:namepos+NAME_SIZE]
header, = struct.unpack("<I", rardata[rarpos:rarpos+4])
infos.append((name,header))
debug("Adding %s to infos" % str((name,header)))
rarpos += PACK_SIZE # Seek past the file contents
return infos
def xmlGetFirstArticle(data, text):
""" Get the article name of the first segment of first file """
for child in data:
subject = child.get('subject')
if subject and text in subject.lower():
try:
c = child.iter()
except AttributeError: # .iter() doesn't exist in Python 2.6
c = child.getiterator()
except:
pass
for elem in c:
if elem.get('number') == "1":
return "<%s>" % elem.text
def check_for_passwords(nzbdata):
""" Check NZB for passworded rar files """
debug("check_for_passwords() called with %s bytes of data" % len(nzbdata))
if DEBUG: write_file(nzbdata, "debug.nzb", rename=False)
# Get root
try:
root = ET.fromstring(nzbdata)
except ET.ParseError:
error = "[!] Error: corrupt or incomplete NZB file"
printl(error)
return error
except:
error = "[!] Error parsing nzb, please report this and send in debug.nzb"
write_file(nzbdata, "debug.nzb", rename=False)
printl(error)
return error
# Find a 'first-file' .rar or .mkv
for i in ['.part001.rar\"', '.part01.rar\"', '.mkv\"', '.avi\"', '.mp4\"', '.rar\"', '.r00\"']:
seg = xmlGetFirstArticle(root, i)
if seg:
break
# Couldn't find anything useful..
if not seg:
error = "Error finding first segment. Probably an incomplete nzb/post."
printl("[!] %s " % error)
return error
debug("First segment of first-file is article %s" % seg)
# Check if we already know DMCA killed this seg
if seg in DMCA_REMOVED:
error = "Article exterminated by DMCA :/"
printl("[!] Previously checked. %s " % error)
return error
# Grab segment..
debug("Grabbing %s..." % seg)
segdata = nntpDownloadArticle(seg)
if not segdata:
error = "Error grabbing article, don't know why :/"
printl("[!] %s " % error)
return error
#Check for DMCA take downs..
if "DMCA" in ''.join(segdata):
error = "Article exterminated by DMCA :/"
printl("[!] %s " % error)
DMCA_REMOVED.append(seg)
return error
# Check we have some yEncoded datas..
if "=ybegin " not in ''.join(segdata):
error = "Error grabbing article, not yencoded :/"
printl("[!] %s " % error)
return error
# yDecode the data
data = yDecode(segdata)
names = []
# Check the 4 byte checksum
checksum, = struct.unpack("<I", data[:4])
validFiles = {561144146:'rar', 2749318426L:'mkv', 1179011410:'avi', 335544320:'mp4', 402653184:'mp4'}
if checksum in validFiles:
debug("Found a .%s file" % validFiles[checksum])
if validFiles[checksum] == 'rar':
debug("Found a rar so lets check inside..")
for item in extractRarInfo(data):
debug("items: %s" % str(item))
if item[1] in validFiles:
debug("Found a .%s file (in rar)" % validFiles[item[1]])
if validFiles[item[1]] == 'rar':
printl("[!] Warning: RAR within a RAR is usually passworded, ignoring this NZB")
else:
names.append(item[0])
else:
debug("Unknown file: %s (%d) (in rar)" % item)
else: #Not a rar
debug("Plain %s file found, adding to names.." % validFiles[checksum].upper())
names.append(validFiles[checksum])
if not names:
error = "[!] Error: No video files found."
printl(error)
return error
#File seems ok..
return False
def process_nzb(data, unwanted_files):
""" Check NZB is ok and remove unwanted files """
header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<!DOCTYPE nzb PUBLIC \"-//newzBin//DTD NZB 1.0//EN\" \"http://www.newzbin.com/DTD/nzb/nzb-1.0.dtd\">\n<!-- NZB fixed by Leechr -->\n<nzb xmlns=\"http://www.newzbin.com/DTD/2003/nzb\">\n"
body = ""
footer = "</nzb>\n"
badcount = 0
goodcount = 0
bytes = 0
xml = BeautifulStoneSoup(data)
files = xml("file")
for f in files:
found = False
name = f["subject"].lower()
for unwanted in unwanted_files:
if unwanted.lower() in name:
found = unwanted.lower()
break
if not found:
body = body + str(f) + "\n"
goodcount += 1
else:
badcount += 1
debug("Stripping unwanted file: %s (%s)" % (name, found))
if goodcount < 1:
printl("[!] Warning: Bad NZB, No files found.")
return False
if badcount > 0:
printl("Stripped %s unwanted files from NZB." % badcount)
return header + body + footer
def striphtmlentities(html):
entities = {' ':' ', '"':'\'', '<':'<', '>':'>', '\t':'', '<strong>':'', '</strong>':''}
for e in entities:
html = html.replace(e, entities[e])
return html
def decodeHTML(html):
""" Decode any HTML entities (%gt; to > etc.)"""
try:
t = unicode(BeautifulStoneSoup(html, convertEntities=BeautifulStoneSoup.HTML_ENTITIES))
except:
t = u""
return t
def exitmsg(message):
printl("")
printl("---------------------------------------------------------------")
printl(" %s" % message)
printl(" If you find Leechr useful please consider buying me a beer :)")
printl(" http://ashysoft.wordpress.com/donate")
printl("---------------------------------------------------------------")
def getEpisodeInfo():
""" Get episode info from myepisodes.com """
page = retrieve_url("http://www.myepisodes.com/rss.php?feed=unacquired&uid="+ME_USERNAME+"&pwdmd5="+hashlib.md5(ME_PASSWORD).hexdigest(), "myepisodes.com")
if not page:
printl("[!] Fatal Error: Could not contact myepisodes.com, Leechr can not continue.")
exit()
xml = BeautifulStoneSoup(page)
items = xml("item")
if not items:
printl("[!] Fatal Error: Bad response from myepisodes.com, Please check your MyEpisodes Username and Password are correct.")
exit()
episodes = []
for item in items:
# Theres no eps to get so break
if item.title.string == "No Episodes":
break
# Split up the stupid string into usable chunks
debug("item.title.string = '%s'" % decodeHTML(item.title.string))
tmp = re.findall("\[ ?(.[^\[\]]*) \]", decodeHTML(item.title.string))
debug("tmp = '%s'" % tmp)
# get season and epi numbers
tmp[1] = tmp[1].lower()
if "x" in tmp[1]:
s,e = tmp[1].split("x")
else:
s,e = tmp[1][1:].split("e")
# Add to the list..
episodes.append({'show_name':tmp[0], 'season_num':int(s), 'episode_num':int(e), 'episode_name':tmp[2], 'air_date':tmp[3]})
return episodes
def create_score(line):
""" Score the given line """
line = line.lower()
score = 0
if "720p" in line: score += 100
if "repack" in line: score += 10
if "proper" in line: score += 10
if "web-dl" in line: score += 20
if "hdtv" in line: score += 10
if "efnet" in line: score += 1 # efnet group posts are generally good
return score
def filterResults(resList, maxAge, showdetails, HD):
""" Get rid of stupid results """
maxAge = float(maxAge) # make sure maxAge is a float.
debug("FilterResults() called, maxAge=%s HD=%s" % (maxAge, HD))
badnzbcounter = 0
debug("*** Result List ***")
for item in reversed(resList):
# item = (full_post_name, id, size, group, age)
itemName = item[0]
itemID = item[1]
itemSize = int(strtonum(item[2]))
itemGroup = item[3]
itemAge = float(strtonum(item[4]))
debug("(%s) %s - %s - %s - %sd" % (itemID, itemName, itemSize, itemGroup, itemAge))
# Check if NZB is in bad-nzbs list
if hashlib.md5(itemID).hexdigest() in BAD_NZBS:
debug("REMOVED - BAD NZB (%s)" % itemID)
badnzbcounter += 1
resList.remove(item)
continue
# Check for show name
remove = True
for n in getAltNames(showdetails['show_name']):
t = [word for word in cleanup_name(n).split() if word.lower() in itemName.lower()]
if len(t) == len(n.split()):
# All words found so...
remove = False
if remove:
debug("REMOVED - Required word not found in name ")
resList.remove(item)
continue
# Check daily show date
if showdetails['show_name'] in DAILY_SHOWS:
# Check for Air-Date
if showdetails['DAILYSHOWAIRDATE'].lower() not in itemName.lower():
debug("REMOVED - NOT CORRECT DAILY-DATE")
resList.remove(item)
continue
else:
# Check for ep num
se1 = "S%.2dE%.2d" % (showdetails['season_num'], showdetails['episode_num'])
se2 = "%dX%.2d" % (showdetails['season_num'], showdetails['episode_num'])
if se1.lower() not in itemName.lower() and se2.lower() not in itemName.lower():
debug("REMOVED - NOT CORRECT EP NUM (%s)" % se1)
resList.remove(item)
continue
# Remove if matches LOCAL_FILTERS
if showdetails['show_name'] in LOCAL_FILTERS:
req = LOCAL_FILTERS[showdetails['show_name']][0]
filt = LOCAL_FILTERS[showdetails['show_name']][1]
#Check req's..
remove = False
for r in req:
if r.lower() not in itemName.lower():
remove = True
debug('REMOVED - LOCAL_FILTERS:REQ not matched')
break
#and filt's..
for f in filt:
if f.lower() in itemName.lower():
remove = True
debug('REMOVED - LOCAL_FILTERS:FILT matched')
break
if remove:
resList.remove(item)
continue
# Remove if too big
if itemSize > FILESIZE_LIMIT:
debug("REMOVED - TOO BIG (%s)" % itemID)
resList.remove(item)
continue
# Remove if wrong format
if (HD and not "720p" in itemName.lower()): #TODO - check its SD properly?
debug("REMOVED - DID NOT MATCH FORMAT HD='%s' (%s)" % (HD, itemID))
resList.remove(item)
continue
# Remove if re does not match..
if showdetails['show_name'] in REMATCH:
if not re.findall(REMATCH[showdetails['show_name']], itemName):
debug("REMOVED - DID NOT MATCH RE (%s)" % itemID)
resList.remove(item)
continue
# Remove if name contains banned_words...
tmp = ""
for word in BANNED_WORDS:
if word.lower() in item[0].lower():
tmp = word.lower()
break
if tmp:
debug("REMOVED - BANNED WORD '%s'" % tmp)
resList.remove(item)
continue
# Remove if group is not in the allowed list..
groups = [item[3]]
if " " in item[3]:
groups = item[3].split(" ")
#debug("groups='%s'" % groups)
groupcheck = True
for group in groups:
if group in BANNED_GROUPS:
groupcheck = False
break
if not groupcheck:
resList.remove(item)
debug("REMOVED - BANNED GROUP '%s'" % item[3])
continue
# Remove if size does not meet minimum size
if "720p" in item[0]:
if item[2] < MINIMUM_POST_SIZE_720P:
resList.remove(item)
debug("REMOVED - BAD SIZE for 720p (%s < %s)" % (item[2], MINIMUM_POST_SIZE_720P))
continue
else:
if item[2] < MINIMUM_POST_SIZE:
resList.remove(item)
debug("REMOVED - BAD SIZE for xvid (%s < %s)" % (item[2], MINIMUM_POST_SIZE))
continue
# Remove if post is older than air date
if itemAge > maxAge:
debug("REMOVED - OLDER THAN AIR DATE (%s > %s)" % (itemAge, maxAge))
resList.remove(item)
continue
# Remove if older than users RETENTION_LIMIT
if RETENTION_LIMIT > 0 and itemAge > RETENTION_LIMIT:
debug("REMOVED - OVER RETENTION (%s > %s)" % (itemAge, RETENTION_LIMIT))
resList.remove(item)
continue
if DEBUG:
debug("*** Result List After Filtering ***")
for item in resList:
debug(" (%s) %s - %s - %s" % (item[1], item[0], item[2], item[3]))
debug("*** End of Result List After Filtering ***")
if badnzbcounter:
printl(" Ignoring %s results as they have bad NZBs" % badnzbcounter)
return resList
def cleanup_name(text):
""" Clean unwanted characters from text and replace others """
swaps = {':':'', '\'':'', '"':'', '(':'', ')':'', '!':'', '?':'', u'\u2019':'', '*':'',
'/':' ', '\\':' ',
'&':'and', u'\xe9':'e', u'\u03a3':'E', u'\xf6':'o', u'\xe4':'a'}
for s in swaps:
text = text.replace(s, swaps[s])
return text
def strtonum(num):
"""Convert string to either int or float."""
if type(num) in [int, float, long]:
return num
num = num.replace(',', '')
try:
ret = int(num)
except ValueError:
ret = float(num)
return ret
def find_config():
""" Find a config file and return the path """
# Check users home dir for config file
if os.access(os.path.join(os.path.expanduser("~"), "leechr.conf"), os.W_OK):
return os.path.join(os.path.expanduser("~"), "leechr.conf")
# Fall back to Default leechr directory
return os.path.join(SCRIPTDIR, "leechr.conf")
class searchmodule(object):
DOWNLOAD_URL = "%s"
MULTISEARCH = True
SLEEP_TIME_SEARCH = 7
SLEEP_TIME_NZB = 7
ERR_MSGS = []
KILL_IF = [] # Remove from searcher list if string matches
def expand_group_names(self, groupstring):
""" Expand usenet group names.. a.b.c > alt.binaries.c """
return groupstring.replace("a.b.", "alt.binaries.")
def get_size(self, s):
""" Convert string to size in MB """
s = s.replace(",", "") # Remove commas
s = s.replace(" ", " ") # Change to space
tmp = re.findall(r"([\d.]*) ([K|M|G]?B)", s)
if not tmp:
return 0
tmp = tmp[0] # get first result
size = strtonum(tmp[0])
if tmp[1] == "GB": return size * 1024.0
elif tmp[1] == "KB": return round(size/1024.0, 2)
elif tmp[1] == "B": return 0
return size
def get_age(self, when, format="%a, %d %b %Y %H:%M:%S"): # "Mon, 17 Nov 2008 01:45:32"
""" Calculate age from date """
debug("Called get_age('%s', '%s')" %(when, format))
delta = datetime.now() - datetime.strptime(when, format)
age = float("%.1f" % (delta.days + (delta.seconds/86400.0))) # divide secs into days
return age
def init_search(self, query, mode='RSS'):
""" Download page and return data """
# Before we begin do we need to Sleep some?
if self.FRIENDLY_NAME in RETRIEVE_TIMES:
t = RETRIEVE_TIMES[self.FRIENDLY_NAME] - int(time.time())
if t > 0:
printl(" Sleeping for %d secs.. Zzz.." % t)
time.sleep(t)
# Set new time
RETRIEVE_TIMES[self.FRIENDLY_NAME] = int(time.time() + self.SLEEP_TIME_SEARCH)
debug(RETRIEVE_TIMES)
if self.NOT_CHAR:
query = query.replace("%21", self.NOT_CHAR) # replace ! with specified not-char
page = retrieve_url(self.RSS_BASE_URL % query, friendly_name=self.FRIENDLY_NAME)
if not page and len(SEARCH_MODULES)>1:
printl("[!] Error: %s appears to be down, we will skip it for this session." % self.FRIENDLY_NAME)
SEARCH_MODULES_OFFLINE.append(self.__class__.__name__)
return None
p = "".join(page).lower()
# Check KILL_IF errors
for e in self.KILL_IF:
if e.lower() in p:
printl("[!] Error: %s had a problem, I have removed this module from active list. (%s)" % (self.FRIENDLY_NAME, e))
SEARCH_MODULES_OFFLINE.append(self.__class__.__name__)
return None
# Check for errors in the page
for error in self.ERR_MSGS: