3 # Copyright (C) 2010-2013 W. Trevor King <wking@tremily.us>
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.
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.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 CGI gallery server for a picture directory organized along::
24 | |-- another_picture.jpg
28 | |-- captioned_picture.jpg
29 | |-- captioned_picture.jpg.txt
36 Note that you can store a caption for ``<PICTURE>`` as plain text in
39 See RFC 3875 for more details on the the Common Gateway Interface.
41 This script can also be run as a Simple Common Gateway Interface
42 (SCGI) with the ``--scgi`` option.
45 import logging as _logging
46 import logging.handlers as _logging_handlers
48 import mimetypes as _mimetypes
50 import os.path as _os_path
51 import random as _random
53 import subprocess as _subprocess
55 import urllib.parse as _urllib_parse
56 except ImportError: # Python 2
57 import urlparse as _urllib_parse
58 import xml.sax.saxutils as _xml_sax_saxutils
64 IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.tif', '.tiff', '.png', '.gif']
65 VIDEO_EXTENSIONS = ['.mov', '.mp4', '.ogv']
66 STREAMING_TYPES = ['video/ogg']
67 RESPONSES = { # httplib takes half a second to load
72 LOG = _logging.getLogger('gallery.py')
73 LOG.addHandler(_logging.StreamHandler())
74 #LOG.addHandler(_logging_handlers.SysLogHandler())
75 LOG.handlers[0].setFormatter(
76 _logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
77 LOG.setLevel(_logging.DEBUG)
78 #LOG.setLevel(_logging.WARNING)
81 class CommandError(Exception):
82 def __init__(self, command, status, stdout=None, stderr=None):
83 strerror = ['Command failed (%d):\n %s\n' % (status, stderr),
84 'while executing\n %s' % str(command)]
85 super(CommandError, self).__init__('\n'.join(strerror))
86 self.command = command
92 class HTTPError(Exception):
93 def __init__(self, status, message=None, content=None):
95 message = RESPONSES[status]
96 super(HTTPError, self).__init__('{} {}'.format(status, message))
98 self.message = message
99 self.content = content
102 class ProcessingComplete(Exception):
106 def invoke(args, stdin=None, stdout=_subprocess.PIPE, stderr=_subprocess.PIPE,
107 expect=(0,), cwd=None, encoding=None):
109 expect should be a tuple of allowed exit codes. cwd should be
110 the directory from which the command will be executed. When
111 unicode_output == True, convert stdout and stdin strings to
112 unicode before returing them.
116 LOG.debug('{}$ {}'.format(cwd, ' '.join(args)))
118 q = _subprocess.Popen(args, stdin=_subprocess.PIPE, stdout=stdout,
119 stderr=stderr, cwd=cwd)
121 raise CommandError(args, status=e.args[0], stderr=e)
122 stdout,stderr = q.communicate(input=stdin)
124 LOG.debug('{:d}\n{}{}'.format(status, stdout, stderr))
125 if status not in expect:
126 raise CommandError(args, status, stdout, stderr)
127 return status, stdout, stderr
129 def is_image(filename):
130 for extension in IMAGE_EXTENSIONS:
131 if filename.lower().endswith(extension):
135 def is_video(filename):
136 for extension in IMAGE_EXTENSIONS:
137 if filename.lower().endswith(extension):
141 def image_base(filename):
142 parts = filename.rsplit('.', 1)
143 assert len(parts) == 2, parts
147 class CGIGalleryServer (object):
148 def __init__(self, base_path='.',
150 cache_path='/tmp/gallery-cache/',
151 serve_originals=True):
152 self._base_path = _os_path.abspath(base_path)
153 self._base_url = base_url
154 self._cache_path = cache_path
155 self._serve_originals = serve_originals
156 self._url_regexp = _re.compile('^[a-zA-Z0-9._/-]*$')
162 def _http_header(self, mime='text/html', status=200):
163 msg = RESPONSES[status]
164 header = ['Status: {:d} {}'.format(status, msg)]
165 if mime.startswith('text/'):
166 charset = '; charset=UTF-8'
169 header.append('Content-type: {}{}'.format(mime, charset))
170 return '\n'.join(header)
172 def _response(self, header=None, content='<h1>It works!</h1>',
175 header = self._http_header()
178 stream.write(content)
179 raise ProcessingComplete()
181 def _response_stream(self, header=None, content=None, stream=None,
183 LOG.debug('streaming response')
185 header = self._http_header()
188 stream.flush() # flush headers
190 chunk = content.read(chunk_size)
194 raise ProcessingComplete()
196 def _error(self, status=404, content=None, stream=None):
197 header = self._http_header(status=status)
199 content = RESPONSES[status]
200 self._response(header=header, content=content, stream=stream)
202 def validate_url(self, url, exists=True, directory=False):
203 LOG.debug('validating {} (exists={}, directory={})'.format(
204 repr(url), exists, directory))
207 elif (not self._url_regexp.match(url) or
208 url.startswith('/') or
211 LOG.error('invalid url')
214 path = _os_path.join(self._base_path, url)
216 if not _os_path.isdir(path):
217 LOG.error('nonexistent directory')
220 if not _os_path.isfile(path):
221 raise HTTPError(404, 'nonexistent file')
223 def serve(self, url=None, page=0, stream=None):
224 LOG.info('serving url {} (page {})'.format(url, page))
228 self.index(stream=stream)
229 elif url.endswith('random'):
231 url=url, stream=stream, max_width=500, max_height=500)
232 elif self.is_cacheable(url=url):
233 self.validate_url(url=url, exists=False)
234 self.cached(url=url, stream=stream)
236 self.validate_url(url=url, exists=False, directory=True)
237 self.page(url=url, page=page, stream=stream)
238 raise HTTPError(404, 'unexpected URL type')
239 except HTTPError as e:
241 self._error(e.status, content=e.content, stream=stream)
242 except ProcessingComplete:
245 def page_from_query(self, query=None, query_string=None):
246 """Extract the requested page from a query string
248 This is a helper method for CGIGalleryServer consumers.
249 Specify either query or query_string, but not both.
252 query = _urllib_parse.parse_qs(query_string)
256 if isinstance(pp, list):
264 def relative_url(self, url):
267 if not url.startswith(self._base_url):
268 message = 'cannot convert {} to a relative URL of {}'.format(
270 raise HTTPError(404, message)
271 if url == self._base_url:
273 return url[len(self._base_url):]
275 def _url(self, path):
276 relpath = _os_path.relpath(
277 _os_path.join(self._base_path, path), self._base_path)
280 elif path.endswith('/'):
282 return '{}{}'.format(self._base_url, relpath)
284 def _label(self, path):
285 dirname,base = _os_path.split(path)
286 if not base: # directory path ending with '/'
287 dirname,base = _os_path.split(dirname)
288 return base.replace('_', ' ').title()
290 def _link(self, path, text=None):
292 text = self._label(path)
293 return '<a href="{}">{}</a>'.format(self._url(path), text)
295 def _subdirs(self, path):
297 order = [d.strip() for d in
298 open(_os_path.join(path, '_order')).readlines()]
301 dirs = sorted(_os.listdir(path))
307 for d in start + dirs:
308 dirpath = _os_path.join(path, d)
309 if _os_path.isdir(dirpath):
312 def _images(self, path):
313 for p in sorted(_os.listdir(path)):
314 if p.startswith('.') or p.endswith('~'):
316 picture_path = _os_path.join(path, p)
317 if is_image(picture_path):
320 def index(self, stream=None):
321 LOG.debug('index page')
322 return self._directory(self._base_path, stream=stream)
324 def _original_url(self, url):
325 """Reverse thumbnail URL mapping
327 Returns (original_url, generating_callback, callback_kwargs).
329 base,extension = _os_path.splitext(url)
330 if extension in ['.png']:
332 root,width,height = base.rsplit('-', 2)
334 raise HTTPError(404, 'missing width/height in {}'.format(base))
338 except ValueError as e:
339 raise HTTPError(404, 'invalid width/height: {}'.format(e))
344 'max_height': height},
346 elif extension in VIDEO_EXTENSIONS:
349 getattr(self, '_{}'.format(extension), None),
352 raise HTTPError(404, 'no original URL for {}'.format(url))
354 def _thumb(self, image, max_width=None, max_height=None):
355 if not _os_path.exists(self._cache_path):
356 _os.makedirs(self._cache_path)
357 dirname,filename = _os_path.split(image)
358 reldir = _os_path.relpath(dirname, self._base_path)
359 cache_dir = _os_path.join(self._cache_path, reldir)
360 if not _os_path.isdir(cache_dir):
361 _os.makedirs(cache_dir)
362 extension = '-{:d}-{:d}.png'.format(max_width, max_height)
363 thumb_filename = image_base(filename)+extension
364 thumb_url = _os_path.join(dirname, thumb_filename)
365 thumb_path = _os_path.join(cache_dir, thumb_filename)
366 image_path = _os_path.join(self._base_path, image)
367 if not _os_path.isfile(image_path):
368 raise HTTPError(404, 'image path for thumbnail does not exist')
369 if (not _os_path.isfile(thumb_path)
370 or _os_path.getmtime(image_path) > _os_path.getmtime(thumb_path)):
371 invoke(['convert', '-format', 'png', '-strip', '-quality', '95',
373 '-thumbnail', '{:d}x{:d}'.format(max_width, max_height),
375 return (thumb_path, self._url(thumb_url))
377 def _mp4(self, video, *args):
378 if not video.endswith('.mov'):
379 raise HTTPError(404, "can't translate {} to MPEGv4".format(video))
380 dirname,filename = _os_path.split(video)
381 mp4_filename = image_base(filename) + '.mp4'
382 reldir = _os_path.relpath(dirname, self._base_path)
383 cache_dir = _os_path.join(self._cache_path, reldir)
384 if not _os_path.isdir(cache_dir):
385 _os.makedirs(cache_dir)
386 mp4_url = _os_path.join(dirname, mp4_filename)
387 mp4_path = _os_path.join(cache_dir, mp4_filename)
388 if not _os_path.isfile(video):
389 raise HTTPError(404, 'source video path does not exist')
390 if (not _os_path.isfile(mp4_path)
391 or _os_path.getmtime(video) > _os_path.getmtime(mp4_path)):
392 arg = ['ffmpeg', '-i', video, '-acodec', 'libfaac', '-aq', '200',
393 '-ac', '1', '-s', '640x480', '-vcodec', 'libx264',
394 '-preset', 'slower', '-vpre', 'ipod640', '-b', '800k',
395 '-bt', '800k', '-aspect', '640:480', '-threads', '0']
399 return (mp4_path, self._url(mp4_url))
401 def _ogv(self, video, *args):
402 if not video.endswith('.mov'):
403 LOG.error("can't translate {} to Ogg Video".format(video))
404 dirname,filename = _os_path.split(video)
405 ogv_filename = image_base(filename) + '.ogv'
406 reldir = _os_path.relpath(dirname, self._base_path)
407 cache_dir = _os_path.join(self._cache_path, reldir)
408 if not _os_path.isdir(cache_dir):
409 _os.makedirs(cache_dir)
410 ogv_url = _os_path.join(dirname, ogv_filename)
411 ogv_path = _os_path.join(cache_dir, ogv_filename)
412 if not _os_path.isfile(video):
413 LOG.error('source video path does not exist')
414 if (not _os_path.isfile(ogv_path)
415 or _os_path.getmtime(video) > _os_path.getmtime(ogv_path)):
416 arg = ['ffmpeg2theora', '--optimize']
418 arg.extend(['--output', ogv_path, video])
420 return (ogv_path, self._url(ogv_url))
422 def _get_image_caption(self, path):
423 caption_path = path + '.txt'
425 return open(caption_path, 'r').read()
429 def _get_image_video(self, path, fallback=None):
430 base_path = image_base(path)
431 for extension in VIDEO_EXTENSIONS:
432 video_path = base_path + extension
433 if _os_path.isfile(video_path):
434 return self._video(video_path, fallback=fallback)
437 def _captioned_video(self, path, href=None):
438 img = self._image(path, max_width=640, max_height=480)
439 caption = self._get_image_caption(path)
440 video = self._get_image_video(path, fallback=[img])
443 content.extend(video)
445 content.append('<p>{}</p>'.format(
446 self._link(path=href, text='gallery page')))
448 content.append(self._link(path=href, text=img))
452 caption = _xml_sax_saxutils.escape(caption)
453 content.append('<p>{}</p>'.format(caption))
456 def _video(self, video, fallback=None, **kwargs):
459 '<p>Your browser does not support the <video> tag, try',
460 'downloading the video and playing it in an external player.',
463 fallback = [' '+line for line in fallback]
464 ogv_path,ogv_url = self._ogv(video)
465 mp4_path,mp4_url = self._mp4(video)
468 (' <video preloads="none" controls="controls" '
469 'width="640" height="480">'),
470 ' <source src="{}"'.format(mp4_url),
471 (''' type='video/mp4; '''
472 '''codecs="avc1.42E01E, mp4a.40.2"' />'''),
473 ' <source src="{}"'.format(ogv_url),
474 ''' type='video/ogg; codecs="theora,vorbis"' />''',
479 ' <a href="{}">Ogg/Theora/Vorbis</a> or'.format(ogv_url),
480 (' <a href="{}">Mpeg4/H.264(ConstrainedBaselineProfile)/AAC</a>.'
485 def _image(self, image, **kwargs):
487 image_path,image_url = self._thumb(image, **kwargs)
490 sections = ['<img src="{}"'.format(image_url)]
491 caption = self._get_image_caption(path=image)
493 caption = _xml_sax_saxutils.quoteattr(
494 caption.replace('\n', ' ').strip())
496 'title={}'.format(caption),
497 'alt={}'.format(caption),
499 sections.append('/>')
500 return ' '.join(sections)
502 def _image_page(self, image):
503 return image_base(image) + '/'
505 def random(self, url=None, stream=None, **kwargs):
506 LOG.debug('random image')
507 if url.endswith('/random'):
508 url = url[:(-len('/random'))]
509 self.validate_url(url=url, directory=True, stream=stream)
510 base_dir = _os_path.join(self._base_path, url)
511 elif url == 'random':
512 base_dir = self._base_path
516 for dirpath,dirnames,filenames in _os.walk(base_dir):
517 for filename in filenames:
518 if is_image(filename):
519 images.append(_os_path.join(dirpath, filename))
521 self._response(content='<p>no images to choose from</p>',
523 image = _random.choice(images)
524 LOG.debug('selected random image {}'.format(image))
525 page = self._image_page(image)
526 content = self._captioned_video(path=image, href=page)
527 self._response(content='\n'.join(content), stream=stream)
529 def is_cacheable(self, url):
530 return is_image(url) or is_video(url)
532 def cached(self, url, stream=None):
533 LOG.debug('retrieving possibly cached item')
534 mime = _mimetypes.guess_type(url)[0]
536 raise HTTPError(404, 'unknown mime type for {}'.format(url))
537 cache_path = _os_path.join(self._cache_path, url)
538 original_path = _os_path.join(self._base_path, url)
540 if _os_path.isfile(cache_path):
541 LOG.debug('return cached item {}'.format(cache_path))
543 elif self._serve_originals and _os_path.isfile(original_path):
544 LOG.debug('return original item {}'.format(original_path))
547 LOG.debug('possibly create cached item {}'.format(cache_path))
548 original_url,callback,kwargs = self._original_url(url)
549 original_path = _os_path.join(self._base_path, original_url)
550 if callback and _os_path.isfile(original_path):
551 path,cache_url = callback(original_path, **kwargs)
555 content = open(path, 'rb')
558 raise HTTPError(404, 'item not found {}'.format(url))
559 header = self._http_header(mime=mime)
560 if mime in STREAMING_TYPES:
561 self._response_stream(
562 header=header, content=content, stream=stream)
563 content = content.read()
564 self._response(header=header, content=content, stream=stream)
566 def page(self, url, page=0, stream=None):
567 LOG.debug('HTML page {} {}'.format(url, page))
568 if not url.endswith('/'):
569 raise HTTPError(404, 'HTML page URLs must end with a slash')
570 abspath = _os_path.join(self._base_path, url)
571 if _os_path.isdir(abspath):
572 self._directory(path=abspath, page=page, stream=stream)
573 for extension in IMAGE_EXTENSIONS:
574 file_path = abspath[:-1] + extension
575 if _os_path.isfile(file_path):
576 self._page(path=file_path, stream=stream)
577 raise HTTPError(404, 'unknown HTML page {}'.format(url))
579 def _directory_header(self, path):
580 relpath = _os_path.relpath(path, self._base_path)
584 dirname,base = _os_path.split(dirname)
586 crumbs.insert(0, base)
588 links = [None] * len(crumbs)
589 for i,c in enumerate(crumbs):
590 if i < len(crumbs)-1:
592 links[i] = self._link(self._base_path, 'Gallery')
594 relpath = '/'.join(crumbs[1:i+1]) + '/'
595 fullpath = _os_path.join(self._base_path, relpath)
596 links[i] = self._link(path=fullpath)
601 links[i] = self._label(crumbs[i])
602 content = ['<h1>{}</h1>'.format(' '.join(links))]
605 def _directory_page_navigation(self, path, page, pages):
608 prev_page = path + '?pp={:d}'.format((page - 1) % pages + 1)
609 next_page = path + '?pp={:d}'.format((page + 1) % pages + 1)
611 '<div style="text-align: center;">',
613 self._link(prev_page, 'previous'),
614 '({:d} of {:d})'.format(page+1, pages),
615 self._link(next_page, 'next'),
620 def _directory_subdirs(self, path):
622 dirs = list(self._subdirs(path))
624 content.append('<ul>')
626 content.append(' <li>{}</li>'.format(self._link(d+'/')))
627 content.append('</ul>')
630 def _directory_images(self, path, images):
631 content = ['<table style="margin-left: auto; margin-right: auto;">']
634 page = self._image_page(image)
635 img = self._image(image, max_width=300, max_height=300)
636 link = self._link(page, img)
638 content.append(' <tr>')
640 ' <td style="text-align: center;">',
645 if column == self._columns:
646 content.append(' </tr>')
650 content.append(' </tr>')
651 content.append('</table>')
654 def _directory(self, path, page=0, stream=None):
655 LOG.debug('directory page {} {}'.format(path, page))
656 images = list(self._images(path))
657 images_per_page = self._rows * self._columns
658 pages = int(_math.ceil(float(len(images)) / images_per_page)) or 1
659 if page < 0 or page >= pages:
662 'page out of bounds for this gallery 0 <= {:d} < {:d}'.format(
664 first_image = images_per_page * page
665 images = images[first_image:first_image+images_per_page]
667 content.extend(self.header)
668 content.extend(self._directory_header(path))
669 nav = self._directory_page_navigation(path, page=page, pages=pages)
671 content.extend(self._directory_subdirs(path))
672 content.extend(self._directory_images(path, images=images))
674 content.extend(self.footer)
675 self._response(content='\n'.join(content), stream=stream)
677 def _page(self, path, stream=None):
678 LOG.debug('image page {}'.format(path))
679 gallery = _os_path.dirname(path)
680 images = list(self._images(gallery))
681 images_per_page = self._rows * self._columns
682 i = images.index(path)
683 page = i / images_per_page
684 gallery_page = '{}/?pp={:d}'.format(gallery, page + 1)
685 prev_page = self._image_page(images[i - 1])
686 next_page = self._image_page(images[(i + 1) % len(images)])
688 content.extend(self.header)
690 '<div style="text-align: center;">',
692 self._link(prev_page, 'previous'),
693 self._link(gallery_page, 'all'),
694 self._link(next_page, 'next'),
697 content.extend(self._captioned_video(path))
698 content.append('</div>')
699 content.extend(self.footer)
700 self._response(content='\n'.join(content), stream=stream)
703 def serve_cgi(server):
710 #cgitb.enable(display=0, logdir="/tmp/")
711 data = cgi.FieldStorage()
712 page = server.page_from_query(
713 query={key: data[key].getlist() for key in data.keys()})
716 if isinstance(p, list):
719 server.serve(url=url, page=page, stream=sys.stdout)
721 def serve_scgi(server, host='localhost', port=4000):
723 import scgi.scgi_server
725 class GalleryHandler(scgi.scgi_server.SCGIHandler):
726 def produce(self, env, bodysize, input, output):
727 #LOG.info(HTTP_USER_AGENT REQUEST_METHOD REMOTE_ADDR REQUEST_URI
728 url = env.get('DOCUMENT_URI', None)
729 page = server.page_from_query(
730 query_string=env.get('QUERY_STRING', ''))
733 url = server.relative_url(url=url)
734 except HTTPError as e:
736 server._error(e.status, content=e.content, stream=output)
737 except ProcessingComplete:
740 server.serve(url=url, page=page, stream=output)
742 s = scgi.scgi_server.SCGIServer(
743 handler_class=GalleryHandler, host=host, port=port)
744 LOG.info('serving SCGI on {}:{}'.format(host, port))
748 if __name__ == '__main__':
749 import argparse as _argparse
751 parser = _argparse.ArgumentParser(
752 description=__doc__, version=__version__,
753 formatter_class=_argparse.RawDescriptionHelpFormatter)
755 '--scgi', default=False, action='store_const', const=True,
756 help='Run as a SCGI server (vs. serving a single CGI call)')
758 '--port', default=4000, type=int,
759 help='Port to listen to (if runing as a SCGI server)')
761 '--base-path', default='.',
762 help='Path to the root gallery source')
764 '--base-url', default='/',
765 help='URL for the root gallery source')
767 '--shared-path', default=None,
768 help=('Optional path to the shared directory containing '
769 '`header.shtml` and `footer.shtml`'))
771 '--cache-path', default='/tmp/gallery-cache',
772 help='Path to the thumbnail and movie cache directory')
774 args = parser.parse_args()
776 s = CGIGalleryServer(
777 base_path=args.base_path, base_url=args.base_url,
778 cache_path=args.cache_path)
780 shared = args.shared_path
781 s.header = [open(_os_path.join(shared, 'header.shtml'), 'r').read()]
782 s.footer = [open(_os_path.join(shared, 'footer.shtml'), 'r').read()]
785 serve_scgi(server=s, port=args.port)