##// END OF EJS Templates
Changed tag description, made it plural
Changed tag description, made it plural

File last commit:

r1320:c450e81f merge decentral
r1364:6850c2d2 default
Show More
__init__.py
63 lines | 1.7 KiB | text/x-python | PythonLexer
neko259
Added support for different attachment types
r1273 import hashlib
import os
import time
from random import random
from django.db import models
neko259
Deduplicated file hash calculation method
r1305 from boards import utils
neko259
Added support for different attachment types
r1273
neko259
Autodetect attachment viewers by getting all abstract viewer subclasses
r1286 from boards.models.attachment.viewers import get_viewers, AbstractViewer
neko259
Added support for different attachment types
r1273
FILES_DIRECTORY = 'files/'
FILE_EXTENSION_DELIMITER = '.'
class AttachmentManager(models.Manager):
def create_with_hash(self, file):
neko259
Deduplicated file hash calculation method
r1305 file_hash = utils.get_file_hash(file)
neko259
Added support for different attachment types
r1273 existing = self.filter(hash=file_hash)
if len(existing) > 0:
attachment = existing[0]
else:
file_type = file.name.split(FILE_EXTENSION_DELIMITER)[-1].lower()
neko259
Deduplicated file hash calculation method
r1305 attachment = Attachment.objects.create(
file=file, mimetype=file_type, hash=file_hash)
neko259
Added support for different attachment types
r1273
return attachment
class Attachment(models.Model):
objects = AttachmentManager()
# TODO Dedup the method
def _update_filename(self, filename):
"""
Gets unique filename
"""
# TODO Use something other than random number in file name
new_name = '{}{}.{}'.format(
str(int(time.mktime(time.gmtime()))),
str(int(random() * 1000)),
filename.split(FILE_EXTENSION_DELIMITER)[-1:][0])
return os.path.join(FILES_DIRECTORY, new_name)
file = models.FileField(upload_to=_update_filename)
mimetype = models.CharField(max_length=50)
hash = models.CharField(max_length=36)
def get_view(self):
file_viewer = None
neko259
Autodetect attachment viewers by getting all abstract viewer subclasses
r1286 for viewer in get_viewers():
neko259
Added support for different attachment types
r1273 if viewer.supports(self.mimetype):
neko259
Refactored attachment viewer getting method
r1306 file_viewer = viewer
neko259
Added support for different attachment types
r1273 break
if file_viewer is None:
neko259
Refactored attachment viewer getting method
r1306 file_viewer = AbstractViewer
neko259
Added support for different attachment types
r1273
neko259
Refactored attachment viewer getting method
r1306 return file_viewer(self.file, self.mimetype).get_view()
neko259
Added support for different attachment types
r1273