Esempio n. 1
0
def add_youtube_doc(req, ensemble_id):
    import base.models as M
    from apiclient.discovery import build
    from urlparse import urlparse, parse_qs
    import re
    re_iso8601 = re.compile("PT(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?")
    youtube = build("youtube", "v3", developerKey=settings.GOOGLE_DEVELOPER_KEY)
    user       = UR.getUserInfo(req, False)
    if user is None:
        redirect_url = "/login?next=%s" % (req.META.get("PATH_INFO","/"),)
        return HttpResponseRedirect(redirect_url)
    if not auth.canEditEnsemble(user.id, ensemble_id):
        return HttpResponseRedirect("/notallowed")
    addform = forms.YoutubeForm()
    if req.method == 'POST':
        addform = forms.YoutubeForm(req.POST)
        if addform.is_valid():
            source = M.Source()
            source.numpages = 1
            source.w = 0
            source.h = 0
            source.rotation = 0
            source.version = 0
            source.type = 2
            source.submittedby=user
            source.save()
            ownership = M.Ownership()
            ownership.source = source
            ownership.ensemble_id = ensemble_id
            ownership.save()
            info = M.YoutubeInfo()
            info.source = source
            url = addform.cleaned_data['url']
            result = urlparse(url)
            key = None
            try:
                # old format ,e.g. http://www.youtube.com/watch?v=Z3EAE9F2Qpo
                key = parse_qs(result.query)["v"][0]
            except KeyError:
                # new format, e.g. http://youtu.be/Z3EAE9F2Qpo
                key = result.path[1:]
            key = key.strip()
            info.key = key
            info.save();
            ginfo = youtube.videos().list(part="id,contentDetails,snippet", id=key).execute()
            source.title = ginfo["items"][0]["snippet"]["title"]
            matches_dict = re_iso8601.match(ginfo["items"][0]["contentDetails"]["duration"]).groupdict()
            numsecs = 0
            if matches_dict["hours"] is not None:
                numsecs += int(matches_dict["hours"])*3600
            if matches_dict["minutes"] is not None:
                numsecs += int(matches_dict["minutes"])*60
            if matches_dict["seconds"] is not None:
                numsecs += int(matches_dict["seconds"])
            source.numpages = numsecs #we use 1/100 sec precision.
            source.save();
            #addform.cleaned_data['title']

            return HttpResponseRedirect("/")
    return render_to_response("web/add_youtube_doc.html", {"form": addform})
Esempio n. 2
0
def add_html5video_doc(req, ensemble_id):
    import base.models as M
    user       = UR.getUserInfo(req, False)
    if user is None:
        redirect_url = "/login?next=%s" % (req.META.get("PATH_INFO","/"),)
        return HttpResponseRedirect(redirect_url)
    if not auth.canEditEnsemble(user.id, ensemble_id):
        return HttpResponseRedirect("/notallowed")
    addform = forms.Html5Form()
    if req.method == 'POST':
        addform = forms.Html5Form(req.POST)
        if addform.is_valid():
            source = M.Source()
            source.numpages = 1
            source.w = 0
            source.h = 0
            source.rotation = 0
            source.version = 0
            source.type = 3
            source.submittedby=user
            source.title = addform.cleaned_data['title']
            source.save()
            ownership = M.Ownership()
            ownership.source = source
            ownership.ensemble_id = ensemble_id
            ownership.save()
            info = M.HTML5Info()
            info.source = source
            # trailing slash is sometimes added by server redirects
            # but person specifying upload url may not realize this
            # so remove trailing slash as well as hash part of the URL
            info.url = addform.cleaned_data['url'].partition("#")[0].rstrip("/") 
            info.save();
            return HttpResponseRedirect("/")
    return render_to_response("web/add_html5video_doc.html", {"form": addform})
Esempio n. 3
0
def add_html_doc(req, ensemble_id): 
    import base.models as M
    user       = UR.getUserInfo(req, False)
    if user is None:
        redirect_url = "/login?next=%s" % (req.META.get("PATH_INFO","/"),)
        return HttpResponseRedirect(redirect_url)
    if not auth.canEditEnsemble(user.id, ensemble_id):
        return HttpResponseRedirect("/notallowed")
    addform = forms.Html5Form()
    if req.method == 'POST':
        addform = forms.Html5Form(req.POST)
        if addform.is_valid():             
            source = M.Source()
            source.numpages = 1
            source.w = 0
            source.h = 0
            source.rotation = 0
            source.version = 0
            source.type = 4
            source.submittedby=user
            source.title = addform.cleaned_data['title']
            source.save()            
            ownership = M.Ownership()
            ownership.source = source
            ownership.ensemble_id = ensemble_id
            ownership.save()
            info = M.HTML5Info()
            info.source = source
            info.url = addform.cleaned_data['url']
            info.save();
            return HttpResponseRedirect("/")         
    return render_to_response("web/add_html_doc.html", {"form": addform})
Esempio n. 4
0
def add_html_doc(req, ensemble_id):
    import base.models as M
    user = UR.getUserInfo(req, False)
    if user is None:
        redirect_url = "/login?next=%s" % (req.META.get("PATH_INFO", "/"), )
        return HttpResponseRedirect(redirect_url)
    if not auth.canEditEnsemble(user.id, ensemble_id):
        return HttpResponseRedirect("/notallowed")
    addform = forms.Html5Form()
    if req.method == 'POST':
        addform = forms.Html5Form(req.POST)
        if addform.is_valid():
            source = M.Source()
            source.numpages = 1
            source.w = 0
            source.h = 0
            source.rotation = 0
            source.version = 0
            source.type = 4
            source.submittedby = user
            source.title = addform.cleaned_data['title']
            source.save()
            ownership = M.Ownership()
            ownership.source = source
            ownership.ensemble_id = ensemble_id
            ownership.save()
            info = M.HTML5Info()
            info.source = source
            info.url = addform.cleaned_data['url']
            info.save()
            return HttpResponseRedirect("/")
    return render_to_response("web/add_html_doc.html", {"form": addform})
Esempio n. 5
0
def properties_ensemble_users(req, id):
    user = UR.getUserInfo(req)
    if user is None:
        return HttpResponseRedirect("/login?next=%s" %
                                    (req.META.get("PATH_INFO", "/"), ))
    if not auth.canEditEnsemble(user.id, id):
        return HttpResponseRedirect("/notallowed")
    ensemble = M.Ensemble.objects.get(pk=id)
    memberships = M.Membership.objects.filter(ensemble=ensemble)
    real_memberships = memberships.filter(
        user__in=M.User.objects.filter(valid=True), deleted=False)
    if "action" in req.GET and "membership_id" in req.GET:
        if req.GET["action"] == "delete":
            m = real_memberships.filter(id=req.GET["membership_id"])
            if len(m):
                m = m[0]
                m.deleted = True
                m.save()
                return HttpResponseRedirect(req.path)
        elif req.GET["action"] == "undelete":
            deleted_memberships = memberships.filter(
                user__in=M.User.objects.filter(valid=True), deleted=True)
            m = deleted_memberships.filter(id=req.GET["membership_id"])
            if len(m):
                m = m[0]
                m.deleted = False
                m.save()
                return HttpResponseRedirect(req.path)
        elif req.GET["action"] == "admin":
            m = real_memberships.filter(id=req.GET["membership_id"])
            if len(m):
                m = m[0]
                m.admin = True
                m.save()
                return HttpResponseRedirect(req.path)
        elif req.GET["action"] == "unadmin":
            m = real_memberships.filter(id=req.GET["membership_id"])
            if len(m):
                m = m[0]
                m.admin = False
                m.save()
                return HttpResponseRedirect(req.path)
        elif req.GET["action"] == "setsection":
            m = real_memberships.filter(id=req.GET["membership_id"])
            if req.POST["section_id"] == "None":
                s = None
            else:
                sections = M.Section.objects.filter(ensemble=ensemble)
                s = sections.filter(id=req.POST["section_id"])[0]
            if len(m):
                m = m[0]
                m.section = s
                m.save()
                return HttpResponseRedirect(req.path)

    return render_to_response("web/properties_ensemble_users.html")
Esempio n. 6
0
def properties_ensemble_users(req, id):
    user       = UR.getUserInfo(req)
    if user is None:
        return HttpResponseRedirect("/login?next=%s" % (req.META.get("PATH_INFO","/"),))
    if not auth.canEditEnsemble(user.id, id):
        return HttpResponseRedirect("/notallowed")
    ensemble = M.Ensemble.objects.get(pk=id)
    sections = M.Section.objects.filter(ensemble=ensemble)
    memberships = M.Membership.objects.filter(ensemble=ensemble)
    pendingconfirmations = memberships.filter(user__in=M.User.objects.filter(valid=False), deleted=False)
    real_memberships = memberships.filter(user__in=M.User.objects.filter(valid=True), deleted=False)
    deleted_memberships =  memberships.filter(user__in=M.User.objects.filter(valid=True), deleted=True)
    pendinginvites = M.Invite.objects.filter(ensemble=ensemble).exclude(user__id__in=real_memberships.values("user_id"))
    if "action" in req.GET and "membership_id" in req.GET:
        if req.GET["action"] == "delete":
            m = real_memberships.filter(id=req.GET["membership_id"])
            if len(m):
                m = m[0]
                m.deleted = True
                m.save()
                return HttpResponseRedirect(req.path)
        elif req.GET["action"] == "undelete":
            m = deleted_memberships.filter(id=req.GET["membership_id"])
            if len(m):
                m = m[0]
                m.deleted = False
                m.save()
                return HttpResponseRedirect(req.path)
        elif req.GET["action"] == "admin":
            m = real_memberships.filter(id=req.GET["membership_id"])
            if len(m):
                m = m[0]
                m.admin = True
                m.save()
                return HttpResponseRedirect(req.path)
        elif req.GET["action"] == "unadmin":
            m = real_memberships.filter(id=req.GET["membership_id"])
            if len(m):
                m = m[0]
                m.admin = False
                m.save()
                return HttpResponseRedirect(req.path)
        elif req.GET["action"] == "setsection":
            m = real_memberships.filter(id=req.GET["membership_id"])
            if req.POST["section_id"] == "None":
		s = None
            else:
                s = sections.filter(id=req.POST["section_id"])[0]
            if len(m):
                m = m[0]
                m.section = s
                m.save()
                return HttpResponseRedirect(req.path)

    return render_to_response("web/properties_ensemble_users.html", {"ensemble": ensemble, "memberships": real_memberships, "pendinginvites": pendinginvites, "pendingconfirmations": pendingconfirmations, "deleted_memberships": deleted_memberships, "sections": sections})
Esempio n. 7
0
def properties_ensemble_sections(req, id):
    user = UR.getUserInfo(req)
    if user is None:
        return HttpResponseRedirect("/login?next=%s" %
                                    (req.META.get("PATH_INFO", "/"), ))
    if not auth.canEditEnsemble(user.id, id):
        return HttpResponseRedirect("/notallowed")
    ensemble = M.Ensemble.objects.get(pk=id)
    sections = M.Section.objects.filter(ensemble=ensemble)
    err = ""
    if "action" in req.GET:
        if req.GET["action"] == "create" and "name" in req.POST:
            if M.Section.objects.filter(ensemble=ensemble,
                                        name=req.POST["name"]).exists():
                err = "Could not create section: a section with the same name already exists."
            else:
                s = M.Section(name=req.POST["name"], ensemble=ensemble)
                s.save()
                return HttpResponseRedirect(req.path)
        elif req.GET["action"] == "delete" and "section_id" in req.GET:
            s = sections.filter(id=req.GET["section_id"])
            if len(s):
                s = s[0]
                if (len(M.Membership.objects.filter(section=s)) > 0):
                    err = "The section you are trying to delete is not empty."
                else:
                    s.delete()
                    return HttpResponseRedirect(req.path)
            else:
                err = "Cannot find section"
        elif req.GET[
                "action"] == "reassign" and "membership_id" in req.POST and "section_id" in req.POST:
            if req.POST["section_id"] == "None":
                s = [None]
            else:
                s = sections.filter(id=req.POST["section_id"])
            if len(s):
                s = s[0]
                m = M.Membership.objects.filter(id=req.POST["membership_id"])
                if len(m):
                    m = m[0]
                    m.section = s
                    m.save()
                else:
                    err = "Cannot find member"
            else:
                err = "Cannot find section"
        else:
            err = "Unrecognized Command"
    if err or "json" in req.GET:
        return HttpResponse(json.dumps({"error_message": err}),
                            content_type="application/json")
    else:
        return render_to_response("web/properties_ensemble_sections.html")
Esempio n. 8
0
def add_youtube_doc(req, ensemble_id): 
    import base.models as M
    from apiclient.discovery import build
    from urlparse import urlparse, parse_qs
    import re
    re_iso8601 = re.compile("PT(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?")
    youtube = build("youtube", "v3", developerKey=settings.GOOGLE_DEVELOPER_KEY)
    user       = UR.getUserInfo(req, False)
    if user is None:
        redirect_url = "/login?next=%s" % (req.META.get("PATH_INFO","/"),)
        return HttpResponseRedirect(redirect_url)
    if not auth.canEditEnsemble(user.id, ensemble_id):
        return HttpResponseRedirect("/notallowed")
    addform = forms.YoutubeForm()
    if req.method == 'POST':
        addform = forms.YoutubeForm(req.POST)
        if addform.is_valid():             
            source = M.Source()
            source.numpages = 1
            source.w = 0
            source.h = 0
            source.rotation = 0
            source.version = 0
            source.type = 2
            source.submittedby=user
            source.save()            
            ownership = M.Ownership()
            ownership.source = source
            ownership.ensemble_id = ensemble_id
            ownership.save()
            info = M.YoutubeInfo()
            info.source = source
            url = addform.cleaned_data['url']
            result = urlparse(url)
            key = parse_qs(result.query)["v"][0]
            info.key = key
            info.save();
            ginfo = youtube.videos().list(part="id,contentDetails,snippet", id=key).execute()
            source.title = ginfo["items"][0]["snippet"]["title"]
            matches_dict = re_iso8601.match(ginfo["items"][0]["contentDetails"]["duration"]).groupdict()
            numsecs = 0
            if matches_dict["hours"] is not None: 
                numsecs += int(matches_dict["hours"])*3600
            if matches_dict["minutes"] is not None: 
                numsecs += int(matches_dict["minutes"])*60
            if matches_dict["seconds"] is not None: 
                numsecs += int(matches_dict["seconds"])
            source.numpages = numsecs #we use 1/100 sec precision. 
            source.save();
            #addform.cleaned_data['title']

            return HttpResponseRedirect("/")         
    return render_to_response("web/add_youtube_doc.html", {"form": addform})
Esempio n. 9
0
def properties_ensemble_users(req, id):
    user       = UR.getUserInfo(req)
    if user is None: 
        return HttpResponseRedirect("/login?next=%s" % (req.META.get("PATH_INFO","/"),))
    if not auth.canEditEnsemble(user.id, id):
        return HttpResponseRedirect("/notallowed")
    ensemble = M.Ensemble.objects.get(pk=id)
    memberships = M.Membership.objects.filter(ensemble=ensemble)
    pendingconfirmations = memberships.filter(user__in=M.User.objects.filter(valid=False), deleted=False)
    real_memberships = memberships.filter(user__in=M.User.objects.filter(valid=True), deleted=False)    
    pendinginvites = M.Invite.objects.filter(ensemble=ensemble).exclude(user__id__in=real_memberships.values("user_id"))    
    return render_to_response("web/properties_ensemble_users.html", {"ensemble": ensemble, "memberships": real_memberships, "pendinginvites": pendinginvites, "pendingconfirmations": pendingconfirmations})
Esempio n. 10
0
def properties_ensemble_sections(req, id):
    user       = UR.getUserInfo(req)
    if user is None:
        return HttpResponseRedirect("/login?next=%s" % (req.META.get("PATH_INFO","/"),))
    if not auth.canEditEnsemble(user.id, id):
        return HttpResponseRedirect("/notallowed")
    ensemble = M.Ensemble.objects.get(pk=id)
    sections = M.Section.objects.filter(ensemble=ensemble)
    all_students = M.Membership.objects.filter(ensemble=ensemble).filter(guest=False)
    students = {}
    for s in sections:
        students[s] = all_students.filter(section=s)
    no_section = all_students.filter(section=None)
    err = ""
    if "action" in req.GET:
        if req.GET["action"] == "create" and "name" in req.POST:
            if M.Section.objects.filter(ensemble=ensemble, name=req.POST["name"]).exists():
                err = "Could not create section: a section with the same name already exists."
            else:
                s = M.Section(name=req.POST["name"], ensemble=ensemble)
                s.save()
        elif req.GET["action"] == "delete" and "section_id" in req.GET:
            s = sections.filter(id=req.GET["section_id"])
            if len(s):
                s = s[0]
                if ( len(M.Membership.objects.filter(section=s)) > 0):
                    err = "The section you are trying to delete is not empty."
                else:
                    s.delete()
                    return HttpResponseRedirect(req.path)
            else:
                err = "Cannot find section"
        elif req.GET["action"] == "reassign" and "membership_id" in req.POST and "section_id" in req.POST:
            if req.POST["section_id"] == "None":
                s = [None]
            else:
                s = sections.filter(id=req.POST["section_id"]);
            if len(s):
                s = s[0];
                m = M.Membership.objects.filter(id=req.POST["membership_id"])
                if len(m):
                    m = m[0]
                    m.section = s
                    m.save()
                else:
                  err = "Cannot find member"
            else:
                err = "Cannot find section"
        else:
           err = "Unrecognized Command"
    if "json" in req.GET:
        return HttpResponse(json.dumps({"error_message": err}), content_type="application/json")
    return render_to_response("web/properties_ensemble_sections.html", {"ensemble": ensemble, "sections": sections, "students": students, "no_section": no_section, "error_message": err })
Esempio n. 11
0
def properties_ensemble_users(req, id):
    user       = UR.getUserInfo(req)
    if user is None: 
        return HttpResponseRedirect("/login?next=%s" % (req.META.get("PATH_INFO","/"),))
    if not auth.canEditEnsemble(user.id, id):
        return HttpResponseRedirect("/notallowed")
    ensemble = M.Ensemble.objects.get(pk=id)
    memberships = M.Membership.objects.filter(ensemble=ensemble)
    pendingconfirmations = memberships.filter(user__in=M.User.objects.filter(valid=False), deleted=False)
    real_memberships = memberships.filter(user__in=M.User.objects.filter(valid=True), deleted=False)    
    pendinginvites = M.Invite.objects.filter(ensemble=ensemble).exclude(user__id__in=real_memberships.values("user_id"))    
    return render_to_response("web/properties_ensemble_users.html", {"ensemble": ensemble, "memberships": real_memberships, "pendinginvites": pendinginvites, "pendingconfirmations": pendingconfirmations})
Esempio n. 12
0
def properties_ensemble(req, id):
    user       = UR.getUserInfo(req)
    if user is None:
        return HttpResponseRedirect("/login?next=%s" % (req.META.get("PATH_INFO","/"),))
    if not auth.canEditEnsemble(user.id, id):
        return HttpResponseRedirect("/notallowed")
    ensemble = M.Ensemble.objects.get(pk=id)
    ensemble_form = None
    if req.method=="POST":
        ensemble_form = forms.EnsembleForm(req.POST, instance=ensemble)
        if ensemble_form.is_valid():
            ensemble_form.save()
            return HttpResponseRedirect('/')
    else:
        return render_to_response("web/properties_ensemble.html")
Esempio n. 13
0
def properties_ensemble(req, id):
    user       = UR.getUserInfo(req)
    if user is None: 
        return HttpResponseRedirect("/login?next=%s" % (req.META.get("PATH_INFO","/"),))
    if not auth.canEditEnsemble(user.id, id):
        return HttpResponseRedirect("/notallowed")
    ensemble = M.Ensemble.objects.get(pk=id)
    ensemble_form = None
    if req.method=="POST": 
        ensemble_form = forms.EnsembleForm(req.POST, instance=ensemble)  
        if ensemble_form.is_valid(): 
            ensemble_form.save()   
            return HttpResponseRedirect('/')   
    else: 
        ensemble_form = forms.EnsembleForm(instance=ensemble)
    return render_to_response("web/properties_ensemble.html", {"form": ensemble_form, "conf_url":  "%s://%s/subscribe?key=%s" %(settings.PROTOCOL, settings.NB_SERVERNAME, ensemble.invitekey)})
Esempio n. 14
0
def properties_ensemble(req, id):
    user = UR.getUserInfo(req)
    if user is None:
        return HttpResponseRedirect("/login?next=%s" %
                                    (req.META.get("PATH_INFO", "/"), ))
    if not auth.canEditEnsemble(user.id, id):
        return HttpResponseRedirect("/notallowed")
    ensemble = M.Ensemble.objects.get(pk=id)
    ensemble_form = None
    if req.method == "POST":
        ensemble_form = forms.EnsembleForm(req.POST, instance=ensemble)
        if ensemble_form.is_valid():
            ensemble_form.save()
            return HttpResponseRedirect('/')
    else:
        return render_to_response("web/properties_ensemble.html")
Esempio n. 15
0
def properties_ensemble(req, id):
    user       = UR.getUserInfo(req)
    if user is None: 
        return HttpResponseRedirect("/login?next=%s" % (req.META.get("PATH_INFO","/"),))
    if not auth.canEditEnsemble(user.id, id):
        return HttpResponseRedirect("/notallowed")
    ensemble = M.Ensemble.objects.get(pk=id)
    ensemble_form = None
    if req.method=="POST": 
        ensemble_form = forms.EnsembleForm(req.POST, instance=ensemble)  
        if ensemble_form.is_valid(): 
            ensemble_form.save()   
            return HttpResponseRedirect('/admin')   
    else: 
        ensemble_form = forms.EnsembleForm(instance=ensemble)
    return render_to_response("web/properties_ensemble.html", {"form": ensemble_form, "conf_url":  "%s://%s/subscribe?key=%s" %(settings.PROTOCOL, settings.NB_SERVERNAME, ensemble.invitekey)})
Esempio n. 16
0
def add_html_doc(req, ensemble_id):
    import base.models as M
    user = UR.getUserInfo(req, False)
    if user is None:
        redirect_url = "/login?next=%s" % (req.META.get("PATH_INFO", "/"), )
        return HttpResponseRedirect(redirect_url)
    if not auth.canEditEnsemble(user.id, ensemble_id):
        return HttpResponseRedirect("/notallowed")
    addform = forms.Html5Form()
    if req.method == 'POST':
        addform = forms.Html5Form(req.POST)
        if addform.is_valid():
            source = M.Source()
            source.numpages = 1
            source.w = 0
            source.h = 0
            source.rotation = 0
            source.version = 0
            source.type = 4
            source.submittedby = user
            source.title = addform.cleaned_data['title']
            source.save()
            ownership = M.Ownership()
            ownership.source = source
            ownership.ensemble_id = ensemble_id
            ownership.save()
            info = M.HTML5Info()
            info.source = source
            # trailing slash is sometimes added by server redirects
            # but person specifying upload url may not realize this
            # so remove trailing slash as well as hash part of the URL
            info.url = addform.cleaned_data['url'].partition("#")[0].rstrip(
                "/")
            info.save()
            return HttpResponseRedirect("/")
    return render_to_response("web/add_html_doc.html", {"form": addform})
Esempio n. 17
0
def properties_ensemble_sections(req, id):
    user = UR.getUserInfo(req)
    if user is None:
        return HttpResponseRedirect("/login?next=%s" % (req.META.get("PATH_INFO","/"),))
    if not auth.canEditEnsemble(user.id, id):
        return HttpResponseRedirect("/notallowed")
    ensemble = M.Ensemble.objects.get(pk=id)
    sections = M.Section.objects.filter(ensemble=ensemble)
    err = ""
    if "action" in req.GET:
        if req.GET["action"] == "create" and "name" in req.POST:
            if M.Section.objects.filter(ensemble=ensemble, name=req.POST["name"]).exists():
                err = "Could not create section \"%s\" because it already exists." % req.POST["name"]
            else:
                s = M.Section(name=req.POST["name"], ensemble=ensemble)
                s.save()
                return HttpResponseRedirect(req.path)
        elif req.GET["action"] == "delete" and "section_id" in req.GET:
            s = sections.filter(id=req.GET["section_id"])
            if len(s):
                s = s[0]
                if ( len(M.Membership.objects.filter(section=s)) > 0):
                    err = "The section you are trying to delete is not empty."
                else:
                    s.delete()
                    return HttpResponseRedirect(req.path)
            else:
                err = "Cannot find section"
        elif req.GET["action"] == "reassign" and "membership_id" in req.POST and "section_id" in req.POST:
            if req.POST["section_id"] == "None":
                s = [None]
            else:
                s = sections.filter(id=req.POST["section_id"]);
            if len(s):
                s = s[0];
                m = M.Membership.objects.filter(id=req.POST["membership_id"])
                if len(m):
                    m = m[0]
                    m.section = s
                    m.save()
                else:
                  err = "Cannot find member"
            else:
                err = "Cannot find section"
        elif req.GET["action"] == "reassign_many":
            json_data = json.loads(req.body)
            new_sections = set(json_data["new_sections"])

            # Check that none of the new_sections already exist
            old_sections = set([s.name for s in M.Section.objects.filter(ensemble=ensemble).all()])
            sections_intersection = old_sections.intersection(new_sections)
            if sections_intersection:
                err = "Could not create the following sections because they already exists: " + \
                      ", ".join(sections_intersection)
                return HttpResponse(json.dumps({"error_message": err}), content_type="application/json")

            # Check that all section names in updated_sections are valid i.e. either an existing section
            # or one of the new_sections.
            all_sections = old_sections.union(new_sections)
            updated_sections = json_data["updated_sections"]
            updated_sections_names = set([r["section"] for r in updated_sections])
            invalid_section_names = updated_sections_names.difference(all_sections)
            if invalid_section_names:
                # Under normal circumstances the code should not get here because the UI should have ensured that all
                # new sections are part of the new_sections field in the json data sent to the server.
                err = "Could not update records because students cannot be added to these sections which do not exist: " + \
                      ", ".join(invalid_section_names)
                return HttpResponse(json.dumps({"error_message": err}), content_type="application/json")

            # Check that all user IDs in updated_sections are valid
            invalid_user_id = []
            for r in updated_sections:
                if not len(M.Membership.objects.filter(id=r["user_id"])):
                    invalid_user_id.append(r["user_id"])
            if invalid_user_id:
                err = "Could not update records because the following user IDs are invalid: " + \
                      ", ".join(invalid_user_id)
                return HttpResponse(json.dumps({"error_message": err}), content_type="application/json")

            # Create new sections
            for section_name in new_sections:
                section_object = M.Section(name=section_name, ensemble=ensemble)
                section_object.save()

            # Update students' sections
            for r in updated_sections:
                m = M.Membership.objects.filter(id=r["user_id"])[0]
                s = sections.filter(name=r["section"], ensemble=ensemble)[0];
                m.section = s
                m.save()
        else:
           err = "Unrecognized Command"
    if err or "json" in req.GET:
        return HttpResponse(json.dumps({"error_message": err}), content_type="application/json")
    else:
        return render_to_response("web/properties_ensemble_sections.html")
Esempio n. 18
0
def properties_ensemble_sections(req, id):
    user = UR.getUserInfo(req)
    if user is None:
        return HttpResponseRedirect("/login?next=%s" %
                                    (req.META.get("PATH_INFO", "/"), ))
    if not auth.canEditEnsemble(user.id, id):
        return HttpResponseRedirect("/notallowed")
    ensemble = M.Ensemble.objects.get(pk=id)
    sections = M.Section.objects.filter(ensemble=ensemble)
    err = ""
    if "action" in req.GET:
        if req.GET["action"] == "create" and "name" in req.POST:
            if M.Section.objects.filter(ensemble=ensemble,
                                        name=req.POST["name"]).exists():
                err = "Could not create section \"%s\" because it already exists." % req.POST[
                    "name"]
            else:
                s = M.Section(name=req.POST["name"], ensemble=ensemble)
                s.save()
                return HttpResponseRedirect(req.path)
        elif req.GET["action"] == "delete" and "section_id" in req.GET:
            s = sections.filter(id=req.GET["section_id"])
            if len(s):
                s = s[0]
                if (len(M.Membership.objects.filter(section=s)) > 0):
                    err = "The section you are trying to delete is not empty."
                else:
                    s.delete()
                    return HttpResponseRedirect(req.path)
            else:
                err = "Cannot find section"
        elif req.GET[
                "action"] == "reassign" and "membership_id" in req.POST and "section_id" in req.POST:
            if req.POST["section_id"] == "None":
                s = [None]
            else:
                s = sections.filter(id=req.POST["section_id"])
            if len(s):
                s = s[0]
                m = M.Membership.objects.filter(id=req.POST["membership_id"])
                if len(m):
                    m = m[0]
                    m.section = s
                    m.save()
                else:
                    err = "Cannot find member"
            else:
                err = "Cannot find section"
        elif req.GET["action"] == "reassign_many":
            json_data = json.loads(req.body)
            new_sections = set(json_data["new_sections"])

            # Check that none of the new_sections already exist
            old_sections = set([
                s.name
                for s in M.Section.objects.filter(ensemble=ensemble).all()
            ])
            sections_intersection = old_sections.intersection(new_sections)
            if sections_intersection:
                err = "Could not create the following sections because they already exists: " + \
                      ", ".join(sections_intersection)
                return HttpResponse(json.dumps({"error_message": err}),
                                    content_type="application/json")

            # Check that all section names in updated_sections are valid i.e. either an existing section
            # or one of the new_sections.
            all_sections = old_sections.union(new_sections)
            updated_sections = json_data["updated_sections"]
            updated_sections_names = set(
                [r["section"] for r in updated_sections])
            invalid_section_names = updated_sections_names.difference(
                all_sections)
            if invalid_section_names:
                # Under normal circumstances the code should not get here because the UI should have ensured that all
                # new sections are part of the new_sections field in the json data sent to the server.
                err = "Could not update records because students cannot be added to these sections which do not exist: " + \
                      ", ".join(invalid_section_names)
                return HttpResponse(json.dumps({"error_message": err}),
                                    content_type="application/json")

            # Check that all user IDs in updated_sections are valid
            invalid_user_id = []
            for r in updated_sections:
                if not len(M.Membership.objects.filter(id=r["user_id"])):
                    invalid_user_id.append(r["user_id"])
            if invalid_user_id:
                err = "Could not update records because the following user IDs are invalid: " + \
                      ", ".join(invalid_user_id)
                return HttpResponse(json.dumps({"error_message": err}),
                                    content_type="application/json")

            # Create new sections
            for section_name in new_sections:
                section_object = M.Section(name=section_name,
                                           ensemble=ensemble)
                section_object.save()

            # Update students' sections
            for r in updated_sections:
                m = M.Membership.objects.filter(id=r["user_id"])[0]
                s = sections.filter(name=r["section"], ensemble=ensemble)[0]
                m.section = s
                m.save()
        else:
            err = "Unrecognized Command"
    if err or "json" in req.GET:
        return HttpResponse(json.dumps({"error_message": err}),
                            content_type="application/json")
    else:
        return render_to_response("web/properties_ensemble_sections.html")