# =======================
#
# An index file is a JSON list which holds the paths to files in a conversation.
-# The file name of an index file is of the form UUID4.json
#
# Why is it used ?
# ================
import os
import pyinotify
import threading
+import datetime
import time
import email.parser
while True:
time.sleep(DUMPER_SLEEP_DURATION)
print "Dumping threads index"
+
+ # sort list by date
self.threads_index.save()
def process_new_email(path, threads_index):
if subject != None:
subject = headers.cleanup_subject(subject)
- if subject in threads_index.data:
- threads_index.data[subject].append(path)
- else:
+ thread = next((thread for thread in threads_index.data if thread.subject == subject), None)
+ if not thread:
# create a new thread
- threads_index.data[subject] = [path]
+ thread = threads.create_thread_structure()
+ thread["subject"] = subject
+ threads_index.data.append(thread)
+
+ thread["messages"].append(path)
+ thread["date"] = datetime.datetime.utcnow()
class ProcessorThread(threading.Thread):
# reading and writing is locking
import os
import json
+import datetime
+import dateutil.parser
from lockfile import FileLock
+class DatetimeEncoder(json.JSONEncoder):
+ def default(self, obj):
+ if isinstance(obj, datetime.datetime):
+ return obj.strftime("%y-%m-%dT%H:%M:%S+00:00")
+
+ 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
try:
with FileLock(self.path):
fd = open(self.path, "r")
- self.data = json.load(fd)
+ self.data = json.load(fd, object_hook=deserialize_datetime)
fd.close()
except IOError:
pass
- def save(self):
+ def save(self, path=None):
+ if path == None:
+ path = self.path
+
def save_proper():
- with open(self.path, "w+") as fd:
- json.dump(self.data, fd)
+ with open(path, "w+") as fd:
+ json.dump(self.data, fd, cls=DatetimeEncoder)
# Lock the file only if it already exists
- if os.path.exists(self.path):
- with FileLock(self.path):
+ # FIXME: this is maybe a race condition
+ if os.path.exists(path):
+ with FileLock(path):
save_proper()
else:
save_proper()
# threads management functions
import jsonfile
+import datetime
import uuid
import os
def load_thread(parent_dir, uuid):
path = os.path.join(parent_dir, name)
+def create_thread_structure():
+ return {"date": datetime.datetime.utcnow(), "messages": [], "subject": ""}
class TestEmailProcessor(unittest.TestCase):
def test_process_email(self):
- threads_index = {"data": {}}
+ class MockThreadsIndex(object):
+ def __init__(self):
+ self.data = []
+
+ threads_index = MockThreadsIndex()
filterdaemon.process_new_email("mocks/test_process_email.txt", threads_index)
- self.assertTrue("Hey, How are you ?" in threads_index["data"])
+ self.assertTrue("Hey, How are you ?" == threads_index.data[0]["subject"])
import tempfile
import fcntl
import os
+import datetime
import kite.jsonfile
import tmpdir
from kite.jsonfile import JsonFile
fd.close()
json_file.refresh()
self.assertEqual(json_file.data, [], msg="Value is not refreshed correctly")
+
+ def test_datetime_serialization(self):
+ d = datetime.datetime.now()
+ json_file = JsonFile()
+ json_file.data = {"date": d}
+ json_file.save(self.tmpfile)
+
+ json_file2 = JsonFile(self.tmpfile)
+ self.assertTrue(isinstance(json_file2.data["date"], datetime.datetime), msg="Datetime value is not deserialized correctly")
+