Esempio n. 1
0
def your_records(request, record_owner_name):
    """
    An ajax-only request to retrieve a specified user's projects, assignment responses and selections
        
    """
    if not request.is_ajax():
        raise Http404()

    course = request.course
    in_course_or_404(record_owner_name, course)
    record_owner = get_object_or_404(User, username=record_owner_name)
    logged_in_user = request.user

    assets = annotated_by(Asset.objects.filter(course=course),
                          record_owner,
                          include_archives=course.is_faculty(record_owner))

    projects = Project.get_user_projects(record_owner,
                                         course).order_by('-modified')
    if not record_owner == logged_in_user:
        projects = [p for p in projects if p.visible(request)]

    project_type = ContentType.objects.get_for_model(Project)
    assignments = []
    for assignment in Project.objects.filter(course.faculty_filter):
        if not assignment.visible(request):
            continue
        if assignment in projects:
            continue
        if is_unanswered_assignment(assignment, record_owner, request,
                                    project_type):
            assignments.append(assignment)

    return get_records(request, record_owner, projects, assignments, assets)
Esempio n. 2
0
def project_create(request):
    user = request.user
    course = request.course
    in_course_or_404(user, course)

    project = Project(author=user, course=course, title="Untitled")
    project.save()

    project.collaboration(request, sync_group=True)

    parent = request.POST.get("parent")
    if parent is not None:
        try:
            parent = Project.objects.get(pk=parent)

            parent_collab = parent.collaboration(request)
            if parent_collab.permission_to("add_child", request):
                parent_collab.append_child(project)

        except Project.DoesNotExist:
            parent = None
            # @todo -- an error has occurred

    if not request.is_ajax():
        return HttpResponseRedirect(project.get_absolute_url())
    else:
        project_context = composition_project_json(request, project, project.can_edit(request))
        project_context["editing"] = True

        data = {"panel_state": "open", "template": "project", "context": project_context}

        return HttpResponse(simplejson.dumps(data, indent=2), mimetype="application/json")
def all_projects(request):
    """
    An ajax-only request to retrieve a course's projects,
    assignment responses and selections
    """

    if not request.is_ajax():
        raise Http404()

    if not request.user.is_staff:
        in_course_or_404(request.user.username, request.course)

    course = request.course
    logged_in_user = request.user

    projects = Project.objects.visible_by_course(request, course)

    # Assemble the context
    user_rez = UserResource()
    course_rez = CourseSummaryResource()
    data = {'projects': homepage_project_json(request, projects, False),
            'space_viewer': user_rez.render_one(request, logged_in_user),
            'course': course_rez.render_one(request, course),
            'compositions': len(projects) > 0,
            'is_faculty': course.is_faculty(logged_in_user)}

    json_stream = simplejson.dumps(data, indent=2)
    return HttpResponse(json_stream, mimetype='application/json')
Esempio n. 4
0
def all_records(request):
    c = request.course

    if not request.user.is_staff:
        in_course_or_404(request.user.username, c)

    return get_records('all', c, request)
Esempio n. 5
0
def triple_homepage(request):
    if not request.course:
        return HttpResponseRedirect('/accounts/login/')

    logged_in_user = request.user
    classwork_owner = request.user  # Viewing your own work by default
    if request.GET.has_key('username'):
        user_name = request.GET['username']
        in_course_or_404(user_name, request.course)
        classwork_owner = get_object_or_404(User, username=user_name)

    context = {
        'classwork_owner':
        classwork_owner,
        'help_homepage_instructor_column':
        UserSetting.get_setting(logged_in_user,
                                "help_homepage_instructor_column", True),
        'help_homepage_classwork_column':
        UserSetting.get_setting(logged_in_user,
                                "help_homepage_classwork_column", True),
        'faculty_feed':
        get_prof_feed(request.course, request),
        'is_faculty':
        request.course.is_faculty(logged_in_user),
        'discussions':
        get_course_discussions(request.course),
        'msg':
        request.GET.get('msg', ''),
        'tag':
        request.GET.get('tag', ''),
        'view':
        request.GET.get('view', '')
    }
    return context
Esempio n. 6
0
def triple_homepage(request):
    if not request.course:
        return HttpResponseRedirect('/accounts/login/')
    
    logged_in_user = request.user
    classwork_owner = request.user # Viewing your own work by default
    if request.GET.has_key('username'):
        user_name = request.GET['username']
        in_course_or_404(user_name, request.course)
        classwork_owner = get_object_or_404(User, username=user_name)

    context = {
        'classwork_owner': classwork_owner,
        'help_homepage_instructor_column': UserSetting.get_setting(logged_in_user, "help_homepage_instructor_column", True),
        'help_homepage_classwork_column':  UserSetting.get_setting(logged_in_user, "help_homepage_classwork_column", True),

        'faculty_feed': get_prof_feed(request.course, request),
        'is_faculty': request.course.is_faculty(logged_in_user),
        'discussions': get_course_discussions(request.course),
        
        'msg': request.GET.get('msg', ''),
        'tag': request.GET.get('tag', ''),
        'view': request.GET.get('view', '')
    }
    return context
Esempio n. 7
0
def your_records(request, record_owner_name):
    """
    An ajax-only request to retrieve a specified user's projects, assignment responses and selections
        
    """    
    if not request.is_ajax():
        raise Http404()

    course = request.course    
    in_course_or_404(record_owner_name, course)
    record_owner = get_object_or_404(User, username = record_owner_name)
    logged_in_user = request.user

    assets = annotated_by(Asset.objects.filter(course = course),
                          record_owner,
                          include_archives = course.is_faculty(record_owner))
            
    projects = Project.get_user_projects(record_owner, course).order_by('-modified')
    if not record_owner == logged_in_user:
        projects = [p for p in projects if p.visible(request)]

    project_type = ContentType.objects.get_for_model(Project)
    assignments = []
    for assignment in Project.objects.filter(course.faculty_filter):
        if not assignment.visible(request):
            continue
        if assignment in projects:
            continue
        if is_unanswered_assignment(assignment, record_owner, request, project_type):
            assignments.append(assignment)
            
    return get_records(request, record_owner, projects, assignments, assets)
Esempio n. 8
0
def all_records(request):
    c = request.course
    
    if not request.user.is_staff:
        in_course_or_404(request.user.username, c)
    
    return get_records('all', c, request);
Esempio n. 9
0
def all_records(request):
    """
    An ajax-only request to retrieve a course's projects, assignment responses and selections
        
    """

    if not request.is_ajax():
        raise Http404()

    if not request.user.is_staff:
        in_course_or_404(request.user.username, request.course)

    course = request.course
    archives = list(request.course.asset_set.archives())
    assets = [
        a for a in Asset.objects.filter(course=course).extra(
            select={
                'lower_title': 'lower(assetmgr_asset.title)'
            }).select_related().order_by('lower_title') if a not in archives
    ]

    projects = [
        p for p in Project.objects.filter(course=course,
                                          submitted=True).order_by('title')
        if p.visible(request)
    ]

    return get_records(request, None, projects, [], assets)
Esempio n. 10
0
 def get_project_owner(self):
     project_owner = self.request.GET.get('owner', None)
     if project_owner:
         in_course_or_404(project_owner, self.request.course)
         return get_object_or_404(User, username=project_owner)
     else:
         # viewing own work by default
         return self.request.user
Esempio n. 11
0
def your_records(request, user_name):
    if not request.is_ajax():
        raise Http404()
    
    c = request.course
    in_course_or_404(user_name, c)
    user = get_object_or_404(User, username=user_name)
    
    return get_records(user, c, request)
Esempio n. 12
0
 def test_in_course_or_404(self):
     assert in_course_or_404(self.student, self.c)
     assert in_course_or_404(self.student, self.student_group)
     try:
         # expect it to raise an error
         in_course_or_404(self.faculty, self.student_group)
         assert False
     except:
         assert True
Esempio n. 13
0
def all_records(request):
    if not request.is_ajax():
        raise Http404()
    
    c = request.course
    
    if not request.user.is_staff:
        in_course_or_404(request.user.username, c)
    
    return get_records('all', c, request);
Esempio n. 14
0
def project_save(request, project_id):
    project = get_object_or_404(Project, pk=project_id, course=request.course)

    if not project.can_edit(request.course, request.user):
        return HttpResponseRedirect(project.get_absolute_url())

    # verify user is in course
    in_course_or_404(project.author.username, request.course)

    projectform = ProjectForm(request, instance=project, data=request.POST)
    if projectform.is_valid():

        # legacy and for optimizing queries
        projectform.instance.submitted = \
            request.POST.get('publish', None) != 'PrivateEditorsAreOwners'

        # this changes for version-tracking purposes
        projectform.instance.author = request.user
        projectform.save()

        projectform.instance.participants.add(request.user)

        # update the collaboration
        policy_name = request.POST.get('publish', 'PrivateEditorsAreOwners')
        projectform.instance.create_or_update_collaboration(policy_name)

        v_num = projectform.instance.get_latest_version()
        is_assignment = projectform.instance.is_assignment(request.course,
                                                           request.user)

        return HttpResponse(json.dumps({
            'status': 'success',
            'is_assignment': is_assignment,
            'title': projectform.instance.title,
            'revision': {
                'id': v_num,
                'public_url': projectform.instance.public_url(),
                'visibility': project.visibility_short(),
                'due_date': project.get_due_date()
            }
        }, indent=2), content_type='application/json')
    else:
        ctx = {'status': 'error', 'msg': ""}
        for key, value in projectform.errors.items():
            if key == '__all__':
                ctx['msg'] = ctx['msg'] + value[0] + "\n"
            else:
                ctx['msg'] = \
                    '%s "%s" is not valid for the %s field.\n %s\n' % \
                    (ctx['msg'], projectform.data[key],
                     projectform.fields[key].label,
                     value[0].lower())

        return HttpResponse(json.dumps(ctx, indent=2),
                            content_type='application/json')
Esempio n. 15
0
def asset_detail(request, asset_id):
    if not request.user.is_staff:
        in_course_or_404(request.user.username, request.course)

    try:
        asset = Asset.objects.get(pk=asset_id, course=request.course)
        the_json = detail_asset_json(request, asset)
        return HttpResponse(simplejson.dumps(the_json, indent=2),
                            mimetype='application/json')
    except Asset.DoesNotExist:
        return asset_switch_course(request, asset_id)
Esempio n. 16
0
def asset_detail(request, asset_id):
    if not request.user.is_staff:
        in_course_or_404(request.user.username, request.course)

    try:
        asset = Asset.objects.get(pk=asset_id, course=request.course)
        the_json = detail_asset_json(request, asset)
        return HttpResponse(simplejson.dumps(the_json, indent=2),
                            mimetype='application/json')
    except Asset.DoesNotExist:
        return asset_switch_course(request, asset_id)
Esempio n. 17
0
def asset_workspace(request, asset_id=None, annot_id=None):
    if not request.user.is_staff:
        in_course_or_404(request.user.username, request.course)

    if asset_id:
        try:
            asset = Asset.objects.get(pk=asset_id, course=request.course)
            asset.primary
        except Asset.DoesNotExist:
            return asset_switch_course(request, asset_id)
        except Source.DoesNotExist:
            response = direct_to_template(request, "500.html", {})
            response.status_code = 500
            return response

    data = {
        'space_owner': request.user.username,
        'asset_id': asset_id,
        'annotation_id': annot_id
    }

    if not request.is_ajax():
        return render_to_response('assetmgr/asset_workspace.html',
                                  data,
                                  context_instance=RequestContext(request))
    elif asset_id:
        # @todo - refactor this context out of the mix
        # ideally, the client would simply request the json
        context = detail_asset_json(request, asset)
    else:
        context = {'type': 'asset'}

    vocabulary = VocabularyResource().render_list(
        request, Vocabulary.objects.get_for_object(request.course))

    user_resource = UserResource()
    owners = user_resource.render_list(request, request.course.members)

    data['panels'] = [{
        'panel_state': 'open',
        'panel_state_label': "Annotate Media",
        'context': context,
        'owners': owners,
        'vocabulary': vocabulary,
        'template': 'asset_workspace',
        'current_asset': asset_id,
        'current_annotation': annot_id,
        'update_history': True,
        'show_collection': True,
    }]

    return HttpResponse(simplejson.dumps(data, indent=2),
                        mimetype='application/json')
Esempio n. 18
0
def asset_delete(request, asset_id):
    in_course_or_404(request.user.username, request.course)

    # Remove all annotations by this user
    # By removing the "global annotation" this effectively removes
    # The asset from the workspace
    asset = get_object_or_404(Asset, pk=asset_id, course=request.course)
    annotations = asset.sherdnote_set.filter(author=request.user)
    annotations.delete()

    json_stream = json.dumps({})
    return HttpResponse(json_stream, content_type='application/json')
Esempio n. 19
0
def asset_switch_course(request, asset_id):
    asset = Asset.objects.get(pk=asset_id)
    in_course_or_404(request.user.username, asset.course)

    # the user is logged into the wrong class?
    rv = {}
    rv['switch_to'] = asset.course
    rv['switch_from'] = request.course
    rv['redirect'] = reverse('asset-view', args=[asset_id])
    return render_to_response('assetmgr/asset_not_found.html',
                              rv,
                              context_instance=RequestContext(request))
Esempio n. 20
0
def asset_delete(request, asset_id):
    in_course_or_404(request.user.username, request.course)

    # Remove all annotations by this user
    # By removing the "global annotation" this effectively removes
    # The asset from the workspace
    asset = get_object_or_404(Asset, pk=asset_id, course=request.course)
    annotations = asset.sherdnote_set.filter(author=request.user)
    annotations.delete()

    json_stream = json.dumps({})
    return HttpResponse(json_stream, content_type='application/json')
Esempio n. 21
0
def project_save(request, project_id):
    project = get_object_or_404(Project, pk=project_id, course=request.course)

    if not project.can_edit(request):
        return HttpResponseRedirect(project.get_absolute_url())

    # verify user is in course
    in_course_or_404(project.author.username, request.course)

    projectform = ProjectForm(request, instance=project, data=request.POST)
    if projectform.is_valid():

        # legacy and for optimizing queries
        projectform.instance.submitted = request.POST.get("publish", None) != "PrivateEditorsAreOwners"

        # this changes for version-tracking purposes
        projectform.instance.author = request.user
        projectform.save()

        projectform.instance.collaboration(request, sync_group=True)

        v_num = projectform.instance.get_latest_version()
        return HttpResponse(
            simplejson.dumps(
                {
                    "status": "success",
                    "is_assignment": projectform.instance.is_assignment(request),
                    "title": projectform.instance.title,
                    "revision": {
                        "id": v_num,
                        "public_url": projectform.instance.public_url(),
                        "visibility": project.visibility_short(),
                        "due_date": project.get_due_date(),
                    },
                },
                indent=2,
            ),
            mimetype="application/json",
        )
    else:
        ctx = {"status": "error", "msg": ""}
        for key, value in projectform.errors.items():
            if key == "__all__":
                ctx["msg"] = ctx["msg"] + value[0] + "\n"
            else:
                ctx["msg"] = '%s "%s" is not valid for the %s field.\n %s\n' % (
                    ctx["msg"],
                    projectform.data[key],
                    projectform.fields[key].label,
                    value[0].lower(),
                )

        return HttpResponse(simplejson.dumps(ctx, indent=2), mimetype="application/json")
Esempio n. 22
0
def asset_switch_course(request, asset_id):
    try:
        asset = Asset.objects.get(pk=asset_id)
        in_course_or_404(request.user.username, asset.course)

        # the user is logged into the wrong class?
        rv = {}
        rv['switch_to'] = asset.course
        rv['switch_from'] = request.course
        rv['redirect'] = reverse('asset-view', args=[asset_id])
        return render(request, 'assetmgr/asset_not_found.html', rv)
    except Asset.DoesNotExist:
        raise Http404("This item does not exist.")
Esempio n. 23
0
def asset_switch_course(request, asset_id):
    try:
        asset = Asset.objects.get(pk=asset_id)
        in_course_or_404(request.user.username, asset.course)

        # the user is logged into the wrong class?
        rv = {}
        rv['switch_to'] = asset.course
        rv['switch_from'] = request.course
        rv['redirect'] = reverse('asset-view', args=[asset_id])
        return render(request, 'assetmgr/asset_not_found.html', rv)
    except Asset.DoesNotExist:
        raise Http404("This item does not exist.")
Esempio n. 24
0
def your_records(request, user_name):

    c = request.course
    in_course_or_404(user_name, c)

    today = datetime.date.today()
    user = get_object_or_404(User, username=user_name)

    editable = (user==request.user)
    assets = annotated_by(Asset.objects.filter(course=c),
                          user,
                          include_archives=c.is_faculty(user)
                          )

    projects = Project.get_user_projects(user, c)
    if not editable:
        projects = projects.filter(submitted=True)
    projects = projects.order_by('-modified')


    for fil in filter_by:
        filter_value = request.GET.get(fil)
        if filter_value:
            assets = [asset for asset in assets
                      if filter_by[fil](asset, filter_value, user)]

    tags = calculate_cloud(Tag.objects.usage_for_queryset(
            user.sherdnote_set.filter(
                asset__course=c),
            counts=True))
    
    active_filters = dict((filter, request.GET.get(filter))
                          for filter in filter_by
                          if filter in request.GET)
    #bad language, we should change this to user_of_assets or something
    space_viewer = user 
    if request.GET.has_key('as') and request.user.is_staff:
        space_viewer = get_object_or_404(User, username=request.GET['as'])

    return {
        'assets'        : assets,
        'projects'      : projects,
        'tags'          : tags,
        'dates'         : {'today':'today',
                           'yesterday':'yesterday',
                           'lastweek':'within the last week'},
        'space_owner'   : user,
        'space_viewer'  : space_viewer,
        'editable'      : editable,
        'active_filters': active_filters,
        }
Esempio n. 25
0
def project_save(request, project_id):
    project = get_object_or_404(Project, pk=project_id, course=request.course)

    if not project.can_edit(request):
        return HttpResponseRedirect(project.get_absolute_url())

    # verify user is in course
    in_course_or_404(project.author.username, request.course)

    projectform = ProjectForm(request, instance=project, data=request.POST)
    if projectform.is_valid():

        # legacy and for optimizing queries
        projectform.instance.submitted = \
            request.POST.get('publish', None) != 'PrivateEditorsAreOwners'

        # this changes for version-tracking purposes
        projectform.instance.author = request.user
        projectform.save()

        projectform.instance.collaboration(request, sync_group=True)

        v_num = projectform.instance.get_latest_version()
        return HttpResponse(json.dumps(
            {
                'status': 'success',
                'is_assignment': projectform.instance.is_assignment(request),
                'title': projectform.instance.title,
                'revision': {
                    'id': v_num,
                    'public_url': projectform.instance.public_url(),
                    'visibility': project.visibility_short(),
                    'due_date': project.get_due_date()
                }
            },
            indent=2),
                            mimetype='application/json')
    else:
        ctx = {'status': 'error', 'msg': ""}
        for key, value in projectform.errors.items():
            if key == '__all__':
                ctx['msg'] = ctx['msg'] + value[0] + "\n"
            else:
                ctx['msg'] = \
                    '%s "%s" is not valid for the %s field.\n %s\n' % \
                    (ctx['msg'], projectform.data[key],
                     projectform.fields[key].label,
                     value[0].lower())

        return HttpResponse(json.dumps(ctx, indent=2),
                            mimetype='application/json')
Esempio n. 26
0
def deprecated_course_detail_view(request, course_pk):
    try:
        course = get_object_or_404(Course, pk=course_pk)
        request.course = course
        request.session[SESSION_KEY] = course
    except Course.DoesNotExist:
        return HttpResponseRedirect('/accounts/login/')

    logged_in_user = request.user
    classwork_owner = request.user  # Viewing your own work by default
    if 'username' in request.GET:
        user_name = request.GET['username']
        in_course_or_404(user_name, request.course)
        classwork_owner = get_object_or_404(User, username=user_name)

    qs = ExternalCollection.objects.filter(course=request.course)
    collections = qs.filter(uploader=False).order_by('title')
    uploader = qs.filter(uploader=True).first()

    owners = []
    if (request.course.is_member(logged_in_user)
            and (logged_in_user.is_staff
                 or logged_in_user.has_perm('assetmgr.can_upload_for'))):
        owners = UserResource().render_list(request, request.course.members)

    context = {
        'classwork_owner':
        classwork_owner,
        'information_title':
        course_information_title(course),
        'faculty_feed':
        Project.objects.faculty_compositions(course, logged_in_user),
        'is_faculty':
        cached_course_is_faculty(course, logged_in_user),
        'discussions':
        get_course_discussions(course),
        'msg':
        request.GET.get('msg', ''),
        'view':
        request.GET.get('view', ''),
        'collections':
        collections,
        'uploader':
        uploader,
        'can_upload':
        course_details.can_upload(request.user, request.course),
        'owners':
        owners
    }

    return context
Esempio n. 27
0
def your_projects(request, user_name):
    in_course_or_404(user_name, request.course)

    user = get_object_or_404(User, username=user_name)

    editable = user == request.user

    if request.method == "GET":
        projects = Project.get_user_projects(
            user, request.course).order_by('modified')
        if not editable:
            projects = [p for p in projects if p.visible(request)]

        try:
            initially_expanded_project = int(request.GET['show'])
        except:
            if len(projects):
                initially_expanded_project = projects[0].pk
            else:
                initially_expanded_project = None

        return {
            'projects': projects,
            'editable': editable,
            'space_owner': user,
            'initially_expanded_project': initially_expanded_project,
        }

    if request.method == "POST":
        if not editable:
            return HttpResponseForbidden("forbidden")

        title = request.POST.get('title', '') or "Untitled"
        project = Project(author=user, course=request.course, title=title)
        project.save()

        project.collaboration(request, sync_group=True)

        parent = request.POST.get("parent")
        if parent is not None:
            try:
                parent = Project.objects.get(pk=parent)
            except Project.DoesNotExist:
                parent = None
                return HttpResponseRedirect(project.get_workspace_url())

            parent_collab = parent.collaboration(request)
            if parent_collab.permission_to("add_child", request):
                parent_collab.append_child(project)

        return HttpResponseRedirect(project.get_workspace_url())
Esempio n. 28
0
def assets_by_course(request):
    """
    An ajax-only request to retrieve a course's projects,
    assignment responses and selections
    """
    if not request.user.is_staff:
        in_course_or_404(request.user.username, request.course)

    assets = Asset.objects \
        .filter(course=request.course) \
        .extra(select={'lower_title': 'lower(assetmgr_asset.title)'}) \
        .select_related().order_by('lower_title')

    return render_assets(request, None, assets)
Esempio n. 29
0
def assets_by_course(request):
    """
    An ajax-only request to retrieve a course's projects,
    assignment responses and selections
    """
    if not request.user.is_staff:
        in_course_or_404(request.user.username, request.course)

    assets = Asset.objects \
        .filter(course=request.course) \
        .extra(select={'lower_title': 'lower(assetmgr_asset.title)'}) \
        .select_related().order_by('lower_title')

    return render_assets(request, None, assets)
Esempio n. 30
0
def your_projects(request, user_name):
    in_course_or_404(user_name, request.course)
    
    user = get_object_or_404(User, username=user_name)

    editable = user==request.user

    if request.method == "GET":
        projects = Project.get_user_projects(user, request.course).order_by('modified')
        if not editable:
            projects = [p for p in projects if p.visible(request)]

        try:
            initially_expanded_project = int(request.GET['show'])
        except:
            if len(projects):
                initially_expanded_project = projects[0].pk
            else:
                initially_expanded_project = None
        
        return {
            'projects': projects,
            'editable': editable,
            'space_owner': user,
            'initially_expanded_project': initially_expanded_project,
            }

    if request.method == "POST":
        if not editable:
            return HttpResponseForbidden("forbidden")
        
        title = request.POST.get('title','') or "Untitled" 
        project = Project(author=user, course=request.course, title=title)
        project.save()

        project.collaboration(request, sync_group=True)

        parent = request.POST.get("parent")
        if parent is not None:
            try:
                parent = Project.objects.get(pk=parent)
            except Project.DoesNotExist:
                parent = None
                return HttpResponseRedirect(project.get_workspace_url())

            parent_collab = parent.collaboration(request)
            if parent_collab.permission_to("add_child", request):
                parent_collab.append_child(project)
                
        return HttpResponseRedirect(project.get_workspace_url())
Esempio n. 31
0
def asset_workspace(request, asset_id=None, annot_id=None):
    if not request.user.is_staff:
        in_course_or_404(request.user.username, request.course)

    if asset_id:
        try:
            asset = Asset.objects.get(pk=asset_id, course=request.course)
            asset.primary
        except Asset.DoesNotExist:
            return asset_switch_course(request, asset_id)
        except Source.DoesNotExist:
            response = direct_to_template(request, "500.html", {})
            response.status_code = 500
            return response

    data = {'space_owner': request.user.username,
            'asset_id': asset_id,
            'annotation_id': annot_id}

    if not request.is_ajax():
        return render_to_response('assetmgr/asset_workspace.html',
                                  data,
                                  context_instance=RequestContext(request))
    elif asset_id:
        # @todo - refactor this context out of the mix
        # ideally, the client would simply request the json
        context = detail_asset_json(request, asset)
    else:
        context = {'type': 'asset'}

    vocabulary = VocabularyResource().render_list(
        request, Vocabulary.objects.get_for_object(request.course))

    user_resource = UserResource()
    owners = user_resource.render_list(request, request.course.members)

    data['panels'] = [{'panel_state': 'open',
                       'panel_state_label': "Annotate Media",
                       'context': context,
                       'owners': owners,
                       'vocabulary': vocabulary,
                       'template': 'asset_workspace',
                       'current_asset': asset_id,
                       'current_annotation': annot_id,
                       'update_history': True,
                       'show_collection': True, }]

    return HttpResponse(simplejson.dumps(data, indent=2),
                        mimetype='application/json')
Esempio n. 32
0
def archive_add_or_remove(request):

    in_course_or_404(request.user.username, request.course)

    if 'remove' in request.POST.keys():
        title = request.POST.get('title')
        lst = Asset.objects.filter(title=title, course=request.course)
        for asset in lst:
            if asset.primary and asset.primary.is_archive():
                redirect = request.POST.get('redirect-url',
                                            reverse('class-manage-sources'))
                url = "%s?delsrc=%s" % (redirect, asset.title)
                asset.delete()
                return HttpResponseRedirect(url)
    else:
        return asset_create(request)
Esempio n. 33
0
def archive_add_or_remove(request):

    in_course_or_404(request.user.username, request.course)

    if 'remove' in request.POST.keys():
        title = request.POST.get('title')
        lst = Asset.objects.filter(title=title, course=request.course)
        for asset in lst:
            if asset.primary and asset.primary.is_archive():
                redirect = request.POST.get('redirect-url',
                                            reverse('class-manage-sources'))
                url = "%s?delsrc=%s" % (redirect, asset.title)
                asset.delete()
                return HttpResponseRedirect(url)
    else:
        return asset_create(request)
Esempio n. 34
0
def remove_record(request, user_name, asset_id):

    in_course_or_404(user_name, request.course)

    asset = get_object_or_404(Asset, pk=asset_id, course=request.course)
    user = get_object_or_404(User, username=user_name)

    if user != request.user:
        return HttpResponseForbidden("forbidden")

    annotations = asset.sherdnote_set.filter(author=user)

    if request.method == "DELETE":
        annotations.delete()
        return HttpResponseRedirect(
            reverse('your-space-records', args=[user_name]))
Esempio n. 35
0
def triple_homepage(request):
    if not request.course:
        return HttpResponseRedirect('/accounts/login/')

    logged_in_user = request.user
    classwork_owner = request.user  # Viewing your own work by default
    if 'username' in request.GET:
        user_name = request.GET['username']
        in_course_or_404(user_name, request.course)
        classwork_owner = get_object_or_404(User, username=user_name)

    course = request.course

    collections = ExternalCollection.objects.filter(
        course=request.course, uploader=False).order_by('title')
    uploader = ExternalCollection.objects.filter(course=request.course,
                                                 uploader=True).first()

    owners = []
    if (in_course(logged_in_user.username, request.course) and
        (logged_in_user.is_staff or
         logged_in_user.has_perm('assetmgr.can_upload_for'))):
        owners = UserResource().render_list(request, request.course.members)

    context = {
        'classwork_owner': classwork_owner,
        "information_title": course_information_title(course),
        'faculty_feed': Project.objects.faculty_compositions(course,
                                                             logged_in_user),
        'is_faculty': course.is_faculty(logged_in_user),
        'discussions': get_course_discussions(course),
        'msg': request.GET.get('msg', ''),
        'view': request.GET.get('view', ''),
        'collections': collections,
        'uploader': uploader,
        'can_upload': course_details.can_upload(request.user, request.course),
        'owners': owners
    }

    if getattr(settings, 'DJANGOSHERD_FLICKR_APIKEY', None):
        # MUST only contain string values for now!!
        # (see templates/assetmgr/bookmarklet.js to see why or fix)
        context['bookmarklet_vars'] = {
            'flickr_apikey': settings.DJANGOSHERD_FLICKR_APIKEY
        }

    return context
Esempio n. 36
0
def triple_homepage(request):
    c = request.course

    if not c:
        return HttpResponseRedirect('/accounts/login/')

    user = request.user
    if request.GET.has_key('username'):
        user_name = request.GET['username']
        in_course_or_404(user_name, c)
        user = get_object_or_404(User, username=user_name)
    elif user.is_staff and request.GET.has_key('as'):
        user = get_object_or_404(User, username=request.GET['as'])
        
    #bad language, we should change this to user_of_assets or something
    space_viewer = request.user 
    if request.GET.has_key('as') and request.user.is_staff:
        space_viewer = get_object_or_404(User, username=request.GET['as'])   

    user_records = {
       'space_viewer': space_viewer,
       'space_owner' : user,
       "help_homepage_instructor_column": UserSetting.get_setting(user, "help_homepage_instructor_column", True),
       "help_homepage_classwork_column":  UserSetting.get_setting(user, "help_homepage_classwork_column", True)
    }
    prof_feed = get_prof_feed(c, request)
    discussions = get_discussions(c)

    full_prof_list = []
    for lis in (prof_feed['projects'], prof_feed['assignments'], discussions,):
        full_prof_list.extend(lis)
    full_prof_list.sort(lambda a, b:cmp(a.title.lower(), b.title.lower()))
    
    user_records.update(
        {'faculty_feed':prof_feed,
         'instructor_full_feed':full_prof_list,
         'is_faculty':c.is_faculty(user),
         'display':{'instructor':prof_feed['show'],
                    'course': (len(prof_feed['tags']) < 5)
                    },
         'discussions' : discussions,
         'msg': request.GET.get('msg', ''),
         'tag': request.GET.get('tag', ''),
         'view': request.GET.get('view', '')
         })
    return user_records
Esempio n. 37
0
def remove_record(request, user_name, asset_id):

    in_course_or_404(user_name, request.course)

    asset = get_object_or_404(Asset, pk=asset_id,
                              course=request.course)
    user = get_object_or_404(User, username=user_name)

    if user != request.user:
        return HttpResponseForbidden("forbidden")

    annotations = asset.sherdnote_set.filter(author=user)

    if request.method == "DELETE":
        annotations.delete()
        return HttpResponseRedirect(
            reverse('your-space-records', args=[user_name]))
def asset_workspace(request, asset_id=None, annot_id=None):
    if not request.user.is_staff:
        in_course_or_404(request.user.username, request.course)

    try:
        if asset_id:
            asset = Asset.objects.get(pk=asset_id, course=request.course)
    except Asset.DoesNotExist:
        asset = Asset.objects.get(pk=asset_id)
        in_course_or_404(request.user.username, asset.course)

        # the user is logged into the wrong class?
        rv = {}
        rv['switch_to'] = asset.course
        rv['switch_from'] = request.course
        rv['redirect'] = reverse('asset-view', args=[asset_id])
        return render_to_response('assetmgr/asset_not_found.html',
                                  rv,
                                  context_instance=RequestContext(request))

    data = {'space_owner': request.user.username,
            'asset_id': asset_id,
            'annotation_id': annot_id}

    if not request.is_ajax():
        return render_to_response('assetmgr/asset_workspace.html',
                                  data,
                                  context_instance=RequestContext(request))
    else:
        if asset_id:
            asset_workspace_context = detail_asset_json(
                request, asset_id, {'include_annotations': True})
        else:
            asset_workspace_context = {'type': 'asset'}

        data['panels'] = [{'panel_state': 'open',
                           'panel_state_label': "Annotate Media",
                           'context': asset_workspace_context,
                           'template': 'asset_workspace',
                           'current_asset': asset_id,
                           'current_annotation': annot_id,
                           'update_history': True,
                           'show_collection': True, }]

        return HttpResponse(simplejson.dumps(data, indent=2),
                            mimetype='application/json')
Esempio n. 39
0
def annotations_collection_fragment(request,username):
    space_viewer = in_course_or_404(username, request.course)
    assets = annotated_by(Asset.objects.filter(course=request.course),
                          space_viewer)
    return {
        'space_viewer':space_viewer,
        'assets':assets,
        }
Esempio n. 40
0
def asset_references(request, asset_id):
    if not request.user.is_staff:
        in_course_or_404(request.user.username, request.course)

    try:
        the_json = {}
        asset = Asset.objects.get(pk=asset_id, course=request.course)

        filters = {'assets': [asset.id], 'counts': True}
        the_json['tags'] = TagResource(request.course).filter(request, filters)

        the_json['vocabulary'] = []
        for vocab in Vocabulary.objects.get_for_object(request.course):
            filters['vocabulary'] = vocab.id
            concepts = TermRelationshipResource(request.course).filter(
                request, filters)
            if len(concepts):
                the_json['vocabulary'].append({
                    'display_name': vocab.display_name,
                    'term_set': concepts
                })

        # DiscussionIndex is misleading. Objects returned are
        # projects & discussions title, object_pk, content_type, modified
        collaboration_items = DiscussionIndex.with_permission(
            request,
            DiscussionIndex.objects.filter(asset=asset).order_by('-modified'))

        the_json['references'] = [{
            'id':
            obj.collaboration.object_pk,
            'title':
            obj.collaboration.title,
            'type':
            obj.get_type_label(),
            'url':
            obj.get_absolute_url(),
            'modified':
            obj.modified.strftime("%m/%d/%y %I:%M %p")
        } for obj in collaboration_items]

        return HttpResponse(simplejson.dumps(the_json, indent=2),
                            mimetype='application/json')
    except Asset.DoesNotExist:
        return asset_switch_course(request, asset_id)
Esempio n. 41
0
def triple_homepage(request):
    c = request.course

    if not c:
        return HttpResponseRedirect('/accounts/login/')

    user = request.user
    if request.GET.has_key('username'):
        user_name = request.GET['username']
        in_course_or_404(user_name, c)
        user = get_object_or_404(User, username=user_name)
    elif user.is_staff and request.GET.has_key('as'):
        user = get_object_or_404(User, username=request.GET['as'])

    #bad language, we should change this to user_of_assets or something
    space_viewer = request.user
    if request.GET.has_key('as') and request.user.is_staff:
        space_viewer = get_object_or_404(User, username=request.GET['as'])

    user_records = {'space_viewer': space_viewer, 'space_owner': user}
    prof_feed = get_prof_feed(c, request)
    discussions = get_discussions(c)

    full_prof_list = []
    for lis in (
            prof_feed['projects'],
            prof_feed['assignments'],
            discussions,
    ):
        full_prof_list.extend(lis)
    full_prof_list.sort(lambda a, b: cmp(a.title.lower(), b.title.lower()))

    user_records.update({
        'faculty_feed': prof_feed,
        'instructor_full_feed': full_prof_list,
        'is_faculty': c.is_faculty(user),
        'display': {
            'instructor': prof_feed['show'],
            'course': (len(prof_feed['tags']) < 5)
        },
        'discussions': discussions,
        'msg': request.GET.get('msg', '')
    })
    return user_records
def your_projects(request, record_owner_name):
    """
    An ajax-only request to retrieve a specified user's projects,
    assignment responses and selections
    """
    if not request.is_ajax():
        raise Http404()

    course = request.course
    in_course_or_404(record_owner_name, course)

    logged_in_user = request.user
    is_faculty = course.is_faculty(logged_in_user)
    record_owner = get_object_or_404(User, username=record_owner_name)
    viewing_own_work = record_owner == logged_in_user

    # Record Owner's Visible Work,
    # sorted by modified date & feedback (if applicable)
    projects = Project.objects.visible_by_course_and_user(request,
                                                          course,
                                                          record_owner)

    # Show unresponded assignments if viewing self & self is a student
    assignments = []
    if not is_faculty and viewing_own_work:
        assignments = Project.objects.unresponded_assignments(request,
                                                              logged_in_user)

    # Assemble the context
    user_rez = UserResource()
    course_rez = CourseSummaryResource()
    data = {
        'assignments': homepage_assignment_json(assignments, is_faculty),
        'projects': homepage_project_json(request, projects, viewing_own_work),
        'space_viewer': user_rez.render_one(request, logged_in_user),
        'space_owner': user_rez.render_one(request, record_owner),
        'editable': viewing_own_work,
        'course': course_rez.render_one(request, course),
        'compositions': len(projects) > 0 or len(assignments) > 0,
        'is_faculty': is_faculty}

    json_stream = simplejson.dumps(data, indent=2)
    return HttpResponse(json_stream, mimetype='application/json')
Esempio n. 43
0
def assets_by_user(request, record_owner_name):
    """
    An ajax-only request to retrieve a specified user's assets
    Example:
        /asset/json/user/sld2131/
    """
    course = request.course
    if (request.user.is_staff and request.user.username == record_owner_name
            and not in_course(request.user.username, request.course)):
        return assets_by_course(request)

    in_course_or_404(record_owner_name, course)
    record_owner = get_object_or_404(User, username=record_owner_name)

    assets = Asset.objects.annotated_by(course,
                                        record_owner,
                                        include_archives=True)

    return render_assets(request, record_owner, assets)
Esempio n. 44
0
def view_project(request, project_id):
    project = get_object_or_404(Project, pk=project_id,
                                course=request.course)
    space_owner = in_course_or_404(project.author.username, request.course)

    if not project.collaboration(request).permission_to('edit',request):
        #LEGACY: try again for legacy projects
        if not project.collaboration(request, sync_group=True).permission_to('edit',request):
            return HttpResponseRedirect(project.get_absolute_url())

    if request.method == "GET":
        if request.META.get('HTTP_ACCEPT','').find('json') >=0:
            return project_json(request, project)
        return project_workspace(request, space_owner, project)

    if request.method == "DELETE":
        project.delete()
        return HttpResponseRedirect(
            reverse('your-records', args=[request.user.username]))

    if request.method == "POST":
        projectform = ProjectForm(request, instance=project,data=request.POST)
        if projectform.is_valid():
            if "Preview" == request.POST.get('submit',None):
                #doesn't send project.author, and other non-exposed fields
                mock_project = projectform.cleaned_data.copy()
                mock_project['attribution_list'] = mock_project['participants']
                mock_project['assignment'] = projectform.instance.assignment()
                mock_project['id'] = project_id
                return project_preview(request, space_owner, mock_project, 
                                       is_participant=True, preview_num=request.GET.get('preview',1))
            
            #legacy and for optimizing queries
            projectform.instance.submitted = (request.POST.get('publish',None) != 'PrivateEditorsAreOwners')
            
            #this changes for version-tracking purposes
            projectform.instance.author = request.user
            projectform.save()

            projectform.instance.collaboration(request, sync_group=True)

            if request.META.get('HTTP_ACCEPT','').find('json') >=0:
                v_num = projectform.instance.get_latest_version()
                return HttpResponse(simplejson.dumps(
                        {'status':'success',
                         'revision':{
                                'id':v_num,
                                'url':reverse('project_version_preview',args=[project_id, v_num]),
                                'public_url':projectform.instance.public_url(),
                                }
                         }, indent=2),
                                    mimetype='application/json')

        redirect_to = '.'
        return HttpResponseRedirect(redirect_to)
Esempio n. 45
0
def asset_references(request, asset_id):
    if not request.user.is_staff:
        in_course_or_404(request.user.username, request.course)

    try:
        the_json = {}
        asset = Asset.objects.get(pk=asset_id, course=request.course)

        filters = {
            'assets': [asset.id],
            'counts': True
        }
        the_json['tags'] = TagResource(request.course).filter(request, filters)

        the_json['vocabulary'] = []
        for vocab in Vocabulary.objects.get_for_object(request.course):
            filters['vocabulary'] = vocab.id
            concepts = TermRelationshipResource(request.course).filter(request,
                                                                       filters)
            if len(concepts):
                the_json['vocabulary'].append(
                    {'display_name': vocab.display_name,
                     'term_set': concepts})

        # DiscussionIndex is misleading. Objects returned are
        # projects & discussions title, object_pk, content_type, modified
        collaboration_items = DiscussionIndex.with_permission(
            request,
            DiscussionIndex.objects.filter(asset=asset).order_by('-modified'))

        the_json['references'] = [{
            'id': obj.collaboration.object_pk,
            'title': obj.collaboration.title,
            'type': obj.get_type_label(),
            'url': obj.get_absolute_url(),
            'modified': obj.modified.strftime("%m/%d/%y %I:%M %p")}
            for obj in collaboration_items]

        return HttpResponse(simplejson.dumps(the_json, indent=2),
                            mimetype='application/json')
    except Asset.DoesNotExist:
        return asset_switch_course(request, asset_id)
Esempio n. 46
0
def assets_by_user(request, record_owner_name):
    """
    An ajax-only request to retrieve a specified user's assets
    Example:
        /asset/json/user/sld2131/
    """
    course = request.course
    if (request.user.is_staff and
        request.user.username == record_owner_name and
            not in_course(request.user.username, request.course)):
        return assets_by_course(request)

    in_course_or_404(record_owner_name, course)
    record_owner = get_object_or_404(User, username=record_owner_name)

    assets = Asset.objects.annotated_by(course,
                                        record_owner,
                                        include_archives=True)

    return render_assets(request, record_owner, assets)
Esempio n. 47
0
def your_projects(request, record_owner_name):
    """
    An ajax-only request to retrieve a specified user's projects,
    assignment responses and selections
    """
    course = request.course
    in_course_or_404(record_owner_name, course)

    logged_in_user = request.user
    is_faculty = course.is_faculty(logged_in_user)
    record_owner = get_object_or_404(User, username=record_owner_name)
    viewing_own_work = record_owner == logged_in_user

    # Record Owner's Visible Work,
    # sorted by modified date & feedback (if applicable)
    projects = Project.objects.visible_by_course_and_user(request,
                                                          course,
                                                          record_owner)

    # Show unresponded assignments if viewing self & self is a student
    assignments = []
    if not is_faculty and viewing_own_work:
        assignments = Project.objects.unresponded_assignments(request,
                                                              logged_in_user)

    # Assemble the context
    user_rez = UserResource()
    course_rez = CourseSummaryResource()
    data = {
        'assignments': homepage_assignment_json(assignments, is_faculty),
        'projects': homepage_project_json(request, projects, viewing_own_work),
        'space_viewer': user_rez.render_one(request, logged_in_user),
        'space_owner': user_rez.render_one(request, record_owner),
        'editable': viewing_own_work,
        'course': course_rez.render_one(request, course),
        'compositions': len(projects) > 0 or len(assignments) > 0,
        'is_faculty': is_faculty}

    json_stream = simplejson.dumps(data, indent=2)
    return HttpResponse(json_stream, mimetype='application/json')
Esempio n. 48
0
def project_create(request):
    if request.method != "POST":
        return HttpResponseForbidden("forbidden")

    user = request.user
    course = request.course 
    in_course_or_404(user, course)
    is_faculty = course.is_faculty(user),
    
    project = Project(author=user, course=course, title="Untitled")
    project.save()

    project.collaboration(request, sync_group=True)

    parent = request.POST.get("parent")
    if parent is not None:
        try:
            parent = Project.objects.get(pk=parent)
            
            parent_collab = parent.collaboration(request)
            if parent_collab.permission_to("add_child", request):
                parent_collab.append_child(project)

        except Project.DoesNotExist:
            parent = None
            # @todo -- an error has occurred
            
    if not request.is_ajax():
        return HttpResponseRedirect(project.get_absolute_url())
    else: 
        project_context = project_json(request, project, project.can_edit(request))    
        project_context['editing'] = True
        
        data = { 'panel_state': 'open', 
                 'template': 'project',
                 'context': project_context 
        }
                
        return HttpResponse(simplejson.dumps(data, indent=2), mimetype='application/json')
Esempio n. 49
0
def course_detail_view(request):
    if not request.course:
        return HttpResponseRedirect('/accounts/login/')

    logged_in_user = request.user
    classwork_owner = request.user  # Viewing your own work by default
    if 'username' in request.GET:
        user_name = request.GET['username']
        in_course_or_404(user_name, request.course)
        classwork_owner = get_object_or_404(User, username=user_name)

    course = request.course

    qs = ExternalCollection.objects.filter(course=request.course)
    collections = qs.filter(uploader=False).order_by('title')
    uploader = qs.filter(uploader=True).first()

    owners = []
    if (request.course.is_member(logged_in_user) and
        (logged_in_user.is_staff or
         logged_in_user.has_perm('assetmgr.can_upload_for'))):
        owners = UserResource().render_list(request, request.course.members)

    context = {
        'classwork_owner': classwork_owner,
        'information_title': course_information_title(course),
        'faculty_feed': Project.objects.faculty_compositions(course,
                                                             logged_in_user),
        'is_faculty': cached_course_is_faculty(course, logged_in_user),
        'discussions': get_course_discussions(course),
        'msg': request.GET.get('msg', ''),
        'view': request.GET.get('view', ''),
        'collections': collections,
        'uploader': uploader,
        'can_upload': course_details.can_upload(request.user, request.course),
        'owners': owners
    }

    return context
Esempio n. 50
0
def project_create(request):
    user = request.user
    course = request.course
    in_course_or_404(user, course)

    project = Project(author=user, course=course, title="Untitled")
    project.save()

    project.collaboration(request, sync_group=True)

    parent = request.POST.get("parent")
    if parent is not None:
        try:
            parent = Project.objects.get(pk=parent)

            parent_collab = parent.collaboration(request)
            if parent_collab.permission_to("add_child", request):
                parent_collab.append_child(project)

        except Project.DoesNotExist:
            parent = None
            # @todo -- an error has occurred

    if not request.is_ajax():
        return HttpResponseRedirect(project.get_absolute_url())
    else:
        project_context = composition_project_json(request,
                                                   project,
                                                   project.can_edit(request))
        project_context['editing'] = True

        data = {'panel_state': 'open',
                'template': 'project',
                'context': project_context}

        return HttpResponse(simplejson.dumps(data, indent=2),
                            mimetype='application/json')
Esempio n. 51
0
    def get(self, request):
        ures = UserResource()
        course_rez = CourseResource()
        pres = ProjectResource(editable=self.viewing_own_records,
                               record_viewer=self.record_viewer,
                               is_viewer_faculty=self.is_viewer_faculty)
        assignments = []

        ctx = {
            'space_viewer': ures.render_one(request, self.record_viewer),
            'editable': self.viewing_own_records,
            'course': course_rez.render_one(request, request.course),
            'is_faculty': self.is_viewer_faculty
        }

        if (self.record_owner):
            in_course_or_404(self.record_owner.username, request.course)

            projects = Project.objects.visible_by_course_and_user(
                request, request.course, self.record_owner,
                self.viewing_faculty_records)

            # Show unresponded assignments if viewing self & self is a student
            if not self.is_viewer_faculty and self.viewing_own_records:
                assignments = Project.objects.unresponded_assignments(
                    request, self.record_viewer)

            ctx['space_owner'] = ures.render_one(request, self.record_owner)
            ctx['assignments'] = pres.render_assignments(request, assignments)
        else:
            projects = Project.objects.visible_by_course(
                request, request.course)

        ctx['projects'] = pres.render_projects(request, projects)
        ctx['compositions'] = len(projects) > 0 or len(assignments) > 0

        return self.render_to_json_response(ctx)
Esempio n. 52
0
def all_projects(request):
    """
    An ajax-only request to retrieve a course's projects,
    assignment responses and selections
    """
    if not request.user.is_staff:
        in_course_or_404(request.user.username, request.course)

    course = request.course
    logged_in_user = request.user

    projects = Project.objects.visible_by_course(request, course)

    # Assemble the context
    user_rez = UserResource()
    course_rez = CourseSummaryResource()
    data = {'projects': homepage_project_json(request, projects, False),
            'space_viewer': user_rez.render_one(request, logged_in_user),
            'course': course_rez.render_one(request, course),
            'compositions': len(projects) > 0,
            'is_faculty': course.is_faculty(logged_in_user)}

    json_stream = simplejson.dumps(data, indent=2)
    return HttpResponse(json_stream, mimetype='application/json')
Esempio n. 53
0
def annotations_collection_fragment(request,username=None):
    """username is WAY overloaded
     username='******' : just give me the selection menu
     username=None : give me all assets for the class
     username=<username> : all username assets
    """
    rv = {'space_viewer':request.user,
          'space_owner':False, #indicates we want the whole class (None is no one)
          'page_in_edit_mode': request.GET.has_key('edit_mode'),
          }
    if username != 'none':
        if username \
                and (request.user.username != username or request.course.is_true_member(request.user)):
            rv['space_owner'] = in_course_or_404(username, request.course)
            #assets = annotated_by(Asset.objects.filter(course=request.course),
            #                      space_owner)
            note_query = rv['space_owner'].sherdnote_set.filter(asset__course=request.course)
        else:
            #assets = Asset.objects.filter(course=request.course)
            note_query = SherdNote.objects.filter(asset__course=request.course)

        rv['tags'] =  calculate_cloud(Tag.objects.usage_for_queryset(note_query, counts=True))

        #all_tags.sort(lambda a,b:cmp(a.name.lower(),b.name.lower()))
        #all_tags = calculate_cloud(all_tags)
    
        filter_by = ('tag','modified')

        for fil in filter_by:
            filter_value = request.GET.get(fil)
            if filter_value:
                s_filter = getattr(SherdNote.objects,'%s_filter'%fil)
                note_query = s_filter(filter_value,note_query)

        #until asset_table.html can work off the notes objects instead of the assets list
        rv['assets'] = Asset.objects.filter(id__in = note_query.values_list('asset',flat=True))

        rv['active_filters'] = get_active_filters(request)
        rv['dates'] = (('today','today'),
                       ('yesterday','yesterday'),
                       ('lastweek','within the last week'),
                       )
    
    return rv
Esempio n. 54
0
def view_project(request, project_id):
    project = get_object_or_404(Project, pk=project_id, course=request.course)
    space_owner = in_course_or_404(project.author.username, request.course)

    if not project.collaboration(request).permission_to('edit', request):
        #LEGACY: try again for legacy projects
        if not project.collaboration(request, sync_group=True).permission_to(
                'edit', request):
            return HttpResponseRedirect(project.get_absolute_url())

    if request.method == "GET":
        if request.META.get('HTTP_ACCEPT', '').find('json') >= 0:
            return project_json(request, project)
        return project_workspace(request, space_owner, project)

    if request.method == "DELETE":
        project.delete()
        return HttpResponseRedirect(
            reverse('your-space-records', args=[request.user.username]))

    if request.method == "POST":
        projectform = ProjectForm(request, instance=project, data=request.POST)
        if projectform.is_valid():
            if "Preview" == request.POST.get('submit', None):
                #doesn't send project.author, and other non-exposed fields
                mock_project = projectform.cleaned_data.copy()
                mock_project['attribution_list'] = mock_project['participants']
                mock_project['assignment'] = projectform.instance.assignment()
                mock_project['id'] = project_id
                return project_preview(request,
                                       space_owner,
                                       mock_project,
                                       is_participant=True,
                                       preview_num=request.GET.get(
                                           'preview', 1))

            #legacy and for optimizing queries
            projectform.instance.submitted = (request.POST.get(
                'publish', None) != 'PrivateEditorsAreOwners')

            #this changes for version-tracking purposes
            projectform.instance.author = request.user
            projectform.save()

            projectform.instance.collaboration(request, sync_group=True)

            if request.META.get('HTTP_ACCEPT', '').find('json') >= 0:
                v_num = projectform.instance.get_latest_version()
                return HttpResponse(simplejson.dumps(
                    {
                        'status': 'success',
                        'revision': {
                            'id':
                            v_num,
                            'url':
                            reverse('project_version_preview',
                                    args=[project_id, v_num]),
                            'public_url':
                            projectform.instance.public_url(),
                        }
                    },
                    indent=2),
                                    mimetype='application/json')

        redirect_to = '.'
        return HttpResponseRedirect(redirect_to)
Esempio n. 55
0
def your_space(request, user_name):

    in_course_or_404(user_name, request.course)

    return HttpResponseRedirect(reverse('your-space-records',
                                        args=[user_name]))
Esempio n. 56
0
def your_records(request, user_name):
    c = request.course
    in_course_or_404(user_name, c)
    user = get_object_or_404(User, username=user_name)

    return get_records(user, c, request)
Esempio n. 57
0
def triple_homepage(request):
    if not request.course:
        return HttpResponseRedirect('/accounts/login/')

    logged_in_user = request.user
    classwork_owner = request.user  # Viewing your own work by default
    if 'username' in request.GET:
        user_name = request.GET['username']
        in_course_or_404(user_name, request.course)
        classwork_owner = get_object_or_404(User, username=user_name)

    course = request.course

    archives = []
    upload_archive = None
    for item in course.asset_set.archives().order_by('title'):
        archive = item.sources['archive']
        thumb = item.sources.get('thumb', None)
        description = item.metadata().get('description', '')
        uploader = item.metadata().get('upload', 0)

        archive_context = {
            "id": item.id,
            "title": item.title,
            "thumb": (None if not thumb else {"id": thumb.id,
                                              "url": thumb.url}),
            "archive": {"id": archive.id, "url": archive.url},
            "metadata": (description[0]
                         if hasattr(description, 'append') else description)
        }

        if (uploader[0] if hasattr(uploader, 'append') else uploader):
            upload_archive = archive_context
        else:
            archives.append(archive_context)

    archives.sort(key=operator.itemgetter('title'))

    owners = []
    if (in_course(logged_in_user.username, request.course) and
        (logged_in_user.is_staff or
         logged_in_user.has_perm('assetmgr.can_upload_for'))):
        owners = UserResource().render_list(request, request.course.members)

    context = {
        'classwork_owner': classwork_owner,
        'help_homepage_instructor_column': False,
        'help_homepage_classwork_column': False,
        'faculty_feed': get_prof_feed(course, request),
        'is_faculty': course.is_faculty(logged_in_user),
        'discussions': get_course_discussions(course),
        'msg': request.GET.get('msg', ''),
        'view': request.GET.get('view', ''),
        'archives': archives,
        'upload_archive': upload_archive,
        'can_upload': course_details.can_upload(request.user, request.course),
        'show_tour': should_show_tour(request, course, logged_in_user),
        'owners': owners
    }

    if getattr(settings, 'DJANGOSHERD_FLICKR_APIKEY', None):
        # MUST only contain string values for now!!
        # (see templates/assetmgr/bookmarklet.js to see why or fix)
        context['bookmarklet_vars'] = {
            'flickr_apikey': settings.DJANGOSHERD_FLICKR_APIKEY
        }

    return context
Esempio n. 58
0
    def dispatch(self, *args, **kwargs):
        if not self.request.user.is_staff:
            in_course_or_404(self.request.user.username, self.request.course)

        return super(LoggedInCourseMixin, self).dispatch(*args, **kwargs)