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

« back to all changes in this revision

Viewing changes to www/apps/fileservice/action.py

  • Committer: mattgiuca
  • Date: 2008-02-03 11:38:23 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:387
Implemented file uploads.
fileservice: Added "putfiles" action (slightly different to putfile action;
    see comments at top which discuss the difference).
browser/listing: Added "upload" button to side panel, which opens an upload
    panel with a file selection dialog. This uses a little trick (documented
    in the code) to get the upload to work without refreshing the page.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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 / Action
 
19
# Author: Matt Giuca
 
20
# Date: 10/1/2008
 
21
 
 
22
# Handles actions requested by the client as part of the 2-stage process of
 
23
# fileservice (the second part being the return listing).
 
24
 
 
25
### Actions ###
 
26
 
 
27
# The most important argument is "action". This determines which action is
 
28
# taken. Note that action, and all other arguments, are ignored unless the
 
29
# request is a POST request. The other arguments depend upon the action.
 
30
# Note that paths are often specified as arguments. Paths that begin with a
 
31
# slash are taken relative to the user's home directory (the top-level
 
32
# directory seen when fileservice has no arguments or path). Paths without a
 
33
# slash are taken relative to the specified path.
 
34
 
 
35
# action=remove: Delete a file(s) or directory(s) (recursively).
 
36
#       path:   The path to the file or directory to delete. Can be specified
 
37
#               multiple times.
 
38
#
 
39
# action=move: Move or rename a file or directory.
 
40
#       from:   The path to the file or directory to be renamed.
 
41
#       to:     The path of the target filename. Error if the file already
 
42
#               exists.
 
43
#
 
44
# action=putfile: Upload a file to the student workspace, and optionally
 
45
#               accept zip files which will be unpacked.
 
46
#       path:   The path to the file to be written. If it exists, will
 
47
#               overwrite. Error if the target file is a directory.
 
48
#       data:   Bytes to be written to the file verbatim. May either be
 
49
#               a string variable or a file upload.
 
50
#       unpack: Optional. If "true", and the data is a valid ZIP file,
 
51
#               will create a directory instead and unpack the ZIP file
 
52
#               into it.
 
53
#
 
54
# action=putfiles: Upload multiple files to the student workspace, and
 
55
#                 optionally accept zip files which will be unpacked.
 
56
#       path:   The path to the DIRECTORY to place files in. Must not be a
 
57
#               file.
 
58
#       data:   A file upload (may not be a simple string). The filename
 
59
#               will be used to determine the target filename within
 
60
#               the given path.
 
61
#       unpack: Optional. If "true", if any data is a valid ZIP file,
 
62
#               will create a directory instead and unpack the ZIP file
 
63
#               into it.
 
64
#
 
65
# The differences between putfile and putfiles are:
 
66
# * putfile can only accept a single file.
 
67
# * putfile can accept string data, doesn't have to be a file upload.
 
68
# * putfile ignores the upload filename, the entire filename is specified on
 
69
#       path. putfiles calls files after the name on the user's machine.
 
70
#
 
71
# Clipboard-based actions. Cut/copy/paste work in the same way as modern
 
72
# file browsers, by keeping a server-side clipboard of files that have been
 
73
# cut and copied. The clipboard is stored in the session data, so it persists
 
74
# across navigation, tabs and browser windows, but not across browser
 
75
# sessions.
 
76
 
77
# action=copy: Write file(s) to the session-based clipboard. Overrides any
 
78
#               existing clipboard data. Does not actually copy the file.
 
79
#               The files are physically copied when the clipboard is pasted.
 
80
#       path:   The path to the file or directory to copy. Can be specified
 
81
#               multiple times.
 
82
 
83
# action=cut: Write file(s) to the session-based clipboard. Overrides any
 
84
#               existing clipboard data. Does not actually move the file.
 
85
#               The files are physically moved when the clipboard is pasted.
 
86
#       path:   The path to the file or directory to cut. Can be specified
 
87
#               multiple times.
 
88
 
89
# action=paste: Copy or move the files stored in the clipboard. Clears the
 
90
#               clipboard. The files are copied or moved to a specified dir.
 
91
#       path:   The path to the DIRECTORY to paste the files to. Must not
 
92
#               be a file.
 
93
#
 
94
# Subversion actions.
 
95
# action=svnadd: Add an existing file(s) to version control.
 
96
#       path:   The path to the file to be added. Can be specified multiple
 
97
#               times.
 
98
#
 
99
# action=svnrevert: Revert a file(s) to its state as of the current revision
 
100
#               / undo local edits.
 
101
#       path:   The path to the file to be reverted. Can be specified multiple
 
102
#               times.
 
103
#
 
104
# action=svnupdate: Bring a file up to date with the head revision.
 
105
#       path:   The path to the file to be updated. Only one file may be
 
106
#               specified.
 
107
#
 
108
# action=svnpublish: Set the "published" flag on a file to True.
 
109
#       path:   The path to the file to be published. Can be specified
 
110
#               multiple times.
 
111
#
 
112
# action=svnunpublish: Set the "published" flag on a file to False.
 
113
#       path:   The path to the file to be unpublished. Can be specified
 
114
#               multiple times.
 
115
#
 
116
# action=svncommit: Commit a file(s) or directory(s) to the repository.
 
117
#       path:   The path to the file or directory to be committed. Can be
 
118
#               specified multiple times. Directories are committed
 
119
#               recursively.
 
120
#       logmsg: Text of the log message. Optional. There is a default log
 
121
#               message if unspecified.
 
122
 
123
# TODO: Implement the following actions:
 
124
#   putfiles, svnrevert, svnupdate, svncommit
 
125
# TODO: Implement ZIP unpacking in putfile and putfiles.
 
126
# TODO: svnupdate needs a digest to tell the user the files that were updated.
 
127
#   This can be implemented by some message passing between action and
 
128
#   listing, and having the digest included in the listing. (Problem if
 
129
#   the listing is not a directory, but we could make it an error to do an
 
130
#   update if the path is not a directory).
 
131
 
 
132
import os
 
133
import shutil
 
134
 
 
135
import pysvn
 
136
 
 
137
from common import (util, studpath)
 
138
 
 
139
# Make a Subversion client object
 
140
svnclient = pysvn.Client()
 
141
 
 
142
DEFAULT_LOGMESSAGE = "No log message supplied."
 
143
 
 
144
# Mime types
 
145
# application/json is the "best" content type but is not good for
 
146
# debugging because Firefox just tries to download it
 
147
mime_dirlisting = "text/html"
 
148
#mime_dirlisting = "application/json"
 
149
 
 
150
class ActionError(Exception):
 
151
    """Represents an error processing an action. This can be
 
152
    raised by any of the action functions, and will be caught
 
153
    by the top-level handler, put into the HTTP response field,
 
154
    and continue.
 
155
 
 
156
    Important Security Consideration: The message passed to this
 
157
    exception will be relayed to the client.
 
158
    """
 
159
    pass
 
160
 
 
161
def handle_action(req, action, fields):
 
162
    """Perform the "action" part of the response.
 
163
    This function should only be called if the response is a POST.
 
164
    This performs the action's side-effect on the server. If unsuccessful,
 
165
    writes the X-IVLE-Action-Error header to the request object. Otherwise,
 
166
    does not touch the request object. Does NOT write any bytes in response.
 
167
 
 
168
    May throw an ActionError. The caller should put this string into the
 
169
    X-IVLE-Action-Error header, and then continue normally.
 
170
 
 
171
    action: String, the action requested. Not sanitised.
 
172
    fields: FieldStorage object containing all arguments passed.
 
173
    """
 
174
    global actions_table        # Table of function objects
 
175
    try:
 
176
        action = actions_table[action]
 
177
    except KeyError:
 
178
        # Default, just send an error but then continue
 
179
        raise ActionError("Unknown action")
 
180
    action(req, fields)
 
181
 
 
182
def actionpath_to_local(req, path):
 
183
    """Determines the local path upon which an action is intended to act.
 
184
    Note that fileservice actions accept two paths: the request path,
 
185
    and the "path" argument given to the action.
 
186
    According to the rules, if the "path" argument begins with a '/' it is
 
187
    relative to the user's home; if it does not, it is relative to the
 
188
    supplied path.
 
189
 
 
190
    This resolves the path, given the request and path argument.
 
191
 
 
192
    May raise an ActionError("Invalid path"). The caller is expected to
 
193
    let this fall through to the top-level handler, where it will be
 
194
    put into the HTTP response field. Never returns None.
 
195
 
 
196
    Does not mutate req.
 
197
    """
 
198
    if path is None:
 
199
        path = req.path
 
200
    elif len(path) > 0 and path[0] == os.sep:
 
201
        # Relative to student home
 
202
        path = path[1:]
 
203
    else:
 
204
        # Relative to req.path
 
205
        path = os.path.join(req.path, path)
 
206
 
 
207
    _, r = studpath.url_to_local(path)
 
208
    if r is None:
 
209
        raise ActionError("Invalid path")
 
210
    return r
 
211
 
 
212
def movefile(req, frompath, topath, copy=False):
 
213
    """Performs a file move, resolving filenames, checking for any errors,
 
214
    and throwing ActionErrors if necessary. Can also be used to do a copy
 
215
    operation instead.
 
216
 
 
217
    frompath and topath are straight paths from the client. Will be checked.
 
218
    """
 
219
    # TODO: Do an SVN mv if the file is versioned.
 
220
    # TODO: Disallow tampering with student's home directory
 
221
    if frompath is None or topath is None:
 
222
        raise ActionError("Required field missing")
 
223
    frompath = actionpath_to_local(req, frompath)
 
224
    topath = actionpath_to_local(req, topath)
 
225
    if not os.path.exists(frompath):
 
226
        raise ActionError("The source file does not exist")
 
227
    if os.path.exists(topath):
 
228
        if frompath == topath:
 
229
            raise ActionError("Source and destination are the same")
 
230
        raise ActionError("Another file already exists with that name")
 
231
 
 
232
    try:
 
233
        if copy:
 
234
            if os.path.isdir(frompath):
 
235
                shutil.copytree(frompath, topath)
 
236
            else:
 
237
                shutil.copy2(frompath, topath)
 
238
        else:
 
239
            shutil.move(frompath, topath)
 
240
    except OSError:
 
241
        raise ActionError("Could not move the file specified")
 
242
    except shutil.Error:
 
243
        raise ActionError("Could not move the file specified")
 
244
 
 
245
### ACTIONS ###
 
246
 
 
247
def action_remove(req, fields):
 
248
    # TODO: Do an SVN rm if the file is versioned.
 
249
    # TODO: Disallow removal of student's home directory
 
250
    """Removes a list of files or directories.
 
251
 
 
252
    Reads fields: 'path' (multiple)
 
253
    """
 
254
    paths = fields.getlist('path')
 
255
    goterror = False
 
256
    for path in paths:
 
257
        path = actionpath_to_local(req, path)
 
258
        try:
 
259
            if os.path.isdir(path):
 
260
                shutil.rmtree(path)
 
261
            else:
 
262
                os.remove(path)
 
263
        except OSError:
 
264
            goterror = True
 
265
        except shutil.Error:
 
266
            goterror = True
 
267
    if goterror:
 
268
        if len(paths) == 1:
 
269
            raise ActionError("Could not delete the file specified")
 
270
        else:
 
271
            raise ActionError(
 
272
                "Could not delete one or more of the files specified")
 
273
 
 
274
def action_move(req, fields):
 
275
    # TODO: Do an SVN mv if the file is versioned.
 
276
    # TODO: Disallow tampering with student's home directory
 
277
    """Removes a list of files or directories.
 
278
 
 
279
    Reads fields: 'from', 'to'
 
280
    """
 
281
    frompath = fields.getfirst('from')
 
282
    topath = fields.getfirst('to')
 
283
    movefile(req, frompath, topath)
 
284
 
 
285
def action_putfile(req, fields):
 
286
    """Writes data to a file, overwriting it if it exists and creating it if
 
287
    it doesn't.
 
288
 
 
289
    Reads fields: 'path', 'data' (file upload)
 
290
    """
 
291
    # TODO: Read field "unpack".
 
292
    # Important: Data is "None" if the file submitted is empty.
 
293
    path = fields.getfirst('path')
 
294
    data = fields.getfirst('data')
 
295
    if path is None:
 
296
        raise ActionError("Required field missing")
 
297
    path = actionpath_to_local(req, path)
 
298
    if data is not None:
 
299
        data = data.file
 
300
 
 
301
    # Copy the contents of file object 'data' to the path 'path'
 
302
    try:
 
303
        dest = open(path, 'wb')
 
304
        if data is not None:
 
305
            shutil.copyfileobj(data, dest)
 
306
    except OSError:
 
307
        raise ActionError("Could not write to target file")
 
308
 
 
309
def action_putfiles(req, fields):
 
310
    """Writes data to one or more files in a directory, overwriting them if
 
311
    it they exist.
 
312
 
 
313
    Reads fields: 'path', 'data' (file upload)
 
314
    """
 
315
    # TODO: Read field "unpack".
 
316
    # Important: Data is "None" if the file submitted is empty.
 
317
    path = fields.getfirst('path')
 
318
    data = fields.getlist('data')
 
319
    if path is None:
 
320
        raise ActionError("Required field missing")
 
321
    path = actionpath_to_local(req, path)
 
322
    goterror = False
 
323
 
 
324
    for datum in data:
 
325
        # Each of the uploaded files
 
326
        filepath = os.path.join(path, datum.filename)
 
327
        filedata = datum.file
 
328
 
 
329
        # Copy the contents of file object 'data' to the path 'path'
 
330
        try:
 
331
            dest = open(filepath, 'wb')
 
332
            if data is not None:
 
333
                shutil.copyfileobj(filedata, dest)
 
334
        except OSError:
 
335
            goterror = True
 
336
 
 
337
    if goterror:
 
338
        if len(data) == 1:
 
339
            raise ActionError("Could not write to target file")
 
340
        else:
 
341
            raise ActionError(
 
342
                "Could not write to one or more of the target files")
 
343
 
 
344
def action_copy_or_cut(req, fields, mode):
 
345
    """Marks specified files on the clipboard, stored in the
 
346
    browser session. Sets clipboard for either a cut or copy operation
 
347
    as specified.
 
348
 
 
349
    Reads fields: 'path'
 
350
    """
 
351
    # The clipboard object created conforms to the JSON clipboard
 
352
    # specification given at the top of listing.py.
 
353
    # Note that we do not check for the existence of files here. That is done
 
354
    # in the paste operation.
 
355
    files = fields.getlist('path')
 
356
    files = map(lambda field: field.value, files)
 
357
    clipboard = { "mode" : mode, "base" : req.path, "files" : files }
 
358
    session = req.get_session()
 
359
    session['clipboard'] = clipboard
 
360
    session.save()
 
361
 
 
362
def action_copy(req, fields):
 
363
    """Marks specified files on the clipboard, stored in the
 
364
    browser session. Sets clipboard for a "copy" action.
 
365
 
 
366
    Reads fields: 'path'
 
367
    """
 
368
    action_copy_or_cut(req, fields, "copy")
 
369
 
 
370
def action_cut(req, fields):
 
371
    """Marks specified files on the clipboard, stored in the
 
372
    browser session. Sets clipboard for a "cut" action.
 
373
 
 
374
    Reads fields: 'path'
 
375
    """
 
376
    action_copy_or_cut(req, fields, "cut")
 
377
 
 
378
def action_paste(req, fields):
 
379
    """Performs the copy or move action with the files stored on
 
380
    the clipboard in the browser session. Copies/moves the files
 
381
    to the specified directory. Clears the clipboard.
 
382
 
 
383
    Reads fields: 'path'
 
384
    """
 
385
    errormsg = None
 
386
 
 
387
    todir = fields.getfirst('path')
 
388
    if todir is None:
 
389
        raise ActionError("Required field missing")
 
390
    todir_local = actionpath_to_local(req, todir)
 
391
    if not os.path.isdir(todir_local):
 
392
        raise ActionError("Target is not a directory")
 
393
 
 
394
    session = req.get_session()
 
395
    try:
 
396
        clipboard = session['clipboard']
 
397
        files = clipboard['files']
 
398
        base = clipboard['base']
 
399
        if clipboard['mode'] == "copy":
 
400
            copy = True
 
401
        else:
 
402
            copy = False
 
403
    except KeyError:
 
404
        raise ActionError("Clipboard was empty")
 
405
 
 
406
    errorfiles = []
 
407
    for file in files:
 
408
        # The source must not be interpreted as relative to req.path
 
409
        # Add a slash (relative to top-level)
 
410
        frompath = os.sep + os.path.join(base, file)
 
411
        # The destination is found by taking just the basename of the file
 
412
        topath = os.path.join(todir, os.path.basename(file))
 
413
        try:
 
414
            movefile(req, frompath, topath, copy)
 
415
        except ActionError, message:
 
416
            # Store the error for later; we want to copy as many as possible
 
417
            if errormsg is None:
 
418
                errormsg = message
 
419
            else:
 
420
                # Multiple errors; generic message
 
421
                errormsg = "One or more files could not be pasted"
 
422
            # Add this file to errorfiles; it will be put back on the
 
423
            # clipboard for possible future pasting.
 
424
            errorfiles.append(file)
 
425
    # If errors occured, augment the clipboard and raise ActionError
 
426
    if len(errorfiles) > 0:
 
427
        clipboard['files'] = errorfiles
 
428
        session['clipboard'] = clipboard
 
429
        session.save()
 
430
        raise ActionError(errormsg)
 
431
 
 
432
    # Success: Clear the clipboard
 
433
    del session['clipboard']
 
434
    session.save()
 
435
 
 
436
def action_svnadd(req, fields):
 
437
    """Performs a "svn add" to each file specified.
 
438
 
 
439
    Reads fields: 'path' (multiple)
 
440
    """
 
441
    paths = fields.getlist('path')
 
442
    paths = map(lambda path: actionpath_to_local(req, path), paths)
 
443
 
 
444
    try:
 
445
        svnclient.add(paths, recurse=True, force=True)
 
446
    except pysvn.ClientError:
 
447
        raise ActionError("One or more files could not be added")
 
448
 
 
449
def action_svnupdate(req, fields):
 
450
    """Performs a "svn update" to each file specified.
 
451
 
 
452
    Reads fields: 'path'
 
453
    """
 
454
    path = fields.getfirst('path')
 
455
    if path is None:
 
456
        raise ActionError("Required field missing")
 
457
    path = actionpath_to_local(req, path)
 
458
 
 
459
    try:
 
460
        svnclient.update(path, recurse=True)
 
461
    except pysvn.ClientError:
 
462
        raise ActionError("One or more files could not be updated")
 
463
 
 
464
def action_svnrevert(req, fields):
 
465
    """Performs a "svn revert" to each file specified.
 
466
 
 
467
    Reads fields: 'path' (multiple)
 
468
    """
 
469
    paths = fields.getlist('path')
 
470
    paths = map(lambda path: actionpath_to_local(req, path), paths)
 
471
 
 
472
    try:
 
473
        svnclient.revert(paths, recurse=True)
 
474
    except pysvn.ClientError:
 
475
        raise ActionError("One or more files could not be reverted")
 
476
 
 
477
def action_svnpublish(req, fields):
 
478
    """Sets svn property "ivle:published" on each file specified.
 
479
    Should only be called on directories (only effective on directories
 
480
    anyway).
 
481
 
 
482
    Reads fields: 'path'
 
483
    """
 
484
    paths = fields.getlist('path')
 
485
    paths = map(lambda path: actionpath_to_local(req, path), paths)
 
486
 
 
487
    try:
 
488
        for path in paths:
 
489
            # Note: Property value doesn't matter
 
490
            svnclient.propset("ivle:published", "", path, recurse=False)
 
491
    except pysvn.ClientError:
 
492
        raise ActionError("One or more files could not be updated")
 
493
 
 
494
def action_svnunpublish(req, fields):
 
495
    """Deletes svn property "ivle:published" on each file specified.
 
496
 
 
497
    Reads fields: 'path'
 
498
    """
 
499
    paths = fields.getlist('path')
 
500
    paths = map(lambda path: actionpath_to_local(req, path), paths)
 
501
 
 
502
    try:
 
503
        for path in paths:
 
504
            svnclient.propdel("ivle:published", path, recurse=False)
 
505
    except pysvn.ClientError:
 
506
        raise ActionError("One or more files could not be updated")
 
507
 
 
508
def action_svncommit(req, fields):
 
509
    """Performs a "svn commit" to each file specified.
 
510
 
 
511
    Reads fields: 'path' (multiple), 'logmsg' (optional)
 
512
    """
 
513
    paths = fields.getlist('path')
 
514
    paths = map(lambda path: actionpath_to_local(req, str(path)), paths)
 
515
    logmsg = str(fields.getfirst('logmsg', DEFAULT_LOGMESSAGE))
 
516
    if logmsg == '': logmsg = DEFAULT_LOGMESSAGE
 
517
 
 
518
    try:
 
519
        svnclient.checkin(paths, logmsg, recurse=True)
 
520
    except pysvn.ClientError:
 
521
        raise ActionError("One or more files could not be committed")
 
522
 
 
523
# Table of all action functions #
 
524
# Each function has the interface f(req, fields).
 
525
 
 
526
actions_table = {
 
527
    "remove" : action_remove,
 
528
    "move" : action_move,
 
529
    "putfile" : action_putfile,
 
530
    "putfiles" : action_putfiles,
 
531
 
 
532
    "copy" : action_copy,
 
533
    "cut" : action_cut,
 
534
    "paste" : action_paste,
 
535
 
 
536
    "svnadd" : action_svnadd,
 
537
    "svnupdate" : action_svnupdate,
 
538
    "svnrevert" : action_svnrevert,
 
539
    "svnpublish" : action_svnpublish,
 
540
    "svnunpublish" : action_svnunpublish,
 
541
    "svncommit" : action_svncommit,
 
542
}