allow to fetch feeds from google reader
[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, session, poll = True):
25                 # Timer
26                 self.poll_timer = eTimer()
27                 self.poll_timer.callback.append(self.poll)
28                 self.do_poll = poll
29
30                 # Save Session, Initialize Var to identify triggered Reload
31                 self.session = session
32                 self.reloading = False
33
34                 self.newItemFeed = BaseFeed(
35                         "",
36                         _("New Items"),
37                         _("New Items since last Auto-Update"),
38                 )
39
40                 # Generate Feeds
41                 self.feeds = [
42                         UniversalFeed(
43                                 x.uri.value,
44                                 x.autoupdate.value
45                         )
46                                 for x in config.plugins.simpleRSS.feed
47                 ]
48
49                 if not config.plugins.simpleRSS.enable_google_reader.value:
50                         if poll:
51                                 self.poll_timer.start(0, 1)
52                 else:
53                         self.googleReader = GoogleReader(config.plugins.simpleRSS.google_username.value, config.plugins.simpleRSS.google_password.value)
54                         self.googleReader.login().addCallback(self.googleLoggedIn).addErrback(self.googleLoginFailed)
55
56                 # Initialize Vars
57                 self.current_feed = 0
58
59         def googleLoggedIn(self, sid = None):
60                 self.googleReader.getSubscriptionList().addCallback(self.googleSubscriptionList).addErrback(self.googleSubscriptionFailed)
61
62         def googleLoginFailed(self, res = None):
63                 AddPopup(
64                         _("Failed to login to GoogleReader."),
65                         MessageBox.TYPE_ERROR,
66                         5,
67                 )
68
69                 self.reloading = False
70                 if self.do_poll:
71                         self.poll_timer.start(0, 1)
72
73         def googleSubscriptionList(self, subscriptions = None):
74                 self.feeds.extend(subscriptions)
75
76                 self.reloading = False
77                 if self.do_poll:
78                         self.poll_timer.start(0, 1)
79
80         def googleSubscriptionFailed(self, res = None):
81                 AddPopup(
82                         _("Failed to get subscriptions from GoogleReader."),
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                                 from Screens.MessageBox import MessageBox
122
123                                 self.session.open(
124                                         MessageBox,
125                                         _("Sorry, this type of feed is unsupported:\n%s") % (str(errmsg)),
126                                         type = MessageBox.TYPE_INFO,
127                                         timeout = 5
128                                 )
129                 except:
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
242         def triggerReload(self):
243                 self.reloading = True
244
245                 newfeeds = []
246                 oldfeeds = self.feeds
247                 found = False
248                 for x in config.plugins.simpleRSS.feed:
249                         for feed in oldfeeds:
250                                 if x.uri.value == feed.uri:
251                                         # Update possibly different autoupdate value
252                                         feed.autoupdate = x.autoupdate.value
253                                         newfeeds.append(feed) # Append to new Feeds
254                                         oldfeeds.remove(feed) # Remove from old Feeds
255                                         found = True
256                                         break
257                         if not found:
258                                 newfeeds.append(
259                                         UniversalFeed(
260                                                 x.uri.value,
261                                                 x.autoupdate.value
262                                 ))
263                         found = False
264
265                 self.feeds = newfeeds
266
267                 if config.plugins.simpleRSS.enable_google_reader.value:
268                         self.googleReader = GoogleReader(config.plugins.simpleRSS.google_username.value, config.plugins.simpleRSS.google_password.value)
269                         self.googleReader.login().addCallback(self.googleLoggedIn).addErrback(self.googleLoginFailed)
270                 else:
271                         self.reloading = False
272