Esempio n. 1
0
def piece_create(request, *args, **kwargs):
    form = validate_dynamic_piece_form(request, PieceForm(request.POST))
    if not form.is_valid():
        # Form errors are rendered for user on the front end.
        errors = {f: [e.get_json_data()[0]['message']] for f, e in form.errors.items()}
        errors = json.dumps({'errors': errors})
        return HttpResponse(content=errors, content_type="application/json", status=status.HTTP_400_BAD_REQUEST)

    clean = Cleanup()
    clean_form = form.cleaned_data
    new_piece = Piece(title=clean_form['title'],
                      creator=request.user,
                      created=datetime.datetime.now(pytz.utc),
                      updated=datetime.datetime.now(pytz.utc))
    clean.list.append({"object": new_piece, "isNew": True})
    try:
        new_piece.save(ignore_solr=True)
    except:
        clean.cleanup()
        raise

    object_list = []
    for key in clean_form:
        object_list.append({'id': key, 'value': clean_form[key]})
    handle_related_models(object_list, new_piece, clean,
                          user=request.user, birth_date=clean_form['composer_birth_date'],
                          death_date=clean_form['composer_death_date'])

    new_piece.save()
    handle_dynamic_file_table(request, new_piece, clean)
    rebuild_suggester_dicts.delay()
    data = json.dumps({'success': True, 'id': new_piece.id,
                       'url': "/piece/{0}".format(new_piece.id)})
    return HttpResponse(data, content_type="application/json", status=status.HTTP_201_CREATED)
Esempio n. 2
0
def piece_update(request, *args, **kwargs):
    # Update a piece based on a dict of changes in request.POST['changes']
    patch_data = request.data
    form = validate_dynamic_piece_form(request, PieceForm(patch_data))
    if not form.is_valid():
        # Form errors are rendered for user on the front end. Collection
        # validation errors are ignored, as these cannot be modified from
        # the update page.
        if form.errors.get("collections"):
            del form.errors["collections"]
        if form.errors:
            errors = {f: [e.get_json_data()[0]["message"]] for f, e in form.errors.items()}
            errors = json.dumps({"errors": errors})
            return HttpResponse(content=errors, content_type="application/json", status=status.HTTP_400_BAD_REQUEST)

    clean = Cleanup()
    piece = Piece.objects.get(id=int(kwargs["pk"]))
    change = json.loads(patch_data["changes"])

    """
    Creating new movements must occur before old movements are deleted,
    as the attachment of files depends on the ordering and numbering
    of movements in the piece's present state. See comment in
    handle_dynamic_file_table() for more information.
    """
    handle_dynamic_file_table(request, piece, clean)

    modify_movements = [x for x in change["modify"] if x["type"] == "M"]
    if modify_movements:
        for item in modify_movements:
            mov = Movement.objects.filter(id=item["id"])
            if not mov:
                break
            mov = mov[0]
            if item.get("tags"):
                tag_list = abstract_model_factory(item["tags"], "Tag", clean)
                mov.tags.clear()
                for x in tag_list:
                    mov.tags.add(x)
            if item.get("instruments_voices"):
                ins_list = abstract_model_factory(item["instruments_voices"], "InstrumentVoice", clean)
                mov.instruments_voices.clear()
                for x in ins_list:
                    mov.instruments_voices.add(x)
            if item.get("comment"):
                mov.comment = item["comment"]
            if item.get("number_of_voices"):
                mov.number_of_voices = int(item["number_of_voices"])
            if item.get("vocalization"):
                mov.vocalization = item["vocalization"]
            if item.get("title"):
                mov.title = item["title"]

            mov.save()

    movement_positions = [x for x in change["modify"] if x["type"] == "M" and x.get("position")]
    movement_positions.extend([x for x in change["add"] if x["type"] == "M" and x.get("position")])
    if movement_positions:
        movements = piece.movements.all()
        for item in movement_positions:
            if item.get("id"):
                mov = movements.get(id=item["id"])
                mov.position = item["position"]
                mov.save()
            elif item.get("name"):
                mov = movements.get(title=item["name"])
                mov.position = item["position"]
                mov.save()

    modify_atts = [x for x in change["modify"] if x["type"] == "A"]
    if modify_atts:
        for item in modify_atts:
            att = Attachment.objects.filter(pk=item["id"])
            if not att:
                break
            att = att[0]
            if item.get("parent"):
                if item.get("newParentTitle") == "Attach to Piece":
                    att.movements.clear()
                    att.pieces.clear()
                    att.pieces.add(piece)
                    att.save()
                else:
                    mov = piece.movements.filter(title=item["newParentTitle"])
                    if not mov:
                        break
                    mov = mov[0]
                    att.movements.clear()
                    att.pieces.clear()
                    att.movements.add(mov)
                    att.save()
            if item.get("source"):
                att.source = item.get("source")
                att.save()

    modify_piece = [x for x in change["modify"] if x["type"] == "F"]
    if modify_piece:
        # Can use the same function as the piece-create here.
        handle_related_models(modify_piece, piece, clean)

    delete_attachments = [x for x in change["delete"] if x["type"] == "A"]
    if delete_attachments:
        for item in delete_attachments:
            att = Attachment.objects.filter(pk=item["id"])[0]
            if att:
                att.delete()

    delete_movements = [x for x in change["delete"] if x["type"] == "M"]
    if delete_movements:
        for item in delete_movements:
            mov = Movement.objects.filter(pk=item["id"])[0]
            if mov:
                mov.delete()

    piece.save()
    rebuild_suggester_dicts.delay()
    data = json.dumps({"success": True, "id": piece.id, "url": "/piece/{0}".format(piece.id)})
    return HttpResponse(data, content_type="json")