1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 from __future__
import absolute_import
24 from werkzeug
.utils
import secure_filename
26 from mediagoblin
.tools
import common
33 class Error(Exception):
37 class InvalidFilepath(Error
):
41 class NoWebServing(Error
):
45 class NotImplementedError(Error
):
49 ###############################################
50 # Storage interface & basic file implementation
51 ###############################################
53 class StorageInterface(object):
55 Interface for the storage API.
57 This interface doesn't actually provide behavior, but it defines
58 what kind of storage patterns subclasses should provide.
60 It is important to note that the storage API idea of a "filepath"
61 is actually like ['dir1', 'dir2', 'file.jpg'], so keep that in
62 mind while reading method documentation.
64 You should set up your __init__ method with whatever keyword
65 arguments are appropriate to your storage system, but you should
66 also passively accept all extraneous keyword arguments like:
68 def __init__(self, **kwargs):
71 See BasicFileStorage as a simple implementation of the
75 # Whether this file store is on the local filesystem.
78 def __raise_not_implemented(self
):
80 Raise a warning about some component not implemented by a
81 subclass of this interface.
83 raise NotImplementedError(
84 "This feature not implemented in this storage API implementation.")
86 def file_exists(self
, filepath
):
88 Return a boolean asserting whether or not file at filepath
89 exists in our storage system.
92 True / False depending on whether file exists or not.
94 # Subclasses should override this method.
95 self
.__raise
_not
_implemented
()
97 def get_file(self
, filepath
, mode
='r'):
99 Return a file-like object for reading/writing from this filepath.
101 Should create directories, buckets, whatever, as necessary.
103 # Subclasses should override this method.
104 self
.__raise
_not
_implemented
()
106 def delete_file(self
, filepath
):
108 Delete or dereference the file (not directory) at filepath.
110 # Subclasses should override this method.
111 self
.__raise
_not
_implemented
()
113 def delete_dir(self
, dirpath
, recursive
=False):
114 """Delete the directory at dirpath
116 :param recursive: Usually, a directory must not contain any
117 files for the delete to succeed. If True, containing files
118 and subdirectories within dirpath will be recursively
121 :returns: True in case of success, False otherwise.
123 # Subclasses should override this method.
124 self
.__raise
_not
_implemented
()
126 def file_url(self
, filepath
):
128 Get the URL for this file. This assumes our storage has been
129 mounted with some kind of URL which makes this possible.
131 # Subclasses should override this method.
132 self
.__raise
_not
_implemented
()
134 def get_unique_filepath(self
, filepath
):
136 If a filename at filepath already exists, generate a new name.
138 Eg, if the filename doesn't exist:
139 >>> storage_handler.get_unique_filename(['dir1', 'dir2', 'fname.jpg'])
140 [u'dir1', u'dir2', u'fname.jpg']
142 But if a file does exist, let's get one back with at uuid tacked on:
143 >>> storage_handler.get_unique_filename(['dir1', 'dir2', 'fname.jpg'])
144 [u'dir1', u'dir2', u'd02c3571-dd62-4479-9d62-9e3012dada29-fname.jpg']
146 # Make sure we have a clean filepath to start with, since
147 # we'll be possibly tacking on stuff to the filename.
148 filepath
= clean_listy_filepath(filepath
)
150 if self
.file_exists(filepath
):
151 return filepath
[:-1] + ["%s-%s" % (uuid
.uuid4(), filepath
[-1])]
155 def get_local_path(self
, filepath
):
157 If this is a local_storage implementation, give us a link to
158 the local filesystem reference to this file.
160 >>> storage_handler.get_local_path(['foo', 'bar', 'baz.jpg'])
161 u'/path/to/mounting/foo/bar/baz.jpg'
163 # Subclasses should override this method, if applicable.
164 self
.__raise
_not
_implemented
()
166 def copy_locally(self
, filepath
, dest_path
):
168 Copy this file locally.
170 A basic working method for this is provided that should
171 function both for local_storage systems and remote storge
172 systems, but if more efficient systems for copying locally
173 apply to your system, override this method with something more
176 if self
.local_storage
:
177 # Note: this will copy in small chunks
178 shutil
.copy(self
.get_local_path(filepath
), dest_path
)
180 with self
.get_file(filepath
, 'rb') as source_file
:
181 with
open(dest_path
, 'wb') as dest_file
:
182 # Copy from remote storage in 4M chunks
183 shutil
.copyfileobj(source_file
, dest_file
, length
=4*1048576)
185 def copy_local_to_storage(self
, filename
, filepath
):
187 Copy this file from locally to the storage system.
189 This is kind of the opposite of copy_locally. It's likely you
190 could override this method with something more appropriate to
193 with self
.get_file(filepath
, 'wb') as dest_file
:
194 with
open(filename
, 'rb') as source_file
:
195 # Copy to storage system in 4M chunks
196 shutil
.copyfileobj(source_file
, dest_file
, length
=4*1048576)
198 def get_file_size(self
, filepath
):
200 Return the size of the file in bytes.
202 # Subclasses should override this method.
203 self
.__raise
_not
_implemented
()
210 def clean_listy_filepath(listy_filepath
):
212 Take a listy filepath (like ['dir1', 'dir2', 'filename.jpg']) and
213 clean out any nastiness from it.
216 >>> clean_listy_filepath([u'/dir1/', u'foo/../nasty', u'linooks.jpg'])
217 [u'dir1', u'foo_.._nasty', u'linooks.jpg']
220 - listy_filepath: a list of filepath components, mediagoblin
224 A cleaned list of unicode objects.
227 six
.text_type(secure_filename(filepath
))
228 for filepath
in listy_filepath
]
230 if u
'' in cleaned_filepath
:
231 raise InvalidFilepath(
232 "A filename component could not be resolved into a usable name.")
234 return cleaned_filepath
237 def storage_system_from_config(config_section
):
239 Utility for setting up a storage system from a config section.
241 Note that a special argument may be passed in to
242 the config_section which is "storage_class" which will provide an
243 import path to a storage system. This defaults to
244 "mediagoblin.storage:BasicFileStorage" if otherwise undefined.
247 - config_section: dictionary of config parameters
250 An instantiated storage system.
253 storage_system_from_config(
254 {'base_url': '/media/',
255 'base_dir': '/var/whatever/media/'})
260 base_dir='/var/whatever/media')
262 # This construct is needed, because dict(config) does
263 # not replace the variables in the config items.
264 config_params
= dict(six
.iteritems(config_section
))
266 if 'storage_class' in config_params
:
267 storage_class
= config_params
['storage_class']
268 config_params
.pop('storage_class')
270 storage_class
= 'mediagoblin.storage.filestorage:BasicFileStorage'
272 storage_class
= common
.import_component(storage_class
)
273 return storage_class(**config_params
)
275 from . import filestorage