]> khamidou — GitHub mirrors - kite.git/commitdiff
refactored threads_index structure
authorkarim hamidou <khamidou@gmail.com>
Sat, 7 Dec 2013 17:28:22 +0000 (18:28 +0100)
committerkarim hamidou <khamidou@gmail.com>
Sat, 7 Dec 2013 17:28:22 +0000 (18:28 +0100)
src/back/kite/filterdaemon.py
src/back/kite/jsonfile.py
src/back/kite/threads.py
src/back/tests/test_filterdaemon.py
src/back/tests/test_jsonfile.py

index 775b212ee4ae156ba5f165aaf03b607679ef5746..e77d2f1420dcf9458ce1ee454c7368c37305fb7a 100755 (executable)
@@ -6,7 +6,6 @@
 # =======================
 #
 # 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 ?
 # ================
@@ -21,6 +20,7 @@ import sys
 import os
 import pyinotify
 import threading
+import datetime
 import time
 import email.parser
 
@@ -71,6 +71,8 @@ class DumperThread(threading.Thread):
         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):
@@ -81,11 +83,15 @@ 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):
index 22d0c3c295fe6961b865a2b9d39fd211273ba798..a6cba42bc658bbcd92a6a0e32f109ea461000f74 100644 (file)
@@ -2,8 +2,25 @@
 # 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
@@ -15,19 +32,23 @@ class JsonFile(object):
             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()
index da24656ed75ee06448d41fee939dd5e37b521334..b20b1796f6e43e90d3705b7db8b63868af1067a0 100644 (file)
@@ -1,5 +1,6 @@
 # threads management functions
 import jsonfile
+import datetime
 import uuid
 import os
 
@@ -16,6 +17,8 @@ def create_thread(parent_dir):
 def load_thread(parent_dir, uuid):
     path = os.path.join(parent_dir, name)
 
+def create_thread_structure():
+    return {"date": datetime.datetime.utcnow(), "messages": [], "subject": ""}
 
     
 
index 1867cc663d61357f77e40232f95fafbd1272dea7..2e8ba1d48981f4f954d1edf925cfab298e09ec4d 100644 (file)
@@ -4,6 +4,10 @@ import kite.filterdaemon as filterdaemon
 
 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"])
index 7ea1237d126d2d8c519667141f073f08c94201ec..5d95f14e207f57d1b3288366bcb3350311e67104 100644 (file)
@@ -2,6 +2,7 @@ import unittest
 import tempfile
 import fcntl
 import os
+import datetime
 import kite.jsonfile
 import tmpdir
 from kite.jsonfile import JsonFile
@@ -19,3 +20,13 @@ class TestJsonfile(tmpdir.TestCaseWithTempFile):
         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")
+