posts:dvd-backup: Fix "you're" -> "your" typo
[blog.git] / posts / gallery / gallery.py
1 #!/usr/bin/env python
2 #
3 # Copyright (C) 2010-2012 W. Trevor King <wking@drexel.edu>
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
19 """
20 CGI gallery server for a picture directory organized along::
21
22   pics
23   |-- some_directory
24   |   |-- a_picture.jpg
25   |   |-- another_picture.jpg
26   |   |-- ...
27   |-- another_directory
28   |   |-- a_picture.jpg
29   |   |-- captioned_picture.jpg
30   |   |-- captioned_picture.jpg.txt
31   |-- ...
32
33 With::
34
35   pics$ gallery.py
36
37 Note that you can store a caption for ``<PICTURE>`` as plain text in
38 ``<PICTURE>.txt``.
39
40 See RFC 3875 for more details on the the Common Gateway Interface.
41
42 This script can also be run as a Simple Common Gateway Interface
43 (SCGI) with the ``--scgi`` option.
44 """
45
46 import logging as _logging
47 import logging.handlers as _logging_handlers
48 import math as _math
49 import mimetypes as _mimetypes
50 import os as _os
51 import os.path as _os_path
52 import random as _random
53 import re as _re
54 import subprocess as _subprocess
55 import xml.sax.saxutils as _xml_sax_saxutils
56
57
58 __version__ = '0.5'
59
60
61 IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.tif', '.tiff', '.png', '.gif']
62 VIDEO_EXTENSIONS = ['.mov', '.mp4', '.ogv']
63 STREAMING_TYPES = ['video/ogg']
64 RESPONSES = {  # httplib takes half a second to load
65     200: 'OK',
66     404: 'Not Found',
67     }
68
69 LOG = _logging.getLogger('gallery.py')
70 LOG.addHandler(_logging.StreamHandler())
71 #LOG.addHandler(_logging_handlers.SysLogHandler())
72 LOG.handlers[0].setFormatter(
73     _logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
74 LOG.setLevel(_logging.DEBUG)
75 #LOG.setLevel(_logging.WARNING)
76
77
78 class CommandError(Exception):
79     def __init__(self, command, status, stdout=None, stderr=None):
80         strerror = ['Command failed (%d):\n  %s\n' % (status, stderr),
81                     'while executing\n  %s' % str(command)]
82         super(CommandError, self).__init__('\n'.join(strerror))
83         self.command = command
84         self.status = status
85         self.stdout = stdout
86         self.stderr = stderr
87
88
89 class HTTPError(Exception):
90     def __init__(self, status, message=None, content=None):
91         if message is None:
92             message = RESPONSES[status]
93         super(HTTPError, self).__init__('{} {}'.format(status, message))
94         self.status = status
95         self.message = message
96         self.content = content
97
98
99 class ProcessingComplete(Exception):
100     pass
101
102
103 def invoke(args, stdin=None, stdout=_subprocess.PIPE, stderr=_subprocess.PIPE,
104            expect=(0,), cwd=None, encoding=None):
105     """
106     expect should be a tuple of allowed exit codes.  cwd should be
107     the directory from which the command will be executed.  When
108     unicode_output == True, convert stdout and stdin strings to
109     unicode before returing them.
110     """
111     if cwd == None:
112         cwd = '.'
113     LOG.debug('{}$ {}'.format(cwd, ' '.join(args)))
114     try :
115         q = _subprocess.Popen(args, stdin=_subprocess.PIPE, stdout=stdout,
116                               stderr=stderr, cwd=cwd)
117     except OSError, e:
118         raise CommandError(args, status=e.args[0], stderr=e)
119     stdout,stderr = q.communicate(input=stdin)
120     status = q.wait()
121     LOG.debug('{:d}\n{}{}'.format(status, stdout, stderr))
122     if status not in expect:
123         raise CommandError(args, status, stdout, stderr)
124     return status, stdout, stderr
125
126 def is_image(filename):
127     for extension in IMAGE_EXTENSIONS:
128         if filename.lower().endswith(extension):
129             return True
130     return False
131
132 def is_video(filename):
133     for extension in IMAGE_EXTENSIONS:
134         if filename.lower().endswith(extension):
135             return True
136     return False
137
138 def image_base(filename):
139     parts = filename.rsplit('.', 1)
140     assert len(parts) == 2, parts
141     return parts[0]
142
143
144 class CGIGalleryServer (object):
145     def __init__(self, base_path='.',
146                  base_url='/',
147                  cache_path='/tmp/gallery-cache/',
148                  serve_originals=True):
149         self._base_path = _os_path.abspath(base_path)
150         self._base_url = base_url
151         self._cache_path = cache_path
152         self._serve_originals = serve_originals
153         self._url_regexp = _re.compile('^[a-zA-Z0-9._/-]*$')
154         self._rows = 3
155         self._columns = 3
156         self.header = []
157         self.footer = []
158
159     def _http_header(self, mime='text/html', status=200):
160         msg = RESPONSES[status]
161         header = ['Status: {:d} {}'.format(status, msg)]
162         if mime.startswith('text/'):
163             charset = '; charset=UTF-8'
164         else:
165             charset = ''
166         header.append('Content-type: {}{}'.format(mime, charset))
167         return '\n'.join(header)
168
169     def _response(self, header=None, content='<h1>It works!</h1>',
170                   stream=None):
171         if header is None:
172             header = self._http_header()
173         stream.write(header)
174         stream.write('\n\n')
175         stream.write(content)
176         raise ProcessingComplete()
177
178     def _response_stream(self, header=None, content=None, stream=None,
179                          chunk_size=1024):
180         LOG.debug('streaming response')
181         if header is None:
182             header = self._http_header()
183         stream.write(header)
184         stream.write('\n\n')
185         stream.flush()  # flush headers
186         while True:
187             chunk = content.read(chunk_size)
188             if not chunk:
189                 break
190             stream.write(chunk)
191         raise ProcessingComplete()
192
193     def _error(self, status=404, content=None, stream=None):
194         header = self._http_header(status=status)
195         if content is None:
196             content = RESPONSES[status]
197         self._response(header=header, content=content, stream=stream)
198
199     def validate_url(self, url, exists=True, directory=False):
200         LOG.debug('validating {} (exists={}, directory={})'.format(
201                 repr(url), exists, directory))
202         if url is None:
203             return
204         elif (not self._url_regexp.match(url) or
205             url.startswith('/') or
206             '..' in url
207             ):
208             LOG.error('invalid url')
209             raise HTTPError(404)
210         if exists:
211             path = _os_path.join(self._base_path, url)
212             if directory:
213                 if not _os_path.isdir(path):
214                     LOG.error('nonexistent directory')
215                     raise HTTPError(404)
216             else:
217                 if not _os_path.isfile(path):
218                     raise HTTPError(404, 'nonexistent file')
219
220     def serve(self, url=None, page=0, stream=None):
221         LOG.info('serving url {} (page {})'.format(url, page))
222         try:
223             try:
224                 if url is None:
225                     self.index(stream=stream)
226                 elif url.endswith('random'):
227                     self.random(
228                         url=url, stream=stream, max_width=500, max_height=500)
229                 elif self.is_cacheable(url=url):
230                     self.validate_url(url=url, exists=False)
231                     self.cached(url=url, stream=stream)
232                 else:
233                     self.validate_url(url=url, exists=False, directory=True)
234                     self.page(url=url, page=page, stream=stream)
235                 raise HTTPError(404, 'unexpected URL type')
236             except HTTPError as e:
237                 LOG.error(e.message)
238                 self._error(e.status, content=e.content, stream=stream)
239         except ProcessingComplete:
240             pass
241
242     def relative_url(self, url):
243         if url is None:
244             return url
245         if not url.startswith(self._base_url):
246             message = 'cannot convert {} to a relative URL of {}'.format(
247                 url, self._base_url)
248             raise HTTPError(404, message)
249         if url == self._base_url:
250             return None
251         return url[len(self._base_url):]
252
253     def _url(self, path):
254         relpath = _os_path.relpath(
255             _os_path.join(self._base_path, path), self._base_path)
256         if relpath == '.':
257             relpath = ''
258         elif path.endswith('/'):
259             relpath += '/'
260         return '{}{}'.format(self._base_url, relpath)
261
262     def _label(self, path):
263         dirname,base = _os_path.split(path)
264         if not base:  # directory path ending with '/'
265             dirname,base = _os_path.split(dirname)
266         return base.replace('_', ' ').title()
267
268     def _link(self, path, text=None):
269         if text is None:
270             text = self._label(path)
271         return '<a href="{}">{}</a>'.format(self._url(path), text)
272
273     def _subdirs(self, path):
274         try:
275             order = [d.strip() for d in
276                      open(_os_path.join(path, '_order')).readlines()]
277         except IOError:
278             order = []
279         dirs = sorted(_os.listdir(path))
280         start = []
281         for d in order:
282             if d in dirs:
283                 start.append(d)
284                 dirs.remove(d)
285         for d in start + dirs:
286             dirpath = _os_path.join(path, d)
287             if _os_path.isdir(dirpath):
288                 yield dirpath
289
290     def _images(self, path):
291         for p in sorted(_os.listdir(path)):
292             if p.startswith('.') or p.endswith('~'):
293                 continue
294             picture_path = _os_path.join(path, p)
295             if is_image(picture_path):
296                 yield picture_path
297
298     def index(self, stream=None):
299         LOG.debug('index page')
300         return self._directory(self._base_path, stream=stream)
301
302     def _original_url(self, url):
303         """Reverse thumbnail URL mapping
304
305         Returns (original_url, generating_callback, callback_kwargs).
306         """
307         base,extension = _os_path.splitext(url)
308         if extension in ['.png']:
309             try:
310                 root,width,height = base.rsplit('-', 2)
311             except ValueError:
312                 raise HTTPError(404, 'missing width/height in {}'.format(base))
313             try:
314                 width = int(width)
315                 height = int(height)
316             except ValueError as e:
317                 raise HTTPError(404, 'invalid width/height: {}'.format(e))
318             return (
319                 root + '.jpg',
320                 self._thumb, 
321                 {'max_width': width,
322                  'max_height': height},
323                 )
324         elif extension in VIDEO_EXTENSIONS:
325             return (
326                 base + '.mov',
327                 getattr(self, '_{}'.format(extension), None),
328                 {},
329                 )
330         raise HTTPError(404, 'no original URL for {}'.format(url))
331
332     def _thumb(self, image, max_width=None, max_height=None):
333         if not _os_path.exists(self._cache_path):
334             _os.makedirs(self._cache_path)
335         dirname,filename = _os_path.split(image)
336         reldir = _os_path.relpath(dirname, self._base_path)
337         cache_dir = _os_path.join(self._cache_path, reldir)
338         if not _os_path.isdir(cache_dir):
339             _os.makedirs(cache_dir)
340         extension = '-{:d}-{:d}.png'.format(max_width, max_height)
341         thumb_filename = image_base(filename)+extension
342         thumb_url = _os_path.join(dirname, thumb_filename)
343         thumb_path = _os_path.join(cache_dir, thumb_filename)
344         image_path = _os_path.join(self._base_path, image)
345         if not _os_path.isfile(image_path):
346             raise HTTPError(404, 'image path for thumbnail does not exist')
347         if (not _os_path.isfile(thumb_path)
348             or _os_path.getmtime(image_path) > _os_path.getmtime(thumb_path)):
349             invoke(['convert', '-format', 'png', '-strip', '-quality', '95',
350                     image_path,
351                     '-thumbnail', '{:d}x{:d}'.format(max_width, max_height),
352                     thumb_path])
353         return (thumb_path, self._url(thumb_url))
354
355     def _mp4(self, video, *args):
356         if not video.endswith('.mov'):
357             raise HTTPError(404, "can't translate {} to MPEGv4".format(video))
358         dirname,filename = _os_path.split(video)
359         mp4_filename = image_base(filename) + '.mp4'
360         reldir = _os_path.relpath(dirname, self._base_path)
361         cache_dir = _os_path.join(self._cache_path, reldir)
362         if not _os_path.isdir(cache_dir):
363             _os.makedirs(cache_dir)
364         mp4_url = _os_path.join(dirname, mp4_filename)
365         mp4_path = _os_path.join(cache_dir, mp4_filename)
366         if not _os_path.isfile(video):
367             raise HTTPError(404, 'source video path does not exist')
368         if (not _os_path.isfile(mp4_path)
369             or _os_path.getmtime(video) > _os_path.getmtime(mp4_path)):
370             arg = ['ffmpeg', '-i', video, '-acodec', 'libfaac', '-aq', '200',
371                    '-ac', '1', '-s', '640x480', '-vcodec', 'libx264',
372                    '-preset', 'slower', '-vpre', 'ipod640', '-b', '800k',
373                    '-bt', '800k', '-aspect', '640:480', '-threads', '0']
374             arg.extend(args)
375             arg.append(mp4_path)
376             invoke(arg)
377         return (mp4_path, self._url(mp4_url))
378
379     def _ogv(self, video, *args):
380         if not video.endswith('.mov'):
381             LOG.error("can't translate {} to Ogg Video".format(video))
382         dirname,filename = _os_path.split(video)
383         ogv_filename = image_base(filename) + '.ogv'
384         reldir = _os_path.relpath(dirname, self._base_path)
385         cache_dir = _os_path.join(self._cache_path, reldir)
386         if not _os_path.isdir(cache_dir):
387             _os.makedirs(cache_dir)
388         ogv_url = _os_path.join(dirname, ogv_filename)
389         ogv_path = _os_path.join(cache_dir, ogv_filename)
390         if not _os_path.isfile(video):
391             LOG.error('source video path does not exist')
392         if (not _os_path.isfile(ogv_path)
393             or _os_path.getmtime(video) > _os_path.getmtime(ogv_path)):
394             arg = ['ffmpeg2theora', '--optimize']
395             arg.extend(args)
396             arg.extend(['--output', ogv_path, video])
397             invoke(arg)
398         return (ogv_path, self._url(ogv_url))
399
400     def _get_image_caption(self, path):
401         caption_path = path + '.txt'
402         try:
403             return open(caption_path, 'r').read()
404         except IOError:
405             return None
406
407     def _get_image_video(self, path, fallback=None):
408         base_path = image_base(path)
409         for extension in VIDEO_EXTENSIONS:
410             video_path = base_path + extension
411             if _os_path.isfile(video_path):
412                 return self._video(video_path, fallback=fallback)
413         return None
414
415     def _captioned_video(self, path, href=None):
416         img = self._image(path, max_width=640, max_height=480)
417         caption = self._get_image_caption(path)
418         video = self._get_image_video(path, fallback=[img])
419         content = []
420         if video:
421             content.extend(video)
422             if href:
423                 content.append('<p>{}</p>'.format(
424                         self._link(path=href, text='gallery page')))
425         elif href:
426             content.append(self._link(path=href, text=img))
427         else:
428             content.append(img)
429         if caption:
430             caption = _xml_sax_saxutils.escape(caption)
431             content.append('<p>{}</p>'.format(caption))
432         return content
433
434     def _video(self, video, fallback=None, **kwargs):
435         if fallback is None:
436             fallback = [
437                 '<p>Your browser does not support the &lt;video&gt; tag, try',
438                 'downloading the video and playing it in an external player.',
439                 '</p>',
440                 ]
441         fallback = ['    '+line for line in fallback]
442         ogv_path,ogv_url = self._ogv(video)
443         mp4_path,mp4_url = self._mp4(video)
444         return [
445             '<p>',
446             ('  <video preloads="none" controls="controls" '
447              'width="640" height="480">'),
448             '    <source src="{}"'.format(mp4_url),
449             ('''            type='video/mp4; '''
450              '''codecs="avc1.42E01E, mp4a.40.2"' />'''),
451             '    <source src="{}"'.format(ogv_url),
452             '''            type='video/ogg; codecs="theora,vorbis"' />''',
453             ] + fallback + [
454             '  </video>',
455             '</p>',
456             '<p>Download as',
457             '  <a href="{}">Ogg/Theora/Vorbis</a> or'.format(ogv_url),
458             ('  <a href="{}">Mpeg4/H.264(ConstrainedBaselineProfile)/AAC</a>.'
459              ).format(mp4_url),
460             '<p>',
461             ]
462
463     def _image(self, image, **kwargs):
464         if kwargs:
465             image_path,image_url = self._thumb(image, **kwargs)
466         else:
467             image_url = image
468         sections = ['<img src="{}"'.format(image_url)]
469         caption = self._get_image_caption(path=image)
470         if caption:
471             caption = _xml_sax_saxutils.quoteattr(
472                 caption.replace('\n', ' ').strip())
473             sections.extend([
474                     'title={}'.format(caption),
475                     'alt={}'.format(caption),
476                     ])
477         sections.append('/>')
478         return ' '.join(sections)
479
480     def _image_page(self, image):
481         return image_base(image) + '/'
482
483     def random(self, url=None, stream=None, **kwargs):
484         LOG.debug('random image')
485         if url.endswith('/random'):
486             url = url[:(-len('/random'))]
487             self.validate_url(url=url, directory=True, stream=stream)
488             base_dir = _os_path.join(self._base_path, url)
489         elif url == 'random':
490             base_dir = self._base_path
491         else:
492             raise HTTPError(404)
493         images = []
494         for dirpath,dirnames,filenames in _os.walk(base_dir):
495             for filename in filenames:
496                 if is_image(filename):
497                     images.append(_os_path.join(dirpath, filename))
498         if not images:
499             self._response(content='<p>no images to choose from</p>',
500                            stream=stream)
501         image = _random.choice(images)
502         LOG.debug('selected random image {}'.format(image))
503         page = self._image_page(image)
504         content = self._captioned_video(path=image, href=page)
505         self._response(content='\n'.join(content), stream=stream)
506
507     def is_cacheable(self, url):
508         return is_image(url) or is_video(url)
509
510     def cached(self, url, stream=None):
511         LOG.debug('retrieving possibly cached item')
512         mime = _mimetypes.guess_type(url)[0]
513         if mime is None:
514             raise HTTPError(404, 'unknown mime type for {}'.format(url))
515         cache_path = _os_path.join(self._cache_path, url)
516         original_path = _os_path.join(self._base_path, url)
517         path = None
518         if _os_path.isfile(cache_path):
519             LOG.debug('return cached item {}'.format(cache_path))
520             path = cache_path
521         elif self._serve_originals and _os_path.isfile(original_path):
522             LOG.debug('return original item {}'.format(original_path))
523             path = original_path
524         else:
525             LOG.debug('possibly create cached item {}'.format(cache_path))
526             original_url,callback,kwargs = self._original_url(url)
527             original_path = _os_path.join(self._base_path, original_url)
528             if callback and _os_path.isfile(original_path):
529                 path,cache_url = callback(original_path, **kwargs)
530         if not path:
531             raise HTTPError(404)
532         try:
533             content = open(path, 'rb')
534         except IOError as e:
535             LOG.error(e)
536             raise HTTPError(404, 'item not found {}'.format(url))
537         header = self._http_header(mime=mime)
538         if mime in STREAMING_TYPES:
539             self._response_stream(
540                 header=header, content=content, stream=stream)
541         content = content.read()
542         self._response(header=header, content=content, stream=stream)
543
544     def page(self, url, page=0, stream=None):
545         LOG.debug('HTML page {} {}'.format(url, page))
546         if not url.endswith('/'):
547             raise HTTPError(404, 'HTML page URLs must end with a slash')
548         abspath = _os_path.join(self._base_path, url)
549         if _os_path.isdir(abspath):
550             self._directory(path=abspath, page=page, stream=stream)
551         for extension in IMAGE_EXTENSIONS:
552             file_path = abspath[:-1] + extension
553             if _os_path.isfile(file_path):
554                 self._page(path=file_path, stream=stream)
555         raise HTTPError(404, 'unknown HTML page {}'.format(url))
556
557     def _directory_header(self, path):
558         relpath = _os_path.relpath(path, self._base_path)
559         crumbs = []
560         dirname = relpath
561         while dirname:
562             dirname,base = _os_path.split(dirname)
563             if base != '.':
564                 crumbs.insert(0, base)
565         crumbs.insert(0, '')
566         links = [None] * len(crumbs)
567         for i,c in enumerate(crumbs):
568             if i < len(crumbs)-1:
569                 if i == 0:
570                     links[i] = self._link(self._base_path, 'Gallery')
571                 else:
572                     relpath = '/'.join(crumbs[1:i+1]) + '/'
573                     fullpath = _os_path.join(self._base_path, relpath)
574                     links[i] = self._link(path=fullpath)
575             else:
576                 if i == 0:
577                     links[i] = 'Gallery'
578                 else:
579                     links[i] = self._label(crumbs[i])
580         content = ['<h1>{}</h1>'.format(' '.join(links))]
581         return content
582
583     def _directory_page_navigation(self, path, page, pages):
584         if pages <= 1:
585             return []
586         prev_page = path + '?pp={:d}'.format((page - 1) % pages + 1)
587         next_page = path + '?pp={:d}'.format((page + 1) % pages + 1)
588         return [
589             '<div style="text-align: center;">',
590             '<p>',
591             self._link(prev_page, 'previous'),
592             '({:d} of {:d})'.format(page+1, pages),
593             self._link(next_page, 'next'),
594             '</p>',
595             '</div>', 
596            ]
597
598     def _directory_subdirs(self, path):
599         content = []
600         dirs = list(self._subdirs(path))
601         if dirs:
602             content.append('<ul>')
603             for d in dirs:
604                 content.append('  <li>{}</li>'.format(self._link(d+'/')))
605             content.append('</ul>')
606         return content
607
608     def _directory_images(self, path, images):
609         content = ['<table style="margin-left: auto; margin-right: auto;">']
610         column = 0
611         for image in images:
612             page = self._image_page(image)
613             img = self._image(image, max_width=300, max_height=300)
614             link = self._link(page, img)
615             if column == 0:
616                 content.append('  <tr>')
617             content.extend([
618                     '    <td style="text-align: center;">',
619                     '      {}'.format(link),
620                     '    </td>',
621                     ])
622             column += 1
623             if column == self._columns:
624                 content.append('  </tr>')
625                 column = 0
626         if column != 0:
627             #content.extend()
628             content.append('  </tr>')
629         content.append('</table>')
630         return content
631
632     def _directory(self, path, page=0, stream=None):
633         LOG.debug('directory page {} {}'.format(path, page))
634         images = list(self._images(path))
635         images_per_page = self._rows * self._columns
636         pages = int(_math.ceil(float(len(images)) / images_per_page)) or 1
637         if page < 0 or page >= pages:
638             raise HTTPError(
639                 404,
640                 'page out of bounds for this gallery 0 <= {:d} < {:d}'.format(
641                     page, pages))
642         first_image = images_per_page * page
643         images = images[first_image:first_image+images_per_page]
644         content = []
645         content.extend(self.header)
646         content.extend(self._directory_header(path))
647         nav = self._directory_page_navigation(path, page=page, pages=pages)
648         content.extend(nav)
649         content.extend(self._directory_subdirs(path))
650         content.extend(self._directory_images(path, images=images))
651         content.extend(nav)
652         content.extend(self.footer)
653         self._response(content='\n'.join(content), stream=stream)
654
655     def _page(self, path, stream=None):
656         LOG.debug('image page {}'.format(path))
657         gallery = _os_path.dirname(path)
658         images = list(self._images(gallery))
659         images_per_page = self._rows * self._columns
660         i = images.index(path)
661         page = i / images_per_page
662         gallery_page = '{}/?pp={:d}'.format(gallery, page + 1)
663         prev_page = self._image_page(images[i - 1])
664         next_page = self._image_page(images[(i + 1) % len(images)])
665         content = []
666         content.extend(self.header)
667         content.extend([
668                 '<div style="text-align: center;">',
669                 '<p>',
670                 self._link(prev_page, 'previous'),
671                 self._link(gallery_page, 'all'),
672                 self._link(next_page, 'next'),
673                 '</p>',
674                 ])
675         content.extend(self._captioned_video(path))
676         content.append('</div>')
677         content.extend(self.footer)
678         self._response(content='\n'.join(content), stream=stream)
679
680
681 def serve_cgi(server):
682     import cgi
683     import cgitb
684     import sys
685
686     url=None
687     page=0
688     cgitb.enable()
689     #cgitb.enable(display=0, logdir="/tmp/")
690     data = cgi.FieldStorage()
691     if 'p' in data:
692         p = data['p']
693         if isinstance(p, list):
694             p = p[0]
695         url = p.value
696     if 'pp' in data:
697         try:
698             page = int(data['pp'].value) - 1
699         except ValueError:
700             pass
701     server.serve(url=url, page=page, stream=sys.stdout)
702
703 def serve_scgi(server, host='localhost', port=4000):
704     import scgi
705     import scgi.scgi_server
706     import urlparse
707
708     class GalleryHandler(scgi.scgi_server.SCGIHandler):
709         def produce(self, env, bodysize, input, output):
710             #LOG.info(HTTP_USER_AGENT REQUEST_METHOD REMOTE_ADDR REQUEST_URI
711             url = env.get('DOCUMENT_URI', None)
712             page = 0
713             data = urlparse.parse_qs(env.get('QUERY_STRING', ''))
714             if 'pp' in data:
715                 pp = data['pp']
716                 if isinstance(pp, list):
717                     pp = pp[0]
718                 try:
719                     page = int(pp) - 1
720                 except ValueError:
721                     pass
722             try:
723                 try:
724                     url = server.relative_url(url=url)
725                 except HTTPError as e:
726                     LOG.error(e.message)
727                     server._error(e.status, content=e.content, stream=stream)
728             except ProcessingComplete:
729                 pass
730             else:
731                 server.serve(url=url, page=page, stream=output)
732
733     s = scgi.scgi_server.SCGIServer(
734         handler_class=GalleryHandler, host=host, port=port)
735     LOG.info('serving SCGI on {}:{}'.format(host, port))
736     s.serve()
737
738
739 if __name__ == '__main__':
740     import argparse as _argparse
741
742     parser = _argparse.ArgumentParser(
743         description=__doc__, version=__version__,
744         formatter_class=_argparse.RawDescriptionHelpFormatter)
745     parser.add_argument(
746         '--scgi', default=False, action='store_const', const=True,
747         help='Run as a SCGI server (vs. serving a single CGI call)')
748     parser.add_argument(
749         '--port', default=4000, type=int,
750         help='Port to listen to (if runing as a SCGI server)')
751     parser.add_argument(
752         '--base-path', default='.',
753         help='Path to the root gallery source')
754     parser.add_argument(
755         '--base-url', default='/',
756         help='URL for the root gallery source')
757     parser.add_argument(
758         '--shared-path', default=None,
759         help=('Optional path to the shared directory containing '
760               '`header.shtml` and `footer.shtml`'))
761     parser.add_argument(
762         '--cache-path', default='/tmp/gallery-cache',
763         help='Path to the thumbnail and movie cache directory')
764
765     args = parser.parse_args()
766
767     s = CGIGalleryServer(
768         base_path=args.base_path, base_url=args.base_url,
769         cache_path=args.cache_path)
770     if args.shared_path:
771         shared = args.shared_path
772         s.header = [open(_os_path.join(shared, 'header.shtml'), 'r').read()]
773         s.footer = [open(_os_path.join(shared, 'footer.shtml'), 'r').read()]
774
775     if args.scgi:
776         serve_scgi(server=s, port=args.port)
777     else:
778         serve_cgi(server=s)