#!/usr/bin/python import web import feedparser import urllib import hashlib import time import re import os.path import sys urls = ( '/', 'usage', '(.*)', 'test' ) app = web.application(urls, globals()) class usage: def GET(self): usage = ''' Hello, world! ''' return usage class test: def GET(self, path): path = path.strip("/").split("/") last = path[-1] if re.search("\.dat$", last): url = "/".join(path[:-3]) rss = self.get_rss(url) dat = self.search_dat(rss, last) return dat elif re.search("subject\.txt$", last): url = "/".join(path[:-2]) rss = self.get_rss(url) subject = self.conv_subject(rss) return subject else: index = "dat/\nsubject.txt\n" return index def get_rss(self, url): md5hash = hashlib.md5(url).hexdigest() + ".txt" try: if os.path.getmtime(md5hash)+60*10 > time.time(): f = open(md5hash) rss = f.read() f.close() else: rss = self.write_rss(url, md5hash) except OSError: rss = self.write_rss(url, md5hash) return feedparser.parse(rss) def write_rss(self, url, md5hash): rss = urllib.urlopen("http://" + url).read() f = open(md5hash, "wb") f.write(rss) f.close() return rss def tags_title(self, entry_tags): tags = [] for tag in entry_tags: tags.append(tag["term"]) tags = ",".join(tags) return tags def conv_subject(self, rss): subject_txt = [] res = "1" for entry in rss["entries"]: tags = self.tags_title(entry["tags"]) dat = int(time.mktime(entry["updated_parsed"])) title = entry["title"] subject = "%s.dat<>[%s] %s (%s)\n" % (dat, tags, title, res) subject_txt.append(subject) subject_txt = "".join(subject_txt) return self.utf8tosjis(subject_txt) def search_dat(self, rss, datfile): epoch = int(re.sub("\.dat$", "", datfile)) date = time.localtime(epoch) for entry in rss["entries"]: if date == entry["updated_parsed"]: return self.conv_dat(entry) return "not found." def conv_dat(self, entry): #name = entry[""] name = "Anonymous" #mail = entry[""] mail = "" date = time.strftime("%Y/%m/%d %H:%M:%S (%a)", entry["updated_parsed"]) if entry["content"]: body = self.untag(entry["content"][0]["value"]) else: body = entry["summary"] tags = self.tags_title(entry["tags"]) title = entry["title"] dat = "%s<>%s<>%s<>%s<>[%s] %s\n" % (name, mail, date, body, tags, title) return self.utf8tosjis(dat) def untag(self, html): u = re.compile("]*/*>") n = re.compile("\n") html = u.sub("", html) html = n.sub("
", html) return html def utf8tosjis(self, data): return unicode(data).encode("Shift_JIS", "replace") if __name__ == '__main__': app.run()