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

« back to all changes in this revision

Viewing changes to lib/common/util.py

  • Committer: drtomc
  • Date: 2007-12-04 00:18:29 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:1
AnĀ initialĀ checkin.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# IVLE - Informatics Virtual Learning Environment
2
 
# Copyright (C) 2007-2008 The University of Melbourne
3
 
#
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.
8
 
#
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.
13
 
#
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
17
 
 
18
 
# Module: common.util
19
 
# Author: Matt Giuca
20
 
# Date: 12/12/2007
21
 
 
22
 
# Contains common utility functions.
23
 
# Also initialises mime types library. You must import util before using
24
 
# Python's builtin mimetypes module to make sure local settings are applied.
25
 
 
26
 
import os
27
 
import mimetypes
28
 
 
29
 
import conf
30
 
import conf.mimetypes
31
 
 
32
 
root_dir = conf.root_dir
33
 
 
34
 
class IVLEError(Exception):
35
 
    """
36
 
    This is the "standard" exception class for IVLE errors.
37
 
    It is the ONLY exception which should propagate to the top - it will then
38
 
    be displayed to the user as an HTTP error with the given code.
39
 
 
40
 
    All other exceptions are considered IVLE bugs and should not occur
41
 
    (they will display a traceback).
42
 
 
43
 
    This error should not be raised directly. Call req.throw_error.
44
 
    """
45
 
    def __init__(self, httpcode, message=None):
46
 
        self.httpcode = httpcode
47
 
        self.message = message
48
 
        self.args = (httpcode, message)
49
 
 
50
 
def make_path(path):
51
 
    """Given a path relative to the IVLE root, makes the path relative to the
52
 
    site root using conf.root_dir. This path can be used in URLs sent to the
53
 
    client."""
54
 
    return os.path.join(root_dir, path)
55
 
 
56
 
def make_local_path(path):
57
 
    """Given a path relative to the IVLE root, on the local file system, makes
58
 
    the path relative to the root using conf.ivle_install_dir. This path can
59
 
    be used in reading files from the local file system."""
60
 
    return os.path.join(conf.ivle_install_dir, 'www', path)
61
 
 
62
 
def unmake_path(path):
63
 
    """Given a path relative to the site root, makes the path relative to the
64
 
    IVLE root by removing conf.root_dir if it appears at the beginning. If it
65
 
    does not appear at the beginning, returns path unchanged. Also normalises
66
 
    the path."""
67
 
    path = os.path.normpath(path)
68
 
    root = os.path.normpath(root_dir)
69
 
 
70
 
    if path.startswith(root):
71
 
        path = path[len(root):]
72
 
        # Take out the slash as well
73
 
        if len(path) > 0 and path[0] == os.sep:
74
 
            path = path[1:]
75
 
 
76
 
    return path
77
 
 
78
 
def split_path(path):
79
 
    """Given a path, returns a tuple consisting of the top-level directory in
80
 
    the path, and the rest of the path. Note that both items in the tuple will
81
 
    NOT begin with a slash, regardless of whether the original path did. Also
82
 
    normalises the path.
83
 
 
84
 
    Always returns a pair of strings, except for one special case, in which
85
 
    the path is completely empty (or just a single slash). In this case the
86
 
    return value will be (None, ''). But still always returns a pair.
87
 
 
88
 
    Examples:
89
 
 
90
 
    >>> split_path("")
91
 
    (None, '')
92
 
    >>> split_path("/")
93
 
    (None, '')
94
 
    >>> split_path("home")
95
 
    ('home', '')
96
 
    >>> split_path("home/docs/files")
97
 
    ('home', 'docs/files')
98
 
    >>> split_path("//home/docs/files")
99
 
    ('', 'home/docs/files')
100
 
    """
101
 
    path = os.path.normpath(path)
102
 
    # Ignore the opening slash
103
 
    if path.startswith(os.sep):
104
 
        path = path[len(os.sep):]
105
 
    if path == '' or path == '.':
106
 
        return (None, '')
107
 
    splitpath = path.split(os.sep, 1)
108
 
    if len(splitpath) == 1:
109
 
        return (splitpath[0], '')
110
 
    else:
111
 
        return tuple(splitpath)
112
 
 
113
 
def open_exercise_file(exercisename):
114
 
    """Given an exercise name, opens the corresponding XML file for reading.
115
 
    Returns None if the exercise file was not found.
116
 
    (For tutorials / worksheets).
117
 
    """
118
 
    # First normalise the path
119
 
    exercisename = os.path.normpath(exercisename)
120
 
    # Now if it begins with ".." or separator, then it's illegal
121
 
    if exercisename.startswith("..") or exercisename.startswith(os.sep):
122
 
        exercisefile = None
123
 
    else:
124
 
        exercisefile = os.path.join(conf.exercises_base, exercisename)
125
 
 
126
 
    try:
127
 
        return open(exercisefile)
128
 
    except (TypeError, IOError):    # TypeError if exercisefile == None
129
 
        return None
130
 
 
131
 
# Initialise mime types library
132
 
mimetypes.init()
133
 
for (ext, mimetype) in conf.mimetypes.additional_mime_types.items():
134
 
    mimetypes.add_type(mimetype, ext)
135
 
 
136
 
def nice_filetype(filename):
137
 
    """Given a filename or basename, returns a "friendly" name for that
138
 
    file's type.
139
 
    eg. nice_mimetype("file.py") == "Python source code".
140
 
        nice_filetype("file.bzg") == "BZG file".
141
 
        nice_filetype("directory/") == "Directory".
142
 
    """
143
 
    if filename[-1] == os.sep:
144
 
        return "Directory"
145
 
    else:
146
 
        try:
147
 
            return conf.mimetypes.nice_mimetypes[
148
 
                mimetypes.guess_type(filename)[0]]
149
 
        except KeyError:
150
 
            filename = os.path.basename(filename)
151
 
            try:
152
 
                return filename[filename.rindex('.')+1:].upper() + " file"
153
 
            except ValueError:
154
 
                return "File"
155
 
 
156
 
def send_terms_of_service(req):
157
 
    """
158
 
    Sends the Terms of Service document to the req object.
159
 
    This consults conf to find out where the TOS is located on disk, and sends
160
 
    that. If it isn't found, it sends a generic message explaining to admins
161
 
    how to create a real one.
162
 
    """
163
 
    try:
164
 
        req.sendfile(conf.tos_path)
165
 
    except IOError:
166
 
        req.write(
167
 
"""<h1>Terms of Service</h1>
168
 
<p><b>*** SAMPLE ONLY ***</b></p>
169
 
<p>This is the text of the IVLE Terms of Service.</p>
170
 
<p>The administrator should create a license file with an appropriate
171
 
"Terms of Service" license for your organisation.</p>
172
 
<h2>Instructions for Administrators</h2>
173
 
<p>You are seeing this message because you have not configured a Terms of
174
 
Service document.</p>
175
 
<p>When you configured IVLE, you specified a path to the Terms of Service
176
 
document (this is found in <b><tt>lib/conf/conf.py</tt></b> under
177
 
"<tt>tos_path</tt>").</p>
178
 
<p>Create a file at this location; an HTML file with the appropriately-worded
179
 
license.</p>
180
 
<p>This should be a normal XHTML file, except it should not contain
181
 
<tt>html</tt>, <tt>head</tt> or <tt>body</tt> elements - it should
182
 
just be the contents of a body element (IVLE will wrap it accordingly).</p>
183
 
<p>This will automatically be used as the license text instead of this
184
 
placeholder text.</p>
185
 
""")