photolib/photoapp/api.py

75 lines
2.4 KiB
Python
Raw Normal View History

2019-06-17 22:43:57 -07:00
import os
import cherrypy
import logging
from datetime import datetime, timedelta
from photoapp.library import PhotoLibrary
from photoapp.types import Photo, PhotoSet, Tag, TagItem, PhotoStatus, User
from jinja2 import Environment, FileSystemLoader, select_autoescape
from sqlalchemy import desc
from sqlalchemy import func, and_, or_
from photoapp.common import pwhash
import math
from urllib.parse import urlparse
from photoapp.utils import mime2ext, auth, require_auth, photo_auth_filter, slugify
from photoapp.dbutils import db
class PhotosApi(object):
def __init__(self):
self.v1 = PhotosApiV1()
class PhotosApiV1(object):
def __init__(self):
pass
@cherrypy.expose
def index(self):
2019-06-22 16:45:32 -07:00
yield f"<plaintext>hello, this is the api. my database is: {db}\n"
2019-06-17 22:43:57 -07:00
@cherrypy.expose
def upload(self, files, meta):
pass
@cherrypy.expose
@cherrypy.tools.json_out()
2019-06-18 18:38:01 -07:00
def byhash(self, sha):
2019-06-22 16:45:32 -07:00
f = db.query(Photo).filter(Photo.hash == sha).first()
2019-06-19 22:34:52 -07:00
if not f:
raise cherrypy.HTTPError(404)
2019-06-18 18:38:01 -07:00
return f.to_json()
@cherrypy.expose
@cherrypy.tools.json_out()
def set(self, uuid):
2019-06-22 16:45:32 -07:00
s = db.query(PhotoSet).filter(PhotoSet.uuid == uuid).first()
2019-06-19 22:34:52 -07:00
if not s:
raise cherrypy.HTTPError(404)
2019-06-18 18:38:01 -07:00
return s.to_json()
@cherrypy.expose
def download(self, uuid):
2019-06-22 16:45:32 -07:00
f = db.query(Photo).filter(Photo.uuid == uuid).first()
2019-06-19 22:34:52 -07:00
if not f:
raise cherrypy.HTTPError(404)
2019-06-18 18:38:01 -07:00
return cherrypy.lib.static.serve_file(os.path.abspath(os.path.join("./library", f.path)),
f.format)#TODO no hardcode path
2019-06-22 16:36:06 -07:00
@cherrypy.expose
@cherrypy.tools.json_out()
def user(self, username=None, password_hash=None):
if username is None: # list all users
2019-06-22 16:45:32 -07:00
return [u.to_json() for u in db.query(User).all()]
2019-06-22 16:36:06 -07:00
elif username and cherrypy.request.method == "DELETE": # delete user
2019-06-22 16:45:32 -07:00
u = db.query(User).filter(User.name == username).first()
2019-06-22 16:36:06 -07:00
if not u:
raise cherrypy.HTTPError(404)
2019-06-22 16:45:32 -07:00
db.delete(u)
2019-06-22 16:36:06 -07:00
elif username and password_hash: # create/update user
2019-06-22 16:45:32 -07:00
u = db.query(User).filter(User.name == username).first()
2019-06-22 16:36:06 -07:00
if u:
u.password = password_hash
else:
2019-06-22 16:45:32 -07:00
db.add(User(name=username, password=password_hash))
2019-06-22 16:36:06 -07:00
return "ok"