diff options
author | Matěj Cepl <mcepl@cepl.eu> | 2018-04-19 00:05:00 +0200 |
---|---|---|
committer | Matěj Cepl <mcepl@cepl.eu> | 2018-04-19 00:08:04 +0200 |
commit | c71bdde47f58ee47d5756abc08edb44961f2f781 (patch) | |
tree | 369e282d31b063ebf2cf372bc4f15acba2c826aa | |
parent | 0060b9e5d2e5b5df9b3a1106e8b9cc36fb49e0fb (diff) | |
download | imapArch-c71bdde47f58ee47d5756abc08edb44961f2f781.tar.gz |
A bit of development on imapArchive.py.
-rwxr-xr-x | imapArchive.py | 173 |
1 files changed, 98 insertions, 75 deletions
diff --git a/imapArchive.py b/imapArchive.py index f965c95..59cfa1e 100755 --- a/imapArchive.py +++ b/imapArchive.py @@ -1,17 +1,28 @@ -# -*- coding: utf-8 -*- +#!/usr/bin/env python3.6 # note http://docs.python.org/lib/module-doctest.html # resp. file:///usr/share/doc/python-docs-*/html/lib/module-doctest.html # for testing -from __future__ import division -from java.util import Properties, Date -from java.lang import System -from javax.mail import * -from jarray import array -import sys, os +import argparse +import configparser +import email +import logging +import os +import sys from datetime import date -from ConfigParser import ConfigParser -debug=False +logging.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', + stream=sys.stdout, level=logging.DEBUG) +log = logging.getLogger('imapArch') + +# from java.util import Properties, Date +# from java.lang import System +# from javax.mail import * +# from jarray import array + + +class FolderNotFoundError(IOError): + pass + def __getMessageDate(msg): """ @@ -21,24 +32,26 @@ def __getMessageDate(msg): @return GregorianCalendar of the messages date @throws MessagingException """ - dateMS = msg.getReceivedDate().getTime()//1000 + dateMS = msg.getReceivedDate().getTime() // 1000 dateStruct = date.fromtimestamp(dateMS) return dateStruct + class ArchivableFolder(list): - def __init__(self,source,year): + + def __init__(self, source, year): """ Constructor for the folder. - + @param source folder from the messages should be archived @param year int of the year for which the messages are archived """ self.sourceFolder = source targetName = self.__getArchiveFolderName(source.getFullName(), year) - self.targetFolder = self.sourceFolder.getFolder(targetName) + self.targetFolder = self.sourceFolder.getFolder(targetName) - def __getArchiveFolderName(self,srcFldName,year): + def __getArchiveFolderName(self, srcFldName, year): """ @param folder string with the folder name @param year int @@ -46,52 +59,54 @@ class ArchivableFolder(list): """ archFolder = "INBOX/Archiv/" rootLen = len("INBOX/") - if not(srcFldName[:rootLen]=="/INBOX/"): - raise FolderNotFoundException(\ + if not(srcFldName[:rootLen] == "/INBOX/"): + raise FolderNotFoundError( "We expect all folders to be under INBOX folder.") baseName = srcFldName[rootLen:] archFolder = "/" + archFolder + year + "/" + baseName - return archFolder + return archFolder - def add(self,msg): + def add(self, msg): self.append(msg) def doArchive(self): if debug: for message in self: print >>sys.stderr, "Moving %s from %s to %s." \ - % (message,self.sourceFolder.getFullName(), + % (message, self.sourceFolder.getFullName(), self.targetFolder.getFullName()) else: - self.sourceFolder.copyMessages(array(self,Message),\ + self.sourceFolder.copyMessages(array(self, Message), self.targetFolder) for message in self: message.setFlag(Flags.Flag.DELETED, true) self.sourceFolder.expunge() + class Archives(dict): """Collects archivable folders indexed by tuple of folderName and year """ + def __init__(self): pass - - def add(self,msg): + + def add(self, msg): """ - Check whether the ArchivableFolder (@see ArchivableFolder) + Check whether the ArchivableFolder (@see ArchivableFolder) for the particular year actually exists, and if not then create - it. In any event add - @param msg + it. In any event add + @param msg """ fld = msg.getFolder() msgDate = __getMessageDate(msg) year = msgDate.year - + if not(self.search(fld, year)): - archfld = ArchivableFolder(fld,year) - self[self.__createKey(fld,year)] = archfld - - def __createKey(self,name,year): + archfld = ArchivableFolder(fld, year) + self[self.__createKey(fld, year)] = archfld + + def __createKey(self, name, year): """ Create a key for the list @param fldName String with the full name of the folder @@ -100,48 +115,51 @@ class Archives(dict): @return tuple consisting from the both parameters of this function. """ - return(name,year) + return(name, year) - def search(self,fld,year): + def search(self, fld, year): """ Find out whether the object with the key consisting of the folder name and year exists in this object. - + @param fld Folder where the message is stored @param year int year of the message date @return boolean saying whether the folder for this message - has been already added to this object. + has been already added to this object. """ key = self.__createKey(fld.getFullName(), year) - return self.has_key(key) - + return key in self + def archive(self): for key in self: self.doArchive() + class ArchivedStore(object): - def __init__(self,paramServer="localhost",paramUser="",paramPassword=""): - self.props = System.getProperties() - self.session = Session.getInstance(self.props,None) - self.props.setProperty("javax.net.ssl.keyStore", "/home/matej/.keystore") - self.props.setProperty("javax.net.ssl.trustStore", "/home/matej/.keystore") - if debug: - self.session.setDebug(True) - try: - self.store = self.session.getStore("imaps") - except: - print >> sys.stderr, "Cannot get Store" - raise - + + def __init__(self, serverKey=None): + config = configparser.ConfigParser() + config.read(os.path.expanduser('~/.config/imap_archiver.cfg')) + acc_name = serverKey if serverKey is not None \ + else config['general']['account'] + self.cfg = dict(config.items(acc_name)) + # if debug: + # self.session.setDebug(True) + # try: + # self.store = self.session.getStore("imaps") + # except: + # print >> sys.stderr, "Cannot get Store" + # raise + self._threeMonthAgo = date.today() - newmonth = self._threeMonthAgo.month-3 + newmonth = self._threeMonthAgo.month - 3 self._threeMonthAgo = self._threeMonthAgo.replace(month=newmonth) - - conffile = os.path.expanduser("~/.bugzillarc") + + conffile = os.path.expanduser("~/.bugzillarc") confUser = ConfigParser() defSection = "localhost" - user,host,port,password = self.props.getProperty("user.name"),\ - "localhost",993,"" + user, host, port, password = self.props.getProperty("user.name"),\ + "localhost", 993, "" if confUser.read(conffile): if confUser.has_section(defSection): if confUser.has_option(defSection, "name"): @@ -154,52 +172,57 @@ class ArchivedStore(object): password = confUser.get(defSection, "password") if paramServer: - host=paramServer + host = paramServer if paramUser: - user=paramUser + user = paramUser if paramPassword: - password=paramPassword + password = paramPassword + + print >>sys.stderr, "host = %s, user = %s, password = %s" % \ + (host, user, password) - print >>sys.stderr,"host = %s, user = %s, password = %s" % \ - (host,user,password) + self.__login(host, user, password) - self.__login(host,user,password) - - def __login(self,server,user,password): + def __login(self, server, user, password): try: - self.store.connect(server,user,password) + self.store.connect(server, user, password) except: print >> sys.stderr, "Cannot connect to %s as %s with password %s" %\ - (server,user,password) + (server, user, password) raise - + def archive(self): inboxfolder = self.store.getDefaultFolder().getFolder("INBOX") - folderList=inboxfolder.list('*') - + folderList = inboxfolder.list('*') + for folder in folderList: if folder.getFullName()[:len("INBOX/Archiv")] != "INBOX/Archiv": archMsgsCnt = self.__archiveFolder(folder) - #folder.close(False) + # folder.close(False) print "Processed messages = %d" % archMsgsCnt - - def __archiveFolder(self,fld): + + def __archiveFolder(self, fld): fld.open(Folder.READ_WRITE) for msg in fld.getMessages(): msgDate = __getMessageDate(msg) - print >>sys.stderr,str(msgDate),str(self._threeMonthAgo) + print >>sys.stderr, str(msgDate), str(self._threeMonthAgo) if msgDate < self._threeMonthAgo: archFolder = self.__getArchiveFolderName(msg) # print >> sys.stderr, archFolder # fld.copyMessages(array([msg],type(msg)), archFolder) # msg.setFlag(Flags.Flag.DELETED, true) print "%s -> %s : %s" % (fld.getFullName(), - archFolder.getFullName(),msgDate) + archFolder.getFullName(), msgDate) folderLen = len(fld.getMessages()) fld.close(False) return(folderLen) -if __name__=='__main__': - myStore = ArchivedStore(paramPassword="lubdkc") +if __name__ == '__main__': + argp = argparse.ArgumentParser() + argp.add_argument('server', + help='Symbolic name of the server to be used') + argp.add_argument('folder', + help='Folder which should be archived') + myStore = ArchivedStore() myStore.archive() - myStore.store.close()
\ No newline at end of file + myStore.store.close() |