import contextlib import os import tempfile from .base import BaseStorage class Storage(BaseStorage): def __init__(self, app): super().__init__(app) os.makedirs(self.app.config['FILE_DIRECTORY'], exist_ok=True) os.makedirs(self.app.config['THUMB_DIRECTORY'], exist_ok=True) def _get_legacy_path(self, file_hash, filename): return os.path.join(self.app.config['FILE_DIRECTORY'], file_hash + os.path.splitext(filename)[1]) def _get_path(self, file_hash): return os.path.join(self.app.config['FILE_DIRECTORY'], file_hash) def _find_path(self, f): path = self._get_legacy_path(f.hash, f.filename) if path and os.path.exists(path): return path path = self._get_path(f.hash) if path and os.path.exists(path): return path return None def get_thumb_path(self, f): return os.path.join(self.app.config['THUMB_DIRECTORY'], f.hash + '.jpg') def upload_file(self, uploaded_file, file_hash, user): size = uploaded_file.content_length if hasattr(uploaded_file.stream, 'file'): temp = None temp_path = uploaded_file.stream.name else: temp = tempfile.NamedTemporaryFile(prefix='upload_', dir=self.app.config['FILE_DIRECTORY'], delete=False) uploaded_file.save(temp.file) temp.close() temp_path = temp.name size = os.path.getsize(temp_path) new_path = self._get_path(file_hash) os.rename(temp_path, new_path) if self.app.config.get('DESTINATION_MODE'): os.chmod(new_path, self.app.config.get('DESTINATION_MODE')) return new_path, size def store_file(self, uploaded_file, file_hash, user, ip): file_path, size = self.upload_file(uploaded_file, file_hash, user) try: return self.add_file(file_hash, uploaded_file.filename, size, user, ip) except: # noqa: E722; we want to unlink and re-raise on all exceptions if os.path.exists(file_path): os.unlink(file_path) raise def file_exists(self, f): path = self._find_path(f) return path and os.path.exists(path) def get_file(self, f): path = self._find_path(f) if not path or not os.path.exists(path): return return path def delete_file(self, f): path = self._find_path(f) if path and os.path.exists(path): os.unlink(path) thumb_path = self.get_thumb_path(f) if thumb_path and os.path.exists(thumb_path): os.unlink(thumb_path) @contextlib.contextmanager def temp_file(self, f): path = self._find_path(f) if not path or not os.path.exists(path): raise FileNotFoundError(path) with open(path, 'rb') as f: yield f def get_thumbnail(self, f): path = self.get_thumb_path(f) if not path or not os.path.exists(path): return return path def store_thumbnail(self, f, stream): path = self.get_thumb_path(f) with open(path, 'wb') as f: buf = stream.read(1024 * 10) while buf: f.write(buf) buf = stream.read(1024 * 10)