UNB/ CS/ David Bremner/ blog/ files/ scan-whitelist.py
#/usr/bin/env python2.5

#  David Bremner 2007/10/10
# placed in the public domain

from mailbox import Maildir

from email import utils

import os
import time
import datetime
import logging
import fcntl

config = { 'loglevel':logging.DEBUG,
	   'logfile':os.path.expanduser('~/var/log/scan-whitelist.log'),
	   'keepdays':14,
	   'maildir':os.path.expanduser("~/Maildir/"),
	   'whitelistfolder':'whitelist',
	   'outfile':os.path.expanduser("~/var/mail/whitelist"),
	   }

logging.basicConfig(level=config['loglevel'],
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename=config['logfile'],
                    filemode='a')

fd=open(config['outfile'],'r+')
exists={}

fcntl.lockf(fd,fcntl.LOCK_EX)
for line in fd.readlines():
    exists[line.strip()]=1

now=datetime.datetime.now()
mainbox=Maildir(config['maildir'])
whitelist=mainbox.get_folder(config['whitelistfolder'])


for key in whitelist.keys():
	msg=whitelist[key]
	addr=msg['from']
	exists[addr]=1
	logging.debug('processing %s %s' %(key,addr))
	whitelist.discard(key)

fd.seek(0)
for line in sorted(exists.keys()):
    print >>fd,line

fcntl.lockf(fd,fcntl.LOCK_UN)
fd.close()