}
$packages = ["python", "python-pip", "bpython",
- "mutt", "python-pyinotify", "mailutils"]
+ "mutt", "python-pyinotify", "mailutils", "python-leveldb"]
$python_packages = ["python-dateutil"]
--- /dev/null
+# A very thin layer over leveldb - it mostly serializes JSON back and forth.
+
+import leveldb
+import utils
+try:
+ import json
+except ImportError:
+ import simplejson as json
+
+
+class Cabinet(object):
+ """Persistent data storage using JSON and berkeley db"""
+ def __init__(self, filename, encoder=json.JSONEncoder, decoder=None, *args):
+ """Set up a Cabinet object.
+
+ The encoder parameter is the class that will be called by the json encoder to encode python objects.
+ decoder is a function which is called for each decoded object to apply special conversions.
+ For more informations, see :
+ http://docs.python.org/dev/library/json.html?highlight=json#encoders-and-decoders
+ """
+ self.filename = filename
+ self.cache = {}
+ self.encoder = encoder
+ self.decoder = decoder
+
+ def __getitem__(self, key):
+ if self.cache.has_key(key):
+ return self.cache[key]
+ else:
+ db = leveldb.LevelDB(self.filename)
+ val = db.Get(key)
+ del db
+ self.cache[key] = json.loads(val, object_hook=self.decoder)
+ return self.cache[key]
+
+ def __setitem__(self, key, item):
+ self.cache[key] = item
+
+ def __delitem__(self, key):
+ del self.cache[key]
+ db = leveldb.LevelDB(self.filename)
+ db.Delete(key)
+ del db
+
+ def __iter__(self):
+ return self.cache.iterkeys()
+
+ def __contains__(self, key):
+ if self.cache.has_key(key):
+ return True
+ else:
+ try:
+ db = leveldb.LevelDB(self.filename)
+ db.Get(key)
+ del db
+ return True
+ except KeyError:
+ return False
+
+ def sync(self):
+ db = leveldb.LevelDB(self.filename)
+ for key in self.cache:
+ db.Put(key, json.dumps(self.cache[key], cls=self.encoder))
+
+def DatetimeCabinet(path):
+ return Cabinet(path, encoder=utils.DatetimeEncoder, decoder=utils.deserialize_datetime)
# filterdaemon.py
# This background process creates indexes files for threads and filters.
#
-# What is an index file ?
-# =======================
-#
-# An index file is a JSON list which holds the paths to files in a conversation.
-#
import sys
import os
import threads
import headers
import users
-from jsonfile import JsonFile
+from cabinet import DatetimeCabinet
import maildir
# The architecture is pretty simple. This program is multithreaded.
notifier.loop()
class DumperThread(threading.Thread):
- def __init__(self, path, threads_index_cache):
+ def __init__(self, path, threads_index):
threading.Thread.__init__(self)
self.path = path
- self.threads_index_cache = threads_index_cache
+ self.threads_index = threads_index
def run(self):
while True:
time.sleep(DUMPER_SLEEP_DURATION)
- for user in self.threads_index_cache:
- print "dumper " + user
- if self.threads_index_cache[user]["dirty"]:
- print "Dumping threads index for user %s at location %s " % (user, self.threads_index_cache[user]["threads_index"].path)
-
- self.threads_index_cache[user]["threads_index"].save()
- self.threads_index_cache[user]["dirty"] = False
+ self.threads_index.sync()
def process_new_email(path, threads_index):
with open(path, "r") as fd:
threads_index.insert(0, thread)
class ProcessorThread(threading.Thread):
- def __init__(self, path, threads_index_cache):
+ def __init__(self, path, threads_index):
threading.Thread.__init__(self)
self.path = path
- self.threads_index_cache = threads_index_cache
+ self.threads_index= threads_index
def run(self):
while True:
username = users.get_username_from_folder(event["path"])
print "username: %s, path: %s\n" % (username, event["path"])
- if username not in self.threads_index_cache:
- threads_index = users.get_user_threads_index(event["path"])
- print "Getting threads_index for user : %s" % username
- self.threads_index_cache[username] = {"threads_index": threads_index, "dirty": True}
+ if username not in self.threads_index:
+ print "Setting threads_index for user : %s" % username
+ self.threads_index[username] = {"threads_index": [], "dirty": True}
- process_new_email(event["path"], self.threads_index_cache[username]["threads_index"].data)
- self.threads_index_cache[username]["dirty"] = True
+ process_new_email(event["path"], self.threads_index[username]["threads_index"])
+ self.threads_index[username]["dirty"] = True
except IOError as e:
# This may be a Postfix/Dovecot temporary file. Ignore it.
print "caught ioerror %s" % e.strerror
path = sys.argv[1]
print "Watching %s..." % path
- threads_index_cache = {}
+ threads_index = DatetimeCabinet("/home/kite/threads.db")
watcher_thread = WatcherThread(path)
- processor_thread = ProcessorThread(path, threads_index_cache)
- dumper_thread = DumperThread(path, threads_index_cache)
+ processor_thread = ProcessorThread(path, threads_index)
+ dumper_thread = DumperThread(path, threads_index)
processor_thread.start()
watcher_thread.start()
+++ /dev/null
-# serialize and deserialize to json.
-# reading and writing is locking
-import os
-import json
-import datetime
-import time
-import dateutil.parser
-import dateutil.tz
-from lockfile import FileLock
-
-class DatetimeEncoder(json.JSONEncoder):
- def default(self, obj):
- if isinstance(obj, datetime.datetime):
- return obj.isoformat()
-
- return json.JSONEncoder.default(self, obj)
-
-def deserialize_datetime(obj):
- try:
- obj['date'] = dateutil.parser.parse(obj['date'])
- except KeyError:
- pass
- return obj
-
-class JsonFile(object):
- def __init__(self, path=None):
- self.path = path
- self.data = None
- self.refresh()
-
- def refresh(self):
- try:
- if self.path != None:
- with FileLock(self.path):
- fd = open(self.path, "r")
- self.data = json.load(fd, object_hook=deserialize_datetime)
- fd.close()
- except IOError:
- pass
-
- def save(self, path=None):
- if path == None:
- path = self.path
-
- def save_proper():
- with open(path, "w+") as fd:
- json.dump(self.data, fd, cls=DatetimeEncoder)
-
- # Lock the file only if it already exists
- # FIXME: this is maybe a race condition
- if os.path.exists(path):
- with FileLock(path):
- save_proper()
- else:
- save_proper()
-
-def serialize_json(obj):
- return json.dumps(obj, cls=DatetimeEncoder)
-
-def deserialize_json(string):
- return json.loads(string, object_hook=deserialize_datetime)
#!/usr/bin/env python
import bottle
import json
-import jsonfile
import sys
-from jsonfile import JsonFile, serialize_json
+from cabinet import DatetimeCabinet
from bottle import route, template, response, abort
from maildir import *
+from utils import serialize_json
@route('/kite/<user>/mail')
def index(user):
# FIXME: input sanitization - check permissions for user
try:
- threads_index = JsonFile("/home/kite/Maildirs/%s/threads_index.json" % user)
+ threads_index = DatetimeCabinet("/home/kite/threads.db")
except IOError:
response.status = 400
return
ret_threads = []
- for thread in threads_index.data[-50:]:
+ try:
+ threads = threads_index[user]["threads_index"]
+ except KeyError:
+ threads = []
+
+ for thread in threads:
ret_threads.append(thread)
response.content_type = "application/json"
@route('/kite/<user>/mail/<id>')
def index(user, id):
# FIXME: input sanitization check perms
- threads_index = JsonFile("/home/kite/Maildirs/%s/threads_index.json" % user)
- thread = None
+ try:
+ threads_index = DatetimeCabinet("/home/kite/threads.db")
+ thread = None
+ except IOError:
+ response.status = 400
+ return
- for thr in threads_index.data:
+ # FIXME: use an index for threads entries ?
+ for thr in threads_index[user]["threads_index"]:
if thr["id"] == id:
thread = thr
abort(404, "Thread not found.")
thr["unread"] = False
- threads_index.save() # FIXME: race condition here
+ threads_index.sync()
response.content_type = "application/json"
# utils.py : various utilities
-
import os
+import json
+import datetime
+import time
+import dateutil.parser
+import dateutil.tz
+
+
+class DatetimeEncoder(json.JSONEncoder):
+ def default(self, obj):
+ if isinstance(obj, datetime.datetime):
+ return obj.isoformat()
+
+ return json.JSONEncoder.default(self, obj)
+
+def serialize_json(obj):
+ return json.dumps(obj, cls=DatetimeEncoder)
+
+def deserialize_json(string):
+ return json.loads(string, object_hook=deserialize_datetime)
+def deserialize_datetime(obj):
+ try:
+ obj['date'] = dateutil.parser.parse(obj['date'])
+ except KeyError:
+ pass
+ return obj