# Copyright (c) 2018, George Tokmaji # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. from ..helpers import * import magic from datetime import datetime def _upload_file(file, entry=None): f = File(id=ObjectId(), name=file.filename, upload=entry) path = os.path.join(os.getcwd(), "media", str(f.id)) file.save(path) with open(path, "rb") as fobj: f.hash = calculateHashForFile(fobj).hexdigest() f.length = fobj.tell() f.content_type = magic.from_file(path, mime=True) return f def _delete_file(file): try: os.unlink(os.path.join(os.getcwd(), "media", str(file.id))) except FileNotFoundError: pass except OSError: print("Failed to unlink", file.id, file=sys.stderr) @get("/api/media") def get_media(): notAllowed() @post("/api/media") @jwt_auth_required def post_media(): session = DBSession() f = _upload_file(next(request.files.values())) session.add(f) session.commit() return HTTPResponse(f.json(), status=201) @get("/api/media/") def get_media_id(id): session = DBSession() try: file = session.query(File).filter_by(id=id).one() except db.orm.exc.NoResultFound: raise HTTPResponse(status=404) response.set_header("Content-Type", file.content_type) response.set_header("Content-Length", file.length) response.set_header("Date", file.date.strftime("%a, %d %b %Y %H:%M:%S GMT")) response.set_header("Content-Disposition", f"attachment; filename=\"{file.name}\"") if request.method == "GET": if file.download_url: #return requests.request(request.method, file.download_url, allow_redirects=True) return HTTPResponse(status=302, headers={"Location" : file.download_url}) else: return static_file(str(file.id), os.path.join(os.getcwd(), "media"), file.content_type, download=file.name if request.params.download else False) raise HTTPResponse(status=404)