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/>.
21 from mediagoblin
.tools
.pluginapi
import hook_handle
22 from mediagoblin
.tools
.translate
import lazy_pass_to_ugettext
as _
24 _log
= logging
.getLogger(__name__
)
26 class FileTypeNotSupported(Exception):
29 class InvalidFileType(Exception):
33 class MediaManagerBase(object):
34 "Base class for all media managers"
36 # Please override in actual media managers
37 media_fetch_order
= None
40 def sniff_handler(*args
, **kwargs
):
43 def __init__(self
, entry
):
46 def __getitem__(self
, i
):
47 return getattr(self
, i
)
49 def __contains__(self
, i
):
50 return hasattr(self
, i
)
53 def sniff_media(media
):
55 Iterate through the enabled media types and find those suited
60 return get_media_type_and_manager(media
.filename
)
61 except FileTypeNotSupported
:
62 _log
.info('No media handler found by file extension. Doing it the expensive way...')
63 # Create a temporary file for sniffers suchs as GStreamer-based
65 media_file
= tempfile
.NamedTemporaryFile()
66 media_file
.write(media
.stream
.read())
69 media_type
= hook_handle('sniff_handler', media_file
, media
=media
)
71 _log
.info('{0} accepts the file'.format(media_type
))
72 return media_type
, hook_handle(('media_manager', media_type
))
74 _log
.debug('{0} did not accept the file'.format(media_type
))
76 raise FileTypeNotSupported(
77 # TODO: Provide information on which file types are supported
78 _(u
'Sorry, I don\'t support that file type :('))
81 def get_media_type_and_manager(filename
):
83 Try to find the media type based on the file name, extension
84 specifically. This is used as a speedup, the sniffing functionality
85 then falls back on more in-depth bitsniffing of the source file.
87 if filename
.find('.') > 0:
88 # Get the file extension
89 ext
= os
.path
.splitext(filename
)[1].lower()
91 # Omit the dot from the extension and match it against
93 if hook_handle('get_media_type_and_manager', ext
[1:]):
94 return hook_handle('get_media_type_and_manager', ext
[1:])
96 _log
.info('File {0} has no file extension, let\'s hope the sniffers get it.'.format(
99 raise FileTypeNotSupported(
100 _(u
'Sorry, I don\'t support that file type :('))