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

« back to all changes in this revision

Viewing changes to ivle/dispatch/request.py

  • Committer: David Coles
  • Date: 2010-07-28 10:52:48 UTC
  • mfrom: (1791.2.10 mediahandlers)
  • Revision ID: coles.david@gmail.com-20100728105248-zvbn9g72v1nsskvd
A series of HTML5 based media handlers using the <audio> and <video> tags.  
This replaces the previous page that just showed a download link (which is 
already available on the menu).

Also solves issue where media files were downloaded by the client twice (once 
in an AJAX request intended only for text).

Known issues:
    * Bug #588285: External BHO will not be able to play media due to not
      having IVLE cookie.
    * Bug #610745: Does not correctly preview revisions
    * Bug #610780: Ogg media does not work in Chromium

Show diffs side-by-side

added added

removed removed

Lines of Context:
29
29
    import mod_python.Session
30
30
    import mod_python.Cookie
31
31
    import mod_python.util
 
32
    import mod_python.apache
 
33
 
 
34
    class PotentiallySecureFileSession(mod_python.Session.FileSession):
 
35
        """A mod_python FileSession that sets secure cookie when appropriate.
 
36
 
 
37
        A secure cookie will be set if the request itself is over HTTPS, or if
 
38
        a proxy in front has set X-Forwarded-Proto: https. Otherwise the cookie
 
39
        will be insecure.
 
40
        """
 
41
        def make_cookie(self):
 
42
            cookie = super(PotentiallySecureFileSession, self).make_cookie()
 
43
            if (self._req.is_https() or
 
44
                self._req.headers_in.get('X-Forwarded-Proto') == 'https'):
 
45
                cookie.secure = True
 
46
            return cookie
32
47
except ImportError:
33
48
    # This needs to be importable from outside Apache.
34
49
    pass
38
53
import ivle.util
39
54
import ivle.database
40
55
from ivle.webapp.base.plugins import CookiePlugin
 
56
import ivle.webapp.security
 
57
 
41
58
 
42
59
class Request:
43
60
    """An IVLE request object. This is presented to the IVLE apps as a way of
48
65
            String. The request method (eg. 'GET', 'POST', etc)
49
66
        uri (read)
50
67
            String. The path portion of the URI.
 
68
        unparsed_uri (read)
 
69
            String. The path portion of the URI, unparsed with query string.
51
70
        app (read)
52
71
            String. Name of the application specified in the URL, or None.
53
72
        path (read)
76
95
            in class Request.
77
96
        content_type (write)
78
97
            String. The Content-Type (mime type) header value.
 
98
        content_length (write)
 
99
            Integer. The number of octets to be transfered.
79
100
        location (write)
80
101
            String. Response "Location" header value. Used with HTTP redirect
81
102
            responses.
94
115
    HTTP_NOT_FOUND                    = 404
95
116
    HTTP_INTERNAL_SERVER_ERROR        = 500
96
117
 
 
118
    _store = None
 
119
 
97
120
    def __init__(self, req, config):
98
121
        """Create an IVLE request from a mod_python one.
99
122
 
116
139
        # Inherit values for the input members
117
140
        self.method = req.method
118
141
        self.uri = req.uri
 
142
        self.unparsed_uri = req.unparsed_uri
119
143
        # Split the given path into the app (top-level dir) and sub-path
120
144
        # (after first stripping away the root directory)
121
 
        path = self.unmake_path(req.uri)
122
 
        (self.app, self.path) = (ivle.util.split_path(path))
123
 
        self.user = None
 
145
        (self.app, self.path) = (ivle.util.split_path(req.uri))
124
146
        self.hostname = req.hostname
125
147
        self.headers_in = req.headers_in
126
148
        self.headers_out = req.headers_out
127
149
 
128
 
        # Open a database connection and transaction, keep it around for users
129
 
        # of the Request object to use
130
 
        self.store = ivle.database.get_store(config)
131
 
 
132
150
        # Default values for the output members
133
151
        self.status = Request.HTTP_OK
134
152
        self.content_type = None        # Use Apache's default
 
153
        self.content_length = None        # Don't provide Content-Length
135
154
        self.location = None
136
155
        # In some cases we don't want the template JS (such as the username
137
156
        # and public FQDN) in the output HTML. In that case, set this to 0.
139
158
        self.got_common_vars = False
140
159
 
141
160
    def __del__(self):
142
 
        """Cleanup."""
143
 
        self.store.close()
 
161
        self.cleanup()
 
162
 
 
163
    def cleanup(self):
 
164
        """Cleanup."""
 
165
        if self._store is not None:
 
166
            self._store.close()
 
167
            self._store = None
 
168
 
 
169
    def commit(self):
 
170
        """Cleanup."""
 
171
        if self._store is not None:
 
172
            self._store.commit()
144
173
 
145
174
    def __writeheaders(self):
146
175
        """Writes out the HTTP and HTML headers before any real data is
150
179
        # Prepare the HTTP and HTML headers before the first write is made
151
180
        if self.content_type != None:
152
181
            self.apache_req.content_type = self.content_type
 
182
        if self.content_length:
 
183
            self.apache_req.set_content_length(self.content_length)
153
184
        self.apache_req.status = self.status
154
185
        if self.location != None:
155
186
            self.apache_req.headers_out['Location'] = self.location
238
269
        """
239
270
        return os.path.join(self.config['urls']['root'], path)
240
271
 
241
 
    def unmake_path(self, path):
242
 
        """Strip the IVLE URL prefix from the given path, if present.
243
 
 
244
 
        Also normalises the path.
245
 
 
246
 
        This method is DEPRECATED. We no longer support use of a prefix.
247
 
        """
248
 
        path = os.path.normpath(path)
249
 
        root = os.path.normpath(self.config['urls']['root'])
250
 
 
251
 
        if path.startswith(root):
252
 
            path = path[len(root):]
253
 
            # Take out the slash as well
254
 
            if len(path) > 0 and path[0] == os.sep:
255
 
                path = path[1:]
256
 
 
257
 
        return path
258
 
 
259
272
    def get_session(self):
260
273
        """Returns a mod_python Session object for this request.
261
274
        Note that this is dependent on mod_python and may need to change
266
279
        """
267
280
        # Cache the session object and set the timeout to 24 hours.
268
281
        if not hasattr(self, 'session'):
269
 
            self.session = mod_python.Session.FileSession(self.apache_req,
270
 
                                               timeout = 60 * 60 * 24)
 
282
            self.session = PotentiallySecureFileSession(
 
283
                self.apache_req, timeout = 60 * 60 * 24)
271
284
        return self.session
272
285
 
273
286
    def get_fieldstorage(self):
288
301
            self.got_common_vars = True
289
302
        return self.apache_req.subprocess_env
290
303
 
291
 
    @staticmethod
292
 
    def get_http_codename(code):
293
 
        """Given a HTTP error code int, returns a (name, description)
294
 
        pair, suitable for displaying to the user.
295
 
        May return (None,None) if code is unknown.
296
 
        Only lists common 4xx and 5xx codes (since this is just used
297
 
        to display throw_error error messages).
298
 
        """
 
304
    @property
 
305
    def store(self):
 
306
        # Open a database connection and transaction, keep it around for users
 
307
        # of the Request object to use.
 
308
        if self._store is None:
 
309
            self._store = ivle.database.get_store(self.config)
 
310
        return self._store
 
311
 
 
312
    @property
 
313
    def user(self):
 
314
        # Get and cache the request user, or None if it's not valid.
 
315
        # This is a property so that we don't create a store unless
 
316
        # some code actually requests the user.
299
317
        try:
300
 
            return http_codenames[code]
301
 
        except KeyError:
302
 
            return None, None
 
318
            return self._user
 
319
        except AttributeError:
 
320
            if self.publicmode:
 
321
                self._user = None
 
322
            else:
 
323
                temp_user = ivle.webapp.security.get_user_details(self)
 
324
                if temp_user and temp_user.valid:
 
325
                    self._user = temp_user
 
326
                else:
 
327
                    self._user = None
 
328
            return self._user
303
329
 
304
 
# Human strings for HTTP response codes
305
 
http_codenames = {
306
 
    Request.HTTP_FORBIDDEN:
307
 
        ("Forbidden",
308
 
        "You are not allowed to view this part of IVLE."),
309
 
    Request.HTTP_NOT_FOUND:
310
 
        ("Not Found",
311
 
        "The application or file you requested does not exist."),
312
 
    Request.HTTP_INTERNAL_SERVER_ERROR:
313
 
        ("Internal Server Error",
314
 
        "An unknown error occured in IVLE."),
315
 
}