views.py 13.3 KB
Newer Older
1 2 3
import logging

from django.views.decorators.cache import cache_control
David Baumgold committed
4
from edxmako.shortcuts import render_to_response
5 6
from django.core.urlresolvers import reverse

Calen Pennington committed
7
from courseware.courses import get_course_with_access
8

9
from xmodule.open_ended_grading_classes.grading_service_module import GradingServiceError
10
import json
Vik Paruchuri committed
11
from student.models import unique_id_for_user
12

13
import open_ended_notifications
14

15 16
from xmodule.modulestore.django import modulestore
from xmodule.modulestore import search
17
from opaque_keys.edx.locations import SlashSeparatedCourseKey
cahrens committed
18
from xmodule.modulestore.exceptions import NoPathToItem
19

20
from django.http import HttpResponse, Http404, HttpResponseRedirect
21
from django.utils.translation import ugettext as _
Vik Paruchuri committed
22

23 24 25
from open_ended_grading.utils import (
    STAFF_ERROR_MESSAGE, StudentProblemList, generate_problem_url, create_controller_query_service
)
Calen Pennington committed
26

27
log = logging.getLogger(__name__)
Calen Pennington committed
28

29 30

def _reverse_with_slash(url_name, course_key):
31 32 33 34 35 36 37
    """
    Reverses the URL given the name and the course id, and then adds a trailing slash if
    it does not exist yet.
    @param url_name: The name of the url (eg 'staff_grading').
    @param course_id: The id of the course object (eg course.id).
    @returns: The reversed url with a trailing slash.
    """
38
    ajax_url = _reverse_without_slash(url_name, course_key)
39 40 41 42
    if not ajax_url.endswith('/'):
        ajax_url += '/'
    return ajax_url

Calen Pennington committed
43

44 45
def _reverse_without_slash(url_name, course_key):
    course_id = course_key.to_deprecated_string()
Vik Paruchuri committed
46 47
    ajax_url = reverse(url_name, kwargs={'course_id': course_id})
    return ajax_url
48

Vik Paruchuri committed
49

50
DESCRIPTION_DICT = {
51 52 53 54
    'Peer Grading': _("View all problems that require peer assessment in this particular course."),
    'Staff Grading': _("View ungraded submissions submitted by students for the open ended problems in the course."),
    'Problems you have submitted': _("View open ended problems that you have previously submitted for grading."),
    'Flagged Submissions': _("View submissions that have been flagged by students as inappropriate."),
Vik Paruchuri committed
55
}
56

57
ALERT_DICT = {
58 59 60 61
    'Peer Grading': _("New submissions to grade"),
    'Staff Grading': _("New submissions to grade"),
    'Problems you have submitted': _("New grades have been returned"),
    'Flagged Submissions': _("Submissions have been flagged for review"),
Vik Paruchuri committed
62
}
Calen Pennington committed
63

64

65 66 67 68 69
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def staff_grading(request, course_id):
    """
    Show the instructor grading interface.
    """
70 71
    course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_with_access(request.user, 'staff', course_key)
72

73
    ajax_url = _reverse_with_slash('staff_grading', course_key)
Calen Pennington committed
74

75 76 77 78 79 80 81
    return render_to_response('instructor/staff_grading.html', {
        'course': course,
        'course_id': course_id,
        'ajax_url': ajax_url,
        # Checked above
        'staff_access': True, })

82

83
def find_peer_grading_module(course):
84 85 86 87 88
    """
    Given a course, finds the first peer grading module in it.
    @param course: A course object.
    @return: boolean found_module, string problem_url
    """
Vik Paruchuri committed
89 90

    # Reverse the base course url.
91 92 93 94
    base_course_url = reverse('courses')
    found_module = False
    problem_url = ""

Vik Paruchuri committed
95
    # Get the peer grading modules currently in the course.  Explicitly specify the course id to avoid issues with different runs.
96
    items = modulestore().get_items(course.id, qualifiers={'category': 'peergrading'})
97
    # See if any of the modules are centralized modules (ie display info from multiple problems)
98
    items = [i for i in items if not getattr(i, "use_for_single_location", True)]
Vik Paruchuri committed
99
    # Loop through all potential peer grading modules, and find the first one that has a path to it.
100
    for item in items:
Vik Paruchuri committed
101
        # Generate a url for the first module and redirect the user to it.
102
        try:
103
            problem_url_parts = search.path_to_location(modulestore(), item.location)
104
        except NoPathToItem:
Vik Paruchuri committed
105 106
            # In the case of nopathtoitem, the peer grading module that was found is in an invalid state, and
            # can no longer be accessed.  Log an informational message, but this will not impact normal behavior.
107
            log.info(u"Invalid peer grading module location %s in course %s.  This module may need to be removed.", item.location, course.id)
108
            continue
109 110 111 112
        problem_url = generate_problem_url(problem_url_parts, base_course_url)
        found_module = True

    return found_module, problem_url
Calen Pennington committed
113

114

115
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
116 117
def peer_grading(request, course_id):
    '''
118 119
    When a student clicks on the "peer grading" button in the open ended interface, link them to a peer grading
    xmodule in the course.
120
    '''
121
    course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
Vik Paruchuri committed
122
    #Get the current course
123
    course = get_course_with_access(request.user, 'load', course_key)
124

125 126
    found_module, problem_url = find_peer_grading_module(course)
    if not found_module:
127
        error_message = _("""
Vik Paruchuri committed
128 129 130
        Error with initializing peer grading.
        There has not been a peer grading module created in the courseware that would allow you to grade others.
        Please check back later for this.
131 132
        """)
        log.exception(error_message + u"Current course is: {0}".format(course_id))
133
        return HttpResponse(error_message)
134

135
    return HttpResponseRedirect(problem_url)
Calen Pennington committed
136

137

138 139
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def student_problem_list(request, course_id):
140
    """
141 142 143 144 145
    Show a list of problems they have attempted to a student.
    Fetch the list from the grading controller server and append some data.
    @param request: The request object for this view.
    @param course_id: The id of the course to get the problem list for.
    @return: Renders an HTML problem list table.
146
    """
147 148
    assert isinstance(course_id, basestring)
    course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
149
    # Load the course.  Don't catch any errors here, as we want them to be loud.
150
    course = get_course_with_access(request.user, 'load', course_key)
151

152 153
    # The anonymous student id is needed for communication with ORA.
    student_id = unique_id_for_user(request.user)
Vik Paruchuri committed
154
    base_course_url = reverse('courses')
155
    error_text = ""
156

157
    student_problem_list = StudentProblemList(course_key, student_id)
158 159 160 161 162 163 164 165 166 167
    # Get the problem list from ORA.
    success = student_problem_list.fetch_from_grading_service()
    # If we fetched the problem list properly, add in additional problem data.
    if success:
        # Add in links to problems.
        valid_problems = student_problem_list.add_problem_data(base_course_url)
    else:
        # Get an error message to show to the student.
        valid_problems = []
        error_text = student_problem_list.error_text
168

169
    ajax_url = _reverse_with_slash('open_ended_problems', course_key)
170

171
    context = {
172
        'course': course,
173
        'course_id': course_key.to_deprecated_string(),
174 175
        'ajax_url': ajax_url,
        'success': success,
176
        'problem_list': valid_problems,
177 178
        'error_text': error_text,
        # Checked above
179
        'staff_access': False,
180
    }
181

182
    return render_to_response('open_ended_problems/open_ended_problems.html', context)
Calen Pennington committed
183

184

185 186 187 188 189
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
def flagged_problem_list(request, course_id):
    '''
    Show a student problem list
    '''
190 191
    course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_with_access(request.user, 'staff', course_key)
192 193 194 195 196 197

    # call problem list service
    success = False
    error_text = ""
    problem_list = []

198 199
    # Make a service that can query edX ORA.
    controller_qs = create_controller_query_service()
200
    try:
201
        problem_list_dict = controller_qs.get_flagged_problem_list(course_key)
202 203 204
        success = problem_list_dict['success']
        if 'error' in problem_list_dict:
            error_text = problem_list_dict['error']
Calen Pennington committed
205
            problem_list = []
206 207
        else:
            problem_list = problem_list_dict['flagged_submissions']
208

209
    except GradingServiceError:
210 211 212 213
        #This is a staff_facing_error
        error_text = STAFF_ERROR_MESSAGE
        #This is a dev_facing_error
        log.error("Could not get flagged problem list from external grading service for open ended.")
214 215 216
        success = False
    # catch error if if the json loads fails
    except ValueError:
217 218 219 220
        #This is a staff_facing_error
        error_text = STAFF_ERROR_MESSAGE
        #This is a dev_facing_error
        log.error("Could not parse problem list from external grading service response.")
221 222
        success = False

223
    ajax_url = _reverse_with_slash('open_ended_flagged_problems', course_key)
224
    context = {
Vik Paruchuri committed
225 226 227 228 229 230 231 232
        'course': course,
        'course_id': course_id,
        'ajax_url': ajax_url,
        'success': success,
        'problem_list': problem_list,
        'error_text': error_text,
        # Checked above
        'staff_access': True,
233 234
    }
    return render_to_response('open_ended_problems/open_ended_flagged_problems.html', context)
235

Calen Pennington committed
236

237
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
238
def combined_notifications(request, course_id):
Vik Paruchuri committed
239 240 241
    """
    Gets combined notifications from the grading controller and displays them
    """
242 243
    course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_with_access(request.user, 'load', course_key)
244
    user = request.user
245
    notifications = open_ended_notifications.combined_notifications(course, user)
246
    response = notifications['response']
Calen Pennington committed
247
    notification_tuples = open_ended_notifications.NOTIFICATION_TYPES
248

249
    notification_list = []
Calen Pennington committed
250 251
    for response_num in xrange(0, len(notification_tuples)):
        tag = notification_tuples[response_num][0]
252 253 254
        if tag in response:
            url_name = notification_tuples[response_num][1]
            human_name = notification_tuples[response_num][2]
255
            url = _reverse_without_slash(url_name, course_key)
256 257
            has_img = response[tag]

258 259 260 261 262 263 264 265 266 267
            # check to make sure we have descriptions and alert messages
            if human_name in DESCRIPTION_DICT:
                description = DESCRIPTION_DICT[human_name]
            else:
                description = ""

            if human_name in ALERT_DICT:
                alert_message = ALERT_DICT[human_name]
            else:
                alert_message = ""
Calen Pennington committed
268

269
            notification_item = {
Calen Pennington committed
270 271 272
                'url': url,
                'name': human_name,
                'alert': has_img,
273 274
                'description': description,
                'alert_message': alert_message
275
            }
276 277 278 279
            #The open ended panel will need to link the "peer grading" button in the panel to a peer grading
            #xmodule defined in the course.  This checks to see if the human name of the server notification
            #that we are currently processing is "peer grading".  If it is, it looks for a peer grading
            #module in the course.  If none exists, it removes the peer grading item from the panel.
280 281 282 283 284 285
            if human_name == "Peer Grading":
                found_module, problem_url = find_peer_grading_module(course)
                if found_module:
                    notification_list.append(notification_item)
            else:
                notification_list.append(notification_item)
286

287
    ajax_url = _reverse_with_slash('open_ended_notifications', course_key)
288
    combined_dict = {
Calen Pennington committed
289 290 291 292 293
        'error_text': "",
        'notification_list': notification_list,
        'course': course,
        'success': True,
        'ajax_url': ajax_url,
294 295
    }

296
    return render_to_response('open_ended_problems/combined_notifications.html', combined_dict)
297

Calen Pennington committed
298

Vik Paruchuri committed
299
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
300 301
def take_action_on_flags(request, course_id):
    """
Vik Paruchuri committed
302 303
    Takes action on student flagged submissions.
    Currently, only support unflag and ban actions.
304
    """
305
    course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
306 307 308 309 310 311
    if request.method != 'POST':
        raise Http404

    required = ['submission_id', 'action_type', 'student_id']
    for key in required:
        if key not in request.POST:
312 313 314 315 316 317
            error_message = u'Missing key {0} from submission.  Please reload and try again.'.format(key)
            response = {
                'success': False,
                'error': STAFF_ERROR_MESSAGE + error_message
            }
            return HttpResponse(json.dumps(response), mimetype="application/json")
318 319 320 321 322

    p = request.POST
    submission_id = p['submission_id']
    action_type = p['action_type']
    student_id = p['student_id']
Vik Paruchuri committed
323 324 325
    student_id = student_id.strip(' \t\n\r')
    submission_id = submission_id.strip(' \t\n\r')
    action_type = action_type.lower().strip(' \t\n\r')
326 327 328

    # Make a service that can query edX ORA.
    controller_qs = create_controller_query_service()
329
    try:
330
        response = controller_qs.take_action_on_flags(course_key, student_id, submission_id, action_type)
331
        return HttpResponse(json.dumps(response), mimetype="application/json")
332
    except GradingServiceError:
Vik Paruchuri committed
333
        log.exception(
334
            u"Error taking action on flagged peer grading submissions, "
David Baumgold committed
335 336
            u"submission_id: {0}, action_type: {1}, grader_id: {2}"
            .format(submission_id, action_type, student_id)
337 338 339 340 341
        )
        response = {
            'success': False,
            'error': STAFF_ERROR_MESSAGE
        }
342
        return HttpResponse(json.dumps(response), mimetype="application/json")