Commit dc1a5179 by Estók Dániel

New feature added: add more anchors for elements.

parent f4363207
from django.contrib import admin
from .models import (
Element,
ElementTemplate,
ElementConnection,
Service,
)
admin.site.register(Element)
admin.site.register(ElementTemplate)
admin.site.register(ElementConnection)
admin.site.register(Service)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Element',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('parameters', models.TextField()),
('displayId', models.TextField()),
('pos_x', models.PositiveSmallIntegerField()),
('pos_y', models.PositiveSmallIntegerField()),
],
),
migrations.CreateModel(
name='ElementConnection',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('source_endpoint', models.TextField()),
('target_endpoint', models.TextField()),
('parameters', models.TextField()),
('source', models.ForeignKey(related_name='source', to='setty.Element')),
('target', models.ForeignKey(related_name='target', to='setty.Element')),
],
),
migrations.CreateModel(
name='ElementTemplate',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=50)),
('logo', models.FileField(upload_to=b'')),
('parameters', models.TextField()),
('tags', taggit.managers.TaggableManager(to='taggit.Tag', through='taggit.TaggedItem', blank=True, help_text='A comma-separated list of tags.', verbose_name='tags')),
],
),
migrations.CreateModel(
name='Service',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.TextField(verbose_name=b'Name')),
('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='element',
name='parent',
field=models.ForeignKey(to='setty.ElementTemplate'),
),
migrations.AddField(
model_name='element',
name='workspace',
field=models.ForeignKey(to='setty.Service'),
),
]
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('setty', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='elementtemplate',
name='description',
field=models.TextField(default=datetime.datetime(2015, 6, 30, 7, 23, 44, 511713, tzinfo=utc)),
preserve_default=False,
),
]
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('setty', '0002_elementtemplate_description'),
]
operations = [
migrations.RenameField(
model_name='element',
old_name='displayId',
new_name='display_id',
),
migrations.RenameField(
model_name='element',
old_name='workspace',
new_name='service',
),
migrations.RemoveField(
model_name='element',
name='parent',
),
]
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('setty', '0003_auto_20150701_1621'),
]
operations = [
migrations.AddField(
model_name='service',
name='status',
field=models.CharField(default=datetime.datetime(2015, 8, 6, 8, 43, 54, 868047, tzinfo=utc), max_length=50),
preserve_default=False,
),
]
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('setty', '0004_service_status'),
]
operations = [
migrations.AddField(
model_name='elementtemplate',
name='compatibles',
field=models.ManyToManyField(related_name='compatibles_rel_+', to='setty.ElementTemplate'),
),
]
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('setty', '0005_elementtemplate_compatibles'),
]
operations = [
migrations.AlterField(
model_name='elementtemplate',
name='logo',
field=models.FileField(upload_to=b'/setty/static'),
),
]
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('setty', '0006_auto_20150827_1017'),
]
operations = [
migrations.AlterField(
model_name='elementtemplate',
name='logo',
field=models.FileField(upload_to=b'setty/'),
),
]
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import setty.storage
class Migration(migrations.Migration):
dependencies = [
('setty', '0007_auto_20150827_1021'),
]
operations = [
migrations.AlterField(
model_name='elementtemplate',
name='logo',
field=models.FileField(storage=setty.storage.OverwriteStorage(), upload_to=b'setty/'),
),
]
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('setty', '0008_auto_20150827_1044'),
]
operations = [
migrations.AddField(
model_name='element',
name='anchors',
field=models.PositiveSmallIntegerField(default=0),
preserve_default=False,
),
]
from django.db import models
from django.db.models import Model
from django.contrib.auth.models import User
from taggit.managers import TaggableManager
from django.utils.translation import ugettext_lazy as _
from storage import OverwriteStorage
class Service(Model):
user = models.ForeignKey(User)
name = models.TextField(verbose_name="Name")
status = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class ElementTemplate(Model):
name = models.CharField(max_length=50)
logo = models.FileField(upload_to='setty/', storage=OverwriteStorage())
description = models.TextField()
parameters = models.TextField()
compatibles = models.ManyToManyField('self')
tags = TaggableManager(blank=True, verbose_name=_("tags"))
def __unicode__(self):
return self.name
class Element(Model):
service = models.ForeignKey(Service, on_delete=models.CASCADE)
parameters = models.TextField()
display_id = models.TextField()
pos_x = models.PositiveSmallIntegerField()
pos_y = models.PositiveSmallIntegerField()
anchors = models.PositiveSmallIntegerField()
def __unicode__(self):
return self.service.name + ", id: " + self.display_id
class ElementConnection(Model):
target = models.ForeignKey(
Element,
related_name='target',
on_delete=models.CASCADE)
source = models.ForeignKey(
Element,
related_name='source',
on_delete=models.CASCADE)
source_endpoint = models.TextField()
target_endpoint = models.TextField()
parameters = models.TextField()
def __unicode__(self):
return self.target.service.name + ", " + str(self.id)
(function() {
/**
* Section to store base data.
*/
var elementConnections = [];
var elementIndex = 0;
var dragContainerScroll = 0;
var clickedConnection;
/***
* Function for updating connection array in whether an event was fired.
*/
updateConnections = function(conn, remove) {
if (!remove)
elementConnections.push(conn);
else {
var idx = -1;
for (var i = 0; i < elementConnections.length; i++) {
if (elementConnections[i] == conn) {
idx = i;
break;
}
}
if (idx != -1)
elementConnections.splice(idx, 1);
}
};
/***
* Function for checking duplicate connections.
*/
checkDuplicateConnection = function(connection) {
for (var i = 0; i < elementConnections.length; i++) {
if ((elementConnections[i].targetId == connection.targetId && elementConnections[i].sourceId == connection.sourceId) ||
(elementConnections[i].targetId == connection.sourceId && elementConnections[i].sourceId == connection.targetId)) {
addMessage("Duplicate connection.", "danger");
return false;
}
}
return true;
};
/***
* Function for checking element compatibility.
*/
checkCompatibility = function(sourceId, targetId) {
var validTargets = $("#" + sourceId).attr("type").split(',');
if (jQuery.inArray(targetId.split('_')[1], validTargets) == -1) {
addMessage("Elements are incompatible.", "danger");
return false;
}
return true;
};
/***
* Function for checking source and target element equality.
*/
checkSourceTargetEquality = function(connection) {
if (connection.targetId == connection.sourceId) {
addMessage("Source element is the same as target element.", "danger");
return false;
}
return true;
};
/***
* Function for determining anchor positions for an element.
*/
getAnchorCoordinate = function(anchor, anchorNum) {
var rate = anchor / anchorNum;
var x = Math.cos(2.0 * Math.PI * rate) / 2;
var y = Math.sin(2.0 * Math.PI * rate) / 2;
if (rate < 0.125) {
x = 0.5;
} else if (rate > 0.125 && rate < 0.375) {
y = -0.5;
} else if (rate > 0.375 && rate < 0.625) {
x = -0.5;
} else if (rate > 0.625 && rate < 0.875) {
y = 0.5;
} else if (rate > 0.875) {
x = -0.5;
} else {
x = Math.sqrt(2) * Math.cos(2 * Math.PI * rate) / 2;
y = Math.sqrt(2) * Math.sin(2 * Math.PI * rate) / 2;
}
return [y + 0.5, -x + 0.5];
};
/***
* Function for managing instantiation of new elements based on their templates.
*/
addNewElement = function(instance, endpointType, templateId, newId, newPositionY, endpoints, parameters, newPositionX) {
var newInstance = $('#' + templateId).clone()
.prop("id", newId)
.prop("title", "Right click to delete")
.removeClass();
if (newPositionY != "")
newInstance.css("top", newPositionY);
if (newPositionX != "")
newInstance.css("left", newPositionX);
newInstance.addClass("element");
newInstance.attr("anchors", endpoints);
$("#dropContainer").append(newInstance);
for (i = 0; i < endpoints; i++) {
var coordinates = getAnchorCoordinate(i, endpoints);
instance.addEndpoint(document.getElementById(newId), {
anchor: [coordinates[0], coordinates[1], 0, 0],
uuid: i + "_" + newId,
}, endpointType);
}
instance.draggable(jsPlumb.getSelector(".element"), {
containment: $("#dropContainer")
});
$(".element").mousedown(function(e) {
if (e.button == 2) {
instance.remove($(this).prop("id"));
return false;
}
return true;
});
};
/**
* The main loop. This main function controls everything based on JQuery.
*/
jsPlumb.ready(function() {
var instance = jsPlumb.getInstance({
DragOptions: {
cursor: 'pointer',
zIndex: 2000,
},
EndpointHoverStyle: {
fillStyle: "green",
},
HoverPaintStyle: {
strokeStyle: "red",
},
EndpointStyle: {
width: 20,
height: 20,
},
Endpoint: "Rectangle",
Anchors: ["TopCenter", "TopCenter"],
Container: "dropContainer"
});
/**
* Loop for handling events.
*/
instance.doWhileSuspended(function() {
instance.bind("connection", function(info) {
updateConnections(info.connection);
info.connection.parameters = "";
});
instance.bind("beforeDrop", function(info) {
return checkDuplicateConnection(info.connection) &&
checkSourceTargetEquality(info.connection) &&
checkCompatibility(info.connection.sourceId, info.connection.targetId);
});
instance.bind("connectionDetached", function(info) {
updateConnections(info.connection, true);
});
instance.bind("connectionMoved", function(info) {
updateConnections(info.connection, true);
});
instance.bind("contextmenu", function(info) {
instance.detach(info);
});
instance.bind("click", function(info) {
clickedConnection = info;
$('#connectionInfoParameters').val(info.parameters);
$('#connectionInfoDialog').modal();
});
instance.draggable(jsPlumb.getSelector(".element"), {
containment: $("#dropContainer")
});
/**
* Defining an endpoint type can be added to object on the site.
*/
var endpointType = {
endpoint: ["Dot", {
radius: 12
}],
paintStyle: {
fillStyle: "#9932cc",
},
isSource: true,
isTarget: true,
deleteEndpointsOnDetach: false,
zIndex: 20,
connectorStyle: {
strokeStyle: "#9932cc",
lineWidth: 8,
},
connector: ["Bezier", {
curviness: 2000,
}],
maxConnections: 1,
dropOptions: {
tolerance: "fit",
},
};
/**
* Handling click event on elements.
*/
$(".elementTemplate").click(function() {
addNewElement(instance,
endpointType,
$(this).prop("id"), (elementIndex++) + "_" + $(this).prop("id"),
$(this).position().top,
7);
});
/**
* Handling click event on clear button.
*/
$("#clearService").click(function(e) {
instance.detachEveryConnection();
instance.deleteEveryEndpoint();
$(".element").remove();
instance.repaintEverything();
JsPlumbUtil.consume(e);
elementIndex = 0;
});
/**
* Handling click event on save button.
*/
$("#saveService").click(function() {
serviceName = $("#serviceName").text();
connectionSet = [];
instanceSet = [];
$.each(elementConnections, function(index) {
connectionSet.push({
"sourceId": elementConnections[index].sourceId,
"sourceEndpoint": elementConnections[index].endpoints[0].getUuid(),
"targetId": elementConnections[index].targetId,
"targetEndpoint": elementConnections[index].endpoints[1].getUuid(),
"parameters": elementConnections[index].parameters
});
});
$.each($(".element"), function(index) {
instanceSet.push({
"displayId": $(this).prop("id"),
"posX": Math.floor($(this).position().left),
"posY": Math.floor($(this).position().top),
"anchors": $(this).attr("anchors")
});
});
$.post("", {
event: "saveService",
data: JSON.stringify({
"serviceName": serviceName,
"elementConnections": connectionSet,
"elements": instanceSet
})
}, function(resultValue) {
if (window.location.href.indexOf("/create") >= 0) {
window.location = "../" + resultValue;
} else {
addMessage("Saved successfully.", "success");
}
});
});
$(window).resize(function() {
$(".element").each(function() {
if ($(this).position().left + $(this).width() > $("#dropContainer").position().left + $("#dropContainer").width()) {
$(this).css("left", $("#dropContainer").position().left + $("#dropContainer").width() - $(this).width() + 4);
}
});
instance.repaintEverything();
});
$("#dragContainerScrollUp").click(function() {
if (dragContainerScroll > 0) dragContainerScroll -= 1;
$("#dragContainer").scrollTop(dragContainerScroll * $("#elementTemplatePanel").height());
});
$("#dragContainerScrollDown").click(function() {
if (dragContainerScroll < $(".elementTemplate").length - 3) dragContainerScroll += 1;
$("#dragContainer").scrollTop(dragContainerScroll * $("#elementTemplatePanel").height());
});
$("#searchElementTemplate").keyup(function() {
$(".elementTemplate").each(function() {
$(this).parent().parent().hide();
if ($(this).attr("alt").toLowerCase().indexOf($("#searchElementTemplateInput").val().toLowerCase()) >= 0) {
$(this).parent().parent().show();
}
});
});
/**
* Handling click event on dialog save button.
*/
$("#connectionInfoSave").click(function() {
clickedConnection.parameters = $("#connectionInfoParameters").val();
});
/**
* Handling page load event.
*/
$(document).ready(function() {
$.post("", {
event: "loadService"
}, function(resultValue) {
var result = jQuery.parseJSON(resultValue);
$("#serviceName").text(result.serviceName);
$.each(result.elements, function(i, element) {
addNewElement(instance,
endpointType,
element.displayId.split('_')[1],
element.displayId,
element.posY + "px",
element.anchors,
element.parameters,
element.posX + "px");
if (elementIndex < element.displayId.split('_')[0]) {
elementIndex = element.displayId.split('_')[0];
}
});
elementIndex++;
$.each(result.elementConnections, function(i, connection) {
var connectionObject = instance.connect({
uuids: [connection.sourceEndpoint, connection.targetEndpoint]
});
connectionObject.parameters = connection.parameters;
});
});
});
});
});
})();
\ No newline at end of file
from django.core.files.storage import FileSystemStorage
from django.conf import settings
import os
class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name):
if self.exists(name):
os.remove(os.path.join(settings.MEDIA_ROOT, name))
return name
<!DOCTYPE html>
{% extends "dashboard/base.html" %}
{% load staticfiles %}
{% load i18n %}
{% block title-page %}{% trans 'Setty' %}{% endblock %}
{% block content %}
<link type="text/css" rel="stylesheet" href="{% static 'setty/style.css' %}">
<div class="row" id="workspace">
<div class="col-xs-2" id="dragPanel">
<div class="panel panel-default text-center">
<div class="panel-heading">
<div class="row">
<h3 class="no-margin">{% trans 'Elements' %}</h3>
</div>
</div>
<div class="panel-heading">
<div class="row" id="searchElementTemplate">
<div class="col-md-12">
<input type="text" class="form-control" id="searchElementTemplateInput" placeholder="{% trans 'Search' %}"/>
</div>
&nbsp;
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary btn-xs btn-block" id="dragContainerScrollUp"><i class="fa fa-chevron-up"></i></button>
</div>
</div>
</div>
<div class="panel-body" id="dragContainer">
{% for element in elementTemplateList %}
<div class="row" id="elementTemplatePanel">
<div class="panel panel-default">
<div class="panel-heading">
<label class="no-margin">{{ element.name }}</label>
</div>
<div class="panel-body">
<img class="elementTemplate" type="{% for target in element.compatibles.all %}{{ target.id }},{% endfor %}"
id="{{ element.id }}" data-container="body" data-placement="right" title="{{ element.description }}"
src="{% static element.logo %}" alt="{{ element.name }}"
ondragstart="return false;"/>
</div>
</div>
</div>
{% endfor %}
</div>
<div class="panel-footer">
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary btn-xs btn-block" id="dragContainerScrollDown"><i class="fa fa-chevron-down"></i></button>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-8">
<div class="panel panel-default">
<div class="panel-heading text-center">
<div class="row">
<div class="col-xs-4">
</div>
<div class="col-xs-4">
<h3 class="no-margin" id="serviceName" contenteditable="true">Service</h3>
</div>
<div class="col-xs-2 text-right">
<button class="btn btn-info btn-xs" id="clearService">{% trans 'Clear' %}</button>
</div>
<div class="col-xs-2 text-right">
<button class="btn btn-success btn-xs" id="saveService">{% trans 'Save' %}</button>
</div>
</div>
</div>
<div class="panel-body" id="dropContainer" oncontextmenu="return false;"></div>
<div class="panel-footer"></div>
</div>
</div>
<div class="col-xs-2 col-md-2">
<div class="panel panel-default">
<div class="panel-heading text-center">
<div class="row">
<h3 class="no-margin">{% trans 'Information' %}</h3>
</div>
</div>
<div class="panel-body" id="informationContainer"></div>
<div class="panel-footer"></div>
</div>
</div>
</div>
<!-- Modal dialogs -->
<div class="modal fade" id="connectionInfoDialog" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">{% trans 'Connection info' %}</h4>
</div>
<div class="modal-body">
<textarea id="connectionInfoParameters" class="form-control" rows="3" placeholder="Parameters" style="resize: none;"></textarea>
</div>
<div class="modal-footer">
<div class="row">
<div class="col-md-2 col-md-push-8">
<button id="connectionInfoSave" type="button" class="btn btn-success" data-dismiss="modal">{% trans 'Save' %}</button>
</div>
<div class="col-md-2 col-md-push-8">
<button type="button" class="btn btn-danger" data-dismiss="modal">{% trans 'Close' %}</button>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
<!DOCTYPE html>
<form method="post">{% csrf_token %}
Are you sure you want to delete "{{ object }}" ?
<input type="submit" value="Submit" />
</form>
\ No newline at end of file
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^create/$',
views.IndexView.as_view(),
name='setty.views.service-create'),
url(r'^delete/(?P<pk>\d+)$',
views.DeleteView.as_view(),
name='setty.views.service-delete'),
url(r'^start/(?P<pk>\d+)$',
views.StartView.as_view(),
name='setty.views.service-start'),
url(r'^list/$',
views.ListView.as_view(),
name='setty.views.service-list'),
url(r'^(?P<pk>\d+)/$',
views.DetailView.as_view(),
name='setty.views.service-detail'),
]
from django.template import RequestContext, loader
from django.template import RequestContext, loader
from django.http import HttpResponse
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from .models import (
Element,
ElementTemplate,
ElementConnection,
Service,
User,
)
import json
class IndexView(TemplateView):
template_name = "setty/index.html"
def get_context_data(self, **kwargs):
pass
@csrf_exempt
def index(request):
if request.method == 'POST':
if request.POST.get('event') == "getLoggedInUser":
username = None
if request.user.is_authenticated():
return HttpResponse(request.user.username)
else:
return HttpResponse("unauthenticated!")
elif request.POST.get('event') == "deleteConfig":
try:
siteUser = User.objects.get(name=request.POST.get('user'))
workSpace = Workspace.objects.get(
name=request.POST.get('data'),
user=siteUser,
)
serviceInstances = ServiceInstance.objects.all().filter(
workspace=workSpace,
)
for instance in serviceInstances:
connectionTargets = ServiceConnection.objects.all().filter(
target=instance,
)
connectionSources = ServiceConnection.objects.all().filter(
source=instance,
)
for connection in connectionSources:
connection.delete()
for connection in connectionTargets:
connection.delete()
instance.delete()
workSpace.delete()
return HttpResponse(
"Workspace (" +
request.POST.get('data') +
") deleted successfully."
)
except:
return HttpResponse(
"Failed deleting workspace (" +
request.POST.get('data') +
")."
)
elif request.POST.get('event') == "saveConfig":
jsonData = json.loads(request.POST.get('data'))
userName = jsonData['exportData']['user']
try:
siteUser = User.objects.get(name=userName)
except User.DoesNotExist:
siteUser = User(name=userName)
siteUser.save()
try:
siteWorkspace = Workspace.objects.get(
name=jsonData['exportData']['workspace'],
user=siteUser,
)
siteWorkspace.delete()
siteWorkspace = Workspace(
user=siteUser,
name=jsonData['exportData']['workspace'],
)
siteWorkspace.save()
except Workspace.DoesNotExist:
siteWorkspace = Workspace(
user=siteUser,
name=jsonData['exportData']['workspace'],
)
siteWorkspace.save()
for connection in jsonData['exportData']['connections']:
tempData = jsonData['exportData']['connections']
sourceId = tempData[connection]['sourceid']
targetId = tempData[connection]['targetid']
sourcePosX = tempData[connection]['sourceposx']
sourcePosY = tempData[connection]['sourceposy']
targetPosX = tempData[connection]['targetposx']
targetPosY = tempData[connection]['targetposy']
sourceendpoint = tempData[connection]['sourceendpoint']
targetendpoint = tempData[connection]['targetendpoint']
targetParent = Service.objects.get(id=targetId)
sourceParent = Service.objects.get(id=sourceId)
serviceInstanceSource = ServiceInstance(
parentservice=sourceParent,
workspace=siteWorkspace,
parameters=Service.objects.get(id=sourceId).configuration,
posX=sourcePosX,
posY=sourcePosY,
)
serviceInstanceSource.save()
serviceInstanceTarget = ServiceInstance(
parentservice=targetParent,
workspace=siteWorkspace,
parameters=Service.objects.get(id=targetId).configuration,
posX=targetPosX,
posY=targetPosY,
)
serviceInstanceTarget.save()
serviceConnection = ServiceConnection(
target=serviceInstanceTarget,
source=serviceInstanceSource,
sourceEndpoint=sourceendpoint,
targetEndpoint=targetendpoint,
parameters='Not yet configured',
)
serviceConnection.save()
print jsonData
return HttpResponse(siteWorkspace.name)
elif request.POST.get('event') == "loadConfig":
i = 0
data = []
siteUser = User.objects.get(name=request.POST.get('user'))
workSpace = Workspace.objects.get(
name=request.POST.get('data'),
user=siteUser,
)
connectionList = ServiceConnection.objects.all().filter(
Q(source__workspace=workSpace) |
Q(target__workspace=workSpace)
)
for connection in connectionList:
++i
seged = {}
seged['targetposx'] = connection.target.posX
seged['targetposy'] = connection.target.posY
seged['targetendpoint'] = connection.targetEndpoint
seged['targetid'] = connection.target.parentservice.id
seged['sourceposx'] = connection.source.posX
seged['sourceposy'] = connection.source.posY
seged['sourceendpoint'] = connection.sourceEndpoint
seged['sourceid'] = connection.source.parentservice.id
data.append(seged)
jsonData = json.dumps(data)
return HttpResponse(jsonData)
elif request.POST.get('event') == "startConfig":
siteUser = User.objects.get(name=request.POST.get('user'))
workSpace = Workspace.objects.get(
name=request.POST.get('data'),
user=siteUser,
)
print request.POST.get('data')
return HttpResponse("Configuration started.")
return HttpResponse("adsf")
elementList = ElementTemplate.objects.all()
template = loader.get_template('builder/index.html')
context = RequestContext(request, {'elementList': elementList})
return HttpResponse(template.render(context))
from django.template import RequestContext
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.db.models import Q
from django.http import HttpResponseForbidden, Http404
from django.shortcuts import redirect
from django.contrib import auth
from .models import (
Element,
ElementTemplate,
ElementConnection,
Service
)
import json
class IndexView(TemplateView):
template_name = "setty/index.html"
def get(self, request, *args, **kwargs):
if self.request.user.is_authenticated():
return TemplateView.get(self, request, *args, **kwargs) # To be checked!
else:
return redirect(auth.views.login)
def get_context_data(self, **kwargs):
elementTemplateList = ElementTemplate.objects.all()
context = RequestContext(
self.request,
{'elementTemplateList': elementTemplateList})
return context
@csrf_exempt
def post(self, request, *args, **kwargs):
if self.request.POST.get('event') == "saveService":
jsonData = json.loads(self.request.POST.get('data'))
serviceName = jsonData['serviceName']
if 'pk' in kwargs:
serviceObject = Service.objects.get(id=kwargs['pk'])
serviceObject.name = serviceName
serviceObject.save()
Element.objects.filter(service=serviceObject).delete()
else:
serviceObject = Service(
name=serviceName,
user=self.request.user
)
serviceObject.save()
for element in jsonData['elements']:
elementObject = Element(
service=serviceObject,
parameters="none", # further plan
display_id=element['displayId'],
pos_x=element['posX'],
pos_y=element['posY'],
anchors=element['anchors']
)
elementObject.save()
for elementConnection in jsonData['elementConnections']:
sourceId = elementConnection['sourceId']
targetId = elementConnection['targetId']
sourceEndpoint = elementConnection['sourceEndpoint']
targetEndpoint = elementConnection['targetEndpoint']
connectionParameters = elementConnection['parameters']
targetObject = Element.objects.get(
display_id=targetId,
service=serviceObject)
sourceObject = Element.objects.get(
display_id=sourceId,
service=serviceObject)
connectionObject = ElementConnection(
target=targetObject,
source=sourceObject,
target_endpoint=targetEndpoint,
source_endpoint=sourceEndpoint,
parameters=connectionParameters
)
connectionObject.save()
return HttpResponse(serviceObject.pk)
else:
return HttpResponse()
class DeleteView(DeleteView):
model = Service
success_url = reverse_lazy("dashboard.index")
class StartView(TemplateView):
pass
class ListView(TemplateView):
pass
class DetailView(IndexView):
def get(self, request, *args, **kwargs):
try:
serviceObject = Service.objects.get(id=kwargs['pk'])
if serviceObject.user != self.request.user:
return HttpResponseForbidden("You don't have permission to open the service.")
except:
raise Http404
else:
return IndexView.get(self, request, *args, **kwargs)
@csrf_exempt
def post(self, request, *args, **kwargs):
if self.request.POST.get('event') == "loadService":
serviceObject = Service.objects.get(id=kwargs['pk'])
elementList = Element.objects.filter(service=serviceObject)
elementConnectionList = ElementConnection.objects.filter(
Q(target__in=elementList) | Q(source__in=elementList))
elements = []
elementConnections = []
for item in elementList:
elements.append({
'parameters': item.parameters,
'displayId': item.display_id,
'posX': item.pos_x,
'posY': item.pos_y,
'anchors': item.anchors
})
for item in elementConnectionList:
elementConnections.append({
'targetEndpoint': item.target_endpoint,
'sourceEndpoint': item.source_endpoint,
'parameters': item.parameters
})
return HttpResponse(json.dumps(
{"elements": elements,
"elementConnections": elementConnections,
"serviceName": serviceObject.name}))
else:
return IndexView.post(self, request, *args, **kwargs)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment