from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler import urllib import urllib2 import cgi import json running = True try: pfile = open('dobroprefs.json', 'r') pdata = pfile.read() pfile.close() threads, timeout, headers = json.loads(pdata) except: threads = {} timeout = 60 headers = {'User-Agent': 'Mozilla/5.0'} modified = {} def check(tid): global headers request = urllib2.Request('http://dobrochan.com/api/thread/%s.json' % tid) request.add_header('Host', 'dobrochan.com') for k, v in headers.items(): request.add_header(k, v) opener = urllib2.build_opener() try: resource = opener.open(request) data = resource.read() resource.close() info = json.loads(data) return info except (urllib2.HTTPError, ValueError): return None def threadlink(tid): global threads, modified info = check(tid) if info == None: return None try: link = u'>>%s X - %s - %s' % (urllib.quote(tid), tid, urllib.quote(tid), info['title'], info['last_modified']) if info['last_modified'] != threads[tid]: modified[tid] = info['last_modified'] return '' + link + '' else: return link except KeyError: return None def threadlinks(): links = '' for k in threads.keys(): link = threadlink(k) if link != None: links += link + '
' return links def listing(): global modified page = '
' + \ threadlinks() + \ '
Shut down' if len(modified) != 0: return '[%d] updates%s' % (len(modified), page) else: return '___%s' % (page) def save(): global threads, timeout, headers pfile = open('dobroprefs.json', 'w') pfile.write(json.dumps((threads, timeout, headers))) pfile.close() class dobroserver(BaseHTTPRequestHandler): def do_GET(self): global running, threads, timeout, headers, modified path, query = urllib.splitquery(self.path) if query == None: query = '' query = cgi.parse_qs(query) if path == '/shutdown': save() running = False if path == '/add': try: tid = urllib.unquote(query['tid'][0]) info = check(tid) if info and tid not in threads: threads[tid] = info['last_modified'] save() except KeyError: pass if path == '/del': try: tid = urllib.unquote(query['tid'][0]) del threads[tid] save() except KeyError: pass self.send_response(200) self.send_header("Content-type", "text/html") if path == '/go': try: tid = urllib.unquote(query['tid'][0]) self.send_header("Refresh", "0;url=http://dobrochan.com/%s.xhtml" % (tid.replace('/', '/res/'))) if modified.has_key(tid): threads[tid] = modified[tid] del modified[tid] save() except KeyError: print 'Err' self.send_header("Refresh", str(timeout) + ";url=/") else: self.send_header("Refresh", str(timeout) + ";url=/") self.end_headers() if path in ['/', '/del', '/add']: self.wfile.write(listing().encode('cp1251')) httpd = HTTPServer(('127.0.0.1', 8000), dobroserver) while running: httpd.handle_request()