Show More
@@ -1,63 +1,63 b'' | |||
|
1 | 1 | import hashlib |
|
2 | 2 | import os |
|
3 | 3 | import time |
|
4 | 4 | |
|
5 | 5 | from random import random |
|
6 | 6 | |
|
7 | 7 | from django.db import models |
|
8 | 8 | from boards import utils |
|
9 | 9 | |
|
10 | 10 | from boards.models.attachment.viewers import get_viewers, AbstractViewer |
|
11 | 11 | |
|
12 | 12 | |
|
13 | 13 | FILES_DIRECTORY = 'files/' |
|
14 | 14 | FILE_EXTENSION_DELIMITER = '.' |
|
15 | 15 | |
|
16 | 16 | |
|
17 | 17 | class AttachmentManager(models.Manager): |
|
18 | 18 | def create_with_hash(self, file): |
|
19 | 19 | file_hash = utils.get_file_hash(file) |
|
20 | 20 | existing = self.filter(hash=file_hash) |
|
21 | 21 | if len(existing) > 0: |
|
22 | 22 | attachment = existing[0] |
|
23 | 23 | else: |
|
24 | 24 | file_type = file.name.split(FILE_EXTENSION_DELIMITER)[-1].lower() |
|
25 | 25 | attachment = Attachment.objects.create( |
|
26 | 26 | file=file, mimetype=file_type, hash=file_hash) |
|
27 | 27 | |
|
28 | 28 | return attachment |
|
29 | 29 | |
|
30 | 30 | |
|
31 | 31 | class Attachment(models.Model): |
|
32 | 32 | objects = AttachmentManager() |
|
33 | 33 | |
|
34 | 34 | # TODO Dedup the method |
|
35 | 35 | def _update_filename(self, filename): |
|
36 | 36 | """ |
|
37 | 37 | Gets unique filename |
|
38 | 38 | """ |
|
39 | 39 | |
|
40 | 40 | # TODO Use something other than random number in file name |
|
41 | 41 | new_name = '{}{}.{}'.format( |
|
42 | 42 | str(int(time.mktime(time.gmtime()))), |
|
43 | 43 | str(int(random() * 1000)), |
|
44 | 44 | filename.split(FILE_EXTENSION_DELIMITER)[-1:][0]) |
|
45 | 45 | |
|
46 | 46 | return os.path.join(FILES_DIRECTORY, new_name) |
|
47 | 47 | |
|
48 | 48 | file = models.FileField(upload_to=_update_filename) |
|
49 | 49 | mimetype = models.CharField(max_length=50) |
|
50 | 50 | hash = models.CharField(max_length=36) |
|
51 | 51 | |
|
52 | 52 | def get_view(self): |
|
53 | 53 | file_viewer = None |
|
54 | 54 | for viewer in get_viewers(): |
|
55 | 55 | if viewer.supports(self.mimetype): |
|
56 |
file_viewer = viewer |
|
|
56 | file_viewer = viewer | |
|
57 | 57 | break |
|
58 | 58 | if file_viewer is None: |
|
59 |
file_viewer = AbstractViewer |
|
|
59 | file_viewer = AbstractViewer | |
|
60 | 60 | |
|
61 | return file_viewer.get_view() | |
|
61 | return file_viewer(self.file, self.mimetype).get_view() | |
|
62 | 62 | |
|
63 | 63 |
General Comments 0
You need to be logged in to leave comments.
Login now