-
Notifications
You must be signed in to change notification settings - Fork 2
/
parserss.py
1538 lines (1207 loc) · 55 KB
/
parserss.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/python
# Copyright (C) 2001-2014, Christof Meerwald
# http://jabrss.cmeerw.org
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 dated June, 1991.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
from __future__ import with_statement
import codecs, functools, hashlib, logging, random, re, socket, struct
import sys, time, threading, traceback, zlib
import sqlite3
import requests
from email.utils import formatdate, mktime_tz, parsedate_tz
try:
from lxml.etree import Element, XMLParser
except ImportError:
try:
from xml.etree.cElementTree import Element, XMLParser
except ImportError:
from xml.etree.ElementTree import Element, XMLParser
from contenttools import htmlelem2plain, html2plain, xml2plain
if sys.version_info[0] == 2:
from HTMLParser import HTMLParser
from StringIO import StringIO
from urlparse import urlsplit, urljoin
else:
from html.parser import HTMLParser
from io import StringIO
from urllib.parse import urlsplit, urljoin
unichr = chr
logger = logging.getLogger('parserss')
__all__ = [
'RSS_Resource', 'RSS_Resource_id2url', 'RSS_Resource_simplify'
'RSS_Resource_db', 'RSS_Resource_Cursor',
'UrlError', 'init_parserss',
]
if sys.version_info[0] == 2:
import string
str_trans = string.maketrans(
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f' \
'\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' \
''.encode('ascii'),
' \x0a '.encode('ascii'))
else:
str_trans = None
def buffer(b):
return b
unicode_trans = {
0x00 : 0x20, 0x01 : 0x20, 0x02 : 0x20, 0x03 : 0x20,
0x04 : 0x20, 0x05 : 0x20, 0x06 : 0x20, 0x07 : 0x20,
0x08 : 0x20, 0x09 : 0x20, 0x0a : 0x0a, 0x0b : 0x20,
0x0c : 0x20, 0x0d : 0x20, 0x0e : 0x20, 0x0f : 0x20,
0x10 : 0x20, 0x11 : 0x20, 0x12 : 0x20, 0x13 : 0x20,
0x14 : 0x20, 0x15 : 0x20, 0x16 : 0x20, 0x17 : 0x20,
0x18 : 0x20, 0x19 : 0x20, 0x1a : 0x20, 0x1b : 0x20,
0x1c : 0x20, 0x1d : 0x20, 0x1e : 0x20, 0x1f : 0x20
}
random.seed()
def RSS_Resource_db():
db = sqlite3.Connection(DB_FILENAME, 60000)
db.isolation_level = None
db.cursor().execute('PRAGMA synchronous=NORMAL')
return db
class Null_Synchronizer:
def acquire(self):
return
def release(self):
return
# configuration settings
INTERVAL_DIVIDER = 3
MIN_INTERVAL = 45*60
MAX_INTERVAL = 24*60*60
MAX_XML_SIZE = 4 * 1024 * 1024
DB_FILENAME = 'parserss.db'
def init_parserss(db_fname = DB_FILENAME,
min_interval = MIN_INTERVAL,
max_interval = MAX_INTERVAL,
interval_div = INTERVAL_DIVIDER,
dbsync_obj = Null_Synchronizer()):
global DB_FILENAME, MIN_INTERVAL, MAX_INTERVAL, INTERVAL_DIVIDER
DB_FILENAME = db_fname
MIN_INTERVAL = min_interval
MAX_INTERVAL = max_interval
INTERVAL_DIVIDER = interval_div
RSS_Resource._db_sync = dbsync_obj
class UrlError(ValueError):
pass
def split_url(url):
u = urlsplit(url)
protocol = u.scheme
netloc_comp = u.netloc.split(':', 2)
host = netloc_comp[0].lower().split('.')
if len(netloc_comp) >= 2:
port = netloc_comp[1]
else:
port = None
path = u.path
if u.query:
path += '?' + u.query
validhost = False
if len(host) == 1 and host[0][:1] == '[' and host[0][-1:] == ']':
try:
host[0] = '[%s]' % (socket.inet_ntop(socket.AF_INET6, socket.inet_pton(socket.AF_INET6, host[0][1:-1])))
validhost = True
except socket.error:
validhost = False
elif len(host) == 4:
try:
host = socket.inet_ntop(socket.AF_INET, socket.inet_pton(socket.AF_INET, '.'.join(host))).split('.')
if int(host[0]) == 10:
pass
elif int(host[0]) == 172 and int(host[1]) in range(16, 32):
pass
elif int(host[0]) == 192 and int(host[1]) == 168:
pass
elif int(host[0]) >= 240:
pass
else:
validhost = True
except socket.error:
validhost = False
if not validhost and len(host) >= 2:
if len(host[-1]) >= 2 and host[-1].isalpha():
validhost = True
if not validhost:
raise UrlError('invalid host in URL "%s"' % ('.'.join(host),))
if protocol == 'http':
if port not in (None, '80', 'http'):
raise UrlError('http ports != 80 not allowed')
elif protocol == 'https':
if port not in (None, '443', 'https'):
raise UrlError('https ports != 443 not allowed')
else:
raise UrlError('unsupported protocol "%s"' % (protocol))
if path == '':
path = '/'
while path[:2] == '//':
path = path[1:]
return protocol, '.'.join(host), path
def normalize_text(s):
if type(s) == type(b''.decode('ascii')):
s = s.translate(unicode_trans)
else:
s = s.translate(str_trans)
s = '\n'.join(filter(lambda x: x != '', [ x.strip() for x in s.split('\n') ]))
s = ' '.join(filter(lambda x: x != '', s.split(' ')))
return s
def normalize_obj(o):
for attr in dir(o):
if attr[0] != '_':
value = getattr(o, attr)
if type(value) in (type(''), type(b''.decode('ascii'))):
setattr(o, attr, normalize_text(value))
return o
def normalize_item(item):
normalize_obj(item)
if item.descr == '':
item.descr = None
if not hasattr(item, 'descr_plain'):
item.descr_plain = item.descr
if not hasattr(item, 'descr_xhtml'):
item.descr_xhtml = None
if item.descr_plain:
item.descr_plain = item.descr_plain[:4096]
del item.descr
return item
re_dateTime = re.compile('^(?P<year>[1-9][0-9][0-9][0-9])-(?P<month>[01][0-9])-(?P<day>[0-3][0-9])T(?P<hour>[0-2][0-9]):(?P<min>[0-6][0-9]):(?P<sec>[0-6][0-9])(\\.[0-9]+)?(Z|(?P<tzsign>[-+])(?P<tzhour>[01][0-9]):(?P<tzmin>[0-6][0-9]))$')
def parse_dateTime(s):
if s == None:
return None
mo = re_dateTime.match(s)
if mo != None:
year, month, day, hour, min, sec = [ int(x) for x in mo.group('year', 'month', 'day', 'hour', 'min', 'sec')]
tzsign, tzhour, tzmin = mo.group('tzsign', 'tzhour', 'tzmin')
if tzhour != None and tzmin != None:
tzoff = 60*(60*int(tzhour) + int(tzmin))
else:
tzoff = 0
if tzsign == '-':
tzoff = -tzoff
tstamp = int(mktime_tz((year, month, day, hour, min, sec, 0, 0, 0, tzoff)))
else:
tstamp = None
return tstamp
def parse_Rfc822DateTime(s):
if s == None:
return None
try:
tstamp = int(mktime_tz(parsedate_tz(s)))
except:
tstamp = None
return tstamp
def compare_items(l, r):
lguid, ltitle, llink = l.guid, l.title, l.link
rguid, rtitle, rlink = r.guid, r.title, r.link
if ltitle == rtitle:
if (lguid != None) and (rguid != None):
return lguid == rguid
lurl = urlsplit(llink)
rurl = urlsplit(rlink)
if lurl.scheme == rurl.scheme and lurl.path == rurl.path and \
lurl.query == rurl.query and lurl.fragment == rurl.fragment:
lhostparts = lurl.netloc.lower().split('.')
if lhostparts[-1] == '':
del lhostparts[-1]
rhostparts = rurl.netloc.lower().split('.')
if rhostparts[-1] == '':
del rhostparts[-1]
if len(lhostparts) >= 2:
del lhostparts[-1]
if len(rhostparts) >= 2:
del rhostparts[-1]
if len(lhostparts) > len(rhostparts):
tmp = lhostparts
lhostparts = rhostparts
rhostparts = tmp
del tmp
if len(lhostparts) == len(rhostparts):
return lhostparts == rhostparts
else:
return lhostparts == rhostparts[-len(lhostparts):]
else:
return 0
else:
return 0
class CleanupOnError:
def __init__(self, callable=None):
self.__callable = callable
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
if self.__callable != None and exc_type != None:
self.__callable()
class Cursor:
def __init__(self, dbconn, parent=None):
self._txn, self._locked = False, False
self._parent = parent
if self._parent == None:
if not hasattr(dbconn, 'cursor'):
self._cursor = dbconn().cursor()
else:
self._cursor = dbconn.cursor()
else:
self._cursor = None
def __enter__(self):
if self._parent == None:
return self
else:
return self._parent
def __exit__(self, exc_type, exc_value, traceback):
if self._parent == None:
self.commit()
def commit(self):
try:
if self._txn:
self._cursor.execute('COMMIT')
self._txn = False
finally:
if self._locked:
RSS_Resource._db_sync.release()
self._locked = False
def begin(self):
if not self._locked:
RSS_Resource._db_sync.acquire()
self._locked = True
if not self._txn:
self._cursor.execute('BEGIN')
self._txn = True
def execute(self, stmt, bindings=None):
self.begin()
if bindings == None:
return self._cursor.execute(stmt)
else:
return self._cursor.execute(stmt, bindings)
def __getattr__(self, name):
if name == 'lastrowid':
return self._cursor.lastrowid
elif name == 'rowcount':
return self._cursor.rowcount
raise AttributeError('object has no attribute \'%s\'' % (name,))
def getdb(self):
return self._cursor.getconnection()
RSS_Resource_Cursor = Cursor
class Data:
def __init__(self, **kw):
for key, value in kw.items():
setattr(self, key, value)
class FeedError(Exception):
def __init__(self, e):
Exception.__init__(self, e)
class RetryAsHtml(Exception):
def __init__(self):
Exception.__init__(self)
def findtag(parent, tags):
elem = None
for tag in tags:
elem = parent.find(tag)
if elem != None:
break
return elem
def findattr(l, textattr, attr=None, values=(), default=''):
text, typ = '', None
for e in l:
thistyp = -1
if attr != None:
try:
thistyp = values.index(e.get(attr, default))
except ValueError:
pass
if text == '' or thistyp > typ:
if e.get(textattr, None):
text, typ = e.get(textattr, None), thistyp
return text
def findelem(l, attr=None, values=(), default=''):
elem, typ = None, None
for e in l:
thistyp = -1
if attr != None:
try:
thistyp = values.index(e.get(attr, default))
except ValueError:
pass
if elem == None or thistyp > typ:
elem, typ = e, thistyp
return elem
def typedtext(elem):
if elem == None:
return ''
if elem.get('type', None) == 'html':
return htmlelem2plain(elem)
else:
buf = StringIO()
xml2plain(elem, buf)
text = buf.getvalue()
buf.close()
return text
class Feed_Parser:
class Handler:
def __init__(self):
self.__doctype, self.__data, self.__elem, self.__last, self.__tail = None, [], [], None, None
self.__toplevel_handler = {
'{http://www.w3.org/2005/Atom}feed' :
(self.atom10_feed_start, self.atom10_feed_end),
'{http://purl.org/atom/ns#}feed' :
(self.atom03_feed_start, self.atom03_feed_end),
'{http://www.w3.org/1999/02/22-rdf-syntax-ns#}RDF' :
(self.rss_start, self.rss_end),
'rss' :
(self.rss_start, self.rss_end),
'{http://backend.userland.com/rss2}rss' :
(self.rss_start, self.rss_end),
# RSS 1.1, see http://inamidst.com/rss1.1/
'{http://purl.org/net/rss1.1#}Channel' :
(self.rss11_start, self.rss11_end),
}
self.__end_handler, self.__element_handler = None, {}
self.redirect_url, self.info, self.elements = None, None, []
def close(self):
assert len(self.__elem) == 0, "missing end tags"
assert self.__last != None, "missing toplevel element"
return self.__last
def __flush(self):
if self.__data:
if self.__last is not None:
text = ''.join(self.__data)
if self.__tail:
assert self.__last.tail is None, "internal error (tail)"
self.__last.tail = text
else:
assert self.__last.text is None, "internal error (text)"
self.__last.text = text
self.__data = []
def data(self, data):
self.__data.append(data)
def start(self, tag, attrs):
if attrs == None:
attrs = {}
self.__flush()
self.__last = elem = Element(tag, attrs)
if len(self.__elem) == 0:
try:
handler, self.__end_handler = self.__toplevel_handler[tag]
except KeyError:
handler = None
if handler:
handler(elem)
elif tag in ('html', '{http://www.w3.org/1999/xhtml}html'):
raise RetryAsHtml()
elif self.__doctype == 'html':
raise RetryAsHtml()
else:
raise FeedError('Unknown start tag %s' % (tag,))
self.__elem.append(elem)
self.__tail = False
return elem
def end(self, tag):
self.__flush()
self.__last = self.__elem.pop()
assert self.__last.tag == tag,\
"end tag mismatch (expected %s, got %s)" % (
self.__last.tag, tag)
self.__tail = True
if len(self.__elem) == 0:
self.__end_handler(self.__last)
else:
try:
handler = self.__element_handler[tag]
except KeyError:
handler, keep = None, len(self.__elem) >= 2
if handler:
keep = handler(self.__last)
if keep:
self.__elem[-1].append(self.__last)
self._root = self.__last
return self.__last
def keep_elem(self, elem):
return True
def atom03_feed_start(self, elem):
self.__element_handler = {
'{http://purl.org/atom/ns#}entry' :
self.atom03_entry,
'{http://purl.org/atom/ns#}title' :
self.keep_elem,
'{http://purl.org/atom/ns#}link' :
self.keep_elem,
'{http://purl.org/atom/ns#}tagline' :
self.keep_elem,
'{http://purl.org/atom/ns#}id' :
self.keep_elem,
'{http://purl.org/atom/ns#}created' :
self.keep_elem,
'{http://purl.org/atom/ns#}modified' :
self.keep_elem,
}
def atom03_feed_end(self, elem):
ns = '{http://purl.org/atom/ns#}'
title = typedtext(elem.find(ns + 'title'))
descr = typedtext(elem.find(ns + 'tagline'))
link = findattr(elem.findall(ns + 'link'),
'href', 'rel',
['via', 'related', 'enclosure', 'alternate'],
'alternate')
guid = elem.findtext(ns + 'id')
published = parse_dateTime(elem.findtext(ns + 'created') or \
elem.findtext(ns + 'modified') or \
None)
self.info = Data(title=title, descr=descr, link=link,
guid=guid, published=published)
def atom03_entry(self, elem):
ns = '{http://purl.org/atom/ns#}'
title = typedtext(elem.find(ns + 'title'))
descr = typedtext(findelem(elem.findall(ns + 'summary') +
elem.findall(ns + 'content'),
'type', ['html', 'xhtml', 'text'],
'text'))
link = findattr(elem.findall(ns + 'link'),
'href', 'rel',
['via', 'related', 'enclosure', 'alternate'],
'alternate')
guid = elem.findtext(ns + 'id')
published = parse_dateTime(elem.findtext(ns + 'created') or \
elem.findtext(ns + 'modified') or \
None)
self.elements.append(Data(title=title, descr=descr, link=link,
guid=guid, published=published))
return False
def atom10_feed_start(self, elem):
self.__element_handler = {
'{http://www.w3.org/2005/Atom}entry' :
self.atom10_entry,
'{http://www.w3.org/2005/Atom}title' :
self.keep_elem,
'{http://www.w3.org/2005/Atom}link' :
self.keep_elem,
'{http://www.w3.org/2005/Atom}subtitle' :
self.keep_elem,
'{http://www.w3.org/2005/Atom}id' :
self.keep_elem,
'{http://www.w3.org/2005/Atom}updated' :
self.keep_elem,
}
def atom10_feed_end(self, elem):
ns = '{http://www.w3.org/2005/Atom}'
title = typedtext(elem.find(ns + 'title'))
descr = typedtext(elem.find(ns + 'subtitle'))
link = findattr(elem.findall(ns + 'link'),
'href', 'rel',
['via', 'related', 'enclosure', 'alternate'],
'alternate')
guid = elem.findtext(ns + 'id')
published = parse_dateTime(elem.findtext(ns + 'published') or \
elem.findtext(ns + 'updated') or \
None)
self.info = Data(title=title, descr=descr, link=link,
guid=guid, published=published)
def atom10_entry(self, elem):
ns = '{http://www.w3.org/2005/Atom}'
title = typedtext(elem.find(ns + 'title'))
descr = typedtext(findelem(elem.findall(ns + 'summary') +
elem.findall(ns + 'content'),
'type', ['html', 'xhtml', 'text'],
'text'))
link = findattr(elem.findall(ns + 'link'),
'href', 'rel',
['via', 'related', 'enclosure', 'alternate'],
'alternate')
guid = elem.findtext(ns + 'id')
published = parse_dateTime(elem.findtext(ns + 'published') or \
elem.findtext(ns + 'updated') or \
None)
self.elements.append(Data(title=title, descr=descr, link=link,
guid=guid, published=published))
return False
def rss_start(self, elem):
self.__element_handler = {
'channel' :
self.keep_elem,
'{http://purl.org/rss/1.0/}channel' :
self.keep_elem,
'{http://purl.org/rss/2.0/}channel' :
self.keep_elem,
'{http://backend.userland.com/rss2}channel' :
self.keep_elem,
'{http://my.netscape.com/publish/formats/rss-0.91.dtd}channel' :
self.keep_elem,
'{http://my.netscape.com/rdf/simple/0.9/}channel' :
self.keep_elem,
'item' :
self.rss_entry,
'{http://purl.org/rss/1.0/}item' :
self.rss_entry,
'{http://purl.org/rss/2.0/}item' :
self.rss_entry,
'{http://backend.userland.com/rss2}item' :
self.rss_entry,
'{http://my.netscape.com/publish/formats/rss-0.91.dtd}item' :
self.rss_entry,
'{http://my.netscape.com/rdf/simple/0.9/}item' :
self.rss_entry,
}
def rss_end(self, elem):
channel = findtag(elem,
('channel',
'{http://backend.userland.com/rss2}channel',
'{http://purl.org/rss/1.0/}channel',
'{http://purl.org/rss/2.0/}channel',
'{http://my.netscape.com/publish/formats/rss-0.91.dtd}channel',
'{http://my.netscape.com/rdf/simple/0.9/}channel'))
if channel != None:
if channel.tag[0] == '{':
ns = channel.tag.split('}')[0] + '}'
else:
ns = ''
title = htmlelem2plain(channel.find(ns + 'title'))
descr = htmlelem2plain(channel.find(ns + 'description'))
link = channel.findtext(ns + 'link')
if link:
link = link.strip()
guid = channel.get('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}about', None)
published = parse_dateTime(channel.findtext('{http://purl.org/dc/elements/1.1/}date')) or \
parse_Rfc822DateTime(channel.findtext(ns + 'lastBuildDate')) or \
None
self.info = Data(title=title, descr=descr, link=link,
guid=guid, published=published)
def rss_entry(self, elem):
if elem.tag[0] == '{':
ns = elem.tag.split('}')[0] + '}'
else:
ns = ''
title = htmlelem2plain(elem.find(ns + 'title'))
descr = htmlelem2plain(elem.find(ns + 'description'))
link = elem.findtext('{http://www.pheedo.com/namespace/pheedo}origLink') or \
elem.findtext('{http://rssnamespace.org/feedburner/ext/1.0}origLink') or \
elem.findtext(ns + 'link')
enclosure = elem.find(ns + 'enclosure')
if enclosure != None and enclosure.get('url', ''):
if not link or enclosure.get('type', '') in ('audio/mpeg',):
# prioritise certain types of enclosures
link = enclosure.get('url', '')
if link == None:
link = ''
else:
link = link.strip()
guid = elem.get('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}about', None) or \
elem.findtext(ns + 'guid')
published = parse_dateTime(elem.findtext('{http://purl.org/dc/elements/1.1/}date')) or \
parse_Rfc822DateTime(elem.findtext(ns + 'pubDate')) or \
None
self.elements.append(Data(title=title, descr=descr, link=link,
guid=guid, published=published))
return False
def rss11_start(self, elem):
self.__element_handler = {
'{http://purl.org/net/rss1.1#}title' :
self.keep_elem,
'{http://purl.org/net/rss1.1#}link' :
self.keep_elem,
'{http://purl.org/net/rss1.1#}description' :
self.keep_elem,
'{http://purl.org/net/rss1.1#}item' :
self.rss11_entry,
}
def rss11_end(self, elem):
ns = '{http://purl.org/net/rss1.1#}'
title = (elem.findtext(ns + 'title') or '').strip()
descr = (elem.findtext(ns + 'description') or '').strip()
link = (elem.findtext(ns + 'link') or '').strip()
guid = None
published = None
self.info = Data(title=title, descr=descr, link=link,
guid=guid, published=published)
def rss11_entry(self, elem):
ns = '{http://purl.org/net/rss1.1#}'
title = (elem.findtext(ns + 'title') or '').strip()
descr = (elem.findtext(ns + 'description') or '').strip()
link = (elem.findtext(ns + 'link') or '').strip()
guid = elem.get('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}about', None)
published = None
self.elements.append(Data(title=title, descr=descr, link=link,
guid=guid, published=published))
return False
class HtmlLinkParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.redirect_url, self.info, self.elements = None, None, []
def close(self):
HTMLParser.close(self)
if not self.redirect_url:
raise FeedError('No RSS autodiscovery links found in html')
def handle_starttag(self, tag, attrs):
if tag == 'link' and self.redirect_url == None:
dattrs = dict(attrs)
if (dattrs.get('rel') == 'alternate' and
dattrs.get('type') in ('application/atom+xml', 'application/rdf+xml', 'application/rss+xml')):
self.redirect_url = dattrs.get('href')
self.info = Data(title=dattrs.get('title', ''),
descr='', link=self.redirect_url,
guid=None, published=None)
elif tag == 'body' and not self.redirect_url:
raise FeedError('No RSS autodiscovery links found in html')
def handle_startendtag(self, tag, attrs):
return self.handle_starttag(tag, attrs)
def handle_endtag(self, tag):
if tag == 'head' and not self.redirect_url:
raise FeedError('No RSS autodiscovery links found in html')
def __init__(self, base_url, encoding):
self.__buf = []
self.__base_url = base_url
self.__handler = Feed_Parser.Handler()
if hasattr(XMLParser, 'feed_error_log'):
self.__parser = XMLParser(target=self.__handler, recover=True, encoding=encoding)
else:
self.__parser = XMLParser(target=self.__handler, encoding=encoding)
def get_error_log(self):
if hasattr(self.__parser, 'feed_error_log'):
return self.__parser.feed_error_log
return None
def get_info(self):
return self.__handler.info
def get_items(self):
return self.__handler.elements
def get_redirect_url(self):
return self.__handler.redirect_url
def __resolve_link(self, url):
return urljoin('%s://%s/%s' % (self.__base_url), url)
def __retry_as_html(self):
self.__handler = Feed_Parser.HtmlLinkParser()
self.__parser = self.__handler
for data in self.__buf:
self.__parser.feed(data.decode('iso8859-1'))
self.__buf = None
def feed(self, data):
try:
try:
res = self.__parser.feed(data)
finally:
if self.__buf != None:
self.__buf.append(data)
except RetryAsHtml:
self.__retry_as_html()
def close(self):
try:
self.__parser.close()
elem = self.__handler.close()
except RetryAsHtml:
self.__retry_as_html()
elem = None
info = self.__handler.info
if info != None:
info.link = self.__resolve_link(info.link)
else:
raise Exception('No feed information found')
redirect_url = self.__handler.redirect_url
if redirect_url != None:
self.__handler.redirect_url = self.__resolve_link(redirect_url)
for item in self.__handler.elements:
item.link = self.__resolve_link(item.link)
return elem
def default_redirect_cb(redirect_url, db, redirect_count,
generate_id, connect_timeout, timeout):
resource_url = RSS_Resource_simplify(redirect_url)
while resource_url != None:
redirect_resource = RSS_Resource(resource_url, db, generate_id, connect_timeout, timeout)
resource_url, redirect_seq = redirect_resource.redirect_info(db)
new_items, next_item_id, redirect_target, redirect_seq, redirects = redirect_resource.update(db, redirect_count)
if len(new_items) > 0:
redirects.insert(0, (redirect_resource, new_items, next_item_id))
if redirect_target != None:
redirect_resource = redirect_target
return redirect_resource, redirects
@functools.total_ordering
class RSS_Resource:
NR_ITEMS = 96
_db_sync = Null_Synchronizer()
http_proxy = None
def __init__(self, url, res_db=None, generate_id=None,
connect_timeout=30, timeout=20):
self._lock = threading.Lock()
self._url = url
self._url_protocol, self._url_host, self._url_path = split_url(url)
self._generate_id = generate_id
self._connect_timeout, self._timeout = connect_timeout, timeout
self._id = None
self._last_updated, self._last_modified = None, None
self._etag = None
self._invalid_since, self._err_info = None, None
self._redirect, self._redirect_seq = None, None
self._penalty = 0
title, description, link = None, None, None
if res_db == None:
db = RSS_Resource_db()
else:
db = res_db
with Cursor(db) as cursor:
result = cursor.execute('SELECT rid, last_updated, last_modified, etag, invalid_since, redirect, redirect_seq, penalty, err_info, title, description, link FROM resource WHERE url=?',
(self._url,))
for row in result:
self._id, self._last_updated, self._last_modified, self._etag, self._invalid_since, self._redirect, self._redirect_seq, self._penalty, self._err_info, title, description, link = row
if self._id == None:
if generate_id == None:
cursor.execute('INSERT INTO resource (url) VALUES (?)',
(self._url,))
self._id = cursor.lastrowid
else:
for i in range(0, 5):
try:
id = generate_id()
cursor.execute('INSERT INTO resource (rid, url) VALUES (?, ?)',
(id, self._url))
self._id = id
break
except sqlite3.IntegrityError:
pass
if self._id == None:
raise UrlError('Unable to add to database')
if self._last_updated == None:
self._last_updated = 0
if self._penalty == None:
self._penalty = 0
if title == None:
title = self._url
if link == None:
link = ''
if description == None:
description = ''
self._channel_info = Data(title=title, link=link, descr=description)
self._history = []
result = cursor.execute('SELECT time_items0, time_items1, time_items2, time_items3, time_items4, time_items5, time_items6, time_items7, time_items8, time_items9, time_items10, time_items11, time_items12, time_items13, time_items14, time_items15, nr_items0, nr_items1, nr_items2, nr_items3, nr_items4, nr_items5, nr_items6, nr_items7, nr_items8, nr_items9, nr_items10, nr_items11, nr_items12, nr_items13, nr_items14, nr_items15 FROM resource_history WHERE rid=?',
(self._id,))
for row in result:
history_times = filter(lambda x: x!=None, row[0:16])
history_nr = filter(lambda x: x!=None, row[16:32])
self._history = list(zip(history_times, history_nr))
del db
def __eq__(self, other):
return (other != None) and (self._id == other._id)
def __lt__(self, other):
return (other != None) and (self._id < other._id)
def sync(self):
return self._lock
def lock(self):