2
# Copyright (C) 2007-2008 The University of Melbourne
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.
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.
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
18
# Module: File Service / Action
22
# Handles actions requested by the client as part of the 2-stage process of
23
# fileservice (the second part being the return listing).
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.
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
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
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
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
58
# data: A file upload (may not be a simple string). The filename
59
# will be used to determine the target filename within
61
# unpack: Optional. If "true", if any data is a valid ZIP file,
62
# will create a directory instead and unpack the ZIP file
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.
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
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
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
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
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
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
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
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
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
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
120
# logmsg: Text of the log message. Optional. There is a default log
121
# message if unspecified.
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).
137
from common import (util, studpath, zip)
139
# Make a Subversion client object
140
svnclient = pysvn.Client()
142
DEFAULT_LOGMESSAGE = "No log message supplied."
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"
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,
156
Important Security Consideration: The message passed to this
157
exception will be relayed to the client.
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.
168
May throw an ActionError. The caller should put this string into the
169
X-IVLE-Action-Error header, and then continue normally.
171
action: String, the action requested. Not sanitised.
172
fields: FieldStorage object containing all arguments passed.
174
global actions_table # Table of function objects
176
action = actions_table[action]
178
# Default, just send an error but then continue
179
raise ActionError("Unknown action")
182
def actionpath_to_urlpath(req, path):
183
"""Determines the URL path (relative to the student home) upon which the
184
action is intended to act. See actionpath_to_local.
188
elif len(path) > 0 and path[0] == os.sep:
189
# Relative to student home
192
# Relative to req.path
193
return os.path.join(req.path, path)
195
def actionpath_to_local(req, path):
196
"""Determines the local path upon which an action is intended to act.
197
Note that fileservice actions accept two paths: the request path,
198
and the "path" argument given to the action.
199
According to the rules, if the "path" argument begins with a '/' it is
200
relative to the user's home; if it does not, it is relative to the
203
This resolves the path, given the request and path argument.
205
May raise an ActionError("Invalid path"). The caller is expected to
206
let this fall through to the top-level handler, where it will be
207
put into the HTTP response field. Never returns None.
211
_, r = studpath.url_to_local(actionpath_to_urlpath(req, path))
213
raise ActionError("Invalid path")
216
def movefile(req, frompath, topath, copy=False):
217
"""Performs a file move, resolving filenames, checking for any errors,
218
and throwing ActionErrors if necessary. Can also be used to do a copy
221
frompath and topath are straight paths from the client. Will be checked.
223
# TODO: Do an SVN mv if the file is versioned.
224
# TODO: Disallow tampering with student's home directory
225
if frompath is None or topath is None:
226
raise ActionError("Required field missing")
227
frompath = actionpath_to_local(req, frompath)
228
topath = actionpath_to_local(req, topath)
229
if not os.path.exists(frompath):
230
raise ActionError("The source file does not exist")
231
if os.path.exists(topath):
232
if frompath == topath:
233
raise ActionError("Source and destination are the same")
234
raise ActionError("Another file already exists with that name")
238
if os.path.isdir(frompath):
239
shutil.copytree(frompath, topath)
241
shutil.copy2(frompath, topath)
243
shutil.move(frompath, topath)
245
raise ActionError("Could not move the file specified")
247
raise ActionError("Could not move the file specified")
251
def action_remove(req, fields):
252
# TODO: Do an SVN rm if the file is versioned.
253
# TODO: Disallow removal of student's home directory
254
"""Removes a list of files or directories.
256
Reads fields: 'path' (multiple)
258
paths = fields.getlist('path')
261
path = actionpath_to_local(req, path)
263
if os.path.isdir(path):
273
raise ActionError("Could not delete the file specified")
276
"Could not delete one or more of the files specified")
278
def action_move(req, fields):
279
# TODO: Do an SVN mv if the file is versioned.
280
# TODO: Disallow tampering with student's home directory
281
"""Removes a list of files or directories.
283
Reads fields: 'from', 'to'
285
frompath = fields.getfirst('from')
286
topath = fields.getfirst('to')
287
movefile(req, frompath, topath)
289
def action_putfile(req, fields):
290
"""Writes data to a file, overwriting it if it exists and creating it if
293
Reads fields: 'path', 'data' (file upload)
295
# TODO: Read field "unpack".
296
# Important: Data is "None" if the file submitted is empty.
297
path = fields.getfirst('path')
298
data = fields.getfirst('data')
300
raise ActionError("Required field missing")
301
path = actionpath_to_local(req, path)
305
# Copy the contents of file object 'data' to the path 'path'
307
dest = open(path, 'wb')
309
shutil.copyfileobj(data, dest)
311
raise ActionError("Could not write to target file")
313
def action_putfiles(req, fields):
314
"""Writes data to one or more files in a directory, overwriting them if
317
Reads fields: 'path', 'data' (file upload, multiple), 'unpack'
319
# Important: Data is "None" if the file submitted is empty.
320
path = fields.getfirst('path')
321
data = fields.getlist('data')
322
unpack = fields.getfirst('unpack')
328
raise ActionError("Required field missing")
329
path = actionpath_to_urlpath(req, path)
333
# Each of the uploaded files
334
filepath = os.path.join(path, datum.filename)
335
filedata = datum.file
337
if unpack and datum.filename.lower().endswith(".zip"):
338
# A zip file - unpack it instead of just copying
339
# TODO: Use the magic number instead of file extension
340
# Note: Just unzip into the current directory (ignore the
343
zip.unzip(path, filedata)
344
except (OSError, IOError):
348
_, filepath_local = studpath.url_to_local(filepath)
349
if filepath_local is None:
350
raise ActionError("Invalid path")
352
# Copy the contents of file object 'data' to the path 'path'
354
dest = open(filepath_local, 'wb')
356
shutil.copyfileobj(filedata, dest)
362
raise ActionError("Could not write to target file")
365
"Could not write to one or more of the target files")
367
def action_copy_or_cut(req, fields, mode):
368
"""Marks specified files on the clipboard, stored in the
369
browser session. Sets clipboard for either a cut or copy operation
374
# The clipboard object created conforms to the JSON clipboard
375
# specification given at the top of listing.py.
376
# Note that we do not check for the existence of files here. That is done
377
# in the paste operation.
378
files = fields.getlist('path')
379
files = map(lambda field: field.value, files)
380
clipboard = { "mode" : mode, "base" : req.path, "files" : files }
381
session = req.get_session()
382
session['clipboard'] = clipboard
385
def action_copy(req, fields):
386
"""Marks specified files on the clipboard, stored in the
387
browser session. Sets clipboard for a "copy" action.
391
action_copy_or_cut(req, fields, "copy")
393
def action_cut(req, fields):
394
"""Marks specified files on the clipboard, stored in the
395
browser session. Sets clipboard for a "cut" action.
399
action_copy_or_cut(req, fields, "cut")
401
def action_paste(req, fields):
402
"""Performs the copy or move action with the files stored on
403
the clipboard in the browser session. Copies/moves the files
404
to the specified directory. Clears the clipboard.
410
todir = fields.getfirst('path')
412
raise ActionError("Required field missing")
413
todir_local = actionpath_to_local(req, todir)
414
if not os.path.isdir(todir_local):
415
raise ActionError("Target is not a directory")
417
session = req.get_session()
419
clipboard = session['clipboard']
420
files = clipboard['files']
421
base = clipboard['base']
422
if clipboard['mode'] == "copy":
427
raise ActionError("Clipboard was empty")
431
# The source must not be interpreted as relative to req.path
432
# Add a slash (relative to top-level)
433
frompath = os.sep + os.path.join(base, file)
434
# The destination is found by taking just the basename of the file
435
topath = os.path.join(todir, os.path.basename(file))
437
movefile(req, frompath, topath, copy)
438
except ActionError, message:
439
# Store the error for later; we want to copy as many as possible
443
# Multiple errors; generic message
444
errormsg = "One or more files could not be pasted"
445
# Add this file to errorfiles; it will be put back on the
446
# clipboard for possible future pasting.
447
errorfiles.append(file)
448
# If errors occured, augment the clipboard and raise ActionError
449
if len(errorfiles) > 0:
450
clipboard['files'] = errorfiles
451
session['clipboard'] = clipboard
453
raise ActionError(errormsg)
455
# Success: Clear the clipboard
456
del session['clipboard']
459
def action_svnadd(req, fields):
460
"""Performs a "svn add" to each file specified.
462
Reads fields: 'path' (multiple)
464
paths = fields.getlist('path')
465
paths = map(lambda path: actionpath_to_local(req, path), paths)
468
svnclient.add(paths, recurse=True, force=True)
469
except pysvn.ClientError:
470
raise ActionError("One or more files could not be added")
472
def action_svnupdate(req, fields):
473
"""Performs a "svn update" to each file specified.
477
path = fields.getfirst('path')
479
raise ActionError("Required field missing")
480
path = actionpath_to_local(req, path)
483
svnclient.update(path, recurse=True)
484
except pysvn.ClientError:
485
raise ActionError("One or more files could not be updated")
487
def action_svnrevert(req, fields):
488
"""Performs a "svn revert" to each file specified.
490
Reads fields: 'path' (multiple)
492
paths = fields.getlist('path')
493
paths = map(lambda path: actionpath_to_local(req, path), paths)
496
svnclient.revert(paths, recurse=True)
497
except pysvn.ClientError:
498
raise ActionError("One or more files could not be reverted")
500
def action_svnpublish(req, fields):
501
"""Sets svn property "ivle:published" on each file specified.
502
Should only be called on directories (only effective on directories
507
paths = fields.getlist('path')
508
paths = map(lambda path: actionpath_to_local(req, path), paths)
512
# Note: Property value doesn't matter
513
svnclient.propset("ivle:published", "", path, recurse=False)
514
except pysvn.ClientError:
515
raise ActionError("One or more files could not be updated")
517
def action_svnunpublish(req, fields):
518
"""Deletes svn property "ivle:published" on each file specified.
522
paths = fields.getlist('path')
523
paths = map(lambda path: actionpath_to_local(req, path), paths)
527
svnclient.propdel("ivle:published", path, recurse=False)
528
except pysvn.ClientError:
529
raise ActionError("One or more files could not be updated")
531
def action_svncommit(req, fields):
532
"""Performs a "svn commit" to each file specified.
534
Reads fields: 'path' (multiple), 'logmsg' (optional)
536
paths = fields.getlist('path')
537
paths = map(lambda path: actionpath_to_local(req, str(path)), paths)
538
logmsg = str(fields.getfirst('logmsg', DEFAULT_LOGMESSAGE))
539
if logmsg == '': logmsg = DEFAULT_LOGMESSAGE
542
svnclient.checkin(paths, logmsg, recurse=True)
543
except pysvn.ClientError:
544
raise ActionError("One or more files could not be committed")
546
# Table of all action functions #
547
# Each function has the interface f(req, fields).
550
"remove" : action_remove,
551
"move" : action_move,
552
"putfile" : action_putfile,
553
"putfiles" : action_putfiles,
555
"copy" : action_copy,
557
"paste" : action_paste,
559
"svnadd" : action_svnadd,
560
"svnupdate" : action_svnupdate,
561
"svnrevert" : action_svnrevert,
562
"svnpublish" : action_svnpublish,
563
"svnunpublish" : action_svnunpublish,
564
"svncommit" : action_svncommit,