#!/usr/bin/python
"""
nserve.py
Sean B. Palmer, , 2003-06
GPL 2. Share and Enjoy!
"""
import sys, os, re, SimpleHTTPServer, BaseHTTPServer, urllib
try: notes = open('notes.text').read().splitlines()
except IOError: notes = []
# notes = notes * 10
def quote(s):
return s.replace('<', '<')
r_uri = re.compile('http:[^ "<>]*')
def getURIs():
uris = []
for line in notes:
uris += r_uri.findall(line)
result = '
\n'
for uri in uris:
result += '- %s
\n' % (uri, uri)
result += '
'
return result
def getNote(i):
previous = 'previous' % (i-1)
next = 'next' % (i+1)
return quote(notes[i]) + ('%s %s
' % (previous, next))
def getWord(w):
result = ''
for i in range(len(notes)):
if notes[i].count(w):
result += 'note %s: %s
' % (i, quote(notes[i]))
return result
def buildSummary(i):
result = []
length = 50
short = notes[i][:length]
words = short.split(' ')
if (words[-1:] != ['']) and (len(notes[i]) > length):
if len(words) > 1: words = words[:-1]
for word in words:
count = 0
for j in range(len(notes)):
if notes[j].count(word): count += 1
if count > 1:
attr, val = word.replace('"', '"'), quote(word)
colour = 'style="color: black;"'
result += ['%s' % (attr, colour, val)]
else: result += [quote(word)]
if len(notes[i]) > length:
result += ['...']
return ' '.join(result)
def getNotes():
result = '\n'
indexes = range(len(notes))
indexes.reverse()
for i in indexes[:100]:
summary = buildSummary(i)
tstamp = notes[i][-17:]
if tstamp.startswith('(') and tstamp.endswith(')'):
year, month, day = tstamp[1:5], tstamp[5:7], tstamp[7:9]
name = '-'.join((year, month, day)) + ', #' + str(i)
else: name = '#' + str(i)
link = '%s' % (i, name)
result += '- %s: %s
\n' % (link, summary)
result += '
'
return result
class HTTPServer(SimpleHTTPServer.SimpleHTTPRequestHandler):
server_version = "nserve/1.0"
def do_GET(self, post=None):
path = self.path[1:]
if path.isdigit():
self.ok({"Content-type": "text/html"}, getNote(int(path)))
elif path.startswith('?'):
self.ok({"Content-type": "text/html"},
{'URIs': getURIs}.get(path[1:], lambda: 'No such function')())
elif path: self.ok({"Content-type": "text/html"}, getWord(path))
else: self.ok({"Content-type": "text/html"}, getNotes())
def do_POST(self):
fmime = 'application/x-www-form-urlencoded'
if self.headers['content-type'] == fmime:
self.ok({"Content-type": "text/plain"}, "Invalid data")
else: self.ok({"Content-type": "text/plain"}, "Invalid form data")
def ok(self, headers, data):
self.send_response(200)
if headers.has_key('Content-Type'):
if headers['Content-type'] == 'text/html':
headers['Content-type'] = 'text/html; charset=utf-8'
headers['content-length'] = '%s' % len(data)
for header in headers.keys():
self.send_header(header, headers[header])
self.end_headers()
self.wfile.write(data)
def main():
if '-web' in sys.argv[1:]: ip, port = urllib.thishost(), 7000
else: ip, port = '127.0.0.1', 7000
if len(sys.argv[1:]) > 0:
port = int(sys.argv[1])
if len(sys.argv[1:]) > 1:
ip = sys.argv[2]
httpd = BaseHTTPServer.HTTPServer((ip, port), HTTPServer)
print >> sys.stderr, "Serving on %s:%s" % httpd.socket.getsockname()
httpd.serve_forever()
if __name__=="__main__":
main()