view pics2/pics_app.py @ 76:51f0da3da721

myrss: fix Atom link parsing
author paulo
date Thu, 12 May 2016 01:04:10 -0700
parents 6318de36e334
children d7d67887102f
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={}, lazyload=False):
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 if lazyload:
117 img_args = dict(img_args)
118 img_args["data-src"] = thumb_img_url
119 a.img(**img_args)
120 else:
121 a.img(src=thumb_img_url, **img_args)
123 body.text(' ')
126 def _go_browse_image_html_body(self, body, img):
127 browse_img_url = self._get_pics_url(img)
129 ext = os.path.splitext(img)[1]
130 if ext == ".webm":
131 body.video(src=browse_img_url, autoplay="true", loop="true")
132 else:
133 body.img(src=browse_img_url)
136 def __init__(self, environ):
137 self._environ = environ
138 self._page_func = None
139 self._show_index = False
141 #logging.debug("environ = %s" % (sorted(self._environ.items(), key=lambda x: x[0]),))
142 logging.debug("environ['PATH_INFO'] = %s" % self._environ["PATH_INFO"])
143 logging.debug("environ['SCRIPT_NAME'] = %s" % self._environ["SCRIPT_NAME"])
144 logging.debug("environ['QUERY_STRING'] = %s" % self._environ["QUERY_STRING"])
146 pi = self._environ["PATH_INFO"]
147 ppi = _parse_path_info(pi)
148 logging.debug("ppi = %s" % ppi)
150 if len(ppi) < 1 or ppi[0] != '':
151 raise AssertionError("Parsed path length must start empty: " + pi)
153 self._qs = urlparse.parse_qs(self._environ["QUERY_STRING"])
154 logging.debug("self._qs = %s" % self._qs)
155 if self._qs.get("lahat", [''])[0] == _lahat():
156 self._show_index = True
158 if len(ppi) >= 2 and _is_pics_dir(ppi[1]):
159 if len(ppi) == 2:
160 self._page_func = self.page_thumbs
161 elif len(ppi) >= 4 and ppi[2] == "browse" and os.path.exists(os.path.join(*ppi)):
162 self._page_func = self.page_browse
163 elif len(ppi) == 1 and self._show_index:
164 self._page_func = self.page_index
166 if self._page_func is None:
167 raise RuntimeError("Cannot find path: " + pi)
170 def page(self):
171 return unicode(self._page_func()).encode("utf-8")
174 def page_index(self):
175 n = 5 # number of thumbnails to display per dir
177 (html_root, html_header, html_body) = self._get_standard_html_doc("Pictures")
179 html_header.script('', type="text/javascript", src=self._get_pics_url("lazyload.js"))
181 pics_dirs = []
182 for i in os.listdir('.'):
183 if _is_pics_dir(i):
184 pics_dirs.append((i, _get_dir_dt(i)))
186 pics_dirs.sort(key=lambda x: x[1], reverse=True)
188 for (d, dt) in pics_dirs:
189 html_body.h2.a(d, href=self._get_app_url(d))
190 html_body.h3(_format_dt(dt))
192 imgs = _get_images(d)
193 imgs_idx = [(i, img) for (i, img) in enumerate(imgs)]
195 sampled_imgs_idx = random.sample(imgs_idx, min(len(imgs_idx), n))
196 sampled_imgs_idx.sort(key=lambda x: x[0])
198 html_p = html_body.p
199 for (i, (t, b)) in sampled_imgs_idx:
200 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, b, lazyload=True)
202 return html_root
205 def page_thumbs(self):
206 ppi = _parse_path_info(self._environ["PATH_INFO"])
207 d = os.path.join(*ppi)
208 (html_root, html_header, html_body) = self._get_standard_html_doc(d)
210 from_img = None
211 if "from" in self._qs:
212 from_img = self._qs["from"][0]
214 html_p = html_body.p
215 for (t, b) in _get_images(d):
216 if from_img is not None and b == from_img:
217 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, b, img_args={"klass":"sel2", "id":"selected"})
218 else:
219 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, b)
221 # TODO: fix me
222 #if self._show_index:
223 # html_body.a("(Other pictures)", href=self._get_app_url(''))
225 return html_root
228 def page_browse(self):
229 ppi = _parse_path_info(self._environ["PATH_INFO"])
230 d = os.path.join(*ppi[:2])
231 imgs = _get_images(d)
232 img = os.path.join(*ppi)
234 # thumbnail preview ribbon
235 w = 7 # must be odd
236 v = w/2
237 imgs_circ = [None] * w
238 x = None
239 n = len(imgs)
240 for (i, (t, b)) in enumerate(imgs):
241 if b == img:
242 x = i + 1
243 imgs_circ[v] = (t, b)
244 for j in range(1, v + 1):
245 if (i + j) < n: imgs_circ[v + j] = imgs[i + j]
246 if (i - j) >= 0: imgs_circ[v - j] = imgs[i - j]
248 break
250 if x is None:
251 raise AssertionError
253 (html_root, html_header, html_body) = self._get_standard_html_doc(u"%s \u2014 %s of %s" % (d, x, len(imgs)))
255 html_header.script('', type="text/javascript", src=self._get_pics_url("np_keys.js"))
257 self._go_browse_image_html_body(html_body.p, img)
259 logging.debug("imgs_circ = %s" % imgs_circ)
261 html_p = html_body.p
262 for (i, img_c) in enumerate(imgs_circ):
263 if img_c is not None:
264 (t, b) = img_c
265 a_args = {}
266 img_args = {}
267 if b == img:
268 a_args = {"id": "up"}
269 img_args = {"klass": "sel"}
270 b = "%s?from=%s#selected" % (d, img)
271 elif i == v + 1:
272 a_args = {"id": "next"}
273 elif i == v - 1:
274 a_args = {"id": "prev"}
276 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, b, a_args, img_args)
278 return html_root
281 def app(environ, start_response):
282 response_code = "500 Internal Server Error"
283 response_type = "text/plain; charset=UTF-8"
285 try:
286 response_body = Main(environ).page()
287 response_code = "200 OK"
288 response_type = "text/html; charset=UTF-8"
289 except:
290 response_body = traceback.format_exc()
292 response_headers = [
293 ("Content-Type", response_type),
294 ("Content-Length", str(len(response_body))),
295 ]
297 start_response(response_code, response_headers)
299 return [response_body]