import os import cherrypy from photoapp.types import PhotoSet, PhotoStatus import hashlib def copysha(fpin, fpout): sha = hashlib.sha256() while True: b = fpin.read(1024 * 256) if not b: break fpout.write(b) sha.update(b) return sha.hexdigest() def shasum(fpin): sha = hashlib.sha256() while True: b = fpin.read(4096) if not b: break sha.update(b) return sha.hexdigest() def mime2ext(mime): """ Given a mime type return the canonical file extension """ return {"image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "application/octet-stream-xmp": "xmp", "image/x-canon-cr2": "cr2", "audio/mp4": "mp4", "video/mp4": "mp4", "video/quicktime": "mov"}[mime] def get_extension(fname): parts = os.path.basename(fname).split(".") if len(parts) == 1: return None return parts[-1].lower() def auth(): """ Return the currently authorized username (per request) or None """ return cherrypy.session.get('authed', None) def require_auth(func): """ Decorator: raise 403 unless session is authed """ def wrapped(*args, **kwargs): if not auth(): raise cherrypy.HTTPError(403) return func(*args, **kwargs) return wrapped def photoset_auth_filter(query): """ Sqlalchemy helper: filter the given PhotoSet query to items that match the authorized user's PhotoStatus access level. Currently, authed users can access ALL photos, and unauthed users can access only PhotoStatus.public status items. """ return query.filter(PhotoSet.status == PhotoStatus.public) if not auth() else query def slugify(words): return ''.join(letter for letter in '-'.join(words.lower().split()) if ('a' <= letter <= 'z') or ('0' <= letter <= '9') or letter == '-')