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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# IVLE
# Copyright (C) 2007-2008 The University of Melbourne
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

# Module: File Service / Action
# Author: Matt Giuca
# Date: 10/1/2008

# Handles actions requested by the client as part of the 2-stage process of
# fileservice (the second part being the return listing).

### Actions ###

# The most important argument is "action". This determines which action is
# taken. Note that action, and all other arguments, are ignored unless the
# request is a POST request. The other arguments depend upon the action.
# Note that paths are often specified as arguments. Paths that begin with a
# slash are taken relative to the user's home directory (the top-level
# directory seen when fileservice has no arguments or path). Paths without a
# slash are taken relative to the specified path.

# action=remove: Delete a file(s) or directory(s) (recursively).
#       path:   The path to the file or directory to delete. Can be specified
#               multiple times.
#
# action=move: Move or rename a file or directory.
#       from:   The path to the file or directory to be renamed.
#       to:     The path of the target filename. Error if the file already
#               exists.
#
# action=putfile: Upload a file to the student workspace, and optionally
#               accept zip files which will be unpacked.
#       path:   The path to the file to be written. If it exists, will
#               overwrite. Error if the target file is a directory.
#       data:   Bytes to be written to the file verbatim. May either be
#               a string variable or a file upload.
#       unpack: Optional. If "true", and the data is a valid ZIP file,
#               will create a directory instead and unpack the ZIP file
#               into it.
#
# action=putfiles: Upload multiple files to the student workspace, and
#                 optionally accept zip files which will be unpacked.
#       path:   The path to the DIRECTORY to place files in. Must not be a
#               file.
#       data:   A file upload (may not be a simple string). The filename
#               will be used to determine the target filename within
#               the given path.
#       unpack: Optional. If "true", if any data is a valid ZIP file,
#               will create a directory instead and unpack the ZIP file
#               into it.
#
# action=mkdir: Create a directory. The parent dir must exist.
#       path:   The path to a file which does not exist, but whose parent
#               does. The dir will be made with this name.
#
# The differences between putfile and putfiles are:
# * putfile can only accept a single file.
# * putfile can accept string data, doesn't have to be a file upload.
# * putfile ignores the upload filename, the entire filename is specified on
#       path. putfiles calls files after the name on the user's machine.
#
# Clipboard-based actions. Cut/copy/paste work in the same way as modern
# file browsers, by keeping a server-side clipboard of files that have been
# cut and copied. The clipboard is stored in the session data, so it persists
# across navigation, tabs and browser windows, but not across browser
# sessions.
# 
# action=copy: Write file(s) to the session-based clipboard. Overrides any
#               existing clipboard data. Does not actually copy the file.
#               The files are physically copied when the clipboard is pasted.
#       path:   The path to the file or directory to copy. Can be specified
#               multiple times.
# 
# action=cut: Write file(s) to the session-based clipboard. Overrides any
#               existing clipboard data. Does not actually move the file.
#               The files are physically moved when the clipboard is pasted.
#       path:   The path to the file or directory to cut. Can be specified
#               multiple times.
# 
# action=paste: Copy or move the files stored in the clipboard. Clears the
#               clipboard. The files are copied or moved to a specified dir.
#       path:   The path to the DIRECTORY to paste the files to. Must not
#               be a file.
#
# Subversion actions.
# action=svnadd: Add an existing file(s) to version control.
#       path:   The path to the file to be added. Can be specified multiple
#               times.
#
# action=svnrevert: Revert a file(s) to its state as of the current revision
#               / undo local edits.
#       path:   The path to the file to be reverted. Can be specified multiple
#               times.
#
# action=svnupdate: Bring a file up to date with the head revision.
#       path:   The path to the file to be updated. Only one file may be
#               specified.
#
# action=svnpublish: Set the "published" flag on a file to True.
#       path:   The path to the file to be published. Can be specified
#               multiple times.
#
# action=svnunpublish: Set the "published" flag on a file to False.
#       path:   The path to the file to be unpublished. Can be specified
#               multiple times.
#
# action=svncommit: Commit a file(s) or directory(s) to the repository.
#       path:   The path to the file or directory to be committed. Can be
#               specified multiple times. Directories are committed
#               recursively.
#       logmsg: Text of the log message. Optional. There is a default log
#               message if unspecified.
# action=svncheckout: Checkout a file/directory from the repository.
#       path:   The [repository] path to the file or directory to be
#               checked out.
# 
# TODO: Implement the following actions:
#   putfiles, svnrevert, svnupdate, svncommit
# TODO: Implement ZIP unpacking in putfile and putfiles.
# TODO: svnupdate needs a digest to tell the user the files that were updated.
#   This can be implemented by some message passing between action and
#   listing, and having the digest included in the listing. (Problem if
#   the listing is not a directory, but we could make it an error to do an
#   update if the path is not a directory).

import os
import cStringIO
import shutil

import pysvn

from common import (util, studpath, zip)
import conf

def get_login(_realm, _username, _may_save):
    """Return the subversion credentials for the user."""
    return (True, conf.login, conf.passwd, True)

# Make a Subversion client object
svnclient = pysvn.Client()
svnclient.callback_get_login = get_login

DEFAULT_LOGMESSAGE = "No log message supplied."

# Mime types
# application/json is the "best" content type but is not good for
# debugging because Firefox just tries to download it
mime_dirlisting = "text/html"
#mime_dirlisting = "application/json"

class ActionError(Exception):
    """Represents an error processing an action. This can be
    raised by any of the action functions, and will be caught
    by the top-level handler, put into the HTTP response field,
    and continue.

    Important Security Consideration: The message passed to this
    exception will be relayed to the client.
    """
    pass

def handle_action(req, action, fields):
    """Perform the "action" part of the response.
    This function should only be called if the response is a POST.
    This performs the action's side-effect on the server. If unsuccessful,
    writes the X-IVLE-Action-Error header to the request object. Otherwise,
    does not touch the request object. Does NOT write any bytes in response.

    May throw an ActionError. The caller should put this string into the
    X-IVLE-Action-Error header, and then continue normally.

    action: String, the action requested. Not sanitised.
    fields: FieldStorage object containing all arguments passed.
    """
    global actions_table        # Table of function objects
    try:
        action = actions_table[action]
    except KeyError:
        # Default, just send an error but then continue
        raise ActionError("Unknown action")
    action(req, fields)

def actionpath_to_urlpath(req, path):
    """Determines the URL path (relative to the student home) upon which the
    action is intended to act. See actionpath_to_local.
    """
    if path is None:
        return req.path
    elif len(path) > 0 and path[0] == os.sep:
        # Relative to student home
        return path[1:]
    else:
        # Relative to req.path
        return os.path.join(req.path, path)

def actionpath_to_local(req, path):
    """Determines the local path upon which an action is intended to act.
    Note that fileservice actions accept two paths: the request path,
    and the "path" argument given to the action.
    According to the rules, if the "path" argument begins with a '/' it is
    relative to the user's home; if it does not, it is relative to the
    supplied path.

    This resolves the path, given the request and path argument.

    May raise an ActionError("Invalid path"). The caller is expected to
    let this fall through to the top-level handler, where it will be
    put into the HTTP response field. Never returns None.

    Does not mutate req.
    """
    (_, _, r) = studpath.url_to_jailpaths(actionpath_to_urlpath(req, path))
    if r is None:
        raise ActionError("Invalid path")
    return r

def movefile(req, frompath, topath, copy=False):
    """Performs a file move, resolving filenames, checking for any errors,
    and throwing ActionErrors if necessary. Can also be used to do a copy
    operation instead.

    frompath and topath are straight paths from the client. Will be checked.
    """
    # TODO: Do an SVN mv if the file is versioned.
    # TODO: Disallow tampering with student's home directory
    if frompath is None or topath is None:
        raise ActionError("Required field missing")
    frompath = actionpath_to_local(req, frompath)
    topath = actionpath_to_local(req, topath)
    if not os.path.exists(frompath):
        raise ActionError("The source file does not exist")
    if os.path.exists(topath):
        if frompath == topath:
            raise ActionError("Source and destination are the same")
        raise ActionError("Another file already exists with that name")

    try:
        if copy:
            if os.path.isdir(frompath):
                shutil.copytree(frompath, topath)
            else:
                shutil.copy2(frompath, topath)
        else:
            shutil.move(frompath, topath)
    except OSError:
        raise ActionError("Could not move the file specified")
    except shutil.Error:
        raise ActionError("Could not move the file specified")

### ACTIONS ###

def action_remove(req, fields):
    # TODO: Do an SVN rm if the file is versioned.
    # TODO: Disallow removal of student's home directory
    """Removes a list of files or directories.

    Reads fields: 'path' (multiple)
    """
    paths = fields.getlist('path')
    goterror = False
    for path in paths:
        path = actionpath_to_local(req, path)
        try:
            if os.path.isdir(path):
                shutil.rmtree(path)
            else:
                os.remove(path)
        except OSError:
            goterror = True
        except shutil.Error:
            goterror = True
    if goterror:
        if len(paths) == 1:
            raise ActionError("Could not delete the file specified")
        else:
            raise ActionError(
                "Could not delete one or more of the files specified")

def action_move(req, fields):
    # TODO: Do an SVN mv if the file is versioned.
    # TODO: Disallow tampering with student's home directory
    """Removes a list of files or directories.

    Reads fields: 'from', 'to'
    """
    frompath = fields.getfirst('from')
    topath = fields.getfirst('to')
    movefile(req, frompath, topath)

def action_mkdir(req, fields):
    """Creates a directory with the given path.
    Reads fields: 'path'
    """
    path = fields.getfirst('path')
    if path is None:
        raise ActionError("Required field missing")
    path = actionpath_to_local(req, path)

    # Create the directory
    try:
        os.mkdir(path)
    except OSError:
        raise ActionError("Could not create directory")

def action_putfile(req, fields):
    """Writes data to a file, overwriting it if it exists and creating it if
    it doesn't.

    Reads fields: 'path', 'data' (file upload)
    """
    # TODO: Read field "unpack".
    # Important: Data is "None" if the file submitted is empty.
    path = fields.getfirst('path')
    data = fields.getfirst('data')
    if path is None:
        raise ActionError("Required field missing")
    if data is None:
        # Workaround - field reader treats "" as None, so this is the only
        # way to allow blank file uploads
        data = ""
    path = actionpath_to_local(req, path)

    if data is not None:
        data = cStringIO.StringIO(data)

    # Copy the contents of file object 'data' to the path 'path'
    try:
        dest = open(path, 'wb')
        if data is not None:
            shutil.copyfileobj(data, dest)
    except OSError:
        raise ActionError("Could not write to target file")

def action_putfiles(req, fields):
    """Writes data to one or more files in a directory, overwriting them if
    it they exist.

    Reads fields: 'path', 'data' (file upload, multiple), 'unpack'
    """

    # Important: Data is "None" if the file submitted is empty.
    path = fields.getfirst('path')
    data = fields['data']
    if type(data) != type([]):
        data = [data]
    unpack = fields.getfirst('unpack')
    if unpack is None:
        unpack = False
    else:
        unpack = True
    if path is None:
        raise ActionError("Required field missing")
    path = actionpath_to_urlpath(req, path)
    goterror = False


    for datum in data:
        # Each of the uploaded files
        filepath = os.path.join(path, datum.filename)
        filedata = datum.value

        if unpack and datum.filename.lower().endswith(".zip"):
            # A zip file - unpack it instead of just copying
            # TODO: Use the magic number instead of file extension
            # Note: Just unzip into the current directory (ignore the
            # filename)
            try:
                zip.unzip(path, filedata)
            except (OSError, IOError):
                goterror = True
        else:
            # Not a zip file
            (_, _, filepath_local) = studpath.url_to_jailpaths(filepath)
            if filepath_local is None:
                raise ActionError("Invalid path")

            # Copy the contents of file object 'data' to the path 'path'
            try:
                dest = open(filepath_local, 'wb')
                if data is not None:
                    shutil.copyfileobj(cStringIO.StringIO(filedata), dest)
            except OSError:
                goterror = True

    if goterror:
        if len(data) == 1:
            raise ActionError("Could not write to target file")
        else:
            raise ActionError(
                "Could not write to one or more of the target files")

def action_copy_or_cut(req, fields, mode):
    """Marks specified files on the clipboard, stored in the
    browser session. Sets clipboard for either a cut or copy operation
    as specified.

    Reads fields: 'path'
    """
    # The clipboard object created conforms to the JSON clipboard
    # specification given at the top of listing.py.
    # Note that we do not check for the existence of files here. That is done
    # in the paste operation.
    files = fields.getlist('path')
    clipboard = { "mode" : mode, "base" : req.path, "files" : files }
    session = req.get_session()
    session['clipboard'] = clipboard
    session.save()

def action_copy(req, fields):
    """Marks specified files on the clipboard, stored in the
    browser session. Sets clipboard for a "copy" action.

    Reads fields: 'path'
    """
    action_copy_or_cut(req, fields, "copy")

def action_cut(req, fields):
    """Marks specified files on the clipboard, stored in the
    browser session. Sets clipboard for a "cut" action.

    Reads fields: 'path'
    """
    action_copy_or_cut(req, fields, "cut")

def action_paste(req, fields):
    """Performs the copy or move action with the files stored on
    the clipboard in the browser session. Copies/moves the files
    to the specified directory. Clears the clipboard.

    Reads fields: 'path'
    """
    errormsg = None

    todir = fields.getfirst('path')
    if todir is None:
        raise ActionError("Required field missing")
    todir_local = actionpath_to_local(req, todir)
    if not os.path.isdir(todir_local):
        raise ActionError("Target is not a directory")

    session = req.get_session()
    try:
        clipboard = session['clipboard']
        files = clipboard['files']
        base = clipboard['base']
        if clipboard['mode'] == "copy":
            copy = True
        else:
            copy = False
    except KeyError:
        raise ActionError("Clipboard was empty")

    errorfiles = []
    for file in files:
        # The source must not be interpreted as relative to req.path
        # Add a slash (relative to top-level)
        frompath = os.sep + os.path.join(base, file)
        # The destination is found by taking just the basename of the file
        topath = os.path.join(todir, os.path.basename(file))
        try:
            movefile(req, frompath, topath, copy)
        except ActionError, message:
            # Store the error for later; we want to copy as many as possible
            if errormsg is None:
                errormsg = message
            else:
                # Multiple errors; generic message
                errormsg = "One or more files could not be pasted"
            # Add this file to errorfiles; it will be put back on the
            # clipboard for possible future pasting.
            errorfiles.append(file)
    # If errors occured, augment the clipboard and raise ActionError
    if len(errorfiles) > 0:
        clipboard['files'] = errorfiles
        session['clipboard'] = clipboard
        session.save()
        raise ActionError(errormsg)

    # Success: Clear the clipboard
    del session['clipboard']
    session.save()

def action_svnadd(req, fields):
    """Performs a "svn add" to each file specified.

    Reads fields: 'path' (multiple)
    """
    paths = fields.getlist('path')
    paths = map(lambda path: actionpath_to_local(req, path), paths)

    try:
        svnclient.add(paths, recurse=True, force=True)
    except pysvn.ClientError:
        raise ActionError("One or more files could not be added")

def action_svnupdate(req, fields):
    """Performs a "svn update" to each file specified.

    Reads fields: 'path'
    """
    path = fields.getfirst('path')
    if path is None:
        raise ActionError("Required field missing")
    path = actionpath_to_local(req, path)

    try:
        svnclient.update(path, recurse=True)
    except pysvn.ClientError:
        raise ActionError("One or more files could not be updated")

def action_svnrevert(req, fields):
    """Performs a "svn revert" to each file specified.

    Reads fields: 'path' (multiple)
    """
    paths = fields.getlist('path')
    paths = map(lambda path: actionpath_to_local(req, path), paths)

    try:
        svnclient.revert(paths, recurse=True)
    except pysvn.ClientError:
        raise ActionError("One or more files could not be reverted")

def action_svnpublish(req, fields):
    """Sets svn property "ivle:published" on each file specified.
    Should only be called on directories (only effective on directories
    anyway).

    Reads fields: 'path'
    """
    paths = fields.getlist('path')
    paths = map(lambda path: actionpath_to_local(req, path), paths)

    try:
        for path in paths:
            # Note: Property value doesn't matter
            svnclient.propset("ivle:published", "", path, recurse=False)
    except pysvn.ClientError, e:
        raise ActionError("Directory could not be published")

def action_svnunpublish(req, fields):
    """Deletes svn property "ivle:published" on each file specified.

    Reads fields: 'path'
    """
    paths = fields.getlist('path')
    paths = map(lambda path: actionpath_to_local(req, path), paths)

    try:
        for path in paths:
            svnclient.propdel("ivle:published", path, recurse=False)
    except pysvn.ClientError:
        raise ActionError("Directory could not be unpublished")

def action_svncommit(req, fields):
    """Performs a "svn commit" to each file specified.

    Reads fields: 'path' (multiple), 'logmsg' (optional)
    """
    paths = fields.getlist('path')
    paths = map(lambda path: actionpath_to_local(req, str(path)), paths)
    logmsg = str(fields.getfirst('logmsg', DEFAULT_LOGMESSAGE))
    if logmsg == '': logmsg = DEFAULT_LOGMESSAGE

    try:
        svnclient.checkin(paths, logmsg, recurse=True)
    except pysvn.ClientError:
        raise ActionError("One or more files could not be committed")

def action_svncheckout(req, fields):
    """Performs a "svn checkout" of each path specified.

    Reads fields: 'path'    (multiple)
    """
    paths = fields.getlist('path')
    if len(paths) != 2:
        raise ActionError("usage: svncheckout url local-path")
    url = conf.svn_addr + "/" + login + "/" + paths[0]
    local_path = actionpath_to_local(req, str(paths[1]))
    try:
        svnclient.callback_get_login = get_login
        svnclient.checkout(url, local_path, recurse=True)
    except pysvn.ClientError:
        raise ActionError("One or more files could not be checked out")

# Table of all action functions #
# Each function has the interface f(req, fields).

actions_table = {
    "remove" : action_remove,
    "move" : action_move,
    "mkdir" : action_mkdir,
    "putfile" : action_putfile,
    "putfiles" : action_putfiles,

    "copy" : action_copy,
    "cut" : action_cut,
    "paste" : action_paste,

    "svnadd" : action_svnadd,
    "svnupdate" : action_svnupdate,
    "svnrevert" : action_svnrevert,
    "svnpublish" : action_svnpublish,
    "svnunpublish" : action_svnunpublish,
    "svncommit" : action_svncommit,
    "svncheckout" : action_svncheckout,
}