harmonized maemo/harmattan src files
[feedingit] / psa_harmattan / feedingit / pysrc / wc.py
1 # Copyright (c) 2011 Neal H. Walfield
2 #
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16 import logging
17 logger = logging.getLogger(__name__)
18 import traceback
19
20 # Don't fail if the Woodchuck modules are not available.  Just disable
21 # Woodchuck's functionality.
22
23 # Whether we imported the woodchuck modules successfully.
24 woodchuck_imported = True
25 try:
26     import pywoodchuck
27     from pywoodchuck import PyWoodchuck
28     from pywoodchuck import woodchuck
29 except ImportError, exception:
30     logger.info(
31         "Unable to load Woodchuck modules: disabling Woodchuck support: %s"
32         % traceback.format_exc ())
33     woodchuck_imported = False
34     class PyWoodchuck (object):
35         def available(self, *args, **kwargs):
36             return False
37     woodchuck = None
38
39 # The default channel refresh interval: 6 hours.
40 refresh_interval = 6 * 60 * 60
41
42 class mywoodchuck (PyWoodchuck):
43     def __init__(self, config, listing, human_readable_name, identifier,
44                  request_feedback):
45         try:
46             PyWoodchuck.__init__ (self, human_readable_name, identifier,
47                                   request_feedback)
48         except Exception, e:
49             logger.error(
50                 "Failed to establish a connection to the Woodchuck server: %s"
51                 % (str(e),))
52             self.available = self.not_available
53             return
54
55         self.config = config
56         self.listing = listing
57
58         try:
59             self.enabled = config.getWoodchuckEnabled()
60         except Exception:
61             logging.exception("Setting enabled")
62
63     def available(self, check_config=True):
64         if not PyWoodchuck.available(self):
65             return False
66         if check_config:
67             return self.config.getWoodchuckEnabled()
68         return True
69
70     def not_available(self, *args, **kwargs):
71         return False
72
73     # Woodchuck upcalls.
74     def stream_update_cb(self, stream, *args, **kwargs):
75         logger.debug("stream update called on %s (%s)"
76                      % (stream.human_readable_name, stream.identifier,))
77
78         # Make sure no one else is concurrently updating this
79         # feed.
80         try:
81             self.listing.updateFeed(stream.identifier)
82         except:
83             logger.debug("Updating %s: %s"
84                          % (stream.identifier, traceback.format_exc ()))
85
86     def object_transfer_cb(self, stream, object,
87                            version, filename, quality,
88                            *args, **kwargs):
89         logger.debug ("object transfer called on %s (%s) in stream %s (%s)"
90                       % (object.human_readable_name, object.identifier,
91                          stream.human_readable_name, stream.identifier))
92         try:
93             self[stream.identifier][object.identifier].dont_transfer = True
94         except Exception, e:
95             logger.warn("Setting '%s'(%s).'%s'(%s).DontTransfer: %s"
96                         % (stream.human_readable_name, stream.identifier,
97                            object.human_readable_name, object.identifier,
98                            str(e)))
99
100 _w = None
101 def wc_init(config, listing, request_feedback=False):
102     """Connect to the woodchuck server and initialize any state."""
103     global _w
104     assert _w is None
105     
106     _w = mywoodchuck (config, listing, "FeedingIt", "org.marcoz.feedingit",
107                       request_feedback)
108
109     if not woodchuck_imported or not _w.available ():
110         logger.info("Unable to contact Woodchuck server.")
111     else:
112         logger.debug("Woodchuck appears to be available.")
113
114 def wc_disable_set(disable=True):
115     """Disable Woodchuck."""
116     if disable:
117         logger.info("Disabling Woodchuck")
118     else:
119         logger.info("Enabling Woodchuck")
120
121     global _w
122     if _w is None:
123         logging.info("Woodchuck not loaded.  Not doing anything.")
124         return
125
126     if not _w.available(check_config=False):
127         logging.info("Woodchuck not available.  Not doing anything.")
128         return
129
130     try:
131         _w.enabled = not disable
132     except Exception:
133         logger.exception("Disabling Woodchuck")
134
135 def wc():
136     """Return the Woodchuck singleton."""
137     global _w
138     assert _w is not None
139     return _w