home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 February / maximum-cd-2011-02.iso / DiscContents / digsby_setup85.exe / lib / mail / imapcheck.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-11-24  |  7.1 KB  |  265 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. import imaplib
  5. import time
  6. import re
  7. import email
  8. from datetime import datetime
  9. from pprint import pformat
  10. from mail.emailobj import DecodedEmail
  11. from mail import Email, AuthenticationError
  12. from logging import getLogger
  13. log = getLogger('imapcheck')
  14. from util import autoassign, callsback, traceguard
  15. import traceback
  16. import ssl
  17. from imaplib import IMAP4_SSL_PORT
  18. import socket
  19.  
  20. class IMAP4_SSL_Fixed(imaplib.IMAP4_SSL):
  21.     
  22.     def open(self, host = '', port = IMAP4_SSL_PORT):
  23.         self.host = host
  24.         self.port = port
  25.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  26.         self.sock.connect((host, port))
  27.         self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, suppress_ragged_eofs = False)
  28.  
  29.     
  30.     def readline(self):
  31.         line = []
  32.         while None:
  33.             char = self.sslobj.read(1)
  34.             if not char:
  35.                 raise ssl.SSLError(ssl.SSL_ERROR_EOF)
  36.             line.append(char)
  37.             if char == '\n':
  38.                 return ''.join(line)
  39.             continue
  40.             return None
  41.  
  42.     
  43.     def read(self, size):
  44.         chunks = []
  45.         read = 0
  46.         while read < size:
  47.             data = self.sslobj.read(min(size - read, 16384))
  48.             if not data:
  49.                 raise ssl.SSLError(ssl.SSL_ERROR_EOF)
  50.             data
  51.             read += len(data)
  52.             chunks.append(data)
  53.         return ''.join(chunks)
  54.  
  55.  
  56.  
  57. class IMAPCheck(object):
  58.     
  59.     def __init__(self, maxfetch = 25):
  60.         self.maxfetch = maxfetch
  61.         self.cache = { }
  62.         self.srv = None
  63.  
  64.     
  65.     def login(self, host, port, ssl, user, password):
  66.         autoassign(self, locals())
  67.  
  68.     
  69.     def update(self):
  70.         if self.srv is not None:
  71.             srv = self.srv
  72.             self.srv = None
  73.             
  74.             try:
  75.                 srv.logout()
  76.             except ssl.SSLError:
  77.                 e = None
  78.                 log.error('got SSLError during logout: %r', e)
  79.             except Exception:
  80.                 traceback.print_exc()
  81.             except:
  82.                 None<EXCEPTION MATCH>ssl.SSLError
  83.             
  84.  
  85.         None<EXCEPTION MATCH>ssl.SSLError
  86.         if self.ssl:
  87.             cls = IMAP4_SSL_Fixed
  88.         else:
  89.             cls = imaplib.IMAP4
  90.         srv = cls(self.host, self.port)
  91.         
  92.         try:
  93.             srv.login(srv._checkquote(self.user.encode('ascii')), self.password)
  94.         except (imaplib.IMAP4.error, imaplib.IMAP4_SSL.error):
  95.             raise AuthenticationError
  96.  
  97.         srv.select()
  98.         (res, lst) = srv.uid('search', None, '(UNSEEN UNDELETED)')
  99.         if res != 'OK':
  100.             raise Exception('could not retrieve unseen messages from the server')
  101.         res != 'OK'
  102.         uids = None if lst[0] else []
  103.         log.info('%d unseen uids: %r', len(uids), uids)
  104.         msg_sendtimes = { }
  105.         unread_msgs = []
  106.         if uids:
  107.             (res, lst) = srv.uid('FETCH', ','.join(uids), '(INTERNALDATE FLAGS)')
  108.             if res != 'OK':
  109.                 raise Exception('could not retrieve message dates from the server')
  110.             res != 'OK'
  111.             for resp in lst:
  112.                 
  113.                 try:
  114.                     dt = getDatetime(resp)
  115.                     uid = getUid(resp)
  116.                     flags = getFlags(resp)
  117.                     log.info('%s %r', uid, flags)
  118.                     if dt is not None and uid is not None and '\\Seen' not in flags and '\\Deleted' not in flags:
  119.                         unread_msgs.append((dt, uid))
  120.                         msg_sendtimes[uid] = dt
  121.                 continue
  122.                 except Exception:
  123.                     traceback.print_exc()
  124.                     continue
  125.                 
  126.  
  127.             
  128.         
  129.         count = len(unread_msgs)
  130.         unread_msgs.sort(reverse = True)
  131.         uids_to_fetch = []
  132.         uids_already_fetched = []
  133.         for dt, uid in unread_msgs[:self.maxfetch]:
  134.             
  135.             try:
  136.                 if uid not in self.cache:
  137.                     uids_to_fetch += [
  138.                         uid]
  139.                 else:
  140.                     uids_already_fetched += [
  141.                         uid]
  142.             continue
  143.             except Exception:
  144.                 traceback.print_exc()
  145.                 continue
  146.             
  147.  
  148.         
  149.         emailobjs = []
  150.         pref = pref
  151.         import common
  152.         if uids_to_fetch:
  153.             (res, lst) = srv.uid('fetch', ','.join(uids_to_fetch), '(BODY.PEEK[]<0.%d>)' % pref('imaplib.max_fetch_bytes', default = 5120, type = int))
  154.             if res != 'OK':
  155.                 raise Exception('could not retrieve message contents from the server')
  156.             res != 'OK'
  157.             lst2 = []
  158.             currinfo = []
  159.             currdata = None
  160.             for resp in lst + [
  161.                 (None, None)]:
  162.                 if isinstance(resp, tuple):
  163.                     if currdata:
  164.                         lst2.append((currinfo, currdata))
  165.                         currdata = None
  166.                         currinfo = []
  167.                     
  168.                     currinfo.append(resp[0])
  169.                     currdata = resp[1]
  170.                     continue
  171.                 currinfo.append(resp)
  172.             
  173.             for resp in lst2:
  174.                 
  175.                 try:
  176.                     if isinstance(resp, tuple):
  177.                         (nfo, msg) = resp
  178.                         uid = getUid(nfo)
  179.                         sndtime = msg_sendtimes[uid]
  180.                         emailobj = emailFromString(uid, msg, sndtime)
  181.                         self.cache[uid] = emailobj
  182.                         emailobjs += [
  183.                             emailobj]
  184.                 continue
  185.                 except Exception:
  186.                     traceback.print_exc()
  187.                     continue
  188.                 
  189.  
  190.             
  191.         
  192.         for uid in uids_already_fetched:
  193.             emailobjs += [
  194.                 self.cache[uid]]
  195.         
  196.         log.info('untagged responses')
  197.         log.info(pformat(srv.untagged_responses))
  198.         srv.untagged_responses.clear()
  199.         self.srv = srv
  200.         return (count, emailobjs)
  201.  
  202.     
  203.     def markAsRead(self, msg, callback = None):
  204.         
  205.         try:
  206.             self.srv.uid('STORE', msg.id, '+FLAGS.SILENT', '(\\SEEN)')
  207.         except:
  208.             import traceback
  209.             traceback.print_exc()
  210.             return callback.error()
  211.  
  212.         callback.success()
  213.  
  214.     markAsRead = callsback(markAsRead)
  215.     
  216.     def delete(self, msg, callback = None):
  217.         
  218.         try:
  219.             self.srv.uid('STORE', msg.id, '+FLAGS.SILENT', '(\\DELETED \\SEEN)')
  220.         except:
  221.             import traceback
  222.             traceback.print_exc()
  223.             return callback.error()
  224.  
  225.         callback.success()
  226.  
  227.     delete = callsback(delete)
  228.  
  229.  
  230. def emailFromString(uid, s, sendtime_if_error):
  231.     return Email.fromEmailMessage(uid, DecodedEmail(email.message_from_string(s)), sendtime_if_error)
  232.  
  233.  
  234. def getDatetime(s):
  235.     timetuple = imaplib.Internaldate2tuple(s)
  236.     if timetuple is not None:
  237.         return datetime.fromtimestamp(time.mktime(timetuple))
  238.  
  239. _uidMatcher = re.compile('UID ([0-9]+)\\D')
  240.  
  241. def getUid(s):
  242.     if isinstance(s, basestring):
  243.         vals = [
  244.             s]
  245.     else:
  246.         vals = s
  247.     for val in vals:
  248.         match = _uidMatcher.search(val)
  249.         if match:
  250.             return match.group(1)
  251.     
  252.  
  253.  
  254. def getFlags(s):
  255.     return imaplib.ParseFlags(s)
  256.  
  257. if __name__ == '__main__':
  258.     i = IMAPCheck()
  259.     i.login('imap.aol.com', 143, False, 'digsby04', 'thisisnotapassword')
  260.     print 
  261.     print 'DONE'
  262.     print 
  263.     print repr(i.update())
  264.  
  265.