psa: Removed some debug messages.
[feedingit] / psa_harmattan / feedingit / deb_dist / feedingit-0.1.0 / pysrc / feedingit.py
1 #!/usr/bin/python
2
3 import sys
4
5 from PySide import QtGui
6 from PySide import QtDeclarative
7 import os
8 from os import mkdir, remove, stat, environ
9 from os.path import isfile, isdir, exists
10 import codecs
11 import dbus
12 # import python dbus GLib mainloop support
13 import dbus.mainloop.glib
14 # Enable glib main loop support
15 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
16
17 # Comment the line below if you don't want to use OpenGL for QML rendering or if it is not supported
18 from PySide import QtOpenGL,  QtCore
19
20 from rss_sqlite import Listing
21 CONFIGDIR = environ.get("HOME", "/home/user") + "/.feedingit/"
22 #CONFIGDIR = "/home/user/.feedingit"
23
24 import logging
25 logger = logging.getLogger(__name__)
26
27 import debugging
28 debugging.init(dot_directory=".feedingit", program_name="feedingit-pyside")
29
30 from cgi import escape
31 from re import sub
32
33 class Controller(QtCore.QObject):
34     cachedList = None
35     
36     def __init__(self, listing):
37         QtCore.QObject.__init__(self)
38         from XmlHandler import XmlHandler
39         self._handler = XmlHandler(listing)
40         
41     def update_progress(self, percent_complete,
42                         completed, in_progress, queued,
43                         bytes_downloaded, bytes_updated, bytes_per_second,
44                         feed_updated):
45         total = completed + in_progress + queued
46         root.updateProgress(int(total), int(completed))
47         
48     def articleCountUpdated(self):
49         print "article updated"
50     
51     def update_started(self):
52         root.updateStarted()
53     
54     def update_finished(self):
55         root.updateFinished()
56
57     @QtCore.Slot(str,str, result=str)
58     def getArticle(self, key, article):
59        feed = listing.getFeed(key)
60        try:
61           file = codecs.open(feed.getContentLink(article), "r", "utf-8")
62           html = file.read().replace("body", "body bgcolor='#ffffff'", 1)
63           file.close()
64        except:
65           html = u"<html><body>Error retrieving article</body></html>"
66        return html
67     
68     @QtCore.Slot(str, result=str)
69     def getFeedsXml(self, catid):
70         return self._handler.generateFeedsXml(catid)
71     
72     @QtCore.Slot(str,result=str)
73     def getArticlesXml(self, key):
74         feed = listing.getFeed(key)
75         self.cachedList = feed.getIds(onlyUnread=True)
76         #onlyUnread = arguments.get("onlyUnread","False")
77         return self._handler.generateArticlesXml(key, config.getHideReadArticles())
78     
79     @QtCore.Slot(str,str,bool,result=str)
80     def getNextId(self, key, articleid, onlyUnread):
81         if (onlyUnread):
82             print self.cachedList, articleid
83             index = self.cachedList.index(articleid)
84             return self.cachedList[(index + 1) % len(self.cachedList)]
85         else:
86             feed = listing.getFeed(key)
87             return feed.getNextId(articleid)
88         
89     @QtCore.Slot(str,str,bool,result=str)
90     def getPreviousId(self, key, articleid, onlyUnread):
91         if (onlyUnread):
92             print self.cachedList, articleid
93             index = self.cachedList.index(articleid)
94             return self.cachedList[(index - 1) % len(self.cachedList)]
95         else:
96             feed = listing.getFeed(key)
97             return feed.getPreviousId(articleid)
98     
99     @QtCore.Slot(result=str)
100     def getCategoryXml(self):
101         return self._handler.generateCategoryXml()
102     
103     @QtCore.Slot(QtCore.QObject)
104     def feedClicked(self, wrapper):
105         #print 'User clicked on:', wrapper._key
106         #articlesModel.updateModel(wrapper._key)
107         pass
108         
109     @QtCore.Slot(str)
110     def updateFeed(self, key):
111         listing.updateFeed(key)
112         
113     @QtCore.Slot()
114     def updateAll(self):
115         for catid in listing.getListOfCategories():
116             for feed in listing.getSortedListOfKeys("Manual", category=catid):
117                 listing.updateFeed(feed)
118
119     @QtCore.Slot(str)
120     def updateCategory(self, catid):
121         for feed in listing.getSortedListOfKeys("Manual", category=catid):
122             listing.updateFeed(feed)           
123
124     @QtCore.Slot(str,str,str)
125     def addFeed(self, title, url, catid):
126         listing.addFeed(title,url, category=catid)
127         
128     @QtCore.Slot(str)
129     def addCategory(self, name):
130         listing.addCategory(name)
131
132     @QtCore.Slot(str)
133     def removeFeed(self, key):
134         listing.removeFeed(key)
135
136     @QtCore.Slot(str)
137     def removeCategory(self, catid):
138         listing.removeCategory(catid)
139
140     @QtCore.Slot(str)
141     def markAllAsRead(self, key):
142         feed = listing.getFeed(key)
143         feed.markAllAsRead()
144         listing.updateUnread(key)
145
146     @QtCore.Slot(str, str)
147     def setEntryRead(self, key, articleid):
148         feed = listing.getFeed(key)
149         feed.setEntryRead(articleid)
150         listing.updateUnread(key)
151
152     @QtCore.Slot(str, result=str)
153     def getConfig(self, item):
154         if (item == "hideReadFeed"):
155             return "True"
156         if (item == "hideReadArticles"):
157             return "False"
158         return ""
159     
160     @QtCore.Slot(str, str)
161     def populateFileDialog(self, path, type):
162         import glob
163         import os.path
164         for file in glob.glob(path+type):
165             logger.debug(file)
166             root.addFileNotification(file, os.path.basename(file))
167     
168     @QtCore.Slot(str, result=int)
169     def importOpml(self, filename):
170         from opml_lib import parseOpml
171         file = open(filename, "r")
172         feeds = parseOpml(file.read())
173         file.close()
174         for (title, url) in feeds:
175             listing.addFeed(title, url)
176         return len(feeds)
177     
178     @QtCore.Slot(str, result=str)
179     def exportOpml(self, filename="/home/user/MyDocs/feedingit-export.opml"):
180         logger.debug("ExportOpmlData: %s" % filename)
181         from opml_lib import getOpmlText
182         try:
183             str = getOpmlText(listing)
184             file = open(filename, "w")
185             file.write(str)
186             file.close()
187             return filename
188         except:
189             logger.debug("Error exporting: %s" % filename)
190             return "error"
191         
192     @QtCore.Slot(str, result=bool)
193     def getBooleanSetting(self, setting):
194         if (setting == "theme"):
195             return config.getTheme()
196         elif (setting == "imageCache" ):
197             return config.getImageCache()
198         elif (setting == "hideReadFeeds"):
199             return config.getHideReadFeeds()
200         elif (setting == "hideReadArticles"):
201             return config.getHideReadArticles()
202         elif (setting == "autoupdate"):
203             return config.isAutoUpdateEnabled()
204         else:
205             return 'True'
206         
207     @QtCore.Slot(str, result=int)
208     def getIntSetting(self, setting):
209         if (setting == "artFontSize"):
210             return config.getArtFontSize()
211         elif (setting == "fontSize" ):
212             return config.getFontSize()
213         else:
214             return -1
215         
216     @QtCore.Slot(str, bool)
217     def setBooleanSetting(self, setting, value):
218         if (setting == "theme"):
219             config.setTheme(value)
220         elif (setting == "imageCache" ):
221             config.setImageCache(value)
222         elif (setting == "hideReadFeeds"):
223             config.setHideReadFeeds(value)
224         elif (setting == "hideReadArticles"):
225             config.setHideReadArticles(value)
226         elif (setting == "autoupdate"):
227             config.setAutoUpdateEnabled(value)
228         config.saveConfig()
229         
230     @QtCore.Slot(str, int)
231     def setIntSetting(self, setting, value):
232         if (setting == "artFontSize"):
233             config.setArtFontSize(value)
234         elif (setting == "fontSize" ):
235             config.setFontSize(value)
236         config.saveConfig()
237     
238     @QtCore.Slot(str, str)
239     def openSettings(self):
240         bus = dbus.SessionBus()
241         settingService = bus.get_object('com.nokia.DuiControlPanel', '/')
242         setting = shareService.get_dbus_method('appletPage', 'com.nokia.DuiControlPanelIf')
243         setting("feedingitsync")
244
245     @QtCore.Slot(str, str)
246     def share(self, key, articleid):
247         feed = listing.getFeed(key)
248         title = feed.getTitle(articleid)
249         link = feed.getExternalLink(articleid)
250         description = 'Shared%20via%20FeedingIt%20on%20Meego'
251         import urllib
252         bus = dbus.SessionBus()
253         shareService = bus.get_object('com.nokia.ShareUi', '/')
254         share = shareService.get_dbus_method('share', 'com.nokia.maemo.meegotouch.ShareUiInterface')
255         #share([u'data:text/x-url;description=Support%20for%20Nokia%20Developers;title=Forum%20Nokia,http%3A%2F%2Fforum.nokia.com',])
256         share( ['data:text/x-url;title=%s;description=%s,%s' %(urllib.quote(title), description, urllib.quote(link)),] )
257
258 def main():
259     if not isdir(CONFIGDIR):
260         try:
261             mkdir(CONFIGDIR)
262         except:
263             logger.error("Error: Can't create configuration directory")
264             from sys import exit
265             exit(1)
266             
267     from config import Config
268     global config
269     config = Config(None,CONFIGDIR+"config.ini")
270
271     global listing
272     listing = Listing(config, CONFIGDIR)
273     
274     import mainthread
275     mainthread.init()
276
277     from jobmanager import JobManager
278     JobManager(True)
279
280     app = QtGui.QApplication(sys.argv)
281     view = QtDeclarative.QDeclarativeView()
282
283     controller = Controller(listing)
284  
285     # listen on dbus for download update progress
286     bus = dbus.SessionBus()
287     
288     bus.add_signal_receiver(handler_function=controller.update_progress,
289                             bus_name=None,
290                             signal_name='UpdateProgress',
291                             dbus_interface='org.marcoz.feedingit',
292                             path='/org/marcoz/feedingit/update')
293     
294     bus.add_signal_receiver(handler_function=controller.articleCountUpdated,
295                             bus_name=None,
296                             signal_name='ArticleCountUpdated',
297                             dbus_interface='org.marcoz.feedingit',
298                             path='/org/marcoz/feedingit/update')
299     bus.add_signal_receiver(handler_function=controller.update_started,
300                             bus_name=None,
301                             signal_name='UpdateStarted',
302                             dbus_interface='org.marcoz.feedingit',
303                             path='/org/marcoz/feedingit/update')
304     bus.add_signal_receiver(handler_function=controller.update_finished,
305                             bus_name=None,
306                             signal_name='UpdateFinished',
307                             dbus_interface='org.marcoz.feedingit',
308                             path='/org/marcoz/feedingit/update')
309  
310     global root
311     rc = view.rootContext()
312  
313     rc.setContextProperty('controller', controller)
314
315     # Comment the two lines below if you don't want to use OpenGL for QML rendering or if it is not supported
316     #glw = QtOpenGL.QGLWidget()
317     #view.setViewport(glw)
318
319     if os.path.exists('/usr/share/feedingit/qml'):
320         glw = QtOpenGL.QGLWidget()
321         view.setViewport(glw)
322         view.setSource('/usr/share/feedingit/qml/main.qml')
323         view.showFullScreen()
324     else:
325         view.setSource(os.path.join('qml','main.qml'))
326         view.show()
327         #view.setSource(os.path.join('qml','FeedingIt.qml'))
328     root = view.rootObject()
329
330     #view.showFullScreen()
331     #view.show()
332     sys.exit(app.exec_())
333
334 if __name__ == "__main__": 
335     main()