2016-02-08 23:46:16 +00:00
|
|
|
import os
|
2020-11-16 18:26:54 +01:00
|
|
|
import tempfile
|
2016-02-08 23:46:16 +00:00
|
|
|
from datetime import datetime
|
|
|
|
|
from time import mktime
|
|
|
|
|
|
2020-11-21 01:42:55 +01:00
|
|
|
import magic
|
2016-02-08 23:46:16 +00:00
|
|
|
from django import forms
|
|
|
|
|
from django.conf import settings
|
2020-11-16 18:26:54 +01:00
|
|
|
from django_q.tasks import async_task
|
2020-11-07 23:25:50 +01:00
|
|
|
from pathvalidate import validate_filename, ValidationError
|
2016-02-08 23:46:16 +00:00
|
|
|
|
2020-11-21 01:42:55 +01:00
|
|
|
from documents.parsers import is_mime_type_supported
|
|
|
|
|
|
2016-02-08 23:46:16 +00:00
|
|
|
|
|
|
|
|
class UploadForm(forms.Form):
|
|
|
|
|
|
|
|
|
|
document = forms.FileField()
|
|
|
|
|
|
|
|
|
|
def clean_document(self):
|
2020-11-21 01:42:55 +01:00
|
|
|
document_name = self.cleaned_data.get("document").name
|
|
|
|
|
|
2020-11-07 23:25:50 +01:00
|
|
|
try:
|
2020-11-21 01:42:55 +01:00
|
|
|
validate_filename(document_name)
|
2020-11-07 23:25:50 +01:00
|
|
|
except ValidationError:
|
|
|
|
|
raise forms.ValidationError("That filename is suspicious.")
|
2020-11-21 01:42:55 +01:00
|
|
|
|
|
|
|
|
document_data = self.cleaned_data.get("document").read()
|
|
|
|
|
|
|
|
|
|
mime_type = magic.from_buffer(document_data, mime=True)
|
|
|
|
|
|
|
|
|
|
if not is_mime_type_supported(mime_type):
|
|
|
|
|
raise forms.ValidationError("This mime type is not supported.")
|
|
|
|
|
|
|
|
|
|
return document_name, document_data
|
2020-11-07 23:25:50 +01:00
|
|
|
|
2016-02-08 23:46:16 +00:00
|
|
|
def save(self):
|
|
|
|
|
"""
|
|
|
|
|
Since the consumer already does a lot of work, it's easier just to save
|
|
|
|
|
to-be-consumed files to the consumption directory rather than have the
|
|
|
|
|
form do that as well. Think of it as a poor-man's queue server.
|
|
|
|
|
"""
|
|
|
|
|
|
2020-11-21 01:42:55 +01:00
|
|
|
original_filename, data = self.cleaned_data.get("document")
|
2016-02-08 23:46:16 +00:00
|
|
|
|
2017-06-11 01:23:37 +01:00
|
|
|
t = int(mktime(datetime.now().timetuple()))
|
2020-11-07 23:25:50 +01:00
|
|
|
|
2020-11-18 11:32:48 +01:00
|
|
|
os.makedirs(settings.SCRATCH_DIR, exist_ok=True)
|
|
|
|
|
|
2020-11-21 14:03:45 +01:00
|
|
|
with tempfile.NamedTemporaryFile(prefix="paperless-upload-",
|
|
|
|
|
dir=settings.SCRATCH_DIR,
|
|
|
|
|
delete=False) as f:
|
2016-02-08 23:46:16 +00:00
|
|
|
|
2020-11-21 01:42:55 +01:00
|
|
|
f.write(data)
|
2020-11-16 18:26:54 +01:00
|
|
|
os.utime(f.name, times=(t, t))
|
|
|
|
|
|
2020-11-21 14:03:45 +01:00
|
|
|
async_task("documents.tasks.consume_file",
|
|
|
|
|
f.name,
|
|
|
|
|
override_filename=original_filename,
|
2020-11-22 13:53:19 +01:00
|
|
|
task_name=os.path.basename(original_filename)[:100])
|