aboutsummaryrefslogtreecommitdiffstats
path: root/routes/media.py
blob: 37f57c94d5a64c55ddcf375922852dea4f45d3bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# 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)

@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/<id>")
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)