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

« back to all changes in this revision

Viewing changes to ivle/webapp/tutorial/service.py

fixed a slight bug on line 155, which referenced a non-existant variable

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# IVLE - Informatics Virtual Learning Environment
2
 
# Copyright (C) 2007-2008 The University of Melbourne
 
2
# Copyright (C) 2007-2009 The University of Melbourne
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
5
5
# it under the terms of the GNU General Public License as published by
15
15
# along with this program; if not, write to the Free Software
16
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
17
 
18
 
# Module: TutorialService
19
 
# Author: Matt Giuca
20
 
# Date:   25/1/2008
21
 
 
22
 
# Provides the AJAX backend for the tutorial application.
23
 
# This allows several actions to be performed on the code the student has
24
 
# typed into one of the exercise boxes.
25
 
 
26
 
# Calling syntax
27
 
# Path must be empty.
28
 
# The arguments determine what is to be done on this file.
29
 
 
30
 
# "action". One of the tutorialservice actions.
31
 
# "exercise" - The path to a exercise file (including the .xml extension),
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.
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.
41
 
 
42
 
# Returns a JSON response string indicating the results.
 
18
# Author: Matt Giuca, Nick Chadwick
 
19
 
 
20
'''AJAX backend for the tutorial application.'''
43
21
 
44
22
import os
45
 
import time
46
23
import datetime
47
 
 
48
 
import cjson
49
 
 
50
 
from ivle import util
51
 
from ivle import console
 
24
import genshi
 
25
 
 
26
import ivle.util
 
27
import ivle.console
52
28
import ivle.database
 
29
from ivle.database import Exercise, ExerciseAttempt, ExerciseSave, Worksheet, \
 
30
                          Offering, Subject, Semester, WorksheetExercise
53
31
import ivle.worksheet
54
32
import ivle.conf
55
 
import test # XXX: Really .test, not real test.
 
33
import ivle.webapp.tutorial.test
 
34
 
 
35
from ivle.webapp.base.rest import (JSONRESTView, named_operation,
 
36
                                   require_permission)
 
37
from ivle.webapp.errors import NotFound
56
38
 
57
39
# If True, getattempts or getattempt will allow browsing of inactive/disabled
58
40
# attempts. If False, will not allow this.
60
42
 
61
43
TIMESTAMP_FORMAT = '%Y-%m-%d %H:%M:%S'
62
44
 
63
 
 
64
 
def handle(req):
65
 
    """Handler for Ajax backend TutorialService app."""
66
 
    # Set request attributes
67
 
    req.write_html_head_foot = False     # No HTML
68
 
 
69
 
    if req.path != "":
70
 
        req.throw_error(req.HTTP_BAD_REQUEST)
71
 
    fields = req.get_fieldstorage()
72
 
    act = fields.getfirst('action')
73
 
    exercise = fields.getfirst('exercise')
74
 
    if act is None or exercise is None:
75
 
        req.throw_error(req.HTTP_BAD_REQUEST)
76
 
    act = act.value
77
 
    exercise = exercise.value
78
 
 
79
 
    if act == 'save' or act == 'test':
80
 
        # Must be POST
81
 
        if req.method != 'POST':
82
 
            req.throw_error(req.HTTP_BAD_REQUEST)
83
 
 
84
 
        code = fields.getfirst('code')
85
 
        if code is None:
86
 
            req.throw_error(req.HTTP_BAD_REQUEST)
87
 
        code = code.value
88
 
 
89
 
        if act == 'save':
90
 
            handle_save(req, exercise, code, fields)
91
 
        else:   # act == "test"
92
 
            handle_test(req, exercise, code, fields)
93
 
    elif act == 'getattempts':
94
 
        handle_getattempts(req, exercise)
95
 
    elif act == 'getattempt':
96
 
        date = fields.getfirst('date')
97
 
        if date is None:
98
 
            req.throw_error(req.HTTP_BAD_REQUEST)
99
 
        date = date.value
100
 
        # Convert into a struct_time
101
 
        # The time *should* be in the same format as the DB (since it should
102
 
        # be bounced back to us from the getattempts output). Assume this.
103
 
        try:
104
 
            date = datetime.datetime.strptime(date, TIMESTAMP_FORMAT)
105
 
        except ValueError:
106
 
            # Date was not in correct format
107
 
            req.throw_error(req.HTTP_BAD_REQUEST)
108
 
        handle_getattempt(req, exercise, date)
109
 
    else:
110
 
        req.throw_error(req.HTTP_BAD_REQUEST)
111
 
 
112
 
def handle_save(req, exercisename, code, fields):
113
 
    """Handles a save action. This saves the user's code without executing it.
114
 
    """
115
 
    # Need to open JUST so we know this is a real exercise.
116
 
    # (This avoids users submitting code for bogus exercises).
117
 
    exercisefile = util.open_exercise_file(exercisename)
118
 
    if exercisefile is None:
119
 
        req.throw_error(req.HTTP_NOT_FOUND,
120
 
            "The exercise was not found.")
121
 
    exercisefile.close()
122
 
 
123
 
    exercise = ivle.database.Exercise.get_by_name(req.store, exercisename)
124
 
    ivle.worksheet.save_exercise(req.store, req.user, exercise,
125
 
                                 unicode(code), datetime.datetime.now())
126
 
    req.store.commit()
127
 
 
128
 
    req.write('{"result": "ok"}')
129
 
 
130
 
 
131
 
def handle_test(req, exercisesrc, code, fields):
132
 
    """Handles a test action."""
133
 
 
134
 
    exercisefile = util.open_exercise_file(exercisesrc)
135
 
    if exercisefile is None:
136
 
        req.throw_error(req.HTTP_NOT_FOUND,
137
 
            "The exercise was not found.")
138
 
 
139
 
    # Start a console to run the tests on
140
 
    jail_path = os.path.join(ivle.conf.jail_base, req.user.login)
141
 
    working_dir = os.path.join("/home", req.user.login)
142
 
    cons = console.Console(req.user.unixid, jail_path, working_dir)
143
 
 
144
 
    # Parse the file into a exercise object using the test suite
145
 
    exercise_obj = test.parse_exercise_file(exercisefile, cons)
146
 
    exercisefile.close()
147
 
 
148
 
    # Run the test cases. Get the result back as a JSONable object.
149
 
    # Return it.
150
 
    test_results = exercise_obj.run_tests(code)
151
 
 
152
 
    # Close the console
153
 
    cons.close()
154
 
 
155
 
    # Get the Exercise from the database
156
 
    exercise = ivle.database.Exercise.get_by_name(req.store, exercisesrc)
157
 
 
158
 
    attempt = ivle.database.ExerciseAttempt(user=req.user,
159
 
                                            exercise=exercise,
160
 
                                            date=datetime.datetime.now(),
161
 
                                            complete=test_results['passed'],
162
 
                                            text=unicode(code)) # XXX
163
 
 
164
 
    req.store.add(attempt)
165
 
    req.store.commit()
166
 
    # Query the DB to get an updated score on whether or not this problem
167
 
    # has EVER been completed (may be different from "passed", if it has
168
 
    # been completed before), and the total number of attempts.
169
 
    completed, attempts = ivle.worksheet.get_exercise_status(req.store,
170
 
        req.user, exercise)
171
 
    test_results["completed"] = completed
172
 
    test_results["attempts"] = attempts
173
 
 
174
 
    req.write(cjson.encode(test_results))
175
 
 
176
 
def handle_getattempts(req, exercisename):
177
 
    """Handles a getattempts action."""
178
 
    exercise = ivle.database.Exercise.get_by_name(req.store, exercisename)
179
 
    attempts = ivle.worksheet.get_exercise_attempts(req.store, req.user,
180
 
        exercise, allow_inactive=HISTORY_ALLOW_INACTIVE)
181
 
    # attempts is a list of ExerciseAttempt objects. Convert to dictionaries.
182
 
    time_fmt = lambda dt: datetime.datetime.strftime(dt, TIMESTAMP_FORMAT)
183
 
    attempts = [{'date': time_fmt(a.date), 'complete': a.complete}
 
45
class AttemptsRESTView(JSONRESTView):
 
46
    '''REST view of a user's attempts at an exercise.'''
 
47
    def __init__(self, req, subject, year, semester, worksheet, 
 
48
                                                exercise, username):
 
49
        self.user = ivle.database.User.get_by_login(req.store, username)
 
50
        if self.user is None:
 
51
            raise NotFound()
 
52
        
 
53
        self.worksheet_exercise = req.store.find(WorksheetExercise,
 
54
            WorksheetExercise.exercise_id == exercise,
 
55
            WorksheetExercise.worksheet_id == Worksheet.id,
 
56
            Worksheet.offering_id == Offering.id,
 
57
            Offering.subject_id == Subject.id,
 
58
            Subject.code == subject,
 
59
            Offering.semester_id == Semester.id,
 
60
            Semester.year == year,
 
61
            Semester.semester == semester).one()
 
62
        
 
63
        self.context = self.user # XXX: Not quite right.
 
64
 
 
65
    @require_permission('edit')
 
66
    def GET(self, req):
 
67
        """Handles a GET Attempts action."""
 
68
        attempts = req.store.find(ExerciseAttempt, 
 
69
                ExerciseAttempt.ws_ex_id == self.worksheet_exercise.id,
 
70
                ExerciseAttempt.user_id == self.user.id)
 
71
        # attempts is a list of ExerciseAttempt objects. Convert to dictionaries
 
72
        time_fmt = lambda dt: datetime.datetime.strftime(dt, TIMESTAMP_FORMAT)
 
73
        attempts = [{'date': time_fmt(a.date), 'complete': a.complete}
184
74
                for a in attempts]
185
 
    req.write(cjson.encode(attempts))
186
 
 
187
 
def handle_getattempt(req, exercisename, date):
188
 
    """Handles a getattempts action. Date is a datetime.datetime."""
189
 
    exercise = ivle.database.Exercise.get_by_name(req.store, exercisename)
190
 
    attempt = ivle.worksheet.get_exercise_attempt(req.store, req.user,
191
 
        exercise, as_of=date, allow_inactive=HISTORY_ALLOW_INACTIVE)
192
 
    if attempt is not None:
193
 
        attempt = attempt.text
194
 
    # attempt may be None; will write "null"
195
 
    req.write(cjson.encode({'code': attempt}))
 
75
 
 
76
        return attempts
 
77
 
 
78
 
 
79
    @require_permission('edit')
 
80
    def PUT(self, req, data):
 
81
        """ Tests the given submission """
 
82
        exercise = req.store.find(Exercise, 
 
83
            Exercise.id == self.worksheet_exercise.exercise_id).one()
 
84
        if exercise is None:
 
85
            raise NotFound()
 
86
 
 
87
        # Start a console to run the tests on
 
88
        jail_path = os.path.join(ivle.conf.jail_base, req.user.login)
 
89
        working_dir = os.path.join("/home", req.user.login)
 
90
        cons = ivle.console.Console(req.user.unixid, jail_path, working_dir)
 
91
 
 
92
        # Parse the file into a exercise object using the test suite
 
93
        exercise_obj = ivle.webapp.tutorial.test.parse_exercise_file(
 
94
                                                            exercise, cons)
 
95
 
 
96
        # Run the test cases. Get the result back as a JSONable object.
 
97
        # Return it.
 
98
        test_results = exercise_obj.run_tests(data['code'])
 
99
 
 
100
        # Close the console
 
101
        cons.close()
 
102
 
 
103
        attempt = ivle.database.ExerciseAttempt(user=req.user,
 
104
            worksheet_exercise = self.worksheet_exercise,
 
105
            date = datetime.datetime.now(),
 
106
            complete = test_results['passed'],
 
107
            text = unicode(data['code'])
 
108
        )
 
109
 
 
110
        req.store.add(attempt)
 
111
 
 
112
        # Query the DB to get an updated score on whether or not this problem
 
113
        # has EVER been completed (may be different from "passed", if it has
 
114
        # been completed before), and the total number of attempts.
 
115
        completed, attempts = ivle.worksheet.get_exercise_status(req.store,
 
116
            req.user, self.worksheet_exercise)
 
117
        test_results["completed"] = completed
 
118
        test_results["attempts"] = attempts
 
119
 
 
120
        return test_results
 
121
 
 
122
 
 
123
class AttemptRESTView(JSONRESTView):
 
124
    '''REST view of an exercise attempt.'''
 
125
 
 
126
    def __init__(self, req, subject, year, semester, worksheet, exercise, 
 
127
                 username, date):
 
128
        # TODO: Find exercise within worksheet.
 
129
        user = ivle.database.User.get_by_login(req.store, username)
 
130
        if user is None:
 
131
            raise NotFound()
 
132
 
 
133
        #try:
 
134
        #    date = datetime.datetime.strptime(date, TIMESTAMP_FORMAT)
 
135
        #except ValueError:
 
136
        #    raise NotFound()
 
137
 
 
138
        worksheet_exercise = req.store.find(WorksheetExercise,
 
139
            WorksheetExercise.exercise_id == exercise,
 
140
            WorksheetExercise.worksheet_id == Worksheet.id,
 
141
            Worksheet.identifier == worksheet,
 
142
            Worksheet.offering_id == Offering.id,
 
143
            Offering.subject_id == Subject.id,
 
144
            Subject.code == subject,
 
145
            Offering.semester_id == Semester.id,
 
146
            Semester.year == year,
 
147
            Semester.semester == semester).one()
 
148
            
 
149
        attempt = req.store.find(ExerciseAttempt,
 
150
            ExerciseAttempt.user_id == user.id,
 
151
            ExerciseAttempt.ws_ex_id == worksheet_exercise.id,
 
152
            ExerciseAttempt.date == date
 
153
        ).one()
 
154
 
 
155
        if attempt is None:
 
156
            raise NotFound()
 
157
 
 
158
        self.context = attempt
 
159
 
 
160
    @require_permission('view')
 
161
    def GET(self, req):
 
162
        return {'code': self.context.text}
 
163
 
 
164
 
 
165
class ExerciseRESTView(JSONRESTView):
 
166
    '''REST view of an exercise.'''
 
167
 
 
168
    def get_permissions(self, user):
 
169
        # XXX: Do it properly.
 
170
        # XXX: Does any user have the ability to save as themselves?
 
171
        # XXX: Does a user EVER have permission to save as another user?
 
172
        if user is not None:
 
173
            return set(['save'])
 
174
        else:
 
175
            return set()
 
176
 
 
177
    @named_operation('save')
 
178
    def save(self, req, text):
 
179
        # Find the appropriate WorksheetExercise to save to. If its not found,
 
180
        # the user is submitting against a non-existant worksheet/exercise
 
181
        worksheet_exercise = req.store.find(WorksheetExercise,
 
182
            WorksheetExercise.exercise_id == self.exercise,
 
183
            WorksheetExercise.worksheet_id == Worksheet.id,
 
184
            Worksheet.offering_id == Offering.id,
 
185
            Offering.subject_id == Subject.id,
 
186
            Subject.code == self.subject,
 
187
            Offering.semester_id == Semester.id,
 
188
            Semester.year == self.year,
 
189
            Semester.semester == self.semester).one()
 
190
        
 
191
        if worksheet_exercise is None:
 
192
            raise NotFound()
 
193
 
 
194
        old_save = req.store.find(ExerciseSave,
 
195
            ExerciseSave.ws_ex_id == worksheet_exercise.id,
 
196
            ExerciseSave.user == req.user).one()
 
197
        
 
198
        #Overwrite the old, or create a new if there isn't one
 
199
        if old_save is None:
 
200
            new_save = ExerciseSave()
 
201
            req.store.add(new_save)
 
202
        else:
 
203
            new_save = old_save
 
204
        
 
205
        new_save.worksheet_exercise = worksheet_exercise
 
206
        new_save.user = req.user
 
207
        new_save.text = unicode(text)
 
208
        new_save.date = datetime.datetime.now()
 
209
 
 
210
        return {"result": "ok"}
 
211
 
 
212
 
 
213
def generate_exerciselist(worksheet, req, worksheetdata):
 
214
    """Runs through the worksheetstream, generating the appropriate
 
215
    WorksheetExercises, and de-activating the old ones."""
 
216
    exercises = []
 
217
    # Turns the worksheet into an xml stream, and then finds all the 
 
218
    # exercise nodes in the stream.
 
219
    worksheetdata = genshi.XML(worksheetdata)
 
220
    for kind, data, pos in worksheetdata:
 
221
        if kind is genshi.core.START:
 
222
            # Data is a tuple of tag name and a list of name->value tuples
 
223
            if data[0] == 'exercise':
 
224
                src = ""
 
225
                optional = False
 
226
                for attr in data[1]:
 
227
                    if attr[0] == 'src':
 
228
                        src = attr[1]
 
229
                    if attr[0] == 'optional':
 
230
                        optional = attr[1] == 'true'
 
231
                if src != "":
 
232
                    exercises.append((src, optional))
 
233
    ex_num = 0
 
234
    # Set all current worksheet_exercises to be inactive
 
235
    db_worksheet_exercises = req.store.find(WorksheetExercise,
 
236
        WorksheetExercise.worksheet_id == worksheet.id)
 
237
    for worksheet_exercise in db_worksheet_exercises:
 
238
        worksheet_exercise.active = False
 
239
    
 
240
    for exerciseid, optional in exercises:
 
241
        worksheet_exercise = req.store.find(WorksheetExercise,
 
242
            WorksheetExercise.worksheet_id == worksheet.id,
 
243
            Exercise.id == WorksheetExercise.exercise_id,
 
244
            Exercise.id == exerciseid).one()
 
245
        if worksheet_exercise is None:
 
246
            exercise = req.store.find(Exercise,
 
247
                Exercise.id == exerciseid
 
248
            ).one()
 
249
            if exercise is None:
 
250
                raise NotFound()
 
251
            worksheet_exercise = WorksheetExercise()
 
252
            worksheet_exercise.worksheet_id = worksheet.id
 
253
            worksheet_exercise.exercise_id = exercise.id
 
254
            req.store.add(worksheet_exercise)
 
255
        worksheet_exercise.active = True
 
256
        worksheet_exercise.seq_no = ex_num
 
257
        worksheet_exercise.optional = optional
 
258
 
 
259
 
 
260
# Note that this is the view of an existing worksheet. Creation is handled
 
261
# by OfferingRESTView (as offerings have worksheets)
 
262
class WorksheetRESTView(JSONRESTView):
 
263
    """View used to update a worksheet."""
 
264
 
 
265
    def get_permissions(self, user):
 
266
        # XXX: Do it properly.
 
267
        # XXX: Lecturers should be allowed to add worksheets Only to subjects
 
268
        #      under their control
 
269
        if user is not None:
 
270
            if user.rolenm == 'admin':
 
271
                return set(['save'])
 
272
            else:
 
273
                return set()
 
274
        else:
 
275
            return set()    
 
276
 
 
277
    def __init__(self, req, **kwargs):
 
278
    
 
279
        self.worksheet = kwargs['worksheet']
 
280
        self.subject = kwargs['subject']
 
281
        self.year = kwargs['year']
 
282
        self.semester = kwargs['semester']
 
283
    
 
284
        self.context = req.store.find(Worksheet,
 
285
            Worksheet.identifier == self.worksheet,
 
286
            Worksheet.offering_id == Offering.id,
 
287
            Offering.subject_id == Subject.id,
 
288
            Subject.code == self.subject,
 
289
            Offering.semester_id == Semester.id,
 
290
            Semester.year == self.year,
 
291
            Semester.semester == self.semester).one()
 
292
        
 
293
        if self.context is None:
 
294
            raise NotFound()
 
295
    
 
296
    @named_operation('save')
 
297
    def save(self, req, name, assessable, data, format):
 
298
        """Takes worksheet data and saves it."""
 
299
        self.generate_exerciselist(self.context, req, data)
 
300
        
 
301
        self.context.name = unicode(name)
 
302
        self.context.assessable = self.convert_bool(assessable)
 
303
        self.context.data = unicode(data)
 
304
        
 
305
        return {"result": "ok"}
 
306
 
 
307
class OfferingRESTView(JSONRESTView):
 
308
    """View used to update Offering and create Worksheets."""
 
309
    
 
310
    def get_permissions(self, user):
 
311
        # XXX: Do it properly.
 
312
        # XXX: Lecturers should be allowed to add worksheets Only to subjects
 
313
        #      under their control
 
314
        if user is not None:
 
315
            if user.rolenm == 'admin':
 
316
                return set(['add_worksheet'])
 
317
            else:
 
318
                return set()
 
319
        else:
 
320
            return set()
 
321
 
 
322
    def __init__(self, req, **kwargs):
 
323
    
 
324
        self.subject = kwargs['subject']
 
325
        self.year = kwargs['year']
 
326
        self.semester = kwargs['semester']
 
327
    
 
328
        self.context = req.store.find(Offering,
 
329
            Offering.subject_id == Subject.id,
 
330
            Subject.code == self.subject,
 
331
            Offering.semester_id == Semester.id,
 
332
            Semester.year == self.year,
 
333
            Semester.semester == self.semester).one()
 
334
        
 
335
        if self.context is None:
 
336
            raise NotFound()
 
337
 
 
338
    @named_operation('add_worksheet')
 
339
    def add_worksheet(self,req, identifier, name, assessable, data, format):
 
340
        """Takes worksheet data and adds it."""
 
341
        
 
342
        new_worksheet = Worksheet()
 
343
        
 
344
        new_worksheet.offering = self.context
 
345
        new_worksheet.identifier = unicode(identifier)
 
346
        new_worksheet.name = unicode(name)
 
347
        new_worksheet.assessable = self.convert_bool(assessable)
 
348
        new_worksheet.data = unicode(data)
 
349
        new_worksheet.format = unicode(format)
 
350
        new_worksheet.seq_no = self.context.worksheets.count()
 
351
        req.store.add(new_worksheet)
 
352
        
 
353
        generate_exerciselist(new_worksheet, req, data)
 
354
        
 
355
        return {"result": "ok"}
 
356