__init__.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. # GNU MediaGoblin -- federated, autonomous media hosting
  2. # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
  3. #
  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.
  8. #
  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.
  13. #
  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/>.
  16. from __future__ import absolute_import
  17. import shutil
  18. import uuid
  19. import six
  20. from werkzeug.utils import secure_filename
  21. from mediagoblin.tools import common
  22. ########
  23. # Errors
  24. ########
  25. class Error(Exception):
  26. pass
  27. class InvalidFilepath(Error):
  28. pass
  29. class NoWebServing(Error):
  30. pass
  31. class NotImplementedError(Error):
  32. pass
  33. ###############################################
  34. # Storage interface & basic file implementation
  35. ###############################################
  36. class StorageInterface(object):
  37. """
  38. Interface for the storage API.
  39. This interface doesn't actually provide behavior, but it defines
  40. what kind of storage patterns subclasses should provide.
  41. It is important to note that the storage API idea of a "filepath"
  42. is actually like ['dir1', 'dir2', 'file.jpg'], so keep that in
  43. mind while reading method documentation.
  44. You should set up your __init__ method with whatever keyword
  45. arguments are appropriate to your storage system, but you should
  46. also passively accept all extraneous keyword arguments like:
  47. def __init__(self, **kwargs):
  48. pass
  49. See BasicFileStorage as a simple implementation of the
  50. StorageInterface.
  51. """
  52. # Whether this file store is on the local filesystem.
  53. local_storage = False
  54. def __raise_not_implemented(self):
  55. """
  56. Raise a warning about some component not implemented by a
  57. subclass of this interface.
  58. """
  59. raise NotImplementedError(
  60. "This feature not implemented in this storage API implementation.")
  61. def file_exists(self, filepath):
  62. """
  63. Return a boolean asserting whether or not file at filepath
  64. exists in our storage system.
  65. Returns:
  66. True / False depending on whether file exists or not.
  67. """
  68. # Subclasses should override this method.
  69. self.__raise_not_implemented()
  70. def get_file(self, filepath, mode='r'):
  71. """
  72. Return a file-like object for reading/writing from this filepath.
  73. Should create directories, buckets, whatever, as necessary.
  74. """
  75. # Subclasses should override this method.
  76. self.__raise_not_implemented()
  77. def delete_file(self, filepath):
  78. """
  79. Delete or dereference the file (not directory) at filepath.
  80. """
  81. # Subclasses should override this method.
  82. self.__raise_not_implemented()
  83. def delete_dir(self, dirpath, recursive=False):
  84. """Delete the directory at dirpath
  85. :param recursive: Usually, a directory must not contain any
  86. files for the delete to succeed. If True, containing files
  87. and subdirectories within dirpath will be recursively
  88. deleted.
  89. :returns: True in case of success, False otherwise.
  90. """
  91. # Subclasses should override this method.
  92. self.__raise_not_implemented()
  93. def file_url(self, filepath):
  94. """
  95. Get the URL for this file. This assumes our storage has been
  96. mounted with some kind of URL which makes this possible.
  97. """
  98. # Subclasses should override this method.
  99. self.__raise_not_implemented()
  100. def get_unique_filepath(self, filepath):
  101. """
  102. If a filename at filepath already exists, generate a new name.
  103. Eg, if the filename doesn't exist:
  104. >>> storage_handler.get_unique_filename(['dir1', 'dir2', 'fname.jpg'])
  105. [u'dir1', u'dir2', u'fname.jpg']
  106. But if a file does exist, let's get one back with at uuid tacked on:
  107. >>> storage_handler.get_unique_filename(['dir1', 'dir2', 'fname.jpg'])
  108. [u'dir1', u'dir2', u'd02c3571-dd62-4479-9d62-9e3012dada29-fname.jpg']
  109. """
  110. # Make sure we have a clean filepath to start with, since
  111. # we'll be possibly tacking on stuff to the filename.
  112. filepath = clean_listy_filepath(filepath)
  113. if self.file_exists(filepath):
  114. return filepath[:-1] + ["%s-%s" % (uuid.uuid4(), filepath[-1])]
  115. else:
  116. return filepath
  117. def get_local_path(self, filepath):
  118. """
  119. If this is a local_storage implementation, give us a link to
  120. the local filesystem reference to this file.
  121. >>> storage_handler.get_local_path(['foo', 'bar', 'baz.jpg'])
  122. u'/path/to/mounting/foo/bar/baz.jpg'
  123. """
  124. # Subclasses should override this method, if applicable.
  125. self.__raise_not_implemented()
  126. def copy_locally(self, filepath, dest_path):
  127. """
  128. Copy this file locally.
  129. A basic working method for this is provided that should
  130. function both for local_storage systems and remote storge
  131. systems, but if more efficient systems for copying locally
  132. apply to your system, override this method with something more
  133. appropriate.
  134. """
  135. if self.local_storage:
  136. # Note: this will copy in small chunks
  137. shutil.copy(self.get_local_path(filepath), dest_path)
  138. else:
  139. with self.get_file(filepath, 'rb') as source_file:
  140. with open(dest_path, 'wb') as dest_file:
  141. # Copy from remote storage in 4M chunks
  142. shutil.copyfileobj(source_file, dest_file, length=4*1048576)
  143. def copy_local_to_storage(self, filename, filepath):
  144. """
  145. Copy this file from locally to the storage system.
  146. This is kind of the opposite of copy_locally. It's likely you
  147. could override this method with something more appropriate to
  148. your storage system.
  149. """
  150. with self.get_file(filepath, 'wb') as dest_file:
  151. with open(filename, 'rb') as source_file:
  152. # Copy to storage system in 4M chunks
  153. shutil.copyfileobj(source_file, dest_file, length=4*1048576)
  154. def get_file_size(self, filepath):
  155. """
  156. Return the size of the file in bytes.
  157. """
  158. # Subclasses should override this method.
  159. self.__raise_not_implemented()
  160. ###########
  161. # Utilities
  162. ###########
  163. def clean_listy_filepath(listy_filepath):
  164. """
  165. Take a listy filepath (like ['dir1', 'dir2', 'filename.jpg']) and
  166. clean out any nastiness from it.
  167. >>> clean_listy_filepath([u'/dir1/', u'foo/../nasty', u'linooks.jpg'])
  168. [u'dir1', u'foo_.._nasty', u'linooks.jpg']
  169. Args:
  170. - listy_filepath: a list of filepath components, mediagoblin
  171. storage API style.
  172. Returns:
  173. A cleaned list of unicode objects.
  174. """
  175. cleaned_filepath = [
  176. six.text_type(secure_filename(filepath))
  177. for filepath in listy_filepath]
  178. if u'' in cleaned_filepath:
  179. raise InvalidFilepath(
  180. "A filename component could not be resolved into a usable name.")
  181. return cleaned_filepath
  182. def storage_system_from_config(config_section):
  183. """
  184. Utility for setting up a storage system from a config section.
  185. Note that a special argument may be passed in to
  186. the config_section which is "storage_class" which will provide an
  187. import path to a storage system. This defaults to
  188. "mediagoblin.storage:BasicFileStorage" if otherwise undefined.
  189. Arguments:
  190. - config_section: dictionary of config parameters
  191. Returns:
  192. An instantiated storage system.
  193. Example:
  194. storage_system_from_config(
  195. {'base_url': '/media/',
  196. 'base_dir': '/var/whatever/media/'})
  197. Will return:
  198. BasicFileStorage(
  199. base_url='/media/',
  200. base_dir='/var/whatever/media')
  201. """
  202. # This construct is needed, because dict(config) does
  203. # not replace the variables in the config items.
  204. config_params = dict(six.iteritems(config_section))
  205. if 'storage_class' in config_params:
  206. storage_class = config_params['storage_class']
  207. config_params.pop('storage_class')
  208. else:
  209. storage_class = 'mediagoblin.storage.filestorage:BasicFileStorage'
  210. storage_class = common.import_component(storage_class)
  211. return storage_class(**config_params)
  212. from . import filestorage