~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/webapp/media.py

  • Committer: William Grant
  • Date: 2009-05-26 03:06:53 UTC
  • Revision ID: grantw@unimelb.edu.au-20090526030653-axxawt0o5ws4icbt
Remove ivle.conf usage from ivle.studpath.

Show diffs side-by-side

added added

removed removed

Lines of Context:
28
28
from ivle.webapp.base.views import BaseView
29
29
from ivle.webapp.base.plugins import PublicViewPlugin, ViewPlugin, MediaPlugin
30
30
from ivle.webapp.errors import NotFound, Forbidden
31
 
from ivle.webapp.publisher import INF
32
 
from ivle.webapp import ApplicationRoot
33
 
 
34
 
# This maps a media namespace to an external dependency directory (in this
35
 
# case specified by the configuration option media/externals/jquery) and a
36
 
# list of permitted subpaths.
37
 
EXTERNAL_MEDIA_MAP = {'jquery': ('jquery', ['jquery.js'])}
38
31
 
39
32
def media_url(req, plugin, path):
40
33
    '''Generates a URL to a media file.
53
46
 
54
47
    return req.make_path(os.path.join(media_path, plugin, path))
55
48
 
56
 
class MediaFile(object):
57
 
    def __init__(self, root, external, version, ns, path):
58
 
        self.root = root
59
 
        self.external = external
60
 
        self.version = version
 
49
class BaseMediaFileView(BaseView):
 
50
    '''A view for media files.
 
51
 
 
52
    This serves static files from directories registered by plugins.
 
53
 
 
54
    Plugins wishing to export media should declare a 'media' attribute,
 
55
    pointing to the directory to serve (relative to the module's directory).
 
56
    The contents of that directory will then be available under
 
57
    /+media/python.path.to.module.
 
58
    '''
 
59
    def __init__(self, req, ns, path):
61
60
        self.ns = ns
62
61
        self.path = path
63
62
 
64
 
    @property
65
 
    def filename(self):
66
 
        if self.external:
67
 
            try:
68
 
                extern = EXTERNAL_MEDIA_MAP[self.ns]
69
 
            except KeyError:
70
 
                return None
71
 
 
72
 
            # Unless it's a whitelisted path, we don't want to hear about it.
73
 
            if self.path not in extern[1]:
74
 
                return None
75
 
 
76
 
            # Grab the admin-configured path for this particular external dep.
77
 
            externdir = self.root.config['media']['externals'][extern[0]]
78
 
 
79
 
            assert isinstance(externdir, basestring)
80
 
 
81
 
            return os.path.join(externdir, self.path)
82
 
        else:
83
 
            try:
84
 
                plugin = self.root.config.plugins[self.ns]
85
 
            except KeyError:
86
 
                return None
87
 
 
88
 
            if not issubclass(plugin, MediaPlugin):
89
 
                return None
90
 
 
91
 
            mediadir = plugin.media
92
 
            plugindir = os.path.dirname(inspect.getmodule(plugin).__file__)
93
 
 
94
 
            return os.path.join(plugindir, mediadir, self.path)
95
 
 
96
 
class MediaFileView(BaseView):
97
 
    permission = None
 
63
    def _make_filename(self, req):
 
64
        raise NotImplementedError()
98
65
 
99
66
    def render(self, req):
100
67
        # If it begins with ".." or separator, it's illegal. Die.
101
 
        if self.context.path.startswith("..") or \
102
 
           self.context.path.startswith('/'):
 
68
        if self.path.startswith("..") or self.path.startswith('/'):
103
69
            raise Forbidden()
104
70
 
105
 
        filename = self.get_filename(req)
106
 
        if filename is None:
107
 
            raise NotFound()
 
71
        filename = self._make_filename(req)
108
72
 
109
73
        # Find an appropriate MIME type.
110
74
        (type, _) = mimetypes.guess_type(filename)
117
81
        if not os.access(filename, os.R_OK) or os.path.isdir(filename):
118
82
            raise Forbidden()
119
83
 
120
 
        if self.context.version is not None:
121
 
            req.headers_out['Expires'] = email.utils.formatdate(
122
 
                                timeval=time.time() + (60*60*24*365),
123
 
                                localtime=False,
124
 
                                usegmt=True)
125
 
 
126
 
 
127
84
        req.content_type = type
128
85
        req.sendfile(filename)
129
86
 
130
 
    def get_filename(self, req):
131
 
        return self.context.filename
132
 
 
133
 
    def get_permissions(self, user, config):
134
 
        return set()
135
 
 
136
 
def root_to_media(root, *segments):
137
 
    if segments[0].startswith('+'):
138
 
        if segments[0] == '+external':
139
 
            external = True
140
 
            version = None
141
 
            path = segments[1:]
142
 
        else:
143
 
            version = segments[0][1:]
144
 
            if segments[1] == '+external':
145
 
                external = True
146
 
                path = segments[2:]
147
 
            else:
148
 
                external = False
149
 
                path = segments[1:]
150
 
    else:
151
 
        external = False
152
 
        version = None
153
 
        path = segments
154
 
 
155
 
    if version is not None and version != root.config['media']['version']:
156
 
        return None
157
 
 
158
 
    ns = path[0]
159
 
    path = os.path.normpath(os.path.join(*path[1:]))
160
 
 
161
 
    return MediaFile(root, external, version, ns, path)
 
87
 
 
88
class MediaFileView(BaseMediaFileView):
 
89
    '''A view for media files.
 
90
 
 
91
    This serves static files from directories registered by plugins.
 
92
 
 
93
    Plugins wishing to export media should declare a 'media' attribute,
 
94
    pointing to the directory to serve (relative to the module's directory).
 
95
    The contents of that directory will then be available under
 
96
    /+media/python.path.to.module.
 
97
    '''
 
98
    permission = None
 
99
 
 
100
    def _make_filename(self, req):
 
101
        try:
 
102
            plugin = req.config.plugins[self.ns]
 
103
        except KeyError:
 
104
            raise NotFound()
 
105
 
 
106
        if not issubclass(plugin, MediaPlugin):
 
107
            raise NotFound()
 
108
 
 
109
        mediadir = plugin.media
 
110
        plugindir = os.path.dirname(inspect.getmodule(plugin).__file__)
 
111
 
 
112
        return os.path.join(plugindir, mediadir, self.path)
 
113
 
 
114
    def get_permissions(self, user):
 
115
        return set()
 
116
 
 
117
class VersionedMediaFileView(MediaFileView):
 
118
    '''A view for versioned media files, with aggressive caching.
 
119
 
 
120
    This serves static media files with a version string, and requests that
 
121
    browsers cache them for a long time.
 
122
    '''
 
123
 
 
124
    def __init__(self, req, ns, path, version):
 
125
        super(VersionedMediaFileView, self).__init__(req, ns, path)
 
126
        self.version = version
 
127
 
 
128
    def _make_filename(self, req):
 
129
        if self.version != req.config['media']['version']:
 
130
            raise NotFound()
 
131
 
 
132
        # Don't expire for a year.
 
133
        req.headers_out['Expires'] = email.utils.formatdate(
 
134
                                    timeval=time.time() + (60*60*24*365),
 
135
                                    localtime=False,
 
136
                                    usegmt=True)
 
137
        return super(VersionedMediaFileView, self)._make_filename(req)
 
138
 
 
139
 
 
140
# This maps a media namespace to an external dependency directory (in this
 
141
# case specified by the configuration option media/externals/jquery) and a
 
142
# list of permitted subpaths.
 
143
EXTERNAL_MEDIA_MAP = {'jquery': ('jquery', ['jquery.js'])}
 
144
 
 
145
class ExternalMediaFileView(BaseMediaFileView):
 
146
    '''A view for media files from external dependencies.
 
147
 
 
148
    This serves specific static files from external dependencies as defined in
 
149
    the IVLE configuration.
 
150
    '''
 
151
    permission = None
 
152
 
 
153
    def _make_filename(self, req):
 
154
        try:
 
155
            extern = EXTERNAL_MEDIA_MAP[self.ns]
 
156
        except KeyError:
 
157
            raise NotFound()
 
158
 
 
159
        # Unless it's a whitelisted path, we don't want to hear about it.
 
160
        if self.path not in extern[1]:
 
161
            raise NotFound()
 
162
 
 
163
        # Grab the admin-configured path for this particular external dep.
 
164
        externdir = req.config['media']['externals'][extern[0]]
 
165
 
 
166
        assert isinstance(externdir, basestring)
 
167
 
 
168
        return os.path.join(externdir, self.path)
 
169
 
 
170
    def get_permissions(self, user):
 
171
        return set()
 
172
 
 
173
class ExternalVersionedMediaFileView(ExternalMediaFileView):
 
174
    '''A view for versioned media files from external dependencies, with
 
175
    aggressive caching.
 
176
 
 
177
    This serves specific static media files from external dependencies with a
 
178
    version string, and requests that browsers cache them for a long time.
 
179
    '''
 
180
 
 
181
    def __init__(self, req, ns, path, version):
 
182
        super(ExternalVersionedMediaFileView, self).__init__(req, ns, path)
 
183
        self.version = version
 
184
 
 
185
    def _make_filename(self, req):
 
186
        if self.version != req.config['media']['version']:
 
187
            raise NotFound()
 
188
 
 
189
        # Don't expire for a year.
 
190
        req.headers_out['Expires'] = email.utils.formatdate(
 
191
                                    timeval=time.time() + (60*60*24*365),
 
192
                                    localtime=False,
 
193
                                    usegmt=True)
 
194
        return super(ExternalVersionedMediaFileView, self)._make_filename(req)
 
195
 
162
196
 
163
197
class Plugin(ViewPlugin, PublicViewPlugin):
164
 
    forward_routes = [(ApplicationRoot, '+media', root_to_media, INF)]
165
 
    views = [(MediaFile, '+index', MediaFileView)]
166
 
    public_forward_routes = forward_routes
167
 
    public_views = views
 
198
    urls = [
 
199
        ('+media/+:version/+external/:ns/*path', ExternalVersionedMediaFileView),
 
200
        ('+media/+external/:ns/*path', ExternalMediaFileView),
 
201
        ('+media/+:version/:ns/*path', VersionedMediaFileView),
 
202
        ('+media/:ns/*path', MediaFileView),
 
203
    ]
 
204
 
 
205
    public_urls = urls