Commit 39a7ffc9 by Estók Dániel

setty: added server-side access management.

parent ea8d0946
/* Settimng up csrf token, touch event and zoom options. */ /* Settimng up csrf token, touch event and zoom options. */
function getCookie(name) {
function getCookie(name) { var cookieValue = null;
var cookieValue = null; if (document.cookie && document.cookie !== '') {
if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';');
var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) {
for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]);
var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) {
if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break;
break; }
} }
} }
} return cookieValue;
return cookieValue; }
}
function csrfSafeMethod(method) {
function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }
}
var csrftoken = getCookie('csrftoken');
var csrftoken = getCookie('csrftoken');
$.ajaxSetup({
$.ajaxSetup({ beforeSend: function(xhr, settings) {
beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.setRequestHeader("X-CSRFToken", csrftoken); }
} }
} });
});
/* Setty implementation starts here. */
/* Setty implementation starts here. */
jsPlumb.ready(function() {
jsPlumb.ready(function() { var jsPlumbInstance = jsPlumb.getInstance({
var jsPlumbInstance = jsPlumb.getInstance({ DragOptions: {
DragOptions: { zIndex: 2000
zIndex: 2000 },
}, EndpointHoverStyle: {
EndpointHoverStyle: { fillStyle: "green"
fillStyle: "green" },
}, HoverPaintStyle: {
HoverPaintStyle: { strokeStyle: "green"
strokeStyle: "green" },
}, Container: "dropContainer"
Container: "dropContainer" });
}); var jsPlumbEndpoint = {
var jsPlumbEndpoint = { endpoint: ["Dot", {
endpoint: ["Dot", { radius: 10
radius: 10 }],
}], paintStyle: {
paintStyle: { fillStyle: "#9932cc"
fillStyle: "#9932cc" },
}, isSource: true,
isSource: true, isTarget: true,
isTarget: true, deleteEndpointsOnDetach: false,
deleteEndpointsOnDetach: false, zIndex: 20,
zIndex: 20, connectorStyle: {
connectorStyle: { strokeStyle: "#9932cc",
strokeStyle: "#9932cc", lineWidth: 8
lineWidth: 8 },
}, connector: ["Bezier", {
connector: ["Bezier", { curviness: 180
curviness: 180 }],
}], maxConnections: 1,
maxConnections: 1, dropOptions: {
dropOptions: { tolerance: "fit"
tolerance: "fit" }
} };
}; var elementConnections = [];
var elementConnections = []; var elementIndex = 0;
var elementIndex = 0; var dragContainerScroll = 0;
var dragContainerScroll = 0; var workspaceWidth = $("#dropContainer").width();
var workspaceWidth = $("#dropContainer").width(); var workspaceHeight = $("#dropContainer").height();
var workspaceHeight = $("#dropContainer").height();
var stackIndexer = 0;
var stackIndexer = 0; var stackSize = 0;
var stackSize = 0; var objectStack = [];
var objectStack = []; var undoStack = [];
var undoStack = []; var redoStack = [];
var redoStack = []; var clickEvent = 0;
var clickEvent = 0; var nextStepConstraint = 0;
var nextStepConstraint = 0;
/* Functions. */
/* Functions. */
setServiceStatus = function(status) {
setServiceStatus = function(status) { if (status == "unsaved") {
if (status == "unsaved") { $("#serviceStatus").text(gettext("Unsaved"));
$("#serviceStatus").text("Unsaved"); } else {
} $("#serviceStatus").empty();
else { }
$("#serviceStatus").empty(); };
}
}; addInfo = function(title, info, object, type) {
mainDiv = $("<div>", {
addInfo = function(title, info, type, object) { class: "row",
/* html: $("<div>", {
$("#informationContainer").empty(); class: "col-xs-12 text-center",
html: row = $("<h4>", {
switch(type){ html: title
case "connection": })
div = })
'<div class="row">' + }).add($("<div>", {
'<div class="col-xs-12 text-center">' + class: "row",
'<h4>' + title + '</h4>' + style: "margin-top: 16px",
'</div>' + html: $("<div>", {
'</div>&nbsp;' + class: "col-xs-12 text-center",
'<div class="row">' + html: row = $("<textarea>", {
'<div class="col-xs-12">' + class: "form-control",
'<textarea class="form-control" rows="28" id="infoInput" placeholder="Config data"></textarea>' + style: "text-align: justify;",
'</div>' + rows: "18",
'</div>&nbsp;' + id: "infoInput",
'<div class="row">' + disabled: !type,
'<div class="col-xs-12 text-center">' + text: info
'<button id="removeConnection" class="btn btn-info">Remove connection</button>' + })
'</div>' + })
'</div>'; }));
break; controlDiv = $("<div>", {
case "element": class: "row",
div = style: "margin-top: 16px",
'<div class="row">' + html: $("<div>", {
'<div class="col-xs-12 text-center">' + class: "col-xs-3 text-center",
'<h4>' + title + '</h4>' + html: $("<button>", {
'</div>' + class: "btn btn-success btn-block",
'</div>&nbsp;' + id: "addEndpoint",
'<div class="row">' + html: gettext("Add endpoint")
'<div class="col-xs-12">' + })
'<textarea class="form-control" rows="24" id="infoInput" placeholder="Config data"></textarea>' + }).add($("<div>", {
'</div>' + class: "col-xs-3 text-center",
'</div>&nbsp;' + html: $("<button>", {
'<div class="row text-center">' + class: "btn btn-danger btn-block",
'<label>Endpoints</label>' + id: "removeEndpoint",
'</div>' + html: gettext("Delete endpoint")
'<div class="row">' + })
'<div class="col-xs-6 text-center">' + })).add($("<div>", {
'<button id="addEndpoint" class="btn btn-success"><i class="fa fa-plus"></i></button>' + class: "col-xs-6 text-center",
'</div>' + html: $("<button>", {
'<div class="col-xs-6 text-center">' + class: "btn btn-info btn-block",
'<button id="removeEndpoint" class="btn btn-danger"><i class="fa fa-minus"></i></button>' + id: "removeElementFromWorkspace",
'</div>' + html: gettext("Remove from workspace")
'</div>&nbsp;' + })
'<div class="row">' + }))
'<div class="col-xs-12 text-center">' + });
'<button id="removeElementFromWorkspace" class="btn btn-info">Remove from workspace</button>' + addElementDiv = $("<div>", {
'</div>' + class: "row",
'</div>'; style: "margin-top: 16px",
break; html: $("<div>", {
case "elementTemplate": class: "col-xs-12 text-center",
div = html: row = $("<button>", {
'<div class="row">' + class: "btn btn-success",
'<div class="col-xs-12 text-center">' + id: "addElementToWorkspace",
'<h4>' + title + '</h4>' + html: gettext("Add to workspace")
'</div>' + })
'</div>&nbsp;' + })
'<div class="row">' + });
'<div class="col-xs-12">' +
'<textarea class="form-control" rows="28" id="infoInput" placeholder="Config data"></textarea>' + $("#informationContainer").html(type?mainDiv.add(controlDiv):mainDiv.add(addElementDiv));
'</div>' +
'</div>&nbsp;' + $("#changeInformationDialog").modal('show');
'<div class="row">' +
'<div class="col-xs-12 text-center">' + sharedObject = object;
'<button id="addElementToWorkspace" class="btn btn-success">Add to workspace</button>' + };
'</div>' +
'</div>'; updateConnections = function(connection, remove) {
break; if (!remove) {
}*/ elementConnections.push(connection);
} else {
// Here comes the ajax getInformation post. index = -1;
// elementtemplateid vagy hostname for (var i = 0; i < elementConnections.length; i++) {
if (elementConnections[i] == connection) {
index = i;
div = 0; break;
}
$("#informationContainer").append(div); }
if (index != -1) {
$("#infoInput").val(info); elementConnections.splice(index, 1);
}
$("#changeInformationDialog").modal('show'); }
sharedObject = object; setServiceStatus("unsaved");
}; };
updateConnections = function(connection, remove) { checkDuplicateConnection = function(connection) {
if (!remove) { for (var i = 0; i < elementConnections.length; i++) {
elementConnections.push(connection); if (((elementConnections[i].targetId ==
} else { connection.targetId &&
index = -1; elementConnections[i].sourceId ==
for (var i = 0; i < elementConnections.length; i++) { connection.sourceId) ||
if (elementConnections[i] == connection) { (elementConnections[i].targetId ==
index = i; connection.sourceId &&
break; elementConnections[i].sourceId ==
} connection.targetId)) &&
} elementConnections[i] != connection) {
if (index != -1) { addMessage(gettext("Twofold connection is forbidden."), "danger");
elementConnections.splice(index, 1); return false;
} }
} }
return true;
setServiceStatus("unsaved"); };
};
checkCompatibility = function(sourceId, targetId) {
checkDuplicateConnection = function(connection) { validTargets = $("#" + sourceId).attr("type").split(',');
for (var i = 0; i < elementConnections.length; i++) {
if (((elementConnections[i].targetId == if (jQuery.inArray(targetId.split('_')[1], validTargets) == -1) {
connection.targetId && addMessage(gettext("Connecting incompatible elements is forbidden."), "danger");
elementConnections[i].sourceId == return false;
connection.sourceId) || }
(elementConnections[i].targetId == return true;
connection.sourceId && };
elementConnections[i].sourceId ==
connection.targetId)) && checkSourceTargetEquality = function(connection) {
elementConnections[i] != connection) { if (connection.targetId == connection.sourceId) {
addMessage("Twofold connection is forbidden.", "danger"); addMessage(gettext("Connecting element to itself is forbidden."), "danger");
return false; return false;
} }
} return true;
return true; };
};
getAnchorCoordinate = function(rate) {
checkCompatibility = function(sourceId, targetId) { x = Math.cos(2.0 * Math.PI * rate) / 2;
validTargets = $("#" + sourceId).attr("type").split(','); y = Math.sin(2.0 * Math.PI * rate) / 2;
dx = 0;
if (jQuery.inArray(targetId.split('_')[1], validTargets) == -1) { dy = 0;
addMessage("Connecting incompatible elements is forbidden.", "danger");
return false; if (rate < 0.125) {
} x = 0.5;
return true; dx = 1;
}; } else if (rate > 0.125 && rate < 0.375) {
y = -0.5;
checkSourceTargetEquality = function(connection) { dy = -1;
if (connection.targetId == connection.sourceId) { } else if (rate > 0.375 && rate < 0.625) {
addMessage("Connecting element to itself is forbidden.", "danger"); x = -0.5;
return false; dx = -1;
} } else if (rate > 0.625 && rate < 0.875) {
return true; y = 0.5;
}; dy = 1;
} else if (rate > 0.875) {
getAnchorCoordinate = function(rate) { x = -0.5;
x = Math.cos(2.0 * Math.PI * rate) / 2; dx = -1;
y = Math.sin(2.0 * Math.PI * rate) / 2; } else {
dx = 0; x = Math.sqrt(2) * Math.cos(2 * Math.PI *
dy = 0; rate) / 2;
y = Math.sqrt(2) * Math.sin(2 * Math.PI *
if (rate < 0.125) { rate) / 2;
x = 0.5;
dx = 1; dx = Math.round(2 * x);
} else if (rate > 0.125 && rate < 0.375) { }
y = -0.5; return [y + 0.5, -x + 0.5, dy, -dx];
dy = -1; };
} else if (rate > 0.375 && rate < 0.625) {
x = -0.5; isConnected = function(anchorId) {
dx = -1; returnValue = false;
} else if (rate > 0.625 && rate < 0.875) { $.each(elementConnections, function(index) {
y = 0.5; if (elementConnections[index].endpoints[0].getUuid() == anchorId ||
dy = 1; elementConnections[index].endpoints[1].getUuid() == anchorId) {
} else if (rate > 0.875) { returnValue = true;
x = -0.5; return;
dx = -1; }
} else { });
x = Math.sqrt(2) * Math.cos(2 * Math.PI * return returnValue;
rate) / 2; };
y = Math.sqrt(2) * Math.sin(2 * Math.PI *
rate) / 2; elementIsConnected = function(element) {
anchors = element.attr("anchors");
dx = Math.round(2 * x); id = element.attr("id");
}
return [y + 0.5, -x + 0.5, dy, -dx]; for (i = 0; i < anchors; i++) {
}; if (isConnected(i + "_" + id)) {
return true;
isConnected = function(anchorId) { }
returnValue = false; }
$.each(elementConnections, function(index) {
if (elementConnections[index].endpoints[0].getUuid() == anchorId || return false;
elementConnections[index].endpoints[1].getUuid() == anchorId) { };
returnValue = true;
return; getConnectionparamAndAnchor = function(anchorId) {
} parameters = "";
}); otherAnchor = "";
return returnValue;
}; $.each(elementConnections, function(index) {
if (elementConnections[index].endpoints[0].getUuid() == anchorId) {
elementIsConnected = function(element) { parameters = elementConnections[index].parameters;
anchors = element.attr("anchors"); otherAnchor = elementConnections[index].endpoints[1].getUuid();
id = element.attr("id"); return;
}
for(i=0;i<anchors;i++)
{ if (elementConnections[index].endpoints[1].getUuid() == anchorId) {
if(isConnected(i + "_" + id)) parameters = elementConnections[index].parameters;
{ otherAnchor = elementConnections[index].endpoints[0].getUuid();
return true; return;
} }
} });
return false; return [otherAnchor, parameters];
}; };
getConnectionparamAndAnchor = function(anchorId) { addEndpoint = function(element) {
parameters = ""; anchors = element.attr("anchors");
otherAnchor = "";
if (anchors == 8) return 1;
$.each(elementConnections, function(index) {
if (elementConnections[index].endpoints[0].getUuid() == anchorId) { anchors++;
parameters = elementConnections[index].parameters;
otherAnchor = elementConnections[index].endpoints[1].getUuid(); jsPlumbInstance.addEndpoint(document.getElementById(element.attr("id")), {
return; uuid: (anchors - 1) + "_" + element.attr("id")
} },
jsPlumbEndpoint);
if (elementConnections[index].endpoints[1].getUuid() == anchorId) {
parameters = elementConnections[index].parameters; for (i = 0; i < anchors; i++) {
otherAnchor = elementConnections[index].endpoints[0].getUuid(); jsPlumbInstance.getEndpoint(i + "_" + element.attr("id")).setAnchor(getAnchorCoordinate(i / (anchors)));
return; }
}
}); element.attr("anchors", anchors);
return [otherAnchor, parameters]; jsPlumbInstance.repaintEverything();
};
return 0;
addEndpoint = function(element) { };
anchors = element.attr("anchors");
removeEndoint = function(element) {
if (anchors == 8) return; anchors = element.attr("anchors");
anchors++; if (anchors == 4) return 1;
jsPlumbInstance.addEndpoint(document.getElementById(element.attr("id")), { i = --anchors;
uuid: (anchors - 1) + "_" + element.attr("id")
}, while (isConnected(i + "_" + element.attr("id")) && i >= 0) i--;
jsPlumbEndpoint);
if (i == -1) {
for (i = 0; i < anchors; i++) { addMessage(gettext("Removing anchors is obstructed."), "danger");
jsPlumbInstance.getEndpoint(i + "_" + element.attr("id")).setAnchor(getAnchorCoordinate(i / (anchors))); return;
} } else if (i == anchors) {
jsPlumbInstance.deleteEndpoint(jsPlumbInstance.getEndpoint(anchors + "_" + element.attr("id")));
element.attr("anchors", anchors); } else {
newId = i + "_" + element.attr("id");
jsPlumbInstance.repaintEverything(); oldId = anchors + "_" + element.attr("id");
};
data = getConnectionparamAndAnchor(oldId);
removeEndoint = function(element) { data.splice(0, 0, newId);
anchors = element.attr("anchors");
jsPlumbInstance.deleteEndpoint(jsPlumbInstance.getEndpoint(oldId));
if (anchors == 4) return;
connectEndpoints(data);
i = --anchors; }
while (isConnected(i + "_" + element.attr("id")) && i >= 0) i--; for (i = 0; i < anchors; i++) jsPlumbInstance.getEndpoint(
i + "_" + element.attr("id")).setAnchor(getAnchorCoordinate(i / (anchors)));
if (i == -1) {
addMessage("Removing anchors is obstructed.", "danger"); element.attr("anchors", anchors);
return;
} else if (i == anchors) { jsPlumbInstance.repaintEverything();
jsPlumbInstance.deleteEndpoint(jsPlumbInstance.getEndpoint(anchors + "_" + element.attr("id")));
} else { return 0;
newId = i + "_" + element.attr("id"); };
oldId = anchors + "_" + element.attr("id");
connectEndpoints = function(data) {
data = getConnectionparamAndAnchor(oldId); connectionObject =
data.splice(0, 0, newId); jsPlumbInstance.connect({
uuids: [data[0], data[1]]
jsPlumbInstance.deleteEndpoint(jsPlumbInstance.getEndpoint(oldId)); });
connectEndpoints(data); connectionObject.parameters = data[2];
}
setServiceStatus("unsaved");
for (i = 0; i < anchors; i++) jsPlumbInstance.getEndpoint( };
i + "_" + element.attr("id")).setAnchor(getAnchorCoordinate(i / (anchors)));
disconnectEndpoints = function(data) {
element.attr("anchors", anchors); for (var i = 0; i < elementConnections.length; i++) {
if (elementConnections[i].endpoints[0].getUuid() == data[0] &&
jsPlumbInstance.repaintEverything(); elementConnections[i].endpoints[1].getUuid() == data[1]) {
}; jsPlumbInstance.detach(elementConnections[i]);
return;
connectEndpoints = function(data) { }
connectionObject = }
jsPlumbInstance.connect({ return;
uuids: [data[0], data[1]] };
});
addElement = function(idOrInstance, newId, newPositionY, endpoints, parameters, newPositionX) {
connectionObject.parameters = data[2]; newInstance = "";
setServiceStatus("unsaved"); if (typeof idOrInstance != "string") {
}; newInstance = idOrInstance;
endpoints = newInstance.attr("anchors");
disconnectEndpoints = function(data) { newInstance.attr("anchors", 0);
for (var i = 0; i < elementConnections.length; i++) { } else {
if (elementConnections[i].endpoints[0].getUuid() == data[0] && newInstance = $('#' + idOrInstance)
elementConnections[i].endpoints[1].getUuid() == data[1]) { .clone()
jsPlumbInstance.detach(elementConnections[i]); .prop("id", newId)
return; .prop("title", "Right click to delete")
} .removeClass()
} .addClass("element")
return; .attr("anchors", 0)
}; .attr("parameters", parameters)
.css("top", newPositionY)
addElement = function(idOrInstance, newId, newPositionY, endpoints, parameters, newPositionX) { .css("left", newPositionX);
newInstance = ""; }
if (typeof idOrInstance != "string") { $("#dropContainer").append(newInstance);
newInstance = idOrInstance;
endpoints = newInstance.attr("anchors"); for (i = 0; i <= endpoints; i++) {
newInstance.attr("anchors", 0); addEndpoint(newInstance);
} else { }
newInstance = $('#' + idOrInstance)
.clone() jsPlumbInstance.draggable(jsPlumb.getSelector(".element"), {
.prop("id", newId) containment: $("#dropContainer")
.prop("title", "Right click to delete") });
.removeClass()
.addClass("element") setServiceStatus("unsaved");
.attr("anchors", 0)
.attr("parameters", parameters) jsPlumbInstance.repaintEverything();
.css("top", newPositionY)
.css("left", newPositionX); return newInstance;
} };
$("#dropContainer").append(newInstance); removeElement = function(object) {
jsPlumbInstance.detachAllConnections(object);
for (i = 0; i <= endpoints; i++) { jsPlumbInstance.remove(object.attr("id"));
addEndpoint(newInstance); };
}
jsPlumbInstance.draggable(jsPlumb.getSelector(".element"), { /* Registering events using JsPlumb. */
containment: $("#dropContainer")
}); jsPlumbInstance.bind("connection", function(info) {
updateConnections(info.connection);
setServiceStatus("unsaved"); info.connection.parameters = "";
jsPlumbInstance.repaintEverything(); if (clickEvent === 0) {
undoStack.splice(stackIndexer, 0, disconnectEndpoints);
return newInstance; redoStack.splice(stackIndexer, 0, connectEndpoints);
}; connectionArray = [];
connectionArray.push(info.connection.endpoints[0].getUuid(),
removeElement = function(object) { info.connection.endpoints[1].getUuid(),
jsPlumbInstance.detachAllConnections(object); info.connection.parameters);
jsPlumbInstance.remove(object.attr("id")); objectStack.splice(stackIndexer, 0, connectionArray);
}; stackIndexer++;
stackSize++;
}
/* Registering events using JsPlumb. */ });
jsPlumbInstance.bind("connection", function(info) { jsPlumbInstance.bind("beforeDrop", function(info) {
updateConnections(info.connection); return checkDuplicateConnection(info.connection) &&
info.connection.parameters = ""; checkSourceTargetEquality(info.connection) &&
checkCompatibility(info.connection.sourceId, info.connection.targetId);
if (clickEvent === 0) { });
undoStack.splice(stackIndexer, 0, disconnectEndpoints);
redoStack.splice(stackIndexer, 0, connectEndpoints); jsPlumbInstance.bind("connectionDetached", function(info) {
connectionArray = []; updateConnections(info.connection, true);
connectionArray.push(info.connection.endpoints[0].getUuid(),
info.connection.endpoints[1].getUuid(), if (clickEvent === 0) {
info.connection.parameters); undoStack.splice(stackIndexer, 0, connectEndpoints);
objectStack.splice(stackIndexer, 0, connectionArray); redoStack.splice(stackIndexer, 0, disconnectEndpoints);
stackIndexer++; connectionArray = [];
stackSize++; connectionArray.push(info.connection.endpoints[0].getUuid(),
} info.connection.endpoints[1].getUuid(),
}); info.connection.parameters);
objectStack.splice(stackIndexer, 0, connectionArray);
jsPlumbInstance.bind("beforeDrop", function(info) { stackIndexer++;
return checkDuplicateConnection(info.connection) && stackSize++;
checkSourceTargetEquality(info.connection) && }
checkCompatibility(info.connection.sourceId, info.connection.targetId); });
});
jsPlumbInstance.bind("connectionMoved", function(info) {
jsPlumbInstance.bind("connectionDetached", function(info) { updateConnections(info.connection, true);
updateConnections(info.connection, true); });
if (clickEvent === 0) { jsPlumbInstance.bind("contextmenu", function(info) {
undoStack.splice(stackIndexer, 0, connectEndpoints); jsPlumbInstance.detach(info);
redoStack.splice(stackIndexer, 0, disconnectEndpoints); });
connectionArray = [];
connectionArray.push(info.connection.endpoints[0].getUuid(), jsPlumbInstance.draggable(jsPlumb.getSelector(".element"), {
info.connection.endpoints[1].getUuid(), containment: $("#dropContainer")
info.connection.parameters); });
objectStack.splice(stackIndexer, 0, connectionArray);
stackIndexer++;
stackSize++; /* Registering events using JQuery. */
}
}); $('body').on('click', '.elementTemplate', function() {
addElement($(this).attr("id"),
jsPlumbInstance.bind("connectionMoved", function(info) { (++elementIndex) + "_" + $(this).attr("id"),
updateConnections(info.connection, true); (elementIndex % 21) * 30, 4, "",
}); (elementIndex % 21) * 30);
jsPlumbInstance.bind("contextmenu", function(info) { undoStack.splice(stackIndexer, 0, removeElement);
jsPlumbInstance.detach(info); redoStack.splice(stackIndexer, 0, addElement);
}); objectStack.splice(stackIndexer, 0, newInstance);
stackSize++;
jsPlumbInstance.bind("dblclick", function(info) { stackIndexer++;
info.setPaintStyle({strokeStyle:"red", lineWidth: 8}); });
addInfo($("#" + info.sourceId.split('_')[1]).attr("alt") + ' - ' + $("#" + info.targetId.split('_')[1]).attr("alt"),
info.parameters, $('body').on('dblclick', '.element', function() {
"connection", element = $(this);
info); element.addClass("elementSelected");
}); addInfo(element.attr("alt"),
element.attr("parameters"),
jsPlumbInstance.draggable(jsPlumb.getSelector(".element"), { element, 1);
containment: $("#dropContainer") $(document).scrollTop(0);
}); });
$('body').on('contextmenu', '.element', function(event) {
/* Registering events using JQuery. */ setServiceStatus("unsaved");
removeElement($(this));
$('body').on('click', '.elementTemplate', function() {
addElement($(this).attr("id"), undoStack.splice(stackIndexer, 0, addElement);
(++elementIndex) + "_" + $(this).attr("id"), redoStack.splice(stackIndexer, 0, removeElement);
(elementIndex % 21) * 30, 4, "", objectStack.splice(stackIndexer, 0, $(this));
(elementIndex % 21) * 30);
nextStepConstraint = 0;
undoStack.splice(stackIndexer, 0, removeElement); stackSize++;
redoStack.splice(stackIndexer, 0, addElement); stackIndexer++;
objectStack.splice(stackIndexer, 0, newInstance); });
stackSize++;
stackIndexer++; $('body').on('keyup', '#infoInput', function() {
}); setServiceStatus("unsaved");
newParams = $("#infoInput").val();
$('body').on('dblclick', '.element', function() {
element = $(this); sharedObject.attr("parameters", newParams);
element.addClass("elementSelected"); });
addInfo(element.attr("alt"),
element.attr("parameters"), $('body').on('click', '#addEndpoint', function() {
"element", element); setServiceStatus("unsaved");
$(document).scrollTop(0); if(addEndpoint(sharedObject)) return;
}); undoStack.splice(stackIndexer, 0, removeEndoint);
redoStack.splice(stackIndexer, 0, addEndpoint);
$('body').on('contextmenu', '.element', function(event) { objectStack.splice(stackIndexer, 0, sharedObject);
setServiceStatus("unsaved"); stackIndexer++;
removeElement($(this)); stackSize++;
});
undoStack.splice(stackIndexer, 0, addElement);
redoStack.splice(stackIndexer, 0, removeElement); $('body').on('click', '#removeEndpoint', function() {
objectStack.splice(stackIndexer, 0, $(this)); setServiceStatus("unsaved");
if(removeEndoint(sharedObject)) return;
nextStepConstraint = 0; undoStack.splice(stackIndexer, 0, addEndpoint);
stackSize++; redoStack.splice(stackIndexer, 0, removeEndoint);
stackIndexer++; objectStack.splice(stackIndexer, 0, sharedObject);
}); stackIndexer++;
stackSize++;
$('body').on('click', '#closeInfoPanel', function() { });
$('#informationPanel').hide();
$('#dragPanel').show(); $('body').on('click', '#removeElementFromWorkspace', function() {
}); setServiceStatus("unsaved");
removeElement(sharedObject);
$('body').on('keyUp', '#infoInput', function() {
setServiceStatus("unsaved"); undoStack.splice(stackIndexer, 0, addElement);
newParams = $("#infoInput").val(); redoStack.splice(stackIndexer, 0, removeElement);
objectStack.splice(stackIndexer, 0, sharedObject);
if (type == "connection") object.parameters = newParams; stackSize++;
if (type == "element") object.attr("parameters", newParams); stackIndexer++;
});
$("#changeInformationDialog").modal('hide');
$('body').on('click', '#addEndpoint', function() { });
addEndpoint(sharedObject);
undoStack.splice(stackIndexer, 0, removeEndoint); $('body').on('click', '#removeConnection', function() {
redoStack.splice(stackIndexer, 0, addEndpoint); jsPlumbInstance.detach(sharedObject);
objectStack.splice(stackIndexer, 0, sharedObject); });
stackIndexer++;
stackSize++; $('body').on('click', '#addElementToWorkspace', function() {
}); newInstance = addElement(sharedObject.attr("id"),
(++elementIndex) + "_" + sharedObject.attr("id"),
$('body').on('click', '#removeEndpoint', function() { (elementIndex % 21) * 30, 4, "",
removeEndoint(sharedObject); (elementIndex % 21) * 30);
undoStack.splice(stackIndexer, 0, addEndpoint);
redoStack.splice(stackIndexer, 0, removeEndoint); undoStack.splice(stackIndexer, 0, removeElement);
objectStack.splice(stackIndexer, 0, sharedObject); redoStack.splice(stackIndexer, 0, addElement);
stackIndexer++; objectStack.splice(stackIndexer, 0, newInstance);
stackSize++; stackSize++;
}); stackIndexer++;
});
$('body').on('click', '#removeElementFromWorkspace', function() {
setServiceStatus("unsaved"); $('body').on('click', '#clearService', function() {
removeElement(sharedObject); //Todo
setServiceStatus("unsaved");
undoStack.splice(stackIndexer, 0, addElement);
redoStack.splice(stackIndexer, 0, removeElement); elementIndex = 0;
objectStack.splice(stackIndexer, 0, sharedObject); });
stackSize++;
stackIndexer++; $('body').on('click', '#undoMovement', function() {
}); if (stackIndexer < 1) return;
stackIndexer--;
$('body').on('click', '#removeConnection', function() { clickEvent = 1;
jsPlumbInstance.detach(sharedObject); object = objectStack[stackIndexer];
}); undoStack[stackIndexer](object);
clickEvent = 0;
$('body').on('click', '#addElementToWorkspace', function() { });
newInstance = addElement(sharedObject.attr("id"),
(++elementIndex) + "_" + sharedObject.attr("id"), $('body').on('click', '#redoMovement', function() {
(elementIndex % 21) * 30, 4, "", if (stackIndexer >= stackSize) return;
(elementIndex % 21) * 30); clickEvent = 1;
object = objectStack[stackIndexer];
undoStack.splice(stackIndexer, 0, removeElement); redoStack[stackIndexer](object);
redoStack.splice(stackIndexer, 0, addElement); stackIndexer++;
objectStack.splice(stackIndexer, 0, newInstance); clickEvent = 0;
stackSize++; });
stackIndexer++;
}); $('body').on('click', '#addMachineDialog', function() {
// Here comes the ajax post of getting machines
$('body').on('click', '#clearService', function() { });
jsPlumbInstance.remove("element");
setServiceStatus("unsaved"); $('body').on('click', '.elementTemplateInfo', function() {
id = $(this).attr("element");
elementIndex = 0; addInfo($("#" + id).attr("alt"), $("#" + id).attr("desc"), $("#" + id), 0);
}); });
$('body').on('click', '#undoMovement', function() { $('body').on('click', '#serviceName', function() {
if (stackIndexer < 1) return; $('#serviceName').hide();
stackIndexer--; $("#serviceNameEdit").css("display", "inline").val($(this).text()).select();
clickEvent = 1; $("#serviceNameSave").css("display", "inline");
object = objectStack[stackIndexer]; setServiceStatus("unsaved");
undoStack[stackIndexer](object); });
clickEvent = 0;
}); $('body').on('click', '#serviceNameSave', function() {
$('#serviceNameEdit').hide();
$('body').on('click', '#redoMovement', function() { $(this).hide();
if (stackIndexer >= stackSize) return; $("#serviceName").show().text($('#serviceNameEdit').val());
clickEvent = 1; });
object = objectStack[stackIndexer];
redoStack[stackIndexer](object); $('body').on('click', '#dragContainerScrollUp', function() {
stackIndexer++; scrollContainer(-1);
clickEvent = 0; });
});
$('body').on('click', '#dragContainerScrollDown', function() {
$('body').on('click', '#addMachineDialog', function() { scrollContainer(1);
// Here comes the ajax post of getMachineAvailableList });
// posting usedhostnames
// $('body').on('hide.bs.modal', '#changeInformationDialog', function() {
// $('.element').removeClass('elementSelected');
// after it, appending obtained content to addmachinedialogbody });
});
$('body').on('keyup', '#searchElementTemplate', function() {
$('body').on('click', '.elementTemplateInfo', function() { $(".elementTemplate").each(function() {
id = $(this).attr("element"); $(this).parent().parent().hide();
addInfo($("#" + id).attr("alt"), $("#" + id).attr("desc"), "elementTemplate", $("#" + id)); if ($(this).attr("alt").toLowerCase().indexOf($("#searchElementTemplateInput").val().toLowerCase()) >= 0)
}); $(this).parent().parent().show();
});
$('body').on('click', '#serviceName', function() { });
$('#serviceName').hide();
$("#serviceNameEdit").css("display", "inline").val($(this).text()).select(); $('body').on('mousewheel DOMMouseScroll onmousewheel', function(event) {
$("#serviceNameSave").css("display", "inline"); var e = window.event || event;
setServiceStatus("unsaved"); var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
});
$('body').addClass("noScroll");
$('body').on('click', '#serviceNameSave', function() {
$('#serviceNameEdit').hide(); dragContainerScroll -= delta;
$(this).hide();
$("#serviceName").show().text($('#serviceNameEdit').val()); if (dragContainerScroll == $(".elementTemplate").length - 2) dragContainerScroll--;
}); if (dragContainerScroll == -1) dragContainerScroll++;
$('body').on('click', '#dragContainerScrollUp', function() { $("#dragContainer").scrollTop(
scrollContainer(-1); dragContainerScroll * $("#elementTemplatePanel").height()
}); );
$('body').on('click', '#dragContainerScrollDown', function() { $('body').removeClass("noScroll");
scrollContainer(1); });
});
$(document).on('keydown', function(e) {
$('body').on('hide.bs.modal', '#changeInformationDialog', function () { var eventObject = window.event ? event : e;
$('.element').removeClass('elementSelected');
jsPlumbInstance.select().setPaintStyle({strokeStyle:'#9932cc', lineWidth: 8}); // Undo (CTRL + Z)
}); if (eventObject.keyCode == 90 && eventObject.ctrlKey) {
eventObject.preventDefault();
$('body').on('keyup', '#searchElementTemplate', function() { $('#undoMovement').click();
$(".elementTemplate").each(function() { }
$(this).parent().parent().hide();
if ($(this).attr("alt").toLowerCase().indexOf($("#searchElementTemplateInput").val().toLowerCase()) >= 0) // Redo (CTRL + Y)
$(this).parent().parent().show(); if (eventObject.keyCode == 89 && eventObject.ctrlKey) {
}); eventObject.preventDefault();
}); $('#redoMovement').click();
}
$('body').on('mousewheel DOMMouseScroll onmousewheel', function(event) {
var e = window.event || event; // Add element (CTRL + A)
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); if (eventObject.keyCode == 65 && eventObject.ctrlKey) {
eventObject.preventDefault();
$('body').addClass("noScroll"); $('#showAddElementDialog').click();
}
dragContainerScroll -= delta;
// Clean (CTRL + C)
if (dragContainerScroll == $(".elementTemplate").length - 2) dragContainerScroll--; if (eventObject.keyCode == 67 && eventObject.ctrlKey) {
if (dragContainerScroll == -1) dragContainerScroll++; eventObject.preventDefault();
$('#clearService').click();
$("#dragContainer").scrollTop( }
dragContainerScroll * $("#elementTemplatePanel").height()
); // Save (CTRL + S)
if (eventObject.keyCode == 83 && eventObject.ctrlKey) {
$('body').removeClass("noScroll"); eventObject.preventDefault();
}); $('#saveService').click();
}
$(document).on('keydown', function(e) {
var eventObject = window.event ? event : e; // Delete (CTRL + D)
if (eventObject.keyCode == 68 && eventObject.ctrlKey) {
// Undo (CTRL + Z) eventObject.preventDefault();
if (eventObject.keyCode == 90 && eventObject.ctrlKey) $('#deleteService').click();
{ }
eventObject.preventDefault();
$('#undoMovement').click(); // Close dialog (ESC)
} if (eventObject.keyCode == 27) {
eventObject.preventDefault();
// Redo (CTRL + Y) $("#changeInformationDialog").modal('hide');
if (eventObject.keyCode == 89 && eventObject.ctrlKey) $("#addElementDialog").modal('hide');
{ }
eventObject.preventDefault(); });
$('#redoMovement').click();
} $(window).on('resize', function() {
$(".element").each(function() {
// Add element (CTRL + A) rate = ($(this).position().left) / workspaceWidth;
if (eventObject.keyCode == 65 && eventObject.ctrlKey) left = rate * ($("#dropContainer").width());
{ $(this).css("left", left);
eventObject.preventDefault(); });
$('#showAddElementDialog').click(); workspaceWidth = $("#dropContainer").width();
} jsPlumbInstance.repaintEverything();
});
// Clean (CTRL + C)
if (eventObject.keyCode == 67 && eventObject.ctrlKey)
{ /* Registering events concerning persistence. */
eventObject.preventDefault();
$('#clearService').click(); $('body').on('click', '#saveService', function() {
} serviceName = $("#serviceName").text();
connectionSet = [];
// Save (CTRL + S) instanceSet = [];
if (eventObject.keyCode == 83 && eventObject.ctrlKey)
{ $.each(elementConnections, function(index) {
eventObject.preventDefault(); connectionSet.push({
$('#saveService').click(); "sourceId": elementConnections[index].sourceId,
} "sourceEndpoint": elementConnections[index].endpoints[0].getUuid(),
"targetId": elementConnections[index].targetId,
// Delete (CTRL + D) "targetEndpoint": elementConnections[index].endpoints[1].getUuid(),
if (eventObject.keyCode == 68 && eventObject.ctrlKey) "parameters": elementConnections[index].parameters
{ });
eventObject.preventDefault(); });
$('#deleteService').click();
} $.each($(".element"), function() {
}); instanceSet.push({
"displayId": $(this).prop("id"),
$(window).on('resize', function() { "positionLeft": $(this).position().left / workspaceWidth,
$(".element").each(function() { "positionTop": $(this).position().top / workspaceHeight,
rate = ($(this).position().left)/workspaceWidth; "anchorNumber": $(this).attr("anchors"),
left = rate*($("#dropContainer").width()); "parameters": $(this).attr("parameters")
$(this).css("left", left); });
}); });
workspaceWidth = $("#dropContainer").width();
jsPlumbInstance.repaintEverything(); $.post("", {
}); event: "saveService",
data: JSON.stringify({
"serviceName": serviceName,
/* Registering events concerning persistence. */ "elementConnections": connectionSet,
"elements": instanceSet
$('body').on('click', '#saveService', function() { })
serviceName = $("#serviceName").text(); }, function(result) {
connectionSet = []; addMessage(result.serviceName + gettext(" saved successfully."), "success");
instanceSet = []; setServiceStatus("saved");
});
$.each(elementConnections, function(index) { });
connectionSet.push({
"sourceId": elementConnections[index].sourceId, $(document).ready(function() {
"sourceEndpoint": elementConnections[index].endpoints[0].getUuid(), if (!$("#dropContainer").length) return; // Protection for not posting sites that differ from setty sites.
"targetId": elementConnections[index].targetId, $.post("", {
"targetEndpoint": elementConnections[index].endpoints[1].getUuid(), event: "loadService"
"parameters": elementConnections[index].parameters}); }, function(result) {
}); $("#serviceName").text(result.serviceName);
$.each($(".element"), function() { $.each(result.elements, function(i, element) {
instanceSet.push({ addElement(element.displayId.split('_')[1],
"displayId": $(this).prop("id"), element.displayId,
"positionLeft": $(this).position().left/workspaceWidth, (element.positionTop * workspaceHeight) + "px",
"positionTop": $(this).position().top/workspaceHeight, element.anchorNumber,
"anchorNumber": $(this).attr("anchors"), element.parameters,
"parameters": $(this).attr("parameters")}); (element.positionLeft * workspaceWidth) + "px");
}); if (elementIndex < element.displayId.split('_')[0])
elementIndex = element.displayId.split('_')[0];
$.post("", { elementIndex++;
event: "saveService", });
data: JSON.stringify({
"serviceName": serviceName, clickEvent = 1;
"elementConnections": connectionSet, $.each(result.elementConnections,
"elements": instanceSet}) function(i, connection) {
}, function(result) { connectEndpoints([connection.sourceEndpoint, connection.targetEndpoint, connection.parameters]);
addMessage(result.serviceName + " saved successfully.","success"); });
setServiceStatus("saved"); clickEvent = 0;
}); setServiceStatus("saved");
}); });
});
$(document).ready(function() { });
if(!$("#dropContainer").length) return; // Protection for not posting sites that differ from setty sites.
$.post("", {
event: "loadService"
}, function(result) {
$("#serviceName").text(result.serviceName);
$.each(result.elements, function(i, element) {
addElement(element.displayId.split('_')[1],
element.displayId,
(element.positionTop*workspaceHeight) + "px",
element.anchorNumber,
element.parameters,
(element.positionLeft*workspaceWidth) + "px");
if (elementIndex < element.displayId.split('_')[0])
elementIndex = element.displayId.split('_')[0];
elementIndex++;
});
clickEvent = 1;
$.each(result.elementConnections,
function(i, connection) {
connectEndpoints([connection.sourceEndpoint, connection.targetEndpoint, connection.parameters]);
});
clickEvent = 0;
setServiceStatus("saved");
});
});
});
...@@ -118,14 +118,14 @@ ...@@ -118,14 +118,14 @@
</div> </div>
<div class="panel-body container-fluid" id="dragContainer"> <div class="panel-body container-fluid" id="dragContainer">
{% for element in elementTemplateList %} {% for element in elementTemplateList %}
<div class="col-md-12 col-sm-4" id="elementTemplatePanel"> <div class="col-md-6 col-sm-4" id="elementTemplatePanel">
<div class="panel panel-default"> <div class="panel panel-default">
<div class="panel-heading"> <div class="panel-heading">
<div class="row text-center"> <div class="row text-center">
<div class="col-xs-10 col-xs-push-1 text-center"> <div class="col-xs-8 col-xs-push-2 text-center">
<label class="no-margin">{{ element.name }}</label> <label class="no-margin">{{ element.name }}</label>
</div> </div>
<div class="col-xs-1 col-xs-push-1 text-right"> <div class="col-xs-2 col-xs-push-2 text-left">
<button class="btn btn-primary btn-xs elementTemplateInfo" element="{{ element.id }}"> <button class="btn btn-primary btn-xs elementTemplateInfo" element="{{ element.id }}">
<i class="fa fa-info"></i> <i class="fa fa-info"></i>
</button> </button>
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
# You should have received a copy of the GNU General Public License along # You should have received a copy of the GNU General Public License along
# with CIRCLE. If not, see <http://www.gnu.org/licenses/>. # with CIRCLE. If not, see <http://www.gnu.org/licenses/>.
from django.contrib import messages # NOTE: ezt tettem ide from django.contrib import messages
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse, reverse_lazy from django.core.urlresolvers import reverse, reverse_lazy
from django.db.models import Q from django.db.models import Q
...@@ -41,85 +41,99 @@ class DetailView(LoginRequiredMixin, TemplateView): ...@@ -41,85 +41,99 @@ class DetailView(LoginRequiredMixin, TemplateView):
template_name = "setty/index.html" template_name = "setty/index.html"
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(DetailView, self).get_context_data(**kwargs) logger.debug('DetailView.get_context_data() called. User: %s',
context['elementTemplateList'] = ElementTemplate.objects.all() unicode(self.request.user))
context['actualId'] = kwargs['pk'] service = Service.objects.get(id=kwargs['pk'])
return context
def post(self, request, *args, **kwargs): if self.request.user == service.user or self.request.user.is_superuser:
if self.request.POST.get('event') == "saveService": context = super(DetailView, self).get_context_data(**kwargs)
data = json.loads(self.request.POST.get('data')) context['elementTemplateList'] = ElementTemplate.objects.all()
service = Service.objects.get(id=kwargs['pk']) context['actualId'] = kwargs['pk']
service.name = data['serviceName'] return context
service.save() else:
raise PermissionDenied
Element.objects.filter(service=service).delete()
for element in data['elements']:
elementObject = Element(
service=service,
parameters=element['parameters'],
display_id=element['displayId'],
position_left=element['positionLeft'],
position_top=element['positionTop'],
anchor_number=element['anchorNumber']
)
elementObject.save()
for elementConnection in data['elementConnections']:
sourceId = elementConnection['sourceId']
targetId = elementConnection['targetId']
sourceEndpoint = elementConnection['sourceEndpoint']
targetEndpoint = elementConnection['targetEndpoint']
connectionParameters = elementConnection['parameters']
targetObject = Element.objects.get(
display_id=targetId,
service=service)
sourceObject = Element.objects.get(
display_id=sourceId,
service=service)
connectionObject = ElementConnection(
target=targetObject,
source=sourceObject,
target_endpoint=targetEndpoint,
source_endpoint=sourceEndpoint,
parameters=connectionParameters
)
connectionObject.save()
return JsonResponse({'serviceName': service.name})
elif self.request.POST.get('event') == "loadService":
service = Service.objects.get(id=kwargs['pk'])
elementList = Element.objects.filter(service=service)
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,
'positionLeft': item.position_left,
'positionTop': item.position_top,
'anchorNumber': item.anchor_number})
for item in elementConnectionList:
elementConnections.append({
'targetEndpoint': item.target_endpoint,
'sourceEndpoint': item.source_endpoint,
'parameters': item.parameters})
return JsonResponse(
{'elements': elements,
'elementConnections': elementConnections,
'serviceName': service.name})
def post(self, request, *args, **kwargs):
logger.debug('DetailView.post() called. User: %s',
unicode(self.request.user))
service = Service.objects.get(id=kwargs['pk'])
if self.request.user == service.user or self.request.user.is_superuser:
if self.request.POST.get('event') == "saveService":
data = json.loads(self.request.POST.get('data'))
service = Service.objects.get(id=kwargs['pk'])
service.name = data['serviceName']
service.save()
Element.objects.filter(service=service).delete()
for element in data['elements']:
elementObject = Element(
service=service,
parameters=element['parameters'],
display_id=element['displayId'],
position_left=element['positionLeft'],
position_top=element['positionTop'],
anchor_number=element['anchorNumber']
)
elementObject.save()
for elementConnection in data['elementConnections']:
sourceId = elementConnection['sourceId']
targetId = elementConnection['targetId']
sourceEndpoint = elementConnection['sourceEndpoint']
targetEndpoint = elementConnection['targetEndpoint']
connectionParameters = elementConnection['parameters']
targetObject = Element.objects.get(
display_id=targetId,
service=service)
sourceObject = Element.objects.get(
display_id=sourceId,
service=service)
connectionObject = ElementConnection(
target=targetObject,
source=sourceObject,
target_endpoint=targetEndpoint,
source_endpoint=sourceEndpoint,
parameters=connectionParameters
)
connectionObject.save()
return JsonResponse({'serviceName': service.name})
elif self.request.POST.get('event') == "loadService":
service = Service.objects.get(id=kwargs['pk'])
elementList = Element.objects.filter(service=service)
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,
'positionLeft': item.position_left,
'positionTop': item.position_top,
'anchorNumber': item.anchor_number})
for item in elementConnectionList:
elementConnections.append({
'targetEndpoint': item.target_endpoint,
'sourceEndpoint': item.source_endpoint,
'parameters': item.parameters})
return JsonResponse(
{'elements': elements,
'elementConnections': elementConnections,
'serviceName': service.name})
else:
raise PermissionDenied
else: else:
raise PermissionDenied raise PermissionDenied
...@@ -128,9 +142,18 @@ class DeleteView(LoginRequiredMixin, DeleteView): ...@@ -128,9 +142,18 @@ class DeleteView(LoginRequiredMixin, DeleteView):
model = Service model = Service
success_url = reverse_lazy("dashboard.index") success_url = reverse_lazy("dashboard.index")
def post(self, request, *args, **kwargs):
logger.debug('DeleteView.post() called. User: %s',
unicode(self.request.user))
service = Service.objects.get(id=kwargs['pk'])
class CreateView(LoginRequiredMixin, TemplateView): if self.request.user == service.user or self.request.user.is_superuser:
return super(DeleteView, self).post(request, *args, **kwargs)
else:
return PermissionDenied
class CreateView(LoginRequiredMixin, TemplateView):
def get_template_names(self): def get_template_names(self):
if self.request.is_ajax(): if self.request.is_ajax():
return ['dashboard/_modal.html'] return ['dashboard/_modal.html']
...@@ -138,6 +161,8 @@ class CreateView(LoginRequiredMixin, TemplateView): ...@@ -138,6 +161,8 @@ class CreateView(LoginRequiredMixin, TemplateView):
return ['dashboard/nojs-wrapper.html'] return ['dashboard/nojs-wrapper.html']
def get_context_data(self, *args, **kwargs): def get_context_data(self, *args, **kwargs):
logger.debug('CreateView.get_context_data() called. User: %s',
unicode(self.request.user))
context = super(CreateView, self).get_context_data(*args, **kwargs) context = super(CreateView, self).get_context_data(*args, **kwargs)
context.update({ context.update({
...@@ -148,6 +173,8 @@ class CreateView(LoginRequiredMixin, TemplateView): ...@@ -148,6 +173,8 @@ class CreateView(LoginRequiredMixin, TemplateView):
return context return context
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
logger.debug('CreateView.post() called. User: %s',
unicode(self.request.user))
service_name = self.request.POST.get('serviceName') service_name = self.request.POST.get('serviceName')
if not service_name: if not service_name:
...@@ -181,11 +208,15 @@ class ListView(LoginRequiredMixin, FilterMixin, SingleTableView): ...@@ -181,11 +208,15 @@ class ListView(LoginRequiredMixin, FilterMixin, SingleTableView):
} }
def get_context_data(self, *args, **kwargs): def get_context_data(self, *args, **kwargs):
logger.debug('ListView.get_context_data() called. User: %s',
unicode(self.request.user))
context = super(ListView, self).get_context_data(*args, **kwargs) context = super(ListView, self).get_context_data(*args, **kwargs)
context['search_form'] = self.search_form context['search_form'] = self.search_form
return context return context
def get(self, *args, **kwargs): def get(self, *args, **kwargs):
logger.debug('ListView.get() called. User: %s',
unicode(self.request.user))
self.search_form = ServiceListSearchForm(self.request.GET) self.search_form = ServiceListSearchForm(self.request.GET)
self.search_form.full_clean() self.search_form.full_clean()
...@@ -203,14 +234,14 @@ class ListView(LoginRequiredMixin, FilterMixin, SingleTableView): ...@@ -203,14 +234,14 @@ class ListView(LoginRequiredMixin, FilterMixin, SingleTableView):
return super(ListView, self).get(*args, **kwargs) return super(ListView, self).get(*args, **kwargs)
def get_queryset(self): def get_queryset(self):
logger.debug('ListView.get _queryset() called. User: %s', logger.debug('ListView.get_queryset() called. User: %s',
unicode(self.request.user)) unicode(self.request.user))
qs = self.model.objects.all() qs = self.model.objects.all()
self.create_fake_get() # NOTE: ezt tettem ide self.create_fake_get()
try: try:
filters, excludes = self.get_queryset_filters() filters, excludes = self.get_queryset_filters()
if not self.request.user.is_superuser: if not self.request.user.is_superuser:
filters['user'] = self.request.user # NOTE: ezt visszairtam filters['user'] = self.request.user
qs = qs.filter(**filters).exclude(**excludes).distinct() qs = qs.filter(**filters).exclude(**excludes).distinct()
except ValueError: except ValueError:
messages.error(self.request, _("Error during filtering.")) messages.error(self.request, _("Error during filtering."))
......
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