-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnewspipe.py
More file actions
1904 lines (1590 loc) · 65.4 KB
/
newspipe.py
File metadata and controls
1904 lines (1590 loc) · 65.4 KB
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 -*-
# $NoKeywords: $ for Visual Sourcesafe, stop replacing tags
__revision__ = "$Revision: 1.68 $"
__revision_number__ = __revision__.split()[1]
__version__ = "1.1.9"
__date__ = "2005-07-03"
__url__ = "http://newspipe.sourceforge.net"
__author__ = "Ricardo M. Reyes <reyesric@ufasta.edu.ar>"
__contributors__ = ["Rui Carmo <http://the.taoofmac.com/space/>", "Bruno Rodrigues <http://www.litux.org/blog/>"]
__id__ = "$Id: newspipe.py,v 1.68 2006/01/22 22:02:37 reyesric Exp $"
ABOUT_NEWSPIPE = """
newspipe.py - version %s revision %s, Copyright (C) 2003-%s \n%s
"""%(__version__, __revision_number__, __date__.split('-')[0], __author__)
#import psyco
#psyco.full()
import ConfigParser
from hashlib import md5
from time import sleep, time
import os, sys, os.path
from cache import *
from datetime import datetime, timedelta
from pprint import pprint
from opml import *
from pickle import load, dump
import smtplib
import re
from htmlentitydefs import entitydefs
from difflib import SequenceMatcher
import email.Utils
import email.Header
import Queue
from htmlentitydefs import *
import MimeWriter
import mimetools
import cStringIO
import base64
import urlparse
import traceback
import sys
import urllib
import urllib2
import logging
import logging.handlers
from urllib2 import URLError
from email import message_from_string
import gc
import socket
try:
import threading as _threading
has_threading = True
except ImportError:
import dummy_threading as _threading
has_threading = False
has_html2text = True
try:
from html2text import *
except ImportError:
has_html2text = False
PYTHON_VERSION = '.'.join([str(x) for x in sys.version_info])
USER_AGENT = 'NewsPipe/'+__version__+' rev.'+__revision_number__+' Python: '+ PYTHON_VERSION+' Platform: '+sys.platform +' / '+__url__
OPML_DEFAULTS = {
'active': '1',
'digest': '0',
'titles': '1',
'download_link': '0',
'diff': '1',
'check_text': '1',
'delay': '60',
'textonly': '0',
'mobile': '0',
'download_images': '1',
'check_time': '',
'mobile_time': '',
'remove': '',
}
CONFIG_DEFAULTS = {
'textonly': '0',
'log_console': '0',
'sleep_time': '5',
'offline': '0',
'debug': '0',
'workers': '10',
'multipart': 'on',
'can_pipe': '0',
'encoding': 'utf-8',
'proxy': '',
'threading': '0',
'subject': '',
'priority' : '1',
'smtp_auth' : '0',
'smtp_user' : '',
'smtp_pass' : '',
'from_address' : '',
'send_method': 'smtp',
'procmail': '',
'reverse' : '0'
}
DEBUG = False
class MyLog:
debug_memory = 0 # include memory information in debug
cache = 2 # keep mem stats for "cache" seconds
h = None # file handler
result = None # memory string
lasttime = None # last access to the file
#def die(self): self.h.close()
def memory(self):
# /proc/self/status is only available on Linux)
if self.debug_memory and sys.platform.lower().startswith('linux2'):
if not self.lasttime:
self.lasttime = time.time() - self.cache - 1
if self.lasttime + self.cache >= time.time():
return self.result
if not self.h:
self.h=file("/proc/self/status")
else:
self.h.seek(0)
x=self.h.read(1024)
result = ""
for l in x.split("\n"):
if l[0:2] != "Vm": continue
l = l.replace(" kB", "")
l = l.replace(" ", "")
l = l.replace("\t", "")
l = l.replace(":", ": ")
result = result + l + ","
# end for
if len(result) > 1:
self.result = result
result = result[:-1]
else:
result = self.result
result = "[" + result + "] "
return result
else:
return ''
# end if
# end def
def debug(self, msg, *args, **kwargs):
msg = self.memory() + msg
log.debug(msg, *args, **kwargs)
def info(self, msg, *args, **kwargs):
msg = self.memory() + msg
log.info(msg, *args, **kwargs)
def warning(self, msg, *args, **kwargs):
msg = self.memory() + msg
log.warning(msg, *args, **kwargs)
def exception(self, msg, *args, **kwargs):
msg = self.memory() + msg
log.exception(msg, *args, **kwargs)
def error(self, msg, *args, **kwargs):
msg = self.memory() + msg
log.error(msg, *args, **kwargs)
def LogFile(stderr=True, name='default', location='.', debug=False):
if not os.path.exists(location):
os.makedirs(location)
logger = logging.getLogger(name)
hdlr = logging.handlers.RotatingFileHandler(os.path.join(location, name+'.log'), maxBytes=1024*500, backupCount=10)
formatter = logging.Formatter('%(asctime)s %(thread)d %(levelname)-10s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
if stderr:
hdlr = logging.StreamHandler(sys.stderr)
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
# end if
if debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
# end if
return logger
# end def
def parseTime (text):
AM = 1
PM = 2
UNKNOWN = 3
text = text.lower()
if 'am' in text:
ampm = AM
text = text.replace('am', '')
elif 'pm' in text:
ampm = PM
text = text.replace('pm', '')
else:
ampm = UNKNOWN
text = text.strip()
partes = text.split(':')
if len(partes) == 1:
partes.append('0')
try:
hours = int(partes[0])
minutes = int(partes[1])
except ValueError:
return None
if ampm == PM:
hours = hours + 12
return (hours, minutes)
return None
def parseTimeRange (text):
begin, end = None, None
text = text.strip()
separadores = [x for x in (' , ; to = / | -').split(' ') if x]
separadores.append(' ')
partes = None
for each in separadores:
aux = text.split(each)
if len(aux) == 2:
partes = aux
if partes:
partes = [x.strip() for x in partes]
begin = parseTime(partes[0])
end = parseTime(partes[1])
if begin and end:
return (begin, end)
return None
def checkTime (range):
n = datetime.now()
hours = n.hour
minutes = n.minute
begin = range[0][0]*100 + range[0][1]
end = range[1][0]*100 + range[1][1]
current = hours*100 + minutes
if end < begin:
end += 2400
result = begin <= current <= end
return result
def formatNumber (text):
i = float(text)
m = i/(1024*1024)
if m < 0.01 and m > 0:
m = 0.01
return '%0.2f MB' % m
def intEnt(m):
m = int(m.groups(1)[0])
return unichr(m)
def xEnt(m):
m = int(m.groups(1)[0], 16)
return unichr(m)
def nameEnt(m):
m = m.groups(1)[0]
if m in entitydefs.keys():
return entitydefs[m].decode("latin1")
else:
return "&"+m+";"
# end if
def expandNumEntities(text):
text = re.sub(r'&#(\d+);', intEnt, text)
text = re.sub(r'&#[Xx](\w+);', xEnt, text)
text = re.sub(r'&(.*?);', nameEnt, text)
return text
def expandEntities(text):
text = text.replace("<", "<")
text = text.replace(">", ">")
text = text.replace(""", '"')
text = text.replace("&ob;", "{")
text = text.replace("&cb;", "}")
text = text.replace("·", "*")
text = re.sub("&[rl]squo;", "'", text)
text = re.sub("&[rl]dquo;", '"', text)
text = re.sub("&([aeiouAEIOU])(grave|acute|circ|tilde|uml|ring);", lambda m: m.groups(1)[0], text)
text = re.sub("&([cC])(cedil);", lambda m: m.groups(1)[0], text)
text = re.sub("&([n])(tilde);", lambda m: m.groups(1)[0], text)
text = re.sub(r'&#(\d+);', intEnt, text)
text = re.sub(r'&#[Xx](\w+);', xEnt, text)
text = re.sub("&(#169|copy);", "(C)", text)
text = re.sub("—", "--", text)
text = re.sub("&", "&", text)
return text
class TextDiff:
"""Create diffs of text snippets."""
def __init__(self, source, target):
"""source = source text - target = target text"""
self.separadores = '"<>'
self.nl = "<NL>"
#self.delTag = "<span class='deleted'>%s</span>"
self.delTag = '<font color="#FF0000"><STRIKE>%s</STRIKE></font>'
#self.insTag = "<span class='inserted'>%s</span>"
self.insTag = '<font color="#337700"><b>%s</b></font>'
self.source = self.SplitHTML(source.replace("\n", "\n%s" % self.nl))
self.target = self.SplitHTML(target.replace("\n", "\n%s" % self.nl))
self.deleteCount, self.insertCount, self.replaceCount = 0, 0, 0
self.diffText = None
self.cruncher = SequenceMatcher(None, self.source, self.target)
self._buildDiff()
def SplitHTML (self, texto):
version1 = re.compile('(<.+?>)').split(texto)
version2 = []
for x in version1:
if re.compile('<.+>').search(x):
version2 += [x,]
else:
version2 += x.split()
# end if
# end for
return version2
def _buildDiff(self):
"""Create a tagged diff."""
outputList = []
for tag, alo, ahi, blo, bhi in self.cruncher.get_opcodes():
if tag == 'replace':
# Text replaced = deletion + insertion
outputList.append(self.delTag % " ".join(self.source[alo:ahi]))
outputList.append(self.insTag % " ".join(self.target[blo:bhi]))
self.replaceCount += 1
elif tag == 'delete':
# Text deleted
outputList.append(self.delTag % " ".join(self.source[alo:ahi]))
self.deleteCount += 1
elif tag == 'insert':
# Text inserted
outputList.append(self.insTag % " ".join(self.target[blo:bhi]))
self.insertCount += 1
elif tag == 'equal':
# No change
outputList.append(" ".join(self.source[alo:ahi]))
diffText = " ".join(outputList)
diffText = " ".join(diffText.split())
self.diffText = diffText.replace(self.nl, "\n")
def getStats(self):
"Return a tuple of stat values."
return (self.insertCount, self.deleteCount, self.replaceCount)
def getDiff(self):
"Return the diff text."
aux = self.diffText
return aux
def createhtmlmail (html, text, headers, images=None, rss_feed=None, link=None, encoding='utf-8'):
"""Create a mime-message that will render HTML in popular
MUAs, text in better ones"""
global cache, log
if not isinstance(text, unicode):
text = text.decode('latin1')
# end if
if isinstance(text, unicode):
text = text.encode('utf-8')
# end if
if not isinstance(html, unicode):
html = html.decode('latin1')
# end if
if isinstance(html, unicode):
html = html.encode('utf-8')
# end if
out = cStringIO.StringIO() # output buffer for our message
htmlin = cStringIO.StringIO(html)
txtin = cStringIO.StringIO(text)
if rss_feed:
rssin = cStringIO.StringIO(rss_feed)
# end if
writer = MimeWriter.MimeWriter(out)
#
# set up some basic headers... we put subject here
# because smtplib.sendmail expects it to be in the
# message body
#
for x,y in headers:
writer.addheader(x, y.encode('utf-8'))
writer.addheader("MIME-Version", "1.0")
#
# start the multipart section of the message
# multipart/alternative seems to work better
# on some MUAs than multipart/mixed
#
writer.startmultipartbody("alternative")
writer.flushheaders()
#
# the plain text section
#
if(text != ""):
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
pout = subpart.startbody("text/plain", [("charset", 'utf-8'), ("delsp", 'yes'), ("format", 'flowed')])
mimetools.encode(txtin, pout, 'quoted-printable')
pout.write (txtin.read())
txtin.close()
#
# start the html subpart of the message
#
if images:
htmlpart = writer.nextpart()
htmlpart.startmultipartbody("related")
subpart = htmlpart.nextpart()
else:
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
#
# returns us a file-ish object we can write to
#
pout = subpart.startbody("text/html", [("charset", 'utf-8')])
mimetools.encode(htmlin, pout, 'quoted-printable')
htmlin.close()
if images:
for x in images:
try:
ext = 'gif'
ruta, archivo = os.path.split(x['url'])
if archivo:
name, ext = os.path.splitext(archivo)
if ext:
ext = ext[1:]
if '?' in ext:
ext = ext[:ext.find('?')]
# end if
# end if
# end if
if link:
# if the url is relative, then add the link url to form an absolute address
url_parts = urlparse.urlsplit(x['url'])
if not url_parts[1]:
if not url_parts[0].upper() == 'FILE:':
x['url'] = urlparse.urljoin(link, x['url'])
# end if
# end if
# end if
x['url'] = x['url'].replace(' ', '%20')
retries = 0;
MAX_RETRIES = 3;
img_referer = link
resource = None
while retries < MAX_RETRIES:
retries += 1
# try to fetch the image.
# in case of Timeout or URLError exceptions, retry up to 3 times
try:
resource = cache.urlopen(x['url'], max_age=999999, referer=img_referer, can_pipe=False)
except HTTPError, e:
# in case of HTTP error 403 ("Forbiden") retry without the Referer
if e.code == 403 and img_referer:
mylog.info ('HTTP error 403 downloading %s, retrying without the referer' % (x['url'],))
img_referer = None
else:
raise
# end if
except (socket.timeout, socket.error):
mylog.info ('Timeout error downloading %s' % (x['url'],))
if retries == MAX_RETRIES:
raise
# end if
except URLError, e:
mylog.info ('URLError (%s) downloading %s' % (e.reason, x['url'],))
if retries == MAX_RETRIES:
raise
# end if
except Exception:
raise # any other exception, kick it up, to be handled later
else:
# if there's no exception, break the loop to continue
# processing the image
break
# end try
mylog.info ('Retrying, %d time' % retries);
# end while
if not resource:
raise Exception('Unknown problem')
# end if
explicacion = resource.info['Cache-Result']
mylog.debug (explicacion + ' ' + x['url'])
info = resource.info
content_type = info['Content-Type']
# end if
subpart = htmlpart.nextpart()
subpart.addheader("Content-Transfer-Encoding", "base64")
subpart.addheader("Content-ID", "<" + x['name'] + ">")
subpart.addheader("Content-Location", x['name'])
subpart.addheader("Content-Disposition", "inline; filename=\"" +x['filename'] + "\"" )
f = subpart.startbody(content_type, [["name", x['name']]])
b64 = base64.encodestring(resource.content.read())
f.write(b64)
image_ok = True # the image was downloaded ok
except KeyboardInterrupt:
raise
except socket.timeout:
mylog.info ('Timeout error downloading %s' % (x['url'],))
image_ok = False
except HTTPError, e:
mylog.info ('HTTP Error %d downloading %s' % (e.code, x['url'],))
image_ok = False
except URLError, e:
mylog.info ('URLError (%s) downloading %s' % (e.reason, x['url'],))
image_ok = False
except OfflineError:
mylog.info ('Resource unavailable when offline (%s)' % x['url'])
image_ok = False
except Exception, e:
mylog.exception ('Error %s downloading %s' % (str(e), x['url'],))
image_ok = False
# end try
if not image_ok:
x['url'] = 'ERROR '+x['url'] # arruino la url para que no se reemplace en el html
# end if
# end for
htmlpart.lastpart()
# end if
#
# the feed section
#
if rss_feed:
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
pout = subpart.startbody("text/plain", [("charset", 'us-ascii'), ("Name", "rss_feed.xml")])
mimetools.encode(rssin, pout, 'quoted-printable')
rssin.close()
# end if
#
# Now that we're done, close our writer and
# return the message body
#
writer.lastpart()
msg_source = out.getvalue()
out.close()
return message_from_string (msg_source.encode(encoding, 'replace'))
def createTextEmail(text, headers, encoding='utf-8'):
t = '\r\n'.join([x+': '+y for x,y in headers])
t += '\r\n\r\n'
t += text
return message_from_string(t.encode(encoding, 'replace'))
# end def
def quitarEntitys (text):
return re.sub(r'(&\D+?;)', '', text)
class Channel:
def __init__(self, title, original, xmlUrl, htmlUrl, download_link, diff, download_images, parameters):
self.original = original
self.xmlUrl = xmlUrl
self.htmlUrl = htmlUrl
self.title = original.get('title', title)
self.description = original.get('description', self.title)
self.creator = original.get('creator', original.get('author', self.title))
self.download_link = download_link
self.download_images = download_images
self.diff = diff
self.parameters = parameters
def NewItem(self, original, encoding="utf-8", remove=None):
return Item(original, self, encoding, remove)
# end def
# end class
def item_checksum(item):
""" Calculates the MD5 checksum of an rss item """
m = md5()
for x in item.values():
m.update (str(x))
# end for
return m.hexdigest()
# end def
historico_posts = {}
historico_feeds = {}
def getEntity(m):
v = int(m.groups(1)[0])
if v in codepoint2name.keys():
return '&'+codepoint2name[v]+';'
else:
return ''
def SanitizeText (text):
text = text.replace('\n', ' ')
entitys = entitydefs
inverso = {}
for i,j in entitys.items():
inverso[j] = '&'+i+';'
chars = filter(lambda x: ord(x) >= 128, text)
if chars:
for c in chars:
if inverso.has_key(c):
text = text.replace(c, inverso[c])
else:
text = text.replace(c, '')
text = re.sub(r'&#(\d+);', getEntity, text)
return text
def GetValue (x):
if isinstance(x, basestring):
return x
elif isinstance(x, list):
try:
return x[0]['value']
except:
return ''
else:
return ''
entitydefs2 = {}
for key,value in entitydefs.items():
entitydefs2[value] = key
# end for
def corregirEntitys(texto):
'''This function replaces special characters with &entities; '''
if not texto:
return texto
# end if
if not isinstance(texto, unicode):
texto = texto.decode('latin1')
result = ''
for c in texto:
if not (c in ('<', '>', '/', '"', "'", '=', '&')):
if c.encode("latin1", 'replace') in entitydefs2.keys():
rep = entitydefs2[c.encode("latin1", "replace")]
rep = '&'+rep+';'
result += rep
else:
result += c
# end if
else:
result += c
# end if
# end for
return result
# end def
def getException():
return '\n'.join(traceback.format_exception (sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))
semaforo_html2text = _threading.BoundedSemaphore()
def makeHeader(text):
if not text:
text = ''
if not isinstance(text, unicode):
text = text.decode('latin1')
# end if
if isinstance(text, unicode):
text = text.encode('utf-8')
# end if
try:
if has_html2text:
text = html2text(text).strip()
except UnicodeError:
pass
return str(email.Header.make_header([(text, 'utf-8')]))
# end def
def getPlainText(html, links=True):
if not isinstance(html, unicode):
html = html.decode('latin1')
# end if
plain_text = u''
if has_html2text:
# html2text seems to be not-thread-safe, so I'm avoiding concurrency
# here using a semaphore
semaforo_html2text.acquire()
try:
try:
plain_text = html2text(html).strip()
except:
plain_text = getException ()
mylog.exception ('Error en getPlainText')
# end try
finally:
semaforo_html2text.release()
# end try
# end if
if not isinstance(plain_text, unicode):
plain_text = plain_text.decode('utf-8')
# end if
return plain_text
# end def
def md5texto(texto):
m = md5()
m.update (texto)
return m.hexdigest()
# end def
class Item:
def __init__(self, original, channel, encoding="utf-8", remove=None):
global historico_posts
if encoding == '': encoding="utf-8"
for key in original.keys():
if type(original.get(key)) == type(""):
original[key] = original[key].decode(encoding, "replace")
# end if
# end for
self.original = original
self.link = GetValue(original.get('link', channel.htmlUrl))
if original.has_key('enclosures'):
self.enclosures = original.enclosures
else:
self.enclosures = ()
# end if
self.texto_nuevo = ''
self.text_key = 'None'
for k in 'content body content_encoded description summary summary_detail'.split():
if k in original.keys():
if original[k]:
self.texto_nuevo = original[k]
self.text_key = k
break
# end if
# end if
# end for
if self.text_key == None and 'summary_detail' in original.keys() and 'value' in original['summary_detail'].keys():
self.texto_nuevo = original['summary_detail']['value']
self.text_key = "summary_detail/value"
# end if
self.texto_nuevo = GetValue (self.texto_nuevo)
if channel.download_link:
try:
downloaded_file = cache.urlopen(self.link, max_age=999999, can_pipe=False);
explicacion = downloaded_file.info['Cache-Result']
mylog.debug (explicacion + ' ' + self.link)
except KeyboardInterrupt:
raise
except:
mylog.exception ('Cannot download '+self.link)
downloaded_file = None
# end try
if downloaded_file:
self.texto_nuevo = downloaded_file.content.read()
# end if
# end if
if remove:
rc = re.compile (remove, re.I+re.S+re.X)
self.texto_nuevo = re.sub(rc, '', self.texto_nuevo)
if type(self.texto_nuevo) == type(""):
try:
self.texto_nuevo = self.texto_nuevo.decode(encoding)
except UnicodeDecodeError, e:
mylog.debug("Error in " + channel.xmlUrl + ", " + original.get('title', original.get('url', '?')) + ": " + str(e))
self.texto_nuevo = self.texto_nuevo.decode(encoding, 'replace')
# end try
# end if
self.texto_nuevo = corregirEntitys(self.texto_nuevo)
self.subject = GetValue (original.get('title', ''))
if not self.subject:
sin_html = ' '.join(re.compile('<.+?>').split(self.texto_nuevo))
self.subject = sin_html[:60].strip()
if '\n' in self.subject:
self.subject = self.subject.split('\n')[0]
# end if
self.subject += '...'
# end if
m = md5()
m.update (self.link.encode('utf-8', 'replace'))
m.update (channel.xmlUrl)
m.update (self.subject.encode('utf-8', 'replace'))
self.urlHash = m.hexdigest()
self.subject = self.subject
if 'modified_parsed' in original.keys() and original['modified_parsed'] != None:
x = original['modified_parsed']
self.timestamp = datetime(year=x[0], month=x[1], day=x[2], hour=x[3], minute=x[4], second=x[5])
else:
self.timestamp = datetime.now()
# end if
self.texto = self.texto_nuevo
if channel.diff and historico_posts.has_key(self.urlHash):
before_diff = self.texto_nuevo
differ = TextDiff(historico_posts[self.urlHash]['text'], self.texto_nuevo)
self.texto = differ.getDiff()
if self.texto <> before_diff:
self.timestamp = datetime.now()
# end if
self.channel = channel
self.creatorName = GetValue(original.get('creator', original.get('author', channel.creator)))
# set the default From: address to "rss@domain" where domain comes from the site's url
self.creatorEmail = 'rss@'+ urlparse.urlparse(channel.htmlUrl)[1]
# search for an email address, in the item first, then in the channel
r = re.compile('([A-Za-z0-9_.\+]+@[A-Za-z0-9_.]+)')
for x in [original.get('creator', ''), original.get('author', ''), channel.creator]:
try:
m = r.search(x)
if m:
self.creatorEmail = m.group(1)
except TypeError:
pass
self.is_modified = 'Unknown'
self.custom_tags = {}
known_tags = ['text', 'link', 'htmlUrl', 'xmlUrl', 'description', 'path', 'title', 'index'] + OPML_DEFAULTS.keys()
for k in channel.parameters.keys():
if not k in known_tags:
self.custom_tags[k] = channel.parameters[k]
def __repr__(self):
#return 'Link: %s\nTimeStamp: %s\nTexto: %s' % (self.link, self.timestamp, self.texto)
return self.subject
#return self.original.__repr__()
# end def
def GetEmail(self, envio, destinatario, format="multipart", encoding='utf-8', include_threading=False, subject_prefix=None, from_address=None):
global historico_posts
template = """
<p>
__body__
</p>
<hr />
<p>
<a href="__htmlUrl__">Home</a>
<a href="__permalink__">Link</a>
__enclosure__
</p>
"""
#self.texto = expandNumEntities(self.texto)
body = self.texto
text_version = getPlainText (body)
text_version = text_version + "\n\n" + "Home: [ " + self.channel.htmlUrl + " ]\n" + "Link: [ " + self.link + " ]\n"
if self.enclosures:
for enclosure in self.enclosures:
text_version = text_version + "Enclosure: [ " + enclosure.get('url') + " (" + formatNumber(enclosure.get('length', '0')) + ") ]\n"
# end for
# end if
html_version = template
html_version = html_version.replace('__subject__', self.subject)
html_version = html_version.replace('__body__', body)
html_version = html_version.replace('__permalink__', self.link)
html_version = html_version.replace('__htmlUrl__', self.channel.htmlUrl)
enclosure_text = ""
if self.enclosures:
for enclosure in self.enclosures:
enclosure_text = enclosure_text + "<a href=\"" + enclosure.get('url') + "\"> Enclosure (" + formatNumber(enclosure.get('length', '0')) + ")</a> "
# end for
#ed if
html_version = html_version.replace('__enclosure__', enclosure_text)
img_search_re = re.compile('<.*?img.+?src.*?=.*?[\'"](.*?)[\'"]', re.IGNORECASE)
# edit all the image urls that are relative to make them fully qualified
if self.link:
urls = re.findall(img_search_re, html_version)
for url in urls:
url_parts = urlparse.urlsplit(url)
if not url_parts[1]:
if not url_parts[0].upper() == 'FILE:':
full_url = urlparse.urljoin(self.link, url)
html_version = html_version.replace (url, full_url)
# end if
# end if
# end if
images = None
if format != "plaintext" and self.channel.download_images:
urls = re.findall(img_search_re, html_version)
if urls:
images = []
seenurls = []
i = 0
for url in urls:
if url:
# check if this url was already proccesed
previous = [x['url'] for x in images]
if not (url in previous):
filename = os.path.basename(url)
if '?' in filename:
filename = filename[:filename.find('?')]
ext = os.path.splitext(url)[1]
if '?' in ext:
ext = ext[:ext.find('?')]
# end if
name = '%s%s' % (md5texto(filename+str(i)),ext)
html_version = html_version.replace(url, 'cid:'+name)
images += [{'name':name, 'url':url, 'filename':filename},]
i += 1
# end if
# end if
# end for
seenurls = None
# end if
# end if