/notes/updates.cgi

#!/usr/bin/env python
"""
updates - Show the most recent updates of .html files in a directory.
License: GPL 2; share and enjoy!
Author: Sean B. Palmer, inamidst.com
Derived from: http://infomesh.net/pwyky/pwyky.py.txt
"""

import cgitb; cgitb.enable()
import sys, os, re, time, glob
method = os.environ.get('REQUEST_METHOD')
r_title = re.compile(r'<title>([^<]+)</title>')
bufsize = 2048

def serve(status, body): 
   sys.stdout.write("Status: %s\r\n" % status)
   sys.stdout.write("Content-Type: text/html; charset=utf-8\r\n\r\n")
   sys.stdout.write(body)
   sys.exit()

def unescape(s): 
   s = s.replace('&lt;', '<')
   s = s.replace('&gt;', '>')
   s = s.replace('&amp;', '&')
   return s

def getTitle(fn): 
   # From http://inamidst.com/inside/misc which itself was: 
   # Modified from the version in bookmarks.cgi
   if not fn.endswith('.html'): 
      return None
   try: f = open(fn)
   except: return None
   else: 
      html = ''
      while 1: 
         s = f.read(bufsize)
         if not s: break
         html += s
         m = r_title.search(html)
         if m: 
            f.close()
            return m.group(1) # unescape(m.group(1))
   f.close()
   return None

def html(title, body): 
   serve(200, """
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>%s</title>
<link rel="stylesheet" type="text/css" href="/trove/pwyky.css" />
</head>
<body>
%s
</body>
</html>
""" % (title, body))

def updates(): 
   i = 100 # Number of results to show
   result = {}
   for fn in glob.glob('*.html'): 
      t = os.stat(fn).st_mtime
      lastmod = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(t))
      while result.has_key(lastmod): 
         lastmod += '_'
      result[lastmod] = fn[:-len('.html')]
   keys = result.keys()
   keys.sort()
   keys.reverse()
   keys = keys[:i]

   today = time.strftime('%Y-%m-%d', time.gmtime())
   s = '<h1>Updates: Recently Changed Pages</h1>\n'
   s += '<p>Today is <strong>%s</strong>. ' % today
   s += 'The %s most recent changes in this site are: </p>\n' % len(keys)
   s += '<ul>\n'
   for n in keys: 
      pdate, ptime = tuple(n.split(' '))
      ptime = ptime.rstrip('_')
      s += '<li><strong>%s</strong>: ' % pdate
      title = result[n]
      htitle = getTitle(result[n] + '.html')
      if htitle and (htitle != title): 
         title = htitle
      s += '<a href="./%s">%s</a> %s' % (result[n], title, ptime)
      length = len(open(result[n] + '.html').read())
      s += ' (size: %s bytes)</li>\n' % length
   s += '</ul>\n<p>Up to %s updates will be shown. ' % i
   s += 'Also: <a href="/inside/notes/updates">source</a>.</p>\n'
   s += '<address>\n'
   s += '<a href="http://inamidst.com/sbp/">Sean B. Palmer</a>\n'
   s += '</address>\n'
   return html('notes - Updates: Recent Changes', s)

def main(): 
   if method == "GET": updates()
   else: serve(501, '<p>Method must be GET.</p>\n')

if __name__=="__main__": 
   main()