photolib/photoapp/utils.py

78 lines
1.9 KiB
Python
Raw Normal View History

2019-06-21 09:22:42 -07:00
import os
2019-06-17 22:43:57 -07:00
import cherrypy
from photoapp.types import PhotoSet, PhotoStatus
2019-07-02 12:34:41 -07:00
import hashlib
def copysha(fpin, fpout):
sha = hashlib.sha256()
while True:
b = fpin.read(1024 * 256)
2019-07-02 12:34:41 -07:00
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()
2019-06-17 22:43:57 -07:00
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",
"video/mp4": "mp4",
"video/quicktime": "mov"}[mime]
2019-06-21 09:22:42 -07:00
def get_extension(fname):
parts = os.path.basename(fname).split(".")
if len(parts) == 1:
return None
return parts[-1].lower()
2019-06-17 22:43:57 -07:00
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
2019-07-04 18:41:57 -07:00
def photoset_auth_filter(query):
2019-06-17 22:43:57 -07:00
"""
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 == '-')