__init__.py
46 lines
| 1.3 KiB
| text/x-python
|
PythonLexer
|
r1369 | import magic | ||
|
r1368 | from django.db import models | ||
|
r1273 | |||
|
r1305 | from boards import utils | ||
|
r1286 | from boards.models.attachment.viewers import get_viewers, AbstractViewer | ||
|
r1368 | from boards.utils import get_upload_filename | ||
|
r1273 | |||
FILES_DIRECTORY = 'files/' | ||||
FILE_EXTENSION_DELIMITER = '.' | ||||
class AttachmentManager(models.Manager): | ||||
def create_with_hash(self, file): | ||||
|
r1305 | file_hash = utils.get_file_hash(file) | ||
|
r1273 | existing = self.filter(hash=file_hash) | ||
if len(existing) > 0: | ||||
attachment = existing[0] | ||||
else: | ||||
|
r1369 | file_type = magic.from_buffer(file.chunks().__next__(), mime=True)\ | ||
.decode().split('/')[-1] | ||||
|
r1305 | attachment = Attachment.objects.create( | ||
file=file, mimetype=file_type, hash=file_hash) | ||||
|
r1273 | |||
return attachment | ||||
class Attachment(models.Model): | ||||
objects = AttachmentManager() | ||||
|
r1368 | file = models.FileField(upload_to=get_upload_filename) | ||
|
r1273 | mimetype = models.CharField(max_length=50) | ||
hash = models.CharField(max_length=36) | ||||
def get_view(self): | ||||
file_viewer = None | ||||
|
r1286 | for viewer in get_viewers(): | ||
|
r1273 | if viewer.supports(self.mimetype): | ||
|
r1306 | file_viewer = viewer | ||
|
r1273 | break | ||
if file_viewer is None: | ||||
|
r1306 | file_viewer = AbstractViewer | ||
|
r1273 | |||
|
r1306 | return file_viewer(self.file, self.mimetype).get_view() | ||
|
r1273 | |||