8acdb7595ec3993c07277076a3707d7f6623ab17
[feedingit] / psa_harmattan / feedingit / deb_dist / feedingit-0.1.0 / debian / feedingit / usr / share / feedingit / XmlHandler.py
1 import sys
2 from rss_sqlite import Listing
3 from xml import sax
4 from cgi import escape
5 from re import sub
6 from htmlentitydefs import name2codepoint
7 from gconf import client_get_default
8
9 import logging
10 logger = logging.getLogger(__name__)
11
12 def unescape(text):
13     def fixup(m):
14         text = m.group(0)
15         if text[:2] == "&#":
16             # character reference
17             try:
18                 if text[:3] == "&#x":
19                     return unichr(int(text[3:-1], 16))
20                 else:
21                     return unichr(int(text[2:-1]))
22             except ValueError:
23                 pass
24         else:
25             # named entity
26             try:
27                 text = unichr(name2codepoint[text[1:-1]])
28             except KeyError:
29                 pass
30         return text # leave as is
31     return sub("&#?\w+;", fixup, text)
32
33 def sanitize(text):
34     from cgi import escape
35     return escape(text).encode('ascii', 'xmlcharrefreplace')
36     
37 class XmlHandler():
38
39     def __init__(self, listing):
40         self.listing=listing
41     
42     def getConfigXml(self):
43         xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><xml>"
44         xml += "<hideReadFeed>True</hideReadFeed>"
45         xml += "<hideReadArticles>True</hideReadArticles>"
46         xml += "</xml>"
47         return xml
48     
49     def generateCategoryXml(self):
50         xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><xml>"
51         for cat in self.listing.getListOfCategories():
52             xml += "<category>"
53             xml += "<catname>%s</catname>" %sanitize(self.listing.getCategoryTitle(cat))
54             xml += "<catid>%s</catid>" % cat
55             xml += "</category>"
56         xml += "</xml>"
57         return xml
58
59     def fix_title(self, title):
60         return escape(unescape(title).replace("<em>","").replace("</em>","").replace("<nobr>","").replace("</nobr>","").replace("<wbr>","").replace("&mdash;","-"))
61     
62     def generateFeedsXml(self, catid):
63         xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><xml>"
64         for key in self.listing.getSortedListOfKeys("Manual", category=catid):
65             xml += "<feed>"
66             xml += "<feedname>%s</feedname>" %sanitize(self.listing.getFeedTitle(key))
67             xml += "<feedid>%s</feedid>" %key
68             xml += "<unread>%s</unread>" %self.listing.getFeedNumberOfUnreadItems(key)
69             xml += "<updatedDate>%s</updatedDate>" %self.listing.getFeedUpdateTime(key)
70             xml += "<icon>%s</icon>" %self.listing.getFavicon(key)
71             # xml += "<updating>True</updating>"
72             xml += "<updating>False</updating>"
73             xml += "</feed>"
74         xml += "</xml>"
75         return xml
76     
77     def generateArticlesXml(self, key, onlyUnread):
78         feed = self.listing.getFeed(key)
79         xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><xml>"
80         if onlyUnread == "False":
81             onlyUnread = False
82         for id in feed.getIds(onlyUnread):
83             xml += "<article>"
84             xml += "<title>%s</title>" %self.fix_title(feed.getTitle(id))
85             xml += "<articleid>%s</articleid>" %id
86             xml += "<unread>%s</unread>" %str(feed.isEntryRead(id))
87             xml += "<updatedDate>%s</updatedDate>" %feed.getDateStamp(id)
88             xml += "<path>%s</path>" %feed.getContentLink(id)
89             xml += "</article>"
90         xml += "</xml>"
91         return xml
92
93     def do_GET(self):
94         (req, sep, arg) = self.path.partition("?")
95         request = req.split("/")
96         arguments = {}
97         if arg != "":
98             args = arg.split("&")
99             for arg in args:
100                 ele = arg.split("=")
101                 arguments[ele[0]] = ele[1]
102         if request[1] == "categories":
103             xml = self.generateCategoryXml()
104         elif request[1] == "feeds":
105             catid = request[2]
106             xml = self.generateFeedsXml(catid)
107         elif request[1] == "articles":
108             key = request[2]
109             onlyUnread = arguments.get("onlyUnread","False")
110             markAllAsRead = arguments.get("markAllAsRead", "False")
111             xml = self.generateArticlesXml(key, onlyUnread, markAllAsRead)
112         elif request[1] == "html":
113             key = request[2]
114             article = request[3]
115             feed = listing.getFeed(key)
116             try:
117                 file = open(feed.getContentLink(article))
118                 html = file.read().replace("body", "body bgcolor='#ffffff'", 1)
119                 file.close()
120             except:
121                 html = "<html><body>Error retrieving article</body></html>"
122             self.send_response(200)
123             self.send_header("Content-type", "text/html")
124             self.end_headers()
125             self.wfile.write(html)
126             #listing.updateUnread(key)
127             return
128         elif request[1] == "isUpdating":
129             xml = "<xml>"
130             key = request[2]
131             if (key in updatingFeeds) or ((key=="") and (len(updatingFeeds)>0)):
132                 xml += "<updating>True</updating>"
133             else:
134                 xml += "<updating>False</updating>"
135             xml += self.getCommands()
136             xml += "</xml>"
137         elif request[1] == "read":
138             key = request[2]
139             article = request[3]
140             feed = listing.getFeed(key)
141             feed.setEntryRead(article)
142             listing.updateUnread(key)
143             self.send_response(200)
144             self.send_header("Content-type", "text/html")
145             self.end_headers()
146             self.wfile.write("OK")
147             return
148         elif request[1] == "config":
149             xml = self.getConfigXml()
150         elif request[1] == "home":
151             file = open(self.path)
152             self.send_response(200)
153             self.send_header("Content-type", "text/html")
154             self.end_headers()
155             self.wfile.write(file.read())
156             file.close()
157             return
158         elif request[1] == "task":
159             self.openTaskSwitch()
160             xml = "<xml>OK</xml>"
161         elif request[1] == "deleteCat":
162             key = request[2]
163             listing.removeCategory(key)
164             xml = "<xml>OK</xml>"
165         elif request[1] == "deleteFeed":
166             key = request[3]
167             listing.removeFeed(key)
168             xml = "<xml>OK</xml>"
169         elif request[1] == "addFeed":
170             cat = request[2]
171             name = request[3]
172             url = arguments.get("url","")
173             listing.addFeed(name, url, category=cat)
174             xml = "<xml>OK</xml>"
175         elif request[1] == "updateFeed":
176             key = request[2]
177             listing.updateFeed (key, priority=-1)
178             #download = Download(listing, [key,])
179             #download.start()
180             xml = "<xml>OK</xml>"
181         elif request[1]=="updateAll":
182             #app.automaticUpdate()
183             self.updateAll()
184             xml = "<xml>OK</xml>"
185         elif request[1] == "addCat":
186             catName = request[2]
187             listing.addCategory(catName)
188             xml = "<xml>OK</xml>"
189         else:
190             self.send_error(404, "File not found")
191             return
192         self.send_response(200)
193         self.send_header("Content-type", "text/xml")
194         self.end_headers()
195         self.wfile.write(xml.encode("utf-8"))