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/>.
22 from mediagoblin
import mg_globals
23 from mediagoblin
.tools
.translate
import lazy_pass_to_ugettext
as _
25 _log
= logging
.getLogger(__name__
)
27 class FileTypeNotSupported(Exception):
30 class InvalidFileType(Exception):
34 def sniff_media(media
):
36 Iterate through the enabled media types and find those suited
41 return get_media_type_and_manager(media
.filename
)
42 except FileTypeNotSupported
:
43 _log
.info('No media handler found by file extension. Doing it the expensive way...')
44 # Create a temporary file for sniffers suchs as GStreamer-based
46 media_file
= tempfile
.NamedTemporaryFile()
47 media_file
.write(media
.stream
.read())
50 for media_type
, manager
in get_media_managers():
51 _log
.info('Sniffing {0}'.format(media_type
))
52 if manager
['sniff_handler'](media_file
, media
=media
):
53 _log
.info('{0} accepts the file'.format(media_type
))
54 return media_type
, manager
56 _log
.debug('{0} did not accept the file'.format(media_type
))
58 raise FileTypeNotSupported(
59 # TODO: Provide information on which file types are supported
60 _(u
'Sorry, I don\'t support that file type :('))
63 def get_media_types():
65 Generator, yields the available media types
67 for media_type
in mg_globals
.app_config
['media_types']:
71 def get_media_managers():
73 Generator, yields all enabled media managers
75 for media_type
in get_media_types():
76 __import__(media_type
)
78 yield media_type
, sys
.modules
[media_type
].MEDIA_MANAGER
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 for media_type
, manager
in get_media_managers():
92 # Omit the dot from the extension and match it against
94 if ext
[1:] in manager
['accepted_extensions']:
95 return media_type
, manager
97 _log
.info('File {0} has no file extension, let\'s hope the sniffers get it.'.format(
100 raise FileTypeNotSupported(
101 _(u
'Sorry, I don\'t support that file type :('))