from django.db import models from boards import utils from boards.models.attachment.viewers import get_viewers, AbstractViewer from boards.utils import get_upload_filename, get_file_mimetype, get_extension class AttachmentManager(models.Manager): def create_with_hash(self, file): file_hash = utils.get_file_hash(file) existing = self.filter(hash=file_hash) if len(existing) > 0: attachment = existing[0] else: # FIXME Use full mimetype here, need to modify viewers too file_type = get_extension(file.name) attachment = self.create(file=file, mimetype=file_type, hash=file_hash) return attachment class Attachment(models.Model): objects = AttachmentManager() file = models.FileField(upload_to=get_upload_filename) mimetype = models.CharField(max_length=50) hash = models.CharField(max_length=36) def get_view(self): file_viewer = None for viewer in get_viewers(): if viewer.supports(self.mimetype): file_viewer = viewer break if file_viewer is None: file_viewer = AbstractViewer return file_viewer(self.file, self.mimetype).get_view() def __str__(self): return self.file.url