|
1 import os |
|
2 |
|
3 from cubicweb.server import hook |
|
4 from cubicweb.predicates import is_instance |
|
5 from cubicweb.entities import adapters |
|
6 |
|
7 from cubicweb_file.entities import UnResizeable |
|
8 |
|
9 |
|
10 class UpdateFileHook(hook.Hook): |
|
11 """a file has been updated, check data_format/data_encoding consistency |
|
12 """ |
|
13 __regid__ = 'updatefilehook' |
|
14 __select__ = hook.Hook.__select__ & is_instance('File') |
|
15 events = ('before_add_entity', 'before_update_entity',) |
|
16 order = -1 # should be run before other hooks |
|
17 category = 'hash' |
|
18 |
|
19 def __call__(self): |
|
20 edited = self.entity.cw_edited |
|
21 if 'data' in edited: |
|
22 self.entity.set_format_and_encoding() |
|
23 maxsize = None |
|
24 if maxsize and self.entity.data_format.startswith('image/'): |
|
25 iimage = self.entity.cw_adapt_to('IImage') |
|
26 try: |
|
27 edited['data'] = iimage.resize(maxsize) |
|
28 except UnResizeable: |
|
29 # if the resize fails for some reason, do nothing |
|
30 # (original image will be stored) |
|
31 pass |
|
32 |
|
33 # thumbnail cache invalidation |
|
34 if 'update' in self.event and 'data' in edited: |
|
35 thumb = self.entity.cw_adapt_to('IThumbnail') |
|
36 if not thumb: |
|
37 return |
|
38 thumbpath = thumb.thumbnail_path() |
|
39 if thumbpath: |
|
40 try: |
|
41 os.unlink(thumbpath) |
|
42 except Exception as exc: |
|
43 self.warning( |
|
44 'could not invalidate thumbnail file `%s` ' |
|
45 '(cause: %s)', |
|
46 thumbpath, exc) |
|
47 |
|
48 |
|
49 class FileIDownloadableAdapter(adapters.IDownloadableAdapter): |
|
50 __select__ = is_instance('File') |
|
51 |
|
52 # IDownloadable |
|
53 def download_url(self, **kwargs): |
|
54 # include filename in download url for nicer url |
|
55 name = self._cw.url_quote(self.download_file_name()) |
|
56 path = '%s/raw/%s' % (self.entity.rest_path(), name) |
|
57 return self._cw.build_url(path, **kwargs) |
|
58 |
|
59 def download_content_type(self): |
|
60 return self.entity.data_format |
|
61 |
|
62 def download_encoding(self): |
|
63 return self.entity.data_encoding |
|
64 |
|
65 def download_file_name(self): |
|
66 return self.entity.data_name |
|
67 |
|
68 def download_data(self): |
|
69 return self.entity.data.getvalue() |