home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 October / maximum-cd-2011-10.iso / DiscContents / digsby_setup.exe / lib / mail / emailobj.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-06-22  |  7.1 KB  |  220 lines

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