simplerss: reread feeds on callback
[enigma2-plugins.git] / simplerss / src / RSSPoller.py
1 # for localized messages
2 from . import _
3
4 from Components.config import config
5 from enigma import eTimer
6
7 from Tools.Notifications import AddPopup
8 from Screens.MessageBox import MessageBox
9
10 from RSSFeed import BaseFeed, UniversalFeed
11
12 from twisted.web.client import getPage
13 from xml.etree.cElementTree import fromstring as cElementTree_fromstring
14
15 from GoogleReader import GoogleReader
16
17 NOTIFICATIONID = 'SimpleRSSUpdateNotification'
18
19 update_callbacks = []
20
21 class RSSPoller:
22         """Keeps all Feed and takes care of (automatic) updates"""
23
24         def __init__(self, poll = True):
25                 # Timer
26                 self.poll_timer = eTimer()
27                 self.poll_timer.callback.append(self.poll)
28                 self.do_poll = poll
29
30                 # this indicates we're reloading the list of feeds
31                 self.reloading = False
32
33                 self.newItemFeed = BaseFeed(
34                         "",
35                         _("New Items"),
36                         _("New Items since last Auto-Update"),
37                 )
38
39                 # Generate Feeds
40                 self.feeds = [
41                         UniversalFeed(
42                                 x.uri.value,
43                                 x.autoupdate.value
44                         )
45                                 for x in config.plugins.simpleRSS.feed
46                 ]
47
48                 if not config.plugins.simpleRSS.enable_google_reader.value:
49                         if poll:
50                                 self.poll_timer.start(0, 1)
51                 else:
52                         self.googleReader = GoogleReader(config.plugins.simpleRSS.google_username.value, config.plugins.simpleRSS.google_password.value)
53                         self.googleReader.login().addCallback(self.googleLoggedIn).addErrback(self.googleLoginFailed)
54
55                 # Initialize Vars
56                 self.current_feed = 0
57
58         def googleLoggedIn(self, sid = None):
59                 self.googleReader.getSubscriptionList().addCallback(self.googleSubscriptionList).addErrback(self.googleSubscriptionFailed)
60
61         def googleLoginFailed(self, res = None):
62                 AddPopup(
63                         _("Failed to login to Google Reader."),
64                         MessageBox.TYPE_ERROR,
65                         5,
66                 )
67
68                 self.reloading = False
69                 if self.do_poll:
70                         self.poll_timer.start(0, 1)
71
72         def googleSubscriptionList(self, subscriptions = None):
73                 self.feeds.extend(subscriptions)
74
75                 self.reloading = False
76                 if self.do_poll:
77                         self.doCallback()
78                         self.poll_timer.start(0, 1)
79
80         def googleSubscriptionFailed(self, res = None):
81                 AddPopup(
82                         _("Failed to get subscriptions from Google Reader."),
83                         MessageBox.TYPE_ERROR,
84                         5,
85                 )
86
87                 self.reloading = False
88                 if self.do_poll:
89                         self.poll_timer.start(0, 1)
90
91         def addCallback(self, callback):
92                 if callback not in update_callbacks:
93                         update_callbacks.append(callback)
94
95         def removeCallback(self, callback):
96                 if callback in update_callbacks:
97                         update_callbacks.remove(callback)
98
99         def doCallback(self, id = None):
100                 for callback in update_callbacks:
101                         try:
102                                 callback(id)
103                         except Exception:
104                                 pass
105
106         def error(self, error = ""):
107                 print "[SimpleRSS] failed to fetch feed:", error
108
109                 # Assume its just a temporary failure and jump over to next feed
110                 self.next_feed()
111
112         def _gotPage(self, data, id = None, callback = False, errorback = None):
113                 # workaround: exceptions in gotPage-callback were ignored
114                 try:
115                         self.gotPage(data, id)
116                         if callback:
117                                 self.doCallback(id)
118                 except NotImplementedError, errmsg:
119                         # Don't show this error when updating in background
120                         if id is not None:
121                                 AddPopup(
122                                         _("Sorry, this type of feed is unsupported:\n%s") % (str(errmsg)),
123                                         MessageBox.TYPE_INFO,
124                                         5,
125                                 )
126                         else:
127                                 # We don't want to stop updating just because one feed is broken
128                                 self.next_feed()
129                 except Exception:
130                         import traceback, sys
131                         traceback.print_exc(file=sys.stdout)
132                         # Errorback given, call it (asumme we don't need do restart timer!)
133                         if errorback is not None:
134                                 errorback()
135                                 return
136                         # Assume its just a temporary failure and jump over to next feed
137                         self.next_feed()
138
139         def gotPage(self, data, id = None):
140                 feed = cElementTree_fromstring(data)
141
142                 # For Single-Polling
143                 if id is not None:
144                         self.feeds[id].gotFeed(feed)
145                         print "[SimpleRSS] single feed parsed..."
146                         return
147
148                 new_items = self.feeds[self.current_feed].gotFeed(feed)
149
150                 print "[SimpleRSS] feed parsed..."
151
152                 # Append new items to locally bound ones
153                 if new_items is not None:
154                         self.newItemFeed.history.extend(new_items)
155
156                 # Start Timer so we can either fetch next feed or show new_items
157                 self.next_feed()
158
159         def singlePoll(self, id, callback = False, errorback = None):
160                 getPage(self.feeds[id].uri).addCallback(self._gotPage, id, callback, errorback).addErrback(errorback)
161
162         def poll(self):
163                 # Reloading, reschedule
164                 if self.reloading:
165                         print "[SimpleRSS] timer triggered while reloading, rescheduling"
166                         self.poll_timer.start(10000, 1)
167                 # End of List
168                 elif len(self.feeds) <= self.current_feed:
169                         # New Items
170                         if self.newItemFeed.history:
171                                 print "[SimpleRSS] got new items, calling back"
172                                 self.doCallback()
173
174                                 # Inform User
175                                 update_notification_value = config.plugins.simpleRSS.update_notification.value
176                                 if update_notification_value == "preview":
177                                         from RSSScreens import RSSFeedView
178
179                                         from Tools.Notifications import AddNotificationWithID, RemovePopup
180
181                                         RemovePopup(NOTIFICATIONID)
182
183                                         AddNotificationWithID(
184                                                 NOTIFICATIONID,
185                                                 RSSFeedView,
186                                                 self.newItemFeed,
187                                                 newItems = True
188                                         )
189                                 elif update_notification_value == "notification":
190                                         AddPopup(
191                                                 _("Received %d new news item(s).") % (len(self.newItemFeed.history)),
192                                                 MessageBox.TYPE_INFO,
193                                                 5,
194                                                 NOTIFICATIONID
195                                         )
196                         # No new Items
197                         else:
198                                 print "[SimpleRSS] no new items"
199
200                         self.current_feed = 0
201                         self.poll_timer.startLongTimer(config.plugins.simpleRSS.interval.value*60)
202                 # It's updating-time
203                 else:
204                         # Assume we're cleaning history if current feed is 0
205                         clearHistory = self.current_feed == 0
206                         if config.plugins.simpleRSS.update_notification.value != "none":
207                                 from Tools.Notifications import current_notifications, notifications
208                                 for x in current_notifications:
209                                         if x[0] == NOTIFICATIONID:
210                                                 print "[SimpleRSS] timer triggered while preview on screen, rescheduling"
211                                                 self.poll_timer.start(10000, 1)
212                                                 return
213
214                                 if clearHistory:
215                                         for x in notifications:
216                                                 if x[4] and x[4] == NOTIFICATIONID:
217                                                         print "[SimpleRSS] wont wipe history because it was never read"
218                                                         clearHistory = False
219                                                         break
220
221                         if clearHistory:
222                                 del self.newItemFeed.history[:]
223
224                         # Feed supposed to autoupdate
225                         feed = self.feeds[self.current_feed]
226
227                         if feed.autoupdate:
228                                 getPage(feed.uri).addCallback(self._gotPage).addErrback(self.error)
229                         # Go to next feed
230                         else:
231                                 print "[SimpleRSS] passing feed"
232                                 self.next_feed()
233
234         def next_feed(self):
235                 self.current_feed += 1
236                 self.poll_timer.start(1000, 1)
237
238         def shutdown(self):
239                 self.poll_timer.callback.remove(self.poll)
240                 self.poll_timer = None
241                 self.do_poll = False
242
243         def triggerReload(self):
244                 self.reloading = True
245
246                 newfeeds = []
247                 oldfeeds = self.feeds
248                 found = False
249                 for x in config.plugins.simpleRSS.feed:
250                         for feed in oldfeeds:
251                                 if x.uri.value == feed.uri:
252                                         # Update possibly different autoupdate value
253                                         feed.autoupdate = x.autoupdate.value
254                                         newfeeds.append(feed) # Append to new Feeds
255                                         oldfeeds.remove(feed) # Remove from old Feeds
256                                         found = True
257                                         break
258                         if not found:
259                                 newfeeds.append(
260                                         UniversalFeed(
261                                                 x.uri.value,
262                                                 x.autoupdate.value
263                                 ))
264                         found = False
265
266                 self.feeds = newfeeds
267
268                 if config.plugins.simpleRSS.enable_google_reader.value:
269                         self.googleReader = GoogleReader(config.plugins.simpleRSS.google_username.value, config.plugins.simpleRSS.google_password.value)
270                         self.googleReader.login().addCallback(self.googleLoggedIn).addErrback(self.googleLoginFailed)
271                 else:
272                         self.reloading = False
273