0.9 beta 3 - Added features to qml interface (dbus, edit mode...)
[feedingit] / src / FeedingIt-Web.py
index a11c816..d261444 100644 (file)
@@ -5,9 +5,18 @@ from xml import sax
 from cgi import escape
 from re import sub
 from htmlentitydefs import name2codepoint
+from gconf import client_get_default
+from urllib2 import ProxyHandler
+from threading import Thread
+from os.path import isfile, isdir, exists
+from os import mkdir, remove, stat
 
 CONFIGDIR = "/home/user/.feedingit/"
 
+updatingFeeds = []
+#commands = [("addFeed","httpwww"), ("openFeed", "xxxx"), ("openArticle", ("feedid","artid"))]
+commands = [("openFeed", "1,", "61ac1458d761423344998dc76770e36e")]
+
 def unescape(text):
     def fixup(m):
         text = m.group(0)
@@ -29,11 +38,74 @@ def unescape(text):
         return text # leave as is
     return sub("&#?\w+;", fixup, text)
 
-class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
+def sanitize(text):
+    from cgi import escape
+    return escape(text).encode('ascii', 'xmlcharrefreplace')
+
+def start_server():
+    global listing
+    listing = Listing(CONFIGDIR)
+    httpd = BaseHTTPServer.HTTPServer(("127.0.0.1", PORT), Handler)
+    httpd.serve_forever()    
+
+class App():
+    def addFeed(self, url):
+        commands.append(("addFeed",url))
+    
+    def getStatus(self):
+        pass
+    
+    def openFeed(self, key):
+        cat = listing.getFeedCategory(key)
+        commands.append( ("openFeed", cat, key) )
+    
+    def OpenArticle(self, key, id):
+        cat = listing.getFeedCategory(key)
+        commands.append( ("openArticle", (cat, key, id)) )
     
+class Download(Thread):
+    def __init__(self, listing, keys):
+        Thread.__init__(self)
+        self.listing = listing
+        self.keys = keys
+        
+    def run (self):
+        for key in self.keys:
+            print "Start update: %s" % key
+            updatingFeeds.append(key)
+            (use_proxy, proxy) = config.getProxy()
+            try:
+                if use_proxy:
+                        self.listing.updateFeed(key, proxy=proxy, imageCache=config.getImageCache() )
+                else:
+                        self.listing.updateFeed(key, imageCache=config.getImageCache() )
+            except:
+                print "Error updating feed: %s" %key
+            updatingFeeds.remove(key)
+            print "End update: %s" % key
+
+class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
     def openTaskSwitch(self):
         import subprocess
         subprocess.Popen("dbus-send /com/nokia/hildon_desktop com.nokia.hildon_desktop.exit_app_view", shell=True)
+        
+    def updateAll(self):
+        import subprocess
+        subprocess.Popen("FeedingIt update", shell=True)
+    
+    def getCommands(self):
+        
+        commandXml = "<commands>"
+        for item in commands:
+            if item[0]=="addFeed":
+                commandXml += "<command c='addFeed'>%s</command>" %(sanitize(item[1]))
+            if item[0]=="openFeed":
+                commandXml += "<command c='openFeed' cat='%s'>%s</command>" % (sanitize(item[1]), sanitize(item[2]) )
+            if item[0]=="openArticle":
+                commandXml += "<command c='openArticle' cat='%s' key='%s'>%s</command>" %(sanitize(item[1], sanitize(item[2][0]), sanitize(item[2][1])) )
+            commands.remove(item)
+        commandXml += "</commands>"
+        return commandXml
     
     def getConfigXml(self):
         xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><xml>"
@@ -64,6 +136,10 @@ class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
             xml += "<unread>%s</unread>" %listing.getFeedNumberOfUnreadItems(key)
             xml += "<updatedDate>%s</updatedDate>" %listing.getFeedUpdateTime(key)
             xml += "<icon>%s</icon>" %listing.getFavicon(key)
+            if key in updatingFeeds:
+                xml += "<updating>True</updating>"
+            else:
+                xml += "<updating>False</updating>"
             xml += "</feed>"
         xml += "</xml>"
         return xml
@@ -93,14 +169,9 @@ class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
         arguments = {}
         if arg != "":
             args = arg.split("&")
-            print args
             for arg in args:
                 ele = arg.split("=")
-                print ele
-                #try:
                 arguments[ele[0]] = ele[1]
-                #except:
-                #    pass
         if request[1] == "categories":
             xml = self.generateCategoryXml()
         elif request[1] == "feeds":
@@ -117,7 +188,6 @@ class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
             feed = listing.getFeed(key)
             try:
                 file = open(feed.getContentLink(article))
-                #feed.setEntryRead(article)
                 html = file.read().replace("body", "body bgcolor='#ffffff'", 1)
                 file.close()
             except:
@@ -128,6 +198,15 @@ class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
             self.wfile.write(html)
             #listing.updateUnread(key)
             return
+        elif request[1] == "isUpdating":
+            xml = "<xml>"
+            key = request[2]
+            if (key in updatingFeeds) or ((key=="") and (len(updatingFeeds)>0)):
+                xml += "<updating>True</updating>"
+            else:
+                xml += "<updating>False</updating>"
+            xml += self.getCommands()
+            xml += "</xml>"
         elif request[1] == "read":
             key = request[2]
             article = request[3]
@@ -152,6 +231,38 @@ class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
         elif request[1] == "task":
             self.openTaskSwitch()
             xml = "<xml>OK</xml>"
+        elif request[1] == "deleteCat":
+            key = request[2]
+            listing.removeCategory(key)
+            xml = "<xml>OK</xml>"
+        elif request[1] == "deleteFeed":
+            key = request[3]
+            listing.removeFeed(key)
+            xml = "<xml>OK</xml>"
+        elif request[1] == "addFeed":
+            cat = request[2]
+            name = request[3]
+            url = arguments.get("url","")
+            listing.addFeed(name, url, category=cat)
+            xml = "<xml>OK</xml>"
+        elif request[1] == "updateFeed":
+            key = request[2]
+            download = Download(listing, [key,])
+            download.start()
+            xml = "<xml>OK</xml>"
+        elif request[1]=="updateAll":
+            feeds = []
+            for cat in listing.getListOfCategories():
+                for feed in listing.getSortedListOfKeys("Manual", category=cat):
+                    feeds.append(feed)
+            print feeds
+            download = Download(listing, feeds)
+            download.start()
+            xml = "<xml>OK</xml>"
+        elif request[1] == "addCat":
+            catName = request[2]
+            listing.addCategory(catName)
+            xml = "<xml>OK</xml>"
         else:
             self.send_error(404, "File not found")
             return
@@ -162,8 +273,28 @@ class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
 
 PORT = 8000
 
-listing = Listing(CONFIGDIR)
+if not isdir(CONFIGDIR):
+    try:
+        mkdir(CONFIGDIR)
+    except:
+        print "Error: Can't create configuration directory"
+        from sys import exit
+        exit(1)
+
+from config import Config
+config = Config(None,CONFIGDIR+"config.ini")
+
+import thread
+
+#print "serving at port", PORT
+thread.start_new_thread(start_server, ())
+
+from feedingitdbus import ServerObject
+#from updatedbus import UpdateServerObject, get_lock
+import gobject
+gobject.threads_init()
+import dbus.mainloop.glib
+dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
 
-httpd = BaseHTTPServer.HTTPServer(("127.0.0.1", PORT), Handler)
-print "serving at port", PORT
-httpd.serve_forever()
+mainloop = gobject.MainLoop()
+mainloop.run()