-
Notifications
You must be signed in to change notification settings - Fork 1
/
rssdler.py
executable file
·2320 lines (2206 loc) · 109 KB
/
rssdler.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 -*-
"""An RSS broadcatching script
(podcasts, videocasts, torrents, or, if you really wanted, web pages."""
from __future__ import division
__version__ = u"0.4.2"
__author__ = u"""lostnihilist <lostnihilist _at_ gmail _dot_ com> or
"lostnihilist" on #[email protected]"""
__copyright__ = u"""RSSDler - RSS Broadcatcher
Copyright (C) 2007, 2008, lostnihilist
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; under version 2 of the license.
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."""
import codecs
import ConfigParser
import cookielib
import email
import getopt
import httplib
import logging
import mimetypes
import operator
import os
import pickle
try: import random
except ImportError: random = None
import re
import signal
import sgmllib
import socket
import StringIO
import sys
import time
import traceback
import urllib
import urllib2
import urlparse
try: import xml.dom.minidom as minidom
except ImportError: minidom = None
if not sys.path.count(''): sys.path.insert(0, '')
import feedparser
try: import mechanize
except ImportError: mechanize = None
# # # # #
# == Globals ==
# # # # #
# Reminders of potential import globals elsewhere.
resource = None #daemon
userFunctions = None
sqlite3 = None #Firefox3 cookies
# Rest of Globals
configFile = os.path.expanduser(os.path.join('~','.rssdler', 'config.txt'))
downloader = None
rss = None
saved = None
MAXFD = 1024
_action = None
_configInstance = None
_runOnce = None
_USER_AGENT = u"RSSDler %s" % __version__
# ~ defined helps with feedburner feeds
percentQuoteDict = {u'!': u'%21', u' ': u'%20', u'#': u'%23', u'%': u'%25',
u'$': u'%24', u"'": u'%27', u'&': u'%26', u')': u'%29', u'(': u'%28',
u'+': u'%2B', u'*': u'%2A', u',': u'%2C', u'=': u'%3D', u'@': u'%40',
u';': u'%3B', u':': u'%3A', u']': u'%5D', u'[': u'%5B', u'?': u'%3F',
u'!':u'%7E'}
percentunQuoteDict = dict(((j,i) for (i,j) in percentQuoteDict.items()))
netscapeHeader= """# HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This is a generated file! Do not edit.\n\n"""
commentConfig = u"""# default config filename is config.txt in ~/.rssdler
# lines (like this one) starting with # are comments and
# will be ignored by the config parser
# the only required section (though the program won't do much without others)
# sections are denoted by a line starting with [
# then the name of the section, then ending with ]
# so this is the global section
[global]
# download files to this directory. Defaults to the working directory.
downloadDir = /home/user/downloads
# makes this the 'working directory' of RSSDler. anytime you specify a filename
# without an absolute path, it will be relative to this, this s the default:
workingDir = /home/user/.rssdler
# if a file is smaller than this, it will not be downloaded.
# if filesize cannot be determined, this is ignored.
# Specified in MB. Remember 1024 MB == 1GB
# 0 means no minimum, as does "None" (w/o the quotes)
minSize = 10
# if a file is larger than this, it will not be downloaded. Default is None
# though this line is ignored because it starts with a #
# maxSize = None
# write messages to a log file. 0 is off, 1 is just error messages,
# 3 tells you when yo download something, 5 is very, very wordy. (default = 0)
log = 0
# where to write those log messages (default 'downloads.log')
logFile = downloads.log
# like log, only prints to the screen (errors to stderr, other to stdout)
# default 3
verbose = 3
# the place where a cookie file can be found. Default None.
cookieFile = /home/user/.mozilla/firefox/user/cookies.txt
# type of cookie file to be found at above location. default MozillaCookieJar
cookieType = MozillaCookieJar
# other possible types are:
# LWPCookieJar, Safari, Firefox3, KDE
# only works if urllib = False and mechanize is installed
# cookieType = MSIECookieJar
#how long to wait between checking feeds (in minutes). Default 15.
scanMins = 10
# how long to wait between http requests (in seconds). Default 0
sleepTime = 2
# to exit after scanning all the feeds, or to keep looping. Default False.
runOnce = True
# set to true to avoid having to install mechanize.
# side effects described in help. Default False.
# will fallback to a sane value if mechanize is not installed
urllib = True
# the rest of the global options are described in the help,
# let's move on to a thread
###################
# each section represents a feed, except for the one called global.
# this is the thread: somesite
###################
[somesite]
# just link to the feed
link = http://somesite.com/rss.xml
# Default None, defers to maxSize in global, otherwise,
# files larger than this size (in MB) will not be downloaded
# only applies to the specific thread
# if set to 0, means no maximum and overrides global option
maxSize = 2048
# like maxSize, only file smaller than this will not be downloaded
# if set to 0, means no minimum, like maxSize. in MB.
minSize = 10
# if specified, will download files in this thread to this directory
directory = /home/user/someotherfiles
# if you do not know what regular expressions are, stop now, do not pass go,
# do not collect USD200 (CAN195)
# google "regular expressions tutorial" and find one that suits your needs
# one with an emphasis on Python may be to your advantage
# Now, without any of the download<x> or regEx options (detailed below)
# every item in the rss feed will be downloaded,
# provided that it has not previously been downloaded
# all the regular expression should be specified in lower case
# (except for character classes and other special regular expression characters,
# if you know what that means)
# as the string that it is searched against is set to lower case.
# Starting with regExTrue (RET)
# let's say we want to make sure there are two numbers,
# separated by something not a number
# for everything we download in this thread.
regExTrue = \d[^\d]+\d
# the default value, None, makes RET ignored
# regExTrue = None
# but we want to make sure we don't get anything with nrg or ccd in the name
# because those are undesirable formats, but we want to make sure to not match
# a name that may have those as a substring e.g. enrgy
# (ok, not a great example, come up with something better and I'll include it)
# REF from now on (\b indicates a word boundary)
regExFalse = (\bnrg\b|\bccd\b)
# the default value, which means it will be ignored
# regExFalse = None
# at this point, as long as the file gets a positive hit in RET
# and no hit in REF, the file will be downloaded
# equivalently said, RET and REF are necessary and sufficient conditions.
# lengthy expressions can be constructed
# to deal with every combination of things you want, but there is
# a looping facility to allow us to get more fine grained control
# over the items we want to grab without having to have hundreds
# of characters on a single line, which of course gets rather unreadable
# making use of this looping facility makes RET and REF neccessary
# (though that can be bypassed too, more later) conditions
# however, they are no longer sufficient....
# download<x> is like regExTrue, but begins the definition of an 'item' and
# we can associate further actions with it if we so choose
# put a non-negative integer where <x> goes
download1 = ubuntu
# but say we love ubuntu, and want to always grab everything that mentions it
# so we want to ignore regExTrue, this 'bypasses' RET when set to False.
# Default True.
download1True = False
# we could also bypass REF. but we really don't like nrg,
# but we'll deal with ccd's, just for ubuntu
# to be clear, download<x>False is a mixed type option,
# taking both True, False for dealing with the global REF
# or a string (like here) to specify what amounts to a 'localized REF',
# which effectively says False to the global REF
# while at the same time specifying the local REF
download1False = \\bnrg\\b
# with %()s interpolation, we can effectively add on to REF in a basic manner
# say for Ubuntu, we don't want want the 'hoary version,
download1False = hoary.*%(regExFalse)s
# this will insert the value for regExFalse in place of the %()s expression
# resulting in: hoarsy.*(\bnrg\b|\bccd\b)
# note the parantheses are there b/c they are in the original REF
# we don't want to download things like howto, md5 files, etc,
# so we can set a minSize (MB)
# this overrides the global/thread minSize when not set to None
# Default None. works like thread-based minSize.
# a maxSize option is also available
download1MinSize = 10
download1MaxSize = 750
# and finally, we can put our ubuntu stuff in a special folder, if we choose
download1Dir = /home/user/ubuntustuff
# note that the numbers are not important
# as long as the options correspond to each other
# there is no download2, and that is ok.
download3 = fedora
# you have to have the base setting to have the other options
# this will not work b/c download4 is not specified
# download4Dir = /home/user/something
"""
configFileNotes = u"""There are two types of sections: global and threads.
There can be as many thread sections as you wish, but only one global section.
global must be named "global." Threads can be named however you wish,
except 'global,' and each name should be unique.
With a couple of noted exceptions, there are three types of options:
Boolean Options: 'True' is indicated by "True", "yes", or "1".
"False" is indicated by "False", "no", or "0" (without the quotes)
Integer Options: Just an integer. 1, 2, 10, 2348. Not 1.1, 2.0, 999.3 or 'a'.
String Options: any string, should make sense in terms of the option
being provided (e.g. a valid file/directory on disk; url to rss feed)
Required indicates RSSDler will not work if the option is not set.
Recommended indicates that the default is probably not what you want.
Optional is not necessarily not recommended, just each case determines use
Run with --comment-config to see what a configuration file would look like.
e.g. rssdler --comment-config > .config.txt.sample
"""
cliOptions = u"""Command Line Options:
--config/-c can be used with all the options except --comment-config, --help
--comment-config: Prints a commented config file to stdout
--help/-h: print the short help message (command line options)
--full-help/-f: print the complete help message (quite long)
--run/-r: run according to the configuration file
--runonce/-o: run only once then exit
--daemon/-d: run in the background (Unix-like only)
--kill/-k: kill the currently running instance (may not work on Windows)
--config/-c: specify a config file (default %s).
--list-failed: Will list the urls of all the failed downloads
--purge-failed: Use to clear the failed download queue.
Use when you have a download stuck (perhaps removed from the site or
wrong url in RSS feed) and you no longer care about RSSDler attempting
to grab it. Will be appended to the saved download list to prevent
readdition to the failed queue.
Should be used alone or with -c/--config. Exits after completion.
--list-saved: Will list everything that has been registered as downloaded.
--purge-saved: Clear the list of saved downloads, not stored anywhere.
--state/-s: Will return the process ID if another instance is running with.
Otherwise exits with return code 1
Note for Windows: will return the pid found in daemonInfo,
regardless of whether it is currently running.
--set-default-config: [No longer available. Deprecated]
""" % configFile
nonCoreDependencies = u"""Non-standard Python libraries used:
feedparser: [REQUIRED] http://www.feedparser.org/
mechanize: [RECOMMENDED] http://wwwsearch.sourceforge.net/mechanize/
For debian based distros:
"sudo apt-get install python-feedparser python-mechanize"
"""
securityIssues = u"""Security Note:
I keep getting notes about people running as root. DO NOT DO THAT!
"""
# # # # #
#Exceptions
# # # # #
class Locked( Exception ):
def __init__(self, value=u"""An lock() on savefile failed.""" ):
self.value = value
def __str__(self): return repr( self.value)
# # # # #
#String/URI Handling
# # # # #
def unicodeC( s ):
if not isinstance(s, basestring):
try:
s= unicode(s) # __str__ for exceptions etc
except:
s= unicode(s.__str__(), errors='ignore')
if isinstance(s, str): s = unicode(s, 'utf-8', 'replace')
if not isinstance(s, unicode):
raise UnicodeEncodeError(u'could not encode %s to unicode' % s)
return s
def xmlUnEscape( sStr, percent=0, pd=percentunQuoteDict ):
u"""xml unescape a string, by default also checking for percent encoded
characters. set percent=0 to ignore percent encoding.
can specify your own percent quote dict
(key, value) pairs are of (search, replace) ordering with percentunQuoteDict
"""
sStr = sStr.replace("<", "<")
sStr = sStr.replace(">", ">")
if percent: sStr = percentUnQuote( sStr, pd )
sStr = sStr.replace("&", "&")
return sStr
def percentIsQuoted(sStr, testCases=percentQuoteDict.values()):
u"""does not include query string or page marker (#) in detection.
these seem to cause the most problems.
Specify your own test values with testCases
"""
for i in testCases:
if sStr.count(i): return True
return False
def percentNeedsQuoted(sStr, testCases=percentQuoteDict.keys()):
u"""if there is a character in the path part of the url that is 'reserved'
"""
for aStr in urlparse.urlparse(sStr)[:4]:
for i in testCases:
if aStr.count(i): return True
return False
def percentUnQuote( sStr, p=percentunQuoteDict, reserved=('%25',) ):
u"""percent unquote a string.
reserved is a sequence of strings that should be replaced last.
it needs have a key in p, with a value to replace it with. will be
replaced in order of the sequence"""
for search in p:
if search in reserved: continue
sStr = sStr.replace( search, p[search] )
for search in reserved:
sStr = sStr.replace( search, p[search])
return sStr
def percentQuote(sStr, urlPart=(2,), pd=percentQuoteDict):
u"""quote the path part of the url.
urlPart is a sequence of parts of the urlunparsed entries to quote"""
urlList = list( urlparse.urlparse(sStr) )
for i in urlPart: urlList[i] = urllib.quote( urlList[i].encode('utf-8') )
return unicodeC(urlparse.urlunparse( urlList ))
def unQuoteReQuote( url, quote=1 ):
u"""fix urls from feedparser. they are not always properly unquoted
then unescaped. will requote by default"""
logging.debug(u"unQuoteReQuote %s" % url)
if percentIsQuoted(url): url = xmlUnEscape( url, 1 )
else: url = xmlUnEscape( url, 0 )
if quote: url = percentQuote( url )
return url
def encodeQuoteUrl( url, encoding='utf-8'):
u"""take a url, percent quote it, if necessary and encode the string
to encoding, default utf-8"""
if not percentIsQuoted(url) and percentNeedsQuoted(url):
logging.debug( u"quoting url: %s" % url)
url = percentQuote( url )
logging.debug( u"encoding url %s" % url)
try: url = url.encode(encoding)
except UnicodeEncodeError:
logging.critical( ''.join((traceback.format_exc(),os.linesep,url)))
return None
return url
class htmlUnQuote(sgmllib.SGMLParser):
from htmlentitydefs import entitydefs
def __init__(self, s=None):
sgmllib.SGMLParser.__init__(self)
self.result = ""
if s: self.feed(s)
def handle_entityref(self, name):
if self.entitydefs.has_key(name): x = ';'
else: x = ''
self.result = "%s&%s%s" % (self.result, name, x)
def handle_data(self, data):
if data: self.result += data
def natsorted(seq, case=False):
"""Returns a copy of seq, sorted by natural string sort. local is faster
Inner functions modified from:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/285264"""
def try_int(s):
"Convert to integer if possible."
try: return int(s)
except (TypeError, ValueError): return s
def natsort_key(s): return map(try_int, re.findall(r'(\d+|\D+)', s))
def natcmp(a, b): return cmp(natsort_key(a), natsort_key(b))
def natcmpcase(a,b): return natcmp(a.lower(), b.lower())
if case: return sorted(seq, cmp=natcmpcase)
else: return sorted(seq, cmp=natcmp)
# # # # #
# Network Communication
# # # # #
def getFilenameFromHTTP(info, url):
u"""info is an http header from the download,
url is the url to the downloaded file (responseObject.geturl() )."""
filename = None
logging.debug(u"determining filename")
filename = email.message_from_string(unicodeC(info).encode('utf-8')).get_filename(failobj=False)
if filename:
m = htmlUnQuote(filename)
if m.result: filename = m.result
logging.debug(u"filename from content-disposition header")
return unicodeC( filename )
logging.debug(u"filename from url")
filename = percentUnQuote( urlparse.urlparse( url )[2].split('/')[-1] )
try: typeGuess = info.gettype()
except AttributeError: typeGuess = None
typeGuess1 = mimetypes.guess_type(filename)[0]
if typeGuess and typeGuess1 and typeGuess == typeGuess1: pass
elif typeGuess: # trust server content-type over filename
logging.debug(u"getting extension from content-type header")
fileExt = mimetypes.guess_extension(typeGuess)
if fileExt: # sloppy filename guess, probably will never get hit
if not filename:
logging.debug(u"""never guessed filename, just setting it to the\
time""")
filename = unicodeC( int(time.time()) ) + fileExt
else: filename += fileExt
elif 'content_type' not in info:
msg = (
u"""Proper file extension could not be determined for the downloaded file:
%s you may need to add an extension to the file for it to work in some programs.
It came from url %s. It may be correct, but I have no way of knowing due to
insufficient information from the server.""" % (filename, url) )
logging.critical( msg)
if not filename:
logging.critical('Could not determine filename for torrent from %s' % url)
return None
if filename.endswith('.obj'): filename = filename[:-4]
return unicodeC( filename)
def convertMoz3ToNet(cookie_file):
"""modified from:
https://addons.mozilla.org/en-US/firefox/discussions/comments.php?DiscussionID=8623"""
conn = sqlite3.connect(cookie_file)
cur = conn.cursor()
cur.execute("""SELECT host, path, isSecure, expiry, name, value FROM \
moz_cookies;""")
s = StringIO.StringIO(netscapeHeader)
s.seek(0,2)
s.writelines( "%s\tTRUE\t%s\t%s\t%d\t%s\t%s\n" % (row[0], row[1],
unicode(bool(row[2])).upper(), row[3], unicode(row[4]), unicode(row[5]))
for row in cur.fetchall())
conn.close()
s.seek(0)
return s
def convertSafariToMoz(cookie_file):
"convert Safari cookies to a Netscape/Mozilla/Firefox format"
if not minidom:
raise ImportError('xml.dom.minidom needed for use of Safari Cookies')
s = StringIO.StringIO(netscapeHeader)
s.seek(0,2)
try: x = minidom.parse(cookie_file)
except IOError: # No xml parsing errors caught.
logging.critical('Cookie file faied to load. Please check for correct path')
s.seek(0)
return s
for cookie in x.getElementsByTagName('dict'):
d = {}
for key in cookie.getElementsByTagName('key'):
keyText = key.firstChild.wholeText.lower()
try: valueText = key.nextSibling.nextSibling.firstChild.wholeText
except AttributeError: valueText = ''
if keyText == 'domain': d['domain'] = valueText
elif keyText == 'path': d['path'] = valueText
elif keyText == 'expires': # ignores HH:MM:SS, etc.: 2018-02-14T15:37:51Z
d['expires'] =str(int(time.mktime(time.strptime(valueText,'%Y-%m-%dT%H:%M:%SZ'))))
elif keyText == 'name': d['name'] = valueText
elif keyText == 'value': d['value'] = valueText
else:
if 5 == len(set(d.keys()).intersection(('domain','path','expires','name','value'))):
d['dspec'] = str(d['domain'].startswith('.')).upper()
s.writelines( "%(domain)s\t%(dspec)s\t%(path)s\tFALSE\t%(expires)s\t%(name)s\t%(value)s\n" % d)
else:
logging.error('there was an error parsing the cookie with these values\n%s' % d)
s.seek(0)
return s
def convertKDEToMoz(cookie_file):
s = StringIO.StringIO(netscapeHeader)
s.seek(0,2)
for line in open(cookie_file,'r').readlines():
line = line.strip()
if (line.startswith('#') or
(line.startswith('[') and line.endswith(']')) or
line == ''):
continue
line = [ x.strip('"') for x in line.split() ]
if line[1] == '': line[1] = line[0]
del line[6], line[4], line[0] #Sec Prot Host
line.insert(2,'FALSE')
line.insert(1, str(line[0].startswith('.')).upper())
s.write('\t'.join(line))
s.write('\n')
s.seek(0)
return s
def cookieHandler():
u"""tries to turn cj into a *CookieJar according to user preferences."""
cj = None
cType = getConfig()['global']['cookieType']
cFile = getConfig()['global']['cookieFile']
netMod = getConfig()['global']['urllib']
m="Cookies disabled. RSSDler will reload the cookies if you fix the problem"
logging.debug(u"""testing cookieFile settings""")
if not cFile: logging.debug(u"""no cookie file configured""")
elif netMod:
logging.debug(u"""attempting to load cookie type: %s""" % cType)
if cType in ['Safari', 'Firefox3','KDE']: cj = cookielib.MozillaCookieJar()
else: cj = getattr(cookielib, cType)()
try:
if cType == 'Firefox3':
cj._really_load(convertMoz3ToNet(cFile), cFile, 0, 0)
elif cType == 'Safari':
cj._really_load(convertSafariToMoz(cFile), cFile, 0, 0)
elif cType == 'KDE':
cj._really_load(convertKDEToMoz(cFile), cFile, 0, 0)
else: cj.load(cFile)
except (cookielib.LoadError, IOError):
logging.critical( traceback.format_exc() + m)
cj = None
else: logging.debug(u"""cookies loaded""")
else:
logging.debug(u"""attempting to load cookie type: %s""" % cType)
if cType in [ 'Safari', 'Firefox3', 'KDE']: cj = mechanize.MozillaCookieJar()
else: cj = getattr(mechanize, cType )()
try:
if cType == 'Firefox3':
cj._really_load(convertMoz3ToNet(cFile), cFile, 0, 0)
elif cType == 'Safari':
cj._really_load(convertSafariToMoz(cFile), cFile, 0, 0)
elif cType == 'KDE':
cj._really_load(convertKDEToMoz(cFile), cFile, 0, 0)
else: cj.load(cFile)
except(mechanize._clientcookie.LoadError, IOError):
logging.critical( traceback.format_exc() + m)
cj = None
else: logging.debug(u"""cookies loaded""")
return cj
def urllib2RetrievePage( url, th=((u'User-agent', _USER_AGENT),)):
u"""URL is the full path to the resource we are retrieve/Posting
th is a sequence of (field,value) pairs of any extra headers
"""
th = [ (x.encode('utf-8'), y.encode('utf-8')) for x,y in th ]
time.sleep( getConfig()['global']['sleepTime'] )
url, urlNotEncoded = encodeQuoteUrl( url, encoding='utf-8' ), url
if not url:
logging.critical(u"""utf encoding, quoting url failed, returning false %s\
""" % url)
return False
if not urllib2._opener:
cj = cookieHandler()
if cj:
logging.debug(u"building and installing urllib opener with cookies")
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj) )
else:
logging.debug(u"building and installing urllib opener without cookies")
opener = urllib2.build_opener( )
urllib2.install_opener(opener)
logging.debug(u"grabbing page at url %s" % urlNotEncoded)
return urllib2.urlopen(urllib2.Request(url, headers=dict(th)))
def mechRetrievePage(url, th=(('User-agent', _USER_AGENT),), ):
u"""URL is the full path to the resource we are retrieve/Posting
txheaders: sequence of tuples of header key, value
"""
th = [ (x.encode('utf-8'), y.encode('utf-8')) for x,y in th ]
time.sleep( getConfig()['global']['sleepTime'] )
url, urlNotEncoded = encodeQuoteUrl( url, encoding='utf-8' ), url
if not url:
logging.critical(u"utf encoding and quoting url failed, returning false")
return False
if not mechanize._opener:
cj = cookieHandler()
if cj:
logging.debug(u"building and installing mechanize opener with cookies")
opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cj),
mechanize.HTTPRefreshProcessor(), mechanize.HTTPRedirectHandler(),
mechanize.HTTPEquivProcessor())
else:
logging.debug(u"building and installing mech opener without cookies")
opener = mechanize.build_opener(mechanize.HTTPRefreshProcessor(),
mechanize.HTTPRedirectHandler(), mechanize.HTTPEquivProcessor())
mechanize.install_opener(opener)
logging.debug(u"grabbing page at url %s" % urlNotEncoded)
return mechanize.urlopen(mechanize.Request(url, headers=dict(th)))
def getFileSize( info, data=None ):
u"""give me the HTTP headers (info) and,
if you expect it to be a torrent file, the actual file,
i'll return the filesize, of type None if not determined"""
logging.debug(u"determining size of file")
size = None
if 'torrent' in info.gettype():
if data:
if hasattr(data, 'read'): data = data.read()
try: tparse = bdecode(data)
except ValueError:
logging.critical(''.join((traceback.format_exc() ,
u"""File was supposed to be torrent data, but could not be bdecoded""")))
return size, data
if 'length' in tparse['info']: size = int(tparse['info']['length'])
elif 'files' in tparse['info']:
size = sum(int(j['length']) for j in tparse['info']['files'])
else:
try:
if 'content-length' in info: size = int(info['content-length'])
except ValueError: pass #
logging.debug(u"filesize seems to be %s" % size)
return size, data
# # # # #
# Check Download
# # # # #
def searchFailed(urlTest):
u"""see if url is in saved.failedDown list"""
for failedItem in getSaved().failedDown:
if urlTest == failedItem['link']: return True
return False
def checkFileSize(size, threadName, downloadDict):
u"""returns True if size is within size constraints specified by config file
takes the size in bytes, threadName and downloadDict (parsed download<x>).
"""
returnValue = True
logging.debug(u"checking file size")
if downloadDict['maxSize'] != None: maxSize = downloadDict['maxSize']
elif getConfig()['threads'][threadName]['maxSize'] != None:
maxSize = getConfig()['threads'][threadName]['maxSize']
elif getConfig()['global']['maxSize'] != None:
maxSize = getConfig()['global']['maxSize']
else: maxSize = None
if maxSize:
maxSize = maxSize * 1024 * 1024
if size > maxSize: returnValue = False
if downloadDict['minSize'] != None: minSize = downloadDict['minSize']
elif getConfig()['threads'][threadName]['minSize'] != None:
minSize = getConfig()['threads'][threadName]['minSize']
elif getConfig()['global']['minSize'] != None:
minSize = getConfig()['global']['minSize']
else: minSize = None
if minSize:
minSize = minSize * 1024 * 1024
if size < minSize: returnValue = False
if returnValue: logging.debug(u"size within parameters")
else: logging.debug(u"size outside parameters")
return returnValue
def checkRegExGTrue(tName, itemNode):
u"""return type True or False if search matches or no, respectively."""
if getConfig()['threads'][tName]['regExTrue']:
logging.debug(u"checking regExTrue on %s" % itemNode['title'])
if getConfig()['threads'][tName]['regExTrueOptions']:
regExSearch = re.compile(
getConfig()['threads'][tName]['regExTrue'],
getattr(re, getConfig()['threads'][tName]['regExTrueOptions']) | re.I )
else:
regExSearch = re.compile(
getConfig()['threads'][tName]['regExTrue'], re.I)
if regExSearch.search(itemNode['title']): return True
else: return False
else: return True
def checkRegExGFalse(tName, itemNode):
u"""return type True or False if search doesn't match or does, respectively.
"""
if getConfig()['threads'][tName]['regExFalse']:
logging.debug(u"checking regExFalse on %s" % itemNode['title'])
if getConfig()['threads'][tName]['regExFalseOptions']:
regExSearch = re.compile(
getConfig()['threads'][tName]['regExFalse'],
getattr(re, getConfig()['threads'][tName]['regExFalseOptions']) | re.I )
else:
regExSearch = re.compile(
getConfig()['threads'][tName]['regExFalse'], re.I)
if regExSearch.search(itemNode['title']): return False
else: return True
else: return True
def checkRegEx(tName, itemNode):
u"""goes through regEx* and download<x> options to see if any of them
provide a positive match. Returns False if Not.
Returns a DownloadItemConfig dictionary if so"""
if getConfig()['threads'][tName]['downloads']:
LDown = checkRegExDown(tName, itemNode)
if LDown: return LDown
else: return False
elif checkRegExGFalse(tName, itemNode) and checkRegExGTrue(tName, itemNode):
return DownloadItemConfig()
else: return False
def checkRegExDown(tName, itemNode):
u"""returns false if nothing found in download<x> to match itemNode.
returns DownloadItemConfig instance otherwise"""
# Also, it's incredibly inefficient
# for every x rss entries and y download items, it runs this xy times.
logging.debug(u"checking download<x>")
for downloadDict in getConfig()['threads'][tName]['downloads']:
if getConfig()['threads'][tName]['regExTrueOptions']:
LTrue = re.compile( downloadDict['localTrue'],
getattr(re, getConfig()['threads'][tName]['regExTrueOptions']) | re.I )
else: LTrue = re.compile(downloadDict['localTrue'], re.I )
if not LTrue.search(itemNode['title']): continue
if type(downloadDict['False']) == type(''):
if getConfig()['threads'][tName]['regExFalseOptions']:
LFalse = re.compile(downloadDict['False'],
getattr(re, getConfig()['threads'][tName]['regExFalseOptions']) | re.I )
else: LFalse = re.compile(downloadDict['False'], re.I)
if LFalse.search(itemNode['title']): continue
elif downloadDict['False'] == False: pass
elif downloadDict['False'] == True:
if not checkRegExGFalse(tName, itemNode): continue
if downloadDict['True'] == True:
if not checkRegExGTrue(tName, itemNode): continue
elif downloadDict['True'] == False: pass
return downloadDict
return False
# # # # #
# Download
# # # # #
def validFileName(aStr, invalid=('?','\\', '/', '*','<','>','"',':',';','!','|','\b','\0','\t')):
invalid = set(invalid)
invalid.update(map(chr, range(32)))
outStr = aStr
for i in invalid:
outStr = outStr.replace(i,'')
if not outStr:
raise ValueError("no characters are valid!")
if aStr== outStr:
logging.debug('no replacement made to filename')
else:
logging.debug('potentially illegal characters removed from filename')
return outStr
def downloadFile(link=None, threadName=None, rssItemNode=None,
downItemConfig=None):
u"""tries to download data at URL. returns None if it was not supposed to,
False if it failed, and a tuple of arguments for userFunct"""
try: data = downloader(link)
except (urllib2.HTTPError, urllib2.URLError, httplib.HTTPException), m:
logging.critical(''.join((traceback.format_exc(), os.linesep,
u'error grabbing url: %s' % link)))
return False
filename = getFilenameFromHTTP(data.info(), link)
if not filename: return False
size, data2 = getFileSize(data.info(), data)
if size and not checkFileSize(size, threadName, downItemConfig):
del data, data2
return None
if downItemConfig['Dir']: directory = downItemConfig['Dir']
elif getConfig()['threads'][threadName]['directory']:
directory = getConfig()['threads'][threadName]['directory']
else: directory = getConfig()['global']['downloadDir']
try: filename = writeNewFile( filename, directory, data2 )
except IOError:
logging.critical( u"write to disk failed")
return False
logging.warn( u"Filename: %s%s\tDirectory: %s%s\tFrom Thread: %s%s" % (
filename, os.linesep, directory, os.linesep, threadName, os.linesep ))
if rss:
logging.debug( u"generating rss item")
if 'description' in rssItemNode: description =rssItemNode['description']
else: description = None
if 'title' in rssItemNode: title = rssItemNode['title']
else: title = None
pubdate = time.strftime(u"%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
itemLoad = {'title':title ,'description':description ,'pubDate':pubdate}
rss.addItem( itemLoad )
userFunctArgs = (directory, filename, rssItemNode, data.geturl(),
downItemConfig, threadName )
return userFunctArgs
def writeNewFile(filename, directory, data):
u"""write a file to disk at location. won't clobber, depending on config.
writes to .__filename.tmp first, then moves to filename"""
filename = validFileName(filename)
if getConfig()['global']['noClobber']:
directory, filename = findNewFile( filename, directory)
tmpPath = os.path.join( *findNewFile( u'.__' + filename + u'.tmp',
directory) )
else: tmpPath = os.path.join(directory, u'.__' + filename + u'.tmp')
realPath = os.path.join(directory, filename)
try:
logging.debug(u'opening %s' % tmpPath)
# open should handle unicode path automagically
fd = codecs.open( tmpPath, 'wb') #'replace' ?
if hasattr(data, 'xreadlines'):
for piece in data.xreadlines(): fd.write(piece)
elif hasattr(data, 'readline'):
piece = data.readline()
while piece:
fd.write(piece)
piece = data.readline()
elif hasattr(data, 'read'): fd.write(data.read())
else: fd.write(data)
fd.flush()
fd.close()
except IOError:
if getConfig()['global']['noClobber'] and os.path.isfile( tmpPath ):
os.unlink(tmpPath)
logging.critical(''.join((traceback.format_exc() ,
u'Failed to write file %s in directory %s'%(filename, directory))))
raise IOError
logging.debug(u'moving to %s' % realPath)
os.rename(tmpPath, realPath)
return filename
def findNewFile(filename, directory):
u"""find a filename in the given directory that isn't already taken.
adds '.1' before the file extension,
or just .1 on the end if no file extension"""
if os.path.isfile( os.path.join(directory, filename) ):
logging.error(u"""filename already taken, looking for another: %s\
""" % filename)
filenameList = filename.split(u'.')
if len( filenameList ) >1:
try:
num = u'.' + unicodeC( int( filenameList[-2] ) +1)
del filenameList[-2]
filename = (u'.'.join( filenameList[:-1] ) + num + u'.' +
filenameList[-1])
except (ValueError, IndexError, UnicodeEncodeError):
try:
num = u'.' + unicodeC( int( filenameList[-1] ) + 1 )
del filenameList[-1]
filename = u'.'.join( filenameList ) + num
except (ValueError, IndexError, UnicodeEncodeError) :
num = u'.' + unicodeC( 1 )
filename = ( u'.'.join( filenameList[:-1] ) + num + '.' +
filenameList[-1] )
else: filename += u'.1'
return findNewFile( filename, directory )
else: return unicodeC(directory), unicodeC(filename)
def bdecode(x):
"""This function decodes torrent data.
It comes (modified) from the GPL Python BitTorrent implementation"""
def decode_int(x, f):
f += 1
newf = x.index('e', f)
try: n = int(x[f:newf])
except (OverflowError, ValueError): n = long(x[f:newf])
if x[f] == '-':
if x[f + 1] == '0': raise ValueError
elif x[f] == '0' and newf != f+1: raise ValueError
return (n, newf+1)
def decode_string(x, f):
colon = x.index(':', f)
try: n = int(x[f:colon])
except (OverflowError, ValueError): n = long(x[f:colon])
if x[f] == '0' and colon != f+1: raise ValueError
colon += 1
return (x[colon:colon+n], colon+n)
def decode_list(x, f):
r, f = [], f+1
while x[f] != 'e':
v, f = decode_func[x[f]](x, f)
r.append(v)
return (r, f + 1)
def decode_dict(x, f):
r, f = {}, f+1
lastkey = None
while x[f] != 'e':
k, f = decode_string(x, f)
if lastkey >= k: raise ValueError
lastkey = k
r[k], f = decode_func[x[f]](x, f)
return (r, f + 1)
decode_func = {
'l' : decode_list ,
'd' : decode_dict,
'i' : decode_int}
for i in range(10): decode_func[str(i)] = decode_string
if hasattr(x, 'read'): x = x.read()
try: r, l = decode_func[x[0]](x, 0)
except (IndexError, KeyError):
try:
x = open(x, 'r').read()
r, l = decode_func[x[0]](x,0)
except (OSError, IOError, IndexError, KeyError): raise ValueError
if l != len(x): raise ValueError
return r
# # # # #
#Persistence
# # # # #
class FailedItem(dict):
u"""represents an item that we tried to download, but failed,
either due to IOError, HTTPError, or some such"""
def __init__(self, link=None, threadName=None, rssItemNode=None,
downItemConfig=None):
u"""upgrade note: [0] = link, [1] = threadName, [2] = itemNode, [3] =
downloadLDir #oldnote"""
dict.__init__(self)
self['link'] = link
self['threadName'] = threadName
self['rssItemNode'] = rssItemNode
self['downItemConfig'] = downItemConfig
def __setstate__(self,state):
if 'data' in state: self.update(state['data'])
class DownloadItemConfig(dict):
u"""downloadDict: a dictionary representing the download<x> options.
keys are: 'localTrue' (corresponding to download<x>) ; 'False' ; 'True' ;
'Dir' ; 'minSize' ; and 'maxSize'
corresponding to their analogues in download<x>."""
def __init__(self, regextrue=None, dFalse=True, dTrue=True, dir=None,
minSize=None, maxSize=None, Function=None):
u"was [0] = localTrue, [1] = False, [2] = True, [3] = dir"
dict.__init__(self)
self['localTrue'] = regextrue
self['False'] = dFalse
self['True'] = dTrue
self['Dir'] = dir
self['minSize'] = minSize
self['maxSize'] = maxSize
self['Function'] = Function
def __setstate__(self,state):
if 'data' in state: self.update(state['data'])
class MakeRss(object):
u"""A class to generate, and optionally parse and load, an RSS 2.0 feed.
Example usage:
rss = MakeRss(filename='rss.xml')
rss.addItem(dict)
rss.close()
rss.write()"""
chanMetOpt = ['title', 'description', 'link', 'language',
'copyright', 'managingEditor', 'webMaster', 'pubDate',
'lastBuildDate', 'category', 'generator', 'docs', 'cloud', 'ttl',
'image', 'rating', 'textInput', 'skipHours', 'skipDays']
itemMeta = ['title', 'link', 'description', 'author', 'category',
'comments', 'enclosure', 'guid', 'pubDate', 'source']
_date_fmt = "%a, %d %b %Y %H:%M:%S GMT"
def __init__(self, channelMeta={}, parse=False, filename=None):
u"""channelMeta is a dictionary where the keys are the feed attributes
(description, title, link are REQUIRED).
filename sets the internal filename, where parsed feeds are parsed from
(by default) and the stored feed data is written to (by default).
parse will read the xml file found at self.filename and load the data
into the various places
or XML objects. The former is easier to deal with and is how RSSDler
works with them as of 0.3.2"""
global minidom, random
if not minidom: raise ImportError('minidom not imported')
if not random: raise ImportError('random not imported')
object.__init__(self)
self.feed = minidom.Document()
self.rss = self.feed.createElement('rss')
self.rss.setAttribute('version', '2.0')
self.channel = self.feed.createElement('channel')
self.channelMeta = channelMeta
self.filename = filename
self.items = []
self.itemsQuaDict = []
if parse: self.parse()
def loadChanOpt(self):
u"""takes self.channelMeta and turns it into xml
and adds the nodes to self.channel. Will only add those elements which
are part of the rss standard (aka those elements in self.chanMetOpt.
If you add to this list, you can override what is allowed
to be added to the feed."""
if 'title' not in self.channelMeta: