Mercurial > hg > index.fcgi > www > www-1
view pics2/pics_app.py @ 71:6318de36e334
pics2: limit access to index
author | paulo |
---|---|
date | Wed, 28 Oct 2015 00:57:23 -0700 |
parents | b7966ae653f2 |
children | ec48011dca1e |
line source
1 import os
2 import re
3 import glob
4 import traceback
5 import datetime
6 import random
7 import urlparse
9 import html
11 import logging
12 logging.basicConfig(
13 level=logging.INFO,
14 filename="_LOG",
15 format="%(asctime)s %(levelname)-8s %(message)s",
16 )
19 def _lahat():
20 ret = None
22 try:
23 with open("_lahat") as lahat_f:
24 ret = lahat_f.read().strip()
25 except IOError:
26 pass
28 return ret
31 def _is_pics_dir(dirpath):
32 return os.path.exists(os.path.join(dirpath, "_picsroot"))
35 def _get_dir_dt(dirpath):
36 if _is_pics_dir(dirpath):
37 dirpath = os.path.join(dirpath, "_picsroot")
39 return datetime.datetime.fromtimestamp(os.stat(dirpath).st_mtime)
42 def _format_dt(dt):
43 return dt.strftime("%Y-%m-%d")
46 def _parse_path_info(path_info):
47 ppi = path_info.split(os.sep)
48 if len(ppi) > 1 and ppi[-1] == '':
49 del ppi[-1]
51 return ppi
54 def _numeric_pad_basename(path, maxdigits=20):
55 return os.path.basename(path).zfill(maxdigits)
58 def _get_images(d):
59 exts = [".jpg", ".webm"]
61 thumb_fns = glob.glob(os.path.join(d, "thumbs", "*.jpg"))
62 thumb_fns = sorted(thumb_fns, key=_numeric_pad_basename)
63 logging.debug("thumb_fns = %s" % thumb_fns)
65 browse_dir = os.path.join(d, "browse")
66 browse_contents = set(os.listdir(browse_dir))
67 logging.debug("browse_contents = %s" % browse_contents)
69 browse_fns = []
70 for i in thumb_fns:
71 i_basename = os.path.splitext(os.path.basename(i))[0]
72 try:
73 for j in exts:
74 browse_fn_basename = i_basename + j
75 if browse_fn_basename in browse_contents:
76 browse_fns.append(os.path.join(browse_dir, browse_fn_basename))
77 raise StopIteration
78 except StopIteration:
79 pass
80 else:
81 raise RuntimeError("Cannot find browse image for %s" % i)
82 logging.debug("browse_fns = %s" % browse_fns)
84 return zip(thumb_fns, browse_fns)
87 class Main:
88 def _get_pics_url(self, dirpath):
89 script_name = self._environ.get("SCRIPT_NAME", '')
90 return os.path.normpath(os.path.join(os.path.dirname(script_name), dirpath))
93 def _get_app_url(self, dirpath):
94 script_name = self._environ.get("SCRIPT_NAME", '')
95 return os.path.normpath(os.path.join(script_name, dirpath))
98 def _get_standard_html_doc(self, title):
99 root = html.HTML("html")
101 header = root.header
102 header.link(rel="stylesheet", type="text/css", href=self._get_pics_url("index.css"))
103 header.title(title)
105 body = root.body
106 body.h1(title)
108 return (root, header, body)
111 def _go_thumbnail_links_to_browse_imgs_html_body(self, body, t, b, a_args={}, img_args={}):
112 thumb_img_url = self._get_pics_url(t)
113 browse_url = self._get_app_url(b)
115 a = body.a(href=browse_url, **a_args)
116 a.img(src=thumb_img_url, **img_args)
118 body.text(' ')
121 def _go_browse_image_html_body(self, body, img):
122 browse_img_url = self._get_pics_url(img)
124 ext = os.path.splitext(img)[1]
125 if ext == ".webm":
126 body.video(src=browse_img_url, autoplay="true", loop="true")
127 else:
128 body.img(src=browse_img_url)
131 def __init__(self, environ):
132 self._environ = environ
133 self._page_func = None
134 self._show_index = False
136 #logging.debug("environ = %s" % (sorted(self._environ.items(), key=lambda x: x[0]),))
137 logging.debug("environ['PATH_INFO'] = %s" % self._environ["PATH_INFO"])
138 logging.debug("environ['SCRIPT_NAME'] = %s" % self._environ["SCRIPT_NAME"])
139 logging.debug("environ['QUERY_STRING'] = %s" % self._environ["QUERY_STRING"])
141 pi = self._environ["PATH_INFO"]
142 ppi = _parse_path_info(pi)
143 logging.debug("ppi = %s" % ppi)
145 if len(ppi) < 1 or ppi[0] != '':
146 raise AssertionError("Parsed path length must start empty: " + pi)
148 self._qs = urlparse.parse_qs(self._environ["QUERY_STRING"])
149 logging.debug("self._qs = %s" % self._qs)
150 if self._qs.get("lahat", [''])[0] == _lahat():
151 self._show_index = True
153 if len(ppi) >= 2 and _is_pics_dir(ppi[1]):
154 if len(ppi) == 2:
155 self._page_func = self.page_thumbs
156 elif len(ppi) >= 4 and ppi[2] == "browse" and os.path.exists(os.path.join(*ppi)):
157 self._page_func = self.page_browse
158 elif len(ppi) == 1 and self._show_index:
159 self._page_func = self.page_index
161 if self._page_func is None:
162 raise RuntimeError("Cannot find path: " + pi)
165 def page(self):
166 return unicode(self._page_func()).encode("utf-8")
169 def page_index(self):
170 n = 5 # number of thumbnails to display
172 (html_root, html_header, html_body) = self._get_standard_html_doc("Pictures")
174 pics_dirs = []
175 for i in os.listdir('.'):
176 if _is_pics_dir(i):
177 pics_dirs.append((i, _get_dir_dt(i)))
179 pics_dirs.sort(key=lambda x: x[1], reverse=True)
181 for (d, dt) in pics_dirs:
182 html_body.h2.a(d, href=self._get_app_url(d))
183 html_body.h3(_format_dt(dt))
185 imgs = _get_images(d)
186 imgs_idx = [(i, img) for (i, img) in enumerate(imgs)]
188 sampled_imgs_idx = random.sample(imgs_idx, min(len(imgs_idx), n))
189 sampled_imgs_idx.sort(key=lambda x: x[0])
191 html_p = html_body.p
192 for (i, (t, b)) in sampled_imgs_idx:
193 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, b)
195 return html_root
198 def page_thumbs(self):
199 ppi = _parse_path_info(self._environ["PATH_INFO"])
200 d = os.path.join(*ppi)
201 (html_root, html_header, html_body) = self._get_standard_html_doc(d)
203 from_img = None
204 if "from" in self._qs:
205 from_img = self._qs["from"][0]
207 html_p = html_body.p
208 for (t, b) in _get_images(d):
209 if from_img is not None and b == from_img:
210 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, b, img_args={"klass":"sel2", "id":"selected"})
211 else:
212 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, b)
214 # TODO: fix me
215 #if self._show_index:
216 # html_body.a("(Other pictures)", href=self._get_app_url(''))
218 return html_root
221 def page_browse(self):
222 ppi = _parse_path_info(self._environ["PATH_INFO"])
223 d = os.path.join(*ppi[:2])
224 imgs = _get_images(d)
225 img = os.path.join(*ppi)
227 # thumbnail preview ribbon
228 w = 7 # must be odd
229 v = w/2
230 imgs_circ = [None] * w
231 x = None
232 n = len(imgs)
233 for (i, (t, b)) in enumerate(imgs):
234 if b == img:
235 x = i + 1
236 imgs_circ[v] = (t, b)
237 for j in range(1, v + 1):
238 if (i + j) < n: imgs_circ[v + j] = imgs[i + j]
239 if (i - j) >= 0: imgs_circ[v - j] = imgs[i - j]
241 break
243 if x is None:
244 raise AssertionError
246 (html_root, html_header, html_body) = self._get_standard_html_doc(u"%s \u2014 %s of %s" % (d, x, len(imgs)))
248 html_header.script('', type="text/javascript", src=self._get_pics_url("np_keys.js"))
250 self._go_browse_image_html_body(html_body.p, img)
252 logging.debug("imgs_circ = %s" % imgs_circ)
254 html_p = html_body.p
255 for (i, img_c) in enumerate(imgs_circ):
256 if img_c is not None:
257 (t, b) = img_c
258 a_args = {}
259 img_args = {}
260 if b == img:
261 a_args = {"id": "up"}
262 img_args = {"klass": "sel"}
263 b = "%s?from=%s#selected" % (d, img)
264 elif i == v + 1:
265 a_args = {"id": "next"}
266 elif i == v - 1:
267 a_args = {"id": "prev"}
269 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, b, a_args, img_args)
271 return html_root
274 def app(environ, start_response):
275 response_code = "500 Internal Server Error"
276 response_type = "text/plain; charset=UTF-8"
278 try:
279 response_body = Main(environ).page()
280 response_code = "200 OK"
281 response_type = "text/html; charset=UTF-8"
282 except:
283 response_body = traceback.format_exc()
285 response_headers = [
286 ("Content-Type", response_type),
287 ("Content-Length", str(len(response_body))),
288 ]
290 start_response(response_code, response_headers)
292 return [response_body]