Removed postoffice spam
[jamaendo] / jamaui / postoffice.py
index 009c884..e47cccf 100644 (file)
 #
 # message central
 
+from __future__ import with_statement
+import logging
+import threading
+
+log = logging.getLogger(__name__)
+
 class PostOffice(object):
-    class Client(object):
-        def __init__(self):
-            self.tags = {}
-        def has_tag(self, tag):
-            return tag in self.tags
-        def notify(self, tags, data):
-            for tag in tags:
-                cb = self.tags.get(tag)
-                if cb:
-                    cb(data)
-        def register(self, tag, callback):
-            self.tags[tag] = callback
 
     def __init__(self):
-        self.clients = {}
-
-    def notify(self, tags, data):
-        if not isinstance(tags, list):
-            tags = [tags]
-        for client in clients:
-            client.notify(tags, data)
-
-    def register(self, client_id, tag, callback):
-        client = self.clients.get(client_id)
-        if not client:
-            client = Client()
-            self.clients[client_id] = client
-        client.register(tag, callback)
+        self.lock = threading.RLock()
+        self.tags = {} # tag -> [callback]
+
+    def notify(self, tag, *data):
+        with self.lock:
+            #log.info("(%s %s)", tag, " ".join(str(x) for x in data))
+            clients = self.tags.get(tag)
+            if clients:
+                for ref, client in clients:
+                    client(*data)
+
+    def connect(self, tag, ref, callback):
+        with self.lock:
+            if not isinstance(tag, list):
+                tag = [tag]
+            for t in tag:
+                if t not in self.tags:
+                    self.tags[t] = []
+                clients = self.tags[t]
+                if callback not in clients:
+                    clients.append((ref, callback))
+
+    def disconnect(self, tag, ref):
+        with self.lock:
+            if not isinstance(tag, list):
+                tag = [tag]
+            for t in tag:
+                if t not in self.tags:
+                    self.tags[t] = []
+                self.tags[t] = [(_ref, cb) for _ref, cb in self.tags[t] if _ref != ref]
 
 postoffice = PostOffice()