How to use snapshotFrame method in Playwright Internal

Best JavaScript code snippet using playwright-internal

snapshot-main.js

Source:snapshot-main.js Github

copy

Full Screen

1var ns = org_opensds_storage_devices;2var hostId = WEB_PLATFORM.getHostId();3var serverGuid = WEB_PLATFORM.getServerGuid();4var urlForLun = ns.webContextPath + "/rest/data/host/unmountableVolumeList/";5var cSnapshotUrl = ns.webContextPath + "/rest/data/host/snapshot";6var lunObj = new Object(), devObj = new Object();7var snapshot = new Object();8var snapshot_array = new Array();9var snapshots = new Array();10var toPage_lun = 1;11var pagesize_lun = 10;12var toPage_sanapshot = 1;13var pagesize_snapshot = 10;14var divhead_id_lun = "bak_lun";15var divhead_id_snapshot = "bak_snapshot";16var loadpage2_data_params = "";17var runNum = 0;18var filterType = "";19var filterValue = "";20//nfs21var lun_fs_flag = "lun";22var urlForFs = ns.webContextPath + "/rest/nfsdata/fs/";23var fsSnapshotUrl = ns.webContextPath + "/rest/nfsdata/fsSnapshot";24var dsNfsUrl = ns.webContextPath + "/rest/nfsdata/datastore";25var pager1Url = "";26var pager2Url = "";27var pager1ResultUrl = "";28var pager2ResultUrl = "";29var fsObj = new Object();30$(document).ready(function () {31 loadLunsOrFs();32 bundleEvent();33});34function loadLunsOrFs() {35 $("#chk_all").prop("checked", false);36 $("#toggleLunFsBtn").prop("disabled", "disabled");37 lunObj = new Object(), devObj = new Object();38 fsObj = new Object();39 if ($("#" + divhead_id_lun).length > 0) {40 $("#" + divhead_id_lun).width($("#divMain").width() - 22);41 }42 $('#lunTabFrame').prop("src", "");43 $('#snapshotFrame').prop("src", "");44 $("#pager1").remove();45 $("#pager2").remove();46 $("#showBackupBtn").addClass("disabled");47 $("#showBackupBtn").prop("disabled", "disabled");48 $("#recoverBtn").addClass("disabled");49 $("#recoverBtn").prop("disabled", "disabled");50 $("#refreshSnapBtn").addClass("disabled");51 $("#refreshSnapBtn").prop("disabled", "disabled");52 $("#delSnapBtn").addClass("disabled");53 $("#delSnapBtn").prop("disabled", "disabled");54 $("#divLoadingSnapshot").hide();55 $("#divLoadingLun").show();56 if (lun_fs_flag == "lun") {57 pager1Url = urlForLun + "count/" + hostId + "?serverGuid=" + serverGuid;58 pager1ResultUrl = ns.webContextPath + "/resources/html/snapshot/lunTab.html";59 } else if (lun_fs_flag == "fs") {60 pager1Url = urlForFs + "count/" + hostId + "?serverGuid=" + serverGuid;61 pager1ResultUrl = ns.webContextPath + "/resources/html/snap shot/fsTab.html";62 }63 var url = pager1Url + "&filterType=" + filterType + "&filterValue=" + filterValue;64 $("#hostLunTab").bigPage({65 container: "pager1",66 ajaxData: {67 url: encodeURI(url),68 params: {69 loaddingId: "divLoadingLun",70 iframeId: "lunTabFrame",71 data_url: pager1ResultUrl,72 data_params: ''73 }74 },75 pageSize: pagesize_lun,76 toPage: toPage_lun,77 position: "down",78 callback: enableToggleBtn79 });80}81function enableToggleBtn() {82 $("#toggleLunFsBtn").prop("disabled", "");83}84function loadSnapshots() {85 if (lun_fs_flag == "lun") {86 loadpage2_data_params = "&lunId=" + lunObj.id + "&deviceId=" + devObj.id + "&t=" + new Date();87 } else if (lun_fs_flag == "fs") {88 loadpage2_data_params = "&fsId=" + fsObj.id + "&deviceId=" + devObj.id + "&t=" + new Date();89 }90 $("#chk_all").prop("checked", false);91 if (lunObj.id == "") {92 $("#divLoadingSnapshot").hide();93 return;94 }95 if ($("#" + divhead_id_snapshot).length > 0) {96 $("#" + divhead_id_snapshot).width($("#divMain").width() - 22);97 }98 snapshot = new Object();99 $("#recoverBtn").addClass("disabled");100 $("#delSnapBtn").addClass("disabled");101 $('#snapshotFrame').prop("src", "");102 $("#pager2").remove();103 $("#divLoadingSnapshot").show();104 if (lun_fs_flag == "lun") {105 pager2Url = ns.webContextPath + "/rest/data/host/snapshot/count?volumeId=" + lunObj.id + "&storageId=" + devObj.id + "&t=" + new Date();106 pager2ResultUrl = ns.webContextPath + "/resources/html/snapshot/lunSnapshotTab.html";107 } else if (lun_fs_flag == "fs") {108 pager2Url = ns.webContextPath + "/rest/nfsdata/fsSnapshot/count?fsId=" + fsObj.id + "&deviceId=" + devObj.id + "&t=" + new Date();109 pager2ResultUrl = ns.webContextPath + "/resources/html/snapshot/fsSnapshotTab.html";110 }111 $("#snapshotTab").bigPage({112 container: "pager2",113 ajaxData: {114 url: encodeURI(pager2Url),115 params: {116 loaddingId: "divLoadingSnapshot",117 iframeId: "snapshotFrame",118 data_url: pager2ResultUrl,119 data_params: loadpage2_data_params120 }121 },122 pageSize: pagesize_snapshot,123 toPage: toPage_sanapshot,124 position: "down",125 callback: function () {126 if ((lun_fs_flag == "lun" && isEmpObj(lunObj.id)) || (lun_fs_flag == "fs" && isEmpObj(fsObj.id))) {127 $("#snapshotFrame")[0].contentWindow.$("#snapshotTable").remove();128 $("#pager2").remove();129 return;130 }131 }132 });133}134function bundleEvent() {135 $("#toggleLunFsBtn").click(function () {136 if (lun_fs_flag == "lun") {137 lun_fs_flag = "fs";138 $("#toggleLunFsBtn").val("Lun");139 $("#lunTabBasicTitle").html("File System");140 $(".lunFsIdTh").attr("title", "File System Id");141 $(".lunFsIdDiv").html("FS Id");142 $(".lunTabWwnTh").hide();143 $(".lunTabWwnDiv").hide();144 $(".lunTabMappingTh").hide();145 $(".lunTabMappingDiv").hide();146 $(".spTabWwnTh").hide();147 $(".spTabWwnDiv").hide();148 $(".spRunningStatusTh").hide();149 $(".spRunningStatusDiv").hide();150 $(".capacityTh").hide();151 $(".capacityDiv").hide();152 $(".activedTh").attr("title", "Created");153 $(".activedDiv").html("Created");154 loadLunsOrFs();155 } else if (lun_fs_flag == "fs") {156 lun_fs_flag = "lun";157 $("#toggleLunFsBtn").val("File System");158 $("#lunTabBasicTitle").html("Lun");159 $(".lunFsIdTh").attr("title", "LUN ID");160 $(".lunFsIdDiv").html("LUN ID");161 $(".lunTabWwnTh").show();162 $(".lunTabWwnDiv").show();163 $(".lunTabMappingTh").show();164 $(".lunTabMappingDiv").show();165 $(".spTabWwnTh").show();166 $(".spTabWwnDiv").show();167 $(".spRunningStatusTh").show();168 $(".spRunningStatusDiv").show();169 $(".capacityTh").show();170 $(".capacityDiv").show();171 $(".activedTh").attr("title", "Activated");172 $(".activedDiv").html("Activated");173 loadLunsOrFs();174 }175 });176 //for search177 $("#btnSearch").click(function () {178 $("#btnSearch").prop("disabled", "disabled");179 $("#btnRefreshLUN").prop("disabled", "disabled");180 setTimeout(function () {181 $("#btnSearch").prop("disabled", "");182 $("#btnRefreshLUN").prop("disabled", "");183 }, 500);184 filterType = $("#filterType").val();185 if (filterType == "NAME" || filterType == "ID") {186 filterValue = trim($("#nameId_filterValue").val());187 }188 else if (filterType == "HEALTHSTATUS") {189 filterValue = $("#healthStatus_filterValue").val();190 if (filterValue == "NORMAL") {191 }192 else if (filterValue == "FAULT") {193 }194 else {195 filterValue = "";196 }197 }198 else if (filterType == "RUNNINGSTATUS") {199 filterValue = $("#runStatus_filterValue").val();200 if (filterValue == "ONLINE") {201 }202 else if (filterValue == "OFFLINE") {203 }204 else {205 filterValue = "";206 }207 }208 loadLunsOrFs();209 });210 $("#filterType").unbind();211 $("#filterType").bind("change", function () {212 $("#nameId_filterValue").val("");213 if ($('#filterType').val() == 'HEALTHSTATUS') {214 $("#nameId_filterValueDiv").hide();215 $("#runStatus_filterValue").hide();216 $("#healthStatus_filterValue").show();217 $("#healthStatus_filterValue").get(0).options[0].selected = true;218 }219 else if ($('#filterType').val() == 'RUNNINGSTATUS') {220 $("#nameId_filterValueDiv").hide();221 $("#healthStatus_filterValue").hide();222 $("#runStatus_filterValue").show();223 $("#runStatus_filterValue").get(0).options[0].selected = true;224 }225 else {226 $("#healthStatus_filterValue").hide();227 $("#runStatus_filterValue").hide();228 $("#nameId_filterValueDiv").show();229 }230 });231 $("#refreshLunBtn").click(function () {232 $("#hostLunTab tr:eq(0) th:eq(0)").width("5%");233 $("#hostLunTab tr:eq(0) th:eq(1)").width("10%");234 $("#hostLunTab tr:eq(0) th:eq(2)").width("10%");235 $("#hostLunTab tr:eq(0) th:eq(3)").width("10%");236 $("#hostLunTab tr:eq(0) th:eq(4)").width("10%");237 $("#hostLunTab tr:eq(0) th:eq(5)").width("5%");238 $("#hostLunTab tr:eq(0) th:eq(6)").width("10%");239 $("#hostLunTab tr:eq(0) th:eq(7)").width("20%");240 $("#hostLunTab tr:eq(0) th:eq(8)").width("10%");241 $("#hostLunTab tr:eq(0) th:eq(9)").width("10%");242 loadLunsOrFs();243 });244 $("#refreshSnapBtn").click(function () {245 $("#snapshotTab tr:eq(0) th:eq(0)").width("4%");246 $("#snapshotTab tr:eq(0) th:eq(1)").width("22%");247 $("#snapshotTab tr:eq(0) th:eq(2)").width("10%");248 $("#snapshotTab tr:eq(0) th:eq(3)").width("10%");249 $("#snapshotTab tr:eq(0) th:eq(4)").width("10%");250 $("#snapshotTab tr:eq(0) th:eq(5)").width("24%");251 $("#snapshotTab tr:eq(0) th:eq(6)").width("20%");252 loadSnapshots();253 });254 $(".cancleBtn").click(function () {255 $("#cSnapBox").css('visibility', 'hidden');256 $(".alertBox").hide();257 unlock();258 });259 $("#delSnapBtn").click(function () {260 if (isEmpObj(devObj.id)) {261 $.debug("del snapshot check, data is null");262 return;263 }264 var id = "";265 snapshots = new Array();266 $snapshot_checked = $("#snapshotFrame")[0].contentWindow.$("input[id^='snapCheckbox_']:checked");267 $snapshot_checked.each(function (index, ele) {268 $tr = $(this).parent().parent();269 var snapshotObj = new Object();270 snapshotObj.id = trim($tr.find("[name='id']").text());271 snapshotObj.storageId = trim($tr.find("[name='storageId']").text());272 if (lun_fs_flag == "lun") {273 snapshotObj.parentId = trim($tr.find("[name='parentId']").text());274 } else if (lun_fs_flag == "fs") {275 snapshotObj.parentId = trim($tr.find("[name='fsId']").text());276 }277 if (isEmpObj(snapshotObj.id)) {278 $.debug("del snapshot check, data is null");279 }280 else {281 snapshots.push(snapshotObj);282 }283 });284 $("#infWords").text("You are about to delete snapshots. This operation cannot be undone. ");285 lock();286 $("#cSnapBox").css('visibility', 'visible');287 $(".alertBox").hide();288 $("#title").text("Delete Snapshot");289 $("#title").show();290 $("#delInfoDiv").show();291 });292 $("#confirBtn").click(function () {293 $("#cSnapBox").css('visibility', 'hidden');294 $("#title").hide();295 $("#delInfoDiv").hide();296 $("#sucType").val("refreshSnapBtn");297 $("#errType").val("refreshSnapBtn");298 var snapReq = "";299 if (lun_fs_flag == "lun") {300 snapReq = new req(cSnapshotUrl + "/" + devObj.id301 + "?hostId=" + hostId + "&serverGuid=" + serverGuid, JSON302 .stringify(snapshots));303 } else if (lun_fs_flag == "fs") {304 snapReq = new req(fsSnapshotUrl + "/" + devObj.id305 + "?hostId=" + hostId + "&serverGuid=" + serverGuid, JSON306 .stringify(snapshots));307 }308 snapReq.type = "DELETE";309 var snaphandler = new handler(function doSuccess(resp) {310 $(".alertBox").hide();311 $("#cSnapBox").css('visibility', 'visible');312 $("#title").text("Excute Result");313 $("#title").show();314 if (resp.data || resp.status == "ok") {315 $("#sucWords").text("Delete snapshot successfully.");316 $("#sucDiv").show();317 }318 else if (resp.msg || resp.status == "error") {319 $("#errWords").text(resp.msg);320 $("#errDiv").show();321 }322 }, function doFailed() {323 $(".alertBox").hide();324 $("#cSnapBox").css('visibility', 'visible');325 $("#title").text("Excute Result");326 $("#title").show();327 $("#errWords").text("Delete snapshot failed.");328 $("#errDiv").show();329 });330 sendMsg(snapReq, snaphandler);331 });332 $("#showBackupBtn").click(function () {333 if ((lun_fs_flag == "lun" && (isEmpObj(lunObj.id) || isEmpObj(lunObj.name))) ||334 lun_fs_flag == "fs" && (isEmpObj(fsObj.id) || isEmpObj(fsObj.name))) {335 $.debug("showBackupBtn check, data is null");336 return;337 }338 var snapshotName = "";339 if (lun_fs_flag == "lun") {340 snapshotName = getSnapName(lunObj.name);341 } else if (lun_fs_flag == "fs") {342 snapshotName = getSnapName(fsObj.name);343 }344 $("#cSnapshotName").val(snapshotName);345 lock();346 $("#cSnapBox").css('visibility', 'visible');347 $(".alertBox").hide();348 $("#title").text("Create Snapshot");349 $("#title").show();350 $("#cSnapBoxContent").show();351 });352 $("#backupBtn").click(function () {353 $("#sucType").val("refreshSnapBtn");354 $("#errType").val("refreshSnapBtn");355 $("#cSnapBox").css('visibility', 'hidden');356 $("#title").hide();357 $("#cSnapBoxContent").hide();358 var snapshot = new Object();359 var lunReq = new Object();360 if (lun_fs_flag == "lun") {361 snapshot.parentId = lunObj.id;362 snapshot.name = $("#cSnapshotName").val();363 snapshot.storageId = devObj.id;364 lunReq = new req(cSnapshotUrl, JSON.stringify(snapshot));365 $.debug("name: " + snapshot.name + ".lunId: " + snapshot.lunId + ", deviceId: " + devObj.id);366 } else if (lun_fs_flag == "fs") {367 snapshot.parentId = fsObj.id;368 snapshot.name = $("#cSnapshotName").val();369 snapshot.storageId = devObj.id;370 lunReq = new req(fsSnapshotUrl, JSON.stringify(snapshot));371 $.debug("name: " + snapshot.name + ".fsId: " + snapshot.fsId + ", deviceId: " + devObj.id);372 }373 lunReq.type = "POST";374 var lunhandler = new handler(function doSuccess(resp) {375 if (resp.data || resp.status.toLowerCase() == "ok") {376 $(".alertBox").hide();377 $("#title").text("Excute Result");378 $("#title").show();379 $("#sucWords").html(resp.msg);380 $("#sucWords").text("Create snapshot successful.");381 $("#sucDiv").show();382 $("#cSnapBox").css('visibility', 'visible');383 }384 else if (resp.msg || resp.status.toLowerCase() == "error") {385 $(".alertBox").hide();386 $("#title").text("Excute Result");387 $("#title").show();388 $("#errWords").html(resp.msg);389 $("#errDiv").show();390 $("#cSnapBox").css('visibility', 'visible');391 }392 else {393 $(".alertBox").hide();394 $("#title").text("Excute Result");395 $("#title").show();396 $("#errWords").html("Create snapshot failed.");397 $("#errDiv").show();398 $("#cSnapBox").css('visibility', 'visible');399 }400 }, function doFailed() {401 $(".alertBox").hide();402 $("#title").text("Excute Result");403 $("#title").show();404 $("#errWords").text("Create snapshot failed.");405 $("#errDiv").show();406 $("#cSnapBox").css('visibility', 'visible');407 });408 sendMsg(lunReq, lunhandler);409 });410 $("#sucOp").click(function () {411 $("#sucWords").text("");412 $("#title").text("");413 var sucType = $("#sucType").val();414 if (sucType == "refreshSnapBtn") {415 loadSnapshots();416 }417 else if (sucType == "refreshLunBtn") {418 loadLunsOrFs();419 }420 $(".alertBox").hide();421 $("#title").text("");422 $("#cSnapBox").css('visibility', 'hidden');423 unlock();424 });425 $("#errOp").click(function () {426 $("#errWords").text("");427 $("#title").text("");428 var errType = $("#errType").val();429 if (errType == "refreshSnapBtn") {430 loadSnapshots();431 }432 else if (errType == "refreshLunBtn") {433 loadLunsOrFs();434 }435 $(".alertBox").hide();436 $("#title").text("");437 $("#cSnapBox").css('visibility', 'hidden');438 unlock();439 });440 $("#recoverBtn").click(function () {441 var used_tip = "";442 if (lun_fs_flag == "lun") {443 used_tip = "The source LUN is used by a datastore.Please unmount the datastore before rollbacking snapshot.";444 } else if (lun_fs_flag == "fs") {445 used_tip = "The source File System is used by a datastore. Click OK to unmount datastore for rollbacking snapshot.";446 }447 var scsiLunState_tip = "";448 scsiLunState_tip = "The source LUN is attached.please detach the source LUN before rollbacking snapshot.";449 var continue_tip = "";450 continue_tip = "The source LUN has been detached.You can rollback the snapshot.";451 if ((lun_fs_flag == "lun" ) || (lun_fs_flag == "fs")) {452 lock();453 $("#cSnapBox").css('visibility', 'visible');454 $(".alertBox").hide();455 $("#title").text("Before Rollbacking Snapshot");456 $("#title").show();457 $("#nextStep").addClass("disabled");458 $("#nextStep").prop("disabled", "disabled");459 $("#nextStep").css("background", "#57C7FF");460 if (lunObj.usedType == "Datastore" || fsObj.usedByStatus == "true") {461 $("#beforeRollback_tip").html(used_tip);462 }463 if (lun_fs_flag == "lun" && (lunObj.usedType != "Datastore" || isEmpObj(lunObj.usedType))) {464 $("#beforeRollback_tip").html(continue_tip);465 $("#nextStep").removeClass("disabled");466 $("#nextStep").prop("disabled", "");467 $("#nextStep").css("background", "#007cbb");468 } else if (lun_fs_flag == "fs") {469 $("#beforeRollback_tip").html(used_tip);470 $("#nextStep").removeClass("disabled");471 $("#nextStep").prop("disabled", "");472 $("#nextStep").css("background", "#007cbb");473 }474 $("#beforeRollback").show();475 }476 else {477 return;478 }479 });480 $("#nextStep").click(function () {481 if (lun_fs_flag == "lun") {482 afterRemoveLunDs();483 } else if (lun_fs_flag == "fs") {484 $("#beforeRollback_tip").html("The datastore is removing, please wait for it done...");485 $("#nextStep").addClass("disabled");486 $("#nextStep").prop("disabled", "disabled");487 $("#nextStep").css("background", "#57C7FF");488 $("#cancelNext").addClass("disabled");489 $("#cancelNext").prop("disabled", "disabled");490 var rmDsReq = new req(dsNfsUrl + "/" + fsObj.datastoreId + "?serverGuid=" + serverGuid + "&hostId=" + hostId, "");491 rmDsReq.type = "DELETE";492 var rmDshandler = new handler(function doSuccess(resp) {493 if (resp.data) {494 afterRemoveNfsDs();495 }496 else if (resp.msg || resp.status.toLowerCase() == "error") {497 $(".alertBox").hide();498 $("#title").text("Excute Result");499 $("#title").show();500 $("#errWords").html(resp.msg);501 $("#errDiv").show();502 $("#cSnapBox").css('visibility', 'visible');503 }504 else {505 $(".alertBox").hide();506 $("#title").text("Excute Result");507 $("#title").show();508 $("#errWords").html("Remove datastore failed.");509 $("#errDiv").show();510 $("#cSnapBox").css('visibility', 'visible');511 }512 }, function doFailed() {513 $(".alertBox").hide();514 $("#title").text("Excute Result");515 $("#title").show();516 $("#errWords").text("Remove datastore failed.");517 $("#errDiv").show();518 $("#cSnapBox").css('visibility', 'visible');519 });520 sendMsg(rmDsReq, rmDshandler);521 }522 });523 $("#rollbackBtn").click(function () {524 $("#sucType").val("refreshSnapBtn");525 $("#errType").val("refreshSnapBtn");526 if (lun_fs_flag == "lun") {527 $("#cSnapBox").css('visibility', 'hidden');528 $("#title").hide();529 $("#rollbackContent").hide();530 } else if (lun_fs_flag == "fs") {531 }532 var snapReq = new Object();533 if (lun_fs_flag == "lun") {534 snapReq = new req(cSnapshotUrl + "/" + devObj.id + "?rollbackSpeed=" + trim($("#rollbackSpeed").val()), JSON.stringify(snapshot));535 } else if (lun_fs_flag == "fs") {536 snapReq = new req(fsSnapshotUrl, JSON.stringify(snapshot));537 }538 snapReq.type = "PUT";539 var snaphandler = new handler(function doSuccess(resp) {540 if (lun_fs_flag == "lun") {541 $(".alertBox").hide();542 $("#cSnapBox").css('visibility', 'visible');543 $("#title").text("Excute Result");544 $("#title").show();545 }546 if (resp.data || resp.status.toLowerCase() == "ok") {547 if (lun_fs_flag == "lun") {548 $("#sucWords").text("Recover snapshot successfully.");549 $("#sucDiv").show();550 } else if (lun_fs_flag == "fs") {551 $("#rollbackContentDiv").html("The datastore is mounting, please wait for it done...");552 $("#rollbackBtn").addClass("disabled");553 $("#rollbackBtn").prop("disabled", "disabled");554 $("#cancelRB").addClass("disabled");555 $("#cancelRB").prop("disabled", "disabled");556 mountNfsDatastore();557 }558 }559 else if (resp.msg || resp.status.toLowerCase() == "error") {560 $("#errWords").text(resp.errorDesc);561 $("#errDiv").show();562 }563 }, function doFailed() {564 $(".alertBox").hide();565 $("#cSnapBox").css('visibility', 'visible');566 $("#title").text("Excute Result");567 $("#title").show();568 $("#errWords").text("Recovery snapshot failed.");569 $("#errDiv").show();570 });571 sendMsg(snapReq, snaphandler);572 });573 $("#cSnapshotName").bind("input propertychange", function () {574 var value = $(this).val();575 var length = getLength(value);576 if (length > 31) {577 this.value = getByteVal(value, 31);578 }579 for (var index = 0; index < this.value.length; index++) {580 if (!(/^[a-zA-Z0-9-_.\u4e00-\u9fa5]$/.test(this.value.charAt(index)))) {581 this.value = this.value.substring(0, index);582 }583 }584 chkSnapName();585 }).bind("blur", function () {586 chkSnapName();587 });588 $("#nameId_filterValue").bind("input propertychange blur", function () {589 filterValue = $(this).val();590 });591}592function afterRemoveLunDs() {593 $("#beforeRollback").hide();594 if (isEmpObj(devObj.id)) {595 return;596 }597 $snapshot_checked = $("#snapshotFrame")[0].contentWindow.$("input[id^='snapCheckbox_']:checked").first();598 $tr = $snapshot_checked.parent().parent();599 snapshot = new Object();600 snapshot.id = trim($tr.find("[name='id']").text());601 snapshot.storageId = devObj.id;602 snapshot.parentId = lunObj.id;603 snapshot.name = trim($tr.find("[name='name']").text());604 if (isEmpObj(snapshot.id)) {605 $.debug("del snapshot check, data is null");606 return;607 }608 $(".alertBox").hide();609 $("#rollbackSnap").text(snapshot.name);610 $("#title").text("Recover Snapshot");611 $("#title").show();612 $("#rollbackContent").show();613 if (lun_fs_flag == "lun") {614 $(".rollbackSpeedTr").show();615 } else if (lun_fs_flag == "fs") {616 $(".rollbackSpeedTr").hide();617 $("#rollbackContentDiv").html("You are about to restore the data on the source File system to the point in time when the\n\t\t\t\t\tsnapshot was created.");618 }619}620function afterRemoveNfsDs() {621 $("#beforeRollback").hide();622 if (isEmpObj(devObj.id)) {623 return;624 }625 $snapshot_checked = $("#snapshotFrame")[0].contentWindow.$("input[id^='snapCheckbox_']:checked").first();626 $tr = $snapshot_checked.parent().parent();627 snapshot = new Object();628 snapshot.id = trim($tr.find("[name='id']").text());629 snapshot.storageId = devObj.id;630 snapshot.fsId = fsObj.id;631 snapshot.name = trim($tr.find("[name='name']").text());632 if (isEmpObj(snapshot.id)) {633 $.debug("del snapshot check, data is null");634 return;635 }636 $(".alertBox").hide();637 $("#rollbackSnap").text(snapshot.name);638 $("#title").text("Recover Snapshot");639 $("#title").show();640 $("#rollbackContent").show();641 if (lun_fs_flag == "lun") {642 $(".rollbackSpeedTr").show();643 } else if (lun_fs_flag == "fs") {644 $(".rollbackSpeedTr").hide();645 $("#rollbackContentDiv").html("You are about to restore the data on the source File system to the point in time when the\n\t\t\t\t\tsnapshot was created.");646 }647}648function mountNfsDatastore() {649 var nfsDatastoreMount = new Object();650 nfsDatastoreMount.localPath = fsObj.localPath;651 nfsDatastoreMount.remoteHost = fsObj.remoteHost;652 nfsDatastoreMount.remotePath = fsObj.remotePath;653 var nfsDsReq = new req(dsNfsUrl + "/" + fsObj.datastoreId + "?serverGuid=" + serverGuid + "&hostId=" + hostId, JSON.stringify(nfsDatastoreMount));654 nfsDsReq.type = "POST";655 var nfsDshandler = new handler(function doSuccess(resp) {656 $(".alertBox").hide();657 $("#cSnapBox").css('visibility', 'visible');658 $("#title").text("Excute Result");659 $("#title").show();660 if (resp.data) {661 $("#sucWords").text("Mount NFS datastore successfully.");662 $("#sucDiv").show();663 }664 else if (resp.errorCode) {665 $("#errWords").text(resp.errorDesc);666 $("#errDiv").show();667 }668 }, function doFailed() {669 $(".alertBox").hide();670 $("#cSnapBox").css('visibility', 'visible');671 $("#title").text("Excute Result");672 $("#title").show();673 $("#errWords").text("Mount NFS datastore failed.");674 $("#errDiv").show();675 });676 sendMsg(nfsDsReq, nfsDshandler);677}678function init() {679 var table = $("#snapshotFrame")[0].contentWindow.$("#snapshotTable")[0];680 rowNum = table.rows.length;681 if (rowNum > 0) {682 setPageCheckBox(rowNum);683 }684}685function setPageCheckBox(rowNum) {686 var $singleChkbox = $("#snapshotFrame")[0].contentWindow.$("input[id^='snapCheckbox_']");687 $("#chk_all").unbind("click");688 $("#chk_all").click(function () {689 var chkAll = this.checked;690 $singleChkbox.each(function (i) {691 if (chkAll) {692 if (!this.checked) {693 this.checked = true;694 }695 } else {696 if (this.checked) {697 this.checked = false;698 }699 }700 });701 if (chkAll) {702 if (rowNum > 0) {703 $("#delSnapBtn").prop("disabled", "");704 $("#delSnapBtn").removeClass("disabled");705 $("#delSnapBtn .plugin_button_div").css("cursor", "pointer");706 if (rowNum == 1) {707 if (lun_fs_flag == "lun") {708 var lunRunningStatus = $("#snapshotFrame")[0].contentWindow.$("input[id^='snapCheckbox_']:checked").parent().parent().find("td[name='runningStatus']").text();709 if (lunRunningStatus == "INACTIVATED") {710 $("#recoverBtn").prop("disabled", "disabled");711 $("#recoverBtn").addClass("disabled");712 $("#recoverBtn .plugin_button_div").css("cursor", "default");713 }714 else {715 $("#recoverBtn").prop("disabled", "");716 $("#recoverBtn").removeClass("disabled");717 $("#recoverBtn .plugin_button_div").css("cursor", "pointer");718 }719 } else if (lun_fs_flag == "fs") {720 $("#recoverBtn").prop("disabled", "");721 $("#recoverBtn").removeClass("disabled");722 $("#recoverBtn .plugin_button_div").css("cursor", "pointer");723 }724 }725 else {726 $("#recoverBtn").prop("disabled", "disabled");727 $("#recoverBtn").addClass("disabled");728 $("#recoverBtn .plugin_button_div").css("cursor", "default");729 }730 }731 } else {732 $("#delSnapBtn").prop("disabled", "disabled");733 $("#recoverBtn").prop("disabled", "disabled");734 $("#delSnapBtn").addClass("disabled");735 $("#recoverBtn").addClass("disabled");736 $("#delSnapBtn .plugin_button_div").css("cursor", "default");737 $("#recoverBtn .plugin_button_div").css("cursor", "default");738 }739 });740 $singleChkbox.unbind("click");741 $singleChkbox.click(function () {742 var num = 0;743 $singleChkbox.each(function (i) {744 if (this.checked) {745 num++;746 }747 });748 if (num == rowNum) {749 if (!$("#chk_all")[0].checked) {750 $("#chk_all").prop("checked", "checked");751 }752 } else {753 $("#chk_all").prop("checked", "");754 }755 if (num > 0) {756 $("#delSnapBtn").prop("disabled", "");757 $("#delSnapBtn").removeClass("disabled");758 $("#delSnapBtn .plugin_button_div").css("cursor", "pointer");759 if (num == 1) {760 if (lun_fs_flag == "lun") {761 var lunRunningStatus = $("#snapshotFrame")[0].contentWindow.$("input[id^='snapCheckbox_']:checked").parent().parent().find("td[name='runningStatus']").text();762 if (lunRunningStatus == "INACTIVATED") {763 $("#recoverBtn").prop("disabled", "disabled");764 $("#recoverBtn").addClass("disabled");765 $("#recoverBtn .plugin_button_div").css("cursor", "default");766 }767 else {768 $("#recoverBtn").prop("disabled", "");769 $("#recoverBtn").removeClass("disabled");770 $("#recoverBtn .plugin_button_div").css("cursor", "pointer");771 }772 } else if (lun_fs_flag == "fs") {773 $("#recoverBtn").prop("disabled", "");774 $("#recoverBtn").removeClass("disabled");775 $("#recoverBtn .plugin_button_div").css("cursor", "pointer");776 }777 }778 else {779 $("#recoverBtn").prop("disabled", "disabled");780 $("#recoverBtn").addClass("disabled");781 $("#recoverBtn .plugin_button_div").css("cursor", "default");782 }783 } else {784 $("#delSnapBtn").prop("disabled", "disabled");785 $("#recoverBtn").prop("disabled", "disabled");786 $("#delSnapBtn").addClass("disabled");787 $("#recoverBtn").addClass("disabled");788 $("#delSnapBtn .plugin_button_div").css("cursor", "default");789 $("#recoverBtn .plugin_button_div").css("cursor", "default");790 $("#chk_all").prop("checked", "");791 }792 });793}794function getSnapName(lunName) {795 var cTime = new Date();796 var cMon = subTime("" + (cTime.getMonth() + 1));797 var cDate = subTime("" + cTime.getDate());798 var cHou = subTime("" + cTime.getHours());799 var cMin = subTime("" + cTime.getMinutes());800 var cSec = ("" + cTime.getSeconds());801 var suffix = ("" + cTime.getFullYear()).substring(2, 4) + cMon + cDate + cHou + cMin + cSec + cTime.getMilliseconds();802 var snapshotName = lunName;803 if (snapshotName.length > 16) {804 snapshotName = snapshotName.substring(0, 16);805 }806 snapshotName = snapshotName + suffix;807 return snapshotName;808}809function subTime(tStr) {810 tStr = tStr.length == 1 ? "0" + tStr : tStr;811 return tStr;812}813function chkSnapName() {814 var sName = $("#cSnapshotName").val();815 if (isEmpObj(sName)) {816 $("#backupBtn").prop("disabled", true);817 }818 else {819 $("#backupBtn").prop("disabled", false);820 }821}822function lock() {823 $("#popupDiv").show();824 $("#ingDiv1").show();825}826function unlock() {827 $("#popupDiv").hide();828 $("#ingDiv1").hide();829}830function getLength(value) {831 var byteValLen = 0;832 var val = value.match(/./g);833 if (null == val) {834 return byteValLen;835 }836 for (var i = 0; i < val.length; i++) {837 if (val[i].match(/[^\x00-\xff]/ig) != null) {838 byteValLen += 3;839 } else {840 byteValLen += 1;841 }842 }843 return byteValLen;844}845function getByteVal(value, max) {846 var returnValue = "";847 var byteValLen = 0;848 var val = value.match(/./g);849 if (null == val) {850 return returnValue;851 }852 for (var i = 0; i < val.length; i++) {853 if (val[i].match(/[^\x00-\xff]/ig) != null) {854 byteValLen += 3;855 } else {856 byteValLen += 1;857 }858 if (byteValLen > max) {859 break;860 }861 returnValue += val[i];862 }863 return returnValue;864}865function trim(str) {866 return str.replace(/(^\s*)|(\s*$)/g, "");...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

1// Utils 公共函数2//Utils命名空间中的函数可以在页面脚本中调用3Utils = {};4utils = Utils;5Utils.sendMsg = function(type, datas, callback){6 var msg = jQuery.extend(true, {type: type}, datas || {});7 chrome.runtime.sendMessage(msg, callback);8};9Utils.putLog = function(text, level, read){10 var logfuns = [console.log, console.info, console.warn, console.error];11 level = level && (level < 4) ? level : 1;12 if(typeof(text) !== 'string')13 text = JSON.stringify(text);14 logfuns[level].call(console, text);15};16/* Extend function 模拟面向对象的类继承 */17Utils.extend = function(subClass, superClass) {18 var F = function() {};19 F.prototype = superClass.prototype;20 subClass.prototype = new F();21 subClass.prototype.constructor = subClass;22 subClass.superClass = superClass.prototype;23 if (superClass.prototype.constructor == Object.prototype.constructor) {24 superClass.prototype.constructor = superClass;25 }26};27//通过浏览器内置的dom解析器,将相对url转换为绝对url28Utils.getAbsURL = function(url) {29 var a = document.createElement('a');30 a.href = url;31 return a.href;32};33//打印错误信息并关闭页面34Utils.failAndClose = function(text) {35 Utils.putLog(text, 4);36 safesite.finishPage({37 discard: true38 });39};40//打印错误信息和重试次数, 然后重新加载页面,再关闭页面。41Utils.failAndRetry = function(text, page, retryTime) {42 var pageData = page.data.length ? JSON.parse(page.data) : {};43 var link = location.href;44 var times = retryTime || 3;45 pageData.retry = pageData.retry ? pageData.retry + 1 : 1;46 if (pageData.retry > times) {47 failAndClose(text + '...已重试' + times + '次!');48 return;49 }50 Utils.putLog(text + '...重试第' + pageData.retry + '次...');51 safesite.addPage({52 url: link,53 force: true,54 front: true,55 priority: 'high',56 savedir: page.savedir,57 savename: page.savename,58 data: JSON.stringify(pageData)59 });60 safesite.finishPage({61 discard: true62 });63};64//将 json 数据写入 csv 文件。 见 forum 模板的应用。65Utils.writeJsonToCsv = function(file, data, firstTime) {66 var line = '';67 if (typeof(data) === 'string') {68 line = data;69 } else if (typeof(data) === 'object') {70 for (var i in data) {71 if (data.hasOwnProperty(i)) {72 var text = String(data[i]).replace(/[,\r\n]/g, ' ');73 line += text + ',';74 }75 }76 }77 if (!line)78 return false;79 line = line.replace(/,$/, '\n');80 if (line.charAt(line.length - 1) !== '\n')81 line += '\n';82 if (firstTime) {83 Utils.putLog('创建文件:' + file, 0);84 safesite.fopen({85 path: file,86 mode: 'a',87 header: line88 });89 } else {90 safesite.fwrite({91 path: file,92 text: line93 });94 }95 return true;96};97//获取文本中的数字;98//参数 obj 可以是字符串, 也可以是 html或$对象99//regex可以指定,也可以不指定100//返回值是一个数字数组。如果没找到正则表达式的内容, 则返回空数组。101Utils.getNumbers = function(obj, regex) {102 var text = obj;103 if (typeof(obj) === 'object') {104 text = $(obj).text();105 }106 regex = regex || /\d+/;107 var m = text.match(regex);108 if (m) {109 return m.map(function(e) {110 var n = parseInt(e, 10);111 return n || 0;112 });113 } else {114 return [];115 }116};117//getNumbers的简单形式, 不接受正则表达式参数, 返回数字。118Utils.getNumber = function(obj) {119 var res = Utils.getNumbers(obj);120 return res.length ? res[0] : 0;121};122//对指定DOM元素的鼠标事件123//element是指要操作的元素124//action指定要模拟的事件,可以为"Click","RightClick",125// "LeftDown","LeftUp","RightDown","RightUp"126Utils.elementMouseEvent = function(element, action) {127 var rc = element.getBoundingClientRect();128 var scroll_pos = rc.bottom - rc.height;129 if (scroll_pos > $(document).height())130 scroll_pos = $(document).height();131 Utils.putLog('Scroll to ' + scroll_pos, 0);132 $("html, body").scrollTop(scroll_pos);133 rc = element.getBoundingClientRect();134 var X = rc.left + rc.width / 2;135 var Y = rc.bottom - rc.height / 2;136 Utils.putLog(action + ' at ' + X + ' x ' + Y, 0);137 safesite.mouseEvent({138 action: action,139 x: parseInt(X, 10),140 y: parseInt(Y, 10)141 });142};143//使用 jQuery 获取某个元素144//context:指定查找范围,其必须是有效的元素145//如果不指定范围,可以设置为0或''146//selector:指定要查找的元素147//position: 可以为数字或者是 "first" 或 "last", 默认为 0。148// 返回值为 dom 对象,如果没有获取到则返回 null149Utils.getElement = function(selector, context, position) {150 context = context || document;151 position = position || 0;152 var nodes = jQuery(selector, context);153 if (!nodes.length)154 return null;155 else {156 if (position === 'first')157 return nodes[0];158 else if (position === 'last')159 return nodes.last()[0];160 else if (typeof(position) === 'number')161 return position >= nodes.length ? null : nodes[position];162 else163 return null;164 }165};166//安全地获取元素的属性值167//context:指定查找范围168//selector:指定要查找的元素169//position: 可以为数字或者是 "first" 或 "last", 默认为 0。170//attribute: 属性名称, 先尝试获取 dom 元素的属性, 如没有则尝试 jQuery.attr() 函数;171//defaultValue: 默认返回值, 如果属性为空则返回该默认值。172//返回值是一个代表属性的字符串。173Utils.getElementAttribute = function (selector, context, position, attribute, defaultValue) {174 defaultValue = defaultValue || '';175 attribute = attribute || 'innerText';176 var element = Utils.getElement(selector, context, position);177 if (!element) {178 return '';179 } else if (element.hasOwnProperty(attribute)) {180 return element[attribute] || defaultValue;181 } else {182 return jQuery(element).attr(attribute) || defaultValue;183 }184};185//转义写入CSV文件中的特殊字符186//实际将出现的英文逗号转换为中文的逗号187Utils.escapeCSV = function(text) {188 if (typeof(text) != 'string')189 return '';190 return text.replace(/,/g, ',');191};192//将文件名中的路径分隔符转义193Utils.escapePath = function(text) {194 if (typeof(text) != 'string')195 return '';196 text = text.replace(/\\/g, ' ');197 return text.replace(/\//g, ' ');198};199//延时回调200//timeout为超时的毫秒数201Utils.delayedExecute = function(timeout, callback) {202 var interval = 100;203 function delay() {204 timeout -= interval;205 if (timeout <= 0) {206 window.clearInterval(id);207 callback();208 }209 }210 var id = window.setInterval(delay, interval);211};212//解析日期时间213//支持如下记法:214// * 2010-11-27 [00:05] (ISO标准时间格式)215// * 05-18 [18:25] (日期无年份)216// * 11:31[:34] (仅时间,日期为今日)217// * 39秒钟前/2 分钟前/5小时前/7 天前 (中文相对时间)218// * 今天 18:50 / 9月3日 [上午]20:24219// * 2013年10月1日 [10时9分38秒]220// 注:以上记法中'-'和'/'是相等的221//返回值为标准的Date对象222Utils.parseDateTime = function(str) {223 var current = new Date();224 var invalid = new Date(NaN);225 var matches = [];226 var offset = 0,227 unit = 0,228 offset_seconds = 0,229 yesterday = 0;230 if (typeof(str) != "string")231 return invalid;232 str = str.replace(/\s/g, ' ');233 str = str.trim();234 //首先用标准的Date.parse()函数来尝试解析字符串,235 //但是对于"05-18 [18:25]"这种无年份的简写情况,236 //可以解析成功但得到的年份不对,因此需要首先处理这种特殊情况237 if (/^\d{1,2}(\/|-|\.)\d{1,2}(\ |$)/.test(str)) {238 str = String(current.getFullYear()) + '-' + str;239 }240 //尝试使用标准ISO格式解析字符串241 var parsed = Date.parse(str);242 if (!isNaN(parsed)) {243 return new Date(parsed);244 }245 //判断是否是仅时间记法,即'11:31'或'11:31:23'246 if (/^\d{1,2}:\d{1,2}(:\d{1,2}|)/.test(str)) {247 matches = (str).match(/^(\d{1,2}):(\d{1,2})(:|)(\d{1,2}|)/);248 current.setHours(matches[1]);249 current.setMinutes(matches[2]);250 if (matches[4].length)251 current.setSeconds(matches[4]);252 return current;253 }254 //判断是否是中文相对时间记法255 if (str.indexOf('前') != -1 &&256 str.indexOf('前天') == -1) {257 //移除空格258 str = str.replace(/\s/g, '');259 //得到偏移值和时间单位260 if (str.indexOf('半') != -1) {261 matches = str.match(/半(\S+)前/);262 if (matches !== null) {263 offset = 0.5;264 unit = matches[1];265 } else266 return invalid;267 } else {268 matches = str.match(/(\d+)(\S+)前/);269 if (matches !== null) {270 offset = matches[1];271 unit = matches[2];272 } else273 return invalid;274 }275 if (unit == '秒' || unit == '秒钟') {276 offset_seconds = offset;277 } else if (unit == '分' || unit == '分钟') {278 offset_seconds = offset * 60;279 } else if (unit == '时' || unit == '小时') {280 offset_seconds = offset * 60 * 60;281 } else if (unit == '日' || unit == '天') {282 offset_seconds = offset * 60 * 60 * 24;283 } else if (unit == '月' || unit == '个月') {284 offset_seconds = offset * 60 * 60 * 24 * 30;285 } else if (unit == '年') {286 offset_seconds = offset * 60 * 60 * 24 * 30 * 12;287 } else {288 //Utils.putLog('无效的时间单位', 3);289 return invalid;290 }291 return new Date(current.getTime() - offset_seconds * 1000);292 }293 //中文格式如:294 //今天 18:50295 //9月3日 [上午]20:24296 //2013年10月1日 [10时9分38秒]297 if (str.indexOf('今天') != -1) {298 str = str.replace('今天', current.toDateString() + ' ');299 } else if (str.indexOf('昨天') != -1) {300 yesterday = new Date(current.getTime() - 60 * 60 * 24 * 1000);301 str = str.replace('昨天', yesterday.toDateString() + ' ');302 } else if (str.indexOf('前天') != -1) {303 yesterday = new Date(current.getTime() - 60 * 60 * 24 * 2 * 1000);304 str = str.replace('前天', yesterday.toDateString() + ' ');305 }306 if (str.indexOf('年') != -1) {307 str = str.replace('年', '-');308 }309 if (str.indexOf('月') != -1) {310 str = str.replace('月', '-');311 }312 if (str.indexOf('日') != -1) {313 str = str.replace('日', ' ');314 }315 if (str.indexOf('时') != -1) {316 str = str.replace('时', ':');317 }318 if (str.indexOf('分') != -1) {319 if (str.indexOf('秒') != -1)320 str = str.replace('分', ':');321 else322 str = str.replace('分', ' ');323 }324 if (str.indexOf('秒') != -1) {325 str = str.replace('秒', ' ');326 }327 if (str.indexOf('上午') != -1) {328 str = str.replace('上午', ' ');329 str += ' am';330 }331 if (str.indexOf('下午') != -1) {332 str = str.replace('下午', ' ');333 str += ' pm';334 }335 //转换为英文后再试336 parsed = Date.parse(str);337 if (!isNaN(parsed)) {338 return new Date(parsed);339 }340 return invalid;341};342Utils.withinDaysInternal = function(date, n) {343 if (isNaN(date.getTime()))344 return false;345 var current = new Date();346 if (date.getTime() > current.getTime())347 return false;348 if (current.getTime() - date.getTime() <349 1000 * 60 * 60 * 24 * n)350 return true;351 return false;352};353//指定日期时间是否是最近一天内354Utils.withinDay = function(time_str) {355 return Utils.withinDaysInternal(Utils.parseDateTime(time_str), 1);356};357//指定日期时间是否是最近一周内358Utils.withinWeek = function(time_str) {359 return Utils.withinDaysInternal(Utils.parseDateTime(time_str), 7);360};361//指定日期时间是否是最近一月内362Utils.withinMonth = function(time_str) {363 return Utils.withinDaysInternal(Utils.parseDateTime(time_str), 30);364};365//指定日期时间是否是最近一年内366Utils.withinYear = function(time_str) {367 return Utils.withinDaysInternal(Utils.parseDateTime(time_str), 365);368};369//截取frame中的窗口时可能需要滚动, 则滚动一屏截取一张图片, 直到截取到底端为止。370Utils.snapShotFrame = function(frameSelector, maindoc, savename, savedir, onFinish) {371 maindoc = maindoc || document;372 var node = $(frameSelector, maindoc);373 var doc = $(frameSelector, maindoc)[0].contentDocument;374 (function ss(index) {375 index = index || 0;376 safesite.snapshot({377 savedir: savedir,378 savename: index ? savename + '_' + index : savename379 }, function(detail) {380 //bugfix, 此处每一次都要重新获取高度, 因为网页可能会改变。381 var winHeight = node.height(),382 docHeight = $(doc).height(),383 curScrollTop = $(doc).scrollTop();384 Utils.putLog('snapShotFrame: winHeight x docHeight x curScrollTop = ' + winHeight + ' x ' + docHeight + ' x ' + curScrollTop, 0);385 if (curScrollTop < docHeight - winHeight) {386 $(doc).scrollTop(curScrollTop + winHeight);387 delayedExecute(1000, ss(index + 1));388 } else {389 onFinish(detail);390 }391 });392 }());393};394//自动滚动到页面底端395//直到appear指定元素出现并且disappear元素消失396//如果appear或disappear 元素为空, 则只判断另一种元素397//timeout:超时时间(毫秒数),该函数精度为1毫秒398//回调函数参数:false表示超时399Utils.autoScroll = function(appear_selector, disappear_selector, process) {400 var interval = 600, //ms401 timeOut = 15000, //ms402 id = 0;403 var doScroll = function() {404 Utils.putLog('autoScroll...', 0);405 var appear = $(appear_selector);406 var disappear = $(disappear_selector);407 timeOut -= interval;408 if ($(document).height() - $(window).height() === $(document).scrollTop()) {409 if ((!appear_selector || appear.length) && (!disappear_selector || !disappear.length)) {410 $("html, body").scrollTop(0);411 window.clearInterval(id);412 process(true);413 return;414 }415 }416 if (timeOut < 0) {417 $("html, body").scrollTop(0);418 window.clearInterval(id);419 process(false);420 return;421 }422 $("html, body").scrollTop($(document).height());423 };424 $("html, body").scrollTop($(document).height());425 id = window.setInterval(doScroll, interval);426};427//往下滚动一屏, 然后回调处理, 直至末尾。428//process: 回调函数, 每滚动一屏时调用。 如果返回false, 则不再往下滚动。 429//例子见 Google+ 模板430Utils.scrollDown = function(process) {431 var interval = 1000,432 scrollCount = 0;433 (function _scrollDown() {434 scrollCount += 1;435 var cur_pos = $(document).scrollTop(),436 win_h = $(window).height();437 $(document).scrollTop(cur_pos + win_h);438 Utils.putLog('scrollDown...('+scrollCount+')', 0);439 delayedExecute(1200, function() {440 var cur_pos = $(document).scrollTop(),441 doc_h = $(document).height();442 if (cur_pos < doc_h - win_h) {443 if (process() !== false) {444 _scrollDown();445 }446 } else {447 process(true);448 }449 });450 }());451};452//等待 comparefunc 完成后回调 process453//compareFunc 只有返回 true 才会继续执行 Process454Utils.waitCompare = function(compareFunc, process){455 var interval = 1000, //ms456 timeOut = 30000, //ms457 el = [];458 if(!compareFunc){459 process(true);460 return;461 }462 var doCompare = function(){463 Utils.putLog('waitCompare...', 0);464 timeOut -= interval;465 var res = compareFunc();466 if(res || timeOut<0){467 window.clearInterval(id);468 process(timeOut > 0);469 }470 };471 var id = window.setInterval(doCompare, interval);472};473//因为某些页面需要加载ajax, 所以用此方法来判断ajax是否已经加载完, 474//然后才处理页面。475//process的参数, 如果超时了为false, 否则true。476Utils.waitForAjax = function(selector, context, process) {477 var interval = 1000; //ms478 var timeOut = 10000; //ms479 var id = 0,480 el = [];481 var doPage = function() {482 Utils.putLog('waitForAjax...', 0);483 timeOut -= interval;484 el = $(selector, context);485 if (el.length >= 1 || timeOut <= 0) {486 window.clearInterval(id);487 process(timeOut > 0);488 }489 };490 id = window.setInterval(doPage, interval);491};492//如果ajax的内容用frame包含起来了,则用此函数等待frame中的内容加载493//然后才处理页面。494//frames可以是一个 frame 的选择器字符串,也可以为字符串数组, 代表多个frame依次包含。495//process的参数, 如果超时了为false, 否则true。496Utils.waitForAjaxInFrame = function(selector, frames, process) {497 var interval = 1000; //ms498 var timeOut = 10000; //ms499 var id = 0,500 el = [];501 var doPage = function() {502 Utils.putLog('waitForAjaxInFrame...', 0);503 timeOut -= interval;504 if (typeof(frames) === 'string') {505 frames = [frames];506 }507 var f = '';508 for (var i = 0; i < frames.length; i++) {509 f = $(frames[i], f);510 if (f.length > 0) {511 f = f[0].contentDocument;512 } else {513 f = '';514 Utils.putLog(frames[i], 0);515 break;516 }517 }518 if (f) {519 el = $(selector, f);520 if (el.length > 0) {521 window.clearInterval(id);522 process(true);523 }524 }525 if (timeOut <= 0) {526 window.clearInterval(id);527 process(false);528 }529 };530 id = window.setInterval(doPage, interval);531};532Utils.waitForChange = function(origin, selector, context, attrName, process) {533 //等待页面元素发生改变后调用process.534 //如果 origin 未定义, 则不等待直接调用process535 //process的参数, 如果超时则为false, 否则为true;536 var interval = 1000, //ms537 timeOut = 10000, //ms538 el = [];539 if (origin === undefined) {540 process(true);541 return;542 }543 var doCompare = function() {544 //Utils.putLog('waitForChange, origin: '+origin, 0);545 Utils.putLog('waitForChange...', 0);546 timeOut -= interval;547 el = $(selector, context);548 var present = el.attr(attrName);549 if ((el.length > 0 && origin != present) || timeOut <= 0) {550 window.clearInterval(id);551 process(timeOut > 0);552 }553 };554 var id = window.setInterval(doCompare, interval);555};556Utils.waitForTextChange = function(origin, selector, context, process) {557 //等待页面元素发生改变后调用process.558 //不同于上面的函数, 这里比较的是 元素的 text。559 //process的参数, 如果超时则为false, 否则为true;560 //如果 origin 未定义, 则不等待直接调用process561 var interval = 500, //ms562 timeOut = 10000, //ms563 el = [];564 if (origin === undefined) {565 process(true);566 return;567 }568 var doCompare = function() {569 // Utils.putLog('waitForTextChange——origin: '+origin, 0);570 Utils.putLog('waitForTextChange...', 0);571 timeOut -= interval;572 el = $(selector, context);573 var present = el.text();574 // Utils.putLog('waitForTextChange——present: '+present, 0);575 if ((el.length > 0 && origin != present) || timeOut <= 0) {576 window.clearInterval(id);577 process(timeOut > 0);578 }579 };580 var id = window.setInterval(doCompare, interval);581};582Utils.waitForTextChangeInFrame = function(origin, selector, frames, process) {583 //等待页面元素发生改变后调用process.584 //不同于上面的函数, 这里比较的是 元素的 text。585 //process的参数, 如果超时则为false, 否则为true;586 //如果 origin 未定义, 则不等待直接调用process587 var interval = 500, //ms588 timeOut = 15000; //ms589 if (origin === undefined) {590 process(true);591 return;592 }593 var doCompare = function() {594 // Utils.putLog('waitForTextChange——origin: '+origin, 0);595 Utils.putLog('waitForTextChangeInFrame...', 0);596 timeOut -= interval;597 if (typeof(frames) === 'string') {598 frames = [frames];599 }600 var f = '';601 for (var i = 0; i < frames.length; i++) {602 f = $(frames[i], f);603 if (f.length > 0) {604 f = f[0].contentDocument;605 } else {606 f = '';607 break;608 }609 }610 if (f) {611 var el = $(selector, f);612 var present = el.text();613 // Utils.putLog('waitForTextChange——present: '+present, 0);614 if (el.length > 0 && origin != present) {615 window.clearInterval(id);616 process(true);617 return;618 }619 }620 if (timeOut <= 0) {621 window.clearInterval(id);622 process(false);623 return;624 }625 };626 var id = window.setInterval(doCompare, interval);...

Full Screen

Full Screen

snapshot_controller.js

Source:snapshot_controller.js Github

copy

Full Screen

1/**2 * "The Software contains copyright protected material, trade secrets and other proprietary information3 * and material of ObjectVideo, Inc. and/or its licensor(s), if any, and is protected by copyright laws,4 * international copyright treaties and trade secret laws, as well as other intellectual property laws and5 * treaties. One or more claims of U.S. Patent Nos. 6,696,945, 6,970,083, 6,954,498, 6,625,310, 7,224,852,6 * 7,424,175, 6,687,883, 6,999,600, 7,424,167, 7,391,907 may apply to this Software."7 */8/**9 * @file snapshot_controller.js10 * snapshot module, controller object11 */12if (objectvideo.snapshot === undefined) {13 objectvideo.snapshot = {};14}15(function($) {16 /**17 * Returns a new snapshot controller instance.18 * @return {Object} A snapshot controller object.19 */20 objectvideo.snapshot.controller = function() {21 var _width=352;22 var _height=288;23 24 /**25 * objectvideo.snapshot.snapshotPlayer object.26 * @type {Object}27 */28 var _snapPlayer = null;29 /**30 * objectvideo.snapshot.markupCanvas object for drawing static shapes.31 * @type {Object}32 * @see _drawingCanvas33 */34 var _staticCanvas = null;35 /**36 * objectvideo.snapshot.markupCanvas object for drawing user-interactive shapes.37 * @type {Object}38 * @see _staticCanvas39 */40 var _drawingCanvas = null;41 /**42 * Size of the markup pane before it is expanded.43 * @type {Object}44 */45 var _savedMarkupSize = null;46 /**47 * Information about a drawing operation.48 * @type {Object}49 */50 var _drawInfo = {51 /**52 * True if we have processed a left button mouse down event53 * since the last left button mouse up event.54 * @type {Boolean}55 */56 isMouseLeftDown: false,57 /**58 * True if we have processed a right button mouse down event59 * since the last right button mouse up event.60 * @type {Boolean}61 */62 isMouseRightDown: false,63 /**64 * The value of event.which from the most recent mouseup event.65 * This value can be used to determine whether a click event66 * is for the left or right mouse button.67 * @type {Number}68 */69 lastMouseUpButton: undefined,70 /**71 * True if in drag mode, false otherwise.72 * @type {Boolean}73 */74 isDragging: false,75 /**76 * The index of the control point on the shape being dragged.77 * @type {Number}78 */79 controlIndex: -1,80 /**81 * The last point from a mouse move event.82 * @type {Object}83 */84 lastPt: null,85 /**86 * An arrays of point objects specifiying the event defintion87 * shape coordinates, in canvas coordinates, for the markup88 * being created/edited.89 */90 points: [],91 baseSetStart: function(pt, hitInfo) {92 if ((! pt) || (pt.x === undefined)) {93 throw new Error('Invalid argument pt');94 }95 this.isMouseLeftDown = true;96 this.points = [ pt ];97 if (hitInfo) {98 this.controlIndex = (hitInfo.isInControl ? hitInfo.controlIndex : -1);99 }100 },101 baseReset: function() {102 this.isMouseLeftDown = false;103 this.isMouseRightDown = false;104 this.isDragging = false;105 this.controlIndex = -1;106 this.points = [];107 this.lastPt = null;108 },109 startPoint: function() {110 return (this.points.length > 0) ? this.points[0] : null;111 },112 endPoint: function() {113 if (this.points.length > 0) {114 return this.points[this.points.length - 1];115 }116 return null;117 },118 setEndPoint: function(pt) {119 this.points[1] = pt;120 },121 scalePoints: function(oldWidth, oldHeight, newWidth, newHeight) {122 var i, pt;123 for (i = 0; i < this.points.length; i++) {124 pt = this.points[i];125 pt.x = (pt.x / oldWidth) * newWidth;126 pt.y = (pt.y / oldHeight) * newHeight;127 this.points[i] = pt;128 }129 if (this.lastPt) {130 this.lastPt.x = (this.lastPt.x / oldWidth) * newWidth;131 this.lastPt.y = (this.lastPt.y / oldHeight) * newHeight;132 }133 }134 };135 // Return the actual controller object.136 return {137 /**138 * Initializes this object's staticCanvas and drawingCanvas fields.139 * @param {Object} snapshotPlayer A snapshotPlayer object.140 * @return {Object} This object141 */142 init: function(snapshotPlayer) {143 var canvasElt;144 // Initialize snapshot marker canvas.145 if (window.G_vmlCanvasManager) {146 try {147 // Re-create the canvas element via the excanvas library.148 canvasElt = document.createElement('canvas');149 canvasElt.setAttribute('id', 'snapshot_markup');150 canvasElt.setAttribute('width', _width);151 canvasElt.setAttribute('height', _height);152 canvasElt = G_vmlCanvasManager.initElement(canvasElt);153 $('#snapshot_markup').after($(canvasElt)).remove();154 }155 catch (ex) {156 $.log('Error initializing Explorer Canvas: ' + ex.name + ' - ' + ex.message);157 canvasElt = null;158 }159 }160 else {161 canvasElt = $('#snapshot_markup')[0];162 }163 _staticCanvas = objectvideo.snapshot.markupCanvas($(canvasElt));164 // Initialize the interactive drawing canvas.165 if (window.G_vmlCanvasManager) {166 try {167 // Re-create the canvas element via the excanvas library.168 canvasElt = document.createElement('canvas');169 canvasElt.setAttribute('id', 'snapshot_interactive_drawing');170 canvasElt.setAttribute('width', _width);171 canvasElt.setAttribute('height', _height);172 canvasElt = G_vmlCanvasManager.initElement(canvasElt);173 $('#snapshot_interactive_drawing').after($(canvasElt)).remove();174 }175 catch (ex) {176 $.log('Error initializing Explorer Canvas: ' + ex.name + ' - ' + ex.message);177 if (ex.stack) {178 $.log(ex);179 }180 canvasElt = null;181 }182 }183 else {184 canvasElt = $('#snapshot_interactive_drawing')[0];185 }186 _drawingCanvas = objectvideo.snapshot.markupCanvas($(canvasElt));187 _snapPlayer = snapshotPlayer;188 _snapPlayer.update();189 },190 /**191 * Gets this object's snapshotPlayer object.192 * @return {Object} The snapshotPlayer object passed to the init method.193 * @see init#194 */195 snapPlayer: function() {196 return _snapPlayer;197 },198 /**199 * Gets the markupCanvas for drawing static shapes.200 * @type {Object} An instance of objectvideo.snapshot.markupCanvas201 * @see drawingCanvas#202 * @see init#203 */204 staticCanvas: function() {205 return _staticCanvas;206 },207 /**208 * Gets the markupCanvas for drawing user-interactive shapes.209 * @type {Object} An instance of objectvideo.snapshot.markupCanvas210 * @see staticCanvas#211 * @see init#212 */213 drawingCanvas: function() {214 return _drawingCanvas;215 },216 /**217 * Gets this object's drawInfo data.218 * @return {Object} A drawInfo object.219 */220 drawInfo: function() {221 return _drawInfo;222 },223 /**224 * Gets the saved markup size.225 * @return {Object} A size object.226 * @see setSavedMarkupSize#227 */228 getSavedMarkupSize: function() {229 return _savedMarkupSize;230 },231 /**232 * Sets the saved markup size.233 * @param {Number} w Width234 * @param {Number} h Height235 * @see getSavedMarkupSize#236 */237 setSavedMarkupSize: function(w, h) {238 _savedMarkupSize = {239 width: w,240 height: h241 };242 },243 /**244 * Creates a new point object whose coordinates are constrained to245 * canvas coordinates.246 * @param {Number} x The unconstrained x-axis page coordinate of the point.247 * @param {Number} y The unconstrained y-axis page coordinate of the point.248 * @return {Object} A new point object whose coordinates are non-negative249 * integers no greater than the width or height of the250 * drawing canvas, relative to the top, left corner of251 * the canvas.252 */253 createCanvasPoint: function(x, y) {254 var offset, dCanvas;255 if (isNaN(x)) {256 throw new Error('Invalid argument: x is not a number');257 }258 if (isNaN(y)) {259 throw new Error('Invalid argument: y is not a number');260 }261 // Offset the point relative to the interactive drawing canvas.262 offset = $('#snapshot_interactive_drawing').offset();263 // Use Math.min to choose the smaller of x/y and canvas width/height,264 // then Math.max to choose the larger of x/y and zero, then265 // use Math.round to get a whole number.266 dCanvas = this.drawingCanvas();267 return objectvideo.geometry.createPoint(268 Math.round(Math.max(0, Math.min(dCanvas.width(), x - offset.left))),269 Math.round(Math.max(0, Math.min(dCanvas.height(), y - offset.top))));270 },271 /**272 * Calculates the size of an expanded markup area based on273 * the size of the browser window.274 * @return {Object} A size object containing numeric properties275 * width and height.276 */277 getExpandedMarkupSize: function() {278 var borderWidth = 32; // width of .rborder_vertical * 2279 var borderHeight = 32; // height of .rborder_horizontal * 2280 var borderPadding = 10; // extra padding outside borders281 var extraBottomPadding = 20; // extra padding at bottom of window282 var markupPane = $('#markup_pane');283 var snapshotFrame = $('#snapshot_frame');284 var paddingW, paddingH;285 var size = {286 width: 0,287 height: 0288 };289 var oldSize = {290 width: snapshotFrame.width(),291 height: snapshotFrame.height()292 };293 paddingW = markupPane.width() - snapshotFrame.width();294 paddingH = markupPane.height() - snapshotFrame.height();295 // Calculate whether to leave extra space beneath border.296 if (($('#markup_error_message').is(':visible')) ||297 ($('#markup_warning_message').is(':visible')) ||298 ($('#markup_hint_message').is(':visible'))) {299 extraBottomPadding = 0;300 }301 // Calculate full frame height, then scale width accordingly.302 size.height = Math.floor($(window).height() - markupPane.offset().top -303 paddingH - borderHeight - borderPadding - extraBottomPadding);304 size.width = Math.floor(oldSize.width * (size.height / oldSize.height));305 if (size.width + markupPane.offset().left + paddingW + borderWidth > $(window).width()) {306 // Scaled width is too wide, so instead calculate307 // full frame width, then scale height accordingly.308 size.width = Math.floor($(window).width() - markupPane.offset().left -309 paddingW - borderWidth - borderPadding);310 size.height = Math.floor(oldSize.height * (size.width / oldSize.width));311 }312 return size;313 },314 /**315 * Enables or disables the expand markup icon based on316 * the size of the browser window. The expand_snapshot icon/button317 * will be disabled if the expanded markup size would be either shorter318 * or narrower than the size of the default markup content area.319 * @return {Object} This object.320 * @see getExpandedMarkupSize#321 */322 resetExpandButton: function() {323 var size = this.getExpandedMarkupSize();324 var snapshotFrame = $('#snapshot_frame');325 if ((size.height > (snapshotFrame.height() * 1.25)) ||326 (size.width > (snapshotFrame.width() * 1.25))) {327 $('#expand_snapshot').removeClass('disabled');328 }329 else {330 $('#expand_snapshot').addClass('disabled');331 }332 return this;333 },334 /**335 * Toggles between normal page layout and expanded rule336 * snapshot/markup layout.337 * @param {Boolean} isExpanding True if the expanded markup should be338 * shown, false if the expanded markup should be hidden.339 */340 toggleExpandedMarkupMode: function(isExpanding) {341 var that = this;342 var borderWidth = 32; // width of .rborder_vertical * 2343 var borderPadding = 10; // extra padding outside borders344 var markupPane = $('#markup_pane');345 var markupContent = $('#markup_content');346 var snapshotFrame = $('#snapshot_frame');347 var newSize, oldSize;348 var fxDuration = 'normal';349 var expandedWidth, expandedHeight;350 var imgBorderWidth = snapshotFrame.outerWidth() - snapshotFrame.width();351 oldSize = {352 width: snapshotFrame.width(),353 height: snapshotFrame.height()354 };355 // Calculate new position and sizes.356 if (isExpanding) {357 // Save frame size for later, when we restore.358 that.setSavedMarkupSize(oldSize.width, oldSize.height);359 newSize = that.getExpandedMarkupSize();360 // Exit immediately if the new size is somehow not361 // larger than the existing size.362 if ((newSize.height <= oldSize.height) || (newSize.width <= oldSize.width)) {363 return;364 }365 // Set explicit width and height for #expanded_markup_frame,366 // so that border elements will size correctly.367 expandedWidth = $('#edit_snapshot_pane').width() +368 $('#tool_palette').outerWidth(true) - snapshotFrame.width() +369 newSize.width + borderWidth + borderPadding;370 expandedHeight = $('#edit_snapshot_pane').height() -371 snapshotFrame.height() + newSize.height + borderPadding;372 $('#expanded_markup_frame').width(expandedWidth)373 .height(expandedHeight);374 $('#expand_snapshot').addClass('collapse_snapshot');375 }376 else {377 newSize = that.getSavedMarkupSize();378 $('#expand_snapshot').removeClass('collapse_snapshot');379 }380 // Show/hide the overlay.381 if (isExpanding) {382 $('#expanded_markup_overlay').show();383 objectvideo.fadeInOverlay($('#markup_overlay_screen'), fxDuration);384 }385 else {386 $('#markup_overlay_screen').fadeOut(fxDuration, function() {387 $('#expanded_markup_overlay').hide();388 });389 }390 // Hide the markupContent via a custom animation.391 // Notes:392 // - Setting queue: false will cause the animation to run in393 // parallel with the call above to fade the overlay in/out.394 // - Callback function 'complete' performs the actual DOM395 // manipulation to expand/shrink markup.396 markupContent.animate({ opacity: 'hide' }, {397 duration: fxDuration,398 queue: false,399 complete: function() {400 var offset;401 // Transform coordinates of any existing points in drawInfo.402 that.drawInfo().scalePoints(oldSize.width, oldSize.height,403 newSize.width, newSize.height);404 if (isExpanding) {405 // Move the element into the overlay,406 // then position its new container.407 offset = markupPane.offset();408 $('#expanded_markup_pane').append($(this));409 $('#filters_pane').fadeOut();410 markupPane.hide();411 $('#expanded_markup_frame').css({412 top: Math.floor(offset.top) + 'px',413 left: Math.floor(offset.left) + 'px'414 });415 }416 else {417 // Move the element into markupPane.418 markupPane.prepend($(this));419 markupPane.show();420 $('#filters_pane').fadeIn();421 }422 // Resize the snapshot pane elements.423 snapshotFrame.width(newSize.width).height(newSize.height);424 _snapPlayer.setDimensions(newSize.width, newSize.height);425 if (window.G_vmlCanvasManager) {426 // Explicitly resize the excanvas-created div inside the canvas element.427 $('#snapshot_markup > div').width(newSize.width).height(newSize.height);428 $('#snapshot_interactive_drawing > div').width(newSize.width).height(newSize.height);429 }430 that.setDimensions(newSize.width, newSize.height).redraw();431 $('#markup_and_filters_pane').css('max-width', Math.floor(newSize.width * 1.5));432 $('#markup_error_message').width(newSize.width + imgBorderWidth);433 $('#snapshot_actions_pane').width(newSize.width + imgBorderWidth);434 $('#edit_snapshot_pane').width(newSize.width + imgBorderWidth);435 // Show the element again.436 $(this).fadeIn(fxDuration);437 }438 });439 },440 /**441 * Sets the dimensions for the static and drawing canvases.442 * @param {Number} width Width in pixels.443 * @param {Number} height Height in pixels.444 * @return {Object} This object.445 */446 setDimensions: function(width, height) {447 var snapshot = $('#snapshot');448 var snapshotFrame = $('#snapshot_frame');449 var frameWidth, frameOuterWidth, frameHeight;450 if (typeof width !== 'number' || isNaN(width)) {451 throw new Error('setDimensions - invalid argument: width is not a number');452 }453 if (typeof height !== 'number' || isNaN(height)) {454 throw new Error('setDimensions - invalid argument: height is not a number');455 }456 // Set frame size to snapshot size, plus borders (if any)457 frameWidth = width + (snapshot.outerWidth() - snapshot.width());458 frameHeight = height + (snapshot.outerHeight() - snapshot.height());459 snapshotFrame.width(frameWidth).height(frameHeight);460 // Set the snapshot element sizes to the frame's outer width and height.461 frameOuterWidth = snapshotFrame.outerWidth();462 $('#edit_snapshot_pane').width(frameOuterWidth);463 if (_staticCanvas) {464 _staticCanvas.setDimensions(width, height);465 if (window.G_vmlCanvasManager) {466 $('#snapshot_markup > div').width(width).height(height);467 }468 }469 if (_drawingCanvas) {470 _drawingCanvas.setDimensions(width, height);471 if (window.G_vmlCanvasManager) {472 $('#snapshot_interactive_drawing > div').width(width).height(height);473 }474 }475 // Explicitly set width of snapshot_actions_pane to center contained text.476 $('#snapshot_actions_pane').width(frameOuterWidth);477 if (_snapPlayer) {478 _snapPlayer.update();479 _snapPlayer.setDimensions(width,height);480 }481 return this;482 },483 /**484 * Redraws both static and drawing canvases.485 * @return {Object} This object.486 */487 redraw: function() {488 if (_staticCanvas) {489 _staticCanvas.redraw();490 }491 if (_drawingCanvas) {492 _drawingCanvas.redraw();493 }494 return this;495 },496 /**497 * Redraws both static and drawing canvases.498 * @return {Object} This object.499 */500 show: function() {501 if (_staticCanvas) {502 _staticCanvas.show();503 }504 if (_drawingCanvas) {505 _drawingCanvas.show();506 }507 return this;508 },509 /**510 * ¸ù¾Ý´«ÈëµÄÖµ¸ü¸ÄÏߵĿí¶È.511 * @param {Number} thickness ÏߵĴÖϸֵ.512 * @{Object} This markupCanvas object.513 * @exception {Error} Èç¹û´«ÈëµÄÖµ²¢·ÇÊý×Ö»òֵСÓÚ1514 */515 setLineThickness: function (thickness) {516 if (isNaN(thickness)||thickness<1) {517 throw new Error('Invalid argument: thickness');518 }519 if (_staticCanvas) {520 _staticCanvas.setLineThickness(thickness);521 _staticCanvas.show();522 }523 //if (_drawingCanvas) {524 // _drawingCanvas.setLineThickness(thickness);525 // _drawingCanvas.show();526 //}527 return this;528 }529 };530 };...

Full Screen

Full Screen

decode.js

Source:decode.js Github

copy

Full Screen

1//ar Parser = require('../lib/binary_parser').Parser;2var Parser = require('binary-parser').Parser;3//var crc = require('crc');4var crc16 = require('crc-itu').crc16;5module.exports.decodeMessage = decodeMessage;6var dateTime = new Parser()7 .uint8('day')8 .uint8('month')9 .uint8('year')10 .uint8('hour')11 .uint8('minute')12 .uint8('second');13var statData = new Parser()14 .endianess('little')15 //Parser.start()16 // Unix time17 .uint32('acc_on_time')18 // Unix time19 .uint32('utc_time')20 .uint32le('mileage_total')21 .uint32le('mileage_current')22 .uint32le('fuel_total')23 .uint16le('fuel_current')24 // TODO: Decode VEH_STATE details.25 .uint32('veh_state')26/* .nest('vstate_flags', {27 type: new Parser()28 .bit1('east_long')29 .bit1('north_lat')30 .bit2('test')31 .bit4('num_satellites')32*/ .string('reserved', {33 encoding: 'hex',34 length: 835 });36var gpsItem = new Parser()37 .endianess('little')38 .nest('date_time', {39 // 3 byes for date, 3 bytes for time.40 type: dateTime41 })42 .uint32le('latitude')43 .uint32le('longitude')44 .uint16le('speed')45 .uint16le('direction')46 .nest('flags', {47 type: new Parser()48 .bit1('east_long')49 .bit1('north_lat')50 .bit2('test')51 .bit4('num_satellites')52 });53// Acceleration Data, GSENSOR_DATA.54var gData = new Parser()55 .endianess('little')56 .int16('x')57 .int16('y')58 .int16('z');59var alarmItems = new Parser()60 .endianess('little')61 .uint8('new_alarm_flag')62 .uint8('alarm_type')63 // TODO: Alarm description is to be further decoded.64 .uint16('alarm_desc')65 .uint16('alarm_threshold');66var TLVItems = new Parser()67 .endianess('little')68 .uint16('tag')69 .uint16('length')70 .array('values', {71 type: 'int8',72 length: 'length'73 });74//-----------------------------------------75var LoginPackage = new Parser()76 //Parser.start()77 .nest('stat_data', {78 // 34 bytes79 type: statData80 })81 .uint8('gps_active')82 // Decode as GPS ITEM only if GPS enabled.83 .choice('gps_item', {84 tag: 'gps_active',85 choices: {86 // Nothing to decode 87 0x00: new Parser(),88 // 20 bytes 89 0x01: gpsItem 90 },91 // TODO: Check this.92 defaultChoice: new Parser()93 })94 .string('sw_version', {95 encoding: 'utf8',96 length: 2097 })98 .string('hw_version', {99 encoding: 'utf8',100 length: 20101 });102var LogoutPackage = new Parser()103 .nest('stat_data', {104 // 34 bytes105 type: statData106 })107 .uint8('gps_active')108 // Decode as GPS ITEM only if GPS enabled.109 .choice('gps_item', {110 tag: 'gps_active',111 choices: {112 // Nothing to decode 113 0x00: new Parser(),114 // 20 bytes 115 0x01: gpsItem 116 },117 // TODO: Check this.118 defaultChoice: new Parser()119 })120// Nothing to decode. Just need to reply.121var HeartBeatPackage = new Parser();122var GPSPackage = new Parser()123 // history(1) or realtime(0).124 .uint8('history')125 .nest('stat_data', {126 // 34 bytes127 // UTC_Time is the sample time of the last GPS data.128 type: statData129 })130 // The first byte of GPS_DATA is interpreted differently131 // in LoginPackage and GPSPackage.132 .uint8('gps_count')133 .array('gps_items', {134 type: gpsItem,135 length: 'gps_count'136 })137 // RPM_DATA138 // if val = 0xffff, invalid RPM.139 .uint8('rpm_count')140 .array('rpm_items', {141 type: 'uint16le',142 length: 'rpm_count'143 });144var PIDPackage = new Parser()145 .endianess('little')146 .nest('stat_data', {147 // 34 bytes148 type: statData149 })150 .uint16('pid_sample_rate')151 .uint8('pid_type_count')152 .array('pid_type', {153 type: 'uint16le',154 length: 'pid_type_count'155 })156 .uint8('pid_group_count')157 .uint8('pid_group_size')158 // TODO: Properly decode PID Group items.159 .array('pid_data', {160 type: 'uint8',161 // TODO: Fix this.162 length: 1163 //length: function() { return (pid_group_count*pid_group_size); }164 });165var GSensorPackage = new Parser()166 .endianess('little')167 .nest('stat_data', {168 // 34 bytes169 type: statData170 })171 .uint16('g_sample_rate')172 .uint8('g_group_count')173 .array('g_data', {174 // Each gData item is 6 bytes.175 type: gData,176 length: 'g_group_count'177 });178var PIDTypesPackage = new Parser()179 .endianess('little')180 .nest('stat_data', {181 // 34 bytes182 type: statData183 })184 .uint8('pid_type_count')185 .array('pid_type', {186 type: 'uint16le',187 length: 'pid_type_count'188 });189// TODO: Decoding in not complete, the tail does not match.190var SnapshotFrame = new Parser()191 .endianess('little')192 .nest('stat_data', {193 // 34 bytes194 type: statData195 })196 .uint8('frozen_flag')197 .uint8('pid_type_count')198 .array('pid_type', {199 type: 'uint16le',200 length: 'pid_type_count'201 })202 // TODO: Decode PID data properly.203 .array('pid_data', {204 type: 'uint8',205 length: 'pid_type_count'206 });207var DTCsCar = new Parser()208 .endianess('little')209 .nest('stat_data', {210 // 34 bytes211 type: statData212 })213 .uint8('dtc_flag')214 .uint8('dtc_count')215 .array('dtc_vals', {216 type: 'uint16le',217 length: 'dtc_count'218 });219var DTCsCommercial = new Parser()220 .endianess('little')221 .nest('stat_data', {222 // 34 bytes223 type: statData224 })225 .uint8('dtc_flag')226 .uint8('dtc_count')227 .array('dtc_vals', {228 // TODO: To be further decoded.229 type: 'uint32le',230 length: 'dtc_count'231 });232var AlarmsPackage = new Parser()233 .endianess('little')234 .uint32('alarm_seq_num')235 .nest('stat_data', {236 // 34 bytes237 type: statData238 })239 // TODO: GPS_DATA not described properly, count-flag/enabled-flag?.240 // Currently treated as enabled-flag, with zero or one GPS item.241 // 0 -> disabled or 0 items242 .uint8('gps_active')243 // Decode as GPS ITEM only if GPS enabled.244 .choice('gps_item', {245 tag: 'gps_active',246 choices: {247 // Nothing to decode 248 0x00: new Parser(),249 // 20 bytes 250 0x01: gpsItem 251 },252 // TODO: Check this.253 defaultChoice: new Parser()254 })255 .uint8('alarm_count')256 .array('alarms', {257 // Each item takes 6 bytes..258 type: alarmItems,259 length: 'alarm_count'260 });261var CellId = new Parser()262 .endianess('little')263 .nest('stat_data', {264 // 34 bytes265 type: statData266 })267 .uint16('local_area_code')268 .uint16('cell_id');269var GPSReportInSleep = new Parser()270 .endianess('little')271 .uint32('utc_time')272 .nest('gps_item', {273 // 19 bytes274 type: gpsItem275 });276var DriverCardId = new Parser()277 .endianess('little')278 .nest('stat_data', {279 // 34 bytes280 type: statData281 })282 .array('card_id', {283 type: 'uint8',284 // TODO: Variable length. May have to search till crc/tail data.285 length: 1286 //length: function() { return this.dataLength - 4; }287 //readUntil: function(item, buffer) { return item === oxodoa; }288 });289var AGPSRequest = new Parser()290 .endianess('little')291 .nest('gps_item', {292 // 19 bytes293 type: gpsItem294 });295var SettingResponse = new Parser()296 .endianess('little')297 .uint16('cmd_seq_num')298 .uint8('success_tag_count')299 .array('success_tags', {300 type: 'uint16le',301 length: 'success_tag_count'302 });303var QueryResponse = new Parser()304 .endianess('little')305 .uint16('cmd_seq_num')306 .uint8('resp_count')307 .uint8('resp_index')308 .uint8('fail_count')309 .array('fail_tags', {310 type: 'uint16le',311 length: 'fail_count'312 })313 .uint8('success_count')314 .array('success_tlvs', {315 type: TLVItems,316 length: 'success_count'317 });318var CurrentLocation = new Parser()319 .endianess('little')320 .uint16('cmd_seq_num')321 .nest('stat_data', {322 // 34 bytes323 type: statData324 })325 .uint8('gps_active')326 // Decode as GPS ITEM only if GPS enabled.327 .choice('gps_item', {328 tag: 'gps_active',329 choices: {330 // Nothing to decode 331 0x00: new Parser(),332 // 20 bytes 333 0x01: gpsItem 334 },335 // TODO: Check this.336 defaultChoice: new Parser()337 })338var ClearDTCResp = new Parser()339 .endianess('little')340 .uint16('cmd_seq_num')341 .uint8('flag');342var RestoreFactorySetResp = new Parser()343 .endianess('little')344 .uint16('cmd_seq_num')345 .uint8('flag');346var TextInfo = new Parser()347 .endianess('little')348 .uint16('cmd_seq_num')349 // TODO: Variable length. Will it be automatically handled?350 .string('info', {351 encoding: 'ascii',352 zeroTerminated: 'true'353 });354var TextInfoResp = new Parser()355 .endianess('little')356 .uint16('cmd_seq_num')357 .uint8('flag');358var UpdateConfirm = new Parser()359 .endianess('little')360 .uint32('update_id')361 .string('firmware_version', {362 encoding: 'ascii',363 length: 16364 })365 .uint8('update_confirmation');366var UpdateMessageConfirm = new Parser()367 .endianess('little')368 .uint32('update_id')369 .uint8('receive_mark')370 .uint16('message_index');371var AGPSConfirm = new Parser()372 .endianess('little')373 .uint8('agps_index')374 .uint8('agps_mark');375//-------------------------------------------376var Message = new Parser()377 //Parser.start()378 .endianess('little')379 .uint16('header')380 .uint16('length')381 .uint8('version')382 .string('dev_id', {383 encoding: 'hex',384 length: 20385 })386/*387 .string('dev_id', {388 encoding: 'ascii',389 length: 15390 })391 // TODO: length: 20, 392 // last 5 chars are now ignored (issue -> hex 00=null).393 .string('dev_id_reserved', {394 encoding: 'hex',395 length: 5396 })397*/398 .uint16be('type')399 .choice('payload', {400 tag: 'type',401 choices: {402 0x1001: LoginPackage,403 0x1002: LogoutPackage,404 0x1003: HeartBeatPackage,405 0x4001: GPSPackage,406 0x4002: PIDPackage, // TODO:407 0x4003: GSensorPackage,408 0x4004: PIDTypesPackage,409 0x4005: SnapshotFrame, // TODO:410 0x4006: DTCsCar,411 0x400B: DTCsCommercial,412 0x4007: AlarmsPackage,413 0x4008: CellId,414 0x4009: GPSReportInSleep,415 0x400C: DriverCardId,416 0x5101: AGPSRequest,417 0xA001: SettingResponse,418 0xA002: QueryResponse,419 0xB001: CurrentLocation,420 0xB002: ClearDTCResp,421 0xB003: RestoreFactorySetResp,422 0x3006: TextInfo,423 0xB006: TextInfoResp,424 0xD001: UpdateConfirm,425 0xD002: UpdateMessageConfirm,426 0xD102: AGPSConfirm427 },428 // TODO: handle this.429 defaultChoice: new Parser()430 })431 .uint16('crc16')432 .uint16('tail');433// var buf = new Buffer('40407F000431333630303030303030310000000000000000001001C1F06952FDF069529C91110000000000698300000C0000000000036401014C00030001190A0D04121A1480D60488C5721800000000AF4944445F3231364730325F532056312E322E31004944445F3231364730325F482056312E322E31000000DF640D0A', 'hex');434// var dcMsg = Message.parse(buf);435function decodeMessage(obdData) {436 var dcMsg = Message.parse(obdData);437 //console.log(dcMsg);438 return dcMsg;439}440//console.log(dcMsg);441//console.log(dcMsg.type);442/*var connection = mysql.createConnection({443 host : 'localhost',444 user : 'root',445 password : 'root123',446 database : 'obd'447});448connection.connect();449connection.query('INSERT INTO location SET ?',450 {dev_id: '23', timestamp: '12345678', longitude: '123.12', latitude: '22.45'},451 function(err, result) {452 if (err) throw err;453 console.log(result.insertId);454});455connection.query('SELECT * from location', function(err, rows, fields) {456 if (!err)457 console.log('The solution is: ', rows);458 else459 console.log('Error while performing Query.');460});461connection.end();462*/463/*464var buf2 = new Buffer('40407F000431303031313132353239393837000000000000001001C1F06952FDF069529C91110000000000698300000C0000000000036401014C00030001190A0D04121A1480D60488C5721800000000AF4944445F3231364730325F532056312E322E31004944445F3231364730325F482056312E322E31000000', 'hex');465//var crcInHex = crc.crc16ccitt(buf2).toString(16);466//var res = crc.crc16(buf2);467var crcInHex = crc16(buf2).toString(16);468console.log(crcInHex);469//console.log(Message.parse(buf));470*/471/*472require('fs').readFile('Hello.class', function(err, data) {473 console.log(require('util').inspect(Message.parse(data), {depth: null}));474});...

Full Screen

Full Screen

snapshotTab.js

Source:snapshotTab.js Github

copy

Full Screen

1$(document).ready(function() {2 initData();3 bindEvent();4});5function initData() {6 var request = new Object();7 request = GetRequest();8 var url = "";9 var lunReq = "";10 if(parent.lun_fs_flag == "lun") {11 url = parent.ns.webContextPath + "/rest/data/host/snapshot";12 lunReq = new req(url, "storageId=" + parent.devObj.id + "&volumeId=" + parent.lunObj.id + "&start=" + request["start"] + "&count=" + request["pagesize"] + "&t=" + new Date());13 } else if(parent.lun_fs_flag == "fs") {14 url = parent.ns.webContextPath + "/rest/nfsdata/fsSnapshot";15 lunReq = new req(url, "storageId=" + parent.devObj.id + "&fsId=" + parent.fsObj.id + "&start=" + request["start"] + "&count=" + request["pagesize"] + "&t=" + new Date());16 }17 var lunhandler = new handler(function doSuccess(resp) {18 if(resp.errorCode) {19 parent.$("#divLoadingSnapshot").hide();20 $("#divError").text(resp.errorDesc).show();21 return;22 }23 resp.data.forEach(function(item, index, array) {24 item.activatedAt = new Date(item.activatedAt);25 })26 a2t("#snapshotTable tbody", "#cloneSnap", resp.data);27 $("#snapshotTable td[name='activatedAt']").each(function() {28 $(this).html(new Date($(this).html()))29 });30 $("#cloneSnap").remove();31 scroll("snapshotTab", "snapshotTabDiv", 1, parent.divhead_id_snapshot, "snapshotTable");32 parent.init();33 parent.$("#divLoadingSnapshot").hide();34 }, function doFailed() {35 parent.$("#divLoadingSnapshot").hide();36 });37 sendMsg(lunReq, lunhandler);38}39function bindEvent() {40 $("#snapshotTable tbody tr").each(function() {41 $(this).find("td").each(function() {42 if($(this).index() != 2) {43 $(this).click(function() {44 console.log("click the tr");45 if($(this).parent("tr").find("td").eq(2).find("input").is(":checked")) {46 $(this).parent("tr").find("td").eq(2).find("input").prop("checked", false);47 } else {48 $(this).parent("tr").find("td").eq(2).find("input").prop("checked", true);49 }50 clickSingleCheckBox();51 });52 }53 });54 });55}56function clickSingleCheckBox() {57 var num = 0;58 var $singleChkbox = parent.$("#snapshotFrame")[0].contentWindow.$("input[id^='snapCheckbox_']");59 $singleChkbox.each(function(i) {60 if(this.checked) {61 num++;62 }63 });64 if(num == parent.rowNum) {65 if(!parent.$("#chk_all")[0].checked) {66 parent.$("#chk_all").prop("checked", "checked");67 }68 } else {69 parent.$("#chk_all").prop("checked", "");70 }71 if(num > 0) {72 parent.$("#delSnapBtn").prop("disabled", "");73 parent.$("#delSnapBtn").removeClass("disabled");74 parent.$("#delSnapBtn .plugin_button_div").css("cursor", "pointer");75 if(num == 1) {76 if(parent.lun_fs_flag == "lun") {77 var lunRunningStatus = parent.$("#snapshotFrame")[0].contentWindow.$("input[id^='snapCheckbox_']:checked").parent().parent().find("td[name='runningStatus']").text();78 if(lunRunningStatus == "INACTIVATED") {79 parent.$("#recoverBtn").prop("disabled", "disabled");80 parent.$("#recoverBtn").addClass("disabled");81 parent.$("#recoverBtn .plugin_button_div").css("cursor", "default");82 } else {83 parent.$("#recoverBtn").prop("disabled", "");84 parent.$("#recoverBtn").removeClass("disabled");85 parent.$("#recoverBtn .plugin_button_div").css("cursor", "pointer");86 }87 } else if(parent.lun_fs_flag == "fs") {88 parent.$("#recoverBtn").prop("disabled", "");89 parent.$("#recoverBtn").removeClass("disabled");90 parent.$("#recoverBtn .plugin_button_div").css("cursor", "pointer");91 }92 } else {93 parent.$("#recoverBtn").prop("disabled", "disabled");94 parent.$("#recoverBtn").addClass("disabled");95 parent.$("#recoverBtn .plugin_button_div").css("cursor", "default");96 }97 } else {98 parent.$("#delSnapBtn").prop("disabled", "disabled");99 parent.$("#recoverBtn").prop("disabled", "disabled");100 parent.$("#delSnapBtn").addClass("disabled");101 parent.$("#recoverBtn").addClass("disabled");102 parent.$("#delSnapBtn .plugin_button_div").css("cursor", "default");103 parent.$("#recoverBtn .plugin_button_div").css("cursor", "default");104 parent.$("#chk_all").prop("checked", "");105 }106}107function scroll(viewid, scrollid, size, divhead_id, tabid) {108 if(parent.$("#" + divhead_id).length > 0) {109 parent.$("#" + divhead_id).width($("#" + tabid).width());110 return;111 }112 var scroll = parent.document.getElementById(scrollid);113 var tb2 = parent.document.getElementById(viewid).cloneNode(true);114 var $table = $(parent.document.getElementById(viewid));115 if($table.find("input[type='checkbox']").length > 0) {116 var id = $(tb2).find("input[type='checkbox']:first").attr("id");117 $table.find("input[type='checkbox']:first").removeAttr("id");118 $(tb2).find("input[type='checkbox']:first").attr("id", id);119 }120 for(var i = tb2.rows.length; i > size; i--) {121 tb2.deleteRow(size);122 }123 var top = parent.$("#" + viewid).offset().top;124 var left = parent.$("#" + viewid).offset().left;125 var bak = parent.document.createElement("div");126 scroll.appendChild(bak);127 bak.appendChild(tb2);128 bak.setAttribute("id", divhead_id);129 bak.style.position = "fixed";130 $(bak).css({131 "left": left,132 "top": top,133 width: $("#" + tabid).width(),134 backgroundColor: "#cfc",135 display: "block"136 });137 parent.$("#" + viewid).find("th").each(function() {138 this.innerHTML = "";139 });140}141function GetRequest() {142 var url = location.search; 143 var theRequest = new Object();144 if(url.indexOf("?") != -1) {145 var str = url.substr(1);146 strs = str.split("&");147 for(var i = 0; i < strs.length; i++) {148 theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);149 }150 }151 return theRequest;152}153function trim(str) {154 return str.replace(/(^\s*)|(\s*$)/g, "");...

Full Screen

Full Screen

lunTab.js

Source:lunTab.js Github

copy

Full Screen

1$(document).ready(function () {2 bindEvent();3 initData();4});5function initData() {6 var request = new Object();7 request = GetRequest();8 parent.$("#divLoadingLun").show();9 var url = "";10 if (parent.lun_fs_flag == "lun") {11 url = parent.urlForLun + parent.hostId + "?" +12 "serverGuid=" + parent.serverGuid +13 "&filterType=" + parent.filterType +14 "&filterValue=" + parent.filterValue +15 "&start=" + request["start"] + "&count=" + request["pagesize"] + "&t=" + new Date();16 } else if (parent.lun_fs_flag == "fs") {17 url = parent.urlForFs + parent.hostId + "?" +18 "serverGuid=" + parent.serverGuid +19 "&filterType=" + parent.filterType +20 "&filterValue=" + parent.filterValue +21 "&start=" + request["start"] + "&count=" + request["pagesize"] + "&t=" + new Date();22 }23 var lunReq = new req(url, "");24 var lunhandler = new handler(function doSuccess(resp) {25 if (resp.errorCode) {26 parent.$("#divLoadingLun").hide();27 $("#divError").text(resp.errorDesc).show();28 return;29 }30 a2t("#hostLunTbody", "#cloneLun", resp.data);31 scroll("hostLunTab", "lunTabDiv", 1, parent.divhead_id_lun, "hostLunTable");32 parent.$("#divLoadingLun").hide();33 parent.$('#snapshotFrame').prop("src", "");34 parent.$("#pager2").remove();35 parent.$("#recoverBtn").addClass("disabled");36 parent.$("#recoverBtn").prop("disabled", "disabled");37 parent.$("#refreshSnapBtn").addClass("disabled");38 parent.$("#delSnapBtn").addClass("disabled");39 parent.$("#delSnapBtn").prop("disabled", "disabled");40 }, function doFailed() {41 parent.$("#divLoadingLun").hide();42 });43 sendMsg(lunReq, lunhandler);44}45/**46 * Only provide radio buttons, do not provide bulk snapshot / backup function, if provided and no longer pass the checkbox47 */48function bindEvent() {49 $("#hostLunTable tbody tr").bind("click", function (event) {50 $("#hostLunTable tbody tr td").css("background-color", "#FFFFFF");51 $(this).find('td').each(function (i) {52 $(this).css("background-color", "#abcefc");53 });54 if (parent.lun_fs_flag == "lun") {55 parent.lunObj.id = $(this).find("[name='id']").text();56 parent.lunObj.name = $(this).find("[name='name']").text();57 parent.lunObj.status = $(this).find("[name='status']").text();58 parent.lunObj.usedType = $(this).find("[name='usedType']").text();59 } else if (parent.lun_fs_flag == "fs") {60 parent.fsObj.id = $(this).find("[name='id']").text();61 parent.fsObj.name = $(this).find("[name='name']").text();62 parent.fsObj.usedByStatus = $(this).find("[name='usedByStatus']").text();63 parent.fsObj.datastoreId = $(this).find("[name='datastoreId']").text();64 //for mount65 parent.fsObj.localPath = $(this).find("[name='localPath']").text();66 parent.fsObj.remoteHost = $(this).find("[name='remoteHost']").text();67 parent.fsObj.remotePath = $(this).find("[name='remotePath']").text();68 }69 parent.devObj.id = $(this).find("[name='storageId']").text();70 parent.$("#refreshSnapBtn").prop("disabled", "");71 parent.$("#refreshSnapBtn").removeClass("disabled");72 parent.$("#refreshLunBtn").prop("disabled", "");73 parent.$("#showBackupBtn").prop("disabled", "");74 parent.$("#showBackupBtn").removeClass("disabled");75 parent.loadSnapshots();76 });77}78/*79 * Lock header (for subpages)80 * viewid Parent page table id81 * scrollid Parent page scrollbar container id82 * size Keep the number of rows in the table when copying83 * divhead_id Copy header id84 * tabid Subpage table id85 */86function scroll(viewid, scrollid, size, divhead_id, tabid) {87 if (parent.$("#" + divhead_id).length > 0) {88 parent.$("#" + divhead_id).width($("#" + tabid).width());89 return;90 }91 var scroll = parent.document.getElementById(scrollid);92 var tb2 = parent.document.getElementById(viewid).cloneNode(true);93 var $table = $(parent.document.getElementById(viewid));94 if ($table.find("input[type='checkbox']").length > 0) {95 var id = $(tb2).find("input[type='checkbox']:first").attr("id");96 $table.find("input[type='checkbox']:first").removeAttr("id");97 $(tb2).find("input[type='checkbox']:first").attr("id", id);98 }99 for (var i = tb2.rows.length; i > size; i--) {100 tb2.deleteRow(size);101 }102 var top = parent.$("#" + viewid).offset().top;103 var left = parent.$("#" + viewid).offset().left;104 var bak = parent.document.createElement("div");105 scroll.appendChild(bak);106 bak.appendChild(tb2);107 bak.setAttribute("id", divhead_id);108 bak.style.position = "fixed";109 $(bak).css({110 "left": left,111 "top": top,112 width: $("#" + tabid).width(),113 backgroundColor: "#cfc",114 display: "block"115 });116 parent.$("#" + viewid).find("th").each(function () {117 this.innerHTML = "";118 });119}120function GetRequest() {121 var url = location.search;122 var theRequest = new Object();123 if (url.indexOf("?") != -1) {124 var str = url.substr(1);125 strs = str.split("&");126 for (var i = 0; i < strs.length; i++) {127 theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);128 }129 }130 return theRequest;...

Full Screen

Full Screen

script.js

Source:script.js Github

copy

Full Screen

1function qsl(s) { return document.querySelector(s); }2let ctx = qsl('#canvas1').getContext('2d');3function setCtxDrawOpts(ctx, drawOpts) {4 ctx.fillStyle = drawOpts.fillStyle || ctx.fillStyle;5 ctx.strokeStyle = drawOpts.strokeStyle || ctx.strokeStyle;6 ctx.font = drawOpts.font || ctx.font;7}8function getCtxDrawOpts(ctx) {9 return {10 fillStyle: ctx.fillStyle,11 strokeStyle: ctx.strokeStyle,12 font: ctx.font,13 }14}15function drawLayers(layers, ctx) {16 let sortedByZOrderLayers =17 layers.sort(18 (l1, l2) =>19 (l1.zOrder < l2.zOrder) ? -1 : (l1.zOrder === l2.zOrder) ? 0 : 120 );21 // reset canvas, clearing all state22 ctx.canvas.width = ctx.canvas.width;23 for (layer of sortedByZOrderLayers) {24 if (layer.ready === false) {25 console.log(`skipping layer ${layer.type} (not ready)`)26 continue;27 }28 if (layerHandlers[layer.type] !== undefined) {29 layerHandlers[layer.type](layer, ctx);30 } else {31 console.error(`handler for layer type: ${layer.type} not defined`);32 //console.error(layer);33 }34 }35}36let layerHandlers = {37 'text': function (layer, ctx) {38 ctx.save();39 setCtxDrawOpts(ctx, layer.drawOpts || getCtxDrawOpts(ctx));40 ctx.fillText(layer.text, layer.rect.x, layer.rect.y);41 ctx.restore();42 },43 'image': function (layer, ctx) {44 ctx.save();45 // TODO - implement scaling/rotation, check if layer has46 // options for scaling/rotation47 ctx.drawImage(layer.image, layer.rect.x, layer.rect.y);48 ctx.restore();49 }50}51function makeLayer() {52 return {53 rect: { x: 0, y: 0, w: 0, h: 0 },54 ready: false,55 zOrder: 0,56 drawOpts: { font: '24px sans-serif', fillStyle: 'black' },57 }58}59// naming is hard :(60function makeImageLayer(options) {61 return new Promise(62 (resolve, reject) => {63 let imgObj = {64 ...makeLayer(),65 type: 'image',66 url: options.url || '',67 image: undefined,68 ready: false,69 ...options,70 };71 imgObj.image = new Image();72 imgObj.image.crossOrigin = 'anonymous';73 imgObj.image.src = options.url || '';74 imgObj.image.onload = function () {75 imgObj.ready = true;76 resolve(imgObj);77 }78 });79}80// TODO this does not need to return a promise81function makeTextLayer(options) {82 return new Promise(83 (resolve, reject) => {84 let textObj = {85 ...makeLayer(),86 type: 'text',87 text: options.text || 'text missing',88 ready: true,89 ...options,90 }91 resolve(textObj);92 });93}94let layerMakers = {95 'text': makeTextLayer,96 'image': makeImageLayer,97}98async function makeLayers(layerDescriptions) {99 console.log('creating layers, loading images etc...');100 let a = []101 for(ld of layerDescriptions){102 if(layerMakers[ld.type] !== undefined){103 a.push( layerMakers[ld.type](ld));104 }else{105 console.error(`no idea how to make layer of type ${ld.type}`);106 }107 }108 let layers = await Promise.all(a);109 console.log('finished making layers');110 return layers;111}112let XXX = [113 {114 type: 'text',115 text: 'lol butts',116 rect: { x: 100, y: 100, w: 0, h: 0 },117 drawOpts: { font: '100px sans-serif', fillStyle: 'red' },118 zOrder: 1,119 },120 {121 type: 'image',122 url: 'https://picsum.photos/512/384',123 rect: { x: 0, y: 0, w: 0, h: 0 },124 zOrder: -100125 }126];127qsl('#txt_layers').value = JSON.stringify(XXX, undefined, 2)128async function generate() {129 let layerDescriptions = f();130 let layers = await makeLayers(layerDescriptions);131 drawLayers(layers, ctx);132}133function clearErrorMessage(){134 qsl('#txt_errorMsg').innerHTML = '';135}136function setErrorMessage(msg) {137 console.error(msg);138 qsl('#txt_errorMsg').innerHTML = msg;139}140function f() {141 const layerDescriptionsJson = qsl('#txt_layers').value142 let layerDescriptions;143 try {144 layerDescriptions = JSON.parse(layerDescriptionsJson);145 } catch (error) {146 setErrorMessage(error);147 return [];148 }149 qsl('#txt_layers').value = JSON.stringify(layerDescriptions, undefined, 2);150 clearErrorMessage();151 return layerDescriptions;152}153function hideSnapshotFrame(){154 console.log('hideSnapshotFrame');155 const snapshotFrame = qsl('#snapshotFrame1');156 snapshotFrame.style.display = 'none'157}158function copyCanvasToImage(){159 const snapshotFrame = qsl('#snapshotFrame1');160 snapshotFrame.style.display = ''161 const targetImageElement = qsl('#targetImage1')162 targetImageElement.src = ctx.canvas.toDataURL();163}164function setCanvasSize(){165 const DEFAULT_WIDTH = 512;166 const DEFAULT_HEIGHT = 384;167 let canvasWidth = Number.parseInt(qsl('#txt_canvasWidth').value);168 let canvasHeight= Number.parseInt(qsl('#txt_canvasHeight').value);169 // bad input for some reason, reset to defaults170 if(isNaN(canvasWidth) || isNaN(canvasHeight)){171 canvasWidth = DEFAULT_WIDTH;172 canvasHeight = DEFAULT_HEIGHT;173 qsl('#txt_canvasWidth').value = canvasWidth;174 qsl('#txt_canvasHeighth').value = canvasHeight;175 }176 const canvasElement = qsl('#canvas1')177 canvasElement.width = canvasWidth;178 canvasElement.height = canvasHeight;179 console.log(canvasWidth, canvasHeight);180}...

Full Screen

Full Screen

Video.js

Source:Video.js Github

copy

Full Screen

1import Overlay from "./Overlay.js";2import Spinner from "./Spinner.js";3import Warning from "./Warning.js";4export function Video(props) {5 let vid = React.useRef();6 let [isCameraEnabled, setCameraEnabled] = React.useState(false);7 let [showsSnapshot, setShowsSnapshot] = React.useState(false);8 // Async does not work here...9 const getSnapShotFrame = () => {10 if (!isCameraEnabled) return;11 let videoTrack = vid.current.srcObject.getVideoTracks()[0];12 vid.current.pause();13 new ImageCapture(videoTrack)14 .grabFrame(videoTrack)15 .then((imageFrame) => getSnapShotDataFromFrame(imageFrame));16 };17 const getSnapShotDataFromFrame = (snapShotFrame) => {18 let offscreenCanvas = new OffscreenCanvas(1000, 1000);19 let ctx = offscreenCanvas.getContext("2d");20 ctx.drawImage(21 snapShotFrame,22 0,23 0,24 offscreenCanvas.width,25 offscreenCanvas.height26 );27 offscreenCanvas.convertToBlob({ type: "image/jpeg" }).then((blob) => {28 props.onSnapShot(blob);29 if (blob != null) setShowsSnapshot(true);30 });31 };32 const turnOnCamera = async () => {33 props.resetImgData();34 let videoStream = await navigator.mediaDevices.getUserMedia({35 // width and height are inverted because on Android36 // the orientation seems to be inverted aswell...37 // TODO: Detect device and handle width/height accordingly38 video: {39 width: 1720,40 height: 1180,41 facingMode: "environment",42 },43 });44 vid.current.srcObject = videoStream;45 setCameraEnabled(true);46 setShowsSnapshot(false);47 };48 const turnOffCamera = () => {49 vid.current.srcObject.getVideoTracks()[0].stop();50 vid.current.srcObject = null;51 setCameraEnabled(false);52 setShowsSnapshot(false);53 props.resetImgData();54 };55 return (56 <div className="video-area">57 <div className="outer-video-frame">58 <div className="video-frame">59 <div className="invisible-wrapper">60 <video ref={vid} autoPlay />61 <Overlay active={props.isTransmitting}>62 <Spinner />63 </Overlay>64 <Overlay active={!isCameraEnabled}>65 <Warning text="Enable Camera before taking a photo" />66 </Overlay>67 </div>68 </div>69 </div>70 <div className="video-frame-overlay" />71 <div className="controls">72 <button73 onClick={showsSnapshot ? turnOnCamera : () => {}}74 className={`${showsSnapshot ? "" : "disabled"}`}75 >76 Reset Camera77 </button>78 <button onClick={getSnapShotFrame}>Take Photo</button>79 <button onClick={isCameraEnabled ? turnOffCamera : turnOnCamera}>80 {`Turn ${isCameraEnabled ? "OFF" : "ON"} Camera`}81 </button>82 </div>83 </div>84 );85}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const element = await page.$('input');7 await element.snapshotFrame({ path: 'screenshot.png' });8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 const element = await page.$('input');16 await element.snapshotFrame({ path: 'screenshot.png', type: 'png' });17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 const element = await page.$('input');25 await element.snapshotFrame({ path: 'screenshot.png', type: 'jpeg' });26 await browser.close();27})();28const { chromium } = require('playwright');29(async () => {30 const browser = await chromium.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 const element = await page.$('input');34 await element.snapshotFrame({ path: 'screenshot.png', type: 'webp' });35 await browser.close();36})();37const { chromium } = require('playwright');38(async () => {39 const browser = await chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 const element = await page.$('input');43 await element.snapshotFrame({ path: 'screenshot.png', type: 'png', quality: 80 });44 await browser.close();45})();46const {

Full Screen

Using AI Code Generation

copy

Full Screen

1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.waitForSelector('text=Get started');7 await page.snapshotFrame('frameName', { timeout: 1000, path: 'snapshot.png' });8 await browser.close();9})();10const {chromium} = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 await page.waitForSelector('text=Get started');16 await page.snapshotFrame('frameName', { timeout: 1000, path: 'snapshot.png' });17 await browser.close();18})();19const {chromium} = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.waitForSelector('text=Get started');25 await page.snapshotFrame('frameName', { timeout: 1000, path: 'snapshot.png' });26 await browser.close();27})();28const {chromium} = require('playwright');29(async () => {30 const browser = await chromium.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 await page.waitForSelector('text=Get started');34 await page.snapshotFrame('frameName', { timeout: 1000, path: 'snapshot.png' });35 await browser.close();36})();37const {chromium} = require('playwright');38(async () => {39 const browser = await chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('text=Get started');7 await page.waitForSelector('.navbar__inner');8 const frame = page.mainFrame().childFrames()[0];9 await frame.waitForSelector('text=Hello, world!');10 await frame.snapshotFrame({ path: 'frame.png' });11 await browser.close();12})();13const playwright = require('playwright');14(async () => {15 const browser = await playwright.chromium.launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 await page.click('text=Get started');19 await page.waitForSelector('.navbar__inner');20 const frame = page.mainFrame().childFrames()[0];21 await frame.waitForSelector('text=Hello, world!');22 const elementHandle = await frame.$('text=Hello, world!');23 await elementHandle.snapshotElement({ path: 'element.png' });24 await browser.close();25})();26const playwright = require('playwright');27(async () => {28 const browser = await playwright.chromium.launch();29 const context = await browser.newContext();30 const page = await context.newPage();31 await page.click('text=Get started');32 await page.waitForSelector('.navbar__inner');33 const frame = page.mainFrame().childFrames()[0];34 await frame.waitForSelector('text=Hello, world!');35 await frame.snapshot({ path: 'snapshot.png' });36 await browser.close();37})();38const playwright = require('playwright');39(async () => {40 const browser = await playwright.chromium.launch();41 const context = await browser.newContext();42 const page = await context.newPage();43 await page.click('text=Get started');44 await page.waitForSelector('.navbar__inner');45 const frame = page.mainFrame().childFrames()[

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const path = require('path');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.waitForTimeout(3000);8 await page.snapshotFrame({ path: path.join(__dirname, 'snapshot.png') });9 await browser.close();10})();11const { chromium } = require('playwright');12const path = require('path');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.waitForTimeout(3000);18 await page.snapshotFrame({ path: path.join(__dirname, 'snapshot.png') });19 await browser.close();20})();21const { chromium } = require('playwright');22const path = require('path');23(async () => {24 const browser = await chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 await page.waitForTimeout(3000);28 await page.snapshotFrame({ path: path.join(__dirname, 'snapshot.png') });29 await browser.close();30})();31const { chromium } = require('playwright');32const path = require('path');33(async () => {34 const browser = await chromium.launch();35 const context = await browser.newContext();36 const page = await context.newPage();37 await page.waitForTimeout(3000);38 await page.snapshotFrame({ path: path.join(__dirname, 'snapshot.png') });39 await browser.close();40})();41const { chromium } = require('playwright');42const path = require('path');43(async () => {44 const browser = await chromium.launch();45 const context = await browser.newContext();46 const page = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.snapshotFrame();6 await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch();11 const page = await browser.newPage();12 const frame = page.mainFrame();13 await frame.snapshotFrame();14 await browser.close();15})();16const { chromium } = require('playwright');17(async () => {18 const browser = await chromium.launch();19 const page = await browser.newPage();20 const frame = page.mainFrame();21 await frame.snapshotFrame();22 await browser.close();23})();24const { chromium } = require('playwright');25(async () => {26 const browser = await chromium.launch();27 const page = await browser.newPage();28 const frame = page.mainFrame();29 await frame.snapshotFrame();30 await browser.close();31})();32const { chromium } =

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const fs = require('fs');3const path = require('path');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.waitForTimeout(5000);9 const snapshot = await page.snapshotFrame();10 const snapshotFile = path.join(__dirname, 'snapshot.png');11 fs.writeFileSync(snapshotFile, snapshot);12 await browser.close();13})();14{15 "scripts": {16 },17 "dependencies": {18 }19}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { snapshotFrame } = require('playwright/lib/server/snapshot/snapshotter');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const buffer = await snapshotFrame(page.mainFrame(), { width: 500, height: 500 });8 console.log(buffer);9 await browser.close();10})();11 at CDPSession.send (C:\Users\Kanika12 at processTicksAndRejections (internal/process/task_queues.js:93:5)13 at async CDPSession.send (C:\Users\Kanika14 at async Object.snapshotFrame (C:\Users\Kanika15 at async Object.<anonymous> (C:\Users\Kanika\test.js:7:23)

Full Screen

Using AI Code Generation

copy

Full Screen

1const { snapshotFrame } = require('@playwright/test/lib/server/snapshot/snapshotter');2const fs = require('fs');3(async () => {4 const frame = await page.frames()[0];5 const snapshot = await snapshotFrame(frame, page, 'html');6 fs.writeFileSync('snapshot.html', snapshot);7})();8{9 "scripts": {10 },11 "devDependencies": {12 }13}14const { snapshotFrame } = require('@playwright/test/lib/server/snapshot/snapshotter');15const fs = require('fs');16(async () => {17 const frame = await page.frames()[0];18 const snapshot = await snapshotFrame(frame, page, 'json');19 fs.writeFileSync('snapshot.json', snapshot);20})();21{22 "scripts": {23 },24 "devDependencies": {25 }26}27options: {28 width?: number;29 height?: number;

Full Screen

Using AI Code Generation

copy

Full Screen

1await page.snapshotFrame({2 frame: page.mainFrame(),3});4await page.snapshotFrame({5 frame: page.mainFrame(),6});7await page.snapshotFrame({8 frame: page.mainFrame(),9});10await page.snapshotFrame({11 frame: page.mainFrame(),12});13await page.snapshotFrame({14 frame: page.mainFrame(),15});16await page.snapshotFrame({17 frame: page.mainFrame(),18});19await page.snapshotFrame({20 frame: page.mainFrame(),21});22await page.snapshotFrame({23 frame: page.mainFrame(),24});25await page.snapshotFrame({26 frame: page.mainFrame(),27});28await page.snapshotFrame({29 frame: page.mainFrame(),30});31await page.snapshotFrame({32 frame: page.mainFrame(),33});34await page.snapshotFrame({35 frame: page.mainFrame(),36});37await page.snapshotFrame({38 frame: page.mainFrame(),

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful