aboutsummaryrefslogtreecommitdiffstats
path: root/purgeObsolete.py
blob: 48173ecba7f037d4419b9f7e915e678b8bb9d851 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# -*- coding: utf-8 -*-
# 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, GregorianCalendar, Locale
from java.text import SimpleDateFormat
from java.lang import System
from javax.mail import *
from javax.mail.search import *
from com.sun.mail.imap import IMAPFolder, IMAPSSLStore
from jarray import array
import sys, os
from datetime import date
import ConfigParser

debug=False

class SimpleDate(GregorianCalendar):
    def __init__(self):
        pass

    def getDate():
        return self.getTime()

    def decrease(self,howMuch,unit="m"):
        pass

    def getMessageDate(msg):
        """
        Return the date of the message

        @param msg analyzed message
        @return GregorianCalendar of the messages date
        @throws MessagingException
        """
        dateMS = msg.getReceivedDate().getTime()//1000
        dateStruct = date.fromtimestamp(dateMS)
        return dateStruct

class ArchivedFolder(object):
    def __init__(self,store,name):
        self.folder = store.store.getDefaultFolder().getFolder(name)
        self.folder.open(Folder.READ_WRITE)

    def purgeOld(self,dateLimit):
        toBeDeleted = []
        for msg in self.folder.getMessages():
            flags = msg.getFlags()
            if (__getMessageDate(msg) < dateLimit) and (flags.contains(Flags.Flag.SEEN)):
                toBeDeleted.append(msg)
        self.folder.setFlags(toBeDeleted,Flags.Flag.DELETED, true)
        self.folder.expunge()

class ArchivedStore(object):
    """
    >>> myStore = ArchivedStore(paramServer="zimbra")
    >>> folderList = myStore.store.getDefaultFolder().list("*")
    >>> len(folderList)>0
    1
    >>> myStore.store.close()

    and
    >>> myStore = ArchivedStore(paramServer="zimbra")
    >>> folder = ArchivedFolder(myStore,"INBOX/bugzilla/xgl")
    >>> folder.folder.getMessageCount() > 0
    1
    >>> myStore.store.close()

    """
    def __init__(self,paramServer="localhost",paramUser="",paramPassword="",maxageMonth=3):
        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

        conffile = os.path.expanduser("~/.bugzillarc")
        if paramServer:
            config = ConfigParser.ConfigParser()
            config.read([conffile])
        user,host,port,password = self.props.getProperty("user.name"),\
            "localhost",993,""

        if config:
            if config.has_section(paramServer):
                if config.has_option(paramServer, "name"):
                    user = config.get(paramServer, "name")
                if config.has_option(paramServer, "host"):
                    host = config.get(paramServer, "host")
                if config.has_option(paramServer, "port"):
                    port = config.get(paramServer, "port")
                if config.has_option(paramServer, "password"):
                    password = config.get(paramServer, "password")

        if paramUser:
            user=paramUser
        if paramPassword:
            password=paramPassword

        if debug:
            print >>sys.stderr,"host = %s, user = %s, password = %s" % \
                (host,user,password)

        self.__login(host,user,password)

    def __login(self,server,user,password):
        try:
            self.store.connect(server,user,password)
        except:
            print >> sys.stderr, "Cannot connect to %s as %s with password %s" %\
                (server,user,password)
            raise

def main():
    """
    >>> threeMonthAgo = date.today()
    >>> JD3MAgo = GregorianCalendar(threeMonthAgo.year,
        threeMonthAgo.month-1,
        threeMonthAgo.day,0,0)
    >>> formatter = SimpleDateFormat("yyyy-MM-dd",Locale.US);
    >>> JD3MAgoStr = formatter.format(JD3MAgo.getTime())
    >>> str(threeMonthAgo)==JD3MAgoStr
    1
    """
    threeMonthAgo = date.today()
    newmonth = threeMonthAgo.month-3
    threeMonthAgo = threeMonthAgo.replace(month=newmonth)
    JD3MAgo = GregorianCalendar(threeMonthAgo.year,
        threeMonthAgo.month-1,
        threeMonthAgo.day,0,0).getTime()

    myStore = ArchivedStore(paramServer="zimbra")
    folder = ArchivedFolder(myStore,"INBOX/bugzilla/xgl")

    unreadTerm = FlagTerm(Flags(Flags.Flag.SEEN),True)
    dateTerm = ReceivedDateTerm(ComparisonTerm.LT,JD3MAgo)
    searchTerm = AndTerm(unreadTerm,dateTerm)
    msgsFound = folder.folder.search(searchTerm)

    print len(msgsFound)
    myStore.store.close()

if __name__=='__main__':
    main()