2018-05-07 08:28:48 -04:00
|
|
|
import hashlib
|
|
|
|
|
|
|
|
from django.core.files.storage import default_storage as store
|
|
|
|
from django.http import HttpResponse
|
|
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
|
|
from django.views.decorators.http import require_POST
|
|
|
|
import magic
|
|
|
|
|
|
|
|
from lemonauth import tokens
|
|
|
|
from lemoncurry.utils import absolute_url
|
2018-07-02 20:03:35 -04:00
|
|
|
from .. import error
|
2018-05-07 08:28:48 -04:00
|
|
|
|
|
|
|
ACCEPTED_MEDIA_TYPES = (
|
2023-08-10 02:52:37 -04:00
|
|
|
"image/gif",
|
|
|
|
"image/jpeg",
|
|
|
|
"image/png",
|
2018-05-07 08:28:48 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
@csrf_exempt
|
|
|
|
@require_POST
|
|
|
|
def media(request):
|
|
|
|
token = tokens.auth(request)
|
2023-08-10 02:52:37 -04:00
|
|
|
if "file" not in request.FILES:
|
2018-07-02 20:03:35 -04:00
|
|
|
raise error.bad_req(
|
2018-05-07 08:28:48 -04:00
|
|
|
"a file named 'file' must be provided to the media endpoint"
|
|
|
|
)
|
2023-08-10 02:52:37 -04:00
|
|
|
file = request.FILES["file"]
|
2018-05-07 08:28:48 -04:00
|
|
|
if file.content_type not in ACCEPTED_MEDIA_TYPES:
|
2023-08-10 02:52:37 -04:00
|
|
|
raise error.bad_req("unacceptable file type {0}".format(file.content_type))
|
2018-05-07 08:28:48 -04:00
|
|
|
|
|
|
|
mime = None
|
|
|
|
sha = hashlib.sha256()
|
|
|
|
for chunk in file.chunks():
|
|
|
|
if mime is None:
|
|
|
|
mime = magic.from_buffer(chunk, mime=True)
|
|
|
|
sha.update(chunk)
|
|
|
|
|
|
|
|
if mime != file.content_type:
|
2018-07-02 20:03:35 -04:00
|
|
|
raise error.bad_req(
|
2023-08-10 02:52:37 -04:00
|
|
|
"detected file type {0} did not match specified file type {1}".format(
|
|
|
|
mime, file.content_type
|
|
|
|
)
|
2018-05-07 08:28:48 -04:00
|
|
|
)
|
|
|
|
|
2023-08-10 02:52:37 -04:00
|
|
|
path = "mp/{0[0]}/{2}.{1}".format(*mime.split("/"), sha.hexdigest())
|
2018-05-07 08:28:48 -04:00
|
|
|
path = store.save(path, file)
|
|
|
|
url = absolute_url(request, store.url(path))
|
|
|
|
|
|
|
|
res = HttpResponse(status=201)
|
2023-08-10 02:52:37 -04:00
|
|
|
res["Location"] = url
|
2018-05-07 08:28:48 -04:00
|
|
|
return res
|