Best JavaScript code snippet using puppeteer
responseMessage.js
Source:responseMessage.js
1module.exports = function (uniqid) {2 return {3 bulkupload: function (reqModifyOBJ,req) {4 let template = {5 queryKey:{6 'agent_id': reqModifyOBJ.agent_id,7 'agent_group_id': reqModifyOBJ.agent_group_id,8 'clinet_id': reqModifyOBJ.client_id,9 'timezone': "Australia/Sydney",10 'res_code': 100,11 'exten': '98888890',12 'context': 'sip-cust',13 'req_uniqkey': uniqid.process('ob-'),14 'remoteAddress':req.connection.remoteAddress ||req.socket.remoteAddress,15 'res_message': 'record process for request'16 },responseKey:{17 'AMI_REJECT_CALL_GENERATE':'Internal Server Error Pl Contact AMI_REJECT_CALL_GENERATE',18 'SELECT_FAILED_RECORD_BULK':'Internal Server Error Pl Contact SELECT_FAILED_RECORD_BULK',19 'INSERT_FAILED_TICKET_BULK':'Internal Server Error Pl Contact INSERT_FAILED_TICKET_BULK',20 'UPDATE_FAILED_RECORD_BULK':'Internal Server Error Pl Contact UPDATE_FAILED_RECORD_BULK',21 'SUCCESSRESPONSE':'request accepted for further processing ',22 'SELECT_FAILED_CALLIN_QUEQE':'Internal Server Error Pl Contact SELECT_FAILED_CALLIN_QUEUE',23 'UPDATE_FAILED_CALLIN_QUEQE':'Internal Server Error Pl Contact UPDATE_FAILED_CALLIN_QUEUE',24 'SELECT_FAILED_AGENT_BUSY':'Internal Server Error Pl Contact SELECT_FAILED_AGENT_BUSY'25 }26 }27 return template;28 },29 callback: function (inputKey) {30 let template = {31 queryKey:{32 'agent_id': inputKey.body.agent_id,33 'ticket_auto_id': inputKey.body.ticket_id,34 'customer_number': inputKey.body.caller_no,35 'timezone': "Australia/Sydney",36 'res_code': 100,37 'exten': '98888889',38 'context': 'sip-cust',39 'req_uniqkey': uniqid.process('cb-'),40 'remoteAddress':inputKey.connection.remoteAddress ||req.socket.remoteAddress,41 'res_message': 'record process for request'42 },responseKey:{43 'AMI_REJECT_CALL_GENERATE':'Internal Server Error Pl Contact AMI_REJECT_CALL_GENERATE',44 'SUCCESSRESPONSE':'request accepted for further processing ',45 'SELECT_FAILED_TICKET_NOFOUND':'Internal Server Error Pl Contact SELECT_FAILED_TICKET_NOFOUND',46 'INSERT_FAILED_CALLBACK':'Internal Server Error Pl Contact INSERT_FAILED_CALLBACK',47 'SELECT_FAILED_AGENT_BUSY':'Internal Server Error Pl Contact SELECT_FAILED_AGENT_BUSY'48 }49 }50 return template;51 },52 manager: function (inputKey) {53 let template = {54 queryKey:{55 'call_channel': inputKey.body.channel,56 'ami_action':'Atxfer',57 'timezone': "Australia/Sydney",58 'ami_exten': '99998888',59 'context': 'from-internal-custom',60 'req_uniqkey': uniqid.process('me-'),61 'remoteAddress':inputKey.connection.remoteAddress ||req.socket.remoteAddress,62 'res_message': 'record process for request'63 },responseKey:{64 'AMI_REJECT_CALL_MANAGER':'Internal Server Error Pl Contact AMI_REJECT_CALL_MANAGER',65 'SUCCESSRESPONSE':'request accepted for further processing ',66 }67 }68 return template;69 }, 70 outboundTrans: function (inputKey) {71 let template = {72 queryKey:{73 'call_channel': inputKey.body.channel,74 'ami_action':'Atxfer',75 'timezone': "Australia/Sydney",76 'ami_exten': '99998884',77 'context': 'from-internal-custom',78 'req_uniqkey': uniqid.process('out-'),79 'remoteAddress':inputKey.connection.remoteAddress ||req.socket.remoteAddress,80 'res_message': 'record process for request'81 },responseKey:{82 'AMI_REJECT_CALL_MANAGER':'Internal Server Error Pl Contact AMI_REJECT_CALL_MANAGER',83 'SUCCESSRESPONSE':'request accepted for further processing ',84 }85 }86 return template;87 },88 recording: function (inputKey) {89 let template = {90 queryKey:{91 'call_channel': inputKey.body.channel,92 'ami_action':'Atxfer',93 'timezone': "Australia/Sydney",94 'ami_exten': '99998885',95 'context': 'from-internal-custom',96 'req_uniqkey': uniqid.process('re-'),97 'remoteAddress':inputKey.connection.remoteAddress ||req.socket.remoteAddress,98 'res_message': 'record process for request'99 },responseKey:{100 'AMI_REJECT_CALL_RECORDING':'Internal Server Error Pl Contact AMI_REJECT_CALL_RECORDING',101 'SUCCESSRESPONSE':'request accepted for further processing ',102 }103 }104 return template;105 },external: function (inputKey) {106 let template = {107 queryKey:{108 'call_channel': inputKey.body.channel,109 'ami_action':'Atxfer',110 'timezone': "Australia/Sydney",111 'ami_exten': '99998887',112 'context': 'from-internal-custom',113 'req_uniqkey': uniqid.process('ex-'),114 'remoteAddress':inputKey.connection.remoteAddress ||req.socket.remoteAddress,115 'res_message': 'record process for request'116 },responseKey:{117 'AMI_REJECT_CALL_MANAGER':'Internal Server Error Pl Contact AMI_REJECT_CALL_MANAGER',118 'SUCCESSRESPONSE':'request accepted for further processing ',119 }120 }121 return template;122 },internal: function (inputKey) {123 let template = {124 queryKey:{125 'call_channel': inputKey.body.channel,126 'ami_action':'BlindTransfer',127 'timezone': "Australia/Sydney",128 'ami_exten': '99998886',129 'context': 'from-internal-custom',130 'req_uniqkey': uniqid.process('int-'),131 'remoteAddress':inputKey.connection.remoteAddress ||req.socket.remoteAddress,132 'res_message': 'record process for request'133 },responseKey:{134 'AMI_REJECT_CALL_MANAGER':'Internal Server Error Pl Contact AMI_REJECT_CALL_MANAGER',135 'SUCCESSRESPONSE':'request accepted for further processing ',136 }137 }138 return template;139 },internalP: function (inputKey) {140 let template = {141 queryKey:{142 'call_channel': inputKey.body.channel,143 'ami_action':'BlindTransfer',144 'timezone': "Australia/Sydney",145 'ami_exten': '99998889',146 'context': 'from-internal-custom',147 'req_uniqkey': uniqid.process('inp-'),148 'remoteAddress':inputKey.connection.remoteAddress ||req.socket.remoteAddress,149 'res_message': 'record process for request'150 },responseKey:{151 'AMI_REJECT_CALL_MANAGER':'Internal Server Error Pl Contact AMI_REJECT_CALL_MANAGER',152 'SUCCESSRESPONSE':'request accepted for further processing ',153 }154 }155 return template;156 },outboundCall: function (caller_number,inputKey) {157 let template = {158 queryKey:{159 'agent_number': caller_number,160 'customer_number': caller_number,161 'timezone': "Australia/Sydney",162 'agent_channel': "voiproute",163 'res_code': 100,164 'exten': '98888887',165 'context': 'sip-cust',166 'req_uniqkey': uniqid.process('out-'),167 'remoteAddress':inputKey.connection.remoteAddress ||req.socket.remoteAddress,168 'res_message': 'record process for request'169 },responseKey:{170 'AMI_REJECT_CALL_GENERATE':'Internal Server Error Pl Contact AMI_REJECT_CALL_GENERATE',171 'SUCCESSRESPONSE':'request accepted for further processing ',172 'SELECT_FAILED_TICKET_NOFOUND':'Internal Server Error Pl Contact SELECT_FAILED_TICKET_NOFOUND',173 'INSERT_FAILED_CALLBACK':'Internal Server Error Pl Contact INSERT_FAILED_CALLBACK',174 'SELECT_FAILED_AGENT_BUSY':'Internal Server Error Pl Contact SELECT_FAILED_AGENT_BUSY'175 }176 }177 return template;178 },spyACall: function (requestData,inputKey) {179 let template = {180 queryKey:{181 'agent_number': requestData['manager_channel_number'],182 'customer_number': requestData['manager_channel_number'],183 'call_channel': requestData['spychannel'],184 'manager_user_id': requestData['manager_user_id'],185 'agent_user_id': requestData['agent_user_id'],186 'timezone': "Australia/Sydney",187 'agent_channel': requestData['manager_channel_route'],188 'res_code': 100,189 'exten': '98888876',190 'context': 'sip-cust',191 'req_uniqkey': uniqid.process('spy-'),192 'remoteAddress':inputKey.connection.remoteAddress ||req.socket.remoteAddress,193 'res_message': 'record process for request'194 },responseKey:{195 'AMI_REJECT_CALL_GENERATE':'Internal Server Error Pl Contact AMI_REJECT_CALL_GENERATE',196 'SUCCESSRESPONSE':'request accepted for further processing ',197 'SELECT_FAILED_TICKET_NOFOUND':'Internal Server Error Pl Contact SELECT_FAILED_TICKET_NOFOUND',198 'INSERT_FAILED_CALLBACK':'Internal Server Error Pl Contact INSERT_FAILED_CALLBACK',199 'SELECT_FAILED_AGENT_BUSY':'Internal Server Error Pl Contact SELECT_FAILED_AGENT_BUSY'200 }201 }202 return template;203 }204 }...
wsevents.js
Source:wsevents.js
1var name = gup('name') || window.location.href; 2var server = gup('server') || 'localhost';3var ws;4var setupWebsocket = function(){5 ws = new WebSocket("ws://"+server+":9000");6 ws.onopen = function() {7 console.log("WebSockets connection opened");8 var adminMsg = { "admin": [9 {"admin": true}10 ]};11 ws.send(JSON.stringify(adminMsg));12 };13 ws.onmessage = function(e) {14 //console.log("Got WebSockets message: " + e.data);15 console.log("Got WebSockets message:");16 console.log(e);17 //try {18 var json = JSON.parse(e.data);19 if (!handleMsg(json)){20 for(var i = 0, end = json.length; i < end; i++){21 handleMsg(json[i]);22 }23 }24 // } catch (err) {25 // console.log('This doesn\'t look like a valid JSON: ', e.data);26 // return;27 // }28 };29 ws.onclose = function() {30 console.log("WebSockets connection closed");31 };32};33var clients = [];34var routes = [];35var handleMsg = function(json){36 if (json.config){37 handleConfigMsg(json);38 } else if (json.message){39 handleMessageMsg(json);40 } else if (json.route){41 handleRouteMsg(json);42 } else if (json.remove){43 handleRemoveMsg(json);44 } else if (json.admin){45 //do nothing46 } else {47 return false;48 }49 return true;50};51var handleMessageMsg = function(msg){52 // for(var i = clients.length - 1; i >= 0; i--){53 // if (clients[i].name === msg.message.clientName54 // && clients[i].remoteAddress === msg.message.remoteAddress){55 // break;56 // }57 // }58 // var selector2 = "input[name=pub][value='{name}_{addr}_{pubName}_{pubType}']:radio".replace("{name}",.Safetify()).replace("{addr}", msg.message.remoteAddress.Safetify()).replace("{pubName}",msg.message.name.Safetify()).replace("{pubType}",msg.message.type.Safetify());59 // $(selector2).parent().addClass('active');60 var itemSelector = getCommItemSelector(true, msg.message.clientName, msg.message.remoteAddress, msg.message.name, msg.message.type);61 var fromEndpoint = myPlumb.endpoints[itemSelector];62 if (fromEndpoint){63 var getImage = function(active){64 return "img/node-"+($("#"+itemSelector).attr('class').indexOf('sub_') < 0 65 ? "open" 66 : "closed")+(active ? "-active-i" : "") + ".png";67 };68 fromEndpoint.setImage(getImage(true));//.setPaintStyle(myPlumb.endpointActiveStyle);69 setTimeout(function(){70 fromEndpoint.setImage(getImage(false));/*setPaintStyle(myPlumb.endpointPaintStyle);*/71 },200);72 }73};74var commSelectorTemplate = Handlebars.compile("{{pub}}_{{Safetify clientName}}_{{Safetify remoteAddress}}_{{Safetify name}}_{{Safetify type}}");75var getCommItem = function(a_bPublisher, a_sClientName, a_sRemoteAddress, a_sName, a_sType){76 return $("#"+getCommItemSelector.apply(this, arguments));77};78var getCommItemSelector = function(a_bPublisher, a_sClientName, a_sRemoteAddress, a_sName, a_sType){79 return commSelectorTemplate({ pub: (a_bPublisher?"pub":"sub"),80 clientName: a_sClientName,81 remoteAddress: a_sRemoteAddress,82 name: a_sName,83 type: a_sType});84};85var routeTemplate;86routeTemplate = Handlebars.compile(document.getElementById( 'route_handlebar' ).textContent);87var clientTemplate;88clientTemplate = Handlebars.compile(document.getElementById( 'client_handlebar' ).textContent);89var pubsubTemplate;90pubsubTemplate = Handlebars.compile(document.getElementById( 'pubsub_handlebar' ).textContent);91var displayRoutes = function(){92 $("#route_list").html(routeTemplate({routes:routes}));93};94var addEndpoints = function(msg){95 var clientName = msg.config.name,96 remoteAddress = msg.config.remoteAddress,97 i,endpoint,currM,id;98 if (msg.config.publish && msg.config.publish.messages){99 i = msg.config.publish.messages.length;100 while (i--){101 currM = msg.config.publish.messages[i];102 id = getCommItemSelector(true, clientName, remoteAddress, currM.name, currM.type);103 endpoint = jsPlumb.addEndpoint(id, myPlumb.sourceEndpoint);104 myPlumb.endpoints[id] = endpoint;105 }106 }107 if (msg.config.subscribe && msg.config.subscribe.messages){108 i = msg.config.subscribe.messages.length;109 while(i--){110 currM = msg.config.subscribe.messages[i];111 id = getCommItemSelector(false, clientName, remoteAddress, currM.name, currM.type);112 endpoint = jsPlumb.addEndpoint(id, myPlumb.targetEndpoint);113 myPlumb.endpoints[id] = endpoint;114 }115 }116};117var handleConfigMsg = function(msg){118 for(var j = 0; j < clients.length; j++){119 if (clients[j].name === msg.config.name120 && clients[j].remoteAddress === msg.config.remoteAddress){121 //TODO: if the client already has a config, lets cleanup122 //the old endpoints and old markup123 clients[j].config = msg.config;124 var itemsMarkup = $(pubsubTemplate(clients[j]));125 itemsMarkup.find(".itemwrapper").click(clickItem).hover(overItem, outItem);126 //itemsMarkup.find(".deletebutton").click(clickDelete);127 var client = $("#"+msg.config.name.Safetify()+"_"+msg.config.remoteAddress.Safetify());128 client.append(itemsMarkup);129 addEndpoints(msg);130 //update the description131 if (msg.config.description){132 var idPart ="info_"+msg.config.name.Safetify()+"_"+msg.config.remoteAddress.Safetify(); 133 $("#button_"+idPart).css("display","inline-block");134 $("#"+idPart+" span").html(msg.config.description);135 client.find(".clientnickname, .clientname").attr("title",msg.config.description);136 }137 return;138 }139 }140 //if we did not find a matching client, then add this one141 var newClient = {name:msg.config.name, remoteAddress:msg.config.remoteAddress};142 var clientMarkup = $(clientTemplate(newClient));143 clientMarkup.find(".infobutton").click(clickInfo);144 $("#client_list").append(clientMarkup);145 clients.push(newClient);146 //and then updated it with the additional info.147 handleConfigMsg(msg);148};149var removeClient = function(client){150 var clientName = client.name,151 remoteAddress = client.remoteAddress,152 name, type;153 $("#"+clientName.Safetify()+"_"+remoteAddress.Safetify()).remove();154 155 if (client.config && client.config.publish && client.config.publish.messages){156 for(var i = 0; i < client.config.publish.messages.length; i++){157 name = client.config.publish.messages[i].name;158 type = client.config.publish.messages[i].type;159 jsPlumb.deleteEndpoint(myPlumb.endpoints[["pub",clientName, remoteAddress, name, type].map(Safetify).join("_")]);160 }161 }162 if (client.config && client.config.subscribe && client.config.subscribe.messages){163 for(var i = 0; i < client.config.subscribe.messages.length; i++){164 name = client.config.subscribe.messages[i].name;165 type = client.config.subscribe.messages[i].type;166 jsPlumb.deleteEndpoint(myPlumb.endpoints[["sub",clientName, remoteAddress, name, type].map(Safetify).join("_")]);167 }168 }169};170var addConnection = function(msg){171 var item = msg.route.publisher;172 var sourceid = getCommItemSelector(true, item.clientName, item.remoteAddress, item.name, item.type);173 item = msg.route.subscriber;174 var targetid = getCommItemSelector(false, item.clientName, item.remoteAddress, item.name, item.type);175 var source = myPlumb.endpoints[sourceid];176 var target = myPlumb.endpoints[targetid];177 source.setImage("img/node-closed.png");178 target.setImage("img/node-closed.png");179 if (!myPlumb.connections[sourceid]){180 myPlumb.connections[sourceid] = {};181 }182 if (!myPlumb.connections[sourceid][targetid]){183 var connection = jsPlumb.connect({source:source,target:target}, myPlumb.connectionParams);184 myPlumb.connections[sourceid][targetid] = connection;185 }186 handleSelecting(sourceid, targetid);187};188var handleSelecting = function(pubId, subId){189 $("#"+subId).addClass(pubId);190 $("#"+pubId).addClass(subId);191 // if (currState == PUB_SELECTED){192 // if (pubId == $(".publisher.selected").prop('id')){193 // $("#"+subId).addClass("selected");194 // }195 // } else if (currState == SUB_SELECTED){196 // if (subId == $(".subscriber.selected").prop('id')){197 // $("#"+pubId).addClass("selected");198 // }199 // }200};201var handleUnselecting = function(pubId, subId){202 var subscriber = $("#"+subId);203 var publisher = $("#"+pubId);204 subscriber.removeClass(pubId);205 publisher.removeClass(subId);206 if (subscriber.attr('class').indexOf('pub_') < 0){207 myPlumb.endpoints[subId].setImage("img/node-open.png");208 }209 if (publisher.attr('class').indexOf('sub_') < 0){210 myPlumb.endpoints[pubId].setImage("img/node-open.png");211 }212};213var removeConnection = function(msg){214 var item = msg.route.publisher;215 var sourceid = getCommItemSelector(true, item.clientName, item.remoteAddress, item.name, item.type);216 item = msg.route.subscriber;217 var targetid = getCommItemSelector(false, item.clientName, item.remoteAddress, item.name, item.type);218 if (myPlumb.connections[sourceid] && myPlumb.connections[sourceid][targetid]){219 jsPlumb.detach(myPlumb.connections[sourceid][targetid]);220 handleUnselecting(sourceid, targetid);221 myPlumb.connections[sourceid][targetid] = undefined;222 }223};224var handleRouteMsg = function(msg){225 if (msg.route.type === 'add'){226 routes.push({publisher:msg.route.publisher,227 subscriber:msg.route.subscriber});228 addConnection(msg);229 } else if (msg.route.type === 'remove'){230 for(var i = routes.length - 1; i >= 0; i--){231 var myPub = routes[i].publisher;232 var thePub = msg.route.publisher;233 var mySub = routes[i].subscriber;234 var theSub = msg.route.subscriber;235 if (myPub.clientName === thePub.clientName236 && myPub.name === thePub.name237 && myPub.type === thePub.type238 && myPub.remoteAddress === thePub.remoteAddress239 && mySub.clientName === theSub.clientName240 && mySub.name === theSub.name241 && mySub.type === theSub.type242 && mySub.remoteAddress === theSub.remoteAddress){243 removeConnection(msg);244 routes.splice(i, 1);245 }246 }247 }248 displayRoutes();249};250var handleRemoveMsg = function(msg){251 //for each entry in the remove list252 //for each entry in the clients list253 //if the name & address match, then remove it from the list254 for(var i = 0; i < msg.remove.length; i++){255 for(var j = 0; j < clients.length; j++){256 if (clients[j].name === msg.remove[i].name257 && clients[j].remoteAddress === msg.remove[i].remoteAddress){258 removeClient(clients.splice(j, 1)[0]);259 break;260 }261 }262 }...
apiService.js
Source:apiService.js
1/**2 * Created by zhuzhipeng on 16/3/21.3 */4'use strict';5angular.module('LobyHome').service('apiService', ['$http', '$q', function ($http, $q) {6 var remoteAddress = 'http://test.lobicom.com/api/';7 if (location.host.indexOf('test') == -1) remoteAddress = 'http://lobicom.com/api/';8 function httpRequest(opts) {9 var d = $q.defer();10 $http(opts).success(d.resolve).error(d.reject);11 return d.promise;12 }13 function transferData(data) {14 if (data.errCode == 200) {15 return data.result;16 }17 return $q.reject(data.result);18 }19 //æ´»å¨å表20 this.getActivityList = function (page, size) {21 size = size || 6;22 page = page || 1;23 return httpRequest({24 method: 'GET',25 url: remoteAddress + 'newest_activity?offset=' + page + '&size=' + size26 }).then(transferData)27 };28 this.getActivityDetails = function (id) {29 return httpRequest({30 method: 'GET',31 url: remoteAddress + 'activity?id=' + id32 }).then(transferData)33 };34 //社åºå表35 this.getCommunityList = function (lon, lat) {36 return httpRequest({37 method: 'GET',38 url: remoteAddress + 'nearest_community?page=1&size=10&radius=1000000&latitude=' + lat + '&longitude=' + lon39 }).then(transferData)40 };41 this.getCommunityDetails = function (id) {42 return httpRequest({43 method: 'GET',44 url: remoteAddress + 'community?id=' + id45 }).then(transferData)46 };47 this.getCommunitySp = function (id) {48 return httpRequest({49 method: 'GET',50 url: remoteAddress + 'community_project?id=' + id51 }).then(transferData)52 };53 this.searchCommunity = function (ky, lat, lon) {54 return httpRequest({55 method: 'GET',56 url: remoteAddress + 'nearest_community?keyword=' + ky + '&latitude=' + lat + '&longitude=' + lon57 }).then(transferData)58 };59 this.joinActivity = function (data) {60 return httpRequest({61 method: 'POST',62 url: remoteAddress + 'join_activity',63 //headers: {'Content-Type': 'application/x-www-form-urlencoded'},64 //transformRequest: function(obj) {65 // var str = [];66 // for(var p in obj)67 // str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));68 // return str.join("&");69 //},70 data: data71 })72 };73 //mall homepage74 this.mallIndex = function () {75 return httpRequest({76 method: 'GET',77 url: '/api/homepage'78 }).then(transferData)79 };80 this.getProductList = function (levelType, levelClass, page, size) {81 var lvClass = levelType == 1 ? 'level1_class' : 'level2_class';82 return httpRequest({83 method: 'GET',84 url: '/api/products?' + lvClass + '=' + levelClass + '&page=' + page + '&size=' + size85 }).then(transferData)86 };87 this.searchProductList = function (keyword, page, size) {88 return httpRequest({89 method: 'GET',90 url: '/api/products?keyword=' + keyword + '&page=' + page + '&size=' + size91 }).then(transferData)92 };93 this.getProductionDetails = function (id) {94 return httpRequest({95 method: 'GET',96 url: remoteAddress + 'products?id=' + id97 }).then(transferData)98 };99 this.getShopCartList = function (id) {100 return httpRequest({101 method: 'GET',102 url: remoteAddress + 'shoppingcart',103 }).then(transferData)104 };105 this.addToShopCart = function (productId, buyNum, userId) {106 return httpRequest({107 method: 'POST',108 url: remoteAddress + 'shoppingcart',109 data: {110 id: userId,111 product_id: productId,112 buy_number: buyNum113 }114 })115 };116 this.editShopCartNum = function (data) {117 return httpRequest({118 method: 'PUT',119 url: remoteAddress + 'shoppingcart',120 data: data121 })122 };123 this.deleteShopCartGood = function (data) {124 return httpRequest({125 method: 'DELETE',126 url: remoteAddress + 'shoppingcart',127 data: data128 })129 };130 this.getMallOrder = function (data) {131 return httpRequest({132 method: 'GET',133 url: remoteAddress + 'order?order_state=0',134 data: data135 }).then(transferData)136 };137 this.getUnpayMallOrder = function () {138 return httpRequest({139 method: 'GET',140 url: remoteAddress + 'order?order_state=1'141 }).then(transferData)142 };143 this.sureOrder = function (id) {144 return httpRequest({145 method: 'GET',146 url: remoteAddress + 'confirm_order?id=' + id147 }).then(transferData)148 };149 this.getMallOrderDetails = function (state, id) {150 return httpRequest({151 method: 'GET',152 url: remoteAddress + 'order_detail?order_state=' + state + '&id=' + id153 }).then(transferData)154 };155 this.generateMallOrder = function (data) {156 return httpRequest({157 method: 'POST',158 url: remoteAddress + 'order',159 data: data160 }).then(transferData)161 };162 this.generatePayOrder = function (data) {163 return httpRequest({164 method: 'POST',165 url: remoteAddress + 'pay',166 data: data167 }).then(transferData)168 };169 this.cancelPayOrder = function (data) {170 return httpRequest({171 method: 'DELETE',172 url: remoteAddress + 'order?order_state=1'173 }).then(transferData)174 };175 this.cancelPay = function () {176 return httpRequest({177 method: 'POST',178 url: remoteAddress + 'cancel_pay'179 }).then(transferData)180 }181 this.getAddressList = function (id) {182 var url = (remoteAddress + 'address');183 if (id) {184 url = (remoteAddress + 'address?id=' + id);185 }186 return httpRequest({187 method: 'GET',188 url: url,189 }).then(transferData)190 };191 this.addAddress = function (data) {192 return httpRequest({193 method: 'POST',194 url: remoteAddress + 'address',195 data: data196 })197 };198 this.editAddress = function (data) {199 return httpRequest({200 method: 'PUT',201 url: remoteAddress + 'address',202 data: data203 })204 };205 this.editDefaultAddress = function (data) {206 return httpRequest({207 method: 'PUT',208 url: remoteAddress + 'setdefault_address',209 data: data210 })211 };212 this.deleteAddress = function (data) {213 return httpRequest({214 method: 'DELETE',215 url: remoteAddress + 'address',216 data: data217 })218 };219 //reg220 this.getRegCheckCode = function (phone) {221 return httpRequest({222 method: 'GET',223 url: remoteAddress + 'check_code?phone_number=' + phone224 })225 };226 this.postReg = function (data) {227 return httpRequest({228 method: 'POST',229 url: remoteAddress + 'register',230 data: data231 }).then(transferData)232 };233 this.checkReg = function (phone) {234 return httpRequest({235 method: 'GET',236 url: remoteAddress + 'register?phone=' + phone237 }).then(transferData)238 };239 this.getLuckyBag = function () {240 return httpRequest({241 method: 'GET',242 url: remoteAddress + 'fu_package'243 }).then(transferData)244 };245 this.getLuckyBagList = function () {246 return httpRequest({247 method: 'GET',248 url: remoteAddress + 'my_cards'249 }).then(transferData);250 };251 this.getCardConfig = function () {252 return httpRequest({253 method: 'GET',254 url: remoteAddress + 'coupon/card_config'255 }).then(transferData);256 };257 this.getCardExt = function () {258 return httpRequest({259 method: 'GET',260 url: remoteAddress + 'coupon/card_ext'261 }).then(transferData);262 };263 this.decryptCardCode = function (cardId, encryptCode) {264 return httpRequest({265 method: 'GET',266 url: remoteAddress + 'coupon/get_code?card_id=' + cardId + '&encrypt_code=' + encryptCode267 }).then(transferData);268 };269 this.destroyCard = function (cardId, code) {270 return httpRequest({271 method: 'POST',272 url: remoteAddress + 'coupon/consume',273 data: {274 card_id: cardId,275 code: code276 }277 }).then(transferData);278 };279 this.returnMoney=function(opts){280 return httpRequest({281 method: 'POST',282 url: remoteAddress + 'ask_refund',283 data: opts284 }).then(transferData);285 };286 //this.deleteInfoArt=(artId)=>httpRequest({method: 'POST', url: `/info/art/delete`, data: {art_id:artId}});...
CentralSystem.js
Source:CentralSystem.js
1const Utils = require('../utils/utils.js');2const SOAPWrapper = require('../utils/SOAPWrapper');3const ip = require('ip');4const UUID = require('uuid-js');5class CentralSystem{6 constructor(port) {7 this.soapWrapper = new SOAPWrapper(port, true);8 var self = this;9 this.port = port;10 this.ip = ip.address();11 this.clients = [];12 this.soapWrapper.createCentralSystemServer();13 console.log(`[CentralSystem] Server IP: ${self.ip}`);14 }15 createChargeBoxClient(station, callback){16 var self = this;17 console.log(`Creating SOAP Client for ${station.endpoint}`);18 this.soapWrapper.createChargePointClient(station.endpoint).then(function(client){19 self.clients.push({20 client: client,21 endpoint: station.endpoint,22 chargeBoxIdentity: station.chargeBoxIdentity23 });24 callback();25 });26 }27 getOnlineChargePoints(){28 return this.clients;29 }30 _getClientByEndpoint(endpoint){31 var soapClient = this.clients.filter(function(client){32 return client.endpoint === endpoint;33 });34 if(soapClient.length > 0){35 return soapClient[0];36 }else{37 return null;38 }39 }40 restartChargingPoint(pointId, endpoint){41 this.reset(pointId, endpoint, {42 type: 'Hard'43 });44 this.unlockConnector(pointId, endpoint);45 }46 clearCache(stationId, remoteAddress){47 this.action = '/ClearCache';48 this._updateSoapHeaders(stationId, remoteAddress);49 var client = this._getClientByEndpoint(remoteAddress);50 if(client){51 var soapClient = client.client;52 var request = {53 clearCacheRequest: {}54 }55 soapClient.ClearCache(request, function(result){56 console.log(JSON.stringify(result));57 });58 }else{59 console.log(`[SOAP Request] Client for ${remoteAddress} is not found !`);60 }61 /*this.chargePointClient.ClearCache(request, function(result){62 console.log(JSON.stringify(result));63 });*/64 }65 changeAvailability(stationId, remoteAddress, data){66 this.action = '/ChangeAvailability';67 this._updateSoapHeaders(stationId, remoteAddress);68 var request = {69 changeAvailabilityRequest: data70 }71 this.chargePointClient.ChangeAvailability(request, function(result){72 console.log(JSON.stringify(result));73 });74 }75 changeConguration(stationId, remoteAddress, data){76 this.action = '/ChangeConguration';77 this._updateSoapHeaders(stationId, remoteAddress);78 var request = {79 changeCongurationRequest: data80 }81 this.chargePointClient.ChangeConguration(request, function(result){82 console.log(JSON.stringify(result));83 });84 }85 getConguration(stationId, remoteAddress){86 this.action = '/GetConguration';87 this._updateSoapHeaders(stationId, remoteAddress);88 var request = {89 getCongurationRequest: {}90 }91 this.chargePointClient.GetConguration(request, function(result){92 console.log(JSON.stringify(result));93 });94 }95 getDiagnostics(stationId, remoteAddress){96 this.action = '/GetDiagnostics';97 this._updateSoapHeaders(stationId, remoteAddress);98 var request = {99 getDiagnosticsRequest: {}100 }101 this.chargePointClient.GetDiagnostics(request, function(result){102 console.log(JSON.stringify(result));103 });104 }105 remoteStartTransaction(stationId, remoteAddress, data){106 this.action = '/RemoteStartTransaction';107 this._updateSoapHeaders(stationId, remoteAddress);108 var request = {109 remoteStartTransactionRequest: data110 }111 this.chargePointClient.RemoteStartTransaction(request, function(result){112 console.log(JSON.stringify(result));113 });114 }115 remoteStopTransaction(stationId, remoteAddress, data){116 this.action = '/RemoteStopTransaction';117 this._updateSoapHeaders(stationId);118 var request = {119 remoteStopTransactionRequest: data120 }121 this.chargePointClient.RemoteStopTransaction(request, function(result){122 console.log(JSON.stringify(result));123 });124 }125 reset(stationId, remoteAddress, data){126 this.action = '/Reset';127 this._updateSoapHeaders(stationId, remoteAddress);128 var client = this._getClientByEndpoint(remoteAddress);129 if(client){130 var soapClient = client.client;131 var request = {132 resetRequest: data133 }134 soapClient.Reset(request, function(result){135 console.log(JSON.stringify(result));136 });137 }else{138 console.log(`[SOAP Request] Client for ${remoteAddress} is not found !`);139 }140 }141 unlockConnector(stationId, remoteAddress){142 this.action = '/UnlockConnector';143 this._updateSoapHeaders(stationId, remoteAddress);144 var client = this._getClientByEndpoint(remoteAddress);145 if(client){146 var soapClient = client.client;147 var request = {148 unlockConnectorRequest: {149 connectorId: '1'150 }151 }152 soapClient.UnlockConnector(request, function(result){153 console.log(JSON.stringify(result));154 });155 }else{156 console.log(`[SOAP Request] Client for ${remoteAddress} is not found !`);157 }158 }159 updateFirmware(stationId, remoteAddress, data){160 this.action = '/UpdateFirmware';161 this._updateSoapHeaders(stationId, remoteAddress);162 var request = {163 updateFirmwareRequest: data164 }165 this.chargePointClient.UpdateFirmware(request, function(result){166 console.log(JSON.stringify(result));167 });168 }169 reserveNow(stationId, remoteAddress, data){170 this.action = '/ReserveNow';171 this._updateSoapHeaders(stationId, remoteAddress);172 var request = {173 reserveNowRequest: data174 }175 this.chargePointClient.ReserveNow(request, function(result){176 console.log(JSON.stringify(result));177 });178 }179 cancelReservation(stationId, remoteAddress, data){180 this.action = '/CancelReservation';181 this._updateSoapHeaders(stationId, remoteAddress);182 var request = {183 cancelReservationRequest: data184 }185 this.chargePointClient.CancelReservation(request, function(result){186 console.log(JSON.stringify(result));187 });188 }189 sendLocalList(stationId, remoteAddress, data){190 this.action = '/SendLocalList';191 this._updateSoapHeaders(stationId, remoteAddress);192 var request = {193 sendLocalListRequest: data194 }195 this.chargePointClient.SendLocalList(request, function(result){196 console.log(JSON.stringify(result));197 });198 }199 getLocalListVersion(stationId, remoteAddress){200 this.action = '/GetLocalListVersion';201 this._updateSoapHeaders(stationId, remoteAddress);202 var request = {203 getLocalListVersionRequest: {}204 }205 this.chargePointClient.GetLocalListVersion(request, function(result){206 console.log(JSON.stringify(result));207 });208 }209 dataTransfer(stationId, remoteAddress, data){210 this.action = '/DataTransfer';211 this._updateSoapHeaders(stationId, remoteAddress);212 var request = {213 dataTransferRequest: data214 }215 this.chargePointClient.DataTransfer(request, function(result){216 console.log(JSON.stringify(result));217 });218 }219 _updateSoapHeaders(clientId, remoteAddress){220 var client = this._getClientByEndpoint(remoteAddress);221 var soapClient;222 if(client){223 soapClient = client.client;224 // Remove soap headers225 soapClient.clearSoapHeaders();226 clientId = clientId || 'Simulator';227 console.log(`Remote Address: ${remoteAddress}`);228 console.log(`Action: ${this.action}`);229 var to = remoteAddress || 'http://192.168.0.114:8081';230 //var to = 'http://127.0.0.1:8081/ChargeBox/Ocpp';231 // Generate a V4 UUID232 var uuid4 = UUID.create();233 soapClient.addSoapHeader('<h:chargeBoxIdentity xmlns:h="urn://Ocpp/Cp/2012/06/" >'+ clientId + '</h:chargeBoxIdentity>')234 soapClient.addSoapHeader('<a:MessageID>urn:uuid:' + uuid4 + '</a:MessageID>')235 soapClient.addSoapHeader('<a:From><a:Address>http://localhost:9220/Ocpp/CentralSystemService</a:Address></a:From>')236 soapClient.addSoapHeader('<a:ReplyTo><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo>')237 soapClient.addSoapHeader('<a:To>'+ to + '</a:To>')238 soapClient.addSoapHeader('<a:Action soap:mustUnderstand="1">'+ this.action +'</a:Action>')239 }else{240 console.log(`[SOAP Headers] Client for ${remoteAddress} is not found !`);241 return;242 }243 }244}...
api.js
Source:api.js
1"use strict";2/* packages3========================================================================== */4var Busboy = require("busboy");5var mongoose = require("mongoose");6var fs = require("fs");7var zlib = require("zlib");8/* controllers and models9========================================================================== */10var Parser = require("./parser.js");11var Geometry = require("./geometryModel.js");12/* API13========================================================================== */14exports.upload = function(req, res) {15 var form = new Busboy({headers: req.headers});16 req.pipe(form);17 form.on("file", function(fieldname, file, filename, encoding, mimetype) {18 var dataChunks = [];19 var dataLength = 0;20 file.on("data", function(chunk) {21 dataChunks.push(chunk);22 dataLength += chunk.length;23 }).on("end", function() {24 writeLog(4, "All chunks of the file captured", {origin: req.connection.remoteAddress, fileName: filename, chunksCount: dataChunks.length});25 /* File assembly */26 var data = new Buffer.alloc(dataLength);27 for (var i=0, pos=0; i<dataChunks.length; i++) {28 dataChunks[i].copy(data, pos);29 pos += dataChunks[i].length;30 }31 writeLog(4, "File assembled", {origin: req.connection.remoteAddress, fileName: filename});32 /* File processing */33 fileProcessing(filename, data);34 });35 }).on("error", function(err) {36 writeLog(1, "Error at file reading", {origin: req.connection.remoteAddress, fileName: filename, error: err.message});37 res.sendStatus(500);38 });39 function fileProcessing(fileName, data) {40 try {41 /* File parse */42 var plotData = Parser.parse(fileName, data);43 writeLog(4, "File parsed", {origin: req.connection.remoteAddress, fileName: fileName});44 /* Response to client */45 res.status(201).send(plotData);46 /* Geometry storage */47 if (mongoose.connection.readyState === 1) {48 var uuid = function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)};49 var deflated = zlib.deflateSync(JSON.stringify(plotData));50 Geometry.create({51 name: fileName,52 path: "./files/" + uuid()53 }, function(err, query) {54 if (err) {55 writeLog(1, "Error at geometry storage", {origin: req.connection.remoteAddress, fileName: fileName, error: err.message});56 res.sendStatus(500);57 } else {58 fs.writeFileSync(query.path, deflated);59 writeLog(3, "Geometry stored", {origin: req.connection.remoteAddress, fileName: fileName, path: query.path});60 }61 });62 } else {63 writeLog(1, "Database disconnected", {origin: req.connection.remoteAddress});64 res.sendStatus(500);65 }66 } catch (err) {67 writeLog(1, "Error at file procesing", {origin: req.connection.remoteAddress, fileName: fileName, error: err.message});68 res.sendStatus(500);69 }70 }71 function writeLog(type, msg, meta) {72 msg = "Upload File: " + msg;73 switch (type) {74 case 1:75 req.app.locals.logger.error(msg, {meta: meta});76 break;77 case 2:78 req.app.locals.logger.warn(msg, {meta: meta});79 break;80 case 3:81 req.app.locals.logger.log(msg, {meta: meta});82 break;83 default:84 req.app.locals.logger.debug(msg, {meta: meta});85 }86 }87};88exports.getAll = function(req, res) {89 if (mongoose.connection.readyState === 1) {90 Geometry.find({}, {91 _id: 1,92 name: 1,93 date: 194 }, function(err, query) {95 if (err) {96 writeLog(1, "Error at getting files list", {origin: req.connection.remoteAddress, error: err.message});97 res.sendStatus(500);98 } else {99 writeLog(3, "Files list obtained", {origin: req.connection.remoteAddress, fileListCount: query.length});100 res.status(200).json(query);101 }102 });103 } else {104 writeLog(1, "Database disconnected", {origin: req.connection.remoteAddress});105 res.sendStatus(500);106 }107 function writeLog(type, msg, meta) {108 msg = "Get Files List: " + msg;109 switch (type) {110 case 1:111 req.app.locals.logger.error(msg, {meta: meta});112 break;113 case 2:114 req.app.locals.logger.warn(msg, {meta: meta});115 break;116 case 3:117 req.app.locals.logger.log(msg, {meta: meta});118 break;119 default:120 req.app.locals.logger.debug(msg, {meta: meta});121 }122 }123};124exports.getById = function(req, res) {125 if (mongoose.connection.readyState === 1) {126 Geometry.findOne({127 _id: req.params.id128 }, {129 _id: 0,130 path: 1131 }, function(err, query) {132 if (err) {133 writeLog(1, "Error at getting geometry", {origin: req.connection.remoteAddress, fileId: req.params.id, error: err.message});134 res.sendStatus(500);135 } else if (query) {136 if (fs.existsSync(query.path)) {137 let data = fs.readFileSync(query.path);138 let inflated = zlib.inflateSync(new Buffer.from(data));139 let geometry = JSON.parse(inflated);140 writeLog(3, "Geometry obtained", {origin: req.connection.remoteAddress, fileId: req.params.id});141 res.status(200).json(geometry);142 } else {143 removeLostFile();144 }145 } else {146 writeLog(2, "File to retrieve not found", {origin: req.connection.remoteAddress, fileId: req.params.id});147 res.sendStatus(404);148 }149 });150 } else {151 writeLog(1, "Database disconnected", {origin: req.connection.remoteAddress});152 res.sendStatus(500);153 }154 function removeLostFile() {155 Geometry.findOneAndRemove({156 _id: req.params.id157 }, {158 select: {159 _id: 0160 }161 }, function(err, query) {162 if (err) {163 writeLog(1, "Error at removing lost geometry", {origin: req.connection.remoteAddress, fileId: req.params.id, error: err.message});164 res.sendStatus(500);165 } else if (query) {166 writeLog(3, "Geometry lost and removed", {origin: req.connection.remoteAddress, fileId: req.params.id});167 res.sendStatus(200);168 } else {169 writeLog(2, "File to remove not found", {origin: req.connection.remoteAddress, fileId: req.params.id});170 res.sendStatus(404);171 }172 });173 }174 function writeLog(type, msg, meta) {175 msg = "Get File: " + msg;176 switch (type) {177 case 1:178 req.app.locals.logger.error(msg, {meta: meta});179 break;180 case 2:181 req.app.locals.logger.warn(msg, {meta: meta});182 break;183 case 3:184 req.app.locals.logger.log(msg, {meta: meta});185 break;186 default:187 req.app.locals.logger.debug(msg, {meta: meta});188 }189 }190};191exports.deleteById = function(req, res) {192 if (mongoose.connection.readyState === 1) {193 Geometry.findOneAndRemove({194 _id: req.params.id195 }, {196 select: {197 _id: 0,198 path: 1199 }200 }, function(err, query) {201 if (err) {202 writeLog(1, "Error at removing geometry", {origin: req.connection.remoteAddress, fileId: req.params.id, error: err.message});203 res.sendStatus(500);204 } else if (query) {205 if (fs.existsSync(query.path)) {206 fs.unlinkSync(query.path);207 }208 writeLog(3, "Geometry removed", {origin: req.connection.remoteAddress, fileId: req.params.id});209 res.sendStatus(200);210 } else {211 writeLog(2, "File not found", {origin: req.connection.remoteAddress, fileId: req.params.id});212 res.sendStatus(404);213 }214 });215 } else {216 writeLog(1, "Database disconnected", {origin: req.connection.remoteAddress});217 res.sendStatus(500);218 }219 function writeLog(type, msg, meta) {220 msg = "Delete File: " + msg;221 switch (type) {222 case 1:223 req.app.locals.logger.error(msg, {meta: meta});224 break;225 case 2:226 req.app.locals.logger.warn(msg, {meta: meta});227 break;228 case 3:229 req.app.locals.logger.log(msg, {meta: meta});230 break;231 default:232 req.app.locals.logger.debug(msg, {meta: meta});233 }234 }235};236exports.checkStatus = function(req, res) {237 checkDatabase(0);238 function checkDatabase(attempt) {239 if (mongoose.connection.readyState === 1) {240 Geometry.find({}, {241 _id: 0,242 date: 1243 }, function(err, query) {244 if (err) {245 if (attempt < 2) {246 setTimeout(() => {247 checkDatabase(++attempt);248 }, 5000);249 } else {250 writeLog(1, "Error accessing Geometries collection", {origin: req.connection.remoteAddress, error: err.message});251 res.sendStatus(500);252 }253 } else {254 writeLog(3, "Database connected and Geometries collection accessible", {origin: req.connection.remoteAddress});255 res.sendStatus(200);256 }257 });258 } else {259 if (attempt < 2) {260 setTimeout(() => {261 checkDatabase(++attempt);262 }, 5000);263 } else {264 writeLog(1, "Database disconnected", {origin: req.connection.remoteAddress});265 res.sendStatus(500);266 }267 }268 }269 function writeLog(type, msg, meta) {270 switch (type) {271 case 1:272 req.app.locals.logger.error(msg, {app: 'Status Check', meta: meta});273 break;274 case 2:275 req.app.locals.logger.warn(msg, {app: 'Status Check', meta: meta});276 break;277 case 3:278 req.app.locals.logger.log(msg, {app: 'Status Check', meta: meta});279 break;280 default:281 req.app.locals.logger.debug(msg, {app: 'Status Check', meta: meta});282 }283 }...
tcp.js
Source:tcp.js
1module.exports = [2 {3 localAddress: 16777343,4 localPort: 6001,5 remoteAddress: 0,6 remotePort: 0,7 rxQueue: 0,8 slot: 0,9 txQueue: 0,10 uid: 1000,11 },12 {13 localAddress: 889192575,14 localPort: 53,15 remoteAddress: 0,16 remotePort: 0,17 rxQueue: 0,18 slot: 1,19 txQueue: 0,20 uid: 195,21 },22 {23 localAddress: 16777343,24 localPort: 53,25 remoteAddress: 0,26 remotePort: 0,27 rxQueue: 0,28 slot: 2,29 txQueue: 0,30 uid: 0,31 },32 {33 localAddress: 0,34 localPort: 22,35 remoteAddress: 0,36 remotePort: 0,37 rxQueue: 0,38 slot: 3,39 txQueue: 0,40 uid: 0,41 },42 {43 localAddress: 16777343,44 localPort: 9050,45 remoteAddress: 0,46 remotePort: 0,47 rxQueue: 0,48 slot: 4,49 txQueue: 0,50 uid: 43,51 },52 {53 localAddress: 16777343,54 localPort: 27017,55 remoteAddress: 0,56 remotePort: 0,57 rxQueue: 0,58 slot: 5,59 txQueue: 0,60 uid: 991,61 },62 {63 localAddress: 16777343,64 localPort: 6379,65 remoteAddress: 0,66 remotePort: 0,67 rxQueue: 0,68 slot: 6,69 txQueue: 0,70 uid: 984,71 },72 {73 localAddress: 0,74 localPort: 5355,75 remoteAddress: 0,76 remotePort: 0,77 rxQueue: 0,78 slot: 7,79 txQueue: 0,80 uid: 195,81 },82 {83 localAddress: 553822400,84 localPort: 58234,85 remoteAddress: 426857100,86 remotePort: 443,87 rxQueue: 0,88 slot: 8,89 txQueue: 0,90 uid: 1000,91 },92 {93 localAddress: 553822400,94 localPort: 58204,95 remoteAddress: 426857100,96 remotePort: 443,97 rxQueue: 0,98 slot: 9,99 txQueue: 0,100 uid: 1000,101 },102 {103 localAddress: 553822400,104 localPort: 51856,105 remoteAddress: 759187896,106 remotePort: 443,107 rxQueue: 0,108 slot: 10,109 txQueue: 0,110 uid: 1000,111 },112 {113 localAddress: 553822400,114 localPort: 53496,115 remoteAddress: 1677904930,116 remotePort: 443,117 rxQueue: 0,118 slot: 11,119 txQueue: 0,120 uid: 1000,121 },122 {123 localAddress: 553822400,124 localPort: 43918,125 remoteAddress: 443634316,126 remotePort: 443,127 rxQueue: 0,128 slot: 12,129 txQueue: 0,130 uid: 1000,131 },132 {133 localAddress: 553822400,134 localPort: 37724,135 remoteAddress: 3164924224,136 remotePort: 443,137 rxQueue: 0,138 slot: 13,139 txQueue: 0,140 uid: 1000,141 },142 {143 localAddress: 388737216,144 localPort: 34730,145 remoteAddress: 3744020269,146 remotePort: 80,147 rxQueue: 0,148 slot: 14,149 txQueue: 0,150 uid: 1000,151 },152 {153 localAddress: 553822400,154 localPort: 39528,155 remoteAddress: 2113740480,156 remotePort: 443,157 rxQueue: 0,158 slot: 15,159 txQueue: 0,160 uid: 1000,161 },...
index.js
Source:index.js
1import net from 'net';2import { EventEmitter } from 'events';3import debug from 'debug';4import Client from './client';5const log = debug('terraria:server');6class Server extends EventEmitter {7 constructor({ port = 7777 } = { }) {8 super();9 this.port = port;10 this.clients = { };11 this.clientAddresses = [ ];12 this.init();13 }14 init() {15 let { port } = this;16 this.server = net.createServer();17 this.server.on('connection', ::this.handleConnection);18 this.server.listen(port, () => {19 let addr = this.server.address();20 log('Listening on %s:%s', addr.address, addr.port);21 });22 }23 handleConnection(socket) {24 let { remoteAddress } = socket;25 let client = new Client(this, socket);26 log('Connected: %s', remoteAddress);27 this.clients[remoteAddress] = client;28 this.clientAddresses.push(remoteAddress);29 socket.on('close', () => {30 this.handleDisconnection(socket);31 });32 this.emit('client', client);33 }34 handleDisconnection(socket) {35 let { remoteAddress } = socket;36 log('Disconnected: %s', remoteAddress);37 delete this.clients[remoteAddress];38 let playerId = this.getPlayerId(remoteAddress);39 delete this.clientAddresses[playerId];40 }41 getPlayerId(client) {42 let remoteAddress;43 if (client instanceof Client) remoteAddress = client.socket.remoteAddress;44 if (client instanceof net.Socket) remoteAddress = client.remoteAddress;45 if (typeof client === 'string') remoteAddress = client;46 let id = this.clientAddresses.indexOf(remoteAddress);47 if (id >= 0) return id;48 console.log(client, remoteAddress, this.clients, this.clientAddresses);49 throw new Error('Untracked client provided');50 }51}...
udp.js
Source:udp.js
1module.exports = [2 {3 localAddress: 4211081440,4 localPort: 5353,5 remoteAddress: 0,6 remotePort: 0,7 rxQueue: 0,8 slot: 475,9 txQueue: 0,10 uid: 1000,11 },12 {13 localAddress: 4211081440,14 localPort: 5353,15 remoteAddress: 0,16 remotePort: 0,17 rxQueue: 0,18 slot: 475,19 txQueue: 0,20 uid: 1000,21 },22 {23 localAddress: 0,24 localPort: 5355,25 remoteAddress: 0,26 remotePort: 0,27 rxQueue: 0,28 slot: 477,29 txQueue: 0,30 uid: 195,31 },32 {33 localAddress: 16777343,34 localPort: 51617,35 remoteAddress: 16777343,36 remotePort: 53,37 rxQueue: 0,38 slot: 1683,39 txQueue: 0,40 uid: 0,41 },42 {43 localAddress: 553822400,44 localPort: 48069,45 remoteAddress: 16951488,46 remotePort: 53,47 rxQueue: 0,48 slot: 2231,49 txQueue: 0,50 uid: 0,51 },52 {53 localAddress: 889192575,54 localPort: 53,55 remoteAddress: 0,56 remotePort: 0,57 rxQueue: 0,58 slot: 3367,59 txQueue: 0,60 uid: 195,61 },62 {63 localAddress: 16777343,64 localPort: 53,65 remoteAddress: 0,66 remotePort: 0,67 rxQueue: 0,68 slot: 3367,69 txQueue: 0,70 uid: 0,71 },72 {73 localAddress: 553822400,74 localPort: 123,75 remoteAddress: 0,76 remotePort: 0,77 rxQueue: 0,78 slot: 3437,79 txQueue: 0,80 uid: 87,81 },82 {83 localAddress: 16777343,84 localPort: 123,85 remoteAddress: 0,86 remotePort: 0,87 rxQueue: 0,88 slot: 3437,89 txQueue: 0,90 uid: 0,91 },92 {93 localAddress: 0,94 localPort: 123,95 remoteAddress: 0,96 remotePort: 0,97 rxQueue: 0,98 slot: 3437,99 txQueue: 0,100 uid: 0,101 },102 {103 localAddress: 553822400,104 localPort: 57526,105 remoteAddress: 16951488,106 remotePort: 53,107 rxQueue: 0,108 slot: 3496,109 txQueue: 0,110 uid: 0,111 },112 {113 localAddress: 0,114 localPort: 49602,115 remoteAddress: 0,116 remotePort: 0,117 rxQueue: 0,118 slot: 3764,119 txQueue: 0,120 uid: 0,121 },...
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({ headless: false });4 const page = await browser.newPage();5 await page.screenshot({ path: 'google.png' });6 const remoteAddress = await page.target().createCDPSession().send('Network.getRemoteDataSettings');7 console.log(remoteAddress);8 await browser.close();9})();10const puppeteer = require('puppeteer');11(async () => {12 const browser = await puppeteer.launch({ headless: false });13 const page = await browser.newPage();14 await page.screenshot({ path: 'google.png' });15 const remoteAddress = await page.target().createCDPSession().send('Network.getRemoteDataSettings');16 console.log(remoteAddress);17 await browser.close();18})();19const puppeteer = require('puppeteer');20(async () => {21 const browser = await puppeteer.launch({ headless: false });22 const page = await browser.newPage();23 await page.screenshot({ path: 'google.png' });24 const remoteAddress = await page.target().createCDPSession().send('Network.getRemoteDataSettings');25 console.log(remoteAddress);26 await browser.close();27})();28const puppeteer = require('puppeteer');29(async () => {30 const browser = await puppeteer.launch({ headless: false });31 const page = await browser.newPage();32 await page.screenshot({ path: 'google.png' });33 const remoteAddress = await page.target().createCDPSession().send('Network.getRemoteDataSettings');34 console.log(remoteAddress);35 await browser.close();36})();37const puppeteer = require('puppeteer');38(async () => {39 const browser = await puppeteer.launch({ headless: false });40 const page = await browser.newPage();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 console.log(await page.evaluate(() => window.location.href));6 await page.screenshot({ path: 'example.png' });7 await browser.close();8})();9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch();12 const page = await browser.newPage();13 console.log(await page.evaluate(() => window.location.href));14 await page.screenshot({ path: 'example.png' });15 await browser.close();16})();17const puppeteer = require('puppeteer');18(async () => {19 const browser = await puppeteer.launch();20 const page = await browser.newPage();21 console.log(await page.evaluate(() => window.location.href));22 await page.screenshot({ path: 'example.png' });23 await browser.close();24})();25const puppeteer = require('puppeteer');26(async () => {27 const browser = await puppeteer.launch();28 const page = await browser.newPage();29 console.log(await page.evaluate(() => window.location.href));30 await page.screenshot({ path: 'example.png' });31 await browser.close();32})();33const puppeteer = require('puppeteer');34(async () => {35 const browser = await puppeteer.launch();36 const page = await browser.newPage();37 console.log(await page.evaluate(() => window.location.href));38 await page.screenshot({ path: 'example.png' });39 await browser.close();40})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 console.log(await page.evaluate(() => document.location.href));6 await browser.close();7})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3(async () => {4 const browser = await puppeteer.launch({headless: false});5 const page = await browser.newPage();6 const remoteAddress = await page.evaluate(() => window.location.href);7 console.log(remoteAddress);8 await browser.close();9})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 const remoteAddress = await page.target().createCDPSession().send('Network.getResponseBodyForInterception', {7 });8 console.log(remoteAddress);9 await browser.close();10})();11{12 body: 'data:application/font-woff;charset=utf-8;base64,d09GMgABAAAAAAh4AAsAAAAABKwAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABMAAAABQAAAAUZnBnbQAAAGQAAABkAAAAZDdnQ1cAAABgAAAAZgAAAGYHaGVhZAA...'13}14const puppeteer = require('puppeteer');15const fs = require('fs');16(async () => {17 const browser = await puppeteer.launch();18 const page = await browser.newPage();19 const remoteAddress = await page.target().createCDPSession().send('Network.getResponseBodyForInterception', {20 });21 console.log(remoteAddress);22 await browser.close();23})();24{25 body: 'data:application/font-woff;charset=utf-8;base64,d09GMgABAAAAAAh4AAsAAAAABKwAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABMAAAABQAAAAUZnBnbQAAAGQAAABkAAAAZDdnQ1cAAABgAAAAZgAAAGYHaGVhZAA...'26}27const puppeteer = require('puppeteer');28const fs = require('fs');29(async () => {30 const browser = await puppeteer.launch();31 const page = await browser.newPage();32 const remoteAddress = await page.target().createCDPSession().send('Network.getResponseBodyForInterception', {33 });34 console.log(remoteAddress);
Using AI Code Generation
1(async () => {2 const browser = await puppeteer.launch();3 const page = await browser.newPage();4 const client = await page.target().createCDPSession();5 const { result: { value } } = await client.send('Network.getResponseBody', { requestId: 'requestId' });6 console.log(value);7 await browser.close();8})();9(async () => {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 const client = await page.target().createCDPSession();13 await client.send('Network.enable');14 const { result: { value } } = await client.send('Network.getResponseBody', { requestId: 'requestId' });15 console.log(value);16 await browser.close();17})();18(async () => {19 const browser = await puppeteer.launch();20 const page = await browser.newPage();21 const client = await page.target().createCDPSession();22 await client.send('Network.enable');23 const { result: { value } } = await client.send('Network.getResponseBody', { requestId: 'requestId' });24 console.log(value);25 await browser.close();26})();27(async () => {28 const browser = await puppeteer.launch();29 const page = await browser.newPage();30 const client = await page.target().createCDPSession();31 await client.send('Network.enable');32 const { result: { value } } = await client.send('Network.getResponseBody', { requestId: 'requestId' });33 console.log(value);34 await browser.close();35})();36(async () => {37 const browser = await puppeteer.launch();38 const page = await browser.newPage();39 const client = await page.target().createCDPSession();40 await client.send('Network.enable');41 const { result: { value } } = await client.send('Network.getResponseBody', { requestId: 'requestId' });42 console.log(value);43 await browser.close();44})();45(async () => {46 const browser = await puppeteer.launch();47 const page = await browser.newPage();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.goto(url);6 const remoteAddress = await page.target().createCDPSession().send('Network.getResponseBodyForInterception', {7 });8 console.log(remoteAddress);9 await browser.close();10})();11const puppeteer = require('puppeteer');12(async () => {13 const browser = await puppeteer.launch({headless: false});14 const page = await browser.newPage();15 await page.goto(url);16 const remoteAddress = await page.evaluate(() => {17 return window.location.href;18 });19 console.log(remoteAddress);20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch({headless: false});25 const page = await browser.newPage();26 await page.goto(url);27 const remoteAddress = await page.evaluate(() => {28 return window.location.href;29 });30 console.log(remoteAddress);31 await browser.close();32})();33const puppeteer = require('puppeteer');34(async () => {35 const browser = await puppeteer.launch({headless: false});36 const page = await browser.newPage();37 await page.goto(url);38 const remoteAddress = await page.evaluate(() => {39 return window.location.href;40 });41 console.log(remoteAddress);42 await browser.close();43})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.goto(url);6 const ip = await page.evaluate(() => {7 return window.__SAP__REMOTE_ADDRESS__;8 });9 console.log(ip);10 await browser.close();11})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 const ip = await page.evaluate(() => JSON.stringify(window.___gcfg));7 console.log(ip);8 await browser.close();9})();10const puppeteer = require('puppeteer');11const fs = require('fs');12(async () => {13 const browser = await puppeteer.launch();14 const page = await browser.newPage();15 const ip = await page.evaluate(() => JSON.stringify(window.___gcfg));16 console.log(ip);17 await browser.close();18})();19const puppeteer = require('puppeteer');20const fs = require('fs');21(async () => {22 const browser = await puppeteer.launch();23 const page = await browser.newPage();24 const ip = await page.evaluate(() => JSON.stringify(window.___gcfg));25 console.log(ip);26 await browser.close();27})();28const puppeteer = require('puppeteer');29const fs = require('fs');30(async () => {31 const browser = await puppeteer.launch();32 const page = await browser.newPage();33 const ip = await page.evaluate(() => JSON.stringify(window.___gcfg));34 console.log(ip);35 await browser.close();36})();37const puppeteer = require('puppeteer');38const fs = require('fs');39(async () => {
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 await page.goto(url);7 const ip = await page.evaluate(() => document.querySelector('.ip').innerText);8 console.log(ip);9 fs.writeFileSync('ip.txt', ip);10 await browser.close();11})();12const express = require('express');13const app = express();14const fs = require('fs');15app.get('/', (req, res) => {16 const ip = fs.readFileSync('ip.txt', 'utf8');17 res.send(ip);18});19app.listen(3000, () => {20 console.log('Server is running on port 3000');21});22 fetch('/')23 .then(res => res.text())24 .then(ip => {25 const h2 = document.createElement('h2');26 h2.innerText = ip;27 document.body.appendChild(h2);28 })
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!