20
20
'''AJAX backend for the tutorial application.'''
25
from storm.locals import Store
27
28
import ivle.database
28
29
from ivle.database import Exercise, ExerciseAttempt, ExerciseSave, Worksheet, \
29
Offering, Subject, Semester, User, WorksheetExercise
30
import ivle.worksheet.utils
31
from ivle.webapp.base.rest import (JSONRESTView, write_operation,
30
Offering, Subject, Semester, WorksheetExercise
33
import ivle.webapp.tutorial.test
35
from ivle.webapp.base.rest import (JSONRESTView, named_operation,
32
36
require_permission)
33
37
from ivle.webapp.errors import NotFound
39
# If True, getattempts or getattempt will allow browsing of inactive/disabled
40
# attempts. If False, will not allow this.
41
HISTORY_ALLOW_INACTIVE = False
36
43
TIMESTAMP_FORMAT = '%Y-%m-%d %H:%M:%S'
39
45
class AttemptsRESTView(JSONRESTView):
40
46
'''REST view of a user's attempts at an exercise.'''
47
def __init__(self, req, subject, year, semester, worksheet,
49
self.user = ivle.database.User.get_by_login(req.store, username)
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()
63
self.context = self.user # XXX: Not quite right.
42
65
@require_permission('edit')
43
66
def GET(self, req):
44
67
"""Handles a GET Attempts action."""
45
68
attempts = req.store.find(ExerciseAttempt,
46
ExerciseAttempt.ws_ex_id == self.context.worksheet_exercise.id,
47
ExerciseAttempt.user_id == self.context.user.id)
69
ExerciseAttempt.ws_ex_id == self.worksheet_exercise.id,
70
ExerciseAttempt.user_id == self.user.id)
48
71
# attempts is a list of ExerciseAttempt objects. Convert to dictionaries
49
72
time_fmt = lambda dt: datetime.datetime.strftime(dt, TIMESTAMP_FORMAT)
50
73
attempts = [{'date': time_fmt(a.date), 'complete': a.complete}
56
79
@require_permission('edit')
57
80
def PUT(self, req, data):
58
81
""" Tests the given submission """
59
test_results = ivle.worksheet.utils.test_exercise_submission(
60
req.config, req.user, self.context.worksheet_exercise.exercise,
82
exercise = req.store.find(Exercise,
83
Exercise.id == self.worksheet_exercise.exercise_id).one()
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)
92
# Parse the file into a exercise object using the test suite
93
exercise_obj = ivle.webapp.tutorial.test.parse_exercise_file(
96
# Run the test cases. Get the result back as a JSONable object.
98
test_results = exercise_obj.run_tests(data['code'])
63
103
attempt = ivle.database.ExerciseAttempt(user=req.user,
64
worksheet_exercise = self.context.worksheet_exercise,
104
worksheet_exercise = self.worksheet_exercise,
65
105
date = datetime.datetime.now(),
66
106
complete = test_results['passed'],
67
107
text = unicode(data['code'])
83
123
class AttemptRESTView(JSONRESTView):
84
124
'''REST view of an exercise attempt.'''
126
def __init__(self, req, subject, year, semester, worksheet, exercise,
128
# TODO: Find exercise within worksheet.
129
user = ivle.database.User.get_by_login(req.store, username)
134
# date = datetime.datetime.strptime(date, TIMESTAMP_FORMAT)
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()
149
attempt = req.store.find(ExerciseAttempt,
150
ExerciseAttempt.user_id == user.id,
151
ExerciseAttempt.ws_ex_id == worksheet_exercise.id,
152
ExerciseAttempt.date == date
158
self.context = attempt
86
160
@require_permission('view')
87
161
def GET(self, req):
88
162
return {'code': self.context.text}
91
class WorksheetExerciseRESTView(JSONRESTView):
92
'''REST view of a worksheet exercise.'''
94
@write_operation('view')
165
class ExerciseRESTView(JSONRESTView):
166
'''REST view of an exercise.'''
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?
177
@named_operation('save')
95
178
def save(self, req, text):
96
179
# Find the appropriate WorksheetExercise to save to. If its not found,
97
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()
191
if worksheet_exercise is None:
99
194
old_save = req.store.find(ExerciseSave,
100
ExerciseSave.ws_ex_id == self.context.id,
195
ExerciseSave.ws_ex_id == worksheet_exercise.id,
101
196
ExerciseSave.user == req.user).one()
103
198
#Overwrite the old, or create a new if there isn't one
115
210
return {"result": "ok"}
118
class WorksheetsRESTView(JSONRESTView):
119
"""View used to update and create Worksheets."""
121
@write_operation('edit_worksheets')
122
def move_up(self, req, worksheetid):
123
"""Takes a list of worksheet-seq_no pairs and updates their
124
corresponding Worksheet objects to match."""
126
worksheet_below = req.store.find(Worksheet,
127
Worksheet.offering_id == self.context.id,
128
Worksheet.identifier == unicode(worksheetid)).one()
129
if worksheet_below is None:
130
raise NotFound('worksheet_below')
131
worksheet_above = req.store.find(Worksheet,
132
Worksheet.offering_id == self.context.id,
133
Worksheet.seq_no == (worksheet_below.seq_no - 1)).one()
134
if worksheet_above is None:
135
raise NotFound('worksheet_above')
137
worksheet_below.seq_no = worksheet_below.seq_no - 1
138
worksheet_above.seq_no = worksheet_above.seq_no + 1
140
return {'result': 'ok'}
142
@write_operation('edit_worksheets')
143
def move_down(self, req, worksheetid):
144
"""Takes a list of worksheet-seq_no pairs and updates their
145
corresponding Worksheet objects to match."""
147
worksheet_above = req.store.find(Worksheet,
148
Worksheet.offering_id == self.context.id,
149
Worksheet.identifier == unicode(worksheetid)).one()
150
if worksheet_above is None:
151
raise NotFound('worksheet_below')
152
worksheet_below = req.store.find(Worksheet,
153
Worksheet.offering_id == self.context.id,
154
Worksheet.seq_no == (worksheet_above.seq_no + 1)).one()
155
if worksheet_below is None:
156
raise NotFound('worksheet_above')
158
worksheet_below.seq_no = worksheet_below.seq_no - 1
159
worksheet_above.seq_no = worksheet_above.seq_no + 1
161
return {'result': 'ok'}
213
def generate_exerciselist(worksheet, req, worksheetdata):
214
"""Runs through the worksheetstream, generating the appropriate
215
WorksheetExercises, and de-activating the old ones."""
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':
229
if attr[0] == 'optional':
230
optional = attr[1] == 'true'
232
exercises.append((src, optional))
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
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
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
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."""
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
270
if user.rolenm == 'admin':
277
def __init__(self, req, **kwargs):
279
self.worksheet = kwargs['worksheet']
280
self.subject = kwargs['subject']
281
self.year = kwargs['year']
282
self.semester = kwargs['semester']
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()
293
if self.context is None:
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)
301
self.context.name = unicode(name)
302
self.context.assessable = self.convert_bool(assessable)
303
self.context.data = unicode(data)
305
return {"result": "ok"}
307
class OfferingRESTView(JSONRESTView):
308
"""View used to update Offering and create Worksheets."""
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
315
if user.rolenm == 'admin':
316
return set(['add_worksheet'])
322
def __init__(self, req, **kwargs):
324
self.subject = kwargs['subject']
325
self.year = kwargs['year']
326
self.semester = kwargs['semester']
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()
335
if self.context is None:
338
@named_operation('add_worksheet')
339
def add_worksheet(self,req, identifier, name, assessable, data, format):
340
"""Takes worksheet data and adds it."""
342
new_worksheet = Worksheet()
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)
353
generate_exerciselist(new_worksheet, req, data)
355
return {"result": "ok"}