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

294 by mattgiuca
Added application: tutorialservice. Will be used as the Ajax backend for
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: TutorialService
19
# Author: Matt Giuca
20
# Date:   25/1/2008
21
22
# Provides the AJAX backend for the tutorial application.
300 by mattgiuca
conf/apps: Added TutorialService as a registered app.
23
# This allows several actions to be performed on the code the student has
515 by stevenbird
Propagated "problem" -> "exercise" nomenclature change.
24
# typed into one of the exercise boxes.
300 by mattgiuca
conf/apps: Added TutorialService as a registered app.
25
26
# Calling syntax
301 by mattgiuca
tutorialservice: Now parses and executes the students code using the test
27
# Path must be empty.
300 by mattgiuca
conf/apps: Added TutorialService as a registered app.
28
# The arguments determine what is to be done on this file.
29
1024 by mattgiuca
tutorialservice: Refactored the handler for this service, to allow potential
30
# "action". One of the tutorialservice actions.
515 by stevenbird
Propagated "problem" -> "exercise" nomenclature change.
31
# "exercise" - The path to a exercise file (including the .xml extension),
1024 by mattgiuca
tutorialservice: Refactored the handler for this service, to allow potential
32
#              relative to the subjects base directory.
33
# action "save" or "test" (POST only):
34
#   "code" - Full text of the student's code being submitted.
1025 by mattgiuca
tutorialservice: Added two new GET actions: getattempts and getattempt.
35
# action "getattempts": No arguments. Returns a list of
36
#   {'date': 'formatted_date', 'complete': bool} dicts.
37
# action "getattempt":
38
#   "date" - Formatted date. Gets most recent attempt before (and including)
39
#   that date.
40
#   Returns JSON string containing code, or null.
300 by mattgiuca
conf/apps: Added TutorialService as a registered app.
41
42
# Returns a JSON response string indicating the results.
43
301 by mattgiuca
tutorialservice: Now parses and executes the students code using the test
44
import os
661 by drtomc
tutorialservice: log submitted attempts to the database.
45
import time
301 by mattgiuca
tutorialservice: Now parses and executes the students code using the test
46
300 by mattgiuca
conf/apps: Added TutorialService as a registered app.
47
import cjson
48
1029 by dcoles
Tutorial Service: Ported the tutorial service to the console so that all
49
from common import (db, util, console)
301 by mattgiuca
tutorialservice: Now parses and executes the students code using the test
50
import test
51
import conf
52
1025 by mattgiuca
tutorialservice: Added two new GET actions: getattempts and getattempt.
53
# If True, getattempts or getattempt will allow browsing of inactive/disabled
54
# attempts. If False, will not allow this.
55
HISTORY_ALLOW_INACTIVE = False
56
300 by mattgiuca
conf/apps: Added TutorialService as a registered app.
57
def handle(req):
58
    """Handler for Ajax backend TutorialService app."""
59
    # Set request attributes
60
    req.write_html_head_foot = False     # No HTML
61
301 by mattgiuca
tutorialservice: Now parses and executes the students code using the test
62
    if req.path != "":
63
        req.throw_error(req.HTTP_BAD_REQUEST)
300 by mattgiuca
conf/apps: Added TutorialService as a registered app.
64
    fields = req.get_fieldstorage()
65
    act = fields.getfirst('action')
515 by stevenbird
Propagated "problem" -> "exercise" nomenclature change.
66
    exercise = fields.getfirst('exercise')
1024 by mattgiuca
tutorialservice: Refactored the handler for this service, to allow potential
67
    if act is None or exercise is None:
300 by mattgiuca
conf/apps: Added TutorialService as a registered app.
68
        req.throw_error(req.HTTP_BAD_REQUEST)
69
    act = act.value
515 by stevenbird
Propagated "problem" -> "exercise" nomenclature change.
70
    exercise = exercise.value
1024 by mattgiuca
tutorialservice: Refactored the handler for this service, to allow potential
71
72
    if act == 'save' or act == 'test':
73
        # Must be POST
74
        if req.method != 'POST':
75
            req.throw_error(req.HTTP_BAD_REQUEST)
1025 by mattgiuca
tutorialservice: Added two new GET actions: getattempts and getattempt.
76
1024 by mattgiuca
tutorialservice: Refactored the handler for this service, to allow potential
77
        code = fields.getfirst('code')
78
        if code is None:
79
            req.throw_error(req.HTTP_BAD_REQUEST)
80
        code = code.value
81
82
        if act == 'save':
83
            handle_save(req, exercise, code, fields)
84
        else:   # act == "test"
85
            handle_test(req, exercise, code, fields)
1025 by mattgiuca
tutorialservice: Added two new GET actions: getattempts and getattempt.
86
    elif act == 'getattempts':
87
        handle_getattempts(req, exercise)
88
    elif act == 'getattempt':
89
        date = fields.getfirst('date')
90
        if date is None:
91
            req.throw_error(req.HTTP_BAD_REQUEST)
92
        date = date.value
93
        # Convert into a struct_time
94
        # The time *should* be in the same format as the DB (since it should
95
        # be bounced back to us from the getattempts output). Assume this.
96
        try:
97
            date = time.strptime(date, db.TIMESTAMP_FORMAT)
98
        except ValueError:
99
            # Date was not in correct format
100
            req.throw_error(req.HTTP_BAD_REQUEST)
101
        handle_getattempt(req, exercise, date)
300 by mattgiuca
conf/apps: Added TutorialService as a registered app.
102
    else:
103
        req.throw_error(req.HTTP_BAD_REQUEST)
104
698 by mattgiuca
Added Save feature to tutorial system.
105
def handle_save(req, exercise, code, fields):
106
    """Handles a save action. This saves the user's code without executing it.
107
    """
108
    # Need to open JUST so we know this is a real exercise.
109
    # (This avoids users submitting code for bogus exercises).
701 by mattgiuca
Moved "open_exercise_file" from tutorialservice to util.
110
    exercisefile = util.open_exercise_file(exercise)
698 by mattgiuca
Added Save feature to tutorial system.
111
    if exercisefile is None:
112
        req.throw_error(req.HTTP_NOT_FOUND,
113
            "The exercise was not found.")
114
    exercisefile.close()
115
116
    req.write('{"result": "ok"}')
117
118
    conn = db.DB()
119
707 by mattgiuca
tutorialservice: "submit" requests now return "completed" and "attempts"
120
    try:
121
        conn.write_problem_save(
122
            login = req.user.login,
123
            exercisename = exercise,
124
            date = time.localtime(),
125
            text = code)
126
    finally:
127
        conn.close()
698 by mattgiuca
Added Save feature to tutorial system.
128
129
def handle_test(req, exercise, code, fields):
130
    """Handles a test action."""
131
701 by mattgiuca
Moved "open_exercise_file" from tutorialservice to util.
132
    exercisefile = util.open_exercise_file(exercise)
698 by mattgiuca
Added Save feature to tutorial system.
133
    if exercisefile is None:
134
        req.throw_error(req.HTTP_NOT_FOUND,
135
            "The exercise was not found.")
301 by mattgiuca
tutorialservice: Now parses and executes the students code using the test
136
1029 by dcoles
Tutorial Service: Ported the tutorial service to the console so that all
137
    # Start a console to run the tests on
138
    jail_path = os.path.join(conf.jail_base, req.user.login)
139
    working_dir = os.path.join("/home", req.user.login)
140
    cons = console.Console(req.user.unixid, jail_path, working_dir)
141
515 by stevenbird
Propagated "problem" -> "exercise" nomenclature change.
142
    # Parse the file into a exercise object using the test suite
1029 by dcoles
Tutorial Service: Ported the tutorial service to the console so that all
143
    exercise_obj = test.parse_exercise_file(exercisefile, cons)
515 by stevenbird
Propagated "problem" -> "exercise" nomenclature change.
144
    exercisefile.close()
1029 by dcoles
Tutorial Service: Ported the tutorial service to the console so that all
145
301 by mattgiuca
tutorialservice: Now parses and executes the students code using the test
146
    # Run the test cases. Get the result back as a JSONable object.
147
    # Return it.
515 by stevenbird
Propagated "problem" -> "exercise" nomenclature change.
148
    test_results = exercise_obj.run_tests(code)
325 by mattgiuca
tutorial: Added "run" button which submits the students code to the
149
1029 by dcoles
Tutorial Service: Ported the tutorial service to the console so that all
150
    # Close the console
151
    cons.close()
152
661 by drtomc
tutorialservice: log submitted attempts to the database.
153
    conn = db.DB()
707 by mattgiuca
tutorialservice: "submit" requests now return "completed" and "attempts"
154
    try:
155
        conn.insert_problem_attempt(
156
            login = req.user.login,
157
            exercisename = exercise,
158
            date = time.localtime(),
159
            complete = test_results['passed'],
160
            attempt = code)
161
162
        # Query the DB to get an updated score on whether or not this problem
163
        # has EVER been completed (may be different from "passed", if it has
164
        # been completed before), and the total number of attempts.
165
        completed, attempts = conn.get_problem_status(req.user.login,
166
            exercise)
167
        test_results["completed"] = completed
168
        test_results["attempts"] = attempts
169
170
        req.write(cjson.encode(test_results))
171
    finally:
172
        conn.close()
1025 by mattgiuca
tutorialservice: Added two new GET actions: getattempts and getattempt.
173
174
def handle_getattempts(req, exercise):
175
    """Handles a getattempts action."""
176
    conn = db.DB()
177
    try:
178
        attempts = conn.get_problem_attempts(
179
            login=req.user.login,
180
            exercisename=exercise,
181
            allow_inactive=HISTORY_ALLOW_INACTIVE)
182
        req.write(cjson.encode(attempts))
183
    finally:
184
        conn.close()
185
186
def handle_getattempt(req, exercise, date):
187
    """Handles a getattempts action. Date is a struct_time."""
188
    conn = db.DB()
189
    try:
190
        attempt = conn.get_problem_attempt(
191
            login=req.user.login,
192
            exercisename=exercise,
193
            as_of=date,
194
            allow_inactive=HISTORY_ALLOW_INACTIVE)
195
        # attempt may be None; will write "null"
1060 by wagrant
Make IVLE work fine in Firefox 3.1 (ie. Gecko/XULRunner 1.9.1). Gecko 1.9.1 has
196
        req.write(cjson.encode({'code': attempt}))
1025 by mattgiuca
tutorialservice: Added two new GET actions: getattempts and getattempt.
197
    finally:
198
        conn.close()