#!/usr/bin/python
#
# Copyright (C) 2006, Stefano Zacchiroli <zack@bononia.it>
#
# Created:       Tue, 12 Dec 2006 13:38:00 +0100 zack
# Last-Modified: Tue, 12 Dec 2006 14:24:41 +0100 zack
#
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.

import anydbm
import datetime
import os
import PyRSS2Gen as RSS2
import syck
import sys

def dsc_of_fname(fname):
    # TODO to be extended with filetype aware features that extract metadata
    # from a given file (e.g. id3 for mp3 files)
    return fname

def is_ignorable(fname):
    try:
        return (fname[0] == '.')
    except IndexError:
        return False

def update_db(db, dir, recursive):
    for root, dirs, files in os.walk(dir):
        if not recursive:
            dirs = []
        for f in files:
            if not is_ignorable(f):
                fname = os.path.join(root, f)
                db[fname] = str(os.stat(fname).st_mtime)

    # side effect: modifies db
def db2rss(db, dirname, size):
    rss = RSS2.RSS2(title = dirname,
            link = 'file://' + dirname,
            description = 'directory content for ' + dirname,
            lastBuildDate = datetime.datetime.now())
    fnames = db.keys()  # now sort: most recent first
    fnames.sort(lambda f1, f2: cmp(int(db[f2]), int(db[f1])))
    for f in fnames[size:]: # expunge old items exceeding size
        del(db[f])
    for f in fnames[:size]: # add a 'size' amount of most recent items
        rss.items.append(RSS2.RSSItem(title = f,
            link = 'file://' + f,
            description = dsc_of_fname(f),
            guid = f,
            pubDate = datetime.datetime.fromtimestamp(int(db[f]))))
    return rss

def update_rss(options):
        # db with pairs <file name, modification time>
        # modification time is in seconds from epoch
    db = anydbm.open(options['db_fname'], 'c')
    update_db(db, options['source_dir'], options['recursive'])
    rss = db2rss(db, options['source_dir'], options['feed_size'])
    db.close()
    rss.write_xml(open(options['rss_fname'], 'w'))

if __name__ == '__main__':
    conf = syck.load(file(sys.argv[1]).read())
    options = conf['options']
    update_rss(options)

