feat: update param filters in listContractProcess

refactor
style
This commit is contained in:
Frank.R.Wu 2021-06-30 10:39:00 +08:00
parent 10841c1b03
commit 59d54cb2b5
12 changed files with 1449 additions and 1457 deletions

View File

@ -405,7 +405,7 @@
</select> </select>
<div class="input-group-append"> <div class="input-group-append">
<button type="button" class="btn btn-outline-primary" <button type="button" class="btn btn-outline-primary"
title="预览" data-toggle="tooltip" onclick="openinClient()"> title="预览" data-toggle="tooltip" onclick="openInClient()">
<img alt="Brand" src="./images/onlineide/preview.png" <img alt="Brand" src="./images/onlineide/preview.png"
class="buttonimg"> class="buttonimg">
</button> </button>

View File

@ -584,7 +584,7 @@
</div> </div>
<select id="selectMemeryFiles" class="custom-select" <select id="selectMemeryFiles" class="custom-select"
onchange="changeMemeryFiles(this.value)" onchange="changeMemoryFiles(this.value)"
style="appearance:none; -webkit-appearance:none"> style="appearance:none; -webkit-appearance:none">
<option selected>选择时间</option> <option selected>选择时间</option>
</select> </select>

View File

@ -413,7 +413,7 @@
</select> </select>
<div class="input-group-append"> <div class="input-group-append">
<button type="button" class="btn btn-outline-primary" <button type="button" class="btn btn-outline-primary"
title="预览" data-toggle="tooltip" onclick="openinClient()"> title="预览" data-toggle="tooltip" onclick="openInClient()">
<img alt="Brand" src="./images/onlineide/preview.png" <img alt="Brand" src="./images/onlineide/preview.png"
class="buttonimg"> class="buttonimg">
</button> </button>

View File

@ -394,7 +394,7 @@
<div class="input-group-append"> <div class="input-group-append">
<button type="button" class="btn btn-outline-primary" <button type="button" class="btn btn-outline-primary"
title="Preview" data-toggle="tooltip" onclick="openinClient()"> title="Preview" data-toggle="tooltip" onclick="openInClient()">
<img alt="Brand" src="./images/onlineide/preview.png" <img alt="Brand" src="./images/onlineide/preview.png"
class="buttonimg"> class="buttonimg">
</button> </button>

View File

@ -1,57 +1,70 @@
var loadContractInstances = function (event) { const CONSENSUS_TABLE = {
console.log("loadContractInstances" + event); 0: '无',
1: 'PBFT',
listContractProcess(); 2: 'RAFT',
3: 'Single'
}; };
var listContractProcess = function (event) { const RESPONSE_TYPE_TABLE = {
0: 'ALL',
1: 'MOST',
2: 'FIRST'
};
function loadContractInstances(event) {
console.log("loadContractInstances" + event);
listContractProcess();
}
function listContractProcess(event) {
console.log("listContractProcess" + event); console.log("listContractProcess" + event);
setTimeout(function () { setTimeout(function () {
var param = {}; global.wssocket.send(JSON.stringify({
param.action = "listContractProcess"; action: 'listContractProcess',
// data: event,
// 1 << 0: INIT, 1 << 1: RUNNING, 1 << 2: HANGED, 1 << 3: KILLED, 0: ALL
filters: global.myRole && global.myRole.indexOf('NodeManager') > -1 ? 0 : 7
}));
// param.data = event; global.wssocket.send(JSON.stringify({
param.fromNodePortal = true; action: 'listLeakContractProcess'
}));
global.wssocket.send(JSON.stringify(param));
var request2 = {};
request2.action = "listLeakContractProcess";
global.wssocket.send(JSON.stringify(request2));
}, 300); }, 300);
}; }
var onListContractProcess1 = function (obj) { function onListContractProcess1(obj) {
console.log("+++++++++=" + obj.data); console.log("+++++++++=" + obj.data.length);
var table = JSON.parse(obj.data); const table = JSON.parse(obj.data);
global.contractList = table; global.contractList = table;
drawContractInstanceStatusPie(table); drawContractInstanceStatusPie(table);
// drawContractInstanceTimesPie(table); // drawContractInstanceTimesPie(table);
drawContractInstanceTypeTimesPie(table); drawContractInstanceTypeTimesPie(table);
drawciTable(table); drawConInfoTable(table);
console.log(table); console.log(table);
$("#selectContractInstance").html(""); $("#selectContractInstance").html("");
var x = document.getElementById("selectContractInstance"); const x = document.getElementById("selectContractInstance");
x.options.length = 0; x.options.length = 0;
x.add(new Option("选择...", " ")); x.add(new Option("选择...", " "));
global.permissionNameMap = {}; global.permissionNameMap = {};
for (var i = 0; i < table.length; i++) { for (let i = 0; i < table.length; i++) {
if (table[i].contractStatus == "KILLED") { if (table[i]['contractStatus'] !== 'RUNNING') {
continue; continue;
} }
var option = document.createElement("option"); let option = document.createElement("option");
option.text = table[i].name; option.text = table[i].name;
console.log(table[i].name); console.log(table[i].name);
global.permissionNameMap[table[i].id] = table[i].contractPermission; global.permissionNameMap[table[i].id] = table[i]['contractPermission'];
// option.value=table[i].id; // option.value=table[i].id;
option.value = table[i].id; option.value = table[i].id;
x.add(option, null); x.add(option, null);
} }
}; }
var drawciTable = function (table) { function drawConInfoTable(table) {
if ($("#ciTabDiv").css("height") == "0px") { const ciTabDiv = $("#ciTabDiv");
console.log("drawciTabDiv: ignore"); if (ciTabDiv.css("height") === "0px") {
console.log("drawConInfoTabDiv: ignore");
return; return;
} }
var dtLang = { var dtLang = {
@ -81,78 +94,51 @@ var drawciTable = function (table) {
"sSortDescending": ": 以降序排列此列" "sSortDescending": ": 以降序排列此列"
} }
}; };
var tableHead = "<table id='ciTabDivTab' class='table display row-border' style='word-break:normal; word-break:keep-all'><thead><tr><th>序号</th><th>ID</th><th>名称</th><th>状态</th><th>端口</th><th>类型</th><th>通讯</th><th>共识</th><th>统计</th><th>次数</th><th>流量</th><th>内存</th><th>管理</th></tr></thead><tbody>"; const tableHead = `<table id='ciTabDivTab' class='table display row-border' style='word-break:keep-all;'>
var tableTail = "</tbody></table>"; <thead><tr>
<th>序号</th>
<th>ID</th>
<th>名称</th>
<th>状态</th>
<th>端口</th>
<th>类型</th>
<th>通讯</th>
<th>共识</th>
<!--<th>返回方式</th>-->
<th>次数</th>
<th>流量</th>
<th>内存</th>
<th>管理</th>
</tr>
</thead><tbody>`;
const tableTail = "</tbody></table>";
console.log("drawciTable"); console.log("drawConInfoTable");
var html = tableHead; let html = tableHead;
for (var i = 0; i < table.length; i++) { for (let i = 0; i < table.length; i++) {
if (table[i].contractStatus=="KILLED") continue; html += `<tr>
html += "<tr><td>"; <td>${i + 1}</td>
html += (i + 1); <td>${table[i].id}</td>
html += "</td> <td>"; <td><a href='/client/bdwareclient.html?self=true&contract=${table[i].id}' target='_blank'>
html += table[i].id; ${table[i].name}
html += "</td> <td>"; </a></td>
html += "<a href='/client/bdwareclient.html?self=true&contract=" <td>${table[i]['contractStatus']}</td>
+ table[i].id + "' target='_blank'>" + table[i].name + "</>"; <td>${table[i].port || '-'}</td>
html += "</td> <td>"; <td>${table[i].type}</td>
html += table[i].contractStatus; <td>${table[i]['networkType'] ? "P2P" : "TCP"}</td>
html += "</td> <td>"; <td>${table[i]['consensusType'] ? CONSENSUS_TABLE[table[i]['consensusType']] : '无'}</td>
html += table[i].port; <!--<td>${table[i].responseType ? RESPONSE_TYPE_TABLE[table[i].responseType] : '-'}</td>-->
html += "</td><td>"; <td>${table[i].times}</td>
html += table[i].type; <td>${table[i]['traffic'] || '-'}</td>
html += "</td> <td>"; <td>${table[i].storage || '-'}</td>
html += table[i].networkType == 0 ? "TCP" : "P2P"; <td style='padding:2px 12px 2px 12px'>
html += "</td><td>"; <button onclick="stopContractByID('${table[i].id}')" class="btn btn-secondary">停止</button>
var consensusType; </td>
switch (table[i].consensusType) { </tr>`
case 0:
consensusType = "无";
break;
case 1:
consensusType = "PBFT";
break;
case 2:
consensusType = "RAFT";
break;
case 3:
consensusType = "Single";
break;
}
html += consensusType;
html += "</td><td>";
var responseType;
switch (table[i].responseType) {
case 0:
responseType = "ALL";
break;
case 1:
responseType = "MOST";
break;
case 2:
responseType = "FIRST";
break;
}
html += responseType;
html += "</td><td>";
html += table[i].times;
table[i].port;
html += "</td> <td>";
html += table[i].traffic;
html += "</td> <td>";
html += table[i].storage;
html += "</td> <td style='padding:2px 12px 2px 12px'>";
html += "<button onclick='stopContractByID(\"" + table[i].id + "\")' class='btn btn-secondary'>" + "停止</button>"
//table[i].resultCheck;
// html += "</td> <td>";
// html += "<button class='btn btn-outline-secondary' type='button'
// onclick='viewContractInstance("+ table[i].contractID +
// ")'>更多</button>";
html += "</td> </tr>";
} }
html += tableTail; html += tableTail;
html = "<h5 class='card-title'>合约实例列表</h5>" + html; html = "<h5 class='card-title'>合约实例列表</h5>" + html;
$("#ciTabDiv").html(html); ciTabDiv.html(html);
$("#ciTabDivTab").DataTable( $("#ciTabDivTab").DataTable(
{ {
@ -161,7 +147,7 @@ var drawciTable = function (table) {
dataIndex) { dataIndex) {
}, },
"headerCallback": function (thead, data, start, end, display) { "headerCallback": function (thead/*, data, start, end, display*/) {
$(thead).css("background", primaryColor); $(thead).css("background", primaryColor);
$(thead).css("color", "white"); $(thead).css("color", "white");
$(thead).children().css("background", primaryColor); $(thead).children().css("background", primaryColor);
@ -174,7 +160,7 @@ var drawciTable = function (table) {
"columnDefs": [ "columnDefs": [
{ {
"targets": 1, "targets": 1,
"render": function (data, type, row, meta) { "render": function (data/*, type, row, meta*/) {
if (data.length > 8) if (data.length > 8)
return "<span title='" + data + "'>" return "<span title='" + data + "'>"
+ data.substring(0, 8) + data.substring(0, 8)
@ -185,46 +171,48 @@ var drawciTable = function (table) {
},] },]
}); });
}; }
var stopContractByID = function (contractID) {
$("#dialogBodyDiv").html("是否停止合约ContractID:" + contractID); function stopContractByID(contractID) {
$("#dialogBodyDiv").html("是否停止合约ContractID" + contractID);
showDialog("请确认", function () { showDialog("请确认", function () {
var request = {}; global.wssocket.send(JSON.stringify({
request.action = "killContractProcess"; action: 'killContractProcess',
request.requestID = new Date().getTime() + ""; requestID: new Date().getTime().toString(),
request.id = contractID; id: contractID
global.wssocket.send(JSON.stringify(request)); }));
}); });
}; }
var drawContractInstanceStatusPie = function (table) {
if ($("#ciStatusPieDiv").css("height") == "0px") { function drawContractInstanceStatusPie(table) {
const ciStatusPieDiv = $("#ciStatusPieDiv")
if (ciStatusPieDiv.css("height") === "0px") {
console.log("drawContractInstanceStatusPie: ignore"); console.log("drawContractInstanceStatusPie: ignore");
return; return;
} }
$("#ciStatusPieDiv") $(ciStatusPieDiv).html(
.html( "<div class='col-12' id='ciStatusPieDivCanv' style='width:100%; min-height: 150px; padding: 0;'></div>");
"<div class='col-12' id='ciStatusPieDivCanv' style='width:100%; min-height: 150px; padding: 0px'></div>"); const result = {};
var result = {}; for (let i = 0; i < table.length; i++) {
for (var i = 0; i < table.length; i++) { const obj = table[i];
var obj = table[i]; if (!result[obj['contractStatus']]) {
if (result[obj.contractStatus] == undefined) { result[obj['contractStatus']] = 1;
result[obj.contractStatus] = 1;
} else } else
result[obj.contractStatus]++; result[obj['contractStatus']]++;
} }
global.result = result; global.result = result;
var dataList = []; const dataList = [];
var valDataList = []; const valDataList = [];
for (var key in result) { for (const key in result) {
dataList.push(key); dataList.push(key);
var l = {}; valDataList.push({
l.name = key name: key,
l.value = result[key]; value: result[key]
valDataList.push(l); });
} }
var myChart = echarts.init($("#ciStatusPieDivCanv")[0], 'walden'); const myChart = echarts.init($("#ciStatusPieDivCanv")[0], 'walden');
var option222 = { const option222 = {
tooltip: { tooltip: {
trigger: 'item', trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)' formatter: '{a} <br/>{b}: {c} ({d}%)'
@ -261,35 +249,35 @@ var drawContractInstanceStatusPie = function (table) {
}] }]
}; };
myChart.setOption(option222); myChart.setOption(option222);
}; }
var drawContractInstanceTimesPie = function (table) { function drawContractInstanceTimesPie(table) {
if ($("#ciTimesPieDiv").css("height") == "0px") { const ciTimesPieDiv = $("#ciTimesPieDiv");
if (ciTimesPieDiv.css("height") === "0px") {
console.log("drawContractInstanceTimesPie: ignore"); console.log("drawContractInstanceTimesPie: ignore");
return; return;
} }
$("#ciTimesPieDiv") ciTimesPieDiv.html(
.html( "<div class='col-12' id='ciTimesPieDivCanv' style='width:100%; min-height: 150px; padding: 0;'></div>");
"<div class='col-12' id='ciTimesPieDivCanv' style='width:100%; min-height: 150px; padding: 0px'></div>"); const result = {};
var result = {}; for (let i = 0; i < table.length; i++) {
for (var i = 0; i < table.length; i++) { const obj = table[i];
var obj = table[i];
result[obj.name] = obj.times; result[obj.name] = obj.times;
} }
global.result = result; global.result = result;
var dataList = []; const dataList = [];
var valDataList = []; const valDataList = [];
for (var key in result) { for (const key in result) {
dataList.push(key); dataList.push(key);
var l = {}; valDataList.push({
l.name = key name: key,
l.value = result[key]; value: result[key]
valDataList.push(l); });
} }
var myChart = echarts.init($("#ciTimesPieDivCanv")[0], 'walden'); const myChart = echarts.init($("#ciTimesPieDivCanv")[0], 'walden');
var option222 = { const option222 = {
tooltip: { tooltip: {
trigger: 'item', trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)' formatter: '{a} <br/>{b}: {c} ({d}%)'
@ -326,18 +314,19 @@ var drawContractInstanceTimesPie = function (table) {
}] }]
}; };
myChart.setOption(option222); myChart.setOption(option222);
}; }
var changeContractInstance = function (obj) { function changeContractInstance(obj) {
let i;
console.log(obj); console.log(obj);
global.contractInstance = obj; global.contractInstance = obj;
console.log(typeof (obj)); console.log(typeof (obj));
showPermissionList(global.contractInstance); showPermissionList(global.contractInstance);
var contract; let contract;
for (var i = 0; i < global.contractList.length; i++) { for (i = 0; i < global.contractList.length; i++) {
if (global.contractList[i].id == obj) { if (global.contractList[i].id === obj) {
contract = global.contractList[i]; contract = global.contractList[i];
global.instance = contract; global.instance = contract;
global.instanceName = contract.name; global.instanceName = contract.name;
@ -350,79 +339,82 @@ var changeContractInstance = function (obj) {
} }
$("#selectContractFunction").html(""); $("#selectContractFunction").html("");
var x = document.getElementById("selectContractFunction"); const x = document.getElementById("selectContractFunction");
x.options.length = 0; x.options.length = 0;
x.add(new Option("选择方法...", " ")); x.add(new Option("选择方法...", " "));
console.log("contract ", contract); console.log("contract ", contract);
for (var i = 0; i < contract.exportedFunctions.length; i++) { for (i = 0; i < contract['exportedFunctions'].length; i++) {
var option = document.createElement("option"); const option = document.createElement("option");
option.text = contract.exportedFunctions[i].functionName; option.text = contract['exportedFunctions'][i].functionName;
option.value = contract.exportedFunctions[i].functionName; option.value = contract['exportedFunctions'][i].functionName;
x.add(option, null); x.add(option, null);
} }
}; }
var changeMemeryFiles = function (obj) { function changeMemoryFiles(obj) {
console.log(obj); console.log(obj);
global.memoryFile = obj; global.memoryFile = obj;
}; }
var executeContractWithDynamicResult = function () { function executeContractWithDynamicResult() {
const argDiv = $("#arg")[0]
console.log("executeContractWithDynamicResult"); console.log("executeContractWithDynamicResult");
var request = {}; const request = {};
request.action = "executeContract"; request.action = "executeContract";
request.requestID = new Date().getTime() + ""; request.requestID = new Date().getTime() + "";
request.contractName = global.contractInstance; request.contractName = global.contractInstance;
request.sequencing = global.instanceSequencing; request.sequencing = global.instanceSequencing;
request.useP2P = global.useP2P; request.useP2P = global.useP2P;
request.isDebug = executeContractAsDebug.checked; request.isDebug = executeContractAsDebug.checked;
var operation = $("#selectContractFunction")[0].value; const operation = $("#selectContractFunction")[0].value;
if (operation == " " && operation == undefined) { if (operation === " " && !operation) {
myToast("执行合约", "请选择合约方法!"); myToast("执行合约", "请选择合约方法!");
return; return;
} }
request.arg = "{\"action\":\"" + operation + "\",\"arg\":\"" request.arg = `{"action":"${operation}","arg":"${argDiv.value}"}`;
+ $("#arg")[0].value + "\"}";
request.pubkey = global.sm2Key.publicKey; request.pubkey = global.sm2Key.publicKey;
request.withDyanmicAnalysis = true; request.withDyanmicAnalysis = true;
request.signature = sm2.doSignature(request.contractID + "|" + operation request.signature = sm2.doSignature(
+ "|" + $("#arg")[0].value + "|" + global.sm2Key.publicKey, `${request.contractID}|${operation}|${argDiv.value}|${global.sm2Key.publicKey}`,
global.sm2Key.privateKey, {hash: true, der: true}); global.sm2Key.privateKey,
{hash: true, der: true});
localStorage.setItem("persisArg", JSON.stringify(request)); localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; }
var executeContract = function () { function executeContract() {
var request = {}; const argDiv = $('#arg')[0];
const request = {};
request.action = "executeContract"; request.action = "executeContract";
request.requestID = new Date().getTime() + ""; request.requestID = new Date().getTime() + "";
request.contractID = global.contractInstance; request.contractID = global.contractInstance;
var operation = $("#selectContractFunction")[0].value; const operation = $("#selectContractFunction")[0].value;
if (operation == " " && operation == undefined) { if (operation === " " && !operation) {
myToast("执行合约", "请选择合约方法!"); myToast("执行合约", "请选择合约方法!");
return; return;
} }
request.operation = operation; request.operation = operation;
request.arg = $("#arg")[0].value; request.arg = argDiv.value;
request.pubkey = global.sm2Key.publicKey; request.pubkey = global.sm2Key.publicKey;
request.isDebug = executeContractAsDebug.checked; request.isDebug = executeContractAsDebug.checked;
console.log(request.arg); console.log(request.arg);
request.signature = sm2.doSignature(request.contractID + "|" + operation request.signature = sm2.doSignature(
+ "|" + $("#arg")[0].value + "|" + global.sm2Key.publicKey, `${request.contractID}|${operation}|${argDiv.value}|${global.sm2Key.publicKey}`,
global.sm2Key.privateKey, {hash: true, der: true}); global.sm2Key.privateKey,
{hash: true, der: true});
localStorage.setItem("persisArg", JSON.stringify(request)); localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; }
var onExecuteResult = function (obj) { function onExecuteResult(obj) {
console.log("onExecuteResult obj.data", obj.data); console.log("onExecuteResult obj.data", obj.data);
try { try {
var result = obj; const result = obj;
var styleTail = "<br>字符串格式"; let styleTail = "<br>字符串格式";
$("#responseStatus").html("执行状态:" + result.status); $("#responseStatus").html("执行状态:" + result.status);
if (result.analysis != undefined) { if (result['analysis']) {
$("#responseArea")[0].value = "执行结果:" + result.result + "\n动态分析结果:" $("#responseArea")[0].value = "执行结果:" + result.result + "\n动态分析结果:"
+ result.analysis; + result['analysis'];
} else { } else {
if (result.result instanceof Object) { if (result.result instanceof Object) {
$("#responseArea")[0].value = JSON.stringify(result.result); $("#responseArea")[0].value = JSON.stringify(result.result);
@ -430,27 +422,25 @@ var onExecuteResult = function (obj) {
} else } else
$("#responseArea")[0].value = result.result; $("#responseArea")[0].value = result.result;
} }
$("#responseID").html("请求ID:" + obj.responseID); $("#responseID").html(`请求ID:${obj['responseID']}`);
$("#responseTime").html("响应时间:" + obj.executeTime + ("ms") + styleTail); $("#responseTime").html(`响应时间:${obj['executeTime']}ms${styleTail}`);
} catch (e) { } catch (e) {
$("#responseStatus").html("执行状态:Fail"); $("#responseStatus").html("执行状态Failed");
$("#responseArea")[0].value = obj.data; $("#responseArea")[0].value = obj.data;
$("#responseID").html("请求ID:" + obj.responseID); $("#responseID").html(`请求ID${obj['responseID']}`);
$("#responseTime").html("响应时间:" + obj.executeTime + ("ms")); $("#responseTime").html(`响应时间:${obj['executeTime']}ms`);
} }
}; }
function onHashResult(obj) {
var onHashResult = function (obj) {
$("#hashResult").html("数链指纹:" + obj.data); $("#hashResult").html("数链指纹:" + obj.data);
}; }
function drawCPTable(table) {
var drawCPTable = function (table) {
console.log("drawCPTable"); console.log("drawCPTable");
global.contractprocess = table.data; global.contractprocess = table.data;
if ($("#ciTabDiv").css("height") == "0px") { if ($("#ciTabDiv").css("height") === "0px") {
console.log("drawciTabDiv: ignore"); console.log("drawCPTableDiv: ignore");
return; return;
} }
var dtLang = { var dtLang = {
@ -480,39 +470,39 @@ var drawCPTable = function (table) {
"sSortDescending": ": 以降序排列此列" "sSortDescending": ": 以降序排列此列"
} }
}; };
var tableHead = "<table id='cpTabDivTab' class='table display row-border'><thead><tr><th>序号</th><th>PID</th><th>是否泄漏</th><th>启动时间</th><th>CPUUser</th><th>CPUSyss</th><th>resident</th><th>memory</th><th>管理</th></tr></thead><tbody>"; const tableHead = `<table id='cpTabDivTab' class='table display row-border'>
var tableTail = "</tbody></table>"; <thead><tr>
<th>序号</th>
<th>PID</th>
<th>是否泄漏</th>
<th>启动时间</th>
<th>CPUUser</th>
<th>CPUSyss</th>
<th>resident</th>
<th>memory</th>
<th>管理</th>
</tr></thead><tbody>`;
const tableTail = "</tbody></table>";
table = table.data; table = table.data;
console.log("drawciTable"); console.log("drawConInfoTable");
var html = tableHead; let html = tableHead;
for (var i = 0; i < table.length; i++) { for (let i = 0; i < table.length; i++) {
html += "<tr><td>"; html += `<tr>
html += (i + 1); <td>${i + 1}</td>
html += "</td> <td>"; <td>${table[i].pid}</td>
html += table[i].pid; <td>${table[i]['isLeak']}</td>
html += "</td> <td>"; <td>${new Date(table[i]['cpuStart']).toLocaleString()}/td>
html += table[i].isLeak; <td>${table[i]['cpuTotal']}</td>
html += "</td> <td>"; <td>${table[i]['cpuSys']}</td>
html += new Date(table[i].cpuStart).toLocaleString(); <td>${(table[i]['resident'] / (1024 * 1024)).toFixed(2)}MB</td>
html += "</td> <td>"; <td>${(table[i]['memsize'] / (1024 * 1024)).toFixed(2)}MB</td>
html += table[i].cpuTotal; <td style='padding:2px 12px 2px 12px'>
html += "</td> <td>"; <button onclick="stopContractByPID('${table[i].pid}')" class='btn btn-secondary'>停止</button>
html += table[i].cpuSys; </td>
html += "</td> <td>"; </tr>`
html += ((table[i].resident) / (1024 * 1024)).toFixed(2) + "MB";
html += "</td><td>";
html += ((table[i].memsize) / (1024 * 1024)).toFixed(2) + "MB";
html += "</td> <td style='padding:2px 12px 2px 12px'>";
html += "<button onclick='stopContractByPID(\"" + table[i].pid + "\")' class='btn btn-secondary'>" + "停止</button>"
//table[i].resultCheck;
// html += "</td> <td>";
// html += "<button class='btn btn-outline-secondary' type='button'
// onclick='viewContractInstance("+ table[i].contractID +
// ")'>更多</button>";
html += "</td> </tr>";
} }
html += tableTail; html += tableTail;
html = "<h5 class='card-title'>合约进程列表</h5>" + html; html = `<h5 class='card-title'>合约进程列表</h5>${html}`;
$("#cpTabDiv").html(html); $("#cpTabDiv").html(html);
$("#cpTabDivTab").DataTable( $("#cpTabDivTab").DataTable(
@ -522,7 +512,7 @@ var drawCPTable = function (table) {
dataIndex) { dataIndex) {
}, },
"headerCallback": function (thead, data, start, end, display) { "headerCallback": function (thead/*, data, start, end, display*/) {
$(thead).css("background", primaryColor); $(thead).css("background", primaryColor);
$(thead).css("color", "white"); $(thead).css("color", "white");
$(thead).children().css("background", primaryColor); $(thead).children().css("background", primaryColor);
@ -535,7 +525,7 @@ var drawCPTable = function (table) {
"columnDefs": [ "columnDefs": [
{ {
"targets": 1, "targets": 1,
"render": function (data, type, row, meta) { "render": function (data/*, type, row, meta*/) {
if (data.length > 10) if (data.length > 10)
// return "<span title='" + data + "'>" // return "<span title='" + data + "'>"
// + data.substring(0, 10) // + data.substring(0, 10)
@ -547,16 +537,17 @@ var drawCPTable = function (table) {
},] },]
}); });
}; }
var stopContractByPID = function (pid) {
function stopContractByPID(pid) {
$("#dialogBodyDiv").html("是否停止PID:" + pid); $("#dialogBodyDiv").html("是否停止PID:" + pid);
showDialog("请确认", function () { showDialog("请确认", function () {
var request = {}; global.wssocket.send(JSON.stringify({
request.action = "killProcessByPID"; action: 'killProcessByPID',
request.pid = pid; pid: pid
global.wssocket.send(JSON.stringify(request)); }));
var request2 = {}; global.wssocket.send(JSON.stringify({
request2.action = "listLeakContractProcess"; action: 'listLeakContractProcess'
global.wssocket.send(JSON.stringify(request2)); }));
}); });
}; }

View File

@ -28,10 +28,10 @@ function WSHandler(event) {
onDeleteFile(obj); onDeleteFile(obj);
break; break;
case "onStartContract": case "onStartContract":
onStartContract(obj); // onStartContract(obj);
break; // break;
case "onStartContractAsDebug": case "onStartContractAsDebug":
onStartContractAsDebug(obj); onStartContract(obj);
break; break;
case "onListContractProcess": case "onListContractProcess":
onListContractProcess(obj); onListContractProcess(obj);
@ -140,9 +140,10 @@ function getControlWsUrl(host) {
} }
function initWSocket() { function initWSocket() {
console.log("[nodecenterManagement.js] initWSocket : "); console.log("[OnlineIDE.js] initWSocket : ");
let host = document.location.host; let host = document.location.host;
let url = getControlWsUrl(global.urlparam && global.urlparam.nodeAddr ? global.urlparam.nodeAddr : host); let url = getControlWsUrl(
global.urlparam && global.urlparam['nodeAddr'] ? global.urlparam['nodeAddr'] : host);
// console.log("connect ws:" + url); // console.log("connect ws:" + url);
global.wssocket = createWssocket(url, function () { global.wssocket = createWssocket(url, function () {
getSession(); getSession();
@ -201,7 +202,7 @@ function onStartContract(data) {
showDialog("部署合约成功", function() { showDialog("部署合约成功", function() {
}); });
}*/ }*/
startResult.innerText = result.status + "(" + data.executeTime + "ms" + ")"; startResult.innerText = `${result.status}(${data['executeTime']}ms)`;
if (result.status !== "Success") { if (result.status !== "Success") {
let body = "<div class='input-group mb-3'>"; let body = "<div class='input-group mb-3'>";
body += " <textarea id='onStartContractFailedContent' class='form-control' style='min-height:300px' ></textarea>"; body += " <textarea id='onStartContractFailedContent' class='form-control' style='min-height:300px' ></textarea>";
@ -213,33 +214,33 @@ function onStartContract(data) {
} }
} }
function onStartContractAsDebug(data) { // function onStartContractAsDebug(data) {
// console.log(data); // // console.log(data);
const result = JSON.parse(data.data); // const result = JSON.parse(data.data);
/* if (result.isInsnLimit) { // /* if (result.isInsnLimit) {
global.withEvaluatesAnalysis = true; // global.withEvaluatesAnalysis = true;
$("#dialogBodyDiv").text("此合约在执行时会消耗gas,请在执行前进行预估,根据预估值给出相应的值,建议给出的值大于预估值"); // $("#dialogBodyDiv").text("此合约在执行时会消耗gas,请在执行前进行预估,根据预估值给出相应的值,建议给出的值大于预估值");
showDialog("部署合约成功", function() { // showDialog("部署合约成功", function() {
}); // });
}*/ // }*/
startResult.innerText = result.status + "(" + data.executeTime + "ms" + ")"; // startResult.innerText = `${result.status}(${data['executeTime']}ms)`;
if (result.status !== "Success") { // if (result.status !== "Success") {
let body = "<div class='input-group mb-3'>"; // let body = "<div class='input-group mb-3'>";
body += " <textarea id='onStartContractFailedContent' class='form-control' style='min-height:300px' ></textarea>"; // body += " <textarea id='onStartContractFailedContent' class='form-control' style='min-height:300px' ></textarea>";
body += " </div>"; // body += " </div>";
$("#dialogBodyDiv").html(body); // $("#dialogBodyDiv").html(body);
$("#onStartContractFailedContent")[0].value = result.result // $("#onStartContractFailedContent")[0].value = result.result
showDialog("部署合约失败", function () { // showDialog("部署合约失败", function () {
}); // });
} // }
} // }
function onKillContractProcess(data) { function onKillContractProcess(data) {
// console.log(data); // console.log(data);
if (data.data === "success") { if (data.data === "success") {
listContracts(); listContracts();
} }
stopResult.innerText = data.data + "(" + data.executeTime + "ms" + ")"; stopResult.innerText = `${data.data}(${data['executeTime']}ms)`;
} }
function onKillAllContract(data) { function onKillAllContract(data) {
@ -275,7 +276,7 @@ function onQueryContractInstanceInfoByDOI(data) {
initContractInstanceInfoArea(); initContractInstanceInfoArea();
// console.log(data); // console.log(data);
$("#contractInstanceInfoTitle") $("#contractInstanceInfoTitle")
.html(" (" + data.executeTime + "ms)"); .html(` (${data['executeTime']}ms)`);
global.contractInstanceInfoEditor.setValue(data.data); global.contractInstanceInfoEditor.setValue(data.data);
let totalLines = global.contractInstanceInfoEditor.lineCount(); let totalLines = global.contractInstanceInfoEditor.lineCount();
@ -292,7 +293,7 @@ function onImportContractInstanceCodeByDOI(data) {
initContractInstanceInfoArea(); initContractInstanceInfoArea();
// console.log(data); // console.log(data);
$("#contractInstanceInfoTitle") $("#contractInstanceInfoTitle")
.html(" (" + data.executeTime + "ms)"); .html(` (${data['executeTime']}ms)`);
global.contractInstanceInfoEditor.setValue(data.data); global.contractInstanceInfoEditor.setValue(data.data);
let totalLines = global.contractInstanceInfoEditor.lineCount(); let totalLines = global.contractInstanceInfoEditor.lineCount();
@ -307,14 +308,12 @@ function onImportContractInstanceCodeByDOI(data) {
global.wssocket.send("{\"action\":\"listProjects\",\"isPrivate\":true}"); global.wssocket.send("{\"action\":\"listProjects\",\"isPrivate\":true}");
} }
function onListContractProcess(data) { function onListContractProcess(data) {
// console.log(data); // console.log(data);
mainVue.contracts = []; mainVue.contracts = [];
var list = JSON.parse(data.data); const list = JSON.parse(data.data);
for (var i = 0; i < list.length; i++) { for (let i = 0; i < list.length; i++) {
if (list[i].contractStatus != "KILLED") { if (list[i].contractStatus !== "KILLED") {
mainVue.contracts.push(list[i]); mainVue.contracts.push(list[i]);
} }
} }
@ -359,25 +358,25 @@ function initResponseAndOutputArea() {
} }
function onExecuteResult(obj) { function onExecuteResult(obj) {
const executeResultTitleEl = $("#executeResultTitle")
const data = obj; const data = obj;
$("#executeResultTitle") executeResultTitleEl
.html(data.status + " (" + obj.executeTime + "ms) 未知格式"); .html(`${data.status} (${obj['executeTime']}ms) 未知格式`);
if (data.result instanceof Object) { if (data.result instanceof Object) {
$("#executeResultTitle") executeResultTitleEl
.html(data.status + " (" + obj.executeTime + "ms) JSON格式"); .html(`${data.status} (${obj['executeTime']}ms) JSON格式`);
global.responseEditor.setValue(JSON.stringify(data.result)); global.responseEditor.setValue(JSON.stringify(data.result));
} else if (typeof data.result == 'string') { } else if (typeof data.result == 'string') {
$("#executeResultTitle") executeResultTitleEl
.html(data.status + " (" + obj.executeTime + "ms) 字符串格式"); .html(`${data.status} (${obj['executeTime']}ms) 字符串格式`);
global.responseEditor.setValue(data.result); global.responseEditor.setValue(data.result);
} else { } else {
if (typeof data.result == 'number') { if (typeof data.result == 'number') {
$("#executeResultTitle") executeResultTitleEl
.html(data.status + " (" + obj.executeTime + "ms) 数值格式"); .html(`${data.status} (${obj['executeTime']}ms) 数值格式`);
} else if (typeof data.result == 'boolean') { } else if (typeof data.result == 'boolean') {
$("#executeResultTitle") executeResultTitleEl
.html(data.status + " (" + obj.executeTime + "ms) 布尔型格式"); .html(`${data.status} (${obj['executeTime']}ms) 布尔型格式`);
} }
global.responseEditor.setValue(data.result.toString()); global.responseEditor.setValue(data.result.toString());
} }
@ -391,9 +390,9 @@ function onExecuteResult(obj) {
}, { }, {
line: totalLines line: totalLines
}); });
if (data.analysis && data.analysis.length > 0) { // if (data['analysis'] && data['analysis'].length > 0) {
// displayOutputStr(data.analysis); // displayOutputStr(data.analysis);
} // }
} }
function onGenerateReadme(obj) { function onGenerateReadme(obj) {

923
js/cm.js
View File

@ -1,527 +1,528 @@
var WSHandler = function(event) { var WSHandler = function (event) {
// console.log(event); // console.log(event);
data = event.data; data = event.data;
// console.log(" -->" + data); // console.log(" -->" + data);
try { try {
var obj = JSON.parse(data); var obj = JSON.parse(data);
switch (obj.action) { switch (obj.action) {
case 'ping': case 'ping':
case 'poing': case 'poing':
break; break;
case 'onExecuteResult': case 'onExecuteResult':
onExecuteResult(obj); onExecuteResult(obj);
break; break;
case 'onListContractProcess': case 'onListContractProcess':
onListContractProcess(obj); onListContractProcess(obj);
break; break;
case 'onStartContract': case 'onStartContract':
onStartContract(obj); onStartContract(obj);
break; break;
case 'onKillContractProcess': case 'onKillContractProcess':
logComm(obj); logComm(obj);
break; break;
case 'onKillAllContract': case 'onKillAllContract':
onKillAllContract(obj); onKillAllContract(obj);
break; break;
case 'onOutputStream': case 'onOutputStream':
displayOutput(obj); displayOutput(obj);
break; break;
case 'onSaveFile': case 'onSaveFile':
onSaveFile(obj); onSaveFile(obj);
break; break;
case 'uploadNext': case 'uploadNext':
onUploadNext(obj); onUploadNext(obj);
break; break;
case 'sendNextSegment': case 'sendNextSegment':
global.wssocket.sendNextSegment(); global.wssocket.sendNextSegment();
break; break;
case 'sendSeg': case 'sendSeg':
receiveSeg(obj); receiveSeg(obj);
break; break;
case 'onException': case 'onException':
logException(obj); logException(obj);
break; break;
case 'onHashResult': case 'onHashResult':
onHashResult(obj); onHashResult(obj);
break; break;
case 'onDumpContract': case 'onDumpContract':
onDumpContract(obj); onDumpContract(obj);
break; break;
default: default:
displayOutput(obj); displayOutput(obj);
break; break;
} }
} catch (err) { } catch (err) {
console.log(err); console.log(err);
} }
}; };
var logException = function(obj) { var logException = function (obj) {
global.tempobj = obj; global.tempobj = obj;
$("#responseStatus").html("Exception (" + obj.executeTime + "ms)"); $("#responseStatus").html("Exception (" + obj.executeTime + "ms)");
displayOutput(obj); displayOutput(obj);
}; };
var logComm = function(obj) { var logComm = function (obj) {
console.log(obj); console.log(obj);
}; };
var displayOutput = function(obj) { var displayOutput = function (obj) {
displayOutputStr(obj.data); displayOutputStr(obj.data);
}; };
var displayOutputStr = function(str) { var displayOutputStr = function (str) {
console.log("[cm.js] displayOutput:" + str); console.log("[cm.js] displayOutput:" + str);
}; };
var getControlWsUrl = function(host) { var getControlWsUrl = function (host) {
var prefix = "ws://"; var prefix = "ws://";
if (document.location.href.startsWith("https")) if (document.location.href.startsWith("https"))
prefix = "wss://"; prefix = "wss://";
var path = document.location.pathname.lastIndexOf("/"); var path = document.location.pathname.lastIndexOf("/");
path = document.location.pathname.substr(0, path + 1); path = document.location.pathname.substr(0, path + 1);
path += "SCExecutor"; path += "SCExecutor";
return prefix + host + path; return prefix + host + path;
}; };
var initWSocket = function() { var initWSocket = function () {
var host = getHost(); var host = getHost();
var url = getControlWsUrl(host); var url = getControlWsUrl(host);
global.wssocket = createWssocket(url, function() { global.wssocket = createWssocket(url, function () {
listContractProcess(); listContractProcess();
}, WSHandler); }, WSHandler);
}; };
// ====== wsHandler // ====== wsHandler
var onStartContract = function(obj) { var onStartContract = function (obj) {
// console.log(obj); // console.log(obj);
var result = JSON.parse(obj.data); var result = JSON.parse(obj.data);
$("#responseStatus").html(result.status + " (" + obj.executeTime + "ms)"); $("#responseStatus").html(result.status + " (" + obj.executeTime + "ms)");
global.responseEditor.setValue(result.result); global.responseEditor.setValue(result.result);
// $("#tabdiv").editableSelect('add', obj.cid); // $("#tabdiv").editableSelect('add', obj.cid);
// $("#tabdiv").editableSelect()[0].value = obj.cid; // $("#tabdiv").editableSelect()[0].value = obj.cid;
}; };
var onExecuteResult = function(obj) { var onExecuteResult = function (obj) {
// console.log(obj); // console.log(obj);
var data = JSON.parse(obj.data); var data = JSON.parse(obj.data);
$("#responseStatus").html(data.status + " (" + obj.executeTime + "ms)"); $("#responseStatus").html(data.status + " (" + obj.executeTime + "ms)");
global.responseEditor.setValue(data.result); global.responseEditor.setValue(data.result);
// console.log(data); // console.log(data);
var totalLines = global.responseEditor.lineCount(); var totalLines = global.responseEditor.lineCount();
global.responseEditor.autoFormatRange({ global.responseEditor.autoFormatRange({
line : 0, line: 0,
ch : 0 ch: 0
}, { }, {
line : totalLines line: totalLines
}); });
if (data.analysis != undefined && data.analysis.length > 0) { if (data.analysis != undefined && data.analysis.length > 0) {
// displayOutputStr(data.analysis); // displayOutputStr(data.analysis);
} }
}; };
var onListContractProcess = function(obj) { var onListContractProcess = function (obj) {
var data = JSON.parse(obj.data); var data = JSON.parse(obj.data);
global.contracts = data; global.contracts = data;
var html = ""; var html = "";
// $("#tabdiv").html(""); // $("#tabdiv").html("");
global.contractName2ID = {}; global.contractName2ID = {};
for (var i = 0; i < data.length; i++) { for (var i = 0; i < data.length; i++) {
global.contractName2ID[data[i].name] = data[i].id; global.contractName2ID[data[i].name] = data[i].id;
html += "<li class=\"ui-widget-content\">" + data[i].name + "</li>"; html += "<li class=\"ui-widget-content\">" + data[i].name + "</li>";
// $("#tabdiv").append( // $("#tabdiv").append(
// $("<option></option>").attr("value", data[i].id).text( // $("<option></option>").attr("value", data[i].id).text(
// data[i].id)); // data[i].id));
} }
$("#contractList").html(html); $("#contractList").html(html);
$("#contractList").selectable( $("#contractList").selectable(
{ {
stop : function() { stop: function () {
var result = ""; var result = "";
global.selectedContracts = []; global.selectedContracts = [];
global.selectedContractIndexs = []; global.selectedContractIndexs = [];
$(".ui-selected", this).each(function() { $(".ui-selected", this).each(function () {
var index = $("#contractList li").index(this); var index = $("#contractList li").index(this);
global.selectedContracts.push(this.innerText); global.selectedContracts.push(this.innerText);
global.selectedContractIndexs.push(index); global.selectedContractIndexs.push(index);
}); });
// console.log("[cm.js] selectContractResult:" // console.log("[cm.js] selectContractResult:"
// + global.selectedContracts); // + global.selectedContracts);
} }
}); });
// $("#tabdiv").selectmenu("refresh"); // $("#tabdiv").selectmenu("refresh");
// $("#tabdiv").html(html); // $("#tabdiv").html(html);
// $("yourid/class here").append($("<option></option>").attr("value", // $("yourid/class here").append($("<option></option>").attr("value",
// youroption-value).text(youroption-text)); // youroption-value).text(youroption-text));
}; };
var onSaveFile = function(obj) { var onSaveFile = function (obj) {
alert("Save file:" + obj.data); alert("Save file:" + obj.data);
}; };
var onKillAllContract = function(obj) { var onKillAllContract = function (obj) {
customAlert(obj.data); customAlert(obj.data);
}; };
var onHashResult = function(obj) { var onHashResult = function (obj) {
$("#hashResult").html("刚刚操作的数链指纹:" + obj.data); $("#hashResult").html("刚刚操作的数链指纹:" + obj.data);
}; };
var onDumpContract = function(obj) { var onDumpContract = function (obj) {
// console.log("DumpResult:" + obj.data); // console.log("DumpResult:" + obj.data);
if (obj.data == "success") { if (obj.data == "success") {
listDumpMemoryDir(); listDumpMemoryDir();
} }
}; };
// ====== wsHandler done! // ====== wsHandler done!
var switchContract = function(off) { var switchContract = function (off) {
// var contract = global.contracts[off]; // var contract = global.contracts[off];
// global.scriptEditor.setValue(contract.script); // global.scriptEditor.setValue(contract.script);
// $("#tabdiv")[0].value = contract.id; // $("#tabdiv")[0].value = contract.id;
var pingObj = {}; var pingObj = {};
pingObj.action = "connectTo"; pingObj.action = "connectTo";
pingObj.name = $("#tabdiv")[0].value; pingObj.name = $("#tabdiv")[0].value;
pingObj.id = global.contractName2ID[pingObj.name]; pingObj.id = global.contractName2ID[pingObj.name];
global.wssocket.send(JSON.stringify(pingObj)); global.wssocket.send(JSON.stringify(pingObj));
} }
var countChar = function(str, c) { var countChar = function (str, c) {
var ret = 0; var ret = 0;
for (var i = 0; i < str.length; i++) { for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == c) if (str.charAt(i) == c)
ret++; ret++;
} }
return ret; return ret;
} }
var generate = function() { var generate = function () {
$.ajax({ $.ajax({
url : "./SCManager?action=generatePrivateKey", url: "./SCManager?action=generatePrivateKey",
dataType : "json" dataType: "json"
}).done(function(result) { }).done(function (result) {
if (result.status) { if (result.status) {
localStorage.setItem("PrivKey", result.data); localStorage.setItem("PrivKey", result.data);
alert("Key successfully generated!"); alert("Key successfully generated!");
initRest(); initRest();
} }
}); });
} }
var initGlobal = function() { var initGlobal = function () {
window.global = {}; window.global = {};
global.privKey = localStorage.getItem("PrivKey"); global.privKey = localStorage.getItem("PrivKey");
if (global.privKey == undefined || global.privKey == null if (global.privKey == undefined || global.privKey == null
|| global.privKey.length < 100) { || global.privKey.length < 100) {
generate(); generate();
} else } else
initRest(); initRest();
} }
var setMainHost = function() { var setMainHost = function () {
var mainHost = $("#targetHost")[0].value; var mainHost = $("#targetHost")[0].value;
localStorage.setItem("mainHost", mainHost); localStorage.setItem("mainHost", mainHost);
} }
var initRest = function() { var initRest = function () {
var mainHost = localStorage.getItem("mainHost"); var mainHost = localStorage.getItem("mainHost");
if (mainHost == undefined) { if (mainHost == undefined) {
localStorage.setItem("mainHost", "39.106.6.6:8080"); localStorage.setItem("mainHost", "39.106.6.6:8080");
mainHost = localStorage.getItem("mainHost"); mainHost = localStorage.getItem("mainHost");
} }
$("#targetHost")[0].value = mainHost; $("#targetHost")[0].value = mainHost;
}; };
var onUploadNext = function() { var onUploadNext = function () {
var request = {}; var request = {};
request.action = "startContract"; request.action = "startContract";
request.owner = global.privKey; request.owner = global.privKey;
request.isPartial = false; request.isPartial = false;
request.script = global.toSend; request.script = global.toSend;
if (request.script.length > 1024) { if (request.script.length > 1024) {
global.toSend = request.script.substr(1024); global.toSend = request.script.substr(1024);
request.script = request.script.substr(0, 1024); request.script = request.script.substr(0, 1024);
request.isPartial = true; request.isPartial = true;
} else { } else {
global.toSend = ""; global.toSend = "";
} }
// console.log("Upload nextPart:"); // console.log("Upload nextPart:");
// console.log(JSON.stringify(request)); // console.log(JSON.stringify(request));
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; };
var disposeContract = function(request, host, contractIndex) { var disposeContract = function (request, host, contractIndex) {
// fileWs.send(JSON.stringify(request)); // fileWs.send(JSON.stringify(request));
// console.log("[cm.js] disposeContract:" + host + "-->" // console.log("[cm.js] disposeContract:" + host + "-->"
// + JSON.stringify(request)); // + JSON.stringify(request));
var wsUrl = getFileWsUrl(host); var wsUrl = getFileWsUrl(host);
var fileWs = new WebSocket(wsUrl); var fileWs = new WebSocket(wsUrl);
fileWs.onerror = function(error) { fileWs.onerror = function (error) {
console.log(error); console.log(error);
}; };
fileWs.contractIndex = contractIndex; fileWs.contractIndex = contractIndex;
fileWs.onopen = function(error) { fileWs.onopen = function (error) {
fileWs.send(JSON.stringify(request)); fileWs.send(JSON.stringify(request));
}; };
fileWs.currHost = host; fileWs.currHost = host;
fileWs.zipInfo = request; fileWs.zipInfo = request;
fileWs.onmessage = downloadHandler; fileWs.onmessage = downloadHandler;
} }
var updateProgress = function(progressIndex, host, progress) { var updateProgress = function (progressIndex, host, progress) {
if (isNaN(progress)) { if (isNaN(progress)) {
console.log("StopHere"); console.log("StopHere");
} }
var hostMap = global.progressStat.get(progressIndex); var hostMap = global.progressStat.get(progressIndex);
hostMap.set(host, progress); hostMap.set(host, progress);
var total = 0; var total = 0;
for (var j = 0; j < global.hosts.length; j++) { for (var j = 0; j < global.hosts.length; j++) {
total += hostMap.get(global.hosts[j]); total += hostMap.get(global.hosts[j]);
} }
// console.log("[cm.js] updateProgress:" + total); // console.log("[cm.js] updateProgress:" + total);
$($("#progressBars .progressDiv")[progressIndex]).progressbar({ $($("#progressBars .progressDiv")[progressIndex]).progressbar({
value : Math.floor(total / global.hosts.length) value: Math.floor(total / global.hosts.length)
}); });
}; };
var downloadHandler = function(obj, wssocket) { var downloadHandler = function (obj, wssocket) {
data = event.data; data = event.data;
// console.log(" -->" + data); // console.log(" -->" + data);
try { try {
var obj = JSON.parse(data); var obj = JSON.parse(data);
switch (obj.action) { switch (obj.action) {
case "onDownloadContract": case "onDownloadContract":
// console.log(JSON.stringify(obj)); // console.log(JSON.stringify(obj));
updateProgress(this.contractIndex, this.currHost, updateProgress(this.contractIndex, this.currHost,
obj.executeTime * 0.95); obj.executeTime * 0.95);
//console.log("[cm.js] obj.executeTime = " + obj.executeTime * 0.95 + " ; " + obj.executeTime); //console.log("[cm.js] obj.executeTime = " + obj.executeTime * 0.95 + " ; " + obj.executeTime);
if (obj.data == "success") { if (obj.data == "success") {
console.log("[cm.js] downloadHandler successs"); console.log("[cm.js] downloadHandler successs");
startContractWithHost(this.currHost, this.zipInfo.fileName, startContractWithHost(this.currHost, this.zipInfo.fileName,
this.contractIndex); this.contractIndex);
this.close(); this.close();
} }
break; break;
case "onStartContract": case "onStartContract":
updateProgress(wssocket.contractIndex, wssocket.currHost, 100); updateProgress(wssocket.contractIndex, wssocket.currHost, 100);
wssocket.close(); wssocket.close();
break; break;
default: default:
} }
} catch (err) { } catch (err) {
console.log(err); console.log(err);
} }
} }
var getControlWsUrl = function(host) { var getControlWsUrl = function (host) {
var prefix = "ws://"; var prefix = "ws://";
if (document.location.href.startsWith("https")) if (document.location.href.startsWith("https"))
prefix = "wss://"; prefix = "wss://";
var path = document.location.pathname.lastIndexOf("/"); var path = document.location.pathname.lastIndexOf("/");
path = document.location.pathname.substr(0, path + 1); path = document.location.pathname.substr(0, path + 1);
path += "SCExecutor"; path += "SCExecutor";
return prefix + host + path; return prefix + host + path;
}; };
var startContractWithHost = function(host, fileName, contractIndex) { var startContractWithHost = function (host, fileName, contractIndex) {
//console.log("[cm.js] host = " + host + " ; fileName" + fileName + " ; contractIndex = " + contractIndex); //console.log("[cm.js] host = " + host + " ; fileName" + fileName + " ; contractIndex = " + contractIndex);
var wsUrl = getControlWsUrl(host); var wsUrl = getControlWsUrl(host);
//console.log("[cm.js] this = " + this); //console.log("[cm.js] this = " + this);
var controller = createWssocket(wsUrl, function() { var controller = createWssocket(wsUrl, function () {
// onopen; // onopen;
var request = {}; var request = {};
request.action = "startContractInTempZips"; request.action = "startContractInTempZips";
request.owner = global.privKey; request.owner = global.privKey;
request.path = fileName; request.path = fileName;
request.script = "empty"; request.script = "empty";
controller.send(JSON.stringify(request)); controller.send(JSON.stringify(request));
this.contractIndex = contractIndex; this.contractIndex = contractIndex;
this.currHost = host; this.currHost = host;
}, downloadHandler); }, downloadHandler);
}; };
var startContract = function() { var startContract = function () {
global.progressStat = new Map();
for (var i = 0; i < global.selectedProjects.length; i++) {
var map = new Map();
for (var j = 0; j < global.hosts.length; j++) {
map.set(global.hosts[j], 0);
}
global.progressStat.set(global.selectedProjectIndexs[i], map);
}
for (var i = 0; i < global.selectedProjects.length; i++) global.progressStat = new Map();
for (var j = 0; j < global.hosts.length; j++) { for (var i = 0; i < global.selectedProjects.length; i++) {
var request = {}; var map = new Map();
request.action = "downloadContract"; for (var j = 0; j < global.hosts.length; j++) {
request.mainHost = $("#targetHost")[0].value; map.set(global.hosts[j], 0);
request.projectName = global.selectedProjects[i].replace(" ", ""); }
request.fileName = request.projectName + "_" + new Date().getTime() global.progressStat.set(global.selectedProjectIndexs[i], map);
+ ".ypk"; }
disposeContract(request, global.hosts[j], for (var i = 0; i < global.selectedProjects.length; i++)
global.selectedProjectIndexs[i]); for (var j = 0; j < global.hosts.length; j++) {
} var request = {};
request.action = "downloadContract";
request.mainHost = $("#targetHost")[0].value;
request.projectName = global.selectedProjects[i].replace(" ", "");
request.fileName = request.projectName + "_" + new Date().getTime()
+ ".ypk";
disposeContract(request, global.hosts[j],
global.selectedProjectIndexs[i]);
}
}; };
var dumpContract = function() { var dumpContract = function () {
var pingObj = {}; var pingObj = {};
for (var i = 0; i < global.selectedContracts.length; i++) { for (var i = 0; i < global.selectedContracts.length; i++) {
pingObj.action = "dumpContract"; pingObj.action = "dumpContract";
pingObj.target = "/memoryDumps/" + global.selectedContracts[i] + "_" pingObj.target = "/memoryDumps/" + global.selectedContracts[i] + "_"
+ new Date().getTime() + ".dyjs"; + new Date().getTime() + ".dyjs";
pingObj.contractID = global.selectedContracts[i]; pingObj.contractID = global.selectedContracts[i];
//console.log("[cm.js] pingObj.target = " + pingObj.target); //console.log("[cm.js] pingObj.target = " + pingObj.target);
//console.log("[cm.js] pingObj.contractID = " + pingObj.contractID); //console.log("[cm.js] pingObj.contractID = " + pingObj.contractID);
global.wssocket.send(JSON.stringify(pingObj)); global.wssocket.send(JSON.stringify(pingObj));
} }
}; };
var loadMemory = function() { var loadMemory = function () {
var pingObj = {}; var pingObj = {};
for (var i = 0; i < global.selectedContracts.length; i++) { for (var i = 0; i < global.selectedContracts.length; i++) {
pingObj.action = "loadMemory"; pingObj.action = "loadMemory";
pingObj.target = "/memoryDumps/" + global.selectedDumps[0]; pingObj.target = "/memoryDumps/" + global.selectedDumps[0];
pingObj.contractID = global.selectedContracts[i]; pingObj.contractID = global.selectedContracts[i];
global.wssocket.send(JSON.stringify(pingObj)); global.wssocket.send(JSON.stringify(pingObj));
} }
}; };
var executeContractWithDynamicResult = function() { var executeContractWithDynamicResult = function () {
var request = {}; var request = {};
request.action = "executeContract"; request.action = "executeContract";
request.requestID = new Date().getTime() + ""; request.requestID = new Date().getTime() + "";
request.contractID = $("#tabdiv")[0].value; request.contractID = $("#tabdiv")[0].value;
request.arg = global.argEditor.getValue(); request.arg = global.argEditor.getValue();
request.privKey = global.privKey; request.privKey = global.privKey;
request.withDyanmicAnalysis = true; request.withDyanmicAnalysis = true;
localStorage.setItem("persisArg", JSON.stringify(request)); localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; };
var executeContract = function() { var executeContract = function () {
var request = {}; var request = {};
request.action = "executeContract"; request.action = "executeContract";
request.requestID = new Date().getTime() + ""; request.requestID = new Date().getTime() + "";
request.contractID = $("#tabdiv")[0].value; request.contractID = $("#tabdiv")[0].value;
request.arg = global.argEditor.getValue(); request.arg = global.argEditor.getValue();
request.privKey = global.privKey; request.privKey = global.privKey;
localStorage.setItem("persisArg", JSON.stringify(request)); localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; };
var listContractProcess = function() { var listContractProcess = function () {
var request = {}; global.wssocket.send(JSON.stringify({
request.action = "listContractProcess"; action: 'listContractProcess',
global.wssocket.send(JSON.stringify(request)); filters: 2
}));
}; };
var killContractProcess = function() { var killContractProcess = function () {
var request = {}; var request = {};
request.action = "killContractProcess"; request.action = "killContractProcess";
request.requestID = new Date().getTime() + ""; request.requestID = new Date().getTime() + "";
request.name = $("#tabdiv")[0].value; request.name = $("#tabdiv")[0].value;
request.id = global.contractName2ID[request.name]; request.id = global.contractName2ID[request.name];
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; };
var staticVerify = function() { var staticVerify = function () {
var request = {}; var request = {};
request.action = "staticVerifyContract"; request.action = "staticVerifyContract";
// TODO should be pubkey // TODO should be pubkey
request.owner = global.privKey; request.owner = global.privKey;
request.isPartial = false; request.isPartial = false;
// TODO ignore contractid // TODO ignore contractid
request.contractid = $("#tabdiv")[0].value; request.contractid = $("#tabdiv")[0].value;
request.script = global.scriptEditor.getValue(); request.script = global.scriptEditor.getValue();
request.path = $(".ui-tabs-active").find("a").html(); request.path = $(".ui-tabs-active").find("a").html();
localStorage.setItem("persisStatus", JSON.stringify(request)); localStorage.setItem("persisStatus", JSON.stringify(request));
if (request.path.startsWith("/")) if (request.path.startsWith("/"))
request.script = "empty"; request.script = "empty";
/* /*
* if (request.script.length > 1024) { global.toSend = * if (request.script.length > 1024) { global.toSend =
* request.script.substr(1024); request.script = request.script.substr(0, * request.script.substr(1024); request.script = request.script.substr(0,
* 1024); request.isPartial = true; } * 1024); request.isPartial = true; }
*/ */
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; };
var downloadContract = function() { var downloadContract = function () {
if (global.lastClickedProjectId == undefined) if (global.lastClickedProjectId == undefined)
global.lastClickedProjectId = 0; global.lastClickedProjectId = 0;
var projectName = global.projects[global.lastClickedProjectId]; var projectName = global.projects[global.lastClickedProjectId];
var url = window.location.href.replace("/scide.html", var url = window.location.href.replace("/scide.html",
"/downLoadServlet?projectName="); "/downLoadServlet?projectName=");
url += projectName; url += projectName;
window.open(url); window.open(url);
}; };
var killAllContract = function() { var killAllContract = function () {
var request = {}; var request = {};
request.action = "killAllContract"; request.action = "killAllContract";
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; };
var customAlert = function(message, title) { var customAlert = function (message, title) {
if (!title) if (!title)
title = 'Alert'; title = 'Alert';
if (!message) if (!message)
message = 'No Message to Display.'; message = 'No Message to Display.';
$('<div></div>').html(message).dialog({ $('<div></div>').html(message).dialog({
title : title, title: title,
resizable : false, resizable: false,
modal : true, modal: true,
buttons : { buttons: {
'Ok' : function() { 'Ok': function () {
$(this).dialog('close'); $(this).dialog('close');
} }
} }
}); });
} }
var init = function() { var init = function () {
initGlobal(); initGlobal();
initWSocket(); initWSocket();
global.hosts = []; global.hosts = [];
$("#serverList").selectable({ $("#serverList").selectable({
stop : function() { stop: function () {
var result = ""; var result = "";
global.hosts = []; global.hosts = [];
$(".ui-selected", this).each(function() { $(".ui-selected", this).each(function () {
var index = $("#serverList li").index(this); var index = $("#serverList li").index(this);
global.hosts.push(this.innerText); global.hosts.push(this.innerText);
}); });
// console.log("[cm.js] selectResult:" + global.hosts); // console.log("[cm.js] selectResult:" + global.hosts);
} }
}); });
}; };
var getRequestParameters = function() { var getRequestParameters = function () {
var arr = (location.search || "").replace(/^\?/, '').split("&"); var arr = (location.search || "").replace(/^\?/, '').split("&");
var params = {}; var params = {};
for (var i = 0; i < arr.length; i++) { for (var i = 0; i < arr.length; i++) {
var data = arr[i].split("="); var data = arr[i].split("=");
if (data.length == 2) { if (data.length == 2) {
params[data[0]] = data[1]; params[data[0]] = data[1];
} }
} }
return params; return params;
}; };
var initHello = function() { var initHello = function () {
var param = getRequestParameters(); var param = getRequestParameters();
var type = parseInt(param["type"]); var type = parseInt(param["type"]);
var template; var template;
switch (type) { switch (type) {
case 1: case 1:
template = getTemplate1(param["name"], decodeURI(param["list"]), template = getTemplate1(param["name"], decodeURI(param["list"]),
param["expiredDate"]); param["expiredDate"]);
break; break;
case 2: case 2:
template = getTemplate2(param["name"], decodeURI(param["list"]), template = getTemplate2(param["name"], decodeURI(param["list"]),
param["expiredDate"]); param["expiredDate"]);
break; break;
case 3: case 3:
var contractID = param["contractID"]; var contractID = param["contractID"];
$.ajax({ $.ajax({
url : "./SCManager?action=getCodeByID&contractID=" + contractID, url: "./SCManager?action=getCodeByID&contractID=" + contractID,
dataType : "json" dataType: "json"
}).done(function(result) { }).done(function (result) {
global.fileContentMap.set(contractID, result.data); global.fileContentMap.set(contractID, result.data);
addTab({ addTab({
"title" : contractID "title": contractID
}); });
}); });
return; return;
default: default:
return; return;
} }
global.scriptEditor.setValue(template); global.scriptEditor.setValue(template);
}; };

View File

@ -50,7 +50,7 @@ var onListMemoryFiles = function(obj){
console.log(htm); console.log(htm);
$("#selectMemeryFiles").html(htm); $("#selectMemeryFiles").html(htm);
changeMemeryFiles($("#selectMemeryFiles")[0].value); changeMemoryFiles($("#selectMemeryFiles")[0].value);
}; };
var transferTo = function(){ var transferTo = function(){

View File

@ -1,151 +1,153 @@
var listContractProcess = function() { function listContractProcess() {
console.log("listContractProcess : "); console.log("listContractProcess : ");
var request = {}; global.wssocket.send(JSON.stringify({
request.action = "listContractProcess"; action: 'listContractProcess',
global.wssocket.send(JSON.stringify(request)); filters: 2
}));
};
var onListContractProcess = function(obj) {
var userManTab = $("#v-pills-contractInstance-tab")[0];
var isActive = (userManTab.getAttribute("aria-selected") == "true");
if (isActive) {
onListContractProcess1(obj);
} else {
onListContractProcess2(obj);
}
};
var changeContractProcess = function(obj) {
global.contractProcess = obj; // 代码管理菜单选中的合约
console.log("oooooooooooo" + global.contractProcess);
//showPermissionList(global.contractProcess);
};
var onListContractProcess2 = function(obj) {
var data = JSON.parse(obj.data);
global.contracts = data;
// $("#contractProcess").editableSelect('clear');
// $("#tabdiv").html("");
global.contractName2ID = {};
//global.permissionNameMap = {};
var name = "";
var htm = "<option selected>选择合约进程</option>";
for (var i = 0; i < data.length; i++) {
// htm += "<option value='" + 0 + "'>" + data[i].name + "</option>";
htm += "<option selected>" + data[i].name + "</option>";
global.contractName2ID[data[i].name] = data[i].id;
//global.permissionNameMap[data[i].name] = data[i].contractPermission;
console.log(htm);
name = data[i].name;
}
//showPermissionList(name);
console.log(htm);
$("#contractProcess").html(htm);
/*
* $("#contractProcess").editableSelect({ effects: 'slide',
* //可选参数default、fade filter: true //false 不过滤,否则选中后其它选项消失 });
*/
/*
* if(data.length > 0){ for (var i = 0; i < data.length; i++) {
* console.log(i); $("#contractProcess").editableSelect('add',
* data[i].name); global.contractName2ID[data[i].name] = data[i].id; //
* $("#tabdiv").append( // $("<option></option>").attr("value",
* data[i].id).text( // data[i].id)); } } if (data.length > 0)
* $("#contractProcess").editableSelect()[0].value = data[0].name;
*/
};
var addTcpNodeUnits = function(data) {
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
var unitID = data[i].key;
var nodes = JSON.parse(data[i].value);
var json = {};
json.type = "TCP";
json.key = unitID;
json.value = nodes;
addNodeUnit(json);
}
}
};
var listSelectUnits = function(data) {
console.log(data);
global.units = {};
var htm = "";
if (data.length > 0) {
// data的key是创建人公钥_时间戳,value是nodes的ID
for (var i = 0; i < data.length; i++) {
var unitID = data[i].key;
var nodes = JSON.parse(data[i].value);
var at_ = data[i].key.indexOf("_");
console.log(nodes);
htm += "<option>集群:" + unitID.substring(at_ + 1)
+ "</option>";
global.units[unitID.substring(at_ + 1)] = nodes;
}
}
htm += "<option selected>选择节点集群</option>";
htm += "<option>无</option>";
console.log(htm);
$("#selectUnits").html(htm);
} }
var onCancelAuth = function(obj) {
myToast("取消权限", obj.data);
if (obj.data == "success") {
}
};
var setPermission = function(data) { function onListContractProcess(obj) {
var request = {}; const userManTab = $("#v-pills-contractInstance-tab")[0];
request.resetContractProcess = data.name; const isActive = (userManTab.getAttribute("aria-selected") === "true");
console.log(request.resetContractName); if (isActive) {
request.closePer = data.permission; onListContractProcess1(obj);
request.oldPer = data.oldPermission; } else {
request.isOpen = data.isOpen; onListContractProcess2(obj);
request.action = "setPermission"; }
global.wssocket.send(JSON.stringify(request)); }
};
var onSetPermission = function(obj) {
console.log(obj);
var html = "<div class='input-group mb-2'>"; function changeContractProcess(obj) {
global.contractProcess = obj; // 代码管理菜单选中的合约
console.log("oooooooooooo" + global.contractProcess);
//showPermissionList(global.contractProcess);
}
html += "<div class='input-group-prepend'>"; function onListContractProcess2(obj) {
html += "<span class='input-group-text' id='inputGroup-sizing-default'>"; const data = JSON.parse(obj.data);
html += "状态保存策略:" + "</span></div>";
html += "<div class='input-group-append'>";
html += "<select id='selectDumpPeriod2' class='custom-select' style='appearance: none; -webkit-appearance: none;'>";
if(period == "43200000"){ global.contracts = data;
html += "<option selected>/1day自动保存</option>"; // $("#contractProcess").editableSelect('clear');
html += "<option selected>/2days自动保存</option> "; // $("#tabdiv").html("");
html += "<option selected>不保存</option>";
html += "<option selected>/12hours自动保存</option>";
}else if(period == "86400000"){
html += "<option selected>/2days自动保存</option> ";
html += "<option selected>不保存</option>";
html += "<option selected>/12hours自动保存</option>";
html += "<option selected>/1day自动保存</option>";
}else if(period == "172800000"){
html += "<option selected>不保存</option>";
html += "<option selected>/12hours自动保存</option>";
html += "<option selected>/1day自动保存</option>";
html += "<option selected>/2days自动保存</option> ";
}else{
html += "<option selected>/12hours自动保存</option>";
html += "<option selected>/1day自动保存</option>";
html += "<option selected>/2days自动保存</option> ";
html += "<option selected>不保存</option>";
}
};
var onListLeakContractProcess = function(obj){ global.contractName2ID = {};
//global.permissionNameMap = {};
let name = "";
let htm = "<option selected>选择合约进程</option>";
for (let i = 0; i < data.length; i++) {
// htm += "<option value='" + 0 + "'>" + data[i].name + "</option>";
htm += "<option selected>" + data[i].name + "</option>";
global.contractName2ID[data[i].name] = data[i].id;
//global.permissionNameMap[data[i].name] = data[i].contractPermission;
console.log(htm);
name = data[i].name;
}
//showPermissionList(name);
console.log(htm);
$("#contractProcess").html(htm);
/*
* $("#contractProcess").editableSelect({ effects: 'slide',
* //可选参数default、fade filter: true //false 不过滤,否则选中后其它选项消失 });
*/
/*
* if(data.length > 0){ for (var i = 0; i < data.length; i++) {
* console.log(i); $("#contractProcess").editableSelect('add',
* data[i].name); global.contractName2ID[data[i].name] = data[i].id; //
* $("#tabdiv").append( // $("<option></option>").attr("value",
* data[i].id).text( // data[i].id)); } } if (data.length > 0)
* $("#contractProcess").editableSelect()[0].value = data[0].name;
*/
}
function addTcpNodeUnits(data) {
if (data.length > 0) {
for (let i = 0; i < data.length; i++) {
const unitID = data[i].key;
const nodes = JSON.parse(data[i].value);
addNodeUnit({
type: 'TCP',
key: unitID,
value: nodes
});
}
}
}
function listSelectUnits(data) {
console.log(data);
global.units = {};
let htm = "";
if (data.length > 0) {
// data的key是创建人公钥_时间戳,value是nodes的ID
for (let i = 0; i < data.length; i++) {
const unitID = data[i].key;
const nodes = JSON.parse(data[i].value);
const at_ = data[i].key.indexOf("_");
console.log(nodes);
htm += "<option>集群:" + unitID.substring(at_ + 1)
+ "</option>";
global.units[unitID.substring(at_ + 1)] = nodes;
}
}
htm += "<option selected>选择节点集群</option>";
htm += "<option>无</option>";
console.log(htm);
$("#selectUnits").html(htm);
}
function onCancelAuth(obj) {
myToast("取消权限", obj.data);
if (obj.data === "success") {
}
}
function setPermission(data) {
// console.log(request.resetContractName);
global.wssocket.send(JSON.stringify({
resetContractProcess: data.name,
closePer: data.permission,
oldPer: data['oldPermission'],
isOpen: data.isOpen,
action: 'setPermission'
}));
}
function onSetPermission(obj) {
console.log(obj);
let html = "<div class='input-group mb-2'>";
html += "<div class='input-group-prepend'>";
html += "<span class='input-group-text' id='inputGroup-sizing-default'>";
html += "状态保存策略:" + "</span></div>";
html += "<div class='input-group-append'>";
html += "<select id='selectDumpPeriod2' class='custom-select' style='appearance: none; -webkit-appearance: none;'>";
if (period === "43200000") {
html += "<option selected>/1day自动保存</option>";
html += "<option selected>/2days自动保存</option> ";
html += "<option selected>不保存</option>";
html += "<option selected>/12hours自动保存</option>";
} else if (period === "86400000") {
html += "<option selected>/2days自动保存</option> ";
html += "<option selected>不保存</option>";
html += "<option selected>/12hours自动保存</option>";
html += "<option selected>/1day自动保存</option>";
} else if (period === "172800000") {
html += "<option selected>不保存</option>";
html += "<option selected>/12hours自动保存</option>";
html += "<option selected>/1day自动保存</option>";
html += "<option selected>/2days自动保存</option> ";
} else {
html += "<option selected>/12hours自动保存</option>";
html += "<option selected>/1day自动保存</option>";
html += "<option selected>/2days自动保存</option> ";
html += "<option selected>不保存</option>";
}
}
function onListLeakContractProcess(obj) {
drawCPTable(obj); drawCPTable(obj);
} }

View File

@ -1,28 +1,31 @@
var expandOrCollapse = function () { function expandOrCollapse() {
if ($("#outputNav").hasClass("col-2")) { const outputNavEl = $("#outputNav")
$("#outputNav").removeClass("col-2").addClass("col-6"); if (outputNavEl.hasClass("col-2")) {
outputNavEl.removeClass("col-2").addClass("col-6");
$("#mainBox").removeClass("col-8").addClass("col-4"); $("#mainBox").removeClass("col-8").addClass("col-4");
$("#expand").html("收起"); $("#expand").html("收起");
} else { } else {
$("#outputNav").removeClass("col-6").addClass("col-2"); outputNavEl.removeClass("col-6").addClass("col-2");
$("#mainBox").removeClass("col-4").addClass("col-8"); $("#mainBox").removeClass("col-4").addClass("col-8");
$("#expand").html("展开"); $("#expand").html("展开");
} }
}; }
var listContracts = function () {
var request = {};
request.action = "listContractProcess";
global.wssocket.send(JSON.stringify(request));
};
var startContract = function () { function listContracts() {
var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key]; global.wssocket.send(JSON.stringify({
var sm2Key = JSON.parse(key.sm2Key); action: 'listContractProcess',
var projectId = $("#selectedProject")[0].value; filters: 2
var project = global.projects[projectId]; }));
}
function startContract() {
const key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
const sm2Key = JSON.parse(key.sm2Key);
const projectId = $("#selectedProject")[0].value;
const project = global.projects[projectId];
startResult.innerText = "正在启动合约:" + project; startResult.innerText = "正在启动合约:" + project;
var request = {}; const request = {};
request.action = "startContract"; request.action = "startContract";
request.isPrivate = $("#privateprojecttab").hasClass("active"); request.isPrivate = $("#privateprojecttab").hasClass("active");
@ -38,17 +41,16 @@ var startContract = function () {
request.script = "empty"; request.script = "empty";
} }
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}
}; function startContractAsDebug() {
const key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
var startContractAsDebug = function () { const sm2Key = JSON.parse(key.sm2Key);
var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key]; const projectId = $("#selectedProject")[0].value;
var sm2Key = JSON.parse(key.sm2Key); const project = global.projects[projectId];
var projectId = $("#selectedProject")[0].value;
var project = global.projects[projectId];
startResult.innerText = "正在以调试模式启动合约:" + project; startResult.innerText = "正在以调试模式启动合约:" + project;
var request = {}; const request = {};
request.action = "startContractAsDebug"; request.action = "startContractAsDebug";
request.isPrivate = $("#privateprojecttab").hasClass("active"); request.isPrivate = $("#privateprojecttab").hasClass("active");
@ -64,32 +66,32 @@ var startContractAsDebug = function () {
request.script = "empty"; request.script = "empty";
} }
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}
}; function stopContract() {
var stopContract = function () { global.wssocket.send(JSON.stringify({
var request = {}; action: 'killContractProcess',
request.action = "killContractProcess"; requestID: new Date().getTime().toString(),
request.requestID = new Date().getTime() + ""; name: mainVue.contracts[selectedContract.value].name,
request.name = mainVue.contracts[selectedContract.value].name; id: mainVue.contracts[selectedContract.value].id
request.id = mainVue.contracts[selectedContract.value].id; }));
global.wssocket.send(JSON.stringify(request)); }
};
var genReadme = function () { function genReadme() {
const request = {
var request = {}; isPrivate: global.currentFile.isPrivate,
request.isPrivate = global.currentFile.isPrivate; path: global.currentFile.path
request.path = global.currentFile.path; };
var tmpIndex = request.path.lastIndexOf('/'); const tmpIndex = request.path.lastIndexOf('/');
var yjsName = request.path.substring(tmpIndex + 1, request.path.length - 4); const yjsName = request.path.substring(tmpIndex + 1, request.path.length - 4);
request.path = request.path.substring(0, tmpIndex); request.path = request.path.substring(0, tmpIndex);
var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key]; const key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
var sm2Key = JSON.parse(key.sm2Key); const sm2Key = JSON.parse(key.sm2Key);
for (c of mainVue.contracts) { for (const c of mainVue.contracts) {
// 这里假设合约名同文件名 // 这里假设合约名同文件名
if (yjsName == c.name) { if (yjsName === c.name) {
var exportedFunction = c.exportedFunctions; const exportedFunction = c.exportedFunctions;
ReadmeFunction = []; ReadmeFunction = [];
for (let f of exportedFunction) { for (let f of exportedFunction) {
let description = "暂无描述"; let description = "暂无描述";
@ -97,11 +99,11 @@ var genReadme = function () {
readmeFunc.functionName = f.functionName; readmeFunc.functionName = f.functionName;
readmeFunc.description = description; readmeFunc.description = description;
for (let anno of f.annotations) { for (let anno of f.annotations) {
if (anno.type == 'Param') { if (anno.type === 'Param') {
readmeFunc.args = anno.args[0]; readmeFunc.args = anno.args[0];
} else if (anno.type == 'Description') { } else if (anno.type === 'Description') {
readmeFunc.description = anno.args[0]; readmeFunc.description = anno.args[0];
} else if (anno.type == 'Result') { } else if (anno.type === 'Result') {
readmeFunc.result = anno.args[0]; readmeFunc.result = anno.args[0];
} }
} }
@ -117,174 +119,168 @@ var genReadme = function () {
} }
} }
myToast("生成文档失败", "请启动合约并检查合约与文件名是否一致!"); myToast("生成文档失败", "请启动合约并检查合约与文件名是否一致!");
}; }
var genData = function () { function genData() {
var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key]; const key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
var sm2Key = JSON.parse(key.sm2Key); const sm2Key = JSON.parse(key.sm2Key);
var value = selectedContract.value; const value = selectedContract.value;
if (value != undefined && value != "选择合约实例") { if (value && value !== "选择合约实例") {
var request = {}; const request = {};
request.action = "generateDataFromRM"; request.action = "generateDataFromRM";
request.requestID = new Date().getTime() + "_" request.requestID = `${new Date().getTime()}_${Math.floor(Math.random() * 10000)}`;
+ Math.floor(Math.random() * 10000); const contract = mainVue.contracts[selectedContract.value];
var contract = mainVue.contracts[selectedContract.value];
request.isPrivate = $("#privateprojecttab").hasClass("active"); request.isPrivate = $("#privateprojecttab").hasClass("active");
request.contractID = contract.id; request.contractID = contract.id;
request.contractName = mainVue.contracts[selectedContract.value].name; request.contractName = mainVue.contracts[selectedContract.value].name;
var arg = {};
if ($('#gasLimit').val() == undefined || $('#gasLimit').val() == "") {
arg.gasLimit = '1000';
} else {
arg.gasLimit = $('#gasLimit').val();
}
// console.log("[arg.gasLimit]"+arg.gasLimit);
request.pubkey = sm2Key.publicKey; request.pubkey = sm2Key.publicKey;
request.signature = sm2.doSignature(request.contractID + "|" + arg.action request.signature = sm2.doSignature(
+ "|" + arg.arg + "|" + sm2Key.publicKey, sm2Key.privateKey); `${request.contractID}|${arg.action}|${arg.arg}|${sm2Key.publicKey}`,
request.arg = JSON.stringify(arg); sm2Key.privateKey,
{hash: true, der: true});
const gasLimit = $('#gasLimit').val()
request.arg = JSON.stringify({
gasLimit: gasLimit ? gasLimit : '1000'
});
localStorage.setItem("persisArg", JSON.stringify(request)); localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
} }
}; }
function queryContractInstanceDOI() {
global.wssocket.send(JSON.stringify({
action: "queryContractInstanceDOI",
requestID: new Date().getTime().toString(),
name: mainVue.contracts[selectedContract.value].name,
id: mainVue.contracts[selectedContract.value].id
}));
}
var queryContractInstanceDOI = function () { function queryContractInstanceInfoByDOI() {
var request = {}; global.wssocket.send(JSON.stringify({
request.action = "queryContractInstanceDOI"; action: 'queryContractInstanceInfoByDOI',
request.requestID = new Date().getTime() + ""; requestID: new Date().getTime().toString(),
request.name = mainVue.contracts[selectedContract.value].name; doi: contractInstanceDOIInput.value
request.id = mainVue.contracts[selectedContract.value].id; }));
global.wssocket.send(JSON.stringify(request)); }
};
var queryContractInstanceInfoByDOI = function () { function importContractInstanceCodeByDOI() {
var request = {}; global.wssocket.send(JSON.stringify({
request.action = "queryContractInstanceInfoByDOI"; action: "importContractInstanceCodeByDOI",
request.requestID = new Date().getTime() + ""; requestID: new Date().getTime().toString(),
request.doi = contractInstanceDOIInput.value; doi: contractInstanceDOIInput.value
global.wssocket.send(JSON.stringify(request)); }));
}; }
var importContractInstanceCodeByDOI = function () { function openInClient() {
var request = {}; window.open(isBaaS ?
request.action = "importContractInstanceCodeByDOI"; `${location.origin}/client/BaaSClient.html${location.search}` :
request.requestID = new Date().getTime() + ""; `${location.origin}/client/bdwareclient.html?self=true&` +
request.doi = contractInstanceDOIInput.value; `contract=${mainVue.contracts[selectedContract.value].id}`);
global.wssocket.send(JSON.stringify(request)); }
};
var openinClient = function () { function stopAllContract() {
let url global.wssocket.send(JSON.stringify({
if (isBaaS) { action: 'killAllContract'
url = `${location.origin}/client/BaaSClient.html${location.search}`; }));
} else { }
url = `${location.origin}/client/bdwareclient.html?self=true&contract=${mainVue.contracts[selectedContract.value].id}`
function selectContractToExecute() {
const value = selectedContractAtExecute.value;
if (value && value !== "选择实例" && mainVue.contracts[value]) {
mainVue.contractFunctions = mainVue.contracts[value].exportedFunctions;
global.wssocket.send(JSON.stringify({
action: "connectTo",
name: mainVue.contracts[value].name,
id: mainVue.contracts[value].id
}));
} }
window.open(url); }
};
var stopAllContract = function () { function executeContract() {
var request = {}; if (!selectedFunction.value) {
request.action = "killAllContract";
global.wssocket.send(JSON.stringify(request));
};
var selectContractToExecute = function () {
var value = selectedContractAtExecute.value;
if (value && value !== "选择实例") {
var exportedFunction = mainVue.contracts[value].exportedFunctions;
mainVue.contractFunctions = exportedFunction;
var pingObj = {};
pingObj.action = "connectTo";
pingObj.name = mainVue.contracts[value].name;
pingObj.id = mainVue.contracts[value].id;
global.wssocket.send(JSON.stringify(pingObj));
}
};
var executeContract = function () {
if (selectedFunction.value == undefined) {
myToast("调用合约失败", "请选择合约方法"); myToast("调用合约失败", "请选择合约方法");
return; return;
} }
if (selectedContractAtExecute.value == undefined) { if (!selectedContractAtExecute.value) {
myToast("调用合约失败", "请选择合约"); myToast("调用合约失败", "请选择合约");
return; return;
} }
var key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key]; const key = pubkeyDialogVue.sm2KeyList[pubkeyDialogVue.selectedSM2Key];
var sm2Key = JSON.parse(key.sm2Key); const sm2Key = JSON.parse(key.sm2Key);
var request = {}; const request = {};
request.action = "executeContract"; request.action = "executeContract";
request.requestID = new Date().getTime() + "_" request.requestID = new Date().getTime() + "_"
+ Math.floor(Math.random() * 10000); + Math.floor(Math.random() * 10000);
var contract = mainVue.contracts[selectedContractAtExecute.value]; const contract = mainVue.contracts[selectedContractAtExecute.value];
request.contractID = contract.id; request.contractID = contract.id;
request.operation = contract.exportedFunctions[selectedFunction.value].functionName; request.operation = contract.exportedFunctions[selectedFunction.value].functionName;
arg = executeContractArgInput.value; const arg = executeContractArgInput.value;
if ($('#gasLimit').val() == undefined || $('#gasLimit').val() == "") { const gasLimit = $('#gasLimit').val()
request.gasLimit = '1000'; request.gasLimit = gasLimit ? gasLimit : '1000'
} else {
request.gasLimit = $('#gasLimit').val();
}
request.pubkey = sm2Key.publicKey; request.pubkey = sm2Key.publicKey;
request.signature = sm2.doSignature(request.contractID + "|" + request.operation request.signature = sm2.doSignature(
+ "|" + arg + "|" + sm2Key.publicKey, sm2Key.privateKey, {hash: true, der: true}); `${request.contractID}|${request.operation}|${arg}|${sm2Key.publicKey}`,
sm2Key.privateKey,
{hash: true, der: true});
request.arg = arg; request.arg = arg;
localStorage.setItem("persisArg", JSON.stringify(request)); localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; }
var executeContractWithDynamicResult = function () {
if (selectedFunction.value == undefined) { function executeContractWithDynamicResult() {
if (!selectedFunction.value) {
myToast("调用合约失败", "请选择合约方法"); myToast("调用合约失败", "请选择合约方法");
return; return;
} }
if (selectedContractAtExecute.value == undefined) { if (!selectedContractAtExecute.value) {
myToast("调用合约失败", "请选择合约"); myToast("调用合约失败", "请选择合约");
return; return;
} }
console.log("executeContractWithDynamicResult"); console.log("executeContractWithDynamicResult");
var request = {}; const request = {};
request.action = "executeContract"; request.action = "executeContract";
request.requestID = new Date().getTime() + ""; request.requestID = new Date().getTime() + "";
var contract = mainVue.contracts[selectedContractAtExecute.value]; const contract = mainVue.contracts[selectedContractAtExecute.value];
request.contractName = contract.id; request.contractName = contract.id;
var arg = {}; const arg = {
arg.action = contract.exportedFunctions[selectedFunction.value].functionName; action: contract.exportedFunctions[selectedFunction.value].functionName,
arg.arg = executeContractArgInput.value; arg: executeContractArgInput.value
};
request.withDyanmicAnalysis = true; request.withDyanmicAnalysis = true;
request.arg = "{\"action\":\"" + arg.action + "\",\"arg\":\"" + arg.arg request.arg = "{\"action\":\"" + arg.action + "\",\"arg\":\"" + arg.arg
+ "\"}"; + "\"}";
request.pubkey = global.sm2Key.publicKey; request.pubkey = global.sm2Key.publicKey;
request.signature = sm2.doSignature(request.contractID + "|" + arg.action request.signature = sm2.doSignature(
+ "|" + arg.arg + "|" + global.sm2Key.publicKey, `${request.contractID}|${arg.action}|${arg.arg}|${global.sm2Key.publicKey}`,
global.sm2Key.privateKey, {hash: true, der: true}); global.sm2Key.privateKey,
{hash: true, der: true});
localStorage.setItem("persisArg", JSON.stringify(request)); localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; }
var testEvaluates = function () {
if (selectedFunction.value == undefined) { function testEvaluates() {
if (!selectedFunction.value) {
myToast("调用合约失败", "请选择合约方法"); myToast("调用合约失败", "请选择合约方法");
return; return;
} }
if (selectedContractAtExecute.value == undefined) { if (!selectedContractAtExecute.value) {
myToast("调用合约失败", "请选择合约"); myToast("调用合约失败", "请选择合约");
return; return;
} }
console.log("Evaluates"); console.log("Evaluates");
var contract = mainVue.contracts[selectedContractAtExecute.value]; const contract = mainVue.contracts[selectedContractAtExecute.value];
var request = {}; global.wssocket.send(JSON.stringify({
request.action = "evaluates"; action: "evaluates",
request.contractName = contract.id; contractName: contract.id,
request.functionName = contract.exportedFunctions[selectedFunction.value].functionName; functionName: contract.exportedFunctions[selectedFunction.value].functionName,
request.args = executeContractArgInput.value; args: executeContractArgInput.value
}));
global.wssocket.send(JSON.stringify(request)); }
};

View File

@ -12,6 +12,7 @@ var expandOrCollapse = function () {
var listContracts = function () { var listContracts = function () {
var request = {}; var request = {};
request.action = "listContractProcess"; request.action = "listContractProcess";
request.filters = 2;
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; };
@ -75,7 +76,7 @@ var importContractInstanceCodeByDOI = function () {
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; };
var openinClient = function () { var openInClient = function () {
var path = document.location.pathname; var path = document.location.pathname;
path = path.replace("/SCIDE", ""); path = path.replace("/SCIDE", "");
path = path.replace("/OnlineIDE.html", ""); path = path.replace("/OnlineIDE.html", "");

View File

@ -1,258 +1,258 @@
var WSHandler = function(event) { var WSHandler = function (event) {
// console.log("[scide.js] WSHandler " + event); // console.log("[scide.js] WSHandler " + event);
data = event.data; data = event.data;
// console.log(" -->" + data); // console.log(" -->" + data);
try { try {
var obj = JSON.parse(data); var obj = JSON.parse(data);
switch (obj.action) { switch (obj.action) {
case 'ping': case 'ping':
case 'poing': case 'poing':
break; break;
case 'onExecuteResult': case 'onExecuteResult':
onExecuteResult(obj); onExecuteResult(obj);
break; break;
case 'onListContractProcess': case 'onListContractProcess':
onListContractProcess(obj); onListContractProcess(obj);
break; break;
case 'onStartContract': case 'onStartContract':
onStartContract(obj); onStartContract(obj);
break; break;
case 'onKillContractProcess': case 'onKillContractProcess':
logComm(obj); logComm(obj);
break; break;
case 'onKillAllContract': case 'onKillAllContract':
onKillAllContract(obj); onKillAllContract(obj);
break; break;
case 'onOutputStream': case 'onOutputStream':
displayOutput(obj); displayOutput(obj);
break; break;
case 'onException': case 'onException':
logException(obj); logException(obj);
break; break;
case 'onHashResult': case 'onHashResult':
onHashResult(obj); onHashResult(obj);
break; break;
default: default:
// displayOutput(obj); // displayOutput(obj);
break; break;
} }
} catch (err) { } catch (err) {
console.log(err); console.log(err);
} }
};// WSHandler() };// WSHandler()
var logException = function(obj) { var logException = function (obj) {
global.tempobj = obj; global.tempobj = obj;
$("#responseStatus").html("Exception (" + obj.executeTime + "ms)"); $("#responseStatus").html("Exception (" + obj.executeTime + "ms)");
displayOutput(obj); displayOutput(obj);
}; };
var logComm = function(obj) { var logComm = function (obj) {
console.log(obj); console.log(obj);
}; };
var displayOutput = function(obj) { var displayOutput = function (obj) {
displayOutputStr(obj.data); displayOutputStr(obj.data);
}; };
var displayOutputStr = function(str) { var displayOutputStr = function (str) {
var val = global.outputStreamEditor.getValue(); var val = global.outputStreamEditor.getValue();
val += "\n" + str; val += "\n" + str;
global.outputStreamEditor.setValue(val); global.outputStreamEditor.setValue(val);
var info = global.outputStreamEditor.getScrollInfo(); var info = global.outputStreamEditor.getScrollInfo();
global.outputStreamEditor.scrollTo(0, info.height); global.outputStreamEditor.scrollTo(0, info.height);
}; };
var checkConnectStatus = function() { var checkConnectStatus = function () {
if (global.wssocket.isOpen() != 1) { if (global.wssocket.isOpen() != 1) {
if ($("#checkConnect").css("display") == "none") { if ($("#checkConnect").css("display") == "none") {
$("#checkConnect").fadeIn(800); $("#checkConnect").fadeIn(800);
} else } else
$("#checkConnect").fadeOut(800); $("#checkConnect").fadeOut(800);
} else { } else {
$("#checkConnect").css("display", "block"); $("#checkConnect").css("display", "block");
$("#checkConnect").css("background-color", "#007FFF"); $("#checkConnect").css("background-color", "#007FFF");
} }
}; };
var initWSocket = function() { var initWSocket = function () {
var prefix = "ws://"; var prefix = "ws://";
if (document.location.href.startsWith("https")) if (document.location.href.startsWith("https"))
prefix = "wss://"; prefix = "wss://";
url = prefix + document.location.host url = prefix + document.location.host
+ (document.location.pathname.replace("scide.html", "SCExecutor")); + (document.location.pathname.replace("scide.html", "SCExecutor"));
// console.log(url); // console.log(url);
global.wssocket = createWssocket(url, function() { global.wssocket = createWssocket(url, function () {
listContractProcess(); listContractProcess();
listProjects(); listProjects();
}, function(data) { }, function (data) {
WSHandler(data); WSHandler(data);
FileHandler(data); FileHandler(data);
}); });
global.filewssocket = global.wssocket; global.filewssocket = global.wssocket;
setInterval(checkConnectStatus, 1000); setInterval(checkConnectStatus, 1000);
}; };
// ====== wsHandler // ====== wsHandler
var onStartContract = function(obj) { var onStartContract = function (obj) {
console.log("onStartContract:"); console.log("onStartContract:");
// console.log(obj); // console.log(obj);
var result = JSON.parse(obj.data); var result = JSON.parse(obj.data);
$("#responseStatus").html(result.status + " (" + obj.executeTime + "ms)"); $("#responseStatus").html(result.status + " (" + obj.executeTime + "ms)");
global.responseEditor.setValue(result.result); global.responseEditor.setValue(result.result);
// $("#tabdiv").editableSelect('add', obj.cid); // $("#tabdiv").editableSelect('add', obj.cid);
// $("#tabdiv").editableSelect()[0].value = obj.cid; // $("#tabdiv").editableSelect()[0].value = obj.cid;
}; };
var onExecuteResult = function(obj) { var onExecuteResult = function (obj) {
console.log("onExecuteResult:"); console.log("onExecuteResult:");
// console.log(obj); // console.log(obj);
var data = JSON.parse(obj.data); var data = JSON.parse(obj.data);
$("#responseStatus").html(data.status + " (" + obj.executeTime + "ms)"); $("#responseStatus").html(data.status + " (" + obj.executeTime + "ms)");
global.responseEditor.setValue(data.result); global.responseEditor.setValue(data.result);
// console.log(data); // console.log(data);
var totalLines = global.responseEditor.lineCount(); var totalLines = global.responseEditor.lineCount();
global.responseEditor.autoFormatRange({ global.responseEditor.autoFormatRange({
line : 0, line: 0,
ch : 0 ch: 0
}, { }, {
line : totalLines line: totalLines
}); });
if (data.analysis != undefined && data.analysis.length > 0) { if (data.analysis != undefined && data.analysis.length > 0) {
// displayOutputStr(data.analysis); // displayOutputStr(data.analysis);
} }
}; };
var onListContractProcess = function(obj) { var onListContractProcess = function (obj) {
var data = JSON.parse(obj.data); var data = JSON.parse(obj.data);
global.contracts = data; global.contracts = data;
var html = ""; var html = "";
$("#tabdiv").editableSelect('clear'); $("#tabdiv").editableSelect('clear');
// $("#tabdiv").html(""); // $("#tabdiv").html("");
global.contractName2ID = {}; global.contractName2ID = {};
for (var i = 0; i < data.length; i++) { for (var i = 0; i < data.length; i++) {
$("#tabdiv").editableSelect('add', data[i].name); $("#tabdiv").editableSelect('add', data[i].name);
global.contractName2ID[data[i].name] = data[i].id; global.contractName2ID[data[i].name] = data[i].id;
// $("#tabdiv").append( // $("#tabdiv").append(
// $("<option></option>").attr("value", data[i].id).text( // $("<option></option>").attr("value", data[i].id).text(
// data[i].id)); // data[i].id));
} }
if (data.length > 0) if (data.length > 0)
$("#tabdiv").editableSelect()[0].value = data[0].name; $("#tabdiv").editableSelect()[0].value = data[0].name;
// $("#tabdiv").selectmenu("refresh"); // $("#tabdiv").selectmenu("refresh");
// $("#tabdiv").html(html); // $("#tabdiv").html(html);
// $("yourid/class here").append($("<option></option>").attr("value", // $("yourid/class here").append($("<option></option>").attr("value",
// youroption-value).text(youroption-text)); // youroption-value).text(youroption-text));
}; };
var onSaveƒe = function(obj) { var onSaveƒe = function (obj) {
alert("Save file:" + obj.data); alert("Save file:" + obj.data);
}; };
var onKillAllContract = function(obj) { var onKillAllContract = function (obj) {
customAlert(obj.data); customAlert(obj.data);
}; };
var onHashResult = function(obj) { var onHashResult = function (obj) {
$("#hashResult").html("刚刚操作的数链指纹:" + obj.data); $("#hashResult").html("刚刚操作的数链指纹:" + obj.data);
}; };
// ====== wsHandler done! // ====== wsHandler done!
var switchContract = function(off) { var switchContract = function (off) {
// var contract = global.contracts[off]; // var contract = global.contracts[off];
// global.scriptEditor.setValue(contract.script); // global.scriptEditor.setValue(contract.script);
// $("#tabdiv")[0].value = contract.id; // $("#tabdiv")[0].value = contract.id;
var pingObj = {}; var pingObj = {};
pingObj.action = "connectTo"; pingObj.action = "connectTo";
pingObj.name = $("#tabdiv")[0].value; pingObj.name = $("#tabdiv")[0].value;
pingObj.id = global.contractName2ID[pingObj.name]; pingObj.id = global.contractName2ID[pingObj.name];
global.wssocket.send(JSON.stringify(pingObj)); global.wssocket.send(JSON.stringify(pingObj));
} }
var countChar = function(str, c) { var countChar = function (str, c) {
var ret = 0; var ret = 0;
for (var i = 0; i < str.length; i++) { for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == c) if (str.charAt(i) == c)
ret++; ret++;
} }
return ret; return ret;
} }
var generateOld = function() { var generateOld = function () {
$.ajax({ $.ajax({
url : "./SCManager?action=generatePrivateKey", url: "./SCManager?action=generatePrivateKey",
dataType : "json" dataType: "json"
}).done(function(result) { }).done(function (result) {
if (result.status) { if (result.status) {
localStorage.setItem("PrivKey", result.data); localStorage.setItem("PrivKey", result.data);
alert("Key successfully generated!"); alert("Key successfully generated!");
initRest(); initRest();
} }
}); });
} }
var generate = function() { var generate = function () {
localStorage.setItem("PrivKey", JSON.stringify(sm2.generateKeyPairHex())); localStorage.setItem("PrivKey", JSON.stringify(sm2.generateKeyPairHex()));
global.privKey = localStorage.getItem("PrivKey"); global.privKey = localStorage.getItem("PrivKey");
} }
var initGlobal = function() { var initGlobal = function () {
window.global = {}; window.global = {};
global.privKey = localStorage.getItem("PrivKey"); global.privKey = localStorage.getItem("PrivKey");
if (global.privKey == undefined || global.privKey == null if (global.privKey == undefined || global.privKey == null
|| global.privKey.length < 100 || !global.privKey.startsWith("{")) { || global.privKey.length < 100 || !global.privKey.startsWith("{")) {
generate(); generate();
initRest(); initRest();
} else } else
initRest(); initRest();
global.privKey = JSON.parse(global.privKey); global.privKey = JSON.parse(global.privKey);
} }
var initRest = function() { var initRest = function () {
global.scriptEditor = CodeMirror.fromTextArea($("#contractArea")[0], { global.scriptEditor = CodeMirror.fromTextArea($("#contractArea")[0], {
matchBrackets : true, matchBrackets: true,
autoCloseBrackets : true, autoCloseBrackets: true,
lineNumbers : true, lineNumbers: true,
height : "auto", height: "auto",
mode : "application/ld+json", mode: "application/ld+json",
lineWrapping : true lineWrapping: true
}); });
global.responseEditor = CodeMirror.fromTextArea($("#responseArea")[0], { global.responseEditor = CodeMirror.fromTextArea($("#responseArea")[0], {
matchBrackets : true, matchBrackets: true,
autoCloseBrackets : true, autoCloseBrackets: true,
lineNumbers : true, lineNumbers: true,
mode : "application/ld+json", mode: "application/ld+json",
lineWrapping : true lineWrapping: true
}); });
global.outputStreamEditor = CodeMirror.fromTextArea( global.outputStreamEditor = CodeMirror.fromTextArea(
$("#outputStreamArea")[0], { $("#outputStreamArea")[0], {
matchBrackets : true, matchBrackets: true,
autoCloseBrackets : true, autoCloseBrackets: true,
lineNumbers : true, lineNumbers: true,
mode : "application/ld+json", mode: "application/ld+json",
lineWrapping : true lineWrapping: true
}); });
global.argEditor = CodeMirror.fromTextArea($("#argArea")[0], { global.argEditor = CodeMirror.fromTextArea($("#argArea")[0], {
matchBrackets : true, matchBrackets: true,
autoCloseBrackets : true, autoCloseBrackets: true,
lineNumbers : true, lineNumbers: true,
mode : "application/ld+json", mode: "application/ld+json",
lineWrapping : true, lineWrapping: true,
height : "auto" height: "auto"
}); });
$('#tabdiv').editableSelect({ $('#tabdiv').editableSelect({
filter : false filter: false
}); });
$("#tabdiv").on('select.editable-select', function(e) { $("#tabdiv").on('select.editable-select', function (e) {
// console.log("====="); // console.log("=====");
// console.log(e); // console.log(e);
// console.log(e.target.value); // console.log(e.target.value);
// TODO; // TODO;
switchContract(); switchContract();
// switchContract // switchContract
}); });
// //
$('#tabdiv').addClass("ui-selectmenu-button"); $('#tabdiv').addClass("ui-selectmenu-button");
$('#tabdiv').addClass("ui-selectmenu-button-closedn"); $('#tabdiv').addClass("ui-selectmenu-button-closedn");
$('#tabdiv').addClass("ui-corner-all"); $('#tabdiv').addClass("ui-corner-all");
$('#tabdiv').addClass("ui-button"); $('#tabdiv').addClass("ui-button");
$('#tabdiv').addClass("ui-widget"); $('#tabdiv').addClass("ui-widget");
}; };
// var onUploadNext = function() { // var onUploadNext = function() {
@ -275,196 +275,198 @@ var initRest = function() {
// global.wssocket.send(JSON.stringify(request)); // global.wssocket.send(JSON.stringify(request));
// }; // };
var startContract = function() { var startContract = function () {
var request = {}; var request = {};
request.action = "startContract"; request.action = "startContract";
// TODO should be pubkey // TODO should be pubkey
request.owner = global.privKey.publicKey; request.owner = global.privKey.publicKey;
request.requestID = new Date().getTime() + ""; request.requestID = new Date().getTime() + "";
// TODO ignore contractid // TODO ignore contractid
request.contractid = $("#tabdiv")[0].value; request.contractid = $("#tabdiv")[0].value;
request.script = global.scriptEditor.getValue(); request.script = global.scriptEditor.getValue();
request.path = $(".ui-tabs-active").find("a").html(); request.path = $(".ui-tabs-active").find("a").html();
localStorage.setItem("persisStatus", JSON.stringify(request)); localStorage.setItem("persisStatus", JSON.stringify(request));
if (request.path.startsWith("/")) { if (request.path.startsWith("/")) {
request.signature = sm2.doSignature("Fixed|" + request.path + "|" request.signature = sm2.doSignature("Fixed|" + request.path + "|"
+ global.privKey.publicKey, global.privKey.privateKey); + global.privKey.publicKey, global.privKey.privateKey);
request.script = "empty"; request.script = "empty";
} else } else
request.signature = sm2.doSignature("Fixed|" + request.script + "|" request.signature = sm2.doSignature("Fixed|" + request.script + "|"
+ global.privKey.publicKey, global.privKey.privateKey); + global.privKey.publicKey, global.privKey.privateKey);
// console.log("path=" + request.path); // console.log("path=" + request.path);
// console.log("[scide.js] startContract() contractid = " // console.log("[scide.js] startContract() contractid = "
// + $("#tabdiv")[0].value); // + $("#tabdiv")[0].value);
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; };
var executeContractWithDynamicResult = function() { var executeContractWithDynamicResult = function () {
var request = {}; var request = {};
request.action = "executeContract"; request.action = "executeContract";
request.requestID = new Date().getTime() + ""; request.requestID = new Date().getTime() + "";
request.contractID = $("#tabdiv")[0].value; request.contractID = $("#tabdiv")[0].value;
request.arg = global.argEditor.getValue(); request.arg = global.argEditor.getValue();
request.privKey = global.privKey; request.privKey = global.privKey;
request.withDyanmicAnalysis = true; request.withDyanmicAnalysis = true;
localStorage.setItem("persisArg", JSON.stringify(request)); localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
}; };
var executeContract = function() { var executeContract = function () {
var request = {}; var request = {};
request.action = "executeContract"; request.action = "executeContract";
request.requestID = new Date().getTime() + ""; request.requestID = new Date().getTime() + "";
request.contractID = $("#tabdiv")[0].value; request.contractID = $("#tabdiv")[0].value;
request.arg = global.argEditor.getValue(); request.arg = global.argEditor.getValue();
request.pubkey = global.privKey.publicKey; request.pubkey = global.privKey.publicKey;
// contractID + "|" + action + "|" + arg + "|" + requester; // contractID + "|" + action + "|" + arg + "|" + requester;
var localArg = JSON.parse(request.arg); var localArg = JSON.parse(request.arg);
request.signature = sm2.doSignature(request.contractID + "|" request.signature = sm2.doSignature(request.contractID + "|"
+ localArg.action + "|" + localArg.arg + "|" + localArg.action + "|" + localArg.arg + "|"
+ global.privKey.publicKey, global.privKey.privateKey); + global.privKey.publicKey, global.privKey.privateKey);
localStorage.setItem("persisArg", JSON.stringify(request)); localStorage.setItem("persisArg", JSON.stringify(request));
global.wssocket.send(JSON.stringify(request)); global.wssocket.send(JSON.stringify(request));
};
var listContractProcess = function() {
var request = {};
request.action = "listContractProcess";
global.wssocket.send(JSON.stringify(request));
}; };
var killContractProcess = function() { function listContractProcess() {
var request = {}; global.wssocket.send(JSON.stringify({
request.action = "killContractProcess"; action: 'listContractProcess',
request.requestID = new Date().getTime() + ""; filters: 2
request.name = $("#tabdiv")[0].value; }));
request.id = global.contractName2ID[request.name];
global.wssocket.send(JSON.stringify(request));
};
var staticVerify = function() {
var request = {};
request.action = "staticVerifyContract";
// TODO should be pubkey
request.owner = global.privKey;
request.isPartial = false;
// TODO ignore contractid
request.contractid = $("#tabdiv")[0].value;
request.script = global.scriptEditor.getValue();
request.path = $(".ui-tabs-active").find("a").html();
localStorage.setItem("persisStatus", JSON.stringify(request));
if (request.path.startsWith("/"))
request.script = "empty";
/*
* if (request.script.length > 1024) { global.toSend =
* request.script.substr(1024); request.script = request.script.substr(0,
* 1024); request.isPartial = true; }
*/
global.wssocket.send(JSON.stringify(request));
};
var downloadContract = function() {
if (global.lastClickedProjectId == undefined)
global.lastClickedProjectId = 0;
var projectName = global.projects[global.lastClickedProjectId];
var url = window.location.href.replace("/scide.html",
"/CMManager?action=downloadContract&projectName=");
url += projectName;
window.open(url);
};
var killAllContract = function() {
var request = {};
request.action = "killAllContract";
global.wssocket.send(JSON.stringify(request));
};
var customAlert = function(message, title) {
if (!title)
title = 'Alert';
if (!message)
message = 'No Message to Display.';
$('<div></div>').html(message).dialog({
title : title,
resizable : false,
modal : true,
buttons : {
'Ok' : function() {
$(this).dialog('close');
}
}
});
} }
var init = function() {
console.log("init:");
initGlobal();
initWSocket();
var req = localStorage.getItem("persisStatus");
// console.log(req);
req = JSON.parse(req);
if (req != undefined) {
// $("#tabdiv")[0].value = req.contractid;
//global.scriptEditor.setValue(req.script);
}
var req2 = localStorage.getItem("persisArg"); var killContractProcess = function () {
req2 = JSON.parse(req2); var request = {};
if (req2 != undefined && req2.arg != undefined) { request.action = "killContractProcess";
global.argEditor.setValue(req2.arg); request.requestID = new Date().getTime() + "";
} request.name = $("#tabdiv")[0].value;
initHello(); request.id = global.contractName2ID[request.name];
global.wssocket.send(JSON.stringify(request));
}; };
var getRequestParameters = function() { var staticVerify = function () {
var arr = (location.search || "").replace(/^\?/, '').split("&"); var request = {};
var params = {}; request.action = "staticVerifyContract";
for (var i = 0; i < arr.length; i++) { // TODO should be pubkey
var data = arr[i].split("="); request.owner = global.privKey;
if (data.length == 2) { request.isPartial = false;
params[data[0]] = data[1]; // TODO ignore contractid
} request.contractid = $("#tabdiv")[0].value;
} request.script = global.scriptEditor.getValue();
return params; request.path = $(".ui-tabs-active").find("a").html();
localStorage.setItem("persisStatus", JSON.stringify(request));
if (request.path.startsWith("/"))
request.script = "empty";
/*
* if (request.script.length > 1024) { global.toSend =
* request.script.substr(1024); request.script = request.script.substr(0,
* 1024); request.isPartial = true; }
*/
global.wssocket.send(JSON.stringify(request));
}; };
var getTemplate1 = function(name, list, expiredDate) { var downloadContract = function () {
var tem = "contract _cname {\n \t//数据清洗逻辑\n function deleteKeys(result,list){\n\t\tfor (var key in list)\n \t\t\tdelete result[list[key]];\n \t\tfor (var key in result){\n \t\t\tif (typeof result[key] == 'object'){\n \t\t\t\tdeleteKeys(result[key],list);\t\n\t\t\t}\n\t\t}\n \t\treturn JSON.stringify(result);\n\t}\n\n \texport function filter(arg){\n \t\tvar result = JSON.parse(arg);\n\t\tvar list = _list;\n \t\tlist = list.split(\",\");\n \t\treturn deleteKeys(result,list);\n\t}\n\t//数据处理逻辑\n\tfunction handle(obj){\n \n }\n\texport function get(arg){\n if (new Date().getTime()<_expiredDate)\n return \"Permission Denied\";\n\t\tvar result = YancloudUtil.httpGet(arg);\n result = JSON.parse(result);\n \tif (result.resposeCode==200){\n \t\t\treturn handle(filter(result.response));\n } else { return result; }\n\t}\n}"; if (global.lastClickedProjectId == undefined)
tem = tem.replace("_cname", name); global.lastClickedProjectId = 0;
tem = tem.replace("_list", JSON.stringify(list)); var projectName = global.projects[global.lastClickedProjectId];
tem = tem.replace("_expiredDate", expiredDate); var url = window.location.href.replace("/scide.html",
return tem; "/CMManager?action=downloadContract&projectName=");
url += projectName;
window.open(url);
}; };
var getTemplate2 = function(name, list, expiredDate) { var killAllContract = function () {
var tem = "contract _cname {\n //数据清洗逻辑\n \tfunction inVal(key,list){\n\t\tfor (var i=0;i<list.length;i++)\n \t\t\tif (list[i]==key) return true;\n \t\treturn false;\n\t}\n \tfunction reserveKeys(result,list){\n \t\tvar ret = {};\n\t\tvar hasVal = false;\n \t\tfor (var key in result){\n \t\t\tif (inVal(key,list)) {\n \t\t\t\tret[key] = result[key];\n \thasVal = true;\n\t\t\t}\n \tvar isObject =( typeof result[key] == 'object');\n if (isObject){\n\t\t\t\tvar val = reserveKeys(result[key],list);\n \t\tif (val!=undefined) {\n \t\t\tret[key] = val;\n \t\t\thasVal = true;\n \t\t}\n\t\t\t} \n\t\n\t\t}\n\t\tif (hasVal)\n \t\t\treturn ret;\n\t\telse\treturn undefined;\n\t}\n \tfunction filter(arg){\n \t\tvar result = JSON.parse(arg);\n\t\tvar list = _list;\n \t\tlist = list.split(\",\");\n \t\treturn reserveKeys(result,list);\n\t}\n function handle(obj){\n return JSON.stringify(obj);\n }\n //数据处理逻辑\n\texport function get(arg){\n\t\tif (new Date().getTime()<_expiredDate)\n return \"Permission Denied\";\n var result = YancloudUtil.httpGet(arg);\n result = JSON.parse(result);\n \tif (result.resposeCode==200){\n \t\t var ret = filter(result.response);\n handle(ret);\n } else { return result; }\n\t}\n}"; var request = {};
tem = tem.replace("_cname", name); request.action = "killAllContract";
tem = tem.replace("_list", JSON.stringify(list)); global.wssocket.send(JSON.stringify(request));
tem = tem.replace("_expiredDate", expiredDate);
return tem;
}; };
var initHello = function() {
var param = getRequestParameters(); var customAlert = function (message, title) {
var type = parseInt(param["type"]); if (!title)
var template; title = 'Alert';
switch (type) {
case 1: if (!message)
template = getTemplate1(param["name"], decodeURI(param["list"]), message = 'No Message to Display.';
param["expiredDate"]);
break; $('<div></div>').html(message).dialog({
case 2: title: title,
template = getTemplate2(param["name"], decodeURI(param["list"]), resizable: false,
param["expiredDate"]); modal: true,
break; buttons: {
case 3: 'Ok': function () {
var contractID = param["contractID"]; $(this).dialog('close');
$.ajax({ }
url : "./SCManager?action=getCodeByID&contractID=" + contractID, }
dataType : "json" });
}).done(function(result) { }
global.fileContentMap.set(contractID, result.data); var init = function () {
addTab({ console.log("init:");
"title" : contractID initGlobal();
}); initWSocket();
}); var req = localStorage.getItem("persisStatus");
return; // console.log(req);
default: req = JSON.parse(req);
return; if (req != undefined) {
} // $("#tabdiv")[0].value = req.contractid;
global.scriptEditor.setValue(template); //global.scriptEditor.setValue(req.script);
}
var req2 = localStorage.getItem("persisArg");
req2 = JSON.parse(req2);
if (req2 != undefined && req2.arg != undefined) {
global.argEditor.setValue(req2.arg);
}
initHello();
};
var getRequestParameters = function () {
var arr = (location.search || "").replace(/^\?/, '').split("&");
var params = {};
for (var i = 0; i < arr.length; i++) {
var data = arr[i].split("=");
if (data.length == 2) {
params[data[0]] = data[1];
}
}
return params;
};
var getTemplate1 = function (name, list, expiredDate) {
var tem = "contract _cname {\n \t//数据清洗逻辑\n function deleteKeys(result,list){\n\t\tfor (var key in list)\n \t\t\tdelete result[list[key]];\n \t\tfor (var key in result){\n \t\t\tif (typeof result[key] == 'object'){\n \t\t\t\tdeleteKeys(result[key],list);\t\n\t\t\t}\n\t\t}\n \t\treturn JSON.stringify(result);\n\t}\n\n \texport function filter(arg){\n \t\tvar result = JSON.parse(arg);\n\t\tvar list = _list;\n \t\tlist = list.split(\",\");\n \t\treturn deleteKeys(result,list);\n\t}\n\t//数据处理逻辑\n\tfunction handle(obj){\n \n }\n\texport function get(arg){\n if (new Date().getTime()<_expiredDate)\n return \"Permission Denied\";\n\t\tvar result = YancloudUtil.httpGet(arg);\n result = JSON.parse(result);\n \tif (result.resposeCode==200){\n \t\t\treturn handle(filter(result.response));\n } else { return result; }\n\t}\n}";
tem = tem.replace("_cname", name);
tem = tem.replace("_list", JSON.stringify(list));
tem = tem.replace("_expiredDate", expiredDate);
return tem;
};
var getTemplate2 = function (name, list, expiredDate) {
var tem = "contract _cname {\n //数据清洗逻辑\n \tfunction inVal(key,list){\n\t\tfor (var i=0;i<list.length;i++)\n \t\t\tif (list[i]==key) return true;\n \t\treturn false;\n\t}\n \tfunction reserveKeys(result,list){\n \t\tvar ret = {};\n\t\tvar hasVal = false;\n \t\tfor (var key in result){\n \t\t\tif (inVal(key,list)) {\n \t\t\t\tret[key] = result[key];\n \thasVal = true;\n\t\t\t}\n \tvar isObject =( typeof result[key] == 'object');\n if (isObject){\n\t\t\t\tvar val = reserveKeys(result[key],list);\n \t\tif (val!=undefined) {\n \t\t\tret[key] = val;\n \t\t\thasVal = true;\n \t\t}\n\t\t\t} \n\t\n\t\t}\n\t\tif (hasVal)\n \t\t\treturn ret;\n\t\telse\treturn undefined;\n\t}\n \tfunction filter(arg){\n \t\tvar result = JSON.parse(arg);\n\t\tvar list = _list;\n \t\tlist = list.split(\",\");\n \t\treturn reserveKeys(result,list);\n\t}\n function handle(obj){\n return JSON.stringify(obj);\n }\n //数据处理逻辑\n\texport function get(arg){\n\t\tif (new Date().getTime()<_expiredDate)\n return \"Permission Denied\";\n var result = YancloudUtil.httpGet(arg);\n result = JSON.parse(result);\n \tif (result.resposeCode==200){\n \t\t var ret = filter(result.response);\n handle(ret);\n } else { return result; }\n\t}\n}";
tem = tem.replace("_cname", name);
tem = tem.replace("_list", JSON.stringify(list));
tem = tem.replace("_expiredDate", expiredDate);
return tem;
};
var initHello = function () {
var param = getRequestParameters();
var type = parseInt(param["type"]);
var template;
switch (type) {
case 1:
template = getTemplate1(param["name"], decodeURI(param["list"]),
param["expiredDate"]);
break;
case 2:
template = getTemplate2(param["name"], decodeURI(param["list"]),
param["expiredDate"]);
break;
case 3:
var contractID = param["contractID"];
$.ajax({
url: "./SCManager?action=getCodeByID&contractID=" + contractID,
dataType: "json"
}).done(function (result) {
global.fileContentMap.set(contractID, result.data);
addTab({
"title": contractID
});
});
return;
default:
return;
}
global.scriptEditor.setValue(template);
}; };