From: Stas Z. <sta...@us...> - 2005-09-23 17:58:15
|
Update of /cvsroot/gmailagent/GA-libgmail2/demos In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10623/demos Added Files: COPYING MakeTarBall.py README archive.py filelist folderlist gcp.py gmailftpd.py gmailpopd.py gmailsmtp.py sendmsg.py test_fwd_attach.py test_notifier.py unreadmsgcount.py Log Message: Added the libgmail files --- NEW FILE: test_notifier.py --- #!/usr/bin/env python # # Rough first draft code to use "official" Gmail Notifier protocol # # Author: fol...@my... # # License: GPL 2.0 # # Obviously this all needs to be turned into something state-machiney # eventually. # # ObBlah: This program is for educational or interoperability purposes. # import os import sys # Allow us to run using installed `libgmail` or the one in parent directory. try: import libgmail logging.warn("Note: Using currently installed `libgmail` version.") except ImportError: # Urghhh... sys.path.insert(1, os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import libgmail r = '\n\x82\x02\x10\x93\xdd\xf8\xab\x87\x99\xa7\xf5\x0f\x18\xc9\x8c\xb2\xce\xea\x1f\x82\x01\x04^all\x82\x01\x02^f\x82\x01\x02^i\x82\x01\x02^u\x92\x01\x1e\n\x18\n\x12...@gm...\x12\x02me\x10\x01\x18\x01\x98\x01\x02\xa2\x01\x97\x01[Test] This is a really really really really really really really really blah blah blah blah long subject line blah blah 123456789012345678901234567890\xaa\x01\x16So, did you see it all\xb8\x01\x01\n\xfa\x01\x10\xd0\x8a\xb8\x97\xf5\xcd\xa4\xf5\x0f\x18\xbd\xea\x9b\xc9\xea\x1f\x82\x01\x04^all\x82\x01\x02^i\x82\x01\x02^u\x92\x01,\n&\n\x18...@go...\x12\nGmail Team\x10\x01\x18\x01\x98\x01\x02\xa2\x014Xxxxxx Xxxxxxx has accepted your invitation to Gmail\xaa\x01iXxxxxx Xxxxxxx has accepted your invitation to Gmail and has chosen the brand new address xxxxxx …\xb8\x01\x01\x88\x01\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' from pprint import pprint #pprint(r.split("\x01")) from cStringIO import StringIO def _getCode(s): """ """ code = ord(s.read(1)) print "code:", hex(code) assert(s.read(1) == "\x01") return code def _getNextBytes(s, nextReadCount = 0): """ """ if not nextReadCount: nextReadCount = ord(s.read(1)) bytes = s.read(nextReadCount) print "bytes:", repr(bytes), return bytes def parseThreadData(s, obj): """ """ # Data header # Unknown initial bytes--maybe message Id? ##nextReadCount = 19 # This does not seem to be consistent... # TODO: Find out why. # # Example: # ## 0x82 02 10 93 dd f8 ab 87 99 a7 f5 0f 18 c9 8c b2 ce ea 1f code: 0x82 ## 0xfa 01 10 d0 8a b8 97 f5 cd a4 f5 0f 18 bd ea 9b c9 ea 1f code: 0x82 ## 0x7f 10 b8 d5 a2 bf b6 b7 a4 f5 0f 18 f8 ed ee c8 ea 1f code: 0x82 ## 0x83 01 10 de 8d d5 8f d6 b3 a4 f5 0f 18 80 ad e7 c8 ea 1f code: 0x82 ## 0x89 01 10 e0 be 9e cb f3 a8 a4 f5 0f 18 98 e7 d1 c8 ea 1f code: 0x82 ## 0x96 01 10 95 d4 e3 d8 d6 a7 a4 f5 0f 18 d8 ae cf c8 ea 1f code: 0x82 ## 0x9e 02 10 94 ba be c9 9b a7 a2 f5 0f 18 a2 b5 ce c4 ea 1f code: 0x82 ## 0xc5 01 10 f0 94 d6 dd fb 94 a2 f5 0f 18 87 f6 a9 c4 ea 1f code: 0x82 ## 0xf5 01 10 e5 f3 b8 97 cd ab a0 f5 0f 18 9b 99 d7 c0 ea 1f code: 0x82 ## 0xf1 01 10 e2 b2 c9 ed f3 96 9b f5 0f 18 87 e7 ad b6 ea 1f code: 0x82 ## 0xaa 02 10 8a 8e ab f9 e7 fd 93 f5 0f 18 a5 ce fb a7 ea 1f code: 0x82 ## 0x81 02 10 a8 aa f4 f2 80 a7 df f4 0f 18 d0 82 ce be e9 1f code: 0x82 ## 0x92 02 10 a0 ae 98 c6 a5 d3 aa f4 0f 18 b8 cb a6 d5 e8 1f code: 0x82 ## 0xf8 01 10 8e d5 bf 98 f9 a0 a1 f4 0f 18 81 f2 c1 c2 e8 1f code: 0x82 ## 0x9c 02 10 be f1 c5 e6 c9 e5 9a f4 0f 18 88 92 cb b5 e8 1f code: 0x82 ## 0x86 02 10 e6 bc 99 ca a0 e5 9a f4 0f 18 f8 c3 ca b5 e8 1f code: 0x82 ## 0x87 01 10 91 ce 8d e8 90 96 9a f4 0f 18 90 a2 ac b4 e8 1f code: 0x82 ## 0xd3 01 10 be f7 b9 8b 81 b2 99 f4 0f 18 a8 81 e4 b2 e8 1f code: 0x82 ## 0xf3 01 10 e6 df b1 c3 ae 9b 97 f4 0f 18 d7 dc b6 ae e8 1f code: 0x82 ## 0xf1 01 10 88 95 e0 8f d9 d0 90 f4 0f 18 c4 b0 a1 a1 e8 1f code: 0x82 ## 0xef 01 10 cc e0 f9 92 b2 da 8f f4 0f 18 f1 e6 b4 9f e8 1f code: 0x82 ## 0xf0 01 10 ac b5 b6 fe af ec 86 f4 0f 18 d3 dd d8 8d e8 1f code: 0x82 ## 0x7b 10 fc 82 eb e0 85 a6 86 f4 0f 18 b7 8a cc 8c e8 1f code: 0x82 ## 0xa5 01 10 e3 f0 87 db f6 91 86 f4 0f 18 a4 ee a3 8c e8 1f code: 0x82 ## 0x73 10 dd a8 e9 b5 ee ea 85 f4 0f 18 ca dd d5 8b e8 1f code: 0x82 byteString = "0x" while True: # Skip unknown bytes (Note: This method probably isn't 100% reliable.) # TODO: Work out what they are--there are some similarities. # Guess is date/time/id? byte = s.read(1) byteString += "%02x " % ord(byte) if byte == "\x1f": print byteString, code = _getCode(s) break while code != 0x92: bytes = _getNextBytes(s) ##, nextReadCount) code = _getCode(s) ##if code == 0x92: ## break fromCount = 0 while True: fromCount +=1 # Unknown, time/date? print "Hard-coded read." bytes = _getNextBytes(s, 4) print # From bytes = _getNextBytes(s) print assert(s.read(1) == "\x12") bytes = _getNextBytes(s) print # --- This isn't right/or is messy... ---- # 0x10 == From? # 0x18 == To? code = _getCode(s) assert((code == 0x10) or (code == 0x18) or (code == 0x98) or (code == 0x92)) if code == 0x98: break if code == 0x92: continue byte = _getCode(s) if byte == 0x18: byte = _getCode(s) if byte == 0x98: break else: assert(byte == 0x92) # ---------------- print "fromCount:", fromCount #elif code == 0x10: # break ##nextReadCount = ord(s.read(1)) ##print "next:", nextReadCount # Unknown for nextReadCount in [2]: bytes = _getNextBytes(s, nextReadCount) print assert(s.read(1) == "\x01") # Subject # Extra long (> n, where n = ???) subjects have form: # length, 0x01, subject # # Shorter length subject have form: # length, subject # # TODO: Determine what happens when length > 255? nextReadCount = ord(s.read(1)) if s.read(1) != "\x01": s.seek(-1, 1) bytes = _getNextBytes(s, nextReadCount) code = _getCode(s) obj.subject = bytes # Message snippet bytes = _getNextBytes(s) code = _getCode(s) obj.snippet = bytes # End of message data #assert(s.read(1) == "\x01") threadMsgCount = ord(s.read(1)) print "threadMsgCount", threadMsgCount # TODO: Find some way to make sure this is true... class GmailNotifierResponse: """ """ def __init__(self, responseData): """ """ # TODO: Merge this with GmailThread? class GmailNotifierThread: """ """ def __init__(self, threadData): """ """ # TODO: Move this to method of this object? parseThreadData(threadData, self) if __name__ == "__main__": # Change the `0` to a `1` to retrieve a live response. if 0: import sys from getpass import getpass try: name = sys.argv[1] except IndexError: name = raw_input("Gmail account name: ") pw = getpass("Password: ") ga = libgmail.GmailAccount(name, pw) print "\nPlease wait, logging in..." #import pdb; pdb.set_trace() ga.login() print "Log in successful.\n" r = ga._retrievePage("https://gmail.google.com/gmail?ui=pb&q=label:^i%20label:^u") #r = ga._retrievePage("https://gmail.google.com/gmail?ui=pb&q=label:^all") #print repr(r) pprint(r.split("\x01")) s = StringIO(r) numMsgs = 0 threads = [] while True: code = ord(s.read(1)) if code == 0x0a: numMsgs += 1 threads.append(GmailNotifierThread(s)) elif code == 0x88: # trailer assert(s.read(1) == "\x01") # If there are no messages there's no trailing count? msgCount = ord(s.read(1)) # TODO: What about count > 255? print "Messages:", msgCount print "Messages found:", numMsgs # Maximum of 30 Messages? try: assert(msgCount == numMsgs) print "All messages retrieved." except AssertionError: print "Not all messages retrieved." assert(msgCount > 30) assert(numMsgs == 30) padding = s.read() # Padding ensures data length is power of 2. print "padding bytes:", len(padding) try: assert(len([byte for byte in padding if byte != "\x00"]) == 0) except AssertionError: # What is the extra data value? ("more", "not all shown"?) print "AssertionError: Not all padding blank." print repr(padding[:10]) break else: raise Exception("Unknown code") print "Total length:", len(r) print for th in threads: print th.subject print th.snippet print --- NEW FILE: unreadmsgcount.py --- #!/usr/bin/env python # # unreadmsgcount.py -- Demo to return unread message count with saved state # # $Revision: 1.1 $ ($Date: 2005/09/23 17:58:08 $) # # Author: fol...@my... # # License: GPL 2.0 # # # This demo intends to show how account state can be saved between script # runs. # import os import sys import logging # Allow us to run using installed `libgmail` or the one in parent directory. try: import libgmail logging.warn("Note: Using currently installed `libgmail` version.") except ImportError: # Urghhh... sys.path.insert(1, os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import libgmail if __name__ == "__main__": import sys from getpass import getpass try: filename = sys.argv[1] except IndexError: print "Usage: %s <state filename>" % sys.argv[0] raise SystemExit if not os.path.isfile(filename): name = raw_input("Gmail account name: ") pw = getpass("Password: ") ga = libgmail.GmailAccount(name, pw) print "\nPlease wait, logging in..." try: ga.login() except libgmail.GmailLoginFailure: print "\nLogin failed. (Wrong username/password?)" raise SystemExit print "Log in successful.\n" else: print "\nDon't wait, not logging in... :-)" ga = libgmail.GmailAccount( state = libgmail.GmailSessionState(filename = filename)) print "Unread messages: %s" % ga.getUnreadMsgCount() print "Saving state..." state = libgmail.GmailSessionState(account = ga).save(filename) print "Done." --- NEW FILE: test_fwd_attach.py --- #!/usr/bin/env python # # Usage: test_fwd_attach.py <account> <password> <recipient> <subject> # # This example forwards the first attachment from the search for "<subject>" # to the recipient. # import os import sys # Allow us to run using installed `libgmail` or the one in parent directory. try: import libgmail logging.warn("Note: Using currently installed `libgmail` version.") except ImportError: # Urghhh... sys.path.insert(1, os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import libgmail account, pw, recipient, searchSubject = sys.argv[1:] ga = libgmail.GmailAccount(account, pw) ga.login() sr = ga.getMessagesByQuery("subject:%s" % searchSubject) attachmentId = None for thread in sr: for msg in thread: if msg.attachments: attachmentId = msg.attachments[0]._fullId break # Just use the first result. if not attachmentId: print "No attachment found." raise SystemExit cm = libgmail.GmailComposedMessage(to=recipient, subject="File attachment from: %s" % msg.subject, body="body") # Note: At present we can only have one forwarded attachment because # we're using a dictionary for the parameters, and all attachments # have the field name "attach". # TODO: Allow multiple forwarded attachments. (Probably by adding to the # `_paramsToMime` function, although that's kinda hacky.) if ga.sendMessage(cm, _extraParams = {'attach': attachmentId}): print "Succeeded." else: print "Failed." --- NEW FILE: archive.py --- #!/usr/bin/env python # # archive.py -- Demo to archive all threads in a Gmail folder # # $Revision: 1.1 $ ($Date: 2005/09/23 17:58:08 $) # # Author: fol...@my... # # License: GPL 2.0 # import os import sys import logging # Allow us to run using installed `libgmail` or the one in parent directory. try: import libgmail logging.warn("Note: Using currently installed `libgmail` version.") except ImportError: # Urghhh... sys.path.insert(1, os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import libgmail if __name__ == "__main__": import sys from getpass import getpass try: name = sys.argv[1] except IndexError: name = raw_input("Gmail account name: ") pw = getpass("Password: ") ga = libgmail.GmailAccount(name, pw) print "\nPlease wait, logging in..." try: ga.login() except libgmail.GmailLoginFailure: print "\nLogin failed. (Wrong username/password?)" else: print "Log in successful.\n" searches = libgmail.STANDARD_FOLDERS + ga.getLabelNames() while 1: try: print "Select folder or label to archive: (Ctrl-C to exit)" print "Note: *All* pages of results will be archived." for optionId, optionName in enumerate(searches): print " %d. %s" % (optionId, optionName) name = searches[int(raw_input("Choice: "))] if name in libgmail.STANDARD_FOLDERS: result = ga.getMessagesByFolder(name, True) else: result = ga.getMessagesByLabel(name, True) print mbox = [] if len(result): for thread in result: print print thread.id, len(thread), thread.subject for msg in thread: print " ", msg.id, msg.number, msg.subject source = msg.source.replace("\r","").lstrip() mbox.append("From - Thu Jan 22 22:03:29 1998\n") mbox.append(source) mbox.append("\n\n") #TODO:Check if we need either/both? import time open("archive-%s-%s.mbox" % (name, time.time()), "w").writelines(mbox) else: print "No threads found in `%s`." % name print except KeyboardInterrupt: break print "\n\nDone." --- NEW FILE: MakeTarBall.py --- #!/usr/bin/env python # make tarball! VERSION = '0.1' PACKAGENAME = 'libgmail-docs_' import os print "\nCreate API docs" os.system('epydoc -o API ../libgmail.py') def cleanup(*args): """Used by os.path.walk to traverse the tree and remove CVS dirs""" if os.path.split(args[1])[1] == "CVS": print "Remove ",args[1] os.system('rm -r %s' % args[1]) filelist = open('filelist', 'r') folderlist = open('folderlist', 'r') myFiles = filelist.readlines() myFolders = folderlist.readlines() os.system('mkdir %s%s' % (PACKAGENAME,VERSION)) for file in myFiles: os.system('cp %s %s%s' % (file[:-1], PACKAGENAME,VERSION)) for folder in myFolders: os.system('mkdir %s%s/%s' % (PACKAGENAME,VERSION, folder[:-1])) os.system('cp -r %s %s%s' % (folder[:-1],PACKAGENAME, VERSION)) # removing the CVS stuff os.path.walk('%s%s' % (PACKAGENAME,VERSION),cleanup,None) print "\nCreate a GNU/Linux tarball..." try: execString = 'tar -czf %s%s.tgz %s%s/' % (PACKAGENAME,VERSION,PACKAGENAME, VERSION) print execString os.system(execString) except Exception,info: print info,"\nYou must have the tar package installed" else: print "Done.\n" print "Create a Windows compatible zipfile..." try: execString = 'zip -rq %s%s.zip ./%s%s' % (PACKAGENAME,VERSION,PACKAGENAME, VERSION) print execString os.system(execString) except Exception,info: print info,"\nYou must have the zip package installed." else: print "Done\n" os.system('rm -rf %s%s' % (PACKAGENAME,VERSION)) --- NEW FILE: filelist --- archive.py gcp.py gmailftpd.py gmailpopd.py gmailsmtp.py sendmsg.py test_fwd_attach.py test_notifier.py unreadmsgcount.py README COPYING --- NEW FILE: sendmsg.py --- #!/usr/bin/env python # # sendmsg.py -- Demo to send a message via Gmail using libgmail # # $Revision: 1.1 $ ($Date: 2005/09/23 17:58:08 $) # # Author: fol...@my... # # License: GPL 2.0 # import os import sys import logging # Allow us to run using installed `libgmail` or the one in parent directory. try: import libgmail ## Wouldn't this the preffered way? ## We shouldn't raise a warning about a normal import ##logging.warn("Note: Using currently installed `libgmail` version.") except ImportError: # Urghhh... sys.path.insert(1, os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import libgmail if __name__ == "__main__": import sys from getpass import getpass try: name = sys.argv[1] to = sys.argv[2] subject = sys.argv[3] msg = sys.argv[4] except IndexError: print "Usage: %s <account> <to address> <subject> <body>" % sys.argv[0] raise SystemExit pw = getpass("Password: ") ga = libgmail.GmailAccount(name, pw) print "\nPlease wait, logging in..." try: ga.login() except libgmail.GmailLoginFailure: print "\nLogin failed. (Wrong username/password?)" else: print "Log in successful.\n" gmsg = libgmail.GmailComposedMessage(to, subject, msg) if ga.sendMessage(gmsg): print "Message sent `%s` successfully." % subject else: print "Could not send message." print "Done." --- NEW FILE: README --- libgmail is licensed under the GPL. See the file named COPYING for more information. Please refer to the libgmail website or project page at sourceforge if you encouter problems using libgmail. http://libgmail.sf.net http://sourceforge.net/projects/libgmail/ You can contact us by email: stas AT linux DOT isbeter DOT nl wdaher AT mit DOT edu follower AT myrealbox DOT com ----------------------------------------------- Possible usage: Run this: python libgmail.py or this: python demos/archive.py or even this: python demos/sendmsg.py <account> <to address> <subject> <body> or perhaps this: python demos/gmailsmtp.py # (Then connect to SMTP proxy on local port 8025) or how about this: python demos/gmailftpd.py # (Then connect to FTP proxy on local port 8021, # after creating a label named 'ftp' and # applying it to some messages with attachments.) or maybe this: python demos/gmailpopd.py # (Then connect to POP3 proxy on local port 8110) for hours of fun!(*) (*) Note: Fun may not last for hours. Use at your own risk, blah, blah, etc... --- NEW FILE: gmailsmtp.py --- #!/usr/bin/env python # # gmailsmtp.py -- Demo to allow smtp delivery via Gmail # # $Revision: 1.1 $ ($Date: 2005/09/23 17:58:08 $) # # Author: fol...@my... # # License: GPL 2.0 # import os import sys import email import base64 import asyncore import smtpd # Allow us to run using installed `libgmail` or the one in parent directory. try: import libgmail logging.warn("Note: Using currently installed `libgmail` version.") except ImportError: # Urghhh... sys.path.insert(1, os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import libgmail ga = None class GmailSmtpProxy(smtpd.SMTPServer): """ """ def process_message(self, peer, mailfrom, rcpttos, data): """ """ result = None body = "" attachments = [] msg = email.message_from_string(data) #import pdb; pdb.set_trace() # Handle attachments, if present. if msg.is_multipart(): for part in msg.get_payload(): if part.get_content_type() == "text/plain": # TODO: Do we need to handle "message/rfc822" too? body = part.get_payload() else: attachments.append(part) else: body = msg.get_payload() gmsg = libgmail.GmailComposedMessage(to = msg["To"], subject = msg["Subject"], body = body, files = attachments) # Don't drop connection until we know we delivered... if not ga.sendMessage(gmsg): result = "Could not deliver." return result def handle_accept(self): conn, addr = self.accept() print >> smtpd.DEBUGSTREAM, 'Incoming connection from %s' % repr(addr) channel = ESMTPChannel(self, conn, addr) class ESMTPChannel(smtpd.SMTPChannel): """ """ def smtp_EHLO(self, arg): if not arg: self.push('501 Syntax: EHLO hostname') return ## if self.__greeting: if self._SMTPChannel__greeting: self.push('503 Duplicate HELO/EHLO') else: ## self.__greeting = arg ## self.push('250 %s' % self.__fqdn) self._SMTPChannel__greeting = arg self.push('250-%s' % self._SMTPChannel__fqdn) self.push('250 AUTH PLAIN') def smtp_AUTH(self, arg): """ """ kind, data = arg.split(" ") # TODO: Ensure kind == "PLAIN" # TODO: Support "LOGIN" (required by Outlook?) <http://www.technoids.org/saslmech.html> data = base64.decodestring(data)[1:] user, pw = data.split("\x00") global ga ga = libgmail.GmailAccount(user, pw) try: ga.login() except libgmail.GmailLoginFailure: self.push("535 Authorization failed") else: self.push('235 Ok') if __name__ == "__main__": #smtpd.DEBUGSTREAM = sys.stderr server = GmailSmtpProxy(("localhost", 8025), None) asyncore.loop() --- NEW FILE: gmailftpd.py --- #!/usr/bin/env python # # gmailftpd.py -- Demo to allow retrieval of attachments via FTP. # # $Revision: 1.1 $ ($Date: 2005/09/23 17:58:08 $) # # Author: fol...@my... # # License: Dual GPL 2.0 and PSF (This file only.) # # # Based on smtpd.py by Barry Warsaw <ba...@py...> (Thanks Barry!) # # Major rewrite of the datachannel handeling by Willy De la Court <wd...@li...> # # Note: Requires messages to be marked with a label named "ftp". # (This requirement can be removed.) # # TODO: Handle duplicate file names... # import sys import os import re import time import socket import asyncore import asynchat import logging program = sys.argv[0] __version__ = 'Python Gmail FTP proxy version 0.0.3' # Allow us to run using installed `libgmail` or the one in parent directory. try: import libgmail logging.warn("Note: Using currently installed `libgmail` version.") except ImportError: # Urghhh... sys.path.insert(1, os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import libgmail class Devnull: def write(self, msg): pass def flush(self): pass DEBUGSTREAM = Devnull() NEWLINE = '\n' EMPTYSTRING = '' nextPort = 9021 class FTPChannel(asynchat.async_chat): def __init__(self, server, conn, addr): asynchat.async_chat.__init__(self, conn) self.__server = server self.__conn = conn self.__addr = addr self.__line = [] self.__fqdn = socket.getfqdn() self.__peer = conn.getpeername() print >> DEBUGSTREAM, 'Peer:', repr(self.__peer) self.push('220 %s %s' % (self.__fqdn, __version__)) self.set_terminator('\r\n') self.my_type = "A" self.my_cwd = "" self.my_user = "" self.filenames = {} self._activeDataChannel = None # Overrides base class for convenience def push(self, msg): asynchat.async_chat.push(self, msg + '\r\n') # Implementation of base class abstract method def collect_incoming_data(self, data): self.__line.append(data) # Implementation of base class abstract method def found_terminator(self): line = EMPTYSTRING.join(self.__line) print >> DEBUGSTREAM, 'Data:', repr(line) self.__line = [] if not line: self.push('500 Error: bad syntax') return method = None i = line.find(' ') if i < 0: command = line.upper() arg = None else: command = line[:i].upper() arg = line[i+1:].strip() method = getattr(self, 'ftp_' + command, None) if not method: self.push('502 Error: command "%s" not implemented' % command) return method(arg) return def get_filelist(self): """ Get the file list from GMail """ r = self.ga.getMessagesByLabel('ftp') for th in r: for m in th: for a in m.attachments: self.filenames[a.filename] = a def ftp_USER(self, arg): """ Process USER ftp command """ if not arg: self.push('501 Syntax: USER username') else: self.my_user = arg self.push('331 Password required') def ftp_PASS(self, arg = ''): """ Process PASS ftp command """ self.ga = libgmail.GmailAccount(self.my_user, arg) try: self.ga.login() except libgmail.GmailLoginFailure: self.push('530 Login failed. (Wrong username/password?)') else: self.push('230 User logged in') def ftp_LIST(self, arg): """ Process LIST ftp command """ self.filenames = {} self._activeDataChannel.cmd = "LIST " + str(arg) self._activeDataChannel.handle_LIST() def ftp_RNFR(self, arg): """ Process RNFR ftp command """ self.push('350 File exists, ready for destination name') def ftp_RNTO(self, arg): """ Process RNTO ftp command """ self.push('250 RNTO command successful.') def ftp_SIZE(self, arg): """ Process SIZE ftp command """ name_req = arg if name_req[:1] == '/': name_req = name_req[1:] try: response = "213 %d" % (self.filenames[name_req].filesize) except: self.push("550 %s: No such file or directory." % (name_req)) else: self.push(response) def ftp_RETR(self, arg): """ Process RETR ftp command """ self._activeDataChannel.cmd = "RETR " + str(arg) self._activeDataChannel.handle_RETR() def ftp_STOR(self, arg): """ Process STORE ftp command """ # TODO: Check this is legit, don't just copy & paste from RETR... self._activeDataChannel.cmd = "STOR " + str(arg) self._activeDataChannel.handle_STOR() def ftp_PASV(self, arg): """ Process PASV ftp command """ # *** TODO: Don't allow non-binary file transfers here? global nextPort PORT = nextPort nextPort += 1 ADDR = ('127.0.0.1', PORT) self._activeDataChannel = DataChannel(ADDR, self) self.push('227 =127,0,0,1,%d,%d' % (PORT / 256, PORT % 256)) def ftp_QUIT(self, arg): """ Process QUIT ftp command """ # args is ignored self.push('221 Bye') self.close_when_done() def ftp_CWD(self, arg): """ Process CWD ftp command """ # TODO: Attach CWD (and other items) to channel... self.my_cwd = arg self.push('550 ' + self.my_cwd + ': No such file or directory.') def ftp_PWD(self, arg): """ Process PWD ftp command """ self.push('257 "/" is current directory.') def ftp_TYPE(self, arg): """ Process TYPE ftp command """ response = '200 OK' if arg in ["A", "A N"]: self.my_type = "A" elif arg in ["I", "L 8"]: self.my_type = "I" else: response = "504 Unsupported TYPE parameter" self.push(response) import tempfile class DataChannel(asyncore.dispatcher): """ """ def __init__(self, localaddr, ControlChannel): self._ControlChannel = ControlChannel self._localaddr = localaddr asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) # try to re-use a server port if possible self.set_reuse_addr() self.bind(localaddr) self.listen(5) print >> DEBUGSTREAM, \ '%s started at %s\n\tLocal addr: %s\n' % ( self.__class__.__name__, time.ctime(time.time()), localaddr) self.cmd = "" def handle_accept(self): """ Start the DATA connection """ conn, addr = self.accept() self._ControlChannel.push('150 Opening data connection.') self.conn = conn def handle_LIST(self): """ Send the data response for the LIST command """ self._ControlChannel.get_filelist() result = "" for file in self._ControlChannel.filenames.keys(): result = result + "-rw-r--r-- 1 %s %s %10d Jan 1 2000 %s\r\n" % (self._ControlChannel.my_user, self._ControlChannel.my_user, self._ControlChannel.filenames[file].filesize, self._ControlChannel.filenames[file].filename) self.conn.sendall(result) self._ControlChannel.push('226 Transfer complete.') self.close() self.conn.close() def handle_RETR(self): """ Send the file for the RETR command """ if self._ControlChannel.my_type != "I": self._ControlChannel.push('426 Only binary transfer mode is supported') self.close() self.conn.close() return name_req = self.cmd[5:] # Remove leading / if name_req[:1] == '/': name_req = name_req[1:] print >> DEBUGSTREAM, "Reading `%s`." % (name_req) # check if the file exists try: name = self._ControlChannel.filenames[name_req].filename except KeyError: # if not the list is probably not read yet self._ControlChannel.get_filelist() # try again try: self.conn.sendall(self._ControlChannel.filenames[name_req].content) response = '226 Transfer complete.' except KeyError: response = '550 ' + name_req + ': No such file or directory.' self._ControlChannel.push(response) self.close() self.conn.close() def handle_STOR(self): """ Receive the file for the STOR command """ if self._ControlChannel.my_type != "I": self._ControlChannel.push('426 Only binary transfer mode is supported') self.close() self.conn.close() return buffer = "" while True: data = self.conn.recv(1024) if not data: break buffer += data filename = self.cmd[5:] # Remove leading / if filename[:1] == '/': filename = filename[1:] tempDir = tempfile.mkdtemp() # Remove trailing '.part' KDE uses this to upload files tempFileName = re.sub('\.part', '', filename) tempFilePath = os.path.join(tempDir, tempFileName) print >> DEBUGSTREAM, "Writing `%s` to `%s`." % (filename, tempFilePath) open(tempFilePath, "wb").write(buffer) self._ControlChannel.ga.storeFile(tempFilePath, "ftp") os.remove(tempFilePath) os.rmdir(tempDir) self._ControlChannel.push('226 Transfer complete.') self.close() self.conn.close() class FTPServer(asyncore.dispatcher): def __init__(self, localaddr): self._localaddr = localaddr asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) # try to re-use a server port if possible self.set_reuse_addr() self.bind(localaddr) self.listen(5) print >> DEBUGSTREAM, \ '%s started at %s\n\tLocal addr: %s\n' % ( self.__class__.__name__, time.ctime(time.time()), localaddr) def handle_accept(self): conn, addr = self.accept() print >> DEBUGSTREAM, 'Incoming connection from %s' % repr(addr) channel = FTPChannel(self, conn, addr) if __name__ == '__main__': DEBUGSTREAM = sys.stderr proxy = FTPServer(('127.0.0.1', 8021)) try: asyncore.loop() except KeyboardInterrupt: pass --- NEW FILE: folderlist --- API --- NEW FILE: COPYING --- GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. --- NEW FILE: gcp.py --- #!/usr/bin/env python # # gcp.py -- Demo to copy a file to Gmail using libgmail # # $Revision: 1.1 $ ($Date: 2005/09/23 17:58:08 $) # # Author: fol...@my... # # License: GPL 2.0 # import os import sys import logging # Allow us to run using installed `libgmail` or the one in parent directory. try: import libgmail logging.warn("Note: Using currently installed `libgmail` version.") except ImportError: # Urghhh... sys.path.insert(1, os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import libgmail if __name__ == "__main__": import sys from getpass import getpass # TODO: Allow copy from account. try: filename = sys.argv[1] destination = sys.argv[2] except IndexError: print "Usage: %s <filename> <account>:[<label>/]" % sys.argv[0] raise SystemExit name, label = destination.split(":", 1) if label.endswith("/"): label = label[:-1] if not label: label = None pw = getpass("Password: ") ga = libgmail.GmailAccount(name, pw) print "\nPlease wait, logging in..." try: ga.login() except libgmail.GmailLoginFailure: print "\nLogin failed. (Wrong username/password?)" else: print "Log in successful.\n" if ga.storeFile(filename, label=label): print "File `%s` stored successfully in `%s`." % (filename, label) else: print "Could not store file." print "Done." --- NEW FILE: gmailpopd.py --- #!/usr/bin/env python # # gmailpopd.py -- Demo to provide POP3 proxy for Gmail message retrieval.. # # $Revision: 1.1 $ ($Date: 2005/09/23 17:58:08 $) # # Author: fol...@my... # # License: Dual GPL 2.0 and PSF (This file only.) # # # Based on smtpd.py by Barry Warsaw <ba...@py...> (Thanks Barry!) # ## Applied the Debian patch bug report #277310 --SZ-- import sys import os import time import socket import asyncore import asynchat program = sys.argv[0] __version__ = 'Python Gmail POP3 proxy version 0.0.1' # Allow us to run using installed `libgmail` or the one in parent directory. try: import libgmail logging.warn("Note: Using currently installed `libgmail` version.") except ImportError: # Urghhh... sys.path.insert(1, os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import libgmail from libgmail import U_AS_SUBSET_UNREAD class Devnull: def write(self, msg): pass def flush(self): pass DEBUGSTREAM = Devnull() NEWLINE = '\n' EMPTYSTRING = '' # TODO: Get rid of this global stuff... my_user = "" snapshot = None # Account snapshot... class GmailAccountSnapshot: """ """ def __init__(self, ga): """ """ self.account = ga # TODO: Work out at what stage messages get marked as 'read'. # (as I think of it, it happens when I retrieve the # messages in the threads, should really preserve read/unread # state then.) # TODO: Fix this so it does not retrieve messages that have already # been read. ("unread" is a property of thread in this case?) # Is this even possible without caching stuff ourselves, # maybe use "archive" as the equivalent of read? self._unreadThreads = ga.getMessagesByQuery("is:" + U_AS_SUBSET_UNREAD, True)#TODO:True as default? self.unreadMsgs = [] for thread in self._unreadThreads: for msg in thread: self.unreadMsgs.append(msg) def retrieveMessage(self, msgNumber, bodyLines = None): """ Returns an array of lines... (TODO: Decide if we want this.) """ # TODO: Check request is in range... # TODO: Don't retrieve all of the message, just what's needed. msgContent = self.unreadMsgs[msgNumber].source msgContent = _massage(msgContent)# TODO: Remove this... msgLines = msgContent.split("\r\n") if bodyLines is not None: blankIndex = msgLines.index("") # Blank line between header & body. msgLines = msgLines[:blankIndex + 1 + bodyLines] return msgLines class POPChannel(asynchat.async_chat): def __init__(self, server, conn, addr): asynchat.async_chat.__init__(self, conn) self.__server = server self.__conn = conn self.__addr = addr self.__line = [] self.__fqdn = socket.getfqdn() self.__peer = conn.getpeername() print >> DEBUGSTREAM, 'Peer:', repr(self.__peer) self.push('+OK %s %s' % (self.__fqdn, __version__)) self.set_terminator('\r\n') self._activeDataChannel = None # Overrides base class for convenience def push(self, msg): asynchat.async_chat.push(self, msg + '\r\n') # Implementation of base class abstract method def collect_incoming_data(self, data): self.__line.append(data) # Implementation of base class abstract method def found_terminator(self): line = EMPTYSTRING.join(self.__line) print >> DEBUGSTREAM, 'Data:', repr(line) self.__line = [] if not line: self.push('500 Error: bad syntax') return method = None i = line.find(' ') if i < 0: command = line.upper() arg = None else: command = line[:i].upper() arg = line[i+1:].strip() method = getattr(self, 'pop_' + command, None) if not method: self.push('-ERR Error : command "%s" not implemented' % command) return method(arg) return def pop_USER... [truncated message content] |