a84158b1a57af60ce02dfdbd287a45b5ad749c7f
[jamaendo] / jamaui / postoffice.py
1 #!/usr/bin/env python
2 #
3 # This file is part of Jamaendo.
4 # Copyright (c) 2010 Kristoffer Gronlund
5 #
6 # Jamaendo is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Jamaendo is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Jamaendo.  If not, see <http://www.gnu.org/licenses/>.
18 #
19 # Player code heavily based on http://thpinfo.com/2008/panucci/:
20 #  A resuming media player for Podcasts and Audiobooks
21 #  Copyright (c) 2008-05-26 Thomas Perl <thpinfo.com>
22 #  (based on http://pygstdocs.berlios.de/pygst-tutorial/seeking.html)
23 #
24 # message central
25
26 from __future__ import with_statement
27 import logging
28 import threading
29
30 log = logging.getLogger(__name__)
31
32 class PostOffice(object):
33
34     def __init__(self):
35         self.lock = threading.RLock()
36         self.tags = {} # tag -> [callback]
37
38     def notify(self, tag, *data):
39         with self.lock:
40             log.info("(%s %s)", tag, " ".join(str(x) for x in data))
41             clients = self.tags.get(tag)
42             if clients:
43                 for ref, client in clients:
44                     client(*data)
45
46     def connect(self, tag, ref, callback):
47         with self.lock:
48             if not isinstance(tag, list):
49                 tag = [tag]
50             for t in tag:
51                 if t not in self.tags:
52                     self.tags[t] = []
53                 clients = self.tags[t]
54                 if callback not in clients:
55                     clients.append((ref, callback))
56
57     def disconnect(self, tag, ref):
58         with self.lock:
59             if not isinstance(tag, list):
60                 tag = [tag]
61             for t in tag:
62                 if t not in self.tags:
63                     self.tags[t] = []
64                 self.tags[t] = [(_ref, cb) for _ref, cb in self.tags[t] if _ref != ref]
65
66 postoffice = PostOffice()
67
68