home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 June / maximum-cd-2009-06.iso / DiscContents / digsby_setup.exe / lib / mail / emailobj.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-02-26  |  7.0 KB  |  219 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. from util import autoassign, strip_html_and_tags, replace_newlines, Storage
  5. from util.lrucache import lru_cache
  6. from util.auxencodings import fuzzydecode
  7. from email.utils import parseaddr, parsedate
  8. from email.header import decode_header
  9. from datetime import datetime
  10. import email.message as email
  11. from common import pref
  12. import sys
  13. import traceback
  14. import logging
  15. log = logging.getLogger('emailobj')
  16. replace_newlines = lru_cache(100)(replace_newlines)
  17. UnicodeErrors = (UnicodeEncodeError, UnicodeDecodeError)
  18.  
  19. def unicode_hdr(hdr, fallback = None):
  20.     more_encs = None if fallback else []
  21.     
  22.     try:
  23.         return (u''.join,)((lambda .0: for hdr, encoding in .0:
  24. None if encoding else hdr)(decode_header(hdr)))
  25.     except UnicodeErrors:
  26.         return fuzzydecode(hdr, more_encs + [
  27.             'utf-8'])
  28.  
  29.  
  30.  
  31. def find_part(email, types):
  32.     if not email.is_multipart():
  33.         return email
  34.     
  35.     results = (dict,)((lambda .0: for part in .0:
  36. if part.get_content_type() in types:
  37. (part.get_content_type(), part)continue)(email))
  38.     print results
  39.     for ty in types:
  40.         if ty in results:
  41.             return results[ty]
  42.             continue
  43.     
  44.  
  45.  
  46. def find_attachments(email):
  47.     attachments = { }
  48.     for part in email:
  49.         if 'Content-Disposition' in part.keys() and 'attachment' in part['Content-Disposition']:
  50.             attachments[part.get_filename()] = Storage(data = part.get_payload(decode = True), content_type = part.get_content_type())
  51.             continue
  52.     
  53.     return attachments
  54.  
  55.  
  56. def parse_content(part):
  57.     charset = part.get_content_charset()
  58.     content_type = part.get_content_type()
  59.     payload = part.get_payload(decode = True)
  60.     html = content_type == 'text/html'
  61.     if payload is None:
  62.         payload = ''
  63.     
  64.     
  65.     try:
  66.         if not charset:
  67.             pass
  68.         content = payload.decode('ascii')
  69.     except (UnicodeDecodeError, LookupError):
  70.         content = payload.decode('utf-8', 'replace')
  71.  
  72.     if html:
  73.         content = strip_html_and_tags(content, [
  74.             'style'])
  75.     else:
  76.         content = content
  77.     return content
  78.  
  79.  
  80. class Email(object):
  81.     
  82.     def __init__(self, id = None, fromname = None, fromemail = None, sendtime = None, subject = None, content = None, attachments = None, labels = None):
  83.         autoassign(self, locals())
  84.  
  85.     
  86.     def update(self, email):
  87.         if isinstance(email, dict):
  88.             attrs = email
  89.         else:
  90.             attrs = vars(email)
  91.         autoassign(self, dict((lambda .0: for k, v in .0:
  92. if v is not None:
  93. (k, v)continue)(attrs.iteritems())))
  94.  
  95.     
  96.     def fromEmailMessage(cls, id, email, sendtime_if_error = None):
  97.         encoding = email.get_content_charset()
  98.         (realname, email_address) = parseaddr(email['From'])
  99.         realname = unicode_hdr(realname, encoding)
  100.         _email = email
  101.         
  102.         try:
  103.             datetuple = parsedate(email['Date'])
  104.             sendtime = datetime(*datetuple[:7])
  105.         except Exception:
  106.             traceback.print_exc()
  107.             print >>sys.stderr, 'using %s for "sendtime" instead' % sendtime_if_error
  108.             sendtime = sendtime_if_error
  109.  
  110.         
  111.         try:
  112.             attachments = find_attachments(email)
  113.         except:
  114.             attachments = { }
  115.  
  116.         part = find_part(email, ('text/plain', 'text/html'))
  117.         if part is None:
  118.             content = u''
  119.         else:
  120.             content = parse_content(part)
  121.         content = replace_newlines(content)
  122.         prev_length = pref('email.preview_length', 200)
  123.         if len(content) > prev_length:
  124.             content = content[:prev_length] + '...'
  125.         else:
  126.             content
  127.         email = cls(id, realname, email_address, sendtime, email['Subject'], content = content, attachments = attachments)
  128.         return email
  129.  
  130.     fromEmailMessage = classmethod(fromEmailMessage)
  131.     
  132.     def __eq__(self, other):
  133.         if not isinstance(other, Email):
  134.             return False
  135.         
  136.         return self.id == other.id
  137.  
  138.     
  139.     def __cmp__(self, other):
  140.         
  141.         try:
  142.             return -cmp(self.sendtime, other.sendtime)
  143.         except TypeError:
  144.             return -1
  145.  
  146.  
  147.     
  148.     def domain(self):
  149.         f = self.fromemail
  150.         if f is not None:
  151.             return f[f.find('@') + 1:]
  152.         
  153.  
  154.     domain = property(domain)
  155.     
  156.     def __unicode__(self):
  157.         if not self.subject:
  158.             pass
  159.         lines = [
  160.             unicode('Subject: %s' % '<none>').encode('utf-8')]
  161.         if self.fromname:
  162.             _fromstr = self.fromname
  163.             if self.fromemail:
  164.                 _fromstr += ' <%s>' % self.fromemail
  165.             
  166.         elif self.fromemail:
  167.             _fromstr = self.fromemail
  168.         else:
  169.             _fromstr = '<unknown>'
  170.         lines.append('From: %s' % _fromstr)
  171.         if self.sendtime:
  172.             lines.append('Sent at %s' % self.sendtime)
  173.         
  174.         if self.content:
  175.             lines.append('')
  176.             lines.append(unicode(self.content))
  177.         
  178.         self.lines = lines
  179.         return u''.join(lines)
  180.  
  181.     
  182.     __str__ = lambda self: self.__unicode__().decode('ascii', 'ignore')
  183.     
  184.     def __repr__(self):
  185.         
  186.         try:
  187.             if not self.fromemail:
  188.                 pass
  189.             return u'<Email (Subject: %r, From: %r)>' % (self.subject[:30], self.fromname)
  190.         except Exception:
  191.             return u'<Email from %r>' % self.fromemail
  192.  
  193.  
  194.  
  195.  
  196. class DecodedEmail(email.message.Message):
  197.     
  198.     def __init__(self, myemail):
  199.         self.email = myemail
  200.  
  201.     
  202.     def __getattr__(self, attr, val = sentinel):
  203.         result = getattr(self.email, attr, val)
  204.         if result is sentinel:
  205.             raise AttributeError
  206.         else:
  207.             return result
  208.  
  209.     
  210.     def __getitem__(self, header):
  211.         s = email.message.Message.__getitem__(self, header)
  212.         if header == 'Content':
  213.             return s
  214.         else:
  215.             return unicode_hdr(s, self.get_content_charset())
  216.  
  217.     __iter__ = email.message.Message.walk
  218.  
  219.