Merge pull request #232 from odoo-dev/saas-4-mass_mailing-fixes-tde
[odoo/odoo.git] / addons / email_template / html2text.py
1 #!/usr/bin/env python
2 """html2text: Turn HTML into equivalent Markdown-structured text."""
3 __version__ = "2.36"
4 __author__ = "Aaron Swartz (me@aaronsw.com)"
5 __copyright__ = "(C) 2004-2008 Aaron Swartz. GNU GPL 3."
6 __contributors__ = ["Martin 'Joey' Schulze", "Ricardo Reyes", "Kevin Jay North"]
7
8 # TODO:
9 #   Support decoded entities with unifiable.
10
11 if not hasattr(__builtins__, 'True'): True, False = 1, 0
12 import re, sys, urllib, htmlentitydefs, codecs
13 import sgmllib
14 import urlparse
15 sgmllib.charref = re.compile('&#([xX]?[0-9a-fA-F]+)[^0-9a-fA-F]')
16
17 try: from textwrap import wrap
18 except: pass
19
20 # Use Unicode characters instead of their ascii psuedo-replacements
21 UNICODE_SNOB = 0
22
23 # Put the links after each paragraph instead of at the end.
24 LINKS_EACH_PARAGRAPH = 0
25
26 # Wrap long lines at position. 0 for no wrapping. (Requires Python 2.3.)
27 BODY_WIDTH = 78
28
29 # Don't show internal links (href="#local-anchor") -- corresponding link targets
30 # won't be visible in the plain text file anyway.
31 SKIP_INTERNAL_LINKS = False
32
33 ### Entity Nonsense ###
34
35 def name2cp(k):
36     if k == 'apos': return ord("'")
37     if hasattr(htmlentitydefs, "name2codepoint"): # requires Python 2.3
38         return htmlentitydefs.name2codepoint[k]
39     else:
40         k = htmlentitydefs.entitydefs[k]
41         if k.startswith("&#") and k.endswith(";"): return int(k[2:-1]) # not in latin-1
42         return ord(codecs.latin_1_decode(k)[0])
43
44 unifiable = {'rsquo':"'", 'lsquo':"'", 'rdquo':'"', 'ldquo':'"',
45 'copy':'(C)', 'mdash':'--', 'nbsp':' ', 'rarr':'->', 'larr':'<-', 'middot':'*',
46 'ndash':'-', 'oelig':'oe', 'aelig':'ae',
47 'agrave':'a', 'aacute':'a', 'acirc':'a', 'atilde':'a', 'auml':'a', 'aring':'a',
48 'egrave':'e', 'eacute':'e', 'ecirc':'e', 'euml':'e',
49 'igrave':'i', 'iacute':'i', 'icirc':'i', 'iuml':'i',
50 'ograve':'o', 'oacute':'o', 'ocirc':'o', 'otilde':'o', 'ouml':'o',
51 'ugrave':'u', 'uacute':'u', 'ucirc':'u', 'uuml':'u'}
52
53 unifiable_n = {}
54
55 for k in unifiable.keys():
56     unifiable_n[name2cp(k)] = unifiable[k]
57
58 def charref(name):
59     if name[0] in ['x','X']:
60         c = int(name[1:], 16)
61     else:
62         c = int(name)
63
64     if not UNICODE_SNOB and c in unifiable_n.keys():
65         return unifiable_n[c]
66     else:
67         return unichr(c)
68
69 def entityref(c):
70     if not UNICODE_SNOB and c in unifiable.keys():
71         return unifiable[c]
72     else:
73         try: name2cp(c)
74         except KeyError: return "&" + c
75         else: return unichr(name2cp(c))
76
77 def replaceEntities(s):
78     s = s.group(1)
79     if s[0] == "#":
80         return charref(s[1:])
81     else: return entityref(s)
82
83 r_unescape = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
84 def unescape(s):
85     return r_unescape.sub(replaceEntities, s)
86
87 def fixattrs(attrs):
88     # Fix bug in sgmllib.py
89     if not attrs: return attrs
90     newattrs = []
91     for attr in attrs:
92         newattrs.append((attr[0], unescape(attr[1])))
93     return newattrs
94
95 ### End Entity Nonsense ###
96
97 def onlywhite(line):
98     """Return true if the line does only consist of whitespace characters."""
99     for c in line:
100         if c is not ' ' and c is not '  ':
101             return c is ' '
102     return line
103
104 def optwrap(text):
105     """Wrap all paragraphs in the provided text."""
106     if not BODY_WIDTH:
107         return text
108
109     assert wrap, "Requires Python 2.3."
110     result = ''
111     newlines = 0
112     for para in text.split("\n"):
113         if len(para) > 0:
114             if para[0] is not ' ' and para[0] is not '-' and para[0] is not '*':
115                 for line in wrap(para, BODY_WIDTH):
116                     result += line + "\n"
117                 result += "\n"
118                 newlines = 2
119             else:
120                 if not onlywhite(para):
121                     result += para + "\n"
122                     newlines = 1
123         else:
124             if newlines < 2:
125                 result += "\n"
126                 newlines += 1
127     return result
128
129 def hn(tag):
130     if tag[0] == 'h' and len(tag) == 2:
131         try:
132             n = int(tag[1])
133             if n in range(1, 10): return n
134         except ValueError: return 0
135
136 class _html2text(sgmllib.SGMLParser):
137     def __init__(self, out=sys.stdout.write, baseurl=''):
138         sgmllib.SGMLParser.__init__(self)
139
140         if out is None: self.out = self.outtextf
141         else: self.out = out
142         self.outtext = u''
143         self.quiet = 0
144         self.p_p = 0
145         self.outcount = 0
146         self.start = 1
147         self.space = 0
148         self.a = []
149         self.astack = []
150         self.acount = 0
151         self.list = []
152         self.blockquote = 0
153         self.pre = 0
154         self.startpre = 0
155         self.lastWasNL = 0
156         self.abbr_title = None # current abbreviation definition
157         self.abbr_data = None # last inner HTML (for abbr being defined)
158         self.abbr_list = {} # stack of abbreviations to write later
159         self.baseurl = baseurl
160
161     def outtextf(self, s):
162         self.outtext += s
163
164     def close(self):
165         sgmllib.SGMLParser.close(self)
166
167         self.pbr()
168         self.o('', 0, 'end')
169
170         return self.outtext
171
172     def handle_charref(self, c):
173         self.o(charref(c))
174
175     def handle_entityref(self, c):
176         self.o(entityref(c))
177
178     def unknown_starttag(self, tag, attrs):
179         self.handle_tag(tag, attrs, 1)
180
181     def unknown_endtag(self, tag):
182         self.handle_tag(tag, None, 0)
183
184     def previousIndex(self, attrs):
185         """ returns the index of certain set of attributes (of a link) in the
186             self.a list
187
188             If the set of attributes is not found, returns None
189         """
190         if not attrs.has_key('href'): return None
191
192         i = -1
193         for a in self.a:
194             i += 1
195             match = 0
196
197             if a.has_key('href') and a['href'] == attrs['href']:
198                 if a.has_key('title') or attrs.has_key('title'):
199                         if (a.has_key('title') and attrs.has_key('title') and
200                             a['title'] == attrs['title']):
201                             match = True
202                 else:
203                     match = True
204
205             if match: return i
206
207     def handle_tag(self, tag, attrs, start):
208         attrs = fixattrs(attrs)
209
210         if hn(tag):
211             self.p()
212             if start: self.o(hn(tag)*"#" + ' ')
213
214         if tag in ['p', 'div']: self.p()
215
216         if tag == "br" and start: self.o("  \n")
217
218         if tag == "hr" and start:
219             self.p()
220             self.o("* * *")
221             self.p()
222
223         if tag in ["head", "style", 'script']:
224             if start: self.quiet += 1
225             else: self.quiet -= 1
226
227         if tag in ["body"]:
228             self.quiet = 0 # sites like 9rules.com never close <head>
229
230         if tag == "blockquote":
231             if start:
232                 self.p(); self.o('> ', 0, 1); self.start = 1
233                 self.blockquote += 1
234             else:
235                 self.blockquote -= 1
236                 self.p()
237
238         if tag in ['em', 'i', 'u']: self.o("_")
239         if tag in ['strong', 'b']: self.o("**")
240         if tag == "code" and not self.pre: self.o('`') #TODO: `` `this` ``
241         if tag == "abbr":
242             if start:
243                 attrsD = {}
244                 for (x, y) in attrs: attrsD[x] = y
245                 attrs = attrsD
246
247                 self.abbr_title = None
248                 self.abbr_data = ''
249                 if attrs.has_key('title'):
250                     self.abbr_title = attrs['title']
251             else:
252                 if self.abbr_title != None:
253                     self.abbr_list[self.abbr_data] = self.abbr_title
254                     self.abbr_title = None
255                 self.abbr_data = ''
256
257         if tag == "a":
258             if start:
259                 attrsD = {}
260                 for (x, y) in attrs: attrsD[x] = y
261                 attrs = attrsD
262                 if attrs.has_key('href') and not (SKIP_INTERNAL_LINKS and attrs['href'].startswith('#')):
263                     self.astack.append(attrs)
264                     self.o("[")
265                 else:
266                     self.astack.append(None)
267             else:
268                 if self.astack:
269                     a = self.astack.pop()
270                     if a:
271                         i = self.previousIndex(a)
272                         if i is not None:
273                             a = self.a[i]
274                         else:
275                             self.acount += 1
276                             a['count'] = self.acount
277                             a['outcount'] = self.outcount
278                             self.a.append(a)
279                         self.o("][" + `a['count']` + "]")
280
281         if tag == "img" and start:
282             attrsD = {}
283             for (x, y) in attrs: attrsD[x] = y
284             attrs = attrsD
285             if attrs.has_key('src'):
286                 attrs['href'] = attrs['src']
287                 alt = attrs.get('alt', '')
288                 i = self.previousIndex(attrs)
289                 if i is not None:
290                     attrs = self.a[i]
291                 else:
292                     self.acount += 1
293                     attrs['count'] = self.acount
294                     attrs['outcount'] = self.outcount
295                     self.a.append(attrs)
296                 self.o("![")
297                 self.o(alt)
298                 self.o("]["+`attrs['count']`+"]")
299
300         if tag == 'dl' and start: self.p()
301         if tag == 'dt' and not start: self.pbr()
302         if tag == 'dd' and start: self.o('    ')
303         if tag == 'dd' and not start: self.pbr()
304
305         if tag in ["ol", "ul"]:
306             if start:
307                 self.list.append({'name':tag, 'num':0})
308             else:
309                 if self.list: self.list.pop()
310
311             self.p()
312
313         if tag == 'li':
314             if start:
315                 self.pbr()
316                 if self.list: li = self.list[-1]
317                 else: li = {'name':'ul', 'num':0}
318                 self.o("  "*len(self.list)) #TODO: line up <ol><li>s > 9 correctly.
319                 if li['name'] == "ul": self.o("* ")
320                 elif li['name'] == "ol":
321                     li['num'] += 1
322                     self.o(`li['num']`+". ")
323                 self.start = 1
324             else:
325                 self.pbr()
326
327         if tag in ["table", "tr"] and start: self.p()
328         if tag == 'td': self.pbr()
329
330         if tag == "pre":
331             if start:
332                 self.startpre = 1
333                 self.pre = 1
334             else:
335                 self.pre = 0
336             self.p()
337
338     def pbr(self):
339         if self.p_p == 0: self.p_p = 1
340
341     def p(self):
342         self.p_p = 2
343
344     def o(self, data, puredata=0, force=0):
345         if self.abbr_data is not None: self.abbr_data += data
346
347         if not self.quiet:
348             if puredata and not self.pre:
349                 data = re.sub('\s+', ' ', data)
350                 if data and data[0] == ' ':
351                     self.space = 1
352                     data = data[1:]
353             if not data and not force: return
354
355             if self.startpre:
356                 #self.out(" :") #TODO: not output when already one there
357                 self.startpre = 0
358
359             bq = (">" * self.blockquote)
360             if not (force and data and data[0] == ">") and self.blockquote: bq += " "
361
362             if self.pre:
363                 bq += "    "
364                 data = data.replace("\n", "\n"+bq)
365
366             if self.start:
367                 self.space = 0
368                 self.p_p = 0
369                 self.start = 0
370
371             if force == 'end':
372                 # It's the end.
373                 self.p_p = 0
374                 self.out("\n")
375                 self.space = 0
376
377
378             if self.p_p:
379                 self.out(('\n'+bq)*self.p_p)
380                 self.space = 0
381
382             if self.space:
383                 if not self.lastWasNL: self.out(' ')
384                 self.space = 0
385
386             if self.a and ((self.p_p == 2 and LINKS_EACH_PARAGRAPH) or force == "end"):
387                 if force == "end": self.out("\n")
388
389                 newa = []
390                 for link in self.a:
391                     if self.outcount > link['outcount']:
392                         self.out("   ["+`link['count']`+"]: " + urlparse.urljoin(self.baseurl, link['href']))
393                         if link.has_key('title'): self.out(" ("+link['title']+")")
394                         self.out("\n")
395                     else:
396                         newa.append(link)
397
398                 if self.a != newa: self.out("\n") # Don't need an extra line when nothing was done.
399
400                 self.a = newa
401
402             if self.abbr_list and force == "end":
403                 for abbr, definition in self.abbr_list.items():
404                     self.out("  *[" + abbr + "]: " + definition + "\n")
405
406             self.p_p = 0
407             self.out(data)
408             self.lastWasNL = data and data[-1] == '\n'
409             self.outcount += 1
410
411     def handle_data(self, data):
412         if r'\/script>' in data: self.quiet -= 1
413         self.o(data, 1)
414
415     def unknown_decl(self, data):
416         pass
417
418 def wrapwrite(text): sys.stdout.write(text.encode('utf8'))
419
420 def html2text_file(html, out=wrapwrite, baseurl=''):
421     h = _html2text(out, baseurl)
422     h.feed(html)
423     h.feed("")
424     return h.close()
425
426 def html2text(html, baseurl=''):
427     return optwrap(html2text_file(html, None, baseurl))
428
429 if __name__ == "__main__":
430     baseurl = ''
431     if sys.argv[1:]:
432         arg = sys.argv[1]
433         if arg.startswith('http://'):
434             baseurl = arg
435             j = urllib.urlopen(baseurl)
436             try:
437                 from feedparser import _getCharacterEncoding as enc
438             except ImportError:
439                    enc = lambda x, y: ('utf-8', 1)
440             text = j.read()
441             encoding = enc(j.headers, text)[0]
442             if encoding == 'us-ascii': encoding = 'utf-8'
443             data = text.decode(encoding)
444
445         else:
446             encoding = 'utf8'
447             if len(sys.argv) > 2:
448                 encoding = sys.argv[2]
449             f = open(arg, 'r')
450             try:
451                     data = f.read().decode(encoding)
452             finally:
453                     f.close()
454     else:
455         data = sys.stdin.read().decode('utf8')
456     wrapwrite(html2text(data, baseurl))
457
458
459 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: