#!/usr/bin/env python

# read index data out of a table and present it as a web page

import sys,os,md5
sys.path.append('/home/acb/null_include')
from stat import *
from Comments import Comments

DATASRC='INDEX.data'
FILE_DIR='/www/null.org/htdocs/audio/_files'
DL_CGI='/cgi-bin/servemp3'

CMT_DBNAME='null'
CMT_DBUSER='acb'
CMT_BASEURL="/cgi-bin/comment.cgi"
CMT_GROUP='mp3'

cmts = Comments(CMT_DBNAME, user=CMT_DBUSER, cmtbaseurl=CMT_BASEURL, group=CMT_GROUP)


# the data file consists of one-line Name:Value pairs, separated by blank lines
# Records consisting of a sole Heading: line are section headings.
# the # character begins a one-line comment

def readRecord(file,defaults={}):
  "Read a record and return as a dict, or None if none remaining"
  result = {}
  l = file.readline()
  # skip any initial blank lines
  while l=='\n': l = file.readline()
  if l=='': return None
  while len(l)>1:
    if l[0]=='#': 
      l = file.readline()
      continue
    (k,v) = map(lambda s:s.strip(),(l.split(':',1)+[None])[:2])
    if k:  result[k.lower()]=v

    l = file.readline()
    
  for k in defaults.keys(): 
    if not result.has_key(k):   result[k]=defaults[k]
  return result

def emitHeading(hdg):
  print "<H2>%s</H2>"%hdg

def filenametocmtitem(fname):
  "Map a filename to a probably-unique comment item ID"
  if len(fname)<22:
    return fname
  else:
    md=md5.new(fname)
    return fname[:18]+"%02x"%ord(md.digest()[0])+"%02x"%ord(md.digest()[1])

def emitRecord(dict):
  "Emit the HTML for a record"
  cmt_item, num_cmts = None,None
  if dict.has_key('file'):  
    print '<A NAME="%s">'%dict['file']
    cmt_item = filenametocmtitem(dict['file'])
    num_cmts = cmts.numComments(cmt_item)
  print """<DIV CLASS="item">
<P CLASS="itemtitle"><B>%(title)s</B>"""%dict,
  if dict.has_key('year'):
    print '(%s)'%dict['year']
  print '</P>'
  if dict.has_key('description'): 
    print '<P CLASS="blurb">%s</P>'%dict['description']
  if dict.has_key('reviews'):
    print '<P CLASS="review">%s</P>'%dict['reviews']
  if dict.has_key('credits'): 
    print '<P CLASS="blurb">%s</P>'%dict['credits']
  if dict.has_key('file'):
    fname = dict['file']
    try:
      stat = os.stat("%s/%s"%(FILE_DIR,fname))
      if stat[ST_SIZE]>=900*1024:
        fsize = "%.1fMb"%(stat[ST_SIZE]/1048576.0)
      else:
        fsize = "%dk"%(stat[ST_SIZE]/1024)
    except OSError:
      fname, fsize = None, None
  if fname:
    print '<A HREF="%s/%s" CLASS="download">[Download %s %s]</A>'%(DL_CGI,fname,fsize,dict['type'])
  if cmt_item:
    cmt_url = "%s?it=%s&mc=%s&gr=%s"%(CMT_BASEURL,cmt_item,cmts.mkmc(cmt_item),CMT_GROUP)
    if num_cmts == 0:
      print '<A HREF="%s" CLASS="comments">[no comments]</A>'%cmt_url
    elif num_cmts == 1:
      print '<A HREF="%s" CLASS="comments">[1 comment]</A>'%cmt_url
    else:
      try:
        print '<A HREF="%s" CLASS="comments">[%d comments]</A>'%(cmt_url,num_cmts)
      except TypeError:
        pass
  print "</DIV>"


print """Content-Type: text/html

<HTML><HEAD>
  <TITLE>The Null Device MP3 repository</TITLE>
  <link REL="StyleSheet" HREF="/audio/audio.css" TYPE="text/css" MEDIA="screen" />
  <link rel="StyleSheet" href="/css/popupmenu.css" type="text/css" media="screen" />
</HEAD>
<BODY>
  <script language="JavaScript1.2" src="/js/popupmenu.js"></script>
  <DIV ID="main">
  <H1>MP3 archive</H1>"""

defaults = {'type':'MP3'}

f = open(DATASRC,'r')
r = readRecord(f,defaults)
while r:
  if r.has_key('heading'):
    emitHeading(r['heading'])
  else:
    emitRecord(r)
  r = readRecord(f,defaults)
f.close()

print """
</DIV>
<P CLASS="fineprint">
&copy; acb 2003. If you can read this, the page has loaded.</P>
</BODY></HTML>"""
