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

1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
1
# IVLE
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: File Service / Listing
19
# Author: Matt Giuca
20
# Date: 10/1/2008
21
22
# Handles the return part of the 2-stage process of fileservice. This
23
# is both the directory listing, and the raw serving of non-directory files.
24
25
# File Service Format.
26
# If a non-directory file is requested, then the HTTP response body will be
27
# the verbatim bytes of that file (if the file is valid). The HTTP response
28
# headers will include the guessed content type of the file, and the header
29
# "X-IVLE-Return: File".
30
31
# Directory Listing Format.
32
# If the path requested is a directory, then the HTTP response body will be
33
# a valid JSON string describing the directory. The HTTP response headers
34
# will include the header "X-IVLE-Return: Dir".
35
#
36
# The JSON structure is as follows:
37
# * The top-level value is an object. It always contains the key "listing",
38
# whose value is the primary listing object. It may also contain a key
39
# "clipboard" which contains the clipboard object.
40
# * The value for "listing" is an object, with one member for each file in the
41
#   directory, plus an additional member (key ".") for the directory itself.
42
# * Each member's key is the filename. Its value is an object, which has
43
#   various members describing the file.
44
# The members of this object are as follows:
45
#   * svnstatus: String. The svn status of the file. Either all files in a
46
#   directory or no files have an svnstatus. String may take the values:
47
#   - none - does not exist
48
#   - unversioned - is not a versioned thing in this wc
49
#   - normal - exists, but uninteresting.
50
#   - added - is scheduled for addition
51
#   - missing - under v.c., but is missing
52
#   - deleted - scheduled for deletion
53
#   - replaced - was deleted and then re-added
54
#   - modified - text or props have been modified
55
#   - merged - local mods received repos mods
56
#   - conflicted - local mods received conflicting repos mods
57
#   - ignored - a resource marked as ignored
58
#   - obstructed - an unversioned resource is in the way of the versioned resource
59
#   - external - an unversioned path populated by an svn:external property
60
#   - incomplete - a directory doesn't contain a complete entries list
61
#   (From pysvn)
62
#   If svnstatus is "Missing" then the file has no other attributes.
63
#   * published: Boolean. True if the file is published. (Marked by a
64
#       .published file in the folder)
65
#   * isdir: Boolean. True if the file is a directory. Always present unless
66
#   svnstatus is "missing".
67
#   * size: Number. Size of the file in bytes. Present for non-directory
68
#   files.
69
#   * type: String. Guessed mime type of the file. Present for non-directory
70
#   files.
71
#   * mtime: Number. Number of seconds elapsed since the epoch.
72
#   The epoch is not defined (this is an arbitrary number used for sorting
73
#   dates).
74
#   * mtime_nice: String. Modification time of the file or directory. Always
75
#   present unless svnstatus is "Missing". Human-friendly.
76
#
77
# Members are not guaranteed to be present - client code should always check
78
# for each member that it is present, and handle gracefully if a member is not
79
# present.
80
#
81
# The listing object is guaranteed to have a "." key. Use this key to
82
# determine whether the directory is under version control or not. If this
83
# member does NOT have a "svnstatus" key, or "svnstatus" is "unversioned",
84
# then the directory is not under revision control (and no other files will
85
# have "svnstatus" either).
86
#
87
# The top-level object MAY contain a "clipboard" key, which specifies the
88
# files copied to the clipboard. This can be used by the client to show the
89
# user what files will be pasted. At the very least, the client should take
90
# the presence or absence of a "clipboard" key as whether to grey out the
91
# "paste" button.
92
#
93
# The "clipboard" object has three members:
94
#   * mode: String. Either "copy" or "cut".
95
#   * base: String. Path relative to the user's root. The common path between
96
#   the files.
97
#   * files: Array of Strings. Each element is a filename relative to base.
98
#   Base and files exactly correspond to the listing path and argument paths
99
#   which were supplied during the last copy or cut request.
100
101
import os
102
import sys
103
import stat
104
import mimetypes
105
import urlparse
106
from cgi import parse_qs
107
108
import cjson
109
import pysvn
110
111
import ivle.svn
112
import ivle.date
1207 by William Grant
Move ivle.conf.mimetypes to ivle.mimetypes, and rename things in it.
113
import ivle.mimetypes
114
from ivle import studpath
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
115
116
# Make a Subversion client object
117
svnclient = pysvn.Client()
118
119
# Whether or not to ignore dot files.
120
# TODO check settings!
121
ignore_dot_files = True
122
123
# Mime types
124
# application/json is the "best" content type but is not good for
125
# debugging because Firefox just tries to download it
126
mime_dirlisting = "text/plain"
127
#mime_dirlisting = "application/json"
128
129
def handle_return(req, return_contents):
130
    """
131
    Perform the "return" part of the response.
132
    This function returns the file or directory listing contained in
133
    req.path. Sets the HTTP response code in req, writes additional headers,
134
    and writes the HTTP response, if any.
135
136
    If return_contents is True, and the path is a non-directory, returns the
137
    contents of the file verbatim. If False, returns a directory listing
138
    with a single file, ".", and info about the file.
139
140
    If the path is a directory, return_contents is ignored.
141
    """
142
1272 by William Grant
.. and one more
143
    path = studpath.to_home_path(req.path)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
144
145
    # FIXME: What to do about req.path == ""?
146
    # Currently goes to 403 Forbidden.
147
    urlpath = urlparse.urlparse(path)
148
    path = urlpath[2]
1089 by chadnickbok
Fixes Issue #14
149
    json = None
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
150
    if path is None:
151
        req.status = req.HTTP_FORBIDDEN
152
        req.headers_out['X-IVLE-Return-Error'] = 'Forbidden'
153
        req.write("Forbidden")
1193 by Matt Giuca
ivle.svn: Added revision_is_dir (like os.path.isdir for revision history).
154
        return
155
156
    # If this is a repository-revision request, it needs to be treated
157
    # differently than if it were a regular file request.
158
    # Note: If there IS a revision requested but the file doesn't exist in
159
    # that revision, this will terminate.
160
    revision = _get_revision_or_die(req, svnclient, path)
161
1194 by Matt Giuca
fileservice: Fixed a bug when browsing previous revisions, that the
162
    if revision is None:
163
        if not os.access(path, os.R_OK):
164
            req.status = req.HTTP_NOT_FOUND
165
            req.headers_out['X-IVLE-Return-Error'] = 'File not found'
166
            req.write("File not found")
167
            return
168
        is_dir = os.path.isdir(path)
169
    else:
170
        is_dir = ivle.svn.revision_is_dir(svnclient, path, revision)
171
172
    if is_dir:
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
173
        # It's a directory. Return the directory listing.
174
        req.content_type = mime_dirlisting
175
        req.headers_out['X-IVLE-Return'] = 'Dir'
1089 by chadnickbok
Fixes Issue #14
176
        # TODO: Fix this dirty, dirty hack
1193 by Matt Giuca
ivle.svn: Added revision_is_dir (like os.path.isdir for revision history).
177
        newjson = get_dirlisting(req, svnclient, path, revision)
1089 by chadnickbok
Fixes Issue #14
178
        if ("X-IVLE-Action-Error" in req.headers_out):
179
            newjson["Error"] = req.headers_out["X-IVLE-Action-Error"]
180
        req.write(cjson.encode(newjson))
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
181
    elif return_contents:
182
        # It's a file. Return the file contents.
183
        # First get the mime type of this file
184
        (type, _) = mimetypes.guess_type(path)
185
        if type is None:
1207 by William Grant
Move ivle.conf.mimetypes to ivle.mimetypes, and rename things in it.
186
            type = ivle.mimetypes.DEFAULT_MIMETYPE
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
187
        req.content_type = type
188
        req.headers_out['X-IVLE-Return'] = 'File'
189
1193 by Matt Giuca
ivle.svn: Added revision_is_dir (like os.path.isdir for revision history).
190
        send_file(req, svnclient, path, revision)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
191
    else:
192
        # It's a file. Return a "fake directory listing" with just this file.
193
        req.content_type = mime_dirlisting
194
        req.headers_out['X-IVLE-Return'] = 'File'
1193 by Matt Giuca
ivle.svn: Added revision_is_dir (like os.path.isdir for revision history).
195
        req.write(cjson.encode(get_dirlisting(req, svnclient, path,
196
                                              revision)))
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
197
198
def _get_revision_or_die(req, svnclient, path):
1192 by Matt Giuca
ivle.fileservice_lib.listing: Proper docstring for the rather confusing
199
    """Looks for a revision specification in req's URL.
200
    Errors and terminates the request if the specification was bad, or it
201
    doesn't exist for the given path.
202
    @param req: Request object.
203
    @param svnclient: pysvn Client object.
204
    @param path: Path to the file whose revision is to be retrieved.
205
    @returns: pysvn Revision object, for the file+revision specified, or None
206
        if there was no revision specified.
207
    """
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
208
    # Work out the revisions from query
209
    r_str = req.get_fieldstorage().getfirst("r")
210
    revision = ivle.svn.revision_from_string(r_str)
211
212
    # Was some revision specified AND (it didn't resolve OR it was nonexistent)
213
    if r_str and not (revision and
214
                      ivle.svn.revision_exists(svnclient, path, revision)):
215
        req.status = req.HTTP_NOT_FOUND
1195 by Matt Giuca
Fileservice: Improved the error message "Revision not found" to
216
        message = ('Revision not found or file not found in revision %d' %
217
                   revision.number)
218
        req.headers_out['X-IVLE-Return-Error'] = message
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
219
        req.ensure_headers_written()
1195 by Matt Giuca
Fileservice: Improved the error message "Revision not found" to
220
        req.write(message)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
221
        req.flush()
222
        sys.exit()
223
    return revision
224
1193 by Matt Giuca
ivle.svn: Added revision_is_dir (like os.path.isdir for revision history).
225
def send_file(req, svnclient, path, revision):
226
    """Given a local absolute path to a file, sends the contents of the file
227
    to the client.
228
229
    @param req: Request object. Will not be mutated; just reads the session.
230
    @param svnclient: Svn client object.
231
    @param path: String. Absolute path on the local file system. Not checked,
232
        must already be guaranteed safe. May be a file or a directory.
233
    @param revision: pysvn Revision object for the given path, or None.
234
    """
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
235
    if revision:
236
        req.write(svnclient.cat(path, revision=revision))
237
    else:
238
        req.sendfile(path)
239
1193 by Matt Giuca
ivle.svn: Added revision_is_dir (like os.path.isdir for revision history).
240
def get_dirlisting(req, svnclient, path, revision):
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
241
    """Given a local absolute path, creates a directory listing object
242
    ready to be JSONized and sent to the client.
243
1193 by Matt Giuca
ivle.svn: Added revision_is_dir (like os.path.isdir for revision history).
244
    @param req: Request object. Will not be mutated; just reads the session.
245
    @param svnclient: Svn client object.
246
    @param path: String. Absolute path on the local file system. Not checked,
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
247
        must already be guaranteed safe. May be a file or a directory.
1193 by Matt Giuca
ivle.svn: Added revision_is_dir (like os.path.isdir for revision history).
248
    @param revision: pysvn Revision object for the given path, or None.
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
249
    """
250
251
    # Start by trying to do an SVN status, so we can report file version
252
    # status
253
    listing = {}
254
    try:
255
        if revision:
256
            ls_list = svnclient.list(path, revision=revision, recurse=False)
257
            for ls in ls_list:
258
                filename, attrs = PysvnList_to_fileinfo(path, ls)
259
                listing[filename.decode('utf-8')] = attrs
260
        else:
261
            status_list = svnclient.status(path, recurse=False, get_all=True,
262
                        update=False)
263
            for status in status_list:
264
                filename, attrs = PysvnStatus_to_fileinfo(path, status)
265
                listing[filename.decode('utf-8')] = attrs
266
    except pysvn.ClientError:
267
        # Presumably the directory is not under version control.
268
        # Fallback to just an OS file listing.
269
        try:
270
            for filename in os.listdir(path):
271
                listing[filename.decode('utf-8')] = file_to_fileinfo(path, filename)[1]
1086 by chadnickbok
This commit fixes issue #10 and part of issue #9
272
                try:
273
                    svnclient.status(os.path.join(path, filename), recurse = False)
274
                    listing[filename.decode('utf-8')]['svnstatus'] = 'normal'
275
                except:
276
                    pass
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
277
        except OSError:
278
            # Non-directories will error - that's OK, we just want the "."
279
            pass
280
        # The subversion one includes "." while the OS one does not.
281
        # Add "." to the output, so the caller can see we are
282
        # unversioned.
283
        listing["."] = file_to_fileinfo(path, "")[1]
284
285
    if ignore_dot_files:
286
        for fn in listing.keys():
287
            if fn != "." and fn.startswith("."):
288
                del listing[fn]
289
290
    # Listing is a nested object inside the top-level JSON.
291
    listing = {"listing" : listing}
292
293
    if revision:
294
        listing['revision'] = revision.number
295
296
    # The other object is the clipboard, if present in the browser session.
297
    # This can go straight from the session to JSON.
298
    session = req.get_session()
299
    if session and 'clipboard' in session:
300
        # In CGI mode, we can't get our hands on the
301
        # session (for the moment), so just leave it out.
302
        listing['clipboard'] = session['clipboard']
303
    
304
    return listing
305
306
def _fullpath_stat_fileinfo(fullpath):
307
    file_stat = os.stat(fullpath)
308
    return _stat_fileinfo(fullpath, file_stat)
309
310
def _stat_fileinfo(fullpath, file_stat):
311
    d = {}
312
    if stat.S_ISDIR(file_stat.st_mode):
313
        d["isdir"] = True
1207 by William Grant
Move ivle.conf.mimetypes to ivle.mimetypes, and rename things in it.
314
        d["type_nice"] = ivle.mimetypes.nice_filetype("/")
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
315
        # Only directories can be published
316
        d["published"] = studpath.published(fullpath)
317
    else:
318
        d["isdir"] = False
319
        d["size"] = file_stat.st_size
320
        (type, _) = mimetypes.guess_type(fullpath)
321
        if type is None:
1207 by William Grant
Move ivle.conf.mimetypes to ivle.mimetypes, and rename things in it.
322
            type = ivle.mimetypes.DEFAULT_MIMETYPE
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
323
        d["type"] = type
1207 by William Grant
Move ivle.conf.mimetypes to ivle.mimetypes, and rename things in it.
324
        d["type_nice"] = ivle.mimetypes.nice_filetype(fullpath)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
325
    d["mtime"] = file_stat.st_mtime
326
    d["mtime_nice"] = ivle.date.make_date_nice(file_stat.st_mtime)
327
    d["mtime_short"] = ivle.date.make_date_nice_short(file_stat.st_mtime)
328
    return d
329
330
def file_to_fileinfo(path, filename):
331
    """Given a filename (relative to a given path), gets all the info "ls"
332
    needs to display about the filename. Returns pair mapping filename to
333
    a dict containing a number of other fields."""
334
    fullpath = path if filename in ('', '.') else os.path.join(path, filename)
335
    return filename, _fullpath_stat_fileinfo(fullpath)
336
337
def PysvnStatus_to_fileinfo(path, status):
338
    """Given a PysvnStatus object, gets all the info "ls"
339
    needs to display about the filename. Returns a pair mapping filename to
340
    a dict containing a number of other fields."""
341
    path = os.path.normcase(path)
342
    fullpath = status.path
343
    # If this is "." (the directory itself)
344
    if path == os.path.normcase(fullpath):
345
        # If this directory is unversioned, then we aren't
346
        # looking at any interesting files, so throw
347
        # an exception and default to normal OS-based listing. 
348
        if status.text_status == pysvn.wc_status_kind.unversioned:
349
            raise pysvn.ClientError
350
        # We actually want to return "." because we want its
351
        # subversion status.
352
        filename = "."
353
    else:
354
        filename = os.path.basename(fullpath)
355
    text_status = status.text_status
356
    d = {'svnstatus': str(text_status)}
1165.1.31 by William Grant
Expose SVN revision and URL information through fileservice.
357
358
    if status.entry is not None:
359
        d.update({
360
           'svnurl': status.entry.url,
361
           'svnrevision': status.entry.revision.number
362
             if status.entry.revision.kind == pysvn.opt_revision_kind.number
363
             else None,
364
        })
365
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
366
    try:
367
        d.update(_fullpath_stat_fileinfo(fullpath))
368
    except OSError:
369
        # Here if, eg, the file is missing.
370
        # Can't get any more information so just return d
371
        pass
372
    return filename, d
373
374
def PysvnList_to_fileinfo(path, list):
375
    """Given a List object from pysvn.Client.list, gets all the info "ls"
376
    needs to display about the filename. Returns a pair mapping filename to
377
    a dict containing a number of other fields."""
378
    path = os.path.normcase(path)
379
    pysvnlist = list[0]
380
    fullpath = pysvnlist.path
381
    # If this is "." (the directory itself)
382
    if path == os.path.normcase(fullpath):
383
        # If this directory is unversioned, then we aren't
384
        # looking at any interesting files, so throw
385
        # an exception and default to normal OS-based listing. 
386
        #if status.text_status == pysvn.wc_status_kind.unversioned:
387
        #    raise pysvn.ClientError
388
        # We actually want to return "." because we want its
389
        # subversion status.
390
        filename = "."
391
    else:
392
        filename = os.path.basename(fullpath)
393
    d = {'svnstatus': 'revision'} # A special status.
394
395
    wrapped = ivle.svn.PysvnListStatWrapper(pysvnlist)
396
    d.update(_stat_fileinfo(fullpath, wrapped))
397
398
    return filename, d