1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2009 The University of Melbourne
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 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 General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
# Author: William Grant
20
'''Media file support for the framework.'''
27
from ivle.webapp.base.views import BaseView
28
from ivle.webapp.base.plugins import ViewPlugin
29
from ivle.webapp.errors import NotFound, Forbidden
31
def media_url(req, plugin, path):
32
'''Generates a URL to a media file.
34
Plugin can be a string, in which case it is put into the path literally,
35
or a plugin object, in which case its name is looked up.'''
36
if not isinstance(plugin, basestring):
37
plugin = req.reverse_plugins[plugin]
39
return os.path.join(ivle.conf.root_dir, '+media', plugin, path)
41
class MediaFileView(BaseView):
42
'''A view for media files.
44
This serves static files from directories registered by plugins.
46
Plugins wishing to export media should declare a 'media' attribute,
47
pointing to the directory to serve (relative to the module's directory).
48
The contents of that directory will then be available under
49
/+media/python.path.to.module.
51
def __init__(self, req, ns, path):
55
def _make_filename(self, req):
57
plugin = req.plugins[self.ns]
62
mediadir = plugin.media
63
except AttributeError:
66
plugindir = os.path.dirname(inspect.getmodule(plugin).__file__)
68
return os.path.join(plugindir, mediadir, self.path)
70
def render(self, req):
71
# If it begins with ".." or separator, it's illegal. Die.
72
if self.path.startswith("..") or self.path.startswith('/'):
75
filename = self._make_filename(req)
77
# Find an appropriate MIME type.
78
(type, _) = mimetypes.guess_type(filename)
80
type = 'application/octet-stream'
82
# Get out if it is unreadable or a directory.
83
if not os.access(filename, os.F_OK):
85
if not os.access(filename, os.R_OK) or os.path.isdir(filename):
88
req.content_type = type
89
req.sendfile(filename)
91
class Plugin(ViewPlugin):
93
('+media/:ns/*path', MediaFileView),