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)
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