Create a basic but functional micropub media endpoint :o
This commit is contained in:
parent
0d5387823d
commit
4d974a5364
8 changed files with 103 additions and 38 deletions
|
@ -1,7 +1,9 @@
|
|||
from django.urls import path
|
||||
from . import views
|
||||
from .views import micropub
|
||||
from .views.media import media
|
||||
|
||||
app_name = 'micropub'
|
||||
urlpatterns = (
|
||||
path('', views.micropub, name='micropub'),
|
||||
path('', micropub, name='micropub'),
|
||||
path('/media', media, name='media'),
|
||||
)
|
||||
|
|
54
micropub/views/media.py
Normal file
54
micropub/views/media.py
Normal file
|
@ -0,0 +1,54 @@
|
|||
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
|
||||
from . import error
|
||||
|
||||
ACCEPTED_MEDIA_TYPES = (
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
)
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
@require_POST
|
||||
def media(request):
|
||||
token = tokens.auth(request)
|
||||
if hasattr(token, 'content'):
|
||||
return token
|
||||
if 'file' not in request.FILES:
|
||||
return error.bad_req(
|
||||
"a file named 'file' must be provided to the media endpoint"
|
||||
)
|
||||
file = request.FILES['file']
|
||||
if file.content_type not in ACCEPTED_MEDIA_TYPES:
|
||||
return error.bad_req(
|
||||
'unacceptable file type {0}'.format(file.content_type)
|
||||
)
|
||||
|
||||
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:
|
||||
return error.bad_req(
|
||||
'detected file type {0} did not match specified file type {1}'
|
||||
.format(mime, file.content_type)
|
||||
)
|
||||
|
||||
path = 'mp/{0[0]}/{2}.{1}'.format(*mime.split('/'), sha.hexdigest())
|
||||
path = store.save(path, file)
|
||||
url = absolute_url(request, store.url(path))
|
||||
|
||||
res = HttpResponse(status=201)
|
||||
res['Location'] = url
|
||||
return res
|
|
@ -1,10 +1,13 @@
|
|||
from django.http import JsonResponse
|
||||
from django.urls import reverse
|
||||
from lemoncurry import requests
|
||||
from lemoncurry.utils import absolute_url
|
||||
from . import error
|
||||
|
||||
|
||||
def config(request):
|
||||
config = syndicate_to(request)
|
||||
config['media-endpoint'] = absolute_url(request, reverse('micropub:media'))
|
||||
return config
|
||||
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue