reorganize files to move lib, templates, www into 'degal' package, keep separate 'cgi-bin' for now use-distutils
authorTero Marttila <terom@fixme.fi>
Wed, 03 Jun 2009 19:03:28 +0300
branchuse-distutils
changeset 41 3b1579a7bffb
parent 40 373392025533
child 42 146997912efb
reorganize files to move lib, templates, www into 'degal' package, keep separate 'cgi-bin' for now
cgi-bin/inc.py
cgi-bin/series.py
cgi-bin/shorturl.py
db/db.sql
de-cgi-bin/inc.py
de-cgi-bin/series.py
de-cgi-bin/shorturl.py
degal/__init__.py
degal/db.py
degal/dexif.py
degal/folder.py
degal/formatbytes.py
degal/helpers.py
degal/image.py
degal/log.py
degal/req.py
degal/settings.py
degal/shorturl.py
degal/static/style.css
degal/template.py
degal/templates/gallery.html
degal/templates/image.html
degal/templates/master.html
degal/utils.py
docs/db.sql
lib/__init__.py
lib/db.py
lib/dexif.py
lib/folder.py
lib/formatbytes.py
lib/helpers.py
lib/image.py
lib/log.py
lib/req.py
lib/settings.py
lib/shorturl.py
lib/template.py
lib/utils.py
templates/gallery.html
templates/image.html
templates/master.html
www/style.css
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cgi-bin/inc.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,27 @@
+# config
+
+# location of DeGAL itself
+
+DEGAL_PATH = "/mnt/photos/public"
+
+
+
+if __name__ == '__main__' :
+    raise Exception("Don't access inc.py directly")
+
+# setup env
+
+import sys
+import os, os.path
+
+#def splitn (path, n) :
+#    for i in xrange(0, n) :
+#        path = os.path.split(path)[0]      
+#    
+#    return path
+#        
+#degal_path = splitn(os.path.join(os.getcwd(), __file__), 2)
+
+os.chdir(DEGAL_PATH)
+sys.path.append(DEGAL_PATH)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cgi-bin/series.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,211 @@
+#!/usr/bin/env python2.4
+#
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+
+import os
+import cgi
+import Cookie
+
+import inc
+from lib import shorturl, template, utils, settings
+
+#
+# load request params
+#
+vars = cgi.FieldStorage()
+
+# these are interpeted different ways, hence the generic naming
+arg1 = vars["keys"].value
+if 'index' in vars :
+    arg2 = vars["index"].value
+else :
+    arg2 = None
+
+# the cookie with the user's current series
+cookie = Cookie.SimpleCookie(os.environ.get('HTTP_COOKIE', None))
+
+# a special action?
+if arg1 and arg1 in ('add', 'del', 'clear', 'view') or arg2 == 'load' :
+    # load the keys from the cookie
+    if 'series' in cookie :
+        keys = cookie["series"].value.split()
+    else :
+        keys = []
+    
+    if arg2 == 'load' :
+        # set the keys in the user's cookie to those in the URL
+        keys = arg1.split()
+
+    elif arg1 == 'add' and arg2 not in keys :
+        # add a code to the list of keys
+        keys.append(arg2)
+
+    elif arg1 == 'del' and arg2 in keys :
+        # remove a key from the list of keys
+        keys.remove(arg2)
+
+    elif arg1 == 'clear' :
+        # clear out the set of keys
+        keys = []
+
+    elif arg1 == 'view' :
+        # just view them
+        pass
+   
+    # set the series cookie value
+    cookie['series'] = ' '.join(keys)
+    cookie['series']['path'] = '/'
+    
+    # if we have keys, redirect to them, otherwise, back to index we go
+    if keys :
+        redirect_to = "../%s/" % ('+'.join(keys))
+    else :
+        redirect_to = "../.."
+    
+    # do the redirect
+    print "Status: 302"
+    print "Location: %s" % redirect_to
+    print cookie
+    print
+    print "Redirect..."
+else :
+    # we're just viewing
+    keys = arg1.split()
+    
+    # is this "My Series"?
+    my_series = 'series' in cookie and cookie['series'].value.split() == keys
+    
+    index = fname = None
+
+    if arg2 :
+        try :
+            index = int(arg2)
+        except ValueError :
+            fname = arg2
+
+    # our custom Series/Image classes, because they do act slightly differently
+
+    class Series (object) :
+        def __init__ (self, keys) :
+            self.images = []
+            prev = None
+
+            self.image_dict = dict()
+
+            images = shorturl.get_images(keys)
+
+            for index, (key, (dir, fname)) in enumerate(zip(keys, images)) :
+                img = Image(self, key, dir, fname, index)
+                self.images.append(img)
+                self.image_dict[fname] = img
+
+                img.prev = prev
+
+                if prev :
+                    prev.next = img
+
+                prev = img
+
+        def render (self) :
+            if my_series :
+                descr = '<a href="../clear/" rel="nofollow">Clear your series</a>'
+            else :
+                descr = '<a href="load" rel="nofollow">Load as your series</a>'
+   
+            return template.gallery.render(
+                stylesheet_url      = utils.url("style.css", up=2),
+                
+                breadcrumb          = [(utils.url(up=1), "Index"), (utils.url(), "Series")],
+
+                dirs                = None,
+                title               = "Series",
+
+                num_pages           = 1,
+                cur_page            = 0,
+
+                images              = self.images,
+
+                description         = descr,
+
+                shorturl            = None,
+                shorturl_code       = None,
+            )
+    
+    class Image (object) :
+        def __init__ (self, series, key, dir, fname, index) :
+            self.fname = fname
+            self.name = utils.url_join(dir, fname, abs=True)
+            self.html_name = utils.url(fname)
+            self.real_html_name = utils.url_join(dir, fname + ".html", abs=True)
+
+            self.thumb_name = utils.url_join(dir, settings.THUMB_DIR, fname, abs=True)
+            self.preview_name = utils.url_join(dir, settings.PREVIEW_DIR, fname, abs=True)
+
+            self.shorturl = key
+
+            self.prev = self.next = None
+
+        def render (self) :
+            descr = '<span style="font-size: x-small"><a href="%s.html">Standalone image</a></span>' % self.real_html_name
+            
+            if my_series :
+                series_url = utils.url_join("del", self.shorturl, up=1)
+                series_verb = "Remove from"
+            else :
+                series_url = series_verb = ""
+
+            return template.image.render(
+                stylesheet_url      = utils.url("style.css", up=3),
+                
+                breadcrumb          = [(utils.url(up=2), "Index"), (utils.url("."), "Series"), (self.html_name, self.fname)],
+
+                title               = self.fname,
+
+                prev                = self.prev,
+                img                 = self,
+                next                = self.next,
+                
+                description         = descr,
+    
+                img_size            = None,
+                file_size           = None,
+                timestamp           = None,
+                
+                shorturl            = utils.url_join("s", self.shorturl, abs=True),
+                shorturl_code       = self.shorturl,
+                
+                series_url          = series_url,
+                series_verb         = series_verb,
+            )
+    
+    series = Series(keys)
+
+    if fname :
+        html = series.image_dict[fname].render()
+    elif index :
+        html = series.images[index - 1].render()
+    else :
+        html = series.render()
+
+    print "Content-Type: text/html"
+    print
+    print html
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cgi-bin/shorturl.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,41 @@
+#!/usr/bin/env python2.5
+#
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+
+import inc
+from lib import shorturl, req
+
+key = req.get_str('key')
+index = req.get_int('index', None)
+
+path = shorturl.html_path(key)
+
+if path :
+    print "Status: 302"
+    print "Location: ../%s" % path
+    print
+    print "../%s" % path
+
+else :
+    print "Status: 404"
+    print
+    print "404"
+
--- a/db/db.sql	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,5 +0,0 @@
-CREATE TABLE 'nodes' (id INTEGER NOT NULL PRIMARY KEY, dirpath TEXT NOT NULL, filename TEXT NOT NULL);
-CREATE TABLE tags (image INTEGER NOT NULL, type TEXT, tag TEXT NOT NULL);
-CREATE VIEW images AS SELECT id, dirpath, filename FROM nodes WHERE filename != '';
-CREATE UNIQUE INDEX tags_unique_image_type ON tags (image, type);
-CREATE UNIQUE INDEX tags_unique_image_type_tag ON tags (image, type, tag);
--- a/de-cgi-bin/inc.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-# config
-
-# location of DeGAL itself
-
-DEGAL_PATH = "/mnt/photos/public"
-
-
-
-if __name__ == '__main__' :
-    raise Exception("Don't access inc.py directly")
-
-# setup env
-
-import sys
-import os, os.path
-
-#def splitn (path, n) :
-#    for i in xrange(0, n) :
-#        path = os.path.split(path)[0]      
-#    
-#    return path
-#        
-#degal_path = splitn(os.path.join(os.getcwd(), __file__), 2)
-
-os.chdir(DEGAL_PATH)
-sys.path.append(DEGAL_PATH)
-
--- a/de-cgi-bin/series.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,211 +0,0 @@
-#!/usr/bin/env python2.4
-#
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-
-import os
-import cgi
-import Cookie
-
-import inc
-from lib import shorturl, template, utils, settings
-
-#
-# load request params
-#
-vars = cgi.FieldStorage()
-
-# these are interpeted different ways, hence the generic naming
-arg1 = vars["keys"].value
-if 'index' in vars :
-    arg2 = vars["index"].value
-else :
-    arg2 = None
-
-# the cookie with the user's current series
-cookie = Cookie.SimpleCookie(os.environ.get('HTTP_COOKIE', None))
-
-# a special action?
-if arg1 and arg1 in ('add', 'del', 'clear', 'view') or arg2 == 'load' :
-    # load the keys from the cookie
-    if 'series' in cookie :
-        keys = cookie["series"].value.split()
-    else :
-        keys = []
-    
-    if arg2 == 'load' :
-        # set the keys in the user's cookie to those in the URL
-        keys = arg1.split()
-
-    elif arg1 == 'add' and arg2 not in keys :
-        # add a code to the list of keys
-        keys.append(arg2)
-
-    elif arg1 == 'del' and arg2 in keys :
-        # remove a key from the list of keys
-        keys.remove(arg2)
-
-    elif arg1 == 'clear' :
-        # clear out the set of keys
-        keys = []
-
-    elif arg1 == 'view' :
-        # just view them
-        pass
-   
-    # set the series cookie value
-    cookie['series'] = ' '.join(keys)
-    cookie['series']['path'] = '/'
-    
-    # if we have keys, redirect to them, otherwise, back to index we go
-    if keys :
-        redirect_to = "../%s/" % ('+'.join(keys))
-    else :
-        redirect_to = "../.."
-    
-    # do the redirect
-    print "Status: 302"
-    print "Location: %s" % redirect_to
-    print cookie
-    print
-    print "Redirect..."
-else :
-    # we're just viewing
-    keys = arg1.split()
-    
-    # is this "My Series"?
-    my_series = 'series' in cookie and cookie['series'].value.split() == keys
-    
-    index = fname = None
-
-    if arg2 :
-        try :
-            index = int(arg2)
-        except ValueError :
-            fname = arg2
-
-    # our custom Series/Image classes, because they do act slightly differently
-
-    class Series (object) :
-        def __init__ (self, keys) :
-            self.images = []
-            prev = None
-
-            self.image_dict = dict()
-
-            images = shorturl.get_images(keys)
-
-            for index, (key, (dir, fname)) in enumerate(zip(keys, images)) :
-                img = Image(self, key, dir, fname, index)
-                self.images.append(img)
-                self.image_dict[fname] = img
-
-                img.prev = prev
-
-                if prev :
-                    prev.next = img
-
-                prev = img
-
-        def render (self) :
-            if my_series :
-                descr = '<a href="../clear/" rel="nofollow">Clear your series</a>'
-            else :
-                descr = '<a href="load" rel="nofollow">Load as your series</a>'
-   
-            return template.gallery.render(
-                stylesheet_url      = utils.url("style.css", up=2),
-                
-                breadcrumb          = [(utils.url(up=1), "Index"), (utils.url(), "Series")],
-
-                dirs                = None,
-                title               = "Series",
-
-                num_pages           = 1,
-                cur_page            = 0,
-
-                images              = self.images,
-
-                description         = descr,
-
-                shorturl            = None,
-                shorturl_code       = None,
-            )
-    
-    class Image (object) :
-        def __init__ (self, series, key, dir, fname, index) :
-            self.fname = fname
-            self.name = utils.url_join(dir, fname, abs=True)
-            self.html_name = utils.url(fname)
-            self.real_html_name = utils.url_join(dir, fname + ".html", abs=True)
-
-            self.thumb_name = utils.url_join(dir, settings.THUMB_DIR, fname, abs=True)
-            self.preview_name = utils.url_join(dir, settings.PREVIEW_DIR, fname, abs=True)
-
-            self.shorturl = key
-
-            self.prev = self.next = None
-
-        def render (self) :
-            descr = '<span style="font-size: x-small"><a href="%s.html">Standalone image</a></span>' % self.real_html_name
-            
-            if my_series :
-                series_url = utils.url_join("del", self.shorturl, up=1)
-                series_verb = "Remove from"
-            else :
-                series_url = series_verb = ""
-
-            return template.image.render(
-                stylesheet_url      = utils.url("style.css", up=3),
-                
-                breadcrumb          = [(utils.url(up=2), "Index"), (utils.url("."), "Series"), (self.html_name, self.fname)],
-
-                title               = self.fname,
-
-                prev                = self.prev,
-                img                 = self,
-                next                = self.next,
-                
-                description         = descr,
-    
-                img_size            = None,
-                file_size           = None,
-                timestamp           = None,
-                
-                shorturl            = utils.url_join("s", self.shorturl, abs=True),
-                shorturl_code       = self.shorturl,
-                
-                series_url          = series_url,
-                series_verb         = series_verb,
-            )
-    
-    series = Series(keys)
-
-    if fname :
-        html = series.image_dict[fname].render()
-    elif index :
-        html = series.images[index - 1].render()
-    else :
-        html = series.render()
-
-    print "Content-Type: text/html"
-    print
-    print html
-
--- a/de-cgi-bin/shorturl.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-#!/usr/bin/env python2.5
-#
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-
-import inc
-from lib import shorturl, req
-
-key = req.get_str('key')
-index = req.get_int('index', None)
-
-path = shorturl.html_path(key)
-
-if path :
-    print "Status: 302"
-    print "Location: ../%s" % path
-    print
-    print "../%s" % path
-
-else :
-    print "Status: 404"
-    print
-    print "404"
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/db.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,78 @@
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+
+import sqlite3
+
+conn = sqlite3.connect("db/degal.db")
+
+def execute (expr, *args) :
+    c = conn.cursor()
+    c.execute(expr, args)
+
+    return c
+
+def execute_many (expr, iter) :
+    c = conn.cursor()
+    c.executemany(expr, iter)
+
+    return c
+
+def insert (expr, *args) :
+    return execute_commit(expr, *args).lastrowid
+
+def insert_many (cb, expr, iter) :
+    """
+        Perform an executemany with the given iterator (which must yield (cb_val, args) tuples), calling the given callback with the args (cb_val, row_id)
+    """
+
+    c = conn.cursor()
+
+    c.executemany(expr, _lastrowid_adapter(c, iter, cb))
+
+    return commit(c)
+
+def _lastrowid_adapter (c, iter, cb) :
+    for val, args in iter :
+        yield args
+
+        cb(val, c.lastrowid)
+
+def commit (cursor) :
+    try :
+        cursor.execute("COMMIT")
+    except sqlite3.OperationalError :
+        pass    # ffs. INSERT just doesn't do anything otherwise
+
+    return cursor
+
+def execute_commit (expr, *args) :
+    return commit(execute(expr, *args))
+
+def execute_commit_many (expr, iter) :
+    return commit(execute_many(expr, iter))
+
+select = execute
+
+delete = execute_commit
+
+delete_many = execute_commit_many
+
+cursor = conn.cursor
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/dexif.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,63 @@
+#
+# dexif.py - simple EXIF processing for Degal
+# Copyright (C) 2008, Santtu Pajukanta <santtu@pajukanta.fi>
+#
+# 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.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+
+from subprocess import Popen, PIPE
+
+# TODO This should be user configurable
+EXIFTOOL="/usr/bin/exiftool"
+
+outputTags = [
+# TODO Create date is in a useless format, needs some strptime love
+    ("CreateDate", "Create date"),
+    ("Model", "Camera model"),
+    ("Aperture", "Aperture"),
+    ("ExposureMode", "Exposure mode"),
+    ("ExposureCompensation", "Exposure compensation"),
+    ("ExposureTime", "Exposure time"),
+    ("Flash", "Flash mode"),
+    ("ISO", "ISO"),
+    ("ShootingMode", "Shooting mode"),
+    ("LensType", "Lens type"),
+    ("FocalLength", "Focal length")
+]
+
+
+class ExifError(Exception):
+    pass
+
+def parse_exif(filepath):
+    """parse_exif(filepath :: String) -> [(String, String)]
+
+    Parse EXIF tags from an image file and return them in a dict.
+    """
+
+    args = [EXIFTOOL, "-s", "-t", filepath]
+    etproc = Popen(args, stdout = PIPE)
+
+    output, errors = etproc.communicate()
+    
+    if etproc.returncode < 0:
+        raise ExifError, "exiftool terminated by signal %d" % (-etproc.returnco)
+    elif etproc.returncode > 0:
+        raise ExifError, "exiftool failed with return code %d" % etproc.returncode
+    
+    tags = dict(line.split("\t", 1) for line in output.split("\n") if line)
+    result = [(descr, tags[key]) for (key, descr) in outputTags if tags.has_key(key)]
+    return result
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/folder.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,329 @@
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+
+import os, os.path
+
+import settings, image, utils, helpers, log
+from template import gallery as gallery_tpl
+from helpers import url_for_page
+
+def dirUp (count=1) :
+    """
+        Returns a relative path to the directly count levels above the current one
+    """
+
+    if not count :
+        return '.'
+
+    return os.path.join(*(['..']*count))
+    
+class Folder (object) :
+    def __init__ (self, name='.', parent=None) :
+        # the directory name, no trailing /
+        self.name = unicode(name.rstrip(os.sep))
+
+        # our parent Folder, or None
+        self.parent = parent
+
+        # the path to this dir, as a relative path to the root of the image gallery, always starts with .
+        if parent and name :
+            self.path = parent.pathFor(self.name)
+        else :
+            self.path = self.name
+
+        # the url-path to the index.html file
+        self.html_path = self.path
+        
+        # dict of fname -> Folder
+        self.subdirs = {}
+
+        # dict of fname -> Image
+        self.images = {}
+        
+        # our human-friendly title
+        self.title = None
+
+        # our long-winded description
+        self.descr = ''
+
+        # is this folder non-empty?
+        self.alive = None
+        
+        # self.images.values(), but sorted by filename
+        self.sorted_images = []
+        
+        # the ShortURL key to this dir
+        self.shorturl_code = None
+
+        # were we filtered out?
+        self.filtered = False
+   
+    def pathFor (self, *fnames) :
+        """
+            Return a root-relative path to the given path inside this dir
+        """
+        return os.path.join(self.path, *fnames)
+
+    def index (self, filters=None) :
+        """
+            Look for other dirs and images inside this dir. Filters must be either None,
+            whereupon all files will be included, or a dict of {filename -> next_filter}.
+            If given, only filenames that are present in the dict will be indexed, and in
+            the case of dirs, the next_filter will be passed on to that Folder's index
+            method.
+        """
+
+        if filters :
+            self.filtered = True
+        
+        # iterate through listdir
+        for fname in os.listdir(self.path) :
+            # the full filesystem path to it
+            fpath = self.pathFor(fname)
+            
+            # ignore dotfiles
+            if fname.startswith('.') :
+                log.debug("Skipping dotfile %s", fname)
+                continue
+            
+            # apply filters
+            if filters :
+                if fname in filters :
+                    next_filter = filters[fname]
+                else :
+                    log.debug("Skip `%s' as we have a filter", fname)
+                    continue
+            else :
+                next_filter = None
+                
+            # recurse into subdirs, but not thumbs/previews
+            if (os.path.isdir(fpath) 
+                and (fname not in (settings.THUMB_DIR, settings.PREVIEW_DIR))
+                and (self.parent or fname not in settings.ROOT_IGNORE)
+            ) :
+                log.down(fname)
+
+                f = Folder(fname, self)
+                
+                try :
+                    if f.index(next_filter) :   # recursion
+                        # if a subdir is alive, we are alive as well
+                        self.subdirs[fname] = f
+                        self.alive = True
+                except Exception, e :
+                    log.warning("skip - %s: %s" % (type(e), e))
+
+                log.up()
+
+            # handle images
+            elif os.path.isfile(fpath) and utils.isImage(fname) :
+                log.next(fname)
+                self.images[fname] = image.Image(self, fname)
+
+            # ignore everything else
+            else :
+                log.debug("Ignoring file %s", fname)
+        
+        # sort and link the images
+        if self.images :
+            self.alive = True
+
+            # sort the images
+            fnames = self.images.keys()
+            fnames.sort()
+
+            prev = None
+
+            # link
+            for fname in fnames :
+                img = self.images[fname]
+
+                img.prev = prev
+
+                if prev :
+                    prev.next = img
+
+                prev = img
+                
+                # add to the sorted images list
+                self.sorted_images.append(img)
+                
+        # figure out our title/ descr. Must be done before our parent dir is rendered (self.title)
+        title_path = self.pathFor(settings.TITLE_FILE)
+        
+        self.title, self.descr = utils.readTitleDescr(title_path)
+        
+        # default title for the root dir
+        if self.title or self.descr :
+            self.alive = True
+            pass # use what was in the title file
+            
+        elif not self.parent :
+            self.title = 'Index'
+
+        else :
+            self.title = self.name
+        
+        if not self.alive :
+            log.debug("Dir %s isn't alive" % self.path)
+
+        return self.alive
+
+    def getObjInfo (self) :
+        """
+            Metadata for shorturls2.db
+        """
+        return 'dir', self.path, ''
+
+    def breadcrumb (self, forImg=None) :
+        """
+            Returns a [(fname, title)] list of this dir's parent dirs
+        """
+
+        f = self
+        b = []
+        d = 0
+        
+        while f :
+            # functionality of the slightly-hacked-in variety
+            if f is self and forImg is not None :
+                url = helpers.url_for_page(self.getPageNumber(forImg))
+            else :
+                url = dirUp(d)
+                
+            b.insert(0, (url, f.title))
+
+            d += 1
+            f = f.parent
+        
+        return b
+        
+    def getPageNumber (self, img) :
+        """
+            Get the page number that the given image is on
+        """
+        
+        return self.sorted_images.index(img) // settings.IMAGE_COUNT
+
+    def countParents (self, acc=0) :
+        if self.parent :
+            return self.parent.countParents(acc+1)
+        else :
+            return acc
+    
+    def inRoot (self, *fnames) :
+        """
+            Return a relative URL from this dir to the given path in the root dir
+        """
+
+        c = self.countParents()
+
+        return utils.url_join(*((['..']*c) + list(fnames)))
+
+    def render (self) :
+        """
+            Render the index.html, Images, and recurse into subdirs
+        """
+        
+        # ded folders are skipped
+        if not self.alive :
+            # dead, skip, no output
+            return
+        
+        index_mtime = utils.mtime(self.pathFor("index.html"))
+        dir_mtime = utils.mtime(self.path)
+
+        # if this dir's contents were filtered out, then we can't render the index.html, as we aren't aware of all the images in here
+        if self.filtered :
+            log.warning("Dir `%s' contents were filtered, so we won't render the gallery index again", self.path)
+
+        elif index_mtime > dir_mtime :
+            # no changes, pass, ignored
+            pass
+
+        else :  
+            # create the thumb/preview dirs if needed
+            for dir in (settings.THUMB_DIR, settings.PREVIEW_DIR) :
+                path = self.pathFor(dir)
+
+                if not os.path.isdir(path) :
+                    log.info("mkdir %s", dir)
+                    os.mkdir(path)
+
+            # sort the subdirs
+            subdirs = self.subdirs.values()
+            subdirs.sort(key=lambda d: d.name)
+            
+            # paginate!
+            images = self.sorted_images
+            image_count = len(images)
+            pages = []
+            
+            while images :
+                pages.append(images[:settings.IMAGE_COUNT])
+                images = images[settings.IMAGE_COUNT:]
+
+            pagination_required = len(pages) > 1
+
+            if pagination_required :
+                log.info("%d pages @ %d images", len(pages), settings.IMAGE_COUNT)
+            elif not pages :
+                log.info("no images, render for subdirs")
+                pages = [[]]
+
+            for cur_page, images in enumerate(pages) :
+                if pagination_required and cur_page > 0 :
+                    shorturl = "%s/%s" % (self.shorturl_code, cur_page+1)
+                else :
+                    shorturl = self.shorturl_code
+                
+                # render to index.html
+                gallery_tpl.render_to(self.pathFor(url_for_page(cur_page)), 
+                    stylesheet_url               = self.inRoot('style.css'),
+                    title                        = self.title,
+                    breadcrumb                   = self.breadcrumb(),
+                    
+                    dirs                         = subdirs,
+                    images                       = images,
+                    
+                    num_pages                    = len(pages),
+                    cur_page                     = cur_page,
+                    
+                    description                  = self.descr,
+                    
+                    shorturl                     = self.inRoot('s', shorturl),
+                    shorturl_code                = shorturl,
+                )
+
+        # render images
+        image_count = len(self.sorted_images)
+        for i, img in enumerate(self.images.itervalues()) :
+            log.next("[%-4d/%4d] %s", i + 1, image_count, img.name)
+
+            img.render()
+        
+        # recurse into subdirs
+        for dir in self.subdirs.itervalues() :
+            log.down(dir.name)
+
+            dir.render()
+
+            log.up()
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/formatbytes.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,116 @@
+###############################################################
+# Functions taken from pathutils.py Version 0.2.5 (2005/12/06), http://www.voidspace.org.uk/python/recipebook.shtml#utils
+# Copyright Michael Foord 2004
+# Released subject to the BSD License
+# Please see http://www.voidspace.org.uk/python/license.shtml
+
+###############################################################
+# formatbytes takes a filesize (as returned by os.getsize() )
+# and formats it for display in one of two ways !!
+
+# For information about bugfixes, updates and support, please join the Pythonutils mailing list.
+# http://groups.google.com/group/pythonutils/
+# Comments, suggestions and bug reports welcome.
+# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
+# E-mail fuzzyman@voidspace.org.uk
+
+def formatbytes(sizeint, configdict=None, **configs):
+    """
+    Given a file size as an integer, return a nicely formatted string that
+    represents the size. Has various options to control it's output.
+    
+    You can pass in a dictionary of arguments or keyword arguments. Keyword
+    arguments override the dictionary and there are sensible defaults for options
+    you don't set.
+    
+    Options and defaults are as follows :
+    
+    *    ``forcekb = False`` -         If set this forces the output to be in terms
+    of kilobytes and bytes only.
+    
+    *    ``largestonly = True`` -    If set, instead of outputting 
+        ``1 Mbytes, 307 Kbytes, 478 bytes`` it outputs using only the largest 
+        denominator - e.g. ``1.3 Mbytes`` or ``17.2 Kbytes``
+    
+    *    ``kiloname = 'Kbytes'`` -    The string to use for kilobytes
+    
+    *    ``meganame = 'Mbytes'`` - The string to use for Megabytes
+    
+    *    ``bytename = 'bytes'`` -     The string to use for bytes
+    
+    *    ``nospace = True`` -        If set it outputs ``1Mbytes, 307Kbytes``, 
+        notice there is no space.
+    
+    Example outputs : ::
+    
+        19Mbytes, 75Kbytes, 255bytes
+        2Kbytes, 0bytes
+        23.8Mbytes
+    
+    .. note::
+    
+        It currently uses the plural form even for singular.
+    """
+    defaultconfigs = {  'forcekb' : False,
+                        'largestonly' : True,
+                        'kiloname' : 'Kbytes',
+                        'meganame' : 'Mbytes',
+                        'bytename' : 'bytes',
+                        'nospace' : True}
+    if configdict is None:
+        configdict = {}
+    for entry in configs:
+        # keyword parameters override the dictionary passed in
+        configdict[entry] = configs[entry]
+    #
+    for keyword in defaultconfigs:
+        if not configdict.has_key(keyword):
+            configdict[keyword] = defaultconfigs[keyword]
+    #
+    if configdict['nospace']:
+        space = ''
+    else:
+        space = ' '
+    #
+    mb, kb, rb = bytedivider(sizeint)
+    if configdict['largestonly']:
+        if mb and not configdict['forcekb']:
+            return stringround(mb, kb)+ space + configdict['meganame']
+        elif kb or configdict['forcekb']:
+            if mb and configdict['forcekb']:
+                kb += 1024*mb
+            return stringround(kb, rb) + space+ configdict['kiloname']
+        else:
+            return str(rb) + space + configdict['bytename']
+    else:
+        outstr = ''
+        if mb and not configdict['forcekb']:
+            outstr = str(mb) + space + configdict['meganame'] +', '
+        if kb or configdict['forcekb'] or mb:
+            if configdict['forcekb']:
+                kb += 1024*mb 
+            outstr += str(kb) + space + configdict['kiloname'] +', '
+        return outstr + str(rb) + space + configdict['bytename']
+
+def stringround(main, rest):
+    """
+    Given a file size in either (mb, kb) or (kb, bytes) - round it
+    appropriately.
+    """
+    # divide an int by a float... get a float
+    value = main + rest/1024.0
+    return str(round(value, 1))
+
+def bytedivider(nbytes):
+    """
+    Given an integer (probably a long integer returned by os.getsize() )
+    it returns a tuple of (megabytes, kilobytes, bytes).
+    
+    This can be more easily converted into a formatted string to display the
+    size of the file.
+    """ 
+    mb, remainder = divmod(nbytes, 1048576)
+    kb, rb = divmod(remainder, 1024)
+    return (mb, kb, rb)
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/helpers.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,51 @@
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+
+# template helper functions
+import urllib
+from formatbytes import formatbytes
+from datetime import datetime
+
+def iter_is_first (seq) :
+    flag = True
+    
+    for item in seq :
+        yield item, flag
+        flag = False
+        
+def url_for_page (page) :
+    assert page >= 0
+
+    if page > 0 :
+        return  'index_%d.html' % page
+    else :
+        return 'index.html'
+
+def tag_for_img (page, img) :
+    return """<a href="%s"><img src="%s" /></a>""" % (page, img)
+
+def format_filesize (size) :
+    return formatbytes(size, forcekb=False, largestonly=True, kiloname='KiB', meganame='MiB', bytename='B', nospace=False)
+
+def format_timestamp (ts) :
+    return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
+
+def format_imgsize (size) :
+    return "%dx%d" % size
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/image.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,166 @@
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+
+import os, os.path
+
+import PIL.Image
+
+import dexif
+
+import settings, utils, log
+from template import image as image_tpl
+    
+class Image (object) :
+    def __init__ (self, dir, name) :
+        # the image filename, e.g. DSC3948.JPG
+        self.name = unicode(name)
+
+        # the Folder object that we are in
+        self.dir = dir
+        
+        # the relative path from the root to us
+        self.path = dir.pathFor(self.name)
+
+        # the basename+ext, e.g. DSCR3948, .JPG
+        self.base_name, self.ext = os.path.splitext(self.name)
+        
+        # our user-friendly title
+        self.title = self.name
+
+        # our long-winded description
+        self.descr = ''
+
+        # the image before and after us, both may be None
+        self.prev = self.next = None
+        
+        # the image-relative names for the html page, thumb and preview images
+        self.html_name = self.name + ".html"
+        self.thumb_name = utils.url_join(settings.THUMB_DIR, self.name)
+        self.preview_name = utils.url_join(settings.PREVIEW_DIR, self.name)
+
+        # the root-relative paths to the html page, thumb and preview images
+        self.html_path = self.dir.pathFor(self.html_name)
+        self.thumb_path = self.dir.pathFor(settings.THUMB_DIR, self.name)
+        self.preview_path = self.dir.pathFor(settings.PREVIEW_DIR, self.name)        
+        
+        #
+        # Figured out after prepare
+        #
+
+        # (w, h) tuple
+        self.img_size = None
+        
+        # the ShortURL code for this image
+        self.shorturl_code = None
+
+	# EXIF data
+	self.exif_data = {}
+
+        # what to use in the rendered templates, intended to be overridden by subclasses
+        self.series_act = "add"
+        self.series_verb = "Add to"
+    
+    def getObjInfo (self) :
+        """
+            Metadata for shorturl2.db
+        """
+        return 'img', self.dir.path, self.name
+
+    def breadcrumb (self) :
+        """
+            Returns a [(fname, title)] list of this image's parents
+       """
+        
+        return self.dir.breadcrumb(forImg=self) + [(self.html_name, self.title)]
+
+    def render (self) :
+        """
+            Write out the .html file
+        """
+        
+        # stat the image file to get the filesize and mtime
+        st = os.stat(self.path)
+
+        self.filesize = st.st_size
+        self.timestamp = st.st_mtime
+        
+        # open the image in PIL to get image attributes + generate thumbnails
+        img = PIL.Image.open(self.path)
+
+        self.img_size = img.size
+
+        for out_path, geom in ((self.thumb_path, settings.THUMB_GEOM), (self.preview_path, settings.PREVIEW_GEOM)) :
+            # if it doesn't exist, or it's older than the image itself, generate
+            if utils.mtime(out_path) < self.timestamp :
+                log.info("render [%sx%s]", geom[0], geom[1], wait=True)
+                
+                # XXX: is this the most efficient way to do this? It seems slow
+                out_img = img.copy()
+                out_img.thumbnail(geom, resample=True)
+                out_img.save(out_path)
+
+                log.done()
+        
+        # look for the metadata file
+        title_path = self.dir.pathFor(self.base_name + '.txt')
+        
+        self.title, self.descr = utils.readTitleDescr(title_path)
+        
+        if not self.title :
+            self.title = self.name
+        
+        if utils.mtime(self.html_path) < self.timestamp :
+            log.info("render %s.html", self.name)
+
+            # parse the exif data from the file
+            try :
+                    self.exif_data = dexif.parse_exif(self.path)
+            except dexif.ExifError, message:
+                    log.warning("Reading EXIF data for %s failed: %s" % (self.filename, message))
+                    self.exif_data = {}
+
+
+            image_tpl.render_to(self.html_path,
+                stylesheet_url             = self.dir.inRoot('style.css'),
+                title                      = self.title,
+                breadcrumb                 = self.breadcrumb(),
+                
+                prev                       = self.prev,
+                next                       = self.next,
+                img                        = self,
+                
+                description                = self.descr,
+                
+                filename                   = self.name,
+                img_size                   = self.img_size,
+                file_size                  = self.filesize,
+                timestamp                  = self.timestamp,
+		exif_data		   = self.exif_data,
+                
+                shorturl                   = self.dir.inRoot('s', self.shorturl_code),
+                shorturl_code              = self.shorturl_code,
+                
+                series_url                 = self.dir.inRoot('series/%s/%s' % (self.series_act, self.shorturl_code)),
+                series_verb                = self.series_verb,
+            )   
+    
+    def __str__ (self) :
+        return "Image `%s' in `%s'" % (self.name, self.dir.path)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/log.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,81 @@
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+
+import logging, sys
+
+log_level = logging.INFO
+stack = []
+
+class g :
+    out_depth = 0
+    node = None
+
+def title (title, *args) :
+    stack.append(title)
+
+    print "%s - %s" % (" "*g.out_depth, title % args)
+
+    g.out_depth += 1
+
+def down (dir_name, *args) :
+    stack.append(dir_name % args)
+    g.node = None
+
+def next (fname, *args) :
+    g.node = fname % args
+
+def up () :
+    stack.pop(-1)
+    g.node = None
+    g.out_depth = min(g.out_depth, len(stack))
+
+def done () :
+    print "done"
+
+def log (level, message, *args, **kwargs) :
+    wait = kwargs.get("wait", False)
+
+    if level >= log_level :
+        if g.out_depth != len(stack) :
+            for segment in stack[g.out_depth:] :
+                print "%sd %s" % (" "*g.out_depth, segment)
+                g.out_depth += 1
+
+        if g.node :
+            print "%sf %s" % (" "*g.out_depth, g.node)
+            g.node = None
+        
+        if wait :
+            print "%s - %s..." % (" "*g.out_depth, message % args),
+            sys.stdout.flush()
+        else :
+            print "%s - %s" % (" "*g.out_depth, message % args)
+
+def _level (level) :
+    def _log_func (message, *args, **kwargs) :
+        log(level, message, *args, **kwargs)
+    
+    return _log_func
+
+debug       = _level(logging.DEBUG)
+info        = _level(logging.INFO)
+warning     = _level(logging.WARNING)
+error       = _level(logging.ERROR)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/req.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,65 @@
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+
+import cgi
+import Cookie
+import os
+
+vars = cgi.FieldStorage()
+
+# the cookie with the user's current series
+cookie = Cookie.SimpleCookie(os.environ.get('HTTP_COOKIE', None))
+
+class token (object) :
+    pass
+
+REQUIRED_PARAM = token()
+
+def get_str (key, default=REQUIRED_PARAM) :
+    if key in vars :
+        return vars[key].value.decode('utf8', 'replace')
+    elif default is REQUIRED_PARAM :
+        raise ValueError("Required param %s" % key)
+    else :
+        return default
+
+def get_str_list (key, default=REQUIRED_PARAM) :
+    if key in vars :
+        return [val.decode('utf8', 'replace') for val in vars.getlist(key)]
+    elif default is REQUIRED_PARAM :
+        raise ValueError("Required param %s" % key)
+    else :
+        return default
+
+def get_int (key, default=REQUIRED_PARAM) :
+    if key in vars :
+        return int(vars[key].value)
+    elif default is REQUIRED_PARAM :
+        raise ValueError("Required param %s" % key)
+    else :
+        return default
+
+def get_int_list (key, default=REQUIRED_PARAM) :
+    if key in vars :
+      return [int(val) for val in vars.getlist(key)]
+    elif default is REQUIRED_PARAM :
+        raise ValueError("Required param %s" % key)
+    else :
+        return default
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/settings.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,20 @@
+TEMPLATE_DIR = './templates'
+TEMPLATE_EXT = 'html'
+
+IMAGE_EXTS = ('jpg', 'jpeg', 'png', 'gif', 'bmp')
+
+THUMB_DIR = 'thumbs'
+PREVIEW_DIR = 'previews'
+TITLE_FILE = 'title.txt'
+
+THUMB_GEOM = (160, 120)
+PREVIEW_GEOM = (640, 480)
+
+DEFAULT_TITLE = 'Image gallery'
+
+# how many image/page
+IMAGE_COUNT = 50
+
+VERSION = "0.5"
+ROOT_IGNORE = ('lib', 'templates')
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/shorturl.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,208 @@
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+
+import struct
+import base64
+import shelve
+import os.path
+
+
+import utils, db, helpers, folder, image, log
+
+def int2key (id) :
+    """
+        Turn an integer into a short-as-possible url-safe string
+    """
+    for type in ('B', 'H', 'I') :
+        try :
+            return base64.b64encode(struct.pack(type, id), '-_').rstrip('=')
+        except struct.error :
+            continue
+
+    raise Exception("ID overflow: %s" % id)
+
+def key2int (key) :
+    # base64 ignores extra padding, but if it doesn't, it's (4 - len%4), if len%4 != 0
+    # and it breaks on unicode strings
+    bytes = base64.b64decode(str(key + '='*6), '-_')
+    
+    type = {
+        1: 'B',
+        2: 'H',
+        4: 'I',
+    }[len(bytes)]
+
+    return struct.unpack(type, bytes)[0]
+
+class DB (object) :
+    def __init__ (self, read_only=True) :
+        self.db = shelve.open('shorturls2', read_only and 'r' or 'c')
+
+    def html_path (self, key, index) :
+        type, dirpath, fname = self.db[key]
+
+        if type == 'img' :
+            fname += '.html'
+        elif type == 'dir' :
+            fname = ''
+
+        if index :
+            dirpath = '../%s' % dirpath
+            
+            if type == 'dir' and index > 1 : 
+                fname = 'index_%s.html' % (index - 1)
+
+        return os.path.join(dirpath, fname)
+   
+    def image_info (self, key) :
+        type, dirpath, fname = self.db[key]
+
+        if type != 'img' :
+            raise ValueError("%s is not an img" % key)
+
+        return dirpath, fname
+    
+    def shorturls_for (self, paths) :
+        ret = []
+
+        for key in self.db.keys() :
+            if key.startswith('_') :
+                continue
+
+            type, dir, fname = self.db[key]
+            path = os.path.join(dir.lstrip('.').lstrip('/'), fname) 
+            if path in paths :
+                ret.append(key)
+                paths.remove(path)
+        
+        if paths :
+            raise ValueError("Paths not found: %s" % " ".join(paths))
+
+        return ret
+
+def html_path (key, index=None) :
+    dir, fname = node_info(key)
+
+    if fname :
+        return utils.url(dir, fname + '.html')
+    else :
+        return utils.url(dir, helpers.url_for_page(index or 0))
+
+def node_info (key) :
+    res = db.select("""SELECT dirpath, filename FROM nodes WHERE id=?""", key2int(key)).fetchone()
+    
+    if res :
+        return res
+
+    else :
+        raise KeyError(key)
+
+def image_info (key) :
+    res = db.select("""SELECT dirpath, filename FROM images WHERE id=?""", key2int(key)).fetchone()
+    
+    if res :
+        return res
+
+    else :
+        raise KeyError(key)
+   
+def get_images (keys) :
+    res = [db.select("""SELECT dirpath, filename FROM images WHERE id=?""", key2int(key)).fetchone() for key in keys]
+
+    # don't mind if we don't get as many as we asked for?
+    if res :
+        return res
+
+    else :
+        raise KeyError(keys)
+
+def _got_obj_key (obj, id) :
+    key = int2key(id)
+
+    obj.shorturl_code = key
+
+    if isinstance(obj, folder.Folder) :
+        dir, fname = utils.strip_path(obj.path), ''
+    elif isinstance(obj, image.Image) :
+        dir, fname = utils.strip_path(obj.dir.path), obj.name
+    else :
+        assert(False, "%r %r" % (obj, id))
+
+    log.info("%6s -> %s/%s", key, dir, fname)
+
+def updateDB (root) :
+    """
+        Update the SQL database
+
+        type    - one of 'img', 'dir'
+        dirpath - the path to the directory, e.g. '.', './foobar', './foobar/quux'
+        fname   - the filename, one of '', 'DSC9839.JPG', 'this.png', etc.
+    """
+
+    dirqueue = [root]
+
+    # dict of (dir, fname) -> obj
+    paths = {}
+
+    while dirqueue :
+        dir = dirqueue.pop(0)
+
+        dirqueue.extend(dir.subdirs.itervalues())
+
+        if dir.alive :
+            pathtuple = (utils.strip_path(dir.path), '')
+            
+            log.debug("dir %50s", pathtuple[0])
+
+            paths[pathtuple] = dir
+
+        for img in dir.images.itervalues() :
+            pathtuple = (utils.strip_path(img.dir.path), img.name)
+            
+            log.debug("img %50s %15s", *pathtuple)
+
+            paths[pathtuple] = img
+    
+    log.info("we have %d nodes", len(paths))
+
+    for (id, dir, fname) in db.select("SELECT id, dirpath, filename FROM nodes") :
+        try :
+            obj = paths.pop((dir, fname))
+            key = int2key(id)
+
+            obj.shorturl_code = key
+
+            log.debug("%s %50s %15s -> %d %s", dir and "img" or "dir", dir, fname, id, key)
+        
+        except KeyError :
+            pass
+#            log.warning("non-existant node (%d, %s, %s) in db", id, dir, fname)
+    
+    if paths :
+        log.info("allocating shorturls for %d new nodes:", len(paths))
+
+        db.insert_many(
+            _got_obj_key,
+            "INSERT INTO nodes (dirpath, filename) VALUES (?, ?)",
+            ((obj, (path, fname)) for ((path, fname), obj) in paths.iteritems())
+        )
+    else :
+        log.info("no new images")
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/static/style.css	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,92 @@
+body {
+	background-color: #333333;
+	color: #cccccc;
+	font-family: "Arial", sans-serif;
+	font-size: small;
+}
+
+a, span.dragged {
+	color: #ff8800;
+	text-decoration: none;
+}
+
+a:hover {
+	text-decoration: underline;
+}
+
+#thumbnails, #image, #description, h1 {
+	text-align: center;
+}
+
+#thumbnails img {
+	margin: 0.2em;
+}
+
+img {
+	border: 1px solid #666666;
+}
+
+a:focus img {
+	border: 1px solid #cccccc;
+}
+
+img:hover, a:focus img:hover {
+	border: 1px solid #ff8800;
+}
+
+div#breadcrumb {
+    
+}
+
+div#info {
+    font-size: x-small;
+    color: #666666;
+}
+
+div#info p {
+    padding: 0px;
+    margin: 0px;
+}
+
+p#about {
+    padding-top: 40px;
+    font-size: xx-small;
+    text-align: center;
+
+}
+
+div.paginate {
+    padding-top: 20px;
+    height: 50px;
+    width: 100%;
+    text-align: center;
+}
+
+div.paginate ul {
+    margin: 0px;
+    padding: 0px;
+
+    line-height: 30px;
+    white-space: nowrap;
+}
+
+div.paginate li {
+    list-style-type: none;
+    display: inline;
+}
+
+div.paginate li *,
+div.paginate li strong,
+div.paginate li span {
+    padding: 7px 10px;
+}
+
+div.paginate li span {
+    color: #444444;
+}
+
+div.paginate li a:hover {
+    text-decoration: none;
+    background-color: #666666;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/template.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,65 @@
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+
+from mako import exceptions
+from mako.lookup import TemplateLookup
+
+import settings, helpers
+
+import log
+
+_lookup = TemplateLookup(
+    directories=[settings.TEMPLATE_DIR], 
+    module_directory='%s/cache' % settings.TEMPLATE_DIR, 
+    output_encoding='utf-8',
+    filesystem_checks=False,        # this may need to be changed if used in a long-term process
+)
+
+TEMPLATE_GLOBALS = dict(
+    h                          = helpers,
+    version                    = settings.VERSION,
+)
+
+class Template (object) :
+    def __init__ (self, name) :
+        self.name = name
+        self.tpl = _lookup.get_template("%s.%s" % (name, settings.TEMPLATE_EXT))
+    
+    def render (self, **data) :
+        data.update(TEMPLATE_GLOBALS)
+        
+        try :
+            log.debug("render %s with %s", self.name, data)
+            return self.tpl.render(**data)
+        except :
+            data = exceptions.text_error_template().render()
+            log.error(data)
+            
+            raise
+    
+    def render_to (self, file, **data) :
+        fh = open(file, "w")
+        fh.write(self.render(**data))
+        fh.close()
+    
+# templates
+gallery = Template("gallery")
+image = Template("image")
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/templates/gallery.html	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,59 @@
+<%! use_javascript = False %>
+<%inherit file="master.html" /> <!-- %> -->
+
+<%def name="pagination(num_pages, cur_page)"> <!-- %> -->
+% if num_pages > 1 :
+        <ul>
+        
+%   if cur_page > 0 :
+            <li><a href="${h.url_for_page(cur_page - 1)}">&laquo; Prev</a></li>
+%   else :
+            <li><span>&laquo; Prev</span></li>
+%   endif
+
+%   for page in xrange(0, num_pages) :
+%     if page == cur_page :
+            <li><strong>${page + 1}</strong></li>
+%     else :
+            <li><a href="${h.url_for_page(page)}">${page + 1}</a></li>
+%     endif            
+%   endfor
+
+%   if cur_page < num_pages - 1 :
+            <li><a href="${h.url_for_page(cur_page + 1)}">Next &raquo;</a></li>
+%   else :
+            <li><span>Next &raquo;</span></li>
+%   endif
+        </ul>
+% endif       
+</%def> <!-- %> -->
+
+    <h1>${title}</h1>
+    <div id="dirs">
+% if dirs :
+        <ul>
+%   for dir in dirs :
+            <li><a href="${dir.name}">${dir.title}</a></li>
+%   endfor
+        </ul>
+% endif
+    </div>
+    <div class="paginate">
+${pagination(num_pages, cur_page)}
+    </div>
+    <div id="thumbnails">
+% for img in images :
+        ${h.tag_for_img(img.html_name, img.thumb_name)}
+% endfor
+    </div>
+    <div class="paginate">
+${pagination(num_pages, cur_page)}
+    </div>
+    <p id="description">
+${description}
+    </p>
+% if shorturl :    
+    <div id="info">
+        <p>ShortURL: <a href="${shorturl}" rel="nofollow">${shorturl_code}</a></p>
+    </div>
+% endif    
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/templates/image.html	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,36 @@
+<%! use_javascript = False %>
+<%inherit file="master.html" /> <!-- %> -->
+
+    <div id="image">
+        <h1>${title}</h1>
+        <p>
+% if prev :        
+            ${h.tag_for_img(prev.html_name, prev.thumb_name)}
+% endif
+            
+            ${h.tag_for_img(img.name, img.preview_name)}
+            
+% if next :            
+            ${h.tag_for_img(next.html_name, next.thumb_name)}
+% endif
+        </p>
+        <p>
+            ${description}
+        </p>
+    </div>
+    <div id="info">
+% if img_size and file_size and timestamp :    
+      <p>File name: ${filename}</p>
+      <p>Dimensions: ${h.format_imgsize(img_size)}</p>
+      <p>File size: ${h.format_filesize(file_size)}</p>
+      <p>Last modified: ${h.format_timestamp(timestamp)}</p>
+% for key, value in exif_data :
+      <p>${key}: ${value}</p>
+% endfor
+
+% endif    
+      <p>ShortURL: <a href="${shorturl}" rel="nofollow">${shorturl_code}</a></p>
+% if series_url :      
+      <p><a href="${series_url}" rel="nofollow">${series_verb}</a> series</p>
+% endif      
+    </div>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/templates/master.html	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
+  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
+  <head>
+    <title>${title}</title>
+    <link rel="Stylesheet" type="text/css" href="${stylesheet_url}" />
+% if self.module.use_javascript :
+    <script type="text/javascript" src="../javascript/prototype.js" />
+    <script type="text/javascript" src="../javascript/scriptaculous.js" />
+    <script type="text/javascript" src="../javascript/taggr.js" />
+% endif
+  </head>
+  <body>
+    <div id="breadcrumb">
+% for (( bc_url, bc_title), is_first) in h.iter_is_first(breadcrumb) :
+%   if not is_first :
+        &raquo;
+%   endif
+        <a href="${bc_url}">${bc_title}</a>
+% endfor
+    </div>
+    ${next.body()}
+    <p id="about"><a href="http://marttila.de/~terom/degal/">DeGAL</a> ${version}</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/utils.py	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,89 @@
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#
+
+import os, os.path
+
+import settings
+
+def isImage (fname) :
+    """
+        Is the given filename likely to be an image file?
+    """
+
+    fname = fname.lower()
+    base, ext = os.path.splitext(fname)
+    ext = ext.lstrip('.')
+
+    return ext in settings.IMAGE_EXTS
+
+def readFile (path) :
+    fo = open(path, 'r')
+    data = fo.read()
+    fo.close()
+
+    return data
+
+def fuzzyDecode (bytes) :
+    try :
+        return bytes.decode('utf8')
+    except UnicodeDecodeError :
+        return bytes.decode('latin1', 'replace')
+
+def readTitleDescr (path) :
+    """
+        Read a title.txt or <imgname>.txt file
+    """
+
+    if os.path.exists(path) :
+        content = readFile(path)
+
+        if '---' in content :
+            title, descr = content.split('---', 1)
+        else :
+            title, descr = content, ''
+        
+        title, descr = fuzzyDecode(title), fuzzyDecode(descr)
+
+        return title.strip(), descr.strip()
+
+    return u"", u""
+
+def url (*parts, **kwargs) :
+    abs = kwargs.pop('abs', False)
+    up = kwargs.pop('up', 0)
+    trailing = kwargs.pop('trailing', False)
+    
+    return '/'.join(([""]*int(abs)) + ([".."]*up) + list(parts) + ([""]*int(trailing)))
+
+url_join = url
+
+def path_join (*parts) :
+    return os.path.join(*[part for part in parts if part is not None])
+
+def strip_path (path) :
+    return path.lstrip('.').lstrip('/')
+
+def mtime (path) :
+    try :
+        return os.stat(path).st_mtime
+    except OSError :
+        # no such file or directory
+        return None
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/docs/db.sql	Wed Jun 03 19:03:28 2009 +0300
@@ -0,0 +1,5 @@
+CREATE TABLE 'nodes' (id INTEGER NOT NULL PRIMARY KEY, dirpath TEXT NOT NULL, filename TEXT NOT NULL);
+CREATE TABLE tags (image INTEGER NOT NULL, type TEXT, tag TEXT NOT NULL);
+CREATE VIEW images AS SELECT id, dirpath, filename FROM nodes WHERE filename != '';
+CREATE UNIQUE INDEX tags_unique_image_type ON tags (image, type);
+CREATE UNIQUE INDEX tags_unique_image_type_tag ON tags (image, type, tag);
--- a/lib/db.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,78 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-
-import sqlite3
-
-conn = sqlite3.connect("db/degal.db")
-
-def execute (expr, *args) :
-    c = conn.cursor()
-    c.execute(expr, args)
-
-    return c
-
-def execute_many (expr, iter) :
-    c = conn.cursor()
-    c.executemany(expr, iter)
-
-    return c
-
-def insert (expr, *args) :
-    return execute_commit(expr, *args).lastrowid
-
-def insert_many (cb, expr, iter) :
-    """
-        Perform an executemany with the given iterator (which must yield (cb_val, args) tuples), calling the given callback with the args (cb_val, row_id)
-    """
-
-    c = conn.cursor()
-
-    c.executemany(expr, _lastrowid_adapter(c, iter, cb))
-
-    return commit(c)
-
-def _lastrowid_adapter (c, iter, cb) :
-    for val, args in iter :
-        yield args
-
-        cb(val, c.lastrowid)
-
-def commit (cursor) :
-    try :
-        cursor.execute("COMMIT")
-    except sqlite3.OperationalError :
-        pass    # ffs. INSERT just doesn't do anything otherwise
-
-    return cursor
-
-def execute_commit (expr, *args) :
-    return commit(execute(expr, *args))
-
-def execute_commit_many (expr, iter) :
-    return commit(execute_many(expr, iter))
-
-select = execute
-
-delete = execute_commit
-
-delete_many = execute_commit_many
-
-cursor = conn.cursor
-
--- a/lib/dexif.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-#
-# dexif.py - simple EXIF processing for Degal
-# Copyright (C) 2008, Santtu Pajukanta <santtu@pajukanta.fi>
-#
-# 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.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-
-from subprocess import Popen, PIPE
-
-# TODO This should be user configurable
-EXIFTOOL="/usr/bin/exiftool"
-
-outputTags = [
-# TODO Create date is in a useless format, needs some strptime love
-    ("CreateDate", "Create date"),
-    ("Model", "Camera model"),
-    ("Aperture", "Aperture"),
-    ("ExposureMode", "Exposure mode"),
-    ("ExposureCompensation", "Exposure compensation"),
-    ("ExposureTime", "Exposure time"),
-    ("Flash", "Flash mode"),
-    ("ISO", "ISO"),
-    ("ShootingMode", "Shooting mode"),
-    ("LensType", "Lens type"),
-    ("FocalLength", "Focal length")
-]
-
-
-class ExifError(Exception):
-    pass
-
-def parse_exif(filepath):
-    """parse_exif(filepath :: String) -> [(String, String)]
-
-    Parse EXIF tags from an image file and return them in a dict.
-    """
-
-    args = [EXIFTOOL, "-s", "-t", filepath]
-    etproc = Popen(args, stdout = PIPE)
-
-    output, errors = etproc.communicate()
-    
-    if etproc.returncode < 0:
-        raise ExifError, "exiftool terminated by signal %d" % (-etproc.returnco)
-    elif etproc.returncode > 0:
-        raise ExifError, "exiftool failed with return code %d" % etproc.returncode
-    
-    tags = dict(line.split("\t", 1) for line in output.split("\n") if line)
-    result = [(descr, tags[key]) for (key, descr) in outputTags if tags.has_key(key)]
-    return result
--- a/lib/folder.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,329 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-
-import os, os.path
-
-import settings, image, utils, helpers, log
-from template import gallery as gallery_tpl
-from helpers import url_for_page
-
-def dirUp (count=1) :
-    """
-        Returns a relative path to the directly count levels above the current one
-    """
-
-    if not count :
-        return '.'
-
-    return os.path.join(*(['..']*count))
-    
-class Folder (object) :
-    def __init__ (self, name='.', parent=None) :
-        # the directory name, no trailing /
-        self.name = unicode(name.rstrip(os.sep))
-
-        # our parent Folder, or None
-        self.parent = parent
-
-        # the path to this dir, as a relative path to the root of the image gallery, always starts with .
-        if parent and name :
-            self.path = parent.pathFor(self.name)
-        else :
-            self.path = self.name
-
-        # the url-path to the index.html file
-        self.html_path = self.path
-        
-        # dict of fname -> Folder
-        self.subdirs = {}
-
-        # dict of fname -> Image
-        self.images = {}
-        
-        # our human-friendly title
-        self.title = None
-
-        # our long-winded description
-        self.descr = ''
-
-        # is this folder non-empty?
-        self.alive = None
-        
-        # self.images.values(), but sorted by filename
-        self.sorted_images = []
-        
-        # the ShortURL key to this dir
-        self.shorturl_code = None
-
-        # were we filtered out?
-        self.filtered = False
-   
-    def pathFor (self, *fnames) :
-        """
-            Return a root-relative path to the given path inside this dir
-        """
-        return os.path.join(self.path, *fnames)
-
-    def index (self, filters=None) :
-        """
-            Look for other dirs and images inside this dir. Filters must be either None,
-            whereupon all files will be included, or a dict of {filename -> next_filter}.
-            If given, only filenames that are present in the dict will be indexed, and in
-            the case of dirs, the next_filter will be passed on to that Folder's index
-            method.
-        """
-
-        if filters :
-            self.filtered = True
-        
-        # iterate through listdir
-        for fname in os.listdir(self.path) :
-            # the full filesystem path to it
-            fpath = self.pathFor(fname)
-            
-            # ignore dotfiles
-            if fname.startswith('.') :
-                log.debug("Skipping dotfile %s", fname)
-                continue
-            
-            # apply filters
-            if filters :
-                if fname in filters :
-                    next_filter = filters[fname]
-                else :
-                    log.debug("Skip `%s' as we have a filter", fname)
-                    continue
-            else :
-                next_filter = None
-                
-            # recurse into subdirs, but not thumbs/previews
-            if (os.path.isdir(fpath) 
-                and (fname not in (settings.THUMB_DIR, settings.PREVIEW_DIR))
-                and (self.parent or fname not in settings.ROOT_IGNORE)
-            ) :
-                log.down(fname)
-
-                f = Folder(fname, self)
-                
-                try :
-                    if f.index(next_filter) :   # recursion
-                        # if a subdir is alive, we are alive as well
-                        self.subdirs[fname] = f
-                        self.alive = True
-                except Exception, e :
-                    log.warning("skip - %s: %s" % (type(e), e))
-
-                log.up()
-
-            # handle images
-            elif os.path.isfile(fpath) and utils.isImage(fname) :
-                log.next(fname)
-                self.images[fname] = image.Image(self, fname)
-
-            # ignore everything else
-            else :
-                log.debug("Ignoring file %s", fname)
-        
-        # sort and link the images
-        if self.images :
-            self.alive = True
-
-            # sort the images
-            fnames = self.images.keys()
-            fnames.sort()
-
-            prev = None
-
-            # link
-            for fname in fnames :
-                img = self.images[fname]
-
-                img.prev = prev
-
-                if prev :
-                    prev.next = img
-
-                prev = img
-                
-                # add to the sorted images list
-                self.sorted_images.append(img)
-                
-        # figure out our title/ descr. Must be done before our parent dir is rendered (self.title)
-        title_path = self.pathFor(settings.TITLE_FILE)
-        
-        self.title, self.descr = utils.readTitleDescr(title_path)
-        
-        # default title for the root dir
-        if self.title or self.descr :
-            self.alive = True
-            pass # use what was in the title file
-            
-        elif not self.parent :
-            self.title = 'Index'
-
-        else :
-            self.title = self.name
-        
-        if not self.alive :
-            log.debug("Dir %s isn't alive" % self.path)
-
-        return self.alive
-
-    def getObjInfo (self) :
-        """
-            Metadata for shorturls2.db
-        """
-        return 'dir', self.path, ''
-
-    def breadcrumb (self, forImg=None) :
-        """
-            Returns a [(fname, title)] list of this dir's parent dirs
-        """
-
-        f = self
-        b = []
-        d = 0
-        
-        while f :
-            # functionality of the slightly-hacked-in variety
-            if f is self and forImg is not None :
-                url = helpers.url_for_page(self.getPageNumber(forImg))
-            else :
-                url = dirUp(d)
-                
-            b.insert(0, (url, f.title))
-
-            d += 1
-            f = f.parent
-        
-        return b
-        
-    def getPageNumber (self, img) :
-        """
-            Get the page number that the given image is on
-        """
-        
-        return self.sorted_images.index(img) // settings.IMAGE_COUNT
-
-    def countParents (self, acc=0) :
-        if self.parent :
-            return self.parent.countParents(acc+1)
-        else :
-            return acc
-    
-    def inRoot (self, *fnames) :
-        """
-            Return a relative URL from this dir to the given path in the root dir
-        """
-
-        c = self.countParents()
-
-        return utils.url_join(*((['..']*c) + list(fnames)))
-
-    def render (self) :
-        """
-            Render the index.html, Images, and recurse into subdirs
-        """
-        
-        # ded folders are skipped
-        if not self.alive :
-            # dead, skip, no output
-            return
-        
-        index_mtime = utils.mtime(self.pathFor("index.html"))
-        dir_mtime = utils.mtime(self.path)
-
-        # if this dir's contents were filtered out, then we can't render the index.html, as we aren't aware of all the images in here
-        if self.filtered :
-            log.warning("Dir `%s' contents were filtered, so we won't render the gallery index again", self.path)
-
-        elif index_mtime > dir_mtime :
-            # no changes, pass, ignored
-            pass
-
-        else :  
-            # create the thumb/preview dirs if needed
-            for dir in (settings.THUMB_DIR, settings.PREVIEW_DIR) :
-                path = self.pathFor(dir)
-
-                if not os.path.isdir(path) :
-                    log.info("mkdir %s", dir)
-                    os.mkdir(path)
-
-            # sort the subdirs
-            subdirs = self.subdirs.values()
-            subdirs.sort(key=lambda d: d.name)
-            
-            # paginate!
-            images = self.sorted_images
-            image_count = len(images)
-            pages = []
-            
-            while images :
-                pages.append(images[:settings.IMAGE_COUNT])
-                images = images[settings.IMAGE_COUNT:]
-
-            pagination_required = len(pages) > 1
-
-            if pagination_required :
-                log.info("%d pages @ %d images", len(pages), settings.IMAGE_COUNT)
-            elif not pages :
-                log.info("no images, render for subdirs")
-                pages = [[]]
-
-            for cur_page, images in enumerate(pages) :
-                if pagination_required and cur_page > 0 :
-                    shorturl = "%s/%s" % (self.shorturl_code, cur_page+1)
-                else :
-                    shorturl = self.shorturl_code
-                
-                # render to index.html
-                gallery_tpl.render_to(self.pathFor(url_for_page(cur_page)), 
-                    stylesheet_url               = self.inRoot('style.css'),
-                    title                        = self.title,
-                    breadcrumb                   = self.breadcrumb(),
-                    
-                    dirs                         = subdirs,
-                    images                       = images,
-                    
-                    num_pages                    = len(pages),
-                    cur_page                     = cur_page,
-                    
-                    description                  = self.descr,
-                    
-                    shorturl                     = self.inRoot('s', shorturl),
-                    shorturl_code                = shorturl,
-                )
-
-        # render images
-        image_count = len(self.sorted_images)
-        for i, img in enumerate(self.images.itervalues()) :
-            log.next("[%-4d/%4d] %s", i + 1, image_count, img.name)
-
-            img.render()
-        
-        # recurse into subdirs
-        for dir in self.subdirs.itervalues() :
-            log.down(dir.name)
-
-            dir.render()
-
-            log.up()
-
--- a/lib/formatbytes.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,116 +0,0 @@
-###############################################################
-# Functions taken from pathutils.py Version 0.2.5 (2005/12/06), http://www.voidspace.org.uk/python/recipebook.shtml#utils
-# Copyright Michael Foord 2004
-# Released subject to the BSD License
-# Please see http://www.voidspace.org.uk/python/license.shtml
-
-###############################################################
-# formatbytes takes a filesize (as returned by os.getsize() )
-# and formats it for display in one of two ways !!
-
-# For information about bugfixes, updates and support, please join the Pythonutils mailing list.
-# http://groups.google.com/group/pythonutils/
-# Comments, suggestions and bug reports welcome.
-# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
-# E-mail fuzzyman@voidspace.org.uk
-
-def formatbytes(sizeint, configdict=None, **configs):
-    """
-    Given a file size as an integer, return a nicely formatted string that
-    represents the size. Has various options to control it's output.
-    
-    You can pass in a dictionary of arguments or keyword arguments. Keyword
-    arguments override the dictionary and there are sensible defaults for options
-    you don't set.
-    
-    Options and defaults are as follows :
-    
-    *    ``forcekb = False`` -         If set this forces the output to be in terms
-    of kilobytes and bytes only.
-    
-    *    ``largestonly = True`` -    If set, instead of outputting 
-        ``1 Mbytes, 307 Kbytes, 478 bytes`` it outputs using only the largest 
-        denominator - e.g. ``1.3 Mbytes`` or ``17.2 Kbytes``
-    
-    *    ``kiloname = 'Kbytes'`` -    The string to use for kilobytes
-    
-    *    ``meganame = 'Mbytes'`` - The string to use for Megabytes
-    
-    *    ``bytename = 'bytes'`` -     The string to use for bytes
-    
-    *    ``nospace = True`` -        If set it outputs ``1Mbytes, 307Kbytes``, 
-        notice there is no space.
-    
-    Example outputs : ::
-    
-        19Mbytes, 75Kbytes, 255bytes
-        2Kbytes, 0bytes
-        23.8Mbytes
-    
-    .. note::
-    
-        It currently uses the plural form even for singular.
-    """
-    defaultconfigs = {  'forcekb' : False,
-                        'largestonly' : True,
-                        'kiloname' : 'Kbytes',
-                        'meganame' : 'Mbytes',
-                        'bytename' : 'bytes',
-                        'nospace' : True}
-    if configdict is None:
-        configdict = {}
-    for entry in configs:
-        # keyword parameters override the dictionary passed in
-        configdict[entry] = configs[entry]
-    #
-    for keyword in defaultconfigs:
-        if not configdict.has_key(keyword):
-            configdict[keyword] = defaultconfigs[keyword]
-    #
-    if configdict['nospace']:
-        space = ''
-    else:
-        space = ' '
-    #
-    mb, kb, rb = bytedivider(sizeint)
-    if configdict['largestonly']:
-        if mb and not configdict['forcekb']:
-            return stringround(mb, kb)+ space + configdict['meganame']
-        elif kb or configdict['forcekb']:
-            if mb and configdict['forcekb']:
-                kb += 1024*mb
-            return stringround(kb, rb) + space+ configdict['kiloname']
-        else:
-            return str(rb) + space + configdict['bytename']
-    else:
-        outstr = ''
-        if mb and not configdict['forcekb']:
-            outstr = str(mb) + space + configdict['meganame'] +', '
-        if kb or configdict['forcekb'] or mb:
-            if configdict['forcekb']:
-                kb += 1024*mb 
-            outstr += str(kb) + space + configdict['kiloname'] +', '
-        return outstr + str(rb) + space + configdict['bytename']
-
-def stringround(main, rest):
-    """
-    Given a file size in either (mb, kb) or (kb, bytes) - round it
-    appropriately.
-    """
-    # divide an int by a float... get a float
-    value = main + rest/1024.0
-    return str(round(value, 1))
-
-def bytedivider(nbytes):
-    """
-    Given an integer (probably a long integer returned by os.getsize() )
-    it returns a tuple of (megabytes, kilobytes, bytes).
-    
-    This can be more easily converted into a formatted string to display the
-    size of the file.
-    """ 
-    mb, remainder = divmod(nbytes, 1048576)
-    kb, rb = divmod(remainder, 1024)
-    return (mb, kb, rb)
-
-
--- a/lib/helpers.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,51 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-
-# template helper functions
-import urllib
-from formatbytes import formatbytes
-from datetime import datetime
-
-def iter_is_first (seq) :
-    flag = True
-    
-    for item in seq :
-        yield item, flag
-        flag = False
-        
-def url_for_page (page) :
-    assert page >= 0
-
-    if page > 0 :
-        return  'index_%d.html' % page
-    else :
-        return 'index.html'
-
-def tag_for_img (page, img) :
-    return """<a href="%s"><img src="%s" /></a>""" % (page, img)
-
-def format_filesize (size) :
-    return formatbytes(size, forcekb=False, largestonly=True, kiloname='KiB', meganame='MiB', bytename='B', nospace=False)
-
-def format_timestamp (ts) :
-    return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
-
-def format_imgsize (size) :
-    return "%dx%d" % size
--- a/lib/image.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,166 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-
-import os, os.path
-
-import PIL.Image
-
-import dexif
-
-import settings, utils, log
-from template import image as image_tpl
-    
-class Image (object) :
-    def __init__ (self, dir, name) :
-        # the image filename, e.g. DSC3948.JPG
-        self.name = unicode(name)
-
-        # the Folder object that we are in
-        self.dir = dir
-        
-        # the relative path from the root to us
-        self.path = dir.pathFor(self.name)
-
-        # the basename+ext, e.g. DSCR3948, .JPG
-        self.base_name, self.ext = os.path.splitext(self.name)
-        
-        # our user-friendly title
-        self.title = self.name
-
-        # our long-winded description
-        self.descr = ''
-
-        # the image before and after us, both may be None
-        self.prev = self.next = None
-        
-        # the image-relative names for the html page, thumb and preview images
-        self.html_name = self.name + ".html"
-        self.thumb_name = utils.url_join(settings.THUMB_DIR, self.name)
-        self.preview_name = utils.url_join(settings.PREVIEW_DIR, self.name)
-
-        # the root-relative paths to the html page, thumb and preview images
-        self.html_path = self.dir.pathFor(self.html_name)
-        self.thumb_path = self.dir.pathFor(settings.THUMB_DIR, self.name)
-        self.preview_path = self.dir.pathFor(settings.PREVIEW_DIR, self.name)        
-        
-        #
-        # Figured out after prepare
-        #
-
-        # (w, h) tuple
-        self.img_size = None
-        
-        # the ShortURL code for this image
-        self.shorturl_code = None
-
-	# EXIF data
-	self.exif_data = {}
-
-        # what to use in the rendered templates, intended to be overridden by subclasses
-        self.series_act = "add"
-        self.series_verb = "Add to"
-    
-    def getObjInfo (self) :
-        """
-            Metadata for shorturl2.db
-        """
-        return 'img', self.dir.path, self.name
-
-    def breadcrumb (self) :
-        """
-            Returns a [(fname, title)] list of this image's parents
-       """
-        
-        return self.dir.breadcrumb(forImg=self) + [(self.html_name, self.title)]
-
-    def render (self) :
-        """
-            Write out the .html file
-        """
-        
-        # stat the image file to get the filesize and mtime
-        st = os.stat(self.path)
-
-        self.filesize = st.st_size
-        self.timestamp = st.st_mtime
-        
-        # open the image in PIL to get image attributes + generate thumbnails
-        img = PIL.Image.open(self.path)
-
-        self.img_size = img.size
-
-        for out_path, geom in ((self.thumb_path, settings.THUMB_GEOM), (self.preview_path, settings.PREVIEW_GEOM)) :
-            # if it doesn't exist, or it's older than the image itself, generate
-            if utils.mtime(out_path) < self.timestamp :
-                log.info("render [%sx%s]", geom[0], geom[1], wait=True)
-                
-                # XXX: is this the most efficient way to do this? It seems slow
-                out_img = img.copy()
-                out_img.thumbnail(geom, resample=True)
-                out_img.save(out_path)
-
-                log.done()
-        
-        # look for the metadata file
-        title_path = self.dir.pathFor(self.base_name + '.txt')
-        
-        self.title, self.descr = utils.readTitleDescr(title_path)
-        
-        if not self.title :
-            self.title = self.name
-        
-        if utils.mtime(self.html_path) < self.timestamp :
-            log.info("render %s.html", self.name)
-
-            # parse the exif data from the file
-            try :
-                    self.exif_data = dexif.parse_exif(self.path)
-            except dexif.ExifError, message:
-                    log.warning("Reading EXIF data for %s failed: %s" % (self.filename, message))
-                    self.exif_data = {}
-
-
-            image_tpl.render_to(self.html_path,
-                stylesheet_url             = self.dir.inRoot('style.css'),
-                title                      = self.title,
-                breadcrumb                 = self.breadcrumb(),
-                
-                prev                       = self.prev,
-                next                       = self.next,
-                img                        = self,
-                
-                description                = self.descr,
-                
-                filename                   = self.name,
-                img_size                   = self.img_size,
-                file_size                  = self.filesize,
-                timestamp                  = self.timestamp,
-		exif_data		   = self.exif_data,
-                
-                shorturl                   = self.dir.inRoot('s', self.shorturl_code),
-                shorturl_code              = self.shorturl_code,
-                
-                series_url                 = self.dir.inRoot('series/%s/%s' % (self.series_act, self.shorturl_code)),
-                series_verb                = self.series_verb,
-            )   
-    
-    def __str__ (self) :
-        return "Image `%s' in `%s'" % (self.name, self.dir.path)
-
--- a/lib/log.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,81 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-
-import logging, sys
-
-log_level = logging.INFO
-stack = []
-
-class g :
-    out_depth = 0
-    node = None
-
-def title (title, *args) :
-    stack.append(title)
-
-    print "%s - %s" % (" "*g.out_depth, title % args)
-
-    g.out_depth += 1
-
-def down (dir_name, *args) :
-    stack.append(dir_name % args)
-    g.node = None
-
-def next (fname, *args) :
-    g.node = fname % args
-
-def up () :
-    stack.pop(-1)
-    g.node = None
-    g.out_depth = min(g.out_depth, len(stack))
-
-def done () :
-    print "done"
-
-def log (level, message, *args, **kwargs) :
-    wait = kwargs.get("wait", False)
-
-    if level >= log_level :
-        if g.out_depth != len(stack) :
-            for segment in stack[g.out_depth:] :
-                print "%sd %s" % (" "*g.out_depth, segment)
-                g.out_depth += 1
-
-        if g.node :
-            print "%sf %s" % (" "*g.out_depth, g.node)
-            g.node = None
-        
-        if wait :
-            print "%s - %s..." % (" "*g.out_depth, message % args),
-            sys.stdout.flush()
-        else :
-            print "%s - %s" % (" "*g.out_depth, message % args)
-
-def _level (level) :
-    def _log_func (message, *args, **kwargs) :
-        log(level, message, *args, **kwargs)
-    
-    return _log_func
-
-debug       = _level(logging.DEBUG)
-info        = _level(logging.INFO)
-warning     = _level(logging.WARNING)
-error       = _level(logging.ERROR)
-
--- a/lib/req.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-
-import cgi
-import Cookie
-import os
-
-vars = cgi.FieldStorage()
-
-# the cookie with the user's current series
-cookie = Cookie.SimpleCookie(os.environ.get('HTTP_COOKIE', None))
-
-class token (object) :
-    pass
-
-REQUIRED_PARAM = token()
-
-def get_str (key, default=REQUIRED_PARAM) :
-    if key in vars :
-        return vars[key].value.decode('utf8', 'replace')
-    elif default is REQUIRED_PARAM :
-        raise ValueError("Required param %s" % key)
-    else :
-        return default
-
-def get_str_list (key, default=REQUIRED_PARAM) :
-    if key in vars :
-        return [val.decode('utf8', 'replace') for val in vars.getlist(key)]
-    elif default is REQUIRED_PARAM :
-        raise ValueError("Required param %s" % key)
-    else :
-        return default
-
-def get_int (key, default=REQUIRED_PARAM) :
-    if key in vars :
-        return int(vars[key].value)
-    elif default is REQUIRED_PARAM :
-        raise ValueError("Required param %s" % key)
-    else :
-        return default
-
-def get_int_list (key, default=REQUIRED_PARAM) :
-    if key in vars :
-      return [int(val) for val in vars.getlist(key)]
-    elif default is REQUIRED_PARAM :
-        raise ValueError("Required param %s" % key)
-    else :
-        return default
--- a/lib/settings.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,20 +0,0 @@
-TEMPLATE_DIR = './templates'
-TEMPLATE_EXT = 'html'
-
-IMAGE_EXTS = ('jpg', 'jpeg', 'png', 'gif', 'bmp')
-
-THUMB_DIR = 'thumbs'
-PREVIEW_DIR = 'previews'
-TITLE_FILE = 'title.txt'
-
-THUMB_GEOM = (160, 120)
-PREVIEW_GEOM = (640, 480)
-
-DEFAULT_TITLE = 'Image gallery'
-
-# how many image/page
-IMAGE_COUNT = 50
-
-VERSION = "0.5"
-ROOT_IGNORE = ('lib', 'templates')
-
--- a/lib/shorturl.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,208 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-
-import struct
-import base64
-import shelve
-import os.path
-
-
-import utils, db, helpers, folder, image, log
-
-def int2key (id) :
-    """
-        Turn an integer into a short-as-possible url-safe string
-    """
-    for type in ('B', 'H', 'I') :
-        try :
-            return base64.b64encode(struct.pack(type, id), '-_').rstrip('=')
-        except struct.error :
-            continue
-
-    raise Exception("ID overflow: %s" % id)
-
-def key2int (key) :
-    # base64 ignores extra padding, but if it doesn't, it's (4 - len%4), if len%4 != 0
-    # and it breaks on unicode strings
-    bytes = base64.b64decode(str(key + '='*6), '-_')
-    
-    type = {
-        1: 'B',
-        2: 'H',
-        4: 'I',
-    }[len(bytes)]
-
-    return struct.unpack(type, bytes)[0]
-
-class DB (object) :
-    def __init__ (self, read_only=True) :
-        self.db = shelve.open('shorturls2', read_only and 'r' or 'c')
-
-    def html_path (self, key, index) :
-        type, dirpath, fname = self.db[key]
-
-        if type == 'img' :
-            fname += '.html'
-        elif type == 'dir' :
-            fname = ''
-
-        if index :
-            dirpath = '../%s' % dirpath
-            
-            if type == 'dir' and index > 1 : 
-                fname = 'index_%s.html' % (index - 1)
-
-        return os.path.join(dirpath, fname)
-   
-    def image_info (self, key) :
-        type, dirpath, fname = self.db[key]
-
-        if type != 'img' :
-            raise ValueError("%s is not an img" % key)
-
-        return dirpath, fname
-    
-    def shorturls_for (self, paths) :
-        ret = []
-
-        for key in self.db.keys() :
-            if key.startswith('_') :
-                continue
-
-            type, dir, fname = self.db[key]
-            path = os.path.join(dir.lstrip('.').lstrip('/'), fname) 
-            if path in paths :
-                ret.append(key)
-                paths.remove(path)
-        
-        if paths :
-            raise ValueError("Paths not found: %s" % " ".join(paths))
-
-        return ret
-
-def html_path (key, index=None) :
-    dir, fname = node_info(key)
-
-    if fname :
-        return utils.url(dir, fname + '.html')
-    else :
-        return utils.url(dir, helpers.url_for_page(index or 0))
-
-def node_info (key) :
-    res = db.select("""SELECT dirpath, filename FROM nodes WHERE id=?""", key2int(key)).fetchone()
-    
-    if res :
-        return res
-
-    else :
-        raise KeyError(key)
-
-def image_info (key) :
-    res = db.select("""SELECT dirpath, filename FROM images WHERE id=?""", key2int(key)).fetchone()
-    
-    if res :
-        return res
-
-    else :
-        raise KeyError(key)
-   
-def get_images (keys) :
-    res = [db.select("""SELECT dirpath, filename FROM images WHERE id=?""", key2int(key)).fetchone() for key in keys]
-
-    # don't mind if we don't get as many as we asked for?
-    if res :
-        return res
-
-    else :
-        raise KeyError(keys)
-
-def _got_obj_key (obj, id) :
-    key = int2key(id)
-
-    obj.shorturl_code = key
-
-    if isinstance(obj, folder.Folder) :
-        dir, fname = utils.strip_path(obj.path), ''
-    elif isinstance(obj, image.Image) :
-        dir, fname = utils.strip_path(obj.dir.path), obj.name
-    else :
-        assert(False, "%r %r" % (obj, id))
-
-    log.info("%6s -> %s/%s", key, dir, fname)
-
-def updateDB (root) :
-    """
-        Update the SQL database
-
-        type    - one of 'img', 'dir'
-        dirpath - the path to the directory, e.g. '.', './foobar', './foobar/quux'
-        fname   - the filename, one of '', 'DSC9839.JPG', 'this.png', etc.
-    """
-
-    dirqueue = [root]
-
-    # dict of (dir, fname) -> obj
-    paths = {}
-
-    while dirqueue :
-        dir = dirqueue.pop(0)
-
-        dirqueue.extend(dir.subdirs.itervalues())
-
-        if dir.alive :
-            pathtuple = (utils.strip_path(dir.path), '')
-            
-            log.debug("dir %50s", pathtuple[0])
-
-            paths[pathtuple] = dir
-
-        for img in dir.images.itervalues() :
-            pathtuple = (utils.strip_path(img.dir.path), img.name)
-            
-            log.debug("img %50s %15s", *pathtuple)
-
-            paths[pathtuple] = img
-    
-    log.info("we have %d nodes", len(paths))
-
-    for (id, dir, fname) in db.select("SELECT id, dirpath, filename FROM nodes") :
-        try :
-            obj = paths.pop((dir, fname))
-            key = int2key(id)
-
-            obj.shorturl_code = key
-
-            log.debug("%s %50s %15s -> %d %s", dir and "img" or "dir", dir, fname, id, key)
-        
-        except KeyError :
-            pass
-#            log.warning("non-existant node (%d, %s, %s) in db", id, dir, fname)
-    
-    if paths :
-        log.info("allocating shorturls for %d new nodes:", len(paths))
-
-        db.insert_many(
-            _got_obj_key,
-            "INSERT INTO nodes (dirpath, filename) VALUES (?, ?)",
-            ((obj, (path, fname)) for ((path, fname), obj) in paths.iteritems())
-        )
-    else :
-        log.info("no new images")
-
--- a/lib/template.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-
-from mako import exceptions
-from mako.lookup import TemplateLookup
-
-import settings, helpers
-
-import log
-
-_lookup = TemplateLookup(
-    directories=[settings.TEMPLATE_DIR], 
-    module_directory='%s/cache' % settings.TEMPLATE_DIR, 
-    output_encoding='utf-8',
-    filesystem_checks=False,        # this may need to be changed if used in a long-term process
-)
-
-TEMPLATE_GLOBALS = dict(
-    h                          = helpers,
-    version                    = settings.VERSION,
-)
-
-class Template (object) :
-    def __init__ (self, name) :
-        self.name = name
-        self.tpl = _lookup.get_template("%s.%s" % (name, settings.TEMPLATE_EXT))
-    
-    def render (self, **data) :
-        data.update(TEMPLATE_GLOBALS)
-        
-        try :
-            log.debug("render %s with %s", self.name, data)
-            return self.tpl.render(**data)
-        except :
-            data = exceptions.text_error_template().render()
-            log.error(data)
-            
-            raise
-    
-    def render_to (self, file, **data) :
-        fh = open(file, "w")
-        fh.write(self.render(**data))
-        fh.close()
-    
-# templates
-gallery = Template("gallery")
-image = Template("image")
-
--- a/lib/utils.py	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,89 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-
-import os, os.path
-
-import settings
-
-def isImage (fname) :
-    """
-        Is the given filename likely to be an image file?
-    """
-
-    fname = fname.lower()
-    base, ext = os.path.splitext(fname)
-    ext = ext.lstrip('.')
-
-    return ext in settings.IMAGE_EXTS
-
-def readFile (path) :
-    fo = open(path, 'r')
-    data = fo.read()
-    fo.close()
-
-    return data
-
-def fuzzyDecode (bytes) :
-    try :
-        return bytes.decode('utf8')
-    except UnicodeDecodeError :
-        return bytes.decode('latin1', 'replace')
-
-def readTitleDescr (path) :
-    """
-        Read a title.txt or <imgname>.txt file
-    """
-
-    if os.path.exists(path) :
-        content = readFile(path)
-
-        if '---' in content :
-            title, descr = content.split('---', 1)
-        else :
-            title, descr = content, ''
-        
-        title, descr = fuzzyDecode(title), fuzzyDecode(descr)
-
-        return title.strip(), descr.strip()
-
-    return u"", u""
-
-def url (*parts, **kwargs) :
-    abs = kwargs.pop('abs', False)
-    up = kwargs.pop('up', 0)
-    trailing = kwargs.pop('trailing', False)
-    
-    return '/'.join(([""]*int(abs)) + ([".."]*up) + list(parts) + ([""]*int(trailing)))
-
-url_join = url
-
-def path_join (*parts) :
-    return os.path.join(*[part for part in parts if part is not None])
-
-def strip_path (path) :
-    return path.lstrip('.').lstrip('/')
-
-def mtime (path) :
-    try :
-        return os.stat(path).st_mtime
-    except OSError :
-        # no such file or directory
-        return None
-
--- a/templates/gallery.html	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,59 +0,0 @@
-<%! use_javascript = False %>
-<%inherit file="master.html" /> <!-- %> -->
-
-<%def name="pagination(num_pages, cur_page)"> <!-- %> -->
-% if num_pages > 1 :
-        <ul>
-        
-%   if cur_page > 0 :
-            <li><a href="${h.url_for_page(cur_page - 1)}">&laquo; Prev</a></li>
-%   else :
-            <li><span>&laquo; Prev</span></li>
-%   endif
-
-%   for page in xrange(0, num_pages) :
-%     if page == cur_page :
-            <li><strong>${page + 1}</strong></li>
-%     else :
-            <li><a href="${h.url_for_page(page)}">${page + 1}</a></li>
-%     endif            
-%   endfor
-
-%   if cur_page < num_pages - 1 :
-            <li><a href="${h.url_for_page(cur_page + 1)}">Next &raquo;</a></li>
-%   else :
-            <li><span>Next &raquo;</span></li>
-%   endif
-        </ul>
-% endif       
-</%def> <!-- %> -->
-
-    <h1>${title}</h1>
-    <div id="dirs">
-% if dirs :
-        <ul>
-%   for dir in dirs :
-            <li><a href="${dir.name}">${dir.title}</a></li>
-%   endfor
-        </ul>
-% endif
-    </div>
-    <div class="paginate">
-${pagination(num_pages, cur_page)}
-    </div>
-    <div id="thumbnails">
-% for img in images :
-        ${h.tag_for_img(img.html_name, img.thumb_name)}
-% endfor
-    </div>
-    <div class="paginate">
-${pagination(num_pages, cur_page)}
-    </div>
-    <p id="description">
-${description}
-    </p>
-% if shorturl :    
-    <div id="info">
-        <p>ShortURL: <a href="${shorturl}" rel="nofollow">${shorturl_code}</a></p>
-    </div>
-% endif    
--- a/templates/image.html	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-<%! use_javascript = False %>
-<%inherit file="master.html" /> <!-- %> -->
-
-    <div id="image">
-        <h1>${title}</h1>
-        <p>
-% if prev :        
-            ${h.tag_for_img(prev.html_name, prev.thumb_name)}
-% endif
-            
-            ${h.tag_for_img(img.name, img.preview_name)}
-            
-% if next :            
-            ${h.tag_for_img(next.html_name, next.thumb_name)}
-% endif
-        </p>
-        <p>
-            ${description}
-        </p>
-    </div>
-    <div id="info">
-% if img_size and file_size and timestamp :    
-      <p>File name: ${filename}</p>
-      <p>Dimensions: ${h.format_imgsize(img_size)}</p>
-      <p>File size: ${h.format_filesize(file_size)}</p>
-      <p>Last modified: ${h.format_timestamp(timestamp)}</p>
-% for key, value in exif_data :
-      <p>${key}: ${value}</p>
-% endfor
-
-% endif    
-      <p>ShortURL: <a href="${shorturl}" rel="nofollow">${shorturl_code}</a></p>
-% if series_url :      
-      <p><a href="${series_url}" rel="nofollow">${series_verb}</a> series</p>
-% endif      
-    </div>
--- a/templates/master.html	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
-  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
-  <head>
-    <title>${title}</title>
-    <link rel="Stylesheet" type="text/css" href="${stylesheet_url}" />
-% if self.module.use_javascript :
-    <script type="text/javascript" src="../javascript/prototype.js" />
-    <script type="text/javascript" src="../javascript/scriptaculous.js" />
-    <script type="text/javascript" src="../javascript/taggr.js" />
-% endif
-  </head>
-  <body>
-    <div id="breadcrumb">
-% for (( bc_url, bc_title), is_first) in h.iter_is_first(breadcrumb) :
-%   if not is_first :
-        &raquo;
-%   endif
-        <a href="${bc_url}">${bc_title}</a>
-% endfor
-    </div>
-    ${next.body()}
-    <p id="about"><a href="http://marttila.de/~terom/degal/">DeGAL</a> ${version}</p>
-  </body>
-</html>
--- a/www/style.css	Wed Jun 03 18:59:46 2009 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,92 +0,0 @@
-body {
-	background-color: #333333;
-	color: #cccccc;
-	font-family: "Arial", sans-serif;
-	font-size: small;
-}
-
-a, span.dragged {
-	color: #ff8800;
-	text-decoration: none;
-}
-
-a:hover {
-	text-decoration: underline;
-}
-
-#thumbnails, #image, #description, h1 {
-	text-align: center;
-}
-
-#thumbnails img {
-	margin: 0.2em;
-}
-
-img {
-	border: 1px solid #666666;
-}
-
-a:focus img {
-	border: 1px solid #cccccc;
-}
-
-img:hover, a:focus img:hover {
-	border: 1px solid #ff8800;
-}
-
-div#breadcrumb {
-    
-}
-
-div#info {
-    font-size: x-small;
-    color: #666666;
-}
-
-div#info p {
-    padding: 0px;
-    margin: 0px;
-}
-
-p#about {
-    padding-top: 40px;
-    font-size: xx-small;
-    text-align: center;
-
-}
-
-div.paginate {
-    padding-top: 20px;
-    height: 50px;
-    width: 100%;
-    text-align: center;
-}
-
-div.paginate ul {
-    margin: 0px;
-    padding: 0px;
-
-    line-height: 30px;
-    white-space: nowrap;
-}
-
-div.paginate li {
-    list-style-type: none;
-    display: inline;
-}
-
-div.paginate li *,
-div.paginate li strong,
-div.paginate li span {
-    padding: 7px 10px;
-}
-
-div.paginate li span {
-    color: #444444;
-}
-
-div.paginate li a:hover {
-    text-decoration: none;
-    background-color: #666666;
-}
-