예제 #1
0
def update_scenario_service(request, scenario_id):
    if request.method == 'POST':
        if scenario_id is not None:
            scenario = Scenario.objects.get(id=scenario_id)
            pd_user = PDUser.objects.get(user=request.user)
            if scenario.owner.id == pd_user.id:
                scenario.script = request.body
                scenario.script = scenario.script.replace('…', "...")
                scenario.script = scenario.script.replace('’', "'")
                scenario.script = scenario.script.replace('‘', "'")
                scenario.script = scenario.script.replace('”', '\\"')
                scenario.script = scenario.script.replace('“', '\\"')
                scen_json = json.loads(scenario.script)
                scenario.order = scen_json['order']
                scenario.type = scen_json['type']
                file_name = scenario.jsonUrl
                gitlab_result = gitlab_utility.update_file(gitlab_utility.get_project_name(), PDUser.branch_for_user(user=request.user),
                                           file_name, scenario.script, "text")
                if gitlab_result is False:
                    return HttpResponse("Gitlab save failed", status = 500)
                
                scenario.save()
                
                return HttpResponse(request.body)
            else:
                return HttpResponse("Unauthorized", status=401)
        else:
            return HttpResponse("Bad Request", status=400)
    else:
        return HttpResponse("Invalid Method", status=405)
예제 #2
0
def dump_component_definitions(request):
    components = {'components': []}
    sets = ComponentSet.objects.all()

    for set in sets:
        components['components'].append({"src": set.jsonRepresentation, "type": set.setType, "random": set.random})

    gitlab_utility.update_file(gitlab_utility.get_project_name(),
                               PDUser.branch_for_user(user=request.user),
                               "component-definitions.json",
                               json.dumps(components, sort_keys=True, indent=4, separators=(',', ': ')),
                               "text")
예제 #3
0
def dump_component_textures(request):
    comp_textures = Texture.objects.filter(type=Texture.CHARACTER_COMPONENT).all()
    assets = {'assets': []}

    for tex in comp_textures:
        d = tex.asDict()
        d.pop("imageUrl", None)
        d['type'] = 'texture'
        assets['assets'].append(d)

    gitlab_utility.update_file(gitlab_utility.get_project_name(),
                               PDUser.branch_for_user(user=request.user),
                               "component-textures.json",
                               json.dumps(assets, sort_keys=True, indent=4, separators=(',', ': ')),
                               "text")
예제 #4
0
def dump_scenarios(request):
    scenarios = []
    scenario_objs = Scenario.objects.all()

    for obj in scenario_objs:

        scenarios.append({
            'src': obj.jsonUrl,
            'order': obj.order,
            'type': obj.type
        })

    gitlab_utility.update_file(gitlab_utility.get_project_name(),
                           PDUser.branch_for_user(user=request.user),
                           "scenarios.json",
                           json.dumps(scenarios, sort_keys=True, indent=4, separators=(',', ': ')),
                           "text")
예제 #5
0
def create_scenario_view(request):
    if request.method == 'GET':
        return render(request, 'scenarioEditor/create/create_scenario.html/', {})
    elif request.method == 'POST':
        if 'scenario_name' in request.POST:
            pd_user = PDUser.objects.get(user=request.user)
            scenario = Scenario(name=str(request.POST['scenario_name']), owner=pd_user)
            file_name = "scenarios/" + scenario.name.replace(" ", "_") + ".json"
            scenario.script = '{"assets":[]}'
            scenario.jsonUrl = file_name
            gitlab_utility.create_file(gitlab_utility.get_project_name(), PDUser.branch_for_user(user=request.user),
                                       file_name, scenario.script, "text")
            scenario.save()
            dump_scenarios(request)
            return redirect(edit_scenario_view, scenario.id)
    else:
        # Return invalid method response
        return HttpResponse("Invalid Method", status=405)
예제 #6
0
def rename_scenario_service(request, scenario_id):
    if request.method == 'POST':
        payload = json.loads(request.body)
        if scenario_id is not None and 'name' in payload:
            scenario = Scenario.objects.get(id=scenario_id)
            pd_user = PDUser.objects.get(user=request.user)
            if scenario.owner.id == pd_user.id:
                old_file_name = scenario.jsonUrl
                scenario.name = payload['name']
                scenario.jsonUrl = "scenarios/" + scenario.name.replace(" ", "_") + ".json"
                gitlab_utility.delete_file(old_file_name, PDUser.branch_for_user(user=request.user))
                gitlab_utility.create_file(gitlab_utility.get_project_name(), PDUser.branch_for_user(user=request.user),
                                       scenario.jsonUrl, scenario.script, "text")
                scenario.save()
                dump_scenarios(request)
                return HttpResponse()
            else:
                return HttpResponse("Unauthorized", status=401)
        else:
            return HttpResponse("Bad Request", status=400)
    else:
        return HttpResponse("Invalid Method", status=405)
예제 #7
0
def post_process_component_set_service(request):
    if request.method == 'POST':
        in_data = json.loads(request.body)
        if 'id' in in_data:
            parent_set = ComponentSet.objects.get(pk=long(in_data['id']))
            if parent_set is not None:

                set_json_str = urllib2.urlopen(
                    gitlab_utility.get_project_url() + "/raw/" + PDUser.branch_for_user(
                        request.user) + "/" + parent_set.jsonRepresentation
                ).read()
                set_json_obj = json.loads(set_json_str)

                joints = set_json_obj["joints"]

                for charComp in parent_set.get_components():
                    tex = charComp.texture
                    if charComp.componentType.upper() == 'UPPER ARM' \
                            or charComp.componentType.upper() == 'LOWER JAW' \
                            or charComp.componentType.upper() == 'TORSO' \
                            or charComp.componentType.upper() == 'UPPER LEG' \
                            or charComp.componentType.upper() == 'PELVIS':
                        joints["texture"] = tex.id
                    elif charComp.componentType.upper() == 'LOWER ARM' \
                            or charComp.componentType.upper() == 'LOWER LEG' \
                            or charComp.componentType.upper() == 'UPPER JAW':
                        joints["components"][0]["texture"] = tex.id
                    elif charComp.componentType.upper() == 'HAND' \
                            or charComp.componentType.upper() == 'NOSE' \
                            or charComp.componentType.upper() == 'FOOT':
                        joints["components"][0]["components"][0]["texture"] = tex.id
                    elif charComp.componentType.upper() == 'LEFT EYE':
                        joints["components"][0]["components"][1]["texture"] = tex.id
                    elif charComp.componentType.upper() == 'RIGHT EYE':
                        joints["components"][0]["components"][2]["texture"] = tex.id
                    elif charComp.componentType.upper() == 'LEFT EYEBROW':
                        joints["components"][0]["components"][3]["texture"] = tex.id
                    elif charComp.componentType.upper() == 'RIGHT EYEBROW':
                        joints["components"][0]["components"][4]["texture"] = tex.id
                    elif charComp.componentType.upper() == 'RIGHT PUPIL':
                        joints["components"][0]["components"][2]['components'][0]["texture"] = tex.id
                    elif charComp.componentType.upper() == 'LEFT PUPIL':
                        joints["components"][0]["components"][1]['components'][0]["texture"] = tex.id

                    if 'textures' not in set_json_obj:
                        set_json_obj['textures'] = []

                    set_json_obj['textures'].append({
                        'id': tex.id,
                        'component': charComp.componentType
                    })

                url_comps = parent_set.jsonRepresentation.split("/")
                file_name = url_comps[len(url_comps) - 1]

                gitlab_utility.update_file(gitlab_utility.get_project_name(),
                                           PDUser.branch_for_user(user=request.user),
                                           "/components/definitions/" + file_name,
                                           json.dumps(set_json_obj, sort_keys=True, indent=4, separators=(',', ': ')),
                                           "text")

                comp_textures = Texture.objects.filter(type=Texture.CHARACTER_COMPONENT).all()
                assets = {'assets': []}

                for tex in comp_textures:
                    d = tex.asDict()
                    d.pop("imageUrl", None)
                    d['type'] = 'texture'
                    assets['assets'].append(d)

                gitlab_utility.update_file(gitlab_utility.get_project_name(),
                                           PDUser.branch_for_user(user=request.user),
                                           "component-textures.json",
                                           json.dumps(assets, sort_keys=True, indent=4, separators=(',', ': ')),
                                           "text")
                return HttpResponse('Success', status=200)
            else:
                return HttpResponse("Component set not found", status=404)
        else:
            return HttpResponse('id param is required', status=400)
    else:
        return HttpResponse("Invalid Method", status=405)
예제 #8
0
def upload_asset(request):
    if request.method == 'POST':
        form = AssetFileForm(request.POST, request.FILES)
        if form.is_valid():
            asset_type = form.cleaned_data["assetType"]
            asset_id = form.cleaned_data["assetId"]
            
            tex = Texture()

            additional_data = None

            try:
                additional_data = json.loads(form.cleaned_data["additionalData"])
            except:
                pass

            if asset_type == Asset.CHARACTER_COMPONENT:

                parent_set = ComponentSet.objects.get(pk=long(asset_id))

                t = additional_data["componentType"].replace(" ", "_")
                name = parent_set.name.replace(" ", "_") + "_" + t
                file_name = name + ".png"

                tex.name = "components/" + file_name

                char_comp = CharacterComponent()
                char_comp.componentType = additional_data["componentType"]
                char_comp.name = name.replace(" ", "_")

                file_name = "components/" + file_name
                tex.imageUrl = file_name

                gitlab_utility.create_file(gitlab_utility.get_project_name(),
                                           PDUser.branch_for_user(user=request.user),
                                           file_name,
                                           request.FILES['file'].read(),
                                           "base64")

                tex.type = Texture.CHARACTER_COMPONENT
                tex.save()

                char_comp.texture = tex

                char_comp.componentSet = parent_set

                char_comp.save()

            elif asset_type == Asset.ITEM:

                item_def = ItemDefinition.objects.get(id=long(asset_id))

                name = item_def.name.replace(" ", "_")
                file_name = name + ".png"

                tex.name = "items/" + file_name
                file_name = "items/" + file_name
                tex.imageUrl = file_name

                gitlab_utility.create_file(gitlab_utility.get_project_name(),
                                           PDUser.branch_for_user(user=request.user),
                                           file_name, request.FILES['file'].read(),
                                           "base64")
                tex.type = Texture.ITEM
                tex.save()
                item_def.texture = tex
                item_def.save()

                item_textures = Texture.objects.filter(type=Texture.ITEM).all()
                assets = {'assets': []}

                for tex in item_textures:
                    d = tex.asDict()
                    d.pop("imageUrl", None)
                    d['type'] = 'texture'
                    assets['assets'].append(d)

                gitlab_utility.update_file(gitlab_utility.get_project_name(),
                                           PDUser.branch_for_user(user=request.user),
                                           "item-textures.json",
                                           json.dumps(assets, sort_keys=True, indent=4, separators=(',', ': ')),
                                           "text")

            elif asset_type == Asset.MESH:
                pass
            return HttpResponse(status=200)

        else:
            return HttpResponse("Bad asset request - " + form.errors.as_json(), status=400)
    else:
        return HttpResponse("Invalid Method", status=405)
예제 #9
0
def component_set_service(request, component_set_id=None):
    if request.method == 'GET':
        try:
            if component_set_id is not None:
                obj = ComponentSet.objects.get(id=component_set_id)
                if obj is not None:
                    data = json.dumps(obj.asDict(), sort_keys=True, indent=4, separators=(',', ': '))
                    return HttpResponse(data, content_type='application/json')
            else:
                get_params = request.GET
                simple_query_items = dict()
                complex_query_items = []

                if 'setType' in get_params:
                    simple_query_items['setType__istartswith'] = get_params['setType']

                if 'name' in get_params:
                    simple_query_items['name__istartswith'] = get_params['name']

                sets = ComponentSet.objects.filter(*complex_query_items, **simple_query_items)

                tagResult = None

                # @TODO This logic should be achievable using a single query
                if 'tags' in get_params:
                    tags = get_params['tags'].split(",")
                    tagResult = Tag.objects.filter(value__in=tags, owner__in=sets)

                filteredSets = []

                if tagResult != None and 'tags' in get_params:
                    for tag in tagResult:
                        for set in sets.all():
                            if tag.owner.id == set.id and set not in filteredSets:
                                filteredSets.append(set)
                else:
                    filteredSets = sets.all()

                paginator = Paginator(filteredSets, 10)

                if 'page' in request.GET:
                    filteredSets = paginator.page(request.GET['page']).object_list

                if len(filteredSets) > 0:
                    cj = []
                    for c in filteredSets:
                        cj.append(c.asDict())
                    data = json.dumps(cj, sort_keys=True, indent=4, separators=(',', ': '))
                    return HttpResponse(data, content_type='application/json')
                else:
                    return HttpResponse("No objects found for query", status=404)
        except:
            return HttpResponse("Object could not be found", status=404)

    elif request.method == 'POST':
        try:
            in_data = json.loads(request.body)
            comp_set_form = ComponentSetForm(data=in_data)
            if comp_set_form.is_valid():
                
                if component_set_id is None:
                    same_name_obj_count = ComponentSet.objects.filter(name=comp_set_form.cleaned_data["name"], setType=comp_set_form.cleaned_data["setType"]).count()
                
                    if(same_name_obj_count != 0):
                        return HttpResponse("Component set with name " + comp_set_form.cleaned_data["name"] + " already exists", status=400)
                    
                    comp_set = ComponentSet()
                else:
                    try:
                        comp_set = ComponentSet.objects.get(id=long(component_set_id))
                    except:
                        return HttpResponse("Could not find component set for id " + str(component_set_id), status=404)

                comp_set.name = comp_set_form.cleaned_data["name"].replace(" ", "_")

                comp_set.description = comp_set_form.cleaned_data["description"]
                comp_set.random = comp_set_form.cleaned_data["random"]

                if component_set_id is None:
                    comp_set.setType = comp_set_form.cleaned_data["setType"]

                    joints_file_name = "components/definitions/" + comp_set_form.cleaned_data["name"].replace(" ", "_") + "_" + comp_set_form.cleaned_data["setType"] + ".json"

                    json_obj = json.loads(comp_set_form.cleaned_data["joints"])

                    gitlab_utility.create_file(gitlab_utility.get_project_name(),
                                               PDUser.branch_for_user(user=request.user),
                                               joints_file_name,
                                               json.dumps(json_obj, sort_keys=True, indent=4, separators=(',', ': ')),
                                               "text")

                    comp_set.jsonRepresentation = joints_file_name

                comp_set.save()

                tags = comp_set.getTags()

                ex_tag_vals = []

                for tag in tags:
                    ex_tag_vals.append(tag.value)

                for t in comp_set_form.cleaned_data["tags"]:
                    if t not in ex_tag_vals:
                        tag = Tag(value=t)
                        tag.owner = comp_set
                        tag.save()

                dump_component_definitions(request)

                return HttpResponse('{"status":"created", "id":' + str(comp_set.id) + '}',
                                    content_type='application/json')
            else:
                return HttpResponse("Invalid request data - " + comp_set_form.errors.as_json(), status=400)
        except:
            return HttpResponse("Bad post data - " + request.body, status=400)
    elif request.method == 'DELETE':
        if component_set_id is not None:
            set = ComponentSet.objects.get(id=component_set_id)
            components = set.get_components()

            branch = PDUser.branch_for_user(user=request.user)

            for comp in components:
                url = comp.texture.imageUrl
                gitlab_utility.delete_file(url, branch)
                comp.texture.delete()
                comp.delete()

            gitlab_utility.delete_file(set.jsonRepresentation, branch)
            set.delete()
            dump_component_definitions(request)
            dump_component_textures(request)
            return HttpResponse('Success')
    else:
        return HttpResponse("Invalid Method", status=405)