forked from jimrollenhagen/pywhatauto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWHATauto.py
executable file
·2750 lines (2505 loc) · 152 KB
/
WHATauto.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 -*-
#python 2.5 support for the "with" command
from __future__ import with_statement
from __future__ import division
print('Starting main program.')
print('pyWHATauto: johnnyfive + blubba. WHATauto original creator: mlapaglia.')
import sys
import globals as G
import irclib as irclib
#import handlePubMSG as handlePubMSG
from torrentparser import torrentparser
VERSION = 'v1.74'
print('You are running pyWHATauto version %s\n'%VERSION)
#from time import strftime, strptime
from datetime import datetime, timedelta
from threading import Thread
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import db, time, os, re, ConfigParser, thread, urllib, urllib2, random, cookielib, socket, math, traceback, sqlite3, threading#, WHATparse as WP, #htmllib,
def main():
global irc, log, log2, lastFSCheck, last, SETUP
last = False
lastFSCheck = False
log = False
os.chdir(G.SCRIPTDIR)
loadConfigs()
if G.LOG:
if not os.path.isdir(os.path.join(G.SCRIPTDIR,'logs')):
os.makedirs(os.path.join(G.SCRIPTDIR,'logs'))
global WIN32FILEE
WIN32FILEE = False
if os.name == 'nt':
try:
import win32file
if win32file:
pass
WIN32FILEE = True
except ImportError:
out('ERROR','The module win32file is not installed. Please download it from http://sourceforge.net/projects/pywin32/files/')
out('ERROR','The program will continue to function normally except where win32file is needed.')
WIN32FILEE = False
out('DEBUG','Starting report thread.')
thread.start_new_thread(writeReport,(20,))
out('DEBUG','Report thread started.')
out('DEBUG','Starting DB thread.')
#Create the DB object
DB = db.sqlDB(G.SCRIPTDIR, G.Q)
DB.setDaemon(True)
DB.start()
out('DEBUG','DB thread started.')
out('DEBUG','Starting web thread.')
#Create the web object
try:
WEB = WebServer(G.SCRIPTDIR, SETUP.get('setup','password'), SETUP.get('setup','port'), SETUP.get('setup','webserverip'))
WEB.setDaemon(True)
WEB.start()
out('DEBUG','Web thread started.')
except Exception:
outexception('Exception caught in main(), when starting webserver')
try:
irc = irclib.IRC()
out('INFO','Main program loaded. Starting bots.')
if G.TESTING:
startBots()
else:
thread.start_new_thread(startBots,(tuple()))
except Exception:
outexception('General exception in main():')
Prompt(.5)
def Prompt(n):
global log, log2
while 1:
time.sleep(n)
if G.EXIT:
print('Exiting.')
if G.LOG:
log.close()
log2.close()
sys.exit(1)
class DuplicateError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def loadConfigs():
global SETUP
#global REGEX, SETUP, CRED, FILTERS, CUSTOM, ALIASES#, REPORTS , NETWORKS
#these get replaced with:
# G.NETWORKS[sitename]['regex'], ['setup'], ['creds'], ['filters'], G.REPORTS G.ALIAS
if os.name == 'nt' and os.path.exists(os.path.join(G.SCRIPTDIR,'nt')):
print('Loading nt settings')
SETUP = ConfigParser.RawConfigParser()
SETUP.readfp(open(os.path.join(G.SCRIPTDIR,'nt','setup.conf')))
CRED = ConfigParser.RawConfigParser()
CRED.readfp(open(os.path.join(G.SCRIPTDIR,'nt','credentials.conf')))
CUSTOM = ConfigParser.RawConfigParser()
CUSTOM.readfp(open(os.path.join(G.SCRIPTDIR,'nt','custom.conf')))
FILTERS = ConfigParser.RawConfigParser()
FILTERS.readfp(open(os.path.join(G.SCRIPTDIR,'nt','filters.conf')))
else:
SETUP = ConfigParser.RawConfigParser()
SETUP.readfp(open(os.path.join(G.SCRIPTDIR,'setup.conf')))
CRED = ConfigParser.RawConfigParser()
CRED.readfp(open(os.path.join(G.SCRIPTDIR,'credentials.conf')))
CUSTOM = ConfigParser.RawConfigParser()
CUSTOM.readfp(open(os.path.join(G.SCRIPTDIR,'custom.conf')))
FILTERS = ConfigParser.RawConfigParser()
try:
FILTERS.readfp(open(os.path.join(G.SCRIPTDIR,'filters.conf')))
except ConfigParser.ParsingError, e:
out('ERROR','There is a problem with your filters.conf. If using newlines, please make sure that each new line is tabbed in once. Error: %s'%e)
raw_input("This program will now exit (okay): ")
quit()
REPORT = ConfigParser.RawConfigParser()
REPORT.readfp(open(os.path.join(G.SCRIPTDIR,'reports.conf')))
REGEX = ConfigParser.RawConfigParser()
REGEX.readfp(open(os.path.join(G.SCRIPTDIR,'regex.conf')))
if SETUP.has_option('debug', 'testing'):
if SETUP.get('debug', 'testing').rstrip().lstrip() == '1':
G.TESTING = True
if SETUP.has_option('setup','log'):
if SETUP.get('setup','log').rstrip().lstrip() == '1':
G.LOG = True
#load the reports. Since we re-write the entire file every time, we have to load them all.
for site in REPORT.sections():
G.REPORTS[site] = dict()
G.REPORTS[site]['seen'] = int(REPORT.get(site, 'seen'))
G.REPORTS[site]['downloaded'] = int(REPORT.get(site, 'downloaded'))
#alias stuff:
G.FROMALIAS = dict()
G.TOALIAS = dict()
for configs in CRED.sections():
try:
if CUSTOM.has_option('aliases', configs):
if CUSTOM.get('aliases',configs) in G.FROMALIAS.keys():
raise DuplicateError('The alias %s is defined for two sites, %s and %s' %(CUSTOM.get('aliases',configs),G.FROMALIAS[CUSTOM.get('aliases',configs)],configs))
G.FROMALIAS[CUSTOM.get('aliases',configs)] = configs
G.TOALIAS[configs] = CUSTOM.get('aliases',configs)
elif SETUP.has_option('aliases', configs):
if SETUP.get('aliases',configs) in G.FROMALIAS.keys():
raise DuplicateError('The alias %s is defined for two sites, %s and %s' %(SETUP.get('aliases',configs),G.FROMALIAS[SETUP.get('aliases',configs)],configs))
G.FROMALIAS[SETUP.get('aliases',configs)] = configs
G.TOALIAS[configs] = SETUP.get('aliases',configs)
else:
G.TOALIAS[configs] = configs
if not configs in G.FROMALIAS.keys():
G.FROMALIAS[configs] = configs
except DuplicateError, e:
if log:
out('ERROR',e)
else:
print(e)
G.EXIT = True
sys.exit()
if CUSTOM.has_option('sites',configs):
G.TOSTART[configs]= CUSTOM.get('sites',configs)
elif SETUP.has_option('sites',configs):
G.TOSTART[configs]= SETUP.get('sites',configs)
else:
G.TOSTART[configs]= "0"
G.ALIASLENGTH = 0
longest = ''
for val in G.TOALIAS.itervalues():
if len(val) > G.ALIASLENGTH:
G.ALIASLENGTH = len(val)
longest = val
if log:
out('DEBUG','Longest alias is %s (%s) with length %d'%(longest,G.FROMALIAS[longest],G.ALIASLENGTH))
else:
print ('Longest alias is %s (%s) with length %d'%(longest,G.FROMALIAS[longest],G.ALIASLENGTH))
if REGEX.has_option('version','version'):
G.REGVERSION = int(REGEX.get('version','version'))
G.NETWORKS = dict()
for configs in CRED.sections(): #for network in credentials.conf
#for key, value in CRED.items(configs):
#if the REPORTS.conf is missing this network, add it!
if not G.REPORTS.has_key(configs):
G.REPORTS[configs] = dict()
G.REPORTS[configs]['seen'] = 0
G.REPORTS[configs]['downloaded'] = 0
#add the credentials for each network key
G.NETWORKS[configs] = dict()
G.NETWORKS[configs]['creds'] = dict()
for key, value in CRED.items(configs):
G.NETWORKS[configs]['creds'][key] = value
#add the regex for each network
G.NETWORKS[configs]['regex'] = dict()
if REGEX.has_section(configs):
for key, value in REGEX.items(configs):
G.NETWORKS[configs]['regex'][key] = value
if CUSTOM.has_section(configs):
for key, value in CUSTOM.items(configs):
G.NETWORKS[configs]['regex'][key] = value
#add the setup to each network (they will all have the same info)
G.NETWORKS[configs]['setup'] = dict()
for key, value in SETUP.items('setup'):
G.NETWORKS[configs]['setup'][key] = value
G.NETWORKS[configs]['notif'] = dict()
for key, value in SETUP.items('notification'):
G.NETWORKS[configs]['notif'][key] = value
#add aliases
G.NETWORKS[configs]['fromalias'] = dict()
for key, value in G.FROMALIAS.iteritems():
G.NETWORKS[configs]['fromalias'][key] = value
G.NETWORKS[configs]['toalias'] = dict()
for key, value in G.TOALIAS.iteritems():
G.NETWORKS[configs]['toalias'][key] = value
#add filters the networks they belong to
G.NETWORKS[configs]['filters'] = dict()
for f in FILTERS.sections():
if FILTERS.get(f, 'site') == configs:
G.NETWORKS[configs]['filters'][f] = dict()
for key, value in FILTERS.items(f):
G.NETWORKS[configs]['filters'][f][key] = value
#load the filter state into the filters dictionary
G.FILTERS[f.lower()] = FILTERS.get(f, 'active')
#if the filter has been manually toggled, load that value instead
if f.lower() in G.FILTERS_CHANGED:
G.NETWORKS[configs]['filters'][f]['active'] = G.FILTERS_CHANGED[f.lower()]
def reloadConfigs():
G.LOCK.acquire()
loadConfigs()
for bot in G.RUNNING.itervalues():
bot.saveNewConfigs(G.NETWORKS[bot.getBotName()])
G.LOCK.release()
out('INFO','Configs re-loaded.')
def outexception(msg=False,site=False):
exc = traceback.format_exc()
if msg:
out('ERROR', msg, site)
for excline in exc.splitlines():
out('ERROR', excline, site)
def out(level, msg, site=False):
global last
levels = ['error','warning','msg','info','cmd','filter','debug']
#getting color output ready for when I decide to implement it
colors = {'error':'%s','warning':'%s','msg':'%s','info':'%s','cmd':'%s','filter':'%s','debug':'%s'}
if levels.index(level.lower()) <= levels.index(SETUP.get('setup','verbosity').lower()):
if site:
if site != last and last != False:
#print('')
if G.LOG:
logging('')
msg = '%s %-*s %-*s %s' %(datetime.now().strftime("%m/%d-%H:%M:%S"),7,level,G.ALIASLENGTH,G.TOALIAS[site], msg)
print(colors[level.lower()]%msg)
last = site
else:
msg = '%s %-*s %-*s %s' %(datetime.now().strftime("%m/%d-%H:%M:%S"),7,level,G.ALIASLENGTH,'', msg)
#msg='%s-%s: %s' %(datetime.now().strftime("%m/%d-%H:%M:%S"),level, msg)
print(msg)
if G.LOG:
logging(msg)
def logging(msg):
global log, log2, logdate
#Create the log file
logdir = os.path.join(G.SCRIPTDIR,'logs')
if not log:
logdate = datetime.now().strftime("%m.%d.%Y-%H.%M")
log = open(os.path.join(logdir,'pyWALog-'+logdate+'.txt'),'w')
log2 = open(os.path.join(logdir,'pyWALog.txt'),'w')
#x = datetime.strptime(logdate,"%m.%d.%Y-%H.%M")
if datetime.now() - datetime.strptime(logdate,"%m.%d.%Y-%H.%M") > timedelta(hours=24):
log.close()
logdate = datetime.now().strftime("%m.%d.%Y-%H.%M")
log = open(os.path.join(logdir,'pyWALog-'+logdate+'.txt'),'w')
log.write(msg+"\n")
log.flush()
log2.write(msg+"\n")
log2.flush()
def startBots():
try:
for key, value in G.TOSTART.items():
if value == "1":
establishBot(key)
irc.process_forever()
except Exception:
outexception('General exception caught, startBots()')
G.EXIT = True
def establishBot(sitename):
'''Does some preliminary checks, creates a new autoBOT instance and connects it to irc'''
#Need to check if there is sufficient regexp and credentials present
if sitename in G.RUNNING.keys():
out('INFO','The autoBOT for this site is already running')
return 'The autoBOT for this site is already running'
re = G.NETWORKS[sitename]['regex']
if not ('server' in re and re['server'] != '' and 'port' in re and re['port'] != '' and 'announcechannel' in re and re['announcechannel'] != ''):
out('INFO','This site does not have an irc announce channel.',site=sitename)
return 'Cannot connect to irc network: this site does not have an irc announce channel.'
cr = G.NETWORKS[sitename]['creds']
if not ('botnick' in cr and cr['botnick'] != '' and 'nickowner' in cr and 'nickservpass' in cr and cr['nickservpass'] != ''):
out('ERROR','The credentials given are not sufficient to connect to the irc server',site=sitename)
return 'ERROR: The credentials given are not sufficient to connect to the irc server'
shared = False
if 'tempbotnick' in cr:
botnick = cr['tempbotnick']
else:
botnick = cr['botnick']
if 'ircpassword' in cr:
ircpw = cr['ircpassword']
else:
ircpw = None
for key in G.RUNNING.keys():
sre = G.NETWORKS[key]['regex']
scr = G.NETWORKS[key]['creds']
if sre['server'].lower() == re['server'].lower():
out('DEBUG','Matching servers found between %s and %s (old), %s' %(sitename,key,re['server']),site=sitename)
if 'tempbotnick' in scr:
sbotnick = scr['tempbotnick']
else:
sbotnick = scr['botnick']
if 'ircpassword' in cr:
sircpw = cr['ircpassword']
else:
sircpw = None
if botnick.lower() == sbotnick.lower() and ircpw == sircpw:
out('DEBUG','servers and nicks are matching the full way! Piggybacking...',site=sitename)
shared = key
break
G.LOCK.acquire()
G.RUNNING[sitename] = autoBOT(sitename,G.NETWORKS[sitename])
G.LOCK.release()
if shared:
G.RUNNING[sitename].setSharedConnection(G.RUNNING[shared])
return 'Connecting to %s by piggybacking on %s\'s connection' %(sitename,shared)
else:
G.RUNNING[sitename].connect()
return 'Connecting to %s' %(sitename)
def writeReport(n):
last = 0
while 1:
now = 0
G.LOCK.acquire()
for key in G.REPORTS.itervalues():
now += int(key['seen'])
if last != now:
config = ConfigParser.RawConfigParser()
for section in sorted(G.REPORTS.iterkeys()):
config.add_section(section)
config.set(section,'seen',G.REPORTS[section]['seen'])
config.set(section,'downloaded',G.REPORTS[section]['downloaded'])
#release the lock before we waste time writing the config.
G.LOCK.release()
# Writing our configuration file to 'reports.conf'
try:
with open('reports.conf', 'wb') as configfile:
config.write(configfile)
last = now
except IOError, e:
out('ERROR',e)
else:
G.LOCK.release()
time.sleep(n)
def getDriveInfo(drive):
if os.name == 'nt' and WIN32FILEE:
def get_drivestats(drive=None):
'''
returns total_space, free_space and drive letter
'''
drive = drive.replace(':\\', '')
import win32file
sectPerCluster, bytesPerSector, freeClusters, totalClusters = win32file.GetDiskFreeSpace(drive + ":\\")
total_space = totalClusters*sectPerCluster*bytesPerSector
free_space = freeClusters*sectPerCluster*bytesPerSector
return total_space, free_space
total_space, free_space = get_drivestats(drive)
return free_space, float(free_space)/float(total_space)
elif os.name == 'posix':
if SETUP.has_option('setup','limit') and SETUP.get('setup','limit').lstrip().rstrip() != '' and SETUP.get('setup','limit').lstrip().rstrip() != '0':
import subprocess, shlex
args = shlex.split('du -s --bytes %s'%drive)
du = subprocess.Popen(args,stdout=subprocess.PIPE)
dureturn = du.communicate()[0]
m = re.search('(\d+).*',dureturn)
used = float(m.group(1)) / (1024 * 1024 * 1024)
free = float(SETUP.get('setup','limit'))-used
return free, free / float(SETUP.get('setup','limit'))
else:
out('ERROR','Unknown filesystem as it seems...')
return 1.0, 1.0
#try:
#s = os.statvfs(drive)
#return (float(s.f_bavail)*float(s.f_bsize))/1024/1024/1024, (float(s.f_bavail)/float(s.f_blocks))
#except OSError, e:
#print(e)
else:
return 1.00, 1.00
def freeSpaceOK():
global lastFSCheck
drive = SETUP.get('setup', 'drive')
limit = SETUP.get('setup', 'freepercent')
if lastFSCheck == False:
lastFSCheck = datetime.now()
elif datetime.now()-lastFSCheck > timedelta(seconds=900):
#if we haven't run this check in the last 15 minutes, then run it, otherwise it's too soon!
free, percent = getDriveInfo(drive)
out('DEBUG','Free HD space: %s' %str(free))
if percent > limit: #if we are still within the limit
return True
else:
return False
else: #if we've already checked within the last 15 minutes
return True
def dlCookie(downloadID, site, cj, target, network=False, name=''):
'''download using login/cookie technique.
Returns 'preset' if a presetcookie is missing or malformatted,
Returns 'password' if the password seems to be wrong
Returns 'moved' if the download of the torrent file retrieves a redirect
Returns 'httperror' for any httperror encountered
Returns 'downloadtype' if the downloadtype is not set in regex.conf
Returns 'passkey' if the passkey is not set in credentials.conf
Returns an urllib2.urlopen object if a 200/ok was received.
'''
#see if there is a cookie already created.
G.LOCK.acquire()
if 'downloadtype' in G.NETWORKS[site]['regex']:
downloadType = G.NETWORKS[site]['regex']['downloadtype']
else:
out('ERROR','Download type is not set in regex.conf for %s' %site, site)
G.LOCK.release()
return 'downloadtype'
if downloadType != '5':
if not os.path.isfile(os.path.join(G.SCRIPTDIR,'cookies',site+'.cookie')):
G.LOCK.release()
#check to make sure this isn't a site that needs a preset cookie.
if 'presetcookie' in G.NETWORKS[site]['regex'] and G.NETWORKS[site]['regex']['presetcookie'] == '1':
out('ERROR','This tracker requires you to manually create a cookie file before you can download.',site)
return 'preset'
else:
#if not, log in and create one
cj = createCookie(site, cj)
if not cj:
return 'password'
else:
#load the cookie since it exists already
try:
cj.load(os.path.join(G.SCRIPTDIR,'cookies',site+'.cookie'), ignore_discard=True, ignore_expires=True)
G.LOCK.release()
except cookielib.LoadError:
if 'presetcookie' in G.NETWORKS[site]['regex'] and G.NETWORKS[site]['regex']['presetcookie'] == '1':
out('ERROR','The cookie for %s is the wrong format'%site,site)
G.LOCK.release()
return 'preset'
else:
G.LOCK.release()
cj = createCookie(site, cj)
if not cj:
return 'password'
else:
G.LOCK.release()
if not 'passkey' in G.NETWORKS[site]['creds'] or ('passkey' in G.NETWORKS[site]['creds'] and G.NETWORKS[site]['creds']['passkey'] == ''):
out('ERROR','This site requires the passkey to be set in credentials.conf')
return 'passkey'
#create the downloadURL based on downloadType
if downloadType == '1': # request a download ID, and get a filename
downloadURL = G.NETWORKS[site]['regex']['downloadurl'] + downloadID
elif downloadType == '2':
downloadURL = G.NETWORKS[site]['regex']['downloadurl'] + '/' + downloadID + '/' + downloadID + '.torrent'
elif downloadType == '3':
downloadURL = G.NETWORKS[site]['regex']['downloadurl'] + '/' + downloadID + '/' + G.NETWORKS[site]['regex']['urlending']
elif downloadType == '4':
downloadURL = G.NETWORKS[site]['regex']['downloadurl'] + downloadID + G.NETWORKS[site]['regex']['urlending'] + downloadID + '.torrent'
elif downloadType == '5':
downloadURL = G.NETWORKS[site]['regex']['downloadurl'] + '/' + downloadID + '/' + G.NETWORKS[site]['creds']['passkey'] + '/' + name + '.torrent'
#set the socket timeout
socket.setdefaulttimeout(25)
handle = None
try:
handle = getFile(downloadURL,cj)
except urllib2.HTTPError, e:
if int(e.code) in (301,302,303,307):
print 'Caught a redirect. Code: %s, url: %s, headers %s, others: %s' %(e.code, e.url, e.headers.dict, e.__dict__.keys())
return 'moved'
else:
print 'Caught another http error. Code: %s, url: %s, headers %s, others: %s' %(e.code, e.url, e.headers.dict, e.__dict__.keys())
return 'httperror'
else:
return handle
def download(downloadID, site, location=False, network=False, target=False, retries=0, email=False, notify=False, filterName=False, announce=False, formLogin=False, sizeLimits=False, name=False, fromweb=False):
"""Take an announce download ID and the site to download from, do some magical stuff with cookies, and download the torrent into the watch folder
Returns a tuplet with (True/False, statusmsg)"""
out('DEBUG', 'Downloading ID: %s, site: %s, filter: %s, location: %s, network: %s, target: %s, retries: %s, email: %s, announce %s, name %s'%(downloadID, site, filterName, location, network, target, retries, email, announce, name))
success = False
error = ''
statusmsg = ''
G.LOCK.acquire()
#load where we should be saving the torrent if not already set
if not location:
location = SETUP.get('setup', 'torrentdir')
if 'watch' in G.NETWORKS[site]['creds'] and G.NETWORKS[site]['creds']['watch'] != '':
location = G.NETWORKS[site]['creds']['watch']
#'network' is only sent if it's a manual download, so if it's false that means this is an automatic dl
#if it's automatic, then check to see if the delay exists
sleepi = None
if retries == 0 and not network and not fromweb:
if SETUP.has_option('setup', 'delay') and SETUP.get('setup', 'delay').lstrip().rstrip() != '':
sleepi = int(SETUP.get('setup', 'delay'))
#check if the network requires a torrentname for downloading
if 'downloadtype' in G.NETWORKS[site]['regex'] and G.NETWORKS[site]['regex']['downloadtype'] == '5':
if 'nameregexp' in G.NETWORKS[site]['regex'] and G.NETWORKS[site]['regex']['nameregexp'] != '':
if not name:
if announce:
name = re.match(G.NETWORKS[site]['regex']['nameregexp'],announce).group(1)
else:
error = 'The download function for this site can only be used for the button and automatic downloads.'
else:
error = 'This site requires the variable \'nameregexp\' to be set in regex.conf.'
G.LOCK.release()
file_info = False
retreived = ''
if not error:
if sleepi: time.sleep(sleepi)
#if this is a retry, then wait 3 seconds.
if retries > 0:
if not network and not fromweb:
time.sleep(3)
else:
time.sleep(0.5)
cj = cookielib.LWPCookieJar()
#use the cookie to download the file
retreived = dlCookie(downloadID, site, cj, target, network, name)
if str(type(retreived)) == "<type 'instance'>":
file_info = retreived.info()
retry = False
if file_info:
if file_info.type == 'text/html':
#This could either mean the torrent doesn't exist or we are not logged in
G.LOCK.acquire()
if 'presetcookie' in G.NETWORKS[site]['regex'] and G.NETWORKS[site]['regex']['presetcookie'] == '1':
statusmsg = 'There was an error downloading torrent %s from %s. Either it was deleted, or the cookie you entered is incorrect.'%(downloadID, site)
else:
statusmsg = 'There was an error downloading torrent %s from %s. Either it was deleted, or the credentials you entered are incorrect.'%(downloadID, site)
G.LOCK.release()
retry = True
elif file_info.type == 'application/x-bittorrent':
#figure out the filename
#see if the file has content disposition, if it does read it.
info = retreived.read()
try:
tp = torrentparser(debug=False, content=info)
mbsize = tp.mbsize()
tpname = tp.name()
except SyntaxError, e:
out('ERROR','The torrentparser was unable to parse the torrent file. Please let blubba know: %s' %e,site=site)
mbsize = None
tpname = None
if not name:
if tpname:
filename = tpname
else:
if 'Content-Disposition' in file_info:
for cd in G.CD:
if cd in file_info['Content-Disposition']:
filename = file_info['Content-Disposition'].replace(cd,'').replace('"','')
if filename == '':
filename = downloadID+'.torrent'
else:
filename = name
if '.torrent' not in filename: filename += '.torrent'
filename = urllib.unquote(filename)
sizeOK = True
if sizeLimits and not (network or fromweb):
sizerange = sizeLimits.split(',')
if mbsize:
G.LOCK.acquire()
if (len(sizerange) == 1 and mbsize > float(sizerange[0])) or (len(sizerange) == 2 and mbsize > float(sizerange[1])):
out('INFO', "(%s) Torrent is larger than required by filter '%s'."%(downloadID,filterName),site)
sizeOK = False
elif len(sizerange) == 2 and mbsize < float(sizerange[0]):
sizeOK = False
out('INFO', "(%s) Torrent is smaller than required by '%s'."%(downloadID,filterName),site)
else:
out('INFO', "(%s) Torrent is within size range required by filter '%s'."%(downloadID,filterName),site)
G.LOCK.release()
elif not (network or fromweb):
G.LOCK.acquire()
out('INFO', '(%s) No Size check.'%downloadID,site)
G.LOCK.release()
if sizeOK:
G.LOCK.acquire()
try:
local_file = open(os.path.join(location, filename),'wb')
local_file.write(info)
local_file.close()
except IOError:
#If there's no room on the hard drive
out('ERROR', '(%s) !! Disk quota exceeded. Not enough room for the torrent!'%downloadID,site)
statusmsg = 'Can\'t write the torrent file on the disk, as there is not enough free space left!'
retry = True
else:
#if the filesize of the torrent is too small, then retry in a moment
if 100 > int(os.path.getsize(os.path.join(location, filename))):
statusmsg = 'The size of the torrent is too small. Maybe try a different torrent of this tracker to see if this is a local or global occurance.'
retry = True
else:
success = True
if mbsize:
statusmsg = 'Torrent (id: %s) successfully downloaded! Size %.2f MB, retries: %d, filename: %s' %(str(downloadID),mbsize,retries,filename)
else:
statusmsg = 'Torrent (id: %s) successfully downloaded! Retries: %d, filename: %s' %(str(downloadID),retries,filename)
G.LOCK.release()
else:
statusmsg = 'The torrent size did not fit the filter.'
else:
out('ERROR','unknown filetype received: %s' %file_info.type, site)
retry = True
elif error:
statusmsg = error
else:
if retreived == 'preset':
statusmsg = 'This site requires a cookie to be preset, called \'%s.torrent\' in the folder \'cookies\'. Either this cookie is missing or malformatted.' %site
elif retreived == 'password':
statusmsg = 'The login credentials set in credentials.conf for %s are incorrect or missing.' %site
#retry = True
elif retreived == 'moved':
statusmsg = 'Either the torrent id (%s) does not exist or your credentials for %s are wrong or missing' %(str(downloadID),site)
retry = True
elif retreived == 'httperror':
statusmsg = 'An http error occured. Please check if the site is online, and check the log for more details if this problem persists.'
retry = True
elif retreived == 'downloadtype':
statusmsg = 'The key \'downloadType\' is not set in regex.conf. Aborting'
elif retreived == 'passkey':
statusmsg = 'This site requires the passkey to be set in credentials.conf. Please set it and try again.'
if retry and retries <= 0:
G.LOCK.acquire()
if not 'presetcookie' in G.NETWORKS[site]['regex'] or ( 'presetcookie' in G.NETWORKS[site]['regex'] and not G.NETWORKS[site]['regex']['presetcookie'] == '1'):
if os.path.isfile(os.path.join(G.SCRIPTDIR,'cookies',site+'.cookie')):
os.remove(os.path.join(G.SCRIPTDIR,'cookies',site+'.cookie'))
else:
out('ERROR','The cookie file doesn\'t exist here... this should not happen!',site)
out('INFO','(%s) !! Torrent file is not ready to be downloaded. Trying again in a moment. Reason: %s'%(downloadID,statusmsg),site)
G.LOCK.release()
return download(downloadID, site, location=location, network=network, target=target, retries=retries+1, email=email, notify=notify, filterName=filterName, announce=announce, formLogin=formLogin, sizeLimits=sizeLimits, name=name, fromweb=fromweb)
elif success:
G.LOCK.acquire()
out('INFO','%s to %s'%(statusmsg,location),site)
if email:
sendEmail(site, announce, filterName, filename)
if notify:
sendNotify(site, announce, filterName, filename)
if network:
network.sendMsg(statusmsg, target)
G.LOCK.release()
return (True, statusmsg)
else:
#did not succeed in downloading!
G.LOCK.acquire()
out('ERROR','Download error (%s): %s'%(downloadID,statusmsg),site)
if network:
network.sendMsg('Download error (%s:%s): %s'%(site,downloadID,statusmsg), target)
G.LOCK.release()
return (False, statusmsg)
def getFile(downloadURL, cj):
#create the opener
if SETUP.get('setup','verbosity').lower() == 'debug':
opener = build_opener(cj, debug=1)
else:
opener = build_opener(cj)
urllib2.install_opener(opener)
req = urllib2.Request(downloadURL)
req.add_header("User-Agent", "pywa")
return urllib2.urlopen(req)
def createCookie(site, cj):
urlopen = urllib2.urlopen
Request = urllib2.Request
#opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
if SETUP.get('setup','verbosity').lower() == 'debug':
opener = build_opener(cj, debug=1)
else:
opener = build_opener(cj)
urllib2.install_opener(opener)
G.NETWORKS[site]['regex']
if 'loginuserpost' in G.NETWORKS[site]['regex'] and G.NETWORKS[site]['regex']['loginuserpost'] != '':
userpost = G.NETWORKS[site]['regex']['loginuserpost']
else:
userpost = 'username'
if 'loginpasswordpost' in G.NETWORKS[site]['regex'] and G.NETWORKS[site]['regex']['loginpasswordpost'] != '':
passpost = G.NETWORKS[site]['regex']['loginpasswordpost']
else:
passpost = 'password'
httpdict = {userpost : G.NETWORKS[site]['creds']['username'], passpost : G.NETWORKS[site]['creds']['password'] }
if 'morepostdata' in G.NETWORKS[site]['regex'] and G.NETWORKS[site]['regex']['morepostdata'] != '':
try:
newdict = eval("{"+ G.NETWORKS[site]['regex']['morepostdata'] + "}")
except SyntaxError:
out('ERROR', 'morepostdata variable raised a syntax error %s' %G.NETWORKS[site]['regex']['morepostdata'], site=site)
httpdict.update(newdict)
if site == 'passthepopcorn':
httpdict['passkey'] = G.NETWORKS[site]['creds']['passkey']
http_args = urllib.urlencode(httpdict)
#http_args = urllib.urlencode(dict(username=G.NETWORKS[site]['creds']['username'], password=G.NETWORKS[site]['creds']['password']))
req = Request(G.NETWORKS[site]['regex']['loginurl'], http_args)
req.add_header("User-Agent", "pywa")
if site == "whatcd":
req.add_header('Referer', 'https://what.cd/login.php')
out('INFO','Logging into %s because a cookie was not previously saved or is outdated.'%site,site=site)
handle = None
try:
handle = urlopen(req)
except urllib2.HTTPError, e:
print 'Caught a redirect. Code: %s, url: %s, headers %s, others: %s' %(e.code, e.url, e.headers.dict, e.__dict__.keys())
#print cj
G.LOCK.acquire()
cj.save(os.path.join(G.SCRIPTDIR,'cookies',site+'.cookie'), ignore_discard=True, ignore_expires=True)
G.LOCK.release()
return cj
if handle and 'login200' in G.NETWORKS[site]['regex'] and G.NETWORKS[site]['regex']['login200'] == '1':
G.LOCK.acquire()
cj.save(os.path.join(G.SCRIPTDIR,'cookies',site+'.cookie'), ignore_discard=True, ignore_expires=True)
G.LOCK.release()
return cj
elif handle and 'loginjson' in G.NETWORKS[site]['regex'] and G.NETWORKS[site]['regex']['loginjson'] == '1':
import json
try:
result = json.loads(handle.read())
except ValueError:
out('ERROR', 'Invalid JSON returned on login attempt', site)
return
if 'Result' in result and result['Result'] == 'Error':
if 'Message' in result:
out('ERROR', "Result: %s, Message: %s" % (result['Result'],result['Message']), site)
else:
out('ERROR', "Result: %s " % result['Result'], site)
elif 'Result' in result and result['Result'] == 'Ok':
G.LOCK.acquire()
cj.save(os.path.join(G.SCRIPTDIR,'cookies','%s.cookie' % site), ignore_discard=True, ignore_expires=True)
G.LOCK.release()
return cj
elif handle:
#print "----"
#print handle.read()
#print "----"
#print handle.info()
out('ERROR','Password seems to be incorrect',site)
return False
else:
out('ERROR','We don\'t have a redirect but still data? How can that happen?',site)
def build_opener(cj, debug=False):
http_handler = urllib2.HTTPHandler(debuglevel=debug)
https_handler = urllib2.HTTPSHandler(debuglevel=debug)
cookie_handler = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(http_handler, https_handler, cookie_handler, smartredirecthandler())
opener.cookie_jar = cj
return opener
class smartredirecthandler(urllib2.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, hdrs, newurl):
out('DEBUG','Redirect received. stuff: %s, %s, %s' %(code,msg,newurl))
return None
def sendEmail(site, announce, filter, filename):
# Imports
import smtplib
from email.mime.text import MIMEText
#create the message
# msg = 'pyWA has detected a new download.\n\nSite: %(site)s\nCaptured Announce: %(announce)s\nMatched Filter: %(filter)s\nSaved Torrent: %(filename)s'%{'filename':filename, 'filter':filter, 'site':site, 'announce':announce}
msg = MIMEText('pyWA has detected a new download.\n\nSite: %(site)s\nCaptured Announce: %(announce)s\nMatched Filter: %(filter)s\nSaved Torrent: %(filename)s'%{'filename':filename, 'filter':filter, 'site':site, 'announce':announce})
gmail = SETUP.get('notification','gmail')
msg['Subject'] = 'pyWA: New %s download!'%site
# Send the message via our own SMTP server
s = smtplib.SMTP("smtp.gmail.com", 587)
s.ehlo()
s.starttls()
s.ehlo()
#s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
try:
out('INFO','Emailing %s with a notification.'%gmail)
s.login(gmail, SETUP.get('notification','password'))
s.sendmail(gmail, gmail, msg.as_string())
s.quit()
except Exception, e:
out('ERROR', 'Could not send notify email. Error: %s'%e.smtp_error)
def sendNotify(site, announce, filter, filename):
sent = False
for net in G.RUNNING.itervalues():
#G.NETWORKS[bot.getBotName()]
if net.getBotName() == SETUP.get('notification', 'server'):
out('INFO', 'Messaging %s with an IRC notification.'%SETUP.get('notification', 'nick'))
net.sendMsg('New DL! Site: %(site)s, Filter: %(filter)s, File: %(file)s '%{'site':site, 'filter':filter,'file':filename}, SETUP.get('notification', 'nick'))
sent = True
if not sent:
out('ERROR','Could not send notification via %s, because I am not connected to that network'%SETUP.get('notification', 'server'))
class WebServer( Thread ):
def __init__(self, loadloc, pw, port, ip=''):
global webpass
Thread.__init__(self)
self.loadloc = loadloc
self.ip = ip
try:
self.port = int(port)
except ValueError:
out('WARNING', 'Bad webserver port, could not start webserver')
raise Exception('Could not start webserver')
if pw != '':
webpass = pw
else:
webpass = str(random.randint(10**5,10**9))
out('ERROR','No webserver password set. Assigning a random one: %s'%webpass)
def run(self):
global CONN, C
CONN = sqlite3.connect(os.path.join(self.loadloc, 'example.db'))
#CONN = sqlite3.connect(":memory:")
C = CONN.cursor()
self.server = ThreadedHTTPServer((self.ip, int(self.port)), MyHandler)
print 'started httpserver...'
self.server.serve_forever()
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
'''Handles requests in threads'''
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
error = False
try:
if self.path.split('?')[0].lower().endswith(".pywa"):
if self.path.startswith("/dl"):
arg = self.path.split("?")
if len(arg)>1:
arg = arg[1].split('&')
args = dict()
for a in arg:
b = a.split('=')
if len(b)>1:
args[b[0]] = b[1]
print args
else:
error = True
if not error:
if 'pass' in args and args['pass'] == webpass:
if 'id' in args and args['id'] != "":
id = args['id']
if 'site' in args and args['site'].lower() in G.FROMALIAS:
site = G.FROMALIAS[args['site'].lower()]
out('INFO',"WebUI download request for id %s received from %s"%(args['id'], self.client_address[0]),site)
if 'name' in args:
name = args['name']
else:
name = None
try:
if 'buttonwatch' in G.NETWORKS[site]['creds']:
loc = G.NETWORKS[site]['creds']['watch']
elif SETUP.has_option('setup','buttonwatch') and SETUP.get('setup', 'buttonwatch') != '':
loc = SETUP.get('setup', 'buttonwatch')
else:
loc = None
output = download(id, site, location=loc, name=name, fromweb=True)
except Exception as e:
outexception('Error while downloading %s from web, error: %s' %(str(id),str(e)),site)
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
if output[0]:
self.wfile.write("<html><head><script>t = null;function moveMe(){t = setTimeout(\"self.close()\",10000);}</script></head><body onload=\"moveMe()\">")
self.wfile.write("%s" %output[1])
self.wfile.write("</body></html>")
else:
self.wfile.write("<html><head></head>")
self.wfile.write("%s" %output[1])
self.wfile.write("</body></html>")
else:
#unknown/no site name
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write("<html><head></head>")
self.wfile.write("Incorrect sitename.")
self.wfile.write("</body></html>")
else:
#no ID supplied
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write("<html><head></head>")
self.wfile.write("Torrentid missing.")
self.wfile.write("</body></html>")
else:
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write("Incorrect password supplied. Try again.")
out('WARNING','Received a webUI download command with the wrong password from ip %s' %self.client_address[0])