How to use networkManager method in Puppeteer

Best JavaScript code snippet using puppeteer

gameManager.js

Source:gameManager.js Github

copy

Full Screen

1const PropertyModel = require("../models/propertyModel");2const {ipcMain} = require('electron');3const mainWindow = require("../../main").mainWindow;4const networkManager = require("./networkManager");5const viewManager = require("./viewManager");6const playerManager = require("./playerManager");7const cardManager = require("./cardManager");8const EventManager = require("./eventManager");9const TradeManager = require("./tradeManager");10const StateManager = require("./stateManager");11const Globals = require("../globals");12let ModelManager;13let house_Count = 32;14let hotel_Count = 12;15let properties = [1, 3, 5, 6, 8, 9, 11, 12, 13, 14, 15, 16, 18, 19, 21, 23, 24, 25, 26, 27, 28, 29, 31, 32, 34, 35, 37, 39];16let chance = [7, 22, 36];17let communityChest = [2, 17, 33];18let goJail = 30;19let incomeTax = 4;20let chanceUsableCards = [16, 17, 6];21let chestUsableCards = [4];22let questComb = [];23let diceComb = [];24class GameManager{25 constructor() {26 this.createListeners();27 networkManager.setStateListener(this.stateTurn.bind(this));28 networkManager.setStartGameListener(this.startGameListenerCallback);29 networkManager.setMoveListener(this.moveListener);30 networkManager.setUpdatePlayerListener(this.updatePlayerListener);31 networkManager.setUpdatePropertyListener(this.updatePropertiesListener);32 networkManager.setAuctionListener(this.auctionListener);33 for( let i = 0; i < 5; i++){34 let x = this.getRandomInt(1,6);35 let y = this.getRandomInt(1,6);36 let dice = {x: x, y: y};37 diceComb.push(dice);38 }39 for( let i = 0; i < 5; i++){40 let x = this.getRandomInt(0, 40);41 let loc = {id: x};42 questComb.push(loc);43 }44 }45 getRandomInt(min, max) {46 min = Math.ceil(min);47 max = Math.floor(max);48 return Math.floor(Math.random() * (max - min + 1)) + min;49 }50 getCurrentUser(){51 return networkManager.getCurrentUser();52 }53 auctionListener(winnerId, propertyModel, bidAmount, auctionStarter){54 let currentProperty = ModelManager.getModels()[propertyModel.id];55 let oldOwner = currentProperty.ownerId;56 if(currentProperty.ownerId){57 let x = currentProperty.ownerId;58 console.log(currentProperty.ownerId);59 playerManager.removeProperty(currentProperty.ownerId, currentProperty);60 }61 let winnerPlayer = playerManager.getPlayers()[winnerId];62 playerManager.setMoney(winnerId, -bidAmount);63 currentProperty.setOwner(winnerId);64 winnerPlayer.properties.push(currentProperty);65 if(networkManager.getCurrentUser().id === oldOwner){66 playerManager.setMoney(oldOwner, bidAmount);67 mainWindow.send("update_money_indicator", playerManager.getMoney(oldOwner));68 mainWindow.send("bm_updateCard", playerManager.getPlayers()[oldOwner]);69 networkManager.updatePlayers([playerManager.getPlayers()[oldOwner]]);70 }71 if(networkManager.getCurrentUser().id === winnerId){72 mainWindow.send("update_money_indicator", winnerPlayer.money);73 mainWindow.send("bm_updateCard", playerManager.getPlayers()[winnerId]);74 mainWindow.send("show_notification", {message: "You win auction for " + propertyModel.name + ".", intent: "success"});75 networkManager.updatePlayers([playerManager.getPlayers()[winnerId]]);76 }77 if(networkManager.getCurrentUser().id === auctionStarter) {78 networkManager.nextState();79 }80 console.log(playerManager.getPlayers());81 }82 updatePlayerListener(players){83 players.forEach(newPlayerModel=>{84 let oldPlayerModel = playerManager.getPlayers()[newPlayerModel.id];85 if(newPlayerModel.money > oldPlayerModel.money){86 if(newPlayerModel.id === networkManager.getCurrentUser().id){87 let diff = newPlayerModel.money - oldPlayerModel.money;88 mainWindow.send("show_notification", {message: "You earn " + diff + "$.", intent: "success"});89 }90 }else if(newPlayerModel.money < oldPlayerModel.money){91 let diff = oldPlayerModel.money - newPlayerModel.money;92 if(newPlayerModel.id === networkManager.getCurrentUser().id) {93 mainWindow.send("show_notification", {message: "You paid " + diff + "$.", intent: "danger"});94 }95 }96 if(newPlayerModel.id === networkManager.getCurrentUser().id){97 mainWindow.send("updatePlayerList", playerManager.getPlayers());98 mainWindow.send("update_money_indicator", newPlayerModel.money);99 }100 console.log("Player " + newPlayerModel.username + " money(old,new): " + oldPlayerModel.money + ", " + newPlayerModel.money);101 // TODO CHECK ALL THE PROPERTIES AND REFLECT THEM TO VIEW102 // TODO DO THIS FOR OTHER PROPERTIES MIGHT BE CHANGE103 playerManager.getPlayers()[newPlayerModel.id].money = newPlayerModel.money;104 });105 }106 updatePropertiesListener(properties){107 properties.forEach(newPropertyModel=>{108 ModelManager.getModels()[newPropertyModel.id].ownerId = newPropertyModel.ownerId;109 ModelManager.getModels()[newPropertyModel.id].isMortgaged= newPropertyModel.isMortgaged;110 console.log("Property name: " + newPropertyModel.name + " was bought by " + newPropertyModel.ownerId + " - " + ModelManager.getModels()[newPropertyModel.id].type);111 if(ModelManager.getModels()[newPropertyModel.id].type === "CityModel"){112 console.log(newPropertyModel.buildings.hotel + " - " + newPropertyModel.buildings.house);113 ModelManager.getModels()[newPropertyModel.id].buildings.house = newPropertyModel.buildings.house;114 ModelManager.getModels()[newPropertyModel.id].buildings.hotel = newPropertyModel.buildings.hotel;115 mainWindow.send("updatePlayerList", playerManager.getPlayers());116 mainWindow.send("bm_updateCity", {id: newPropertyModel.id, house: newPropertyModel.buildings.house, hotel: newPropertyModel.buildings.hotel});117 }118 // TODO CHECK ALL THE PROPERTIES AND REFLECT THEM TO VIEW119 });120 }121 moveListener(args){122 let playerId = args.playerId;123 let destinationTileId = args.destinationTileId;124 playerManager.getPlayers()[playerId].currentTile = destinationTileId;125 mainWindow.send("bm_move" , {playerId, destinationTileId});126 }127 startGameListenerCallback(room){128 playerManager.createPlayers(room.users);129 cardManager.setCards([130 new PropertyModel(0, "Ankara", 10, 1, 100, 2, 0),131 new PropertyModel(1, "Konya", 10, 1, 3, 2, 0)132 ]);133 ModelManager = require("./modelManager");134 mainWindow.send("updatePlayerList", playerManager.getPlayers());135 //for(let model in ModelManager.getModels()){136 // ModelManager.getModels()[model].setOwner(room.users[0].id);137 //}138 let names = {};139 let colors = {};140 for(let index in ModelManager.getModels()){141 names[index] = (ModelManager.getModels()[index].name);142 colors[index] = (ModelManager.getModels()[index].color);143 }144 mainWindow.send("bm_initializeGame" , {players:playerManager.getPlayers(),names: names, colors: colors} );145 }146 moveAction(destinationTileId){147 networkManager.movePlayer(destinationTileId);148 let oldTile = playerManager.getPlayers()[networkManager.getCurrentUser().id].currentTile;149 playerManager.getPlayers()[networkManager.getCurrentUser().id].currentTile = destinationTileId;150 if(playerManager.isInJail(networkManager.getCurrentUser().id)){151 // set state to jail screen152 Globals.isDouble = false;153 let turnsLeft = playerManager.getJailLeft(networkManager.getCurrentUser().id);154 if(turnsLeft === 0){155 playerManager.exitJail(networkManager.getCurrentUser().id);156 this.stateTurn({stateName: "playNormalTurn", payload:{}});157 }else{158 playerManager.reduceJailLeft(networkManager.getCurrentUser().id);159 let jailCard = playerManager.searchCard(networkManager.getCurrentUser().id, 6);160 if(!jailCard)161 jailCard = playerManager.searchCard(networkManager.getCurrentUser().id, 4);162 if(jailCard)163 this.stateTurn({stateName: "playNormalTurn", payload:{turnsLeft: turnsLeft,haveCard: true}});164 else165 this.stateTurn({stateName: "playNormalTurn", payload:{turnsLeft: turnsLeft,haveCard: false}});166 }167 }else{168 // set state to according to tile169 console.log("WENT TO NEW TILE: " + destinationTileId);170 // TODO call stateTurn according to new tile171 //console.log("THIS.TILES: " + JSON.stringify(Globals.tiles, null, 2));172 let currentTile = Globals.selectedTileId === 1 ? Globals.tiles.find(tile=> tile.tile === destinationTileId) : Globals.tiles2.find(tile=> tile.tile === destinationTileId);173 switch(currentTile.type){174 case "CornerTile":175 if(destinationTileId === 30){176 playerManager.sendJail(networkManager.getCurrentUser().id);177 Globals.isDouble = false;178 mainWindow.send("show_notification", {message: "You entered jail.", intent: "danger"});179 setTimeout(()=>{180 networkManager.movePlayer(10);181 networkManager.nextState();182 },2000);183 }else{184 networkManager.nextState();185 }186 break;187 case "StationTile":188 let stationModel = ModelManager.getModels()[currentTile.tile];189 let ownerOfStationId = stationModel.getOwner();190 if(ownerOfStationId){191 if(ownerOfStationId === networkManager.getCurrentUser().id){192 // BU CITY BIZIM193 console.log("BU BENIM STATIONU");194 networkManager.nextState();195 }else{196 // BU CITY BASKASININ197 console.log("BU BASKASININ STATIONU");198 let rentPrice = stationModel.getRentPrice();199 let counter = 0;200 for(let i=0; i<4; i++){201 if(ModelManager.getModels()[(5 + (10*i))].ownerId === stationModel.ownerId){202 counter++;203 }204 }205 rentPrice = rentPrice * counter;206 let cond = playerManager.setMoney(networkManager.getCurrentUser().id, -rentPrice);207 if(!cond){208 mainWindow.send("show_notification", {message: "You need to sell property", intent: "danger"});209 mainWindow.send("next_state_bf", {stateName: "SellState", payload: {}});210 cond = playerManager.setMoney(networkManager.getCurrentUser().id, -rentPrice);211 }212 playerManager.setMoney(ownerOfStationId, rentPrice);213 console.log("Your price: " + playerManager.getMoney(networkManager.getCurrentUser().id));214 mainWindow.send("show_notification", {message: "You paid " + rentPrice + "$.", intent: "danger"});215 console.log(playerManager.getPlayers()[ownerOfStationId].username + " price: " + playerManager.getMoney(ownerOfStationId));216 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id], playerManager.getPlayers()[ownerOfStationId]]);217 networkManager.nextState();218 }219 }else{220 // BU CITY ALINMAMIS221 this.stateTurn({stateName: "buyNewProperty", payload: stationModel});222 }223 break;224 case "UtilityTile":225 let utilityModel = ModelManager.getModels()[currentTile.tile];226 let ownerOfUtilityId = utilityModel.getOwner();227 if(ownerOfUtilityId){228 if(ownerOfUtilityId === networkManager.getCurrentUser().id){229 // BU CITY BIZIM230 console.log("BU BENIM UTILITY");231 networkManager.nextState();232 }else{233 // BU CITY BASKASININ234 console.log("BU BASKASININ UTILITYSI");235 let counter = 0;236 if(ModelManager.getModels()[12].ownerId === utilityModel.ownerId){237 counter++;238 }239 if(ModelManager.getModels()[28].ownerId === utilityModel.ownerId){240 counter++;241 }242 if(counter === 1){243 counter = 4;244 }else{245 counter = 10;246 }247 let rentPrice = (destinationTileId - oldTile) * counter;248 let cond = playerManager.setMoney(networkManager.getCurrentUser().id, -rentPrice);249 if(!cond){250 mainWindow.send("show_notification", {message: "You need to sell property", intent: "danger"});251 mainWindow.send("next_state_bf", {stateName: "SellState", payload: {}});252 cond = playerManager.setMoney(networkManager.getCurrentUser().id, -rentPrice);253 }254 playerManager.setMoney(ownerOfUtilityId, rentPrice);255 console.log("Your price: " + playerManager.getMoney(networkManager.getCurrentUser().id));256 mainWindow.send("show_notification", {message: "You paid " + rentPrice + "$.", intent: "danger"});257 console.log(playerManager.getPlayers()[ownerOfUtilityId].username + " price: " + playerManager.getMoney(ownerOfUtilityId));258 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id], playerManager.getPlayers()[ownerOfUtilityId]]);259 networkManager.nextState();260 }261 }else{262 // BU CITY ALINMAMIS263 this.stateTurn({stateName: "buyNewProperty", payload: utilityModel});264 }265 break;266 case "CityTile":267 let cityModel = ModelManager.getModels()[currentTile.tile];268 let ownerOfCityId = cityModel.getOwner();269 if(ownerOfCityId){270 if(ownerOfCityId === networkManager.getCurrentUser().id){271 // BU CITY BIZIM272 console.log("BU BENIM CITYM");273 networkManager.nextState();274 }else{275 // BU CITY BASKASININ276 console.log("BU BASKASININ CITYSI");277 let rentPrice = cityModel.getRentPrice();278 let double = true;279 for(let model in ModelManager.getModels()){280 if(ModelManager.getModels()[model].color && ModelManager.getModels()[model].color === cityModel.color){281 if(ModelManager.getModels()[model].ownerId !== cityModel.ownerId){282 double = false;283 }284 }285 }286 if(double){287 rentPrice = rentPrice * 2;288 }289 let cond = playerManager.setMoney(networkManager.getCurrentUser().id, -rentPrice);290 if(!cond){291 mainWindow.send("show_notification", {message: "You need to sell property", intent: "danger"});292 mainWindow.send("next_state_bf", {stateName: "SellState", payload: {}});293 cond = playerManager.setMoney(networkManager.getCurrentUser().id, -rentPrice);294 }295 playerManager.setMoney(ownerOfCityId, rentPrice);296 console.log("Your price: " + playerManager.getMoney(networkManager.getCurrentUser().id));297 mainWindow.send("show_notification", {298 message: "You paid " + rentPrice + "$.",299 intent: "danger"300 });301 console.log(playerManager.getPlayers()[ownerOfCityId].username + " price: " + playerManager.getMoney(ownerOfCityId));302 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id], playerManager.getPlayers()[ownerOfCityId]]);303 networkManager.nextState();304 }305 }else{306 // BU CITY ALINMAMIS307 this.stateTurn({stateName: "buyNewProperty", payload: cityModel});308 }309 break;310 case "SpecialTile":311 // let chance = [7, 22, 36];312 // let communityChest = [2, 17, 33];313 if((destinationTileId) === 7 ||(destinationTileId) === 22 ||(destinationTileId) === 36){314 this.drawChanceCard(networkManager.getCurrentUser().id, destinationTileId);315 }316 else if((destinationTileId) === 17 ||(destinationTileId) === 2 ||(destinationTileId) === 33){317 this.drawChestCard(networkManager.getCurrentUser().id, destinationTileId);318 }319 else if(destinationTileId === 4){320 playerManager.setMoney(networkManager.getCurrentUser().id, -200);321 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);322 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);323 }else if(destinationTileId === 38){324 playerManager.setMoney(networkManager.getCurrentUser().id, -100);325 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);326 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);327 }328 networkManager.nextState();329 break;330 default:331 console.log("Wrong tile type");332 break;333 }334 }335 // networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);336 // networkManager.nextState();337 }338 createListeners(){339 ipcMain.on("create_room_fb", (event, args) => {340 networkManager.createRoom(args);341 });342 ipcMain.on("updateTilesAndModels", (event, args)=>{343 this.tiles = args.tiles;344 this.models = args.models;345 console.log("TILES UPDATED: " + JSON.stringify(this.tiles, null, 2));346 });347 ipcMain.on("join_room_fb", (event, args)=>{348 networkManager.joinRoom(args);349 });350 ipcMain.on("start_game_fb", (event, args)=>{351 networkManager.startGame(args);352 });353 ipcMain.on("sell_fb", args=>{354 mainWindow.send("next_state_bf", {stateName: "SellStateNormal", payload: {}});355 Globals.isDouble = true;356 });357 ipcMain.on("goBack_fb", args=>{358 Globals.isDouble = true;359 console.log("FGIRDI");360 mainWindow.send("next_state_bf", {stateName: "playNormalTurn", payload: {}});361 });362 ipcMain.on("buy_property_fb", (event, propertyModel)=>{363 const user = networkManager.getCurrentUser();364 propertyModel = ModelManager.getModels()[propertyModel.id];365 if(playerManager.addProperty(user.id, propertyModel)){366 // ALDI367 mainWindow.send("show_notification", {message: "You bought " + propertyModel.name + ".", intent: "success"});368 mainWindow.send("bm_updateCard", playerManager.getPlayers()[networkManager.getCurrentUser().id]);369 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);370 networkManager.updateProperties([propertyModel]);371 networkManager.nextState();372 }else{373 // PARA YOK374 mainWindow.send("show_notification", {message: "You dont have enough money to buy " + propertyModel.name + ".", intent: "danger"});375 networkManager.setAuction(propertyModel, 0);376 }377 });378 ipcMain.on("determineStartOrder_fb", (event, sum)=>{379 networkManager.determineStartOrder(sum);380 });381 ipcMain.on("move_player_fb", (event, rolledDice)=>{382 console.log("NETWORKMANAGER CURRENT: ");383 console.log(networkManager.getCurrentUser());384 console.log("PLAYERMANAGER ALL:");385 console.log(playerManager.getPlayers());386 let currentTile = playerManager.getPlayers()[networkManager.getCurrentUser().id].currentTile;387 let destinationTileId = (currentTile + rolledDice[0] + rolledDice[1]) % ((Globals.tileNumber-1) * 4);388 if(destinationTileId !== (currentTile + rolledDice[0] + rolledDice[1])){389 if(playerManager.isInJail(networkManager.getCurrentUser().id)){390 }else{391 playerManager.setMoney(networkManager.getCurrentUser().id, 200);392 mainWindow.send("update_money_indicator", playerManager.getMoney(networkManager.getCurrentUser().id).money);393 mainWindow.send("show_notification", {message: "You gain 200$ from passing starting tile.", intent: "primary"});394 }395 }396 if(rolledDice[0] === rolledDice[1]){397 // double rolled398 if(playerManager.increaseDoubleCount(networkManager.getCurrentUser().id)){399 // goto jail400 destinationTileId = Globals.tileNumber-1;401 playerManager.sendJail(networkManager.getCurrentUser().id);402 networkManager.movePlayer(destinationTileId);403 Globals.isDouble = false;404 mainWindow.send("show_notification", {message: "You entered jail.", intent: "danger"});405 networkManager.nextState();406 return;407 }408 }else{409 playerManager.resetDoubleCount(networkManager.getCurrentUser().id);410 }411 Globals.isDouble = rolledDice[0] === rolledDice[1];412 if(questComb.forEach(quest => {if(quest.id === destinationTileId) return true;}))413 if(diceComb.forEach(dice => {414 if(dice.x === rolledDice[0] && dice.y === rolledDice[1] ||415 dice.y === rolledDice[0] && dice.x === rolledDice[1])416 return true;}))417 playerManager.setMoney(networkManager.getCurrentUser().id, 600);418 this.moveAction(destinationTileId);419 });420 //same buildings, bidding commences and the buildings go to the highest bidder421 //we need to implement an auction for bidding houses and hotels422 /**423 * args = {propertyModelID, BuildingModel}424 */425 ipcMain.on("set_building_fb", (event, args)=>{426 const user = networkManager.getCurrentUser();427 let property = ModelManager.getModels()[args.id];428 if(property.type !== "CityModel"){429 mainWindow.send("show_notification", {message: "You cannot set a building to a non-city property.", intent: "danger"});430 return;431 }432 let type = args.type;433 console.log("SET BUILD ARG");434 console.log(args);435 if(type === 'hotel' && Globals.hotelCount === 0)436 mainWindow.send("show_notification", {message: "There is no hotel left in game.", intent: "danger"});437 else if(type === 'house' && Globals.houseCount === 0)438 mainWindow.send("show_notification", {message: "There is no house left in game.", intent: "danger"});439 else{440 if(type==="house"){441 if(property.buildings.hotel === 1){442 mainWindow.send("show_notification", {message: "You cannot build house after a hotel.", intent: "danger"});443 return;444 }445 if(property.buildings.house === 4){446 mainWindow.send("show_notification", {message: "You cannot build more than 4 house.", intent: "danger"});447 return;448 }449 let canBuild = true;450 let allModels = ModelManager.getModels();451 for(let index in allModels){452 let currentModel = allModels[index];453 if(currentModel.type === "CityModel" && currentModel.color === property.color){454 if(currentModel.ownerId !== user.id){455 mainWindow.send("show_notification", {message: "You cannot build before collect all the cities in a color.", intent: "danger"});456 return;457 }458 if(currentModel.buildings.house < property.buildings.house){459 canBuild = false;460 }461 }462 }463 if(canBuild){464 if(playerManager.setMoney(networkManager.getCurrentUser().id, -property.houseCost)){465 property.buildings.house = property.buildings.house + 1;466 Globals.houseCount = Globals.houseCount - 1;467 mainWindow.send("show_notification", {message: "The new house built.", intent: "success"});468 ModelManager.getModels()[args.id].buildings = property.buildings;469 mainWindow.send("bm_updateCity", {id: args.id, house: property.buildings.house, hotel: property.buildings.hotel});470 networkManager.updateProperties([property]);471 }else{472 mainWindow.send("show_notification", {message: "There is not enough money for building.", intent: "danger"});473 }474 }else{475 mainWindow.send("show_notification", {message: "You cannot build more house here.", intent: "danger"});476 }477 }else{478 let canBuild = true;479 let allModels = ModelManager.getModels();480 for(let index in allModels){481 let currentModel = allModels[index];482 if(currentModel.type === "CityModel" && currentModel.color === property.color){483 if(currentModel.ownerId !== user.id){484 mainWindow.send("show_notification", {message: "You cannot build before collect all the cities in a color.", intent: "danger"});485 return;486 }487 if(currentModel.buildings.house < property.buildings.house){488 canBuild = false;489 }490 }491 }492 if(canBuild){493 if(property.buildings.house !== 4){494 mainWindow.send("show_notification", {message: "You cannot build a hotel before got 4 houses.", intent: "danger"});495 return;496 }497 if(property.buildings.hotel === 1){498 mainWindow.send("show_notification", {message: "You cannot build more than one hotel.", intent: "danger"});499 return;500 }501 if(playerManager.setMoney(networkManager.getCurrentUser().id, -property.hotelCost)){502 property.buildings.hotel = property.buildings.hotel + 1;503 Globals.hotelCount = Globals.hotelCount - 1;504 Globals.houseCount = Globals.houseCount + 4;505 mainWindow.send("show_notification", {message: "The new hotel built.", intent: "success"});506 ModelManager.getModels()[args.id].buildings = property.buildings;507 mainWindow.send("bm_updateCity", {id: args.id, house: property.buildings.house, hotel: property.buildings.hotel});508 networkManager.updateProperties([property]);509 }else{510 mainWindow.send("show_notification", {message: "There is not enough money for building.", intent: "danger"});511 }512 }else{513 mainWindow.send("show_notification", {message: "You cannot build a hotel before got 4 houses in each city.", intent: "danger"});514 }515 }516 }517 });518 /**519 * args = {PropertyModelId, BuildingModel}520 */521 ipcMain.on("sell_building_house_fb", (event, args)=>{522 const user = networkManager.getCurrentUser();523 let property = cardManager.getCardById(args[0]);524 let type = args[1].type;525 if(house_Count === 32)526 console.log("All houses are in the bank, there cannot be a house on the board.");527 else {528 let cond = playerManager.sellBuilding(user.id, args, "house");529 if (cond) {530 console.log("Building is removed successfully!");531 house_Count += 1;532 } else {533 console.log('Failed to remove building due to an error.')534 }535 }536 });537 ipcMain.on("sell_building_hotel_fb", (event, args)=>{538 const user = networkManager.getCurrentUser();539 console.log("Property ID " + args);540 if(hotel_Count === 32)541 console.log("All hotels are in the bank, there cannot be a house on the board.");542 else {543 let cond = playerManager.sellBuilding(user.id, args, "hotel");544 if (cond) {545 console.log("Building is removed successfully!");546 hotel_Count += 1;547 } else {548 console.log('Failed to remove building due to an error.')549 }550 }551 });552 /**553 * channel: event name554 *555 * args = property556 */557 ipcMain.on("auction_fb", (event, args)=>{558 networkManager.setAuction(args.propertyModel, args.bidAmount);559 });560 ipcMain.on("sell_property_fb", (event, args)=>{//property ID561 if(args === -1){562 let properties = playerManager.getPlayers()[networkManager.getCurrentUser().id].properties;563 if(Object.keys(properties).length === 0){564 console.log("BANKRUPCY");565 mainWindow.send("show_notification", {message: "Game over", intent: "danger"});566 mainWindow.send("change_page_bf", {done: true});567 }else{568 for(let i in properties){569 let property = properties[i];570 networkManager.setAuction(property, 0);571 networkManager.updateProperties([property]);572 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);573 return;574 }575 }576 }else{577 let property = ModelManager.getModels()[args];578 networkManager.setAuction(property, 0);579 networkManager.updateProperties([property]);580 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);581 }582 });583 /**584 * args: {newTile:number, }585 */586 ipcMain.on('new_tile', (event, args)=>{587 let players = playerManager.getPlayers();588 let currentUser = networkManager.getCurrentUser();589 //get the player id590 let playerId = currentUser.id;591 //current tile of the player before moving592 let oldTile = players[playerId].currentTile;593 let newTile = args[0]594 let startBonus = false;595 if (oldTile <= 39 && newTile >= 0) {596 startBonus = true;597 }598 playerManager.move(currentUser, newTile, startBonus);599 // if new tile is jail600 if (newTile !== goJail) {601 //ToDo602 //Here call the function which the player is sent to jail to wait 3 turns603 }604 //if tile is income, player spends $200 or 10% of his/her money605 else if (newTile === incomeTax) {606 playerManager.setMoney(playerId, -200);607 mainWindow.send("update_money_indicator", playerId.money);608 }609 //traverse the arrays in order to find the tile type610 else {611 let typeTile = -1;612 let found = false;613 for (let i = 0; i < properties.length; i++) {614 if (properties[i] === newTile) {615 typeTile = 0;616 found = true;617 break;618 }619 }620 //if tile type is found, no need to traverse other arrays621 if (!found) {622 for (let i = 0; i < chance.length; i++) {623 if (chance[i] === newTile) {624 typeTile = 1;625 found = true;626 break;627 }628 }629 if (!found) {630 for (let i = 0; i < communityChest.length; i++) {631 if (communityChest[i] === newTile) {632 typeTile = 2;633 found = true;634 break;635 }636 }637 }638 }639 //arrays are traversed, do what needs to be done after moving to a new tile640 if (typeTile === 0) {641 let property = cardManager.getCardById(args[0]);642 if (property.ownerId == null) {643 //ToDo644 //depending on whether the user chooses to buy or not, give tile to user start an auction645 //give tile if no auction646 playerManager.addProperty(playerId, property);647 }648 }649 else if (typeTile === 1) {650 //ToDo651 //Draw a chance card652 // let chanceCard = cardManager.653 }654 else if (typeTile === 2) {655 //ToDo656 //Draw a community chest card657 // let communityCard = cardManager.658 }659 else {660 console.log("Cannot find the type of the newTile. Debug.");661 }662 }663 });664 ipcMain.on("use_skill_fb", args =>{665 let character = playerManager.getPlayers()[networkManager.getCurrentUser().id].character;666 let tile = playerManager.getPlayers()[networkManager.getCurrentUser().id].currentTile;667 if(character === 1){668 //Driver669 let x;670 do {671 x = this.getRandomInt(4,24);672 }while(x % 2 !== 0);673 mainWindow.send("show_notification", {message: "You used character skill! Moving " + x, intent: "success"});674 this.moveAction((tile + x) % ((Globals.tileNumber-1) * 4));675 }676 else if(character === 2){677 //child678 let x = this.getRandomInt(1,6);679 mainWindow.send("show_notification", {message: "You used character skill! Moving " + x, intent: "success"});680 this.moveAction((tile + x) % ((Globals.tileNumber-1) * 4));681 }682 else if(character === 3){683 //traveler684 if(tile !== 5 && tile !== 15 && tile !== 25 && tile !== 35){685 mainWindow.send("show_notification", {message: "You are not in the Station", intent: "danger"});686 Globals.isDouble = true;687 mainWindow.send("next_state_bf", {stateName:"playNormalTurn", payload: {}});688 }689 else{690 mainWindow.send("show_notification", {message: "You are going to the selected tile", intent: "success"});691 this.moveAction(args);692 }693 }694 });695 ipcMain.on("exit_from_jail", (event, arg) =>{696 if(arg.type === 0){697 //next turn698 networkManager.nextState();699 }else if(arg.type === 1){700 if(playerManager.getJailLeft(networkManager.getCurrentUser().id) === 0){701 playerManager.setMoney(networkManager.getCurrentUser().id, -50);702 mainWindow.send("update_money_indicator", playerManager.getMoney(networkManager.getCurrentUser().id));703 mainWindow.send("show_notification", {message: "You paid 50$ to exit from jail.", intent: "warning"});704 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);705 }706 // exit with rolling dice707 setTimeout(()=>{708 let currentTile = playerManager.getPlayers()[networkManager.getCurrentUser().id].currentTile;709 let destinationTileId = (currentTile + arg.rolledDice[0] + arg.rolledDice[1]) % ((Globals.tileNumber-1) * 4);710 playerManager.resetDoubleCount(networkManager.getCurrentUser().id);711 Globals.isDouble = false;712 if(questComb.forEach(quest => {if(quest.id === destinationTileId) return true;}))713 if(diceComb.forEach(dice => {714 if(dice.x === arg.rolledDice[0] && dice.y === arg.rolledDice[1] ||715 dice.y === arg.rolledDice[0] && dice.x === arg.rolledDice[1])716 return true;}))717 playerManager.setMoney(networkManager.getCurrentUser().id, 400);718 playerManager.exitJail(networkManager.getCurrentUser().id);719 this.moveAction(destinationTileId);720 },1000);721 }else if(arg.type === 2){722 // exit with pay723 if(playerManager.setMoney(networkManager.getCurrentUser().id, -50)){724 mainWindow.send("show_notification", {message: "You paid 50$ to exit from jail.", intent: "warning"});725 playerManager.exitJail(networkManager.getCurrentUser().id);726 mainWindow.send("bm_updateCard", playerManager.getPlayers()[networkManager.getCurrentUser().id]);727 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);728 mainWindow.send("next_state_bf", {stateName:"playNormalTurn", payload: {}});729 }else{730 mainWindow.send("show_notification", {message: "You dont have enough money to exit from jail.", intent: "danger"});731 //TODO732 }733 }else if(arg.type === 3){734 // exit with card735 mainWindow.send("show_notification", {message: "You used your card to exit from jail.", intent: "warning"});736 if(!playerManager.useCard(networkManager.getCurrentUser().id, 4)){737 playerManager.useCard(networkManager.getCurrentUser().id, 6);738 }739 playerManager.exitJail(networkManager.getCurrentUser().id);740 mainWindow.send("bm_updateCard", playerManager.getPlayers()[networkManager.getCurrentUser().id]);741 mainWindow.send("addJailCard", true);742 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);743 networkManager.nextState();744 }745 });746 /**747 * signal_from: get_characters_fb748 * */749 ipcMain.on('get_characters_fb', (event, args) => {750 networkManager.getCharacters();751 });752 /**753 * signal_from: get_character_sb754 * setCharObj: {roomName, currentUser, selectedCharId}755 * */756 ipcMain.on('set_character_fb', (event, setCharObj) => {757 networkManager.setCharacter(setCharObj);758 });759 ipcMain.on('get_messages_fb', (event, args) => {760 networkManager.getMessages();761 });762 ipcMain.on('send_message_fb', (event, messageObj) => {763 networkManager.sendMessage(messageObj);764 });765 ipcMain.on('send_message_widget_fb', (event, messageObj) => {766 networkManager.sendWidgetMessage(messageObj);767 });768 }769 stateTurn(stateObject){770 let stateName = stateObject.stateName;771 let payload = stateObject.payload;772 //console.log("NEXT STATE: " + stateName + " PAYLOAD: " + JSON.stringify(payload));773 switch (stateName) {774 case "playNormalTurn":775 if(playerManager.isInJail(networkManager.getCurrentUser().id)){776 let turnsLeft = playerManager.getJailLeft(networkManager.getCurrentUser().id);777 if(turnsLeft === 0){778 playerManager.exitJail(networkManager.getCurrentUser().id);779 mainWindow.send("next_state_bf", {stateName:"playNormalTurn", payload: payload});780 }else{781 playerManager.reduceJailLeft(networkManager.getCurrentUser().id);782 let jailCard = playerManager.searchCard(networkManager.getCurrentUser().id, 6);783 if(!jailCard)784 jailCard = playerManager.searchCard(networkManager.getCurrentUser().id, 4);785 if(jailCard)786 mainWindow.send("next_state_bf", {stateName:"waitInJail", payload:{turnsLeft: turnsLeft,haveCard: true}});787 else788 mainWindow.send("next_state_bf", {stateName:"waitInJail", payload:{turnsLeft: turnsLeft,haveCard: false}});789 }790 }else{791 mainWindow.send("next_state_bf", {stateName:"playNormalTurn", payload: payload});792 }793 break;794 case "waitOtherPlayerTurn":795 mainWindow.send("next_state_bf", {stateName:"waitOtherPlayerTurn", payload: payload});796 break;797 case "buyNewProperty":798 mainWindow.send("next_state_bf", stateObject);799 break;800 case "BidYourTurn":801 for( let id in stateObject.payload.auction){802 stateObject.payload.auction[id] = {name: playerManager.getPlayers()[id], bid: stateObject.payload.auction[id]};803 }804 mainWindow.send("next_state_bf", stateObject);805 break;806 case "BidOtherPlayerTurn":807 for( let id in stateObject.payload.auction){808 stateObject.payload.auction[id] = {name: playerManager.getPlayers()[id], bid: stateObject.payload.auction[id]};809 }810 mainWindow.send("next_state_bf", stateObject);811 break;812 default:813 console.log("GIRMEMEN LAZIMDI");814 break;815 }816 }817 rollToExitJail(currentUser){818 if(x === y)819 playerManager.exitJail(currentUser);820 else{821 if(playerManager.getJailLeft(currentUser) > 0)822 playerManager.reduceJailLeft(currentUser);823 else824 return false;825 }826 return true;827 }828 payToExitJail(currentUser){829 let amount = 50;830 return playerManager.setMoney(currentUser, -amount);831 }832 useCardToExitJail(currentUser){833 let chanceCardID = 6;834 let chestCardID = 4;835 let cond1 = playerManager.useCard(currentUser, chanceCardID);836 if(cond1){837 cardManager.addChanceCard(chanceCardID, "Get Out of Jail Free");838 playerManager.exitJail(currentUser);839 return true;840 }841 else{842 let cond2 = playerManager.useCard(currentUser, chestCardID);843 if(cond2) {844 cardManager.addChestCard(chestCardID, "Get Out of Jail Free");845 playerManager.exitJail(currentUser);846 return true;847 }848 }849 return false;850 }851 /**852 * Send Current User to the Jail853 */854 goJail(playerID){855 playerManager.sendJail(playerID);856 }857 drawChestCard(playerID){858 let card = cardManager.drawChestCard();859 if(!chestUsableCards.includes(card.id)){860 cardManager.addChestCard(card.id, card.description);861 if(card.id === 0){862 mainWindow.send("show_notification", {message: "Advance to GO", intent: "success"});863 setTimeout(()=>{864 playerManager.setMoney(networkManager.getCurrentUser().id, 200);865 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);866 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);867 this.moveAction(0);868 }, 2000);869 }870 else if(card.id === 1){871 mainWindow.send("show_notification", {message: "Bank error in your favor—Collect $200", intent: "success"});872 playerManager.setMoney(playerID, 200);873 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);874 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);875 }876 else if(card.id === 2){877 mainWindow.send("show_notification", {message: "Doctor's fee—Pay $50", intent: "danger"});878 playerManager.setMoney(playerID, -50);879 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);880 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);881 }882 else if(card.id === 3){883 mainWindow.send("show_notification", {message: "From sale of stock you get $50", intent: "success"});884 playerManager.setMoney(playerID, 50);885 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);886 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);887 }888 else if(card.id === 5){889 mainWindow.send("show_notification", {message: "Go to Jail–Go directly to jail–Do not pass Go–Do not collect $200!", intent: "danger"});890 playerManager.sendJail(playerID);891 setTimeout(()=>{892 this.moveAction(10);893 }, 2000);894 }895 else if(card.id === 6){896 mainWindow.send("show_notification", {message: "Grand Opera Night—Collect $50 from every player for opening night seats", intent: "primary"});897 let players = playerManager.getPlayers();898 for(let i in players){899 let player = players[i];900 if(playerID === player.id) {901 playerManager.setMoney(playerID, (50 * (Object.keys(players).length - 1)));902 }else {903 playerManager.setMoney(player.id, -50);904 }905 mainWindow.send("update_money_indicator", playerManager.getPlayers()[playerID].money);906 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);907 }908 }909 else if(card.id === 7){910 mainWindow.send("show_notification", {message: "Holiday Fund matures—Receive $100", intent: "success"});911 playerManager.setMoney(playerID, 100);912 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);913 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);914 }915 else if(card.id === 8){916 mainWindow.send("show_notification", {message: "Income tax refund–Collect $20", intent: "success"});917 playerManager.setMoney(playerID, 20);918 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);919 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);920 }921 else if(card.id === 9){922 playerManager.setMoney(playerID, 10);923 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);924 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);925 mainWindow.send("show_notification", {message: "It is your birthday—Collect $10!", intent: "success"});926 }927 else if(card.id === 10){928 playerManager.setMoney(playerID, 100);929 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);930 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);931 mainWindow.send("show_notification", {message: "Life insurance matures–Collect $100", intent: "success"});932 }933 else if(card.id === 11){934 mainWindow.send("show_notification", {message: "Pay hospital fees of $100", intent: "danger"});935 playerManager.setMoney(playerID, -100);936 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);937 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);938 }939 else if(card.id === 12){940 mainWindow.send("show_notification", {message: "Pay school fees of $150", intent: "danger"});941 playerManager.setMoney(playerID, -150);942 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);943 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);944 }945 else if(card.id === 13){946 playerManager.setMoney(playerID, 25);947 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);948 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);949 mainWindow.send("show_notification", {message: "Receive $25 consultancy fee!", intent: "success"});950 }951 else if(card.id === 14){952 mainWindow.send("show_notification", {message: "You are assessed for street repairs–$40 per house–$115 per hotel!", intent: "primary"});953 playerManager.payRepair(playerID, 40, 115);954 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);955 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);956 }957 else if(card.id === 15){958 mainWindow.send("show_notification", {message: "You have won second prize in a beauty contest–Collect $10!", intent: "success"});959 playerManager.setMoney(playerID, 10);960 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);961 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);962 }963 else if(card.id === 16){964 mainWindow.send("show_notification", {message: "You inherit $100!", intent: "success"});965 playerManager.setMoney(playerID, 100);966 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);967 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);968 }969 }970 else {971 playerManager.addCard(playerID, card);972 mainWindow.send("addJailCard", true);973 mainWindow.send("show_notification", {message: "You get a Jail Free Card!", intent: "success"});974 }975 }976 drawChanceCard(playerID, locationID){977 let card = cardManager.drawChanceCard();978 if(!chanceUsableCards.includes(card.id)){979 cardManager.addChanceCard(card.id, card.description);980 if(card.id === 0){981 mainWindow.send("show_notification", {message: "Advance to GO", intent: "success"});982 playerManager.setMoney(networkManager.getCurrentUser().id, 200);983 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);984 setTimeout(()=>{985 this.moveAction(0);986 }, 2000);987 }988 else if(card.id === 1){989 //move illinois990 mainWindow.send("show_notification", {message: "Advance to Illinois Ave – If you pass Go, collect $200", intent: "success"});991 if(locationID > 24){992 playerManager.setMoney(networkManager.getCurrentUser().id, 200);993 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);994 mainWindow.send("show_notification", {message: "You passed Start. Earned a start bonus!", intent: "success"});995 }996 setTimeout(()=>{997 this.moveAction(24);998 }, 2000);999 }1000 else if(card.id === 2){1001 mainWindow.send("show_notification", {message: "Advance to St. Charles Place – If you pass Go, collect $200", intent: "success"});1002 if(locationID > 11){1003 playerManager.setMoney(networkManager.getCurrentUser().id, 200);1004 mainWindow.send("update_money_indicator", playerManager.getPlayers()[networkManager.getCurrentUser().id].money);1005 mainWindow.send("show_notification", {message: "You passed Start. Earned a start bonus!", intent: "success"});1006 }1007 setTimeout(()=>{1008 this.moveAction(11);1009 }, 2000);1010 }1011 else if(card.id === 3){1012 //,"Advance token to nearest Utility. If unowned, you may buy it from the Bank.1013 // If owned, throw dice and pay owner a total ten times the amount thrown."1014 mainWindow.send("show_notification", {message: "Advance token to nearest Utility. If unowned, you may buy it from the Bank. " +1015 "If owned, throw dice and pay owner a total ten times the amount thrown.", intent: "primary"});1016 if(locationID === 36){1017 let currentTile = Globals.selectedTileId === 1 ? Globals.tiles[28] : Globals.tiles2[28];1018 let cityModel = ModelManager.getModels()[currentTile.tile];1019 let ownerOfCityId = cityModel.getOwner();1020 // if(ownerOfCityId && ownerOfCityId !== playerID){1021 // playerManager.setMoney(ownerOfCityId, cityModel.getRentPrice());1022 // playerManager.setMoney(playerID, -cityModel.getRentPrice());1023 // }1024 setTimeout(()=>{1025 this.moveAction(28);1026 }, 2000);1027 }1028 if(locationID === 22){1029 let currentTile = Globals.selectedTileId === 1 ? Globals.tiles[28] : Globals.tiles2[28];1030 let cityModel = ModelManager.getModels()[currentTile.tile];1031 let ownerOfCityId = cityModel.getOwner();1032 // if(ownerOfCityId && ownerOfCityId !== playerID){1033 // playerManager.setMoney(ownerOfCityId, cityModel.getRentPrice());1034 // playerManager.setMoney(playerID, -cityModel.getRentPrice());1035 // }1036 setTimeout(()=>{1037 this.moveAction(28);1038 }, 2000);1039 }1040 if(locationID === 7){1041 let currentTile = Globals.selectedTileId === 1 ? Globals.tiles[12] : Globals.tiles2[12];1042 let cityModel = ModelManager.getModels()[currentTile.tile];1043 let ownerOfCityId = cityModel.getOwner();1044 // if(ownerOfCityId && ownerOfCityId !== playerID){1045 // playerManager.setMoney(ownerOfCityId, cityModel.getRentPrice());1046 // playerManager.setMoney(playerID, -cityModel.getRentPrice());1047 // }1048 setTimeout(()=>{1049 this.moveAction(5);1050 }, 2000);1051 }1052 }1053 else if(card.id === 4){1054 //,"Advance token to the nearest Railroad and pay owner twice the rental to which1055 // he/she {he} is otherwise entitled. If Railroad is unowned, you may buy it from the Bank."1056 mainWindow.send("show_notification", {message: "Advance token to the nearest Railroad and pay owner twice the rental to which " +1057 "he/she {he} is otherwise entitled. If Railroad is unowned, you may buy it from the Bank", intent: "primary"});1058 if(locationID === 36){1059 let currentTile = Globals.selectedTileId === 1 ? Globals.tiles[35] : Globals.tiles2[35];1060 let cityModel = ModelManager.getModels()[currentTile.tile];1061 let ownerOfCityId = cityModel.getOwner();1062 if(ownerOfCityId && ownerOfCityId !== playerID){1063 playerManager.setMoney(ownerOfCityId, cityModel.getRentPrice());1064 playerManager.setMoney(playerID, -cityModel.getRentPrice());1065 }1066 mainWindow.send("update_money_indicator", playerManager.getPlayers()[playerID].money);1067 setTimeout(()=>{1068 this.moveAction(35);1069 }, 2000);1070 }1071 if(locationID === 22){1072 let currentTile = Globals.selectedTileId === 1 ? Globals.tiles[25] : Globals.tiles2[25];1073 let cityModel = ModelManager.getModels()[currentTile.tile];1074 let ownerOfCityId = cityModel.getOwner();1075 if(ownerOfCityId && ownerOfCityId !== playerID){1076 playerManager.setMoney(ownerOfCityId, cityModel.getRentPrice());1077 playerManager.setMoney(playerID, -cityModel.getRentPrice());1078 }1079 mainWindow.send("update_money_indicator", playerManager.getPlayers()[playerID].money);1080 setTimeout(()=>{1081 this.moveAction(25);1082 }, 2000);1083 }1084 if(locationID === 7){1085 let currentTile = Globals.selectedTileId === 1 ? Globals.tiles[5] : Globals.tiles2[5];1086 let cityModel = ModelManager.getModels()[currentTile.tile];1087 let ownerOfCityId = cityModel.getOwner();1088 if(ownerOfCityId && ownerOfCityId !== playerID){1089 playerManager.setMoney(ownerOfCityId, cityModel.getRentPrice());1090 playerManager.setMoney(playerID, -cityModel.getRentPrice());1091 }1092 mainWindow.send("update_money_indicator", playerManager.getPlayers()[playerID].money);1093 setTimeout(()=>{1094 this.moveAction(5);1095 }, 2000);1096 }1097 }1098 else if(card.id === 5){1099 //,"Bank pays you dividend of $50"1100 playerManager.setMoney(playerID, 50);1101 mainWindow.send("update_money_indicator", playerManager.getPlayers()[playerID].money);1102 mainWindow.send("show_notification", {message: "You earned 50$ from bank!", intent: "success"});1103 }1104 else if(card.id === 7){1105 //,"Go Back 3 Spaces"1106 mainWindow.send("show_notification", {message: "Go Back 3 Spaces", intent: "primary"});1107 setTimeout(()=>{1108 this.moveAction(locationID - 3);1109 }, 2000);1110 }1111 else if(card.id === 8){1112 //,"Go to Jail–Go directly to Jail–Do not pass Go, do not collect $200"1113 mainWindow.send("show_notification", {message: "Go to Jail–Go directly to Jail–Do not pass Go, do not collect $200", intent: "danger"});1114 playerManager.sendJail(playerID);1115 setTimeout(()=>{1116 this.moveAction(10);1117 }, 2000);1118 }1119 else if(card.id === 9){1120 //,"Make general repairs on all your property–For each house pay $25–For each hotel $100"1121 mainWindow.send("show_notification", {message: "Make general repairs on all your property–For each house pay $25–For each hotel $100", intent: "primary"});1122 playerManager.payRepair(playerID, 25, 100);1123 }1124 else if(card.id === 10){1125 //,"Pay poor tax of $15"1126 playerManager.setMoney(playerID, -15);1127 mainWindow.send("update_money_indicator", playerManager.getPlayers()[playerID].money);1128 mainWindow.send("show_notification", {message: "You lost 15$ for paying tax!", intent: "danger"});1129 }1130 else if(card.id === 11){1131 // ,"Take a trip to Reading Railroad–If you pass Go, collect $200"1132 mainWindow.send("show_notification", {message: "Take a trip to Reading Railroad–If you pass Go, collect $200", intent: "primary"});1133 if(locationID > 5){1134 playerManager.setMoney(playerID, 200);1135 mainWindow.send("update_money_indicator", playerManager.getPlayers()[playerID].money);1136 mainWindow.send("show_notification", {message: "You passed Start. Earned a start bonus!", intent: "success"});1137 }1138 setTimeout(()=>{1139 this.moveAction(5);1140 }, 2000);1141 }1142 else if(card.id === 12){1143 //,"Take a walk on the Boardwalk–Advance token to Boardwalk"1144 mainWindow.send("show_notification", {message: "Take a walk on the Boardwalk–Advance token to Boardwalk", intent: "primary"});1145 setTimeout(()=>{1146 this.moveAction(39);1147 }, 2000);1148 }1149 else if(card.id === 13){1150 //,"You have been elected Chairman of the Board–Pay each player $50"1151 mainWindow.send("show_notification", {message: "You have been elected Chairman of the Board–Pay each player $50", intent: "primary"});1152 let players = playerManager.getPlayers();1153 for(let i in players){1154 let player = players[i];1155 if(playerID === player.id)1156 playerManager.setMoney(playerID, -(50 * (Object.keys(players).length - 1)));1157 else1158 playerManager.setMoney(player.id, 50);1159 mainWindow.send("update_money_indicator", playerManager.getPlayers()[playerID].money);1160 }1161 }1162 else if(card.id === 14){1163 //,"Your building and loan matures—Collect $150"1164 playerManager.setMoney(playerID, 150);1165 mainWindow.send("update_money_indicator", playerManager.getPlayers()[playerID].money);1166 mainWindow.send("show_notification", {message: "Your building and loan matures—Collect $150!", intent: "primary"});1167 }1168 else if(card.id === 15) {1169 //,"You have won a crossword competition—Collect $100"1170 playerManager.setMoney(playerID, 100);1171 mainWindow.send("update_money_indicator", playerManager.getPlayers()[playerID].money);1172 mainWindow.send("show_notification", {1173 message: "You have won a crossword competition—Collect $100!",1174 intent: "primary"1175 });1176 }else if(card.id === 16)1177 mainWindow.send("show_notification", {message: "You get a Natural Disaster Card!", intent: "success"});1178 else if(card.id === 17)1179 mainWindow.send("show_notification", {message: "You get a Profit Card!", intent: "success"});1180 }1181 else { //6-16-171182 playerManager.addCard(playerID, card);1183 if(card.id === 6) {1184 mainWindow.send("show_notification", {message: "You get a Jail Free Card!", intent: "success"});1185 mainWindow.send("addJailCard", true);1186 }1187 }1188 networkManager.updatePlayers([playerManager.getPlayers()[networkManager.getCurrentUser().id]]);1189 }1190 mortgage(playerID, property){1191 playerManager.mortgage(playerID, property);1192 }1193 liftMortgage(playerID, property){1194 playerManager.liftMortgage(playerID,property);1195 }1196}...

Full Screen

Full Screen

manage-network-access.js

Source:manage-network-access.js Github

copy

Full Screen

1ndexApp.controller('manageNetworkAccessController',2 ['ndexService', 'ndexUtility', 'sharedProperties', '$scope', '$location',3 '$routeParams', '$q', 'ndexNavigation', 'uiMisc','$window',4 function (ndexService, ndexUtility, sharedProperties, $scope, $location,5 $routeParams, $q, ndexNavigation, uiMisc, $window ) {6 // Process the URL to get application state7 //-----------------------------------------------------------------------------------8 var identifier = $routeParams.identifier;9 var returnto = $routeParams.returnto;10 // CONTROLLER DECLARATIONS/INTIALIZATIONS11 //------------------------------------------------------------------------------------12 $scope.networkManager = {};13 var networkManager = $scope.networkManager;14 networkManager.errors = [];15 networkManager.isAdmin = false;16 networkManager.externalId = identifier;17 networkManager.networkUserMemberships = [];18 networkManager.networkGroupMemberships = [];19 networkManager.newUsers = {};20 networkManager.newGroups = {};21 networkManager.selectedAccountsForUpdatingAccessPermissions = [];22 networkManager.originalAccessPermissions = [];23 networkManager.showShareURLControl = false;24 networkManager.mapOfUserPermissions = {};25 networkManager.mapOfGroupPermissions = {};26 networkManager.modifiedAccessObjects = [];27 networkManager.deletedAccessObjects = [];28 networkManager.newAdminObj = [];29 networkManager.networkShareableURL = null;30 networkManager.networkShareableURLLabel = null;31 $scope.progressMessage = null;32 $scope.errorMessage = null;33 $scope.showChangeShareURLButton = false;34 $scope.showChangeShareURLButtonTitle = "";35 $scope.showOriginalCopyNetworkShareURLTitle = function() {36 $scope.copyNetworkShareURLTitle = (networkManager.network.visibility.toUpperCase() === 'PUBLIC') ?37 'Copy network URL to clipboard' :38 'Copy Share URL to clipboard';39 };40 $scope.showCopiedNetworkShareURLTitle = function() {41 $scope.copyNetworkShareURLTitle = 'Copied';42 };43 $scope.isDOIPending = function() {44 return uiMisc.isDOIPending(networkManager.network);45 };46 $scope.isDOIAssigned = function() {47 return uiMisc.isDOIAssigned(networkManager.network);48 };49 $scope.isNetworkCertified = function() {50 return uiMisc.isNetworkCertified(networkManager.network);51 };52 $scope.showChangeShareURLButton = function() {53 var isDOIAssignedOrPendingOrNetworkCertified =54 $scope.isDOIPending() || $scope.isDOIAssigned() || $scope.isNetworkCertified();55 $scope.showChangeShareURLButton = !isDOIAssignedOrPendingOrNetworkCertified;56 if (uiMisc.isNetworkCertified(networkManager.network)) {57 if (uiMisc.isDOIAssigned(networkManager.network)) {58 $scope.showChangeShareURLButtonTitle = "Unable to Disable Share URL for this network: it is certified and a DOI has been assigned";59 } else if (uiMisc.isDOIPending(networkManager.network)) {60 $scope.showChangeShareURLButtonTitle = "Unable to Disable Share URL for this network: a request has been submitted and the DOI is pending assignment";61 };62 } else if (uiMisc.isDOIPending(networkManager.network)) {63 $scope.showChangeShareURLButtonTitle = "Unable to Disable Share URL for this network: a request has been submitted and the DOI is pending assignment";64 } else if (uiMisc.isDOIAssigned(networkManager.network)) {65 $scope.showChangeShareURLButtonTitle = "Unable to Disable Share URL for this network: a DOI been assigned";66 };67 };68 networkManager.accessWasRemoved = function(accessObj) {69 if ((typeof(accessObj) === 'undefined') ||70 (typeof(accessObj.memberUUID) === 'undefined')) {71 return false;72 }73 for (var i = 0; i < networkManager.selectedAccountsForUpdatingAccessPermissions.length; i++) {74 if (accessObj.memberUUID ===75 networkManager.selectedAccountsForUpdatingAccessPermissions[i].memberUUID) {76 return false;77 }78 }79 return true;80 }81 networkManager.accessWasAdded = function(accessObj) {82 if ((typeof(accessObj) === 'undefined') ||83 (typeof(accessObj.memberUUID) === 'undefined')) {84 return false;85 }86 for (var i = 0; i < networkManager.originalAccessPermissions.length; i++) {87 if (accessObj.memberUUID ===88 networkManager.originalAccessPermissions[i].memberUUID) {89 return false;90 }91 }92 return true;93 };94 networkManager.accessWasModified = function(accessObj) {95 if ((typeof(accessObj) === 'undefined') ||96 (typeof(accessObj.memberUUID) === 'undefined')) {97 return false;98 }99 for (var i = 0; i < networkManager.selectedAccountsForUpdatingAccessPermissions.length; i++) {100 if ((accessObj.memberUUID ===101 networkManager.selectedAccountsForUpdatingAccessPermissions[i].memberUUID) &&102 (accessObj.permissions.toLowerCase() !==103 networkManager.selectedAccountsForUpdatingAccessPermissions[i].permissions.toLowerCase())) {104 return true;105 }106 }107 return false;108 }109 $scope.$on('ADDING_PERMISSIONS_DONE', function () {110 //console.log('DONE adding permissions, now update');111 updateNetworkMembership(networkManager.modifiedAccessObjects, 5, 1, 'UPDATING_PERMISSIONS_DONE');112 });113 $scope.$on('UPDATING_PERMISSIONS_DONE', function () {114 //console.log('DONE updating permissions, now delete');115 deleteNetworkMembership(networkManager.deletedAccessObjects, 5, 1, 'DELETING_PERMISSIONS_DONE');116 });117 $scope.$on('DELETING_PERMISSIONS_DONE', function () {118 //console.log('DONE deleting permissions, finally change admin');119 updateNetworkMembership(networkManager.newAdminObj, 5, 1, 'ALL_PERMISSIONS_DONE');120 });121 $scope.$on('ALL_PERMISSIONS_DONE', function () {122 //console.log('DONE changing admin, go back to Network View page.');123 $scope.progressMessage = null;124 $scope.isProcessing = false;125 if ( returnto === 'nnv') {126 $window.location.href = ('/viewer/networks/' + networkManager.externalId);127 } else {128 $location.path('/network/' + networkManager.externalId);129 }130 });131 var updateNetworkMembership = function(memberships, updateNetworkMembershipTries, secsToWait, eventToEmit) {132 if (!memberships || memberships.length == 0) {133 $scope.$emit(eventToEmit);134 return;135 }136 var newMembership = memberships[0];137 var permissionAccount = (newMembership.accountType.toLowerCase() == 'user') ?138 " user " + newMembership.firstName + " " + newMembership.lastName :139 " group " + newMembership.groupName;140 $scope.progressMessage = "Processing permission " + newMembership.permissions + " for " + permissionAccount;141 142 ndexService.updateNetworkPermissionV2(143 newMembership.resourceUUID,144 newMembership.accountType,145 newMembership.memberUUID,146 newMembership.permissions,147 function(data, status, headers, config, statusText) {148 //console.log(" update network permissions successfully");149 memberships.splice(0 ,1);150 updateNetworkMembership(memberships, updateNetworkMembershipTries, secsToWait, eventToEmit);151 },152 function(error, status, headers, config, statusText) {153 if ((status == 500) &&154 (error && error.errorCode && (error.errorCode == 'NDEx_Concurrent_Modification_Exception')))155 {156 updateNetworkMembershipTries = updateNetworkMembershipTries - 1;157 if (updateNetworkMembershipTries == 0) {158 159 var title = "Unable to Update Network Access";160 var message = "Unable to update access to network for ";161 if (newMembership.accountType.toLowerCase() == 'group') {162 message = message + ' group <strong>' + newMembership.groupName + '</strong>.<br>'163 } else {164 message = message + ' user <strong>' + newMembership.firstName + ' ' +165 newMembership.lastName + '</strong>.<br>'166 }167 $scope.progressMessage = null;168 message = message + error.message;169 $scope.errorMessage = message;170 ndexNavigation.genericInfoModal(title, message);171 //$scope.$emit(eventToEmit);172 return;173 };174 if (secsToWait === undefined) {175 secsToWait = 1;176 }177 // wait and try to update/add this membership again (recursively call itself)178 setTimeout(function()179 {180 updateNetworkMembership(memberships, updateNetworkMembershipTries, secsToWait, eventToEmit);181 },182 secsToWait * 1000);183 } else {184 // server reported error ... give error message and stop processing185 var title = "Unable to Update or Add Network Access";186 var message = "Unable to update or add network access for ";187 if (newMembership.accountType.toLowerCase() == 'group') {188 message = message + ' group <strong>' + newMembership.groupName + '</strong>.<br>'189 } else {190 message = message + ' user <strong>' + newMembership.firstName + ' ' +191 newMembership.lastName + '</strong>.<br>'192 }193 $scope.progressMessage = null;194 message = message + error.message;195 $scope.errorMessage = message;196 ndexNavigation.genericInfoModal(title, message);197 return;198 };199 // give error message here -- and continue updating ...200 //updateNetworkMembership(memberships, updateNetworkMembershipTries, secsToWait, eventToEmit);201 });202 }203 var deleteNetworkMembership = function (memberships, deleteNetworkMembershipTries, secsToWait, eventToEmit) {204 if (!memberships || memberships.length == 0) {205 $scope.$emit(eventToEmit);206 return;207 }208 var membershipObj = memberships[0];209 var permissionAccount = (membershipObj.accountType.toLowerCase() == 'user') ?210 " user " + membershipObj.firstName + " " + membershipObj.lastName :211 " group " + membershipObj.groupName;212 $scope.progressMessage = "Deleting permission " + membershipObj.permissions + " for " + permissionAccount;213 ndexService.deleteNetworkPermissionV2(membershipObj.resourceUUID, membershipObj.accountType, membershipObj.memberUUID,214 function(data, status, headers, config, statusText) {215 // success, membership deleted216 memberships.splice(0 ,1);217 deleteNetworkMembership(memberships, deleteNetworkMembershipTries, secsToWait, eventToEmit);218 },219 function(error, status, headers, config, statusText) {220 // memberships.splice(0 ,1);221 // unable to delete membership. Check if network is currently locked on the222 // server by another process, wait, and try to delete again223 if ((status == 500) &&224 (error && error.errorCode && (error.errorCode == 'NDEx_Concurrent_Modification_Exception')))225 {226 deleteNetworkMembershipTries = deleteNetworkMembershipTries - 1;227 if (deleteNetworkMembershipTries == 0) {228 //console.log("unable to delete network membership");229 var title = "Unable to Delete Network Access";230 var message = "Unable to remove access to network for ";231 if (membershipObj.accountType.toLowerCase() == 'group') {232 message = message + ' group <strong>' + membershipObj.groupName + '</strong>.<br>'233 } else {234 message = message + ' user <strong>' + membershipObj.firstName + ' ' +235 membershipObj.lastName + '</strong>.<br>'236 }237 $scope.progressMessage = null;238 message = message + error.message;239 $scope.errorMessage = message;240 ndexNavigation.genericInfoModal(title, message);241 //$scope.$emit(eventToEmit);242 return;243 };244 if (secsToWait === undefined) {245 secsToWait = 1;246 }247 // wait and try to delete this membership again (recursively call itself)248 setTimeout(function()249 {250 deleteNetworkMembership(membershipObj, deleteNetworkMembershipTries, secsToWait)251 },252 secsToWait * 1000);253 } else {254 // server reported error ... give error message and stop processing255 var title = "Unable to Delete Network Access";256 var message = "Unable to remove access to network for ";257 if (membershipObj.accountType.toLowerCase() == 'group') {258 message = message + ' group <strong>' + membershipObj.groupName + '</strong>.<br>'259 } else {260 message = message + ' user <strong>' + membershipObj.firstName + ' ' +261 membershipObj.lastName + '</strong>.<br>'262 }263 $scope.progressMessage = null;264 message = message + error.message;265 $scope.errorMessage = message;266 ndexNavigation.genericInfoModal(title, message);267 return;268 }269 // give error message here -- and continue deleting ...270 //deleteNetworkMembership(memberships, deleteNetworkMembershipTries, secsToWait, eventToEmit);271 });272 }273 /*274 * Find and return UUID of ADMIN.275 */276 var getAdminUUID = function(accounts) {277 _.each(accounts, function(membershipObj)278 {279 if (membershipObj['permissions']) {280 membershipObj['permissions'] = membershipObj['permissions'].toUpperCase();281 };282 });283 var adminObj = _.find(accounts, {permissions: "ADMIN"});284 return adminObj ? adminObj['memberUUID'] : null;285 };286 var getAccountName = function(accounts, memberUUID) {287 var memberObj = _.find(accounts, {memberUUID: memberUUID});288 if (memberObj) {289 var accountName = (memberObj['accountType'] && (memberObj['accountType'].toLowerCase() == 'user')) ?290 memberObj['firstName'] + ' ' + memberObj['lastName'] : memberObj['groupName'];291 }292 return accountName ? accountName : "";293 };294 networkManager.isSelfAdminRemoval = function(){295 //Determine if the user is going to remove themselves as admin296 var return_dict = {'adminIssue': false, 'issueSeverity': 'none'};297 var newAdminUUIDs = [];298 var multiple_admin_count = 0;299 var originalAdminUUID = getAdminUUID(networkManager.originalAccessPermissions);300 _.each(networkManager.selectedAccountsForUpdatingAccessPermissions, function(membershipObj)301 {302 if (membershipObj['permissions'] == 'ADMIN') {303 multiple_admin_count++;304 if (originalAdminUUID != membershipObj['memberUUID']) {305 newAdminUUIDs.push(membershipObj['memberUUID']);306 }307 };308 });309 if (multiple_admin_count == 0) { //User removed admin (self) but did not specify new admin310 return_dict['adminIssue'] = true;311 return_dict['issueSeverity'] = 'ABORT';312 return_dict['title'] = 'Admin Required';313 return_dict['message'] = 'This action cannot be completed because one admin should always be designated.';314 return return_dict;315 }316 if ((multiple_admin_count > 2) ||317 ((multiple_admin_count == 2) && (newAdminUUIDs.length > 1))) {318 //We do not support multiple admins, or two admins if there are no original admin319 return_dict['adminIssue'] = true;320 return_dict['issueSeverity'] = 'ABORT';321 return_dict['title'] = 'Too Many Admins Specified';322 return_dict['message'] = 'You specified ' + multiple_admin_count + ' admins. ' +323 'Please select only one admin.';324 return return_dict;325 }326 // At this point we know that there are 2 or 1 admin specified.327 // In case there are 2 admins, then one is new and one is old;328 // In case there is one admin, we need to check if it is not the same as old one --329 // in both cases we downgraded the current admin and assign a newly selected admin330 if ((multiple_admin_count == 2) ||331 ((multiple_admin_count == 1) && ((newAdminUUIDs.length == 1)))) {332 return_dict['adminIssue'] = true;333 return_dict['issueSeverity'] = 'WARNING';334 return_dict['title'] = 'New Admin Specified';335 var newAdminName =336 getAccountName(networkManager.selectedAccountsForUpdatingAccessPermissions, newAdminUUIDs[0]);337 var oldAdminName = getAccountName(networkManager.originalAccessPermissions, originalAdminUUID);338 return_dict['message'] = 'You specified <strong>' + newAdminName + ' </strong>as new admin. <br><br>' +339 '<strong>' + oldAdminName + '</strong> permission will be downgraded to "Can Edit" and this ' +340 ' user will no longer be able to manage access permissions for this network. <br><br>' +341 'Are you sure you want to proceed?';342 return return_dict;343 }344 // same admin, no new admin selected345 return return_dict;346 }347 networkManager.save = function() {348 if (!networkManager.changesWereMade()) {349 // theoretically, this "if" should never execute since if no changes were made, then350 // the "Save Changes" button is unavailable on the Manage Access page and351 // this function cannot be called since it is invoked by clicking the "Save Changes" button352 $scope.isProcessing = false;353 //$location.path("network/"+ $scope.networkManager.externalId);354 if ( returnto === 'nnv') {355 $window.location.href = ('/viewer/networks/' + networkId);356 } else {357 $location.path('/network/' + networkManager.externalId);358 }359 return;360 }361 if( $scope.isProcessing )362 return;363 $scope.isProcessing = true;364 var originalAdminUUID = getAdminUUID(networkManager.originalAccessPermissions);365 var newAdminUUID = getAdminUUID(networkManager.selectedAccountsForUpdatingAccessPermissions);366 var downgradeOriginalAdmin = (originalAdminUUID != newAdminUUID);367 if (downgradeOriginalAdmin) {368 // we selected a new Admin; the current one will be downgraded369 // so we need to make sure that the370 // permission object with (memberUUID == originalAdminUUID) is processed very last371 _.remove(networkManager.originalAccessPermissions, {memberUUID: originalAdminUUID});372 _.remove(networkManager.originalAccessPermissions, {memberUUID: newAdminUUID});373 _.remove(networkManager.selectedAccountsForUpdatingAccessPermissions, {memberUUID: originalAdminUUID});374 networkManager.newAdminObj.push(_.clone(_.find(networkManager.selectedAccountsForUpdatingAccessPermissions,375 {memberUUID: newAdminUUID})));376 _.remove(networkManager.selectedAccountsForUpdatingAccessPermissions, {memberUUID: newAdminUUID});377 }378 var addedAccessObjects = [];379 _.each(networkManager.selectedAccountsForUpdatingAccessPermissions, function(accessObj) {380 if (networkManager.accessWasAdded(accessObj)) {381 var newMembership = {382 memberUUID: accessObj.memberUUID,383 resourceUUID: accessObj.resourceUUID,384 permissions: accessObj.permissions,385 accountType: accessObj.accountType.toLowerCase()386 }387 if (newMembership['accountType'] == 'user') {388 newMembership['firstName'] = accessObj.firstName;389 newMembership['lastName'] = accessObj.lastName;390 } else {391 newMembership['groupName'] = accessObj.groupName;392 }393 addedAccessObjects.push(newMembership);394 }395 });396 _.each(addedAccessObjects, function(membershipObj) {397 // remove added permission objects from networkManager.selectedAccountsForUpdatingAccessPermissions398 _.remove(networkManager.selectedAccountsForUpdatingAccessPermissions, {memberUUID: membershipObj.memberUUID});399 });400 _.each(networkManager.originalAccessPermissions, function(accessObj) {401 if (networkManager.accessWasRemoved(accessObj)) {402 networkManager.deletedAccessObjects.push(accessObj);403 }404 });405 _.each(networkManager.deletedAccessObjects, function(membershipObj) {406 // remove deleted permission objects from networkManager.originalAccessPermissions list407 _.remove(networkManager.originalAccessPermissions, {memberUUID: membershipObj.memberUUID});408 });409 _.each(networkManager.originalAccessPermissions, function(accessObj) {410 if (networkManager.accessWasModified(accessObj)) {411 var modifiedAccessObj =412 _.find(networkManager.selectedAccountsForUpdatingAccessPermissions,413 {memberUUID: accessObj.memberUUID});414 var newMembership = {415 memberUUID: accessObj.memberUUID,416 resourceUUID: accessObj.resourceUUID,417 permissions: modifiedAccessObj.permissions,418 accountType: accessObj.accountType.toLowerCase()419 }420 if (newMembership['accountType'] == 'user') {421 newMembership['firstName'] = accessObj.firstName;422 newMembership['lastName'] = accessObj.lastName;423 } else {424 newMembership['groupName'] = accessObj.groupName;425 }426 networkManager.modifiedAccessObjects.push(newMembership);427 }428 });429 _.each(networkManager.modifiedAccessObjects, function(membershipObj)430 {431 _.remove(networkManager.selectedAccountsForUpdatingAccessPermissions, {memberUUID: membershipObj.memberUUID});432 });433 // add new network memberships, once done, dispatch ADDING_PERMISSIONS_DONE event that will be caught434 // by the function that listens on this event.435 // updateNetworkMembership is recursive, it calls itself until it exhausts the addedAccessObjects list,436 // at which point it dispatches ADDING_PERMISSIONS_DONE.437 // The function that catches this event then calls updateNetworkMembership with438 // networkManager.modifiedAccessObjects list for modifying permissions on the server, etc.439 // We process permissions recursively since we want to make sure that changing admin (if it was selected)440 // is the very last operation.441 updateNetworkMembership(addedAccessObjects, 5, 1, 'ADDING_PERMISSIONS_DONE');442 };443 networkManager.memberIsAdmin = function(member) {444 if (!member || !member.memberUUID) {445 return false;446 };447 var adminPermissionObj = _.find(networkManager.originalAccessPermissions, {permissions: 'ADMIN'});448 var retValue = (adminPermissionObj && (adminPermissionObj['memberUUID'] == member.memberUUID));449 return retValue;450 };451 networkManager.loadUserPermissionsOnNetwork = function() {452 // no permission means return all permissions453 var permission = null;454 ndexService.getAllPermissionsOnNetworkV2(networkManager.externalId, "user", permission, 0, 1000000,455 function (mapOfUserPermissions, networkId) {456 var userUUIDs = Object.keys(mapOfUserPermissions);457 networkManager.mapOfUserPermissions = mapOfUserPermissions;458 ndexService.getUsersByUUIDsV2(userUUIDs)459 .success(460 function (userList) {461 networkManager.networkUserMemberships = userList;462 networkManager.processUserAccessPermissions();463 })464 .error(465 function(error) {466 console.log("unable to get users by UUIDs");467 }468 )469 }),470 function (error, networkId) {471 console.log("unable to get user permissions on network");472 };473 };474 networkManager.loadGroupPermissionsOnNetwork = function() {475 476 // no permission means return all permissions477 var permission = null;478 ndexService.getAllPermissionsOnNetworkV2(networkManager.externalId, "group", permission, 0, 1000000,479 function (mapOfGroupPermissions, groupId) {480 var groupsUUIDs = Object.keys(mapOfGroupPermissions);481 networkManager.mapOfGroupPermissions = mapOfGroupPermissions;482 ndexService.getGroupsByUUIDsV2(groupsUUIDs)483 .success(484 function (groupList) {485 networkManager.networkGroupMemberships = groupList;486 networkManager.processGroupAccessPermissions();487 })488 .error(489 function(error) {490 console.log("unable to get groups by UUIDs");491 }492 )493 }),494 function (error, groupId) {495 console.log("unable to get group permissions on network");496 };497 };498 networkManager.processGroupAccessPermissions = function() {499 // get accounts info; we need to know what accounts are user500 // and what accounts are group accounts; we display First and Last Names for User accounts501 // and Group Account Name for group accounts502 for (var i = 0; i < networkManager.networkGroupMemberships.length; i++) {503 var group = networkManager.networkGroupMemberships[i];504 var newMembership = {505 memberUUID: group.externalId,506 groupName: group.groupName,507 resourceUUID: networkManager.externalId,508 permissions: networkManager.mapOfGroupPermissions[group.externalId],509 accountType: "group",510 member: true511 }512 networkManager.originalAccessPermissions.push(newMembership);513 // make a copy of newMembership anda push it to selectedAccountsForUpdatingAccessPermissions;514 // we cannot do just networkManager.selectedAccountsForUpdatingAccessPermissions.push(newMembership)515 // since in this case any manipulations on selectedAccountsForUpdatingAccessPermissions will516 // also affect networkManager.originalAccessPermissions517 networkManager.selectedAccountsForUpdatingAccessPermissions.push(JSON.parse(JSON.stringify(newMembership)));518 }519 }520 networkManager.processUserAccessPermissions = function() {521 // get accounts info; we need to know what accounts are user522 // and what accounts are group accounts; we display First and Last Names for User accounts523 // and Group Account Name for group accounts524 for (var i = 0; i < networkManager.networkUserMemberships.length; i++) {525 var user = networkManager.networkUserMemberships[i];526 var newMembership = {527 memberAccountName: user.userName,528 memberUUID: user.externalId,529 resourceUUID: networkManager.externalId,530 permissions: networkManager.mapOfUserPermissions[user.externalId],531 firstName: user.firstName,532 lastName: user.lastName,533 accountType: "user",534 member: true535 }536 537 networkManager.originalAccessPermissions.push(newMembership);538 // make a copy of newMembership anda push it to selectedAccountsForUpdatingAccessPermissions;539 // we cannot do just networkManager.selectedAccountsForUpdatingAccessPermissions.push(newMembership)540 // since in this case any manipulations on selectedAccountsForUpdatingAccessPermissions will541 // also affect networkManager.originalAccessPermissions542 networkManager.selectedAccountsForUpdatingAccessPermissions.push(JSON.parse(JSON.stringify(newMembership)));543 }544 };545 546 networkManager.getGroupPermissions = function(accountsInfo, newMembership) {547 var accountUUID = newMembership.memberUUID;548 for (var i = 0; i < accountsInfo.length; i++)549 {550 if (accountUUID === accountsInfo[i].externalId)551 {552 newMembership.groupName = accountsInfo[i].groupName;553 break;554 }555 }556 return;557 }558 networkManager.getNamesAndAccountType = function(accountsInfo, newMembership) {559 var accountUUID = newMembership.memberUUID;560 for (var i = 0; i < accountsInfo.length; i++) {561 if (accountUUID === accountsInfo[i].externalId) {562 if (accountsInfo[i].accountType.toLowerCase() === "user") {563 newMembership.firstName = accountsInfo[i].firstName;564 newMembership.lastName = accountsInfo[i].lastName;565 newMembership.accountType = accountsInfo[i].accountType;566 } else if (accountsInfo[i].accountType.toLowerCase() === "group") {567 newMembership.groupName = accountsInfo[i].groupName;568 newMembership.accountType = accountsInfo[i].accountType;569 }570 break;571 }572 }573 return;574 }575 networkManager.findUsers = function() {576 var searchString = networkManager.searchString;577 ndexService.searchUsersV2(searchString, 0, 10,578 function(users) {579 networkManager.newUsers = users.resultList;580 var length2 = users.resultList.length;581 var length = networkManager.selectedAccountsForUpdatingAccessPermissions.length;582 for(var jj=0; jj<length2; jj++) {583 for(var ii=0; ii<length; ii++) {584 if(networkManager.selectedAccountsForUpdatingAccessPermissions[ii].memberUUID == users.resultList[jj].externalId)585 users.resultList[jj].member = true;586 };587 };588 },589 function(error) {590 networkManager.errors.push(error.data)591 });592 };593 networkManager.findGroups = function() {594 ndexService.searchGroupsV2(networkManager.groupSearchString, 0, 10,595 function(groups) {596 networkManager.newGroups = groups.resultList;597 var length2 = groups.resultList.length;598 var length = networkManager.selectedAccountsForUpdatingAccessPermissions.length599 for(var jj=0; jj<length2; jj++) {600 for(var ii=0; ii<length; ii++) {601 if(networkManager.selectedAccountsForUpdatingAccessPermissions[ii].memberUUID == groups.resultList[jj].externalId)602 groups.resultList[jj].member = true;603 };604 };605 },606 function(error) {607 networkManager.errors.push(error.data)608 });609 };610 networkManager.discardChanges = function() {611 if (!networkManager.changesWereMade()) {612 // no changes to the list of accounts with permissions were made;613 // no action is required614 return;615 }616 // to discard all the changes, we need to empty the list of selectedAccountsForUpdatingAccessPermissions and617 // repopulate it with the values from originalAccessPermissions618 for (var i = 0; i < networkManager.selectedAccountsForUpdatingAccessPermissions.length; i++) {619 var accountToRemove = networkManager.selectedAccountsForUpdatingAccessPermissions[i];620 if ((accountToRemove.accountType.toLowerCase() === 'user') &&621 (typeof(networkManager.newUsers) !== 'undefined')) {622 for (var j = 0; j < networkManager.newUsers.length; j++) {623 if (networkManager.newUsers[j].externalId === accountToRemove.memberUUID) {624 networkManager.newUsers[j].member = false;625 };626 };627 } else if ((accountToRemove.accountType.toLowerCase() === 'group') &&628 (typeof(networkManager.newGroups) !== 'undefined')) {629 for (var j = 0; j < networkManager.newGroups.length; j++) {630 if (networkManager.newGroups[j].externalId === accountToRemove.memberUUID) {631 networkManager.newGroups[j].member = false;632 }633 }634 };635 };636 networkManager.selectedAccountsForUpdatingAccessPermissions = [];637 for (var i = 0; i < networkManager.originalAccessPermissions.length; i++) {638 var originalAccessPerm = networkManager.originalAccessPermissions[i];639 networkManager.selectedAccountsForUpdatingAccessPermissions.push(JSON.parse(JSON.stringify(originalAccessPerm)));640 if (typeof(networkManager.newUsers) !== 'undefined') {641 for (var j = 0; j < networkManager.newUsers.length; j++) {642 if (networkManager.newUsers[j].externalId === originalAccessPerm.memberUUID) {643 networkManager.newUsers[j].member = true;644 };645 };646 };647 if (typeof(networkManager.newGroups) !== 'undefined') {648 for (var j = 0; j < networkManager.newGroups.length; j++) {649 if (networkManager.newGroups[j].externalId === originalAccessPerm.memberUUID) {650 networkManager.newGroups[j].member = true;651 };652 };653 };654 };655 };656 networkManager.removeMember = function(index, memberToRemove) {657 networkManager.selectedAccountsForUpdatingAccessPermissions.splice(index, 1);658 if (typeof(networkManager.newUsers) !== 'undefined') {659 for (var i = 0; i < networkManager.newUsers.length; i++) {660 if (networkManager.newUsers[i].externalId === memberToRemove.memberUUID) {661 networkManager.newUsers[i].member = false;662 };663 };664 };665 if (typeof(networkManager.newGroups) !== 'undefined') {666 for (var i = 0; i < networkManager.newGroups.length; i++) {667 if (networkManager.newGroups[i].externalId === memberToRemove.memberUUID) {668 networkManager.newGroups[i].member = false;669 };670 };671 };672 };673 networkManager.addMember = function(member) {674 var newMembership = {675 memberAccountName: networkManager.getAccountName(member),676 memberUUID: member.externalId,677 resourceName: networkManager.network.name,678 resourceUUID: networkManager.network.externalId,679 permissions: 'READ',680 firstName: ((typeof(member.firstName) === 'undefined') ? "" : member.firstName),681 lastName: ((typeof(member.lastName) === 'undefined') ? "" : member.lastName),682 groupName: ((typeof(member.groupName) === 'undefined') ? "" : member.groupName),683 accountType: member.accountType,684 member: true685 };686 member.member = true;687 networkManager.selectedAccountsForUpdatingAccessPermissions.push(newMembership);688 };689 690 networkManager.addUserMember = function(user) {691 var newMembership = {692 memberAccountName: networkManager.getUserAccountName(user),693 memberUUID: user.externalId,694 resourceName: networkManager.network.name,695 resourceUUID: networkManager.network.externalId,696 permissions: 'READ',697 firstName: ((typeof(user.firstName) === 'undefined') ? "" : user.firstName),698 lastName: ((typeof(user.lastName) === 'undefined') ? "" : user.lastName),699 accountType: 'user',700 member: true701 };702 user.member = true;703 networkManager.selectedAccountsForUpdatingAccessPermissions.push(newMembership);704 };705 networkManager.addGroupMember = function(group) {706 var newMembership = {707 memberAccountName: networkManager.getGroupAccountName(group),708 memberUUID: group.externalId,709 resourceName: networkManager.network.name,710 resourceUUID: networkManager.network.externalId,711 permissions: 'READ',712 groupName: ((typeof(group.groupName) === 'undefined') ? "" : group.groupName),713 accountType: 'group',714 member: true715 };716 group.member = true;717 networkManager.selectedAccountsForUpdatingAccessPermissions.push(newMembership);718 };719 networkManager.changesWereMade = function() {720 if (networkManager.selectedAccountsForUpdatingAccessPermissions.length !=721 networkManager.originalAccessPermissions.length) {722 return true;723 };724 for (var i = 0; i < networkManager.selectedAccountsForUpdatingAccessPermissions.length; i++) {725 var selectedObj = networkManager.selectedAccountsForUpdatingAccessPermissions[i];726 var found = false;727 for (var j = 0; j < networkManager.originalAccessPermissions.length; j++) {728 var originalObj = networkManager.originalAccessPermissions[j];729 if (selectedObj.memberUUID === originalObj.memberUUID) {730 if (selectedObj.permissions.toUpperCase() === originalObj.permissions.toUpperCase()) {731 found = true;732 break;733 }734 else {735 return true;736 };737 };738 };739 if (!found) {740 return true;741 };742 };743 return false;744 };745 networkManager.nothingSelected = function() {746 return networkManager.selectedAccountsForUpdatingAccessPermissions.length == 0;747 };748 networkManager.getAccountName = function(account) {749 if (typeof(account) === 'undefined') {750 return 'undefined';751 };752 if ((typeof(account.userName) !== 'undefined') && (account.userName === 'ndexadministrator')) {753 return account.userName;754 };755 if ((typeof(account.memberAccountName) !== 'undefined') && (account.memberAccountName === 'ndexadministrator')) {756 return account.memberAccountName;757 };758 if (account.accountType.toLowerCase() == 'user') {759 return account.firstName + " " + account.lastName;760 };761 if (account.accountType.toLowerCase() == 'group') {762 return account.groupName;763 };764 return "unknown account type";765 };766 networkManager.getUserAccountName = function(user) {767 if (typeof(user) === 'undefined') {768 return 'undefined';769 };770 if ((typeof(user.userName) !== 'undefined') && (user.userName === 'ndexadministrator')) {771 return user.userName;772 };773 if ((typeof(user.memberAccountName) !== 'undefined') && (user.memberAccountName === 'ndexadministrator')) {774 return user.memberAccountName;775 };776 if (user.isIndividual) {777 if (user.firstName && user.lastName) {778 return user.firstName + " " + user.lastName;779 };780 } else {781 if (user.displayName) {782 return user.displayName;783 };784 };785 return "unknown user";786 };787 networkManager.getGroupAccountName = function(group) {788 if (typeof(group) === 'undefined') {789 return 'undefined';790 };791 if (group.groupName) {792 return group.groupName;793 };794 795 return "unknown group";796 };797 networkManager.checkIfUserAccount = function(member) {798 if (member && member.accountType) {799 return (member.accountType.toLowerCase() === 'user') ? true : false;800 };801 return false;802 };803 networkManager.switchShareableURL = function() {804 var action = (networkManager.networkShareableURL) ? "disable" : "enable";805 ndexService.disableOrEnableAccessKeyOnNetworkV2(networkManager.externalId, action,806 function(data, status, headers, config, statusText) {807 if (action == 'enable') {808 networkManager.networkShareableURLLabel = "Disable Share URL";809 networkManager.networkShareableURL =810 uiMisc.buildNetworkURL(data['accessKey'], networkManager.externalId);811 } else {812 networkManager.networkShareableURLLabel = "Enable Share URL";813 networkManager.networkShareableURL = null;814 };815 },816 function(error) {817 console.log("unable to get access key for network " + networkManager.externalId);818 });819 };820 networkManager.getStatusOfShareableURL = function() {821 ndexService.getAccessKeyOfNetworkV2(networkManager.externalId,822 function(data) {823 if (!data) {824 // empty string - access is deactivated825 networkManager.networkShareableURL = null;826 networkManager.networkShareableURLLabel = "Enable Share URL";827 } else if (data['accessKey']) {828 // received data['accessKey'] - access is enabled829 networkManager.networkShareableURL =830 uiMisc.buildNetworkURL(data['accessKey'], networkManager.externalId);831 networkManager.networkShareableURLLabel = "Disable Share URL";832 } else {833 // this should not happen; something went wrong; access deactivated834 networkManager.networkShareableURL = null;835 networkManager.networkShareableURLLabel = "Enable Share URL";836 };837 },838 function(error) {839 console.log("unable to get access key for network " + networkManager.externalId);840 });841 };842 // INTIALIZATIONS843 //------------------------------------------------------------------------------------844 ndexService.getNetworkSummaryV2(identifier)845 .success(846 function(network){847 networkManager.network = network;848 $scope.showChangeShareURLButton();849 if (network.visibility && (network.visibility.toUpperCase() == 'PRIVATE')) {850 networkManager.showShareURLControl = true;851 networkManager.getStatusOfShareableURL();852 };853 })854 .error(855 function(error){856 networkManager.errors.push(error.data);857 })858 var userId = sharedProperties.getCurrentUserId();859 var networkId = identifier;860 var directonly = false;861 ndexService.getUserPermissionForNetworkV2(userId, networkId, directonly,862 function(membership) {863 if (membership) {864 var myMembership = membership[networkId];865 if (myMembership == 'ADMIN') {866 networkManager.isAdmin = true;867 }868 }869 },870 function(error) {871 networkManager.errors.push(error.data)872 })873 networkManager.loadUserPermissionsOnNetwork();874 networkManager.loadGroupPermissionsOnNetwork();...

Full Screen

Full Screen

HallAPI.js

Source:HallAPI.js Github

copy

Full Screen

1var api = module.exports = {};23//进入大厅4api.entry = function (token, userInfo, cbRouter, cbFail) {5 var router = 'connector.entryHandler.entry';6 var requestData = {7 token: token,8 userInfo: userInfo9 };10 Global.NetworkManager.send(router, requestData, cbRouter || 'EntryHallResponse', cbFail);11};1213// --------------------------------------------用户相关------------------------------------------14//查找玩家,获取玩家信息15api.searchRequest = function (uid, cbRouter) {16 var router = 'hall.userHandler.searchUserData';17 var requestData = {18 uid: uid19 };20 Global.NetworkManager.send(router, requestData, cbRouter || 'SearchResponse')21};2223//绑定手机号24api.bindAccountRequest = function (account, code, uniqueID, password, cbRouter, cbFail) {25 var router = 'hall.userHandler.bindAccount';26 var requestData = {27 account: account,28 code: code,29 uniqueID: uniqueID,30 password: password31 };32 Global.NetworkManager.send(router, requestData, cbRouter || 'bindAccountResponse', cbFail);33};3435//绑定真实姓名36api.bindRealNameRequest = function (realName, cbRouter) {37 var router = 'hall.userHandler.bindRealName';38 var requestData = {39 realName: realName40 };41 Global.NetworkManager.send(router, requestData, cbRouter || 'BindRealNameResponse');42};4344// 修改昵称45api.changeNicknameRequest = function (nickName, cbRouter) {46 var router = 'hall.userHandler.updateNickName';47 var requestData = {48 nickName: nickName49 };50 Global.NetworkManager.send(router, requestData, cbRouter || 'ChangeNicknameResponse');51};5253// 修改头像54api.changeAvatarRequest = function (avatar, sex, cbRouter) {55 var router = 'hall.userHandler.updateAvatar';56 var requestData = {57 avatar: avatar,58 sex: sex59 };60 Global.NetworkManager.send(router, requestData, cbRouter || 'ChangeAvatarResponse');61};6263// 更新银行卡信息64api.updateBankCardInfoRequest = function (ownerName, cardNumber, code, province, city, bankInfo, cbRouter) {65 var router = 'hall.userHandler.updateBankCardInfo';66 var requestData = {67 bankCardInfo: {68 cardNumber: cardNumber,69 ownerName: ownerName,70 code: code,71 province: province,72 city: city,73 bankInfo: bankInfo,74 //ownerName名字75 // cardNumber 卡号76 // code 银行code77 // province 省份78 // city 城市79 // bankInfo 开户行80 }81 };82 Global.NetworkManager.send(router, requestData, cbRouter || 'UpdateBankCardInfoResponse');83};8485// 更新支付宝信息86api.updateAliPayInfoRequest = function (aliPayAccount, ownerName, cbRouter) {87 var router = 'hall.userHandler.updateAliPayInfoRequest';88 var requestData = {89 aliPayInfo: {90 aliPayAccount: aliPayAccount,91 ownerName: ownerName92 }93 };94 Global.NetworkManager.send(router, requestData, cbRouter || 'UpdateAliPayInfoResponse');95};9697// 保险柜操作98/**99 * @param count 大于0为存入,小于0为取出100 * @param password 取出时需要密码101 * @param cbRouter102 */103api.safeBoxOperationRequest = function (count, password, cbRouter) {104 var router = 'hall.userHandler.safeBoxOperation';105 var requestData = {106 count: Number(count),107 safePassword: password108 };109 Global.NetworkManager.send(router, requestData, cbRouter || 'SafeBoxOperationResponse');110};111112// 修改登录密码113api.updateLoginPasswordRequest = function (oldPassword, newPassword, cbRouter) {114 var router = 'hall.userHandler.updateLoginPassword';115 var requestData = {116 oldPassword: oldPassword,117 newPassword: newPassword118 };119 Global.NetworkManager.send(router, requestData, cbRouter || 'UpdateLoginPasswordResponse');120};121122// 修改保险柜密码123api.updateSafePasswordRequest = function (oldPassword, newPassword, cbRouter) {124 var router = 'hall.userHandler.updateSafePassword';125 var requestData = {126 oldPassword: oldPassword,127 newPassword: newPassword128 };129 Global.NetworkManager.send(router, requestData, cbRouter || 'UpdateSafePasswordResponse');130};131132// 提款申请133/**134 * @param count135 * @param withdrawCashType: enumeration.withdrawCashType136 * @param cbRouter137 */138api.withdrawCashRequest = function (count, withdrawCashType, cbRouter) {139 var router = 'hall.currencyHandler.withdrawCashRequest';140 var requestData = {141 count: count,142 withdrawCashType: withdrawCashType143 };144 Global.NetworkManager.send(router, requestData, cbRouter || 'WithdrawCashResponse');145};146147// 提取佣金148api.extractionCommissionRequest = function (cbRouter) {149 var router = 'hall.currencyHandler.extractionCommission';150 var requestData = {};151 Global.NetworkManager.send(router, requestData, cbRouter || 'ExtractionCommissionResponse');152};153154155//提取佣金记录156api.getRecordData = function (startIndex, count, RecordType, cbRouter) {157 var router = 'hall.recordHandler.getRecordData';158 var requestData = {159 recordType: RecordType,160 startIndex: startIndex,161 count: count162 };163 cc.log(router, RecordType)164 Global.NetworkManager.send(router, requestData, cbRouter || 'getRecordDataResponse');165};166167// --------------------------------------------排行榜相关------------------------------------------168// 获取今日赢金币数量排行榜169// api.getTodayWinGoldCountRankRequest = function (startIndex, count, cbRouter) {170// var router = 'hall.rankHandler.getTodayWinGoldCountRankRequest';171// var requestData = {172// startIndex: startIndex,173// count: count174// };175// Global.NetworkManager.send(router, requestData, cbRouter || 'GetTodayWinGoldCountRankResponse');176// };177178// 获取今日赢金币数量排行榜179api.getTodayWinGoldCountRankRequest = function (startIndex, count, cbRouter) {180 var router = 'center.rankHandler.getTodayWinGoldCountRankRequest';181 var requestData = {182 startIndex: startIndex,183 count: count184 };185 Global.NetworkManager.send(router, requestData, cbRouter || 'GetTodayWinGoldCountRankResponse');186};187188// --------------------------------------------充值相关------------------------------------------189//购买商城物品190api.purchaseRechargeItemRequest = function (itemID, rechargePlatform, rechargeInfo, cbRouter) {191 var router = 'hall.rechargeHandler.purchaseItem';192 var requestData = {193 itemID: itemID,194 rechargePlatform: rechargePlatform,195 rechargeInfo: rechargeInfo196 };197 Global.NetworkManager.send(router, requestData, cbRouter || 'PurchaseRechargeItemResponse');198};199200// --------------------------------------------记录相关------------------------------------------201// 获取记录202/**203 * recordType : enumeration.recordType204 */205api.getRecordDataRequest = function (recordType, startIndex, count, cbRouter) {206 var router = 'hall.recordHandler.getRecordData';207 var requestData = {208 recordType: recordType,209 startIndex: startIndex,210 count: count211 };212 Global.NetworkManager.send(router, requestData, cbRouter || 'GetRecordDataResponse')213};214215api.getDirectlyMemberRecordDataRequest = function (startIndex, count, cbRouter) {216 var router = 'hall.recordHandler.getDirectlyMemberRecordData';217 var requestData = {218 startIndex: startIndex,219 count: count220 };221 Global.NetworkManager.send(router, requestData, cbRouter || 'GetDirectlyMemberRecordDataResponse')222};223224api.getAgentMemberRecordDataRequest = function (startIndex, count, cbRouter) {225 var router = 'hall.recordHandler.getAgentMemberRecordData';226 var requestData = {227 startIndex: startIndex,228 count: count229 };230 Global.NetworkManager.send(router, requestData, cbRouter || 'GetAgentMemberRecordDataResponse')231};232233// --------------------------------------------房间相关------------------------------------------234api.createRoomRequest = function (parameters, gameTypeID, cbRouter) {235 var router = 'hall.gameHandler.createRoom';236 var requestData = {237 gameRule: parameters,238 gameTypeID: gameTypeID239 };240 Global.NetworkManager.send(router, requestData, cbRouter || 'CreateRoomResponse');241};242243api.joinRoomRequest = function (joinRoomID, cbRouter, cbFail, gameID) {244 var router = 'hall.gameHandler.joinRoom';245 var requestData = {246 roomId: joinRoomID247 };248 console.warn("正在加入房间::" + joinRoomID);249250 if (gameID) {251 Global.NetworkManager.send(router, requestData, cbRouter || 'JoinRoomResponse', (data) => {252 Confirm.show("房间已经解散", () => {253 ViewMgr.goBackHall(gameID);254 })255 });256 } else {257 Global.NetworkManager.send(router, requestData, cbRouter || 'JoinRoomResponse', cbFail);258 }259260};261262api.exitRoomRequest = function (cbRouter) {263 var router = 'hall.gameHandler.exitRoom';264 var requestData = {};265 Global.NetworkManager.send(router, requestData, cbRouter || 'ExitRoomResponse');266};267268api.matchRoomRequest = function (gameTypeID, cbRouter, cbFail) {269 var router = 'hall.gameHandler.matchRoom';270 var requestData = {271 gameTypeID: gameTypeID272 };273 Global.NetworkManager.send(router, requestData, cbRouter || 'MatchRoomResponse', cbFail);274};275276api.stopMatchRoomRequest = function (cbRouter) {277 var router = 'hall.gameHandler.stopMatchRoom';278 var requestData = {};279 Global.NetworkManager.send(router, requestData, cbRouter || 'StopMatchRoomResponse');280};281282api.getAllRoomGameDataByKind = function (kindID, cbRouter) {283 var router = 'hall.gameHandler.getAllRoomGameDataByKind';284 var requestData = {285 kindID: kindID286 };287 //异步函数处理288 if (typeof cbRouter == "function") {289 Global.NetworkManager.send(router, requestData, cbRouter || 'getAllRoomGameDataByKindResponse');290 } else {291 return new Promise((resolve, reject) => {292 Global.NetworkManager.send(router, requestData,293 (msg) => {294 resolve(msg);295 },296 (msg) => {297 resolve(msg);298 });299 });300 }301};302303api.getRoomGameDataByRoomID = function (roomID, cbRouter) {304 var router = 'hall.gameHandler.getRoomGameDataByRoomID';305 var requestData = {306 roomID: roomID307 };308 Global.NetworkManager.send(router, requestData, cbRouter || 'GetRoomGameDataByRoomIDResponse');309};310311// --------------------------------------------其他相关------------------------------------------312api.readEmailRequest = function (emailID, cbRouter) {313 var router = 'hall.emailHandler.readEmail';314 var requestData = {315 emailID: emailID316 };317 Global.NetworkManager.send(router, requestData, cbRouter || 'ReadEmailResponse')318};319//获取游戏公告320api.getNoticeRequest = function (cbRouter) {321 var router = 'hall.hallHandler.getNotice';322 var requestData = {};323 Global.NetworkManager.send(router, requestData, cbRouter || 'getNoticeResponse')324};325326//签到查询327api.CheckInRecordRequest = function (cbRouter) {328 var router = 'hall.activityHandler.getCheckInRecord';329 var requestData = {};330 Global.NetworkManager.send(router, requestData, cbRouter || 'CheckInRecordResponse');331}332333//签到334api.CheckInRequest = function (cbRouter) {335 var router = 'hall.activityHandler.checkIn';336 var requestData = {};337 Global.NetworkManager.send(router, requestData, cbRouter || 'CheckInResponse');338}339340//获取邮件列表341api.getMailRequest = function (cbRouter) {342 var router = 'hall.emailHandler.getEmail';343 var requestData = {};344 Global.NetworkManager.send(router, requestData, cbRouter || 'getMailResponse')345};346347//邮件操作状态348api.operationEmail = function (ID, type, cbRouter) {349 var router = 'hall.emailHandler.operationEmail';350 var requestData = {351 _id: ID,352 type: type353 };354 Global.NetworkManager.send(router, requestData, cbRouter || 'operationEmailResponse')355};356357//洗码记录358api.getWashCodeRecord = function (cbRouter) {359 var router = 'hall.activityHandler.getWashCodeRecord';360 var requestData = {};361 Global.NetworkManager.send(router, requestData, cbRouter || 'getWashCodeRecordResponse')362};363364//获取洗码信息365api.getWashCodeDate = function (cbRouter) {366 var router = 'hall.activityHandler.getWashCodeData';367 var requestData = {};368 Global.NetworkManager.send(router, requestData, cbRouter || 'getWvashCodeDataResponse')369};370371//请求洗码372api.washCodeRequest = function (cbRouter) {373 var router = 'hall.activityHandler.washCode';374 var requestData = {};375 Global.NetworkManager.send(router, requestData, cbRouter || 'washCodeResponse')376};377//抽奖转盘 获取大奖记录378api.getTurntableGrandPrizeRecordRequest = function (cbRouter) {379 var router = 'hall.activityHandler.getTurntableGrandPrizeRecord';380 var requestData = {};381 Global.NetworkManager.send(router, requestData, cbRouter || 'getTurntableGrandPrizeRecordResponse');382};383384//抽奖转盘 获取个人中奖记录385api.getTurntableSelfRecordRequest = function (cbRouter) {386 var router = 'hall.activityHandler.getTurntableSelfRecord';387 var requestData = {};388 Global.NetworkManager.send(router, requestData, cbRouter || 'getTurntableSelfRecordResponse');389};390391//抽奖转盘 抽奖392api.turntableRequest = function (type_, cbRouter, cbFail) {393 var router = 'hall.activityHandler.turntable';394 var requestData = {};395 requestData.type = type_;396 Global.NetworkManager.send(router, requestData, cbRouter || 'turntableResponse', cbFail);397};398399//抽奖转盘 获取转盘配置400api.getTurntableGrandConfigRequest = function (cbRouter) {401 var router = 'hall.activityHandler.getTurntableGrandConfig';402 var requestData = {};403 Global.NetworkManager.send(router, requestData, cbRouter || 'getTurntableGrandConfigResponse');404};405406//获取会员等级407api.getVIPactivityRequest = function (cbRouter) {408 var router = 'hall.activityHandler.getUserVipInfo';409 var requestData = {};410 Global.NetworkManager.send(router, requestData, cbRouter || 'getUserVipInfoResponse');411};412413414// //晋级礼金领取415// api.getVIPPromotionMoney = function (cbRouter) {416// var router = 'hall.activityHandler.getVIPPromotionMoney';417// var requestData = {};418// Global.NetworkManager.send(router, requestData, cbRouter || 'getVIPPromotionMoneyResponse');419// };420421// //周礼金领取422// api.getVIPWeeksMoney = function (cbRouter) {423// var router = 'hall.activityHandler.getVIPWeeksMoney';424// var requestData = {};425// Global.NetworkManager.send(router, requestData, cbRouter || 'getVIPWeeksMoneyResponse');426// };427428// //月礼金领取429// api.getVIPMonthMoney = function (cbRouter) {430// var router = 'hall.activityHandler.getVIPMonthMoney';431// var requestData = {};432// Global.NetworkManager.send(router, requestData, cbRouter || 'getVIPMonthMoneyResponse');433// };434435//领取Vip权益436api.getVipReward = function (type, cbRouter) {437 var router = 'hall.activityHandler.getVipReward';438 var requestData = {439 type: type440 };441 Global.NetworkManager.send(router, requestData, cbRouter || 'getVIPMonthMoneyResponse');442};443444//获取游戏房间列表445api.getRoomListByKind = function (kindID, cbRouter) {446 var router = 'hall.gameHandler.getRoomListByKind';447 var requestData = {448 kindID: kindID,449 }450 //异步函数处理451 if (typeof cbRouter == "function") {452 Global.NetworkManager.send(router, requestData, cbRouter || 'getRoomListByKindResponse');453 } else {454 return new Promise((resolve, reject) => {455 try {456 Global.NetworkManager.send(router, requestData,457 (msg) => {458 resolve(msg);459 },460 (msg) => {461 resolve(msg);462 });463 } catch (error) {464 console.error(error);465 resolve();466 }467468 });469 }470471};472473//获取游戏代理充值配置474api.getAgentRechargeConfigs = function (cbRouter, cbFail) {475 var router = 'hall.rechargeHandler.getAgentRechargeConfigs';476 var requestData = {};477 Global.NetworkManager.send(router, requestData, cbRouter || 'getAgentRechargeConfigsResponse', cbFail);478};479480//获取游戏银行充值配置481//type 1 银行卡转账 2 微信转银行卡 3 支付宝转银行卡482api.getBankRechargeConfigs = function (type, cbRouter, cbFail) {483 var router = 'hall.rechargeHandler.getBankRechargeConfigs';484 var requestData = {485 type: type486 };487 Global.NetworkManager.send(router, requestData, cbRouter || 'getBankRechargeConfigsResponse', cbFail);488};489490//投诉代理491api.complaintAgent = function (data, cbRouter) {492 var router = 'hall.rechargeHandler.complaintAgent';493 var requestData = {494 weChat: data.weChat,495 content: data.content496 };497 Global.NetworkManager.send(router, requestData, cbRouter || 'complaintAgentResponse');498};499500// 银行转账充值501api.userBankRecharge = function (data, cbRouter) {502 var router = 'hall.rechargeHandler.userBankRecharge';503 var requestData = {504 uuid: data.uuid,505 rechargeInfo: data.rechargeInfo,506 gold: data.gold,507 type: data.type508 };509 Global.NetworkManager.send(router, requestData, cbRouter || 'userBankRechargeResponse');510};511512// 获取充值方式513api.getRechargeDis = function (cbRouter, cbFail) {514 var router = 'hall.rechargeHandler.getRechargeDis';515 var requestData = {};516 Global.NetworkManager.send(router, requestData, cbRouter || 'getRechargeDisResponse', cbFail);517};518519//获取线上充值配置520api.getOnlineRechargeConfig = function (rechargeDisID, cbRouter, cbFail) {521 var router = 'hall.rechargeHandler.getOnlineRechargeConfig';522 var requestData = {523 rechargeDisID: rechargeDisID524 };525 Global.NetworkManager.send(router, requestData, cbRouter || 'getOnlineRechargeConfigResponse', cbFail);526};527528529//获取充值配置530api.getOnlineRechargeUrl = function (rechargeID, rechargeGold, cbRouter, cbFail) {531 var router = 'hall.rechargeHandler.getOnlineRechargeUrl';532 var requestData = {533 rechargeID: rechargeID,534 rechargeGold: parseInt(rechargeGold)535 };536 Global.NetworkManager.send(router, requestData, cbRouter || 'getOnlineRechargeUrlResponse', cbFail);537};538539//获取充值记录540api.getRechargeRecord = function (cbRouter, cbFail) {541 var router = 'hall.rechargeHandler.getRechargeRecord';542 var requestData = {};543 Global.NetworkManager.send(router, requestData, cbRouter || 'getRechargeRecordResponse', cbFail);544};545//获取当前平台支持的提现方式546api.getWithdrawCashConfig = function (cbRouter, cbFail) {547 var router = 'hall.currencyHandler.getWithdrawCashConfig';548 var requestData = {};549 Global.NetworkManager.send(router, requestData, cbRouter || 'getWithdrawCashConfigResponse', cbFail); ...

Full Screen

Full Screen

NetworkLog.js

Source:NetworkLog.js Github

copy

Full Screen

1/*2 * Copyright (C) 2011 Google Inc. All rights reserved.3 *4 * Redistribution and use in source and binary forms, with or without5 * modification, are permitted provided that the following conditions are6 * met:7 *8 * * Redistributions of source code must retain the above copyright9 * notice, this list of conditions and the following disclaimer.10 * * Redistributions in binary form must reproduce the above11 * copyright notice, this list of conditions and the following disclaimer12 * in the documentation and/or other materials provided with the13 * distribution.14 * * Neither the name of Google Inc. nor the names of its15 * contributors may be used to endorse or promote products derived from16 * this software without specific prior written permission.17 *18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29 */30/**31 * @implements {SDK.SDKModelObserver<!SDK.NetworkManager>}32 */33SDK.NetworkLog = class extends Common.Object {34 constructor() {35 super();36 /** @type {!Array<!SDK.NetworkRequest>} */37 this._requests = [];38 /** @type {!Set<!SDK.NetworkRequest>} */39 this._requestsSet = new Set();40 /** @type {!Map<!SDK.NetworkManager, !SDK.NetworkLog.PageLoad>} */41 this._pageLoadForManager = new Map();42 this._isRecording = true;43 SDK.targetManager.observeModels(SDK.NetworkManager, this);44 }45 /**46 * @override47 * @param {!SDK.NetworkManager} networkManager48 */49 modelAdded(networkManager) {50 const eventListeners = [];51 eventListeners.push(52 networkManager.addEventListener(SDK.NetworkManager.Events.RequestStarted, this._onRequestStarted, this));53 eventListeners.push(54 networkManager.addEventListener(SDK.NetworkManager.Events.RequestUpdated, this._onRequestUpdated, this));55 eventListeners.push(56 networkManager.addEventListener(SDK.NetworkManager.Events.RequestRedirected, this._onRequestRedirect, this));57 eventListeners.push(58 networkManager.addEventListener(SDK.NetworkManager.Events.RequestFinished, this._onRequestUpdated, this));59 eventListeners.push(networkManager.addEventListener(60 SDK.NetworkManager.Events.MessageGenerated, this._networkMessageGenerated.bind(this, networkManager)));61 const resourceTreeModel = networkManager.target().model(SDK.ResourceTreeModel);62 if (resourceTreeModel) {63 eventListeners.push(64 resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.WillReloadPage, this._willReloadPage, this));65 eventListeners.push(resourceTreeModel.addEventListener(66 SDK.ResourceTreeModel.Events.MainFrameNavigated, this._onMainFrameNavigated, this));67 eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load, this._onLoad, this));68 eventListeners.push(resourceTreeModel.addEventListener(69 SDK.ResourceTreeModel.Events.DOMContentLoaded, this._onDOMContentLoaded.bind(this, resourceTreeModel)));70 }71 networkManager[SDK.NetworkLog._events] = eventListeners;72 }73 /**74 * @override75 * @param {!SDK.NetworkManager} networkManager76 */77 modelRemoved(networkManager) {78 this._removeNetworkManagerListeners(networkManager);79 }80 /**81 * @param {!SDK.NetworkManager} networkManager82 */83 _removeNetworkManagerListeners(networkManager) {84 Common.EventTarget.removeEventListeners(networkManager[SDK.NetworkLog._events]);85 }86 /**87 * @param {boolean} enabled88 */89 setIsRecording(enabled) {90 if (this._isRecording === enabled)91 return;92 this._isRecording = enabled;93 if (enabled) {94 SDK.targetManager.observeModels(SDK.NetworkManager, this);95 } else {96 SDK.targetManager.unobserveModels(SDK.NetworkManager, this);97 SDK.targetManager.models(SDK.NetworkManager).forEach(this._removeNetworkManagerListeners.bind(this));98 }99 }100 /**101 * @param {string} url102 * @return {?SDK.NetworkRequest}103 */104 requestForURL(url) {105 return this._requests.find(request => request.url() === url) || null;106 }107 /**108 * @return {!Array<!SDK.NetworkRequest>}109 */110 requests() {111 return this._requests;112 }113 /**114 * @param {!SDK.NetworkManager} networkManager115 * @param {!Protocol.Network.RequestId} requestId116 * @return {?SDK.NetworkRequest}117 */118 requestByManagerAndId(networkManager, requestId) {119 // We itterate backwards because the last item will likely be the one needed for console network request lookups.120 for (let i = this._requests.length - 1; i >= 0; i--) {121 const request = this._requests[i];122 if (requestId === request.requestId() && networkManager === SDK.NetworkManager.forRequest(request))123 return request;124 }125 return null;126 }127 /**128 * @param {!SDK.NetworkManager} networkManager129 * @param {string} url130 * @return {?SDK.NetworkRequest}131 */132 _requestByManagerAndURL(networkManager, url) {133 for (const request of this._requests) {134 if (url === request.url() && networkManager === SDK.NetworkManager.forRequest(request))135 return request;136 }137 return null;138 }139 /**140 * @param {!SDK.NetworkRequest} request141 */142 _initializeInitiatorSymbolIfNeeded(request) {143 if (!request[SDK.NetworkLog._initiatorDataSymbol]) {144 /** @type {!{info: ?SDK.NetworkLog._InitiatorInfo, chain: !Set<!SDK.NetworkRequest>, request: (?SDK.NetworkRequest|undefined)}} */145 request[SDK.NetworkLog._initiatorDataSymbol] = {146 info: null,147 chain: null,148 request: undefined,149 };150 }151 }152 /**153 * @param {!SDK.NetworkRequest} request154 * @return {!SDK.NetworkLog._InitiatorInfo}155 */156 initiatorInfoForRequest(request) {157 this._initializeInitiatorSymbolIfNeeded(request);158 if (request[SDK.NetworkLog._initiatorDataSymbol].info)159 return request[SDK.NetworkLog._initiatorDataSymbol].info;160 let type = SDK.NetworkRequest.InitiatorType.Other;161 let url = '';162 let lineNumber = -Infinity;163 let columnNumber = -Infinity;164 let scriptId = null;165 let initiatorStack = null;166 const initiator = request.initiator();167 const redirectSource = request.redirectSource();168 if (redirectSource) {169 type = SDK.NetworkRequest.InitiatorType.Redirect;170 url = redirectSource.url();171 } else if (initiator) {172 if (initiator.type === Protocol.Network.InitiatorType.Parser) {173 type = SDK.NetworkRequest.InitiatorType.Parser;174 url = initiator.url ? initiator.url : url;175 lineNumber = initiator.lineNumber ? initiator.lineNumber : lineNumber;176 } else if (initiator.type === Protocol.Network.InitiatorType.Script) {177 for (let stack = initiator.stack; stack; stack = stack.parent) {178 const topFrame = stack.callFrames.length ? stack.callFrames[0] : null;179 if (!topFrame)180 continue;181 type = SDK.NetworkRequest.InitiatorType.Script;182 url = topFrame.url || Common.UIString('<anonymous>');183 lineNumber = topFrame.lineNumber;184 columnNumber = topFrame.columnNumber;185 scriptId = topFrame.scriptId;186 break;187 }188 if (!initiator.stack && initiator.url) {189 type = SDK.NetworkRequest.InitiatorType.Script;190 url = initiator.url;191 lineNumber = initiator.lineNumber || 0;192 }193 if (initiator.stack && initiator.stack.callFrames && initiator.stack.callFrames.length)194 initiatorStack = initiator.stack || null;195 } else if (initiator.type === Protocol.Network.InitiatorType.Preload) {196 type = SDK.NetworkRequest.InitiatorType.Preload;197 } else if (initiator.type === Protocol.Network.InitiatorType.SignedExchange) {198 type = SDK.NetworkRequest.InitiatorType.SignedExchange;199 url = initiator.url;200 }201 }202 request[SDK.NetworkLog._initiatorDataSymbol].info = {203 type: type,204 url: url,205 lineNumber: lineNumber,206 columnNumber: columnNumber,207 scriptId: scriptId,208 stack: initiatorStack209 };210 return request[SDK.NetworkLog._initiatorDataSymbol].info;211 }212 /**213 * @param {!SDK.NetworkRequest} request214 * @return {!SDK.NetworkLog.InitiatorGraph}215 */216 initiatorGraphForRequest(request) {217 /** @type {!Set<!SDK.NetworkRequest>} */218 const initiated = new Set();219 const networkManager = SDK.NetworkManager.forRequest(request);220 for (const otherRequest of this._requests) {221 const otherRequestManager = SDK.NetworkManager.forRequest(request);222 if (networkManager === otherRequestManager && this._initiatorChain(otherRequest).has(request))223 initiated.add(otherRequest);224 }225 return {initiators: this._initiatorChain(request), initiated: initiated};226 }227 /**228 * @param {!SDK.NetworkRequest} request229 * @return {!Set<!SDK.NetworkRequest>}230 */231 _initiatorChain(request) {232 this._initializeInitiatorSymbolIfNeeded(request);233 let initiatorChainCache =234 /** @type {?Set<!SDK.NetworkRequest>} */ (request[SDK.NetworkLog._initiatorDataSymbol].chain);235 if (initiatorChainCache)236 return initiatorChainCache;237 initiatorChainCache = new Set();238 let checkRequest = request;239 do {240 if (checkRequest[SDK.NetworkLog._initiatorDataSymbol].chain) {241 initiatorChainCache.addAll(checkRequest[SDK.NetworkLog._initiatorDataSymbol].chain);242 break;243 }244 if (initiatorChainCache.has(checkRequest))245 break;246 initiatorChainCache.add(checkRequest);247 checkRequest = this._initiatorRequest(checkRequest);248 } while (checkRequest);249 request[SDK.NetworkLog._initiatorDataSymbol].chain = initiatorChainCache;250 return initiatorChainCache;251 }252 /**253 * @param {!SDK.NetworkRequest} request254 * @return {?SDK.NetworkRequest}255 */256 _initiatorRequest(request) {257 this._initializeInitiatorSymbolIfNeeded(request);258 if (request[SDK.NetworkLog._initiatorDataSymbol].request !== undefined)259 return request[SDK.NetworkLog._initiatorDataSymbol].request;260 const url = this.initiatorInfoForRequest(request).url;261 const networkManager = SDK.NetworkManager.forRequest(request);262 request[SDK.NetworkLog._initiatorDataSymbol].request =263 networkManager ? this._requestByManagerAndURL(networkManager, url) : null;264 return request[SDK.NetworkLog._initiatorDataSymbol].request;265 }266 _willReloadPage() {267 if (!Common.moduleSetting('network_log.preserve-log').get())268 this.reset();269 }270 /**271 * @param {!Common.Event} event272 */273 _onMainFrameNavigated(event) {274 const mainFrame = /** @type {!SDK.ResourceTreeFrame} */ (event.data);275 const manager = mainFrame.resourceTreeModel().target().model(SDK.NetworkManager);276 if (!manager || mainFrame.resourceTreeModel().target().parentTarget())277 return;278 const oldRequests = this._requests;279 const oldManagerRequests = this._requests.filter(request => SDK.NetworkManager.forRequest(request) === manager);280 const oldRequestsSet = this._requestsSet;281 this._requests = [];282 this._requestsSet = new Set();283 this.dispatchEventToListeners(SDK.NetworkLog.Events.Reset);284 // Preserve requests from the new session.285 let currentPageLoad = null;286 const requestsToAdd = [];287 for (const request of oldManagerRequests) {288 if (request.loaderId !== mainFrame.loaderId)289 continue;290 if (!currentPageLoad) {291 currentPageLoad = new SDK.NetworkLog.PageLoad(request);292 let redirectSource = request.redirectSource();293 while (redirectSource) {294 requestsToAdd.push(redirectSource);295 redirectSource = redirectSource.redirectSource();296 }297 }298 requestsToAdd.push(request);299 }300 // Preserve service worker requests from the new session.301 const serviceWorkerRequestsToAdd = [];302 for (const swRequest of oldRequests) {303 const networkManager = SDK.NetworkManager.forRequest(swRequest);304 if (!networkManager)305 continue;306 const target = networkManager.target();307 if (!(target.type() === SDK.Target.Type.Worker && target.parentTarget() &&308 target.parentTarget().type() === SDK.Target.Type.ServiceWorker))309 continue;310 // If there is a matching request that came before this one, keep it.311 const keepRequest = requestsToAdd.some(312 request => request.url() === swRequest.url() && request.issueTime() <= swRequest.issueTime());313 if (keepRequest)314 serviceWorkerRequestsToAdd.push(swRequest);315 }316 requestsToAdd.push(...serviceWorkerRequestsToAdd);317 for (const request of requestsToAdd) {318 oldRequestsSet.delete(request);319 this._requests.push(request);320 this._requestsSet.add(request);321 currentPageLoad.bindRequest(request);322 this.dispatchEventToListeners(SDK.NetworkLog.Events.RequestAdded, request);323 }324 if (Common.moduleSetting('network_log.preserve-log').get()) {325 for (const request of oldRequestsSet) {326 this._requests.push(request);327 this._requestsSet.add(request);328 this.dispatchEventToListeners(SDK.NetworkLog.Events.RequestAdded, request);329 }330 }331 if (currentPageLoad)332 this._pageLoadForManager.set(manager, currentPageLoad);333 }334 /**335 * @param {!Array<!SDK.NetworkRequest>} requests336 */337 importRequests(requests) {338 this.reset();339 this._requests = [];340 this._requestsSet.clear();341 for (const request of requests) {342 this._requests.push(request);343 this._requestsSet.add(request);344 this.dispatchEventToListeners(SDK.NetworkLog.Events.RequestAdded, request);345 }346 }347 /**348 * @param {!Common.Event} event349 */350 _onRequestStarted(event) {351 const request = /** @type {!SDK.NetworkRequest} */ (event.data);352 this._requests.push(request);353 this._requestsSet.add(request);354 const manager = SDK.NetworkManager.forRequest(request);355 const pageLoad = manager ? this._pageLoadForManager.get(manager) : null;356 if (pageLoad)357 pageLoad.bindRequest(request);358 this.dispatchEventToListeners(SDK.NetworkLog.Events.RequestAdded, request);359 }360 /**361 * @param {!Common.Event} event362 */363 _onRequestUpdated(event) {364 const request = /** @type {!SDK.NetworkRequest} */ (event.data);365 if (!this._requestsSet.has(request))366 return;367 this.dispatchEventToListeners(SDK.NetworkLog.Events.RequestUpdated, request);368 }369 /**370 * @param {!Common.Event} event371 */372 _onRequestRedirect(event) {373 const request = /** @type {!SDK.NetworkRequest} */ (event.data);374 delete request[SDK.NetworkLog._initiatorDataSymbol];375 }376 /**377 * @param {!SDK.ResourceTreeModel} resourceTreeModel378 * @param {!Common.Event} event379 */380 _onDOMContentLoaded(resourceTreeModel, event) {381 const networkManager = resourceTreeModel.target().model(SDK.NetworkManager);382 const pageLoad = networkManager ? this._pageLoadForManager.get(networkManager) : null;383 if (pageLoad)384 pageLoad.contentLoadTime = /** @type {number} */ (event.data);385 }386 /**387 * @param {!Common.Event} event388 */389 _onLoad(event) {390 const networkManager = event.data.resourceTreeModel.target().model(SDK.NetworkManager);391 const pageLoad = networkManager ? this._pageLoadForManager.get(networkManager) : null;392 if (pageLoad)393 pageLoad.loadTime = /** @type {number} */ (event.data.loadTime);394 }395 reset() {396 this._requests = [];397 this._requestsSet.clear();398 const managers = new Set(SDK.targetManager.models(SDK.NetworkManager));399 for (const manager of this._pageLoadForManager.keys()) {400 if (!managers.has(manager))401 this._pageLoadForManager.delete(manager);402 }403 this.dispatchEventToListeners(SDK.NetworkLog.Events.Reset);404 }405 /**406 * @param {!SDK.NetworkManager} networkManager407 * @param {!Common.Event} event408 */409 _networkMessageGenerated(networkManager, event) {410 const message = /** @type {!SDK.NetworkManager.Message} */ (event.data);411 const consoleMessage = new SDK.ConsoleMessage(412 networkManager.target().model(SDK.RuntimeModel), SDK.ConsoleMessage.MessageSource.Network,413 message.warning ? SDK.ConsoleMessage.MessageLevel.Warning : SDK.ConsoleMessage.MessageLevel.Info,414 message.message);415 this.associateConsoleMessageWithRequest(consoleMessage, message.requestId);416 SDK.consoleModel.addMessage(consoleMessage);417 }418 /**419 * @param {!SDK.ConsoleMessage} consoleMessage420 * @param {!Protocol.Network.RequestId} requestId421 */422 associateConsoleMessageWithRequest(consoleMessage, requestId) {423 const target = consoleMessage.target();424 const networkManager = target ? target.model(SDK.NetworkManager) : null;425 if (!networkManager)426 return;427 const request = this.requestByManagerAndId(networkManager, requestId);428 if (!request)429 return;430 consoleMessage[SDK.NetworkLog._requestSymbol] = request;431 const initiator = request.initiator();432 if (initiator) {433 consoleMessage.stackTrace = initiator.stack || undefined;434 if (initiator.url) {435 consoleMessage.url = initiator.url;436 consoleMessage.line = initiator.lineNumber || 0;437 }438 }439 }440 /**441 * @param {!SDK.ConsoleMessage} consoleMessage442 * @return {?SDK.NetworkRequest}443 */444 static requestForConsoleMessage(consoleMessage) {445 return consoleMessage[SDK.NetworkLog._requestSymbol] || null;446 }447};448SDK.NetworkLog.PageLoad = class {449 /**450 * @param {!SDK.NetworkRequest} mainRequest451 */452 constructor(mainRequest) {453 this.id = ++SDK.NetworkLog.PageLoad._lastIdentifier;454 this.url = mainRequest.url();455 this.startTime = mainRequest.startTime;456 /** @type {number} */457 this.loadTime;458 /** @type {number} */459 this.contentLoadTime;460 this.mainRequest = mainRequest;461 this._showDataSaverWarningIfNeeded();462 }463 async _showDataSaverWarningIfNeeded() {464 const manager = SDK.NetworkManager.forRequest(this.mainRequest);465 if (!manager)466 return;467 if (!this.mainRequest.finished)468 await this.mainRequest.once(SDK.NetworkRequest.Events.FinishedLoading);469 const saveDataHeader = this.mainRequest.requestHeaderValue('Save-Data');470 if (!SDK.NetworkLog.PageLoad._dataSaverMessageWasShown && saveDataHeader && saveDataHeader === 'on') {471 const message = Common.UIString(472 'Consider disabling %s while debugging. For more info see: %s', Common.UIString('Chrome Data Saver'),473 'https://support.google.com/chrome/?p=datasaver');474 manager.dispatchEventToListeners(475 SDK.NetworkManager.Events.MessageGenerated,476 {message: message, requestId: this.mainRequest.requestId(), warning: true});477 SDK.NetworkLog.PageLoad._dataSaverMessageWasShown = true;478 }479 }480 /**481 * @param {!SDK.NetworkRequest} request482 * @return {?SDK.NetworkLog.PageLoad}483 */484 static forRequest(request) {485 return request[SDK.NetworkLog.PageLoad._pageLoadForRequestSymbol] || null;486 }487 /**488 * @param {!SDK.NetworkRequest} request489 */490 bindRequest(request) {491 request[SDK.NetworkLog.PageLoad._pageLoadForRequestSymbol] = this;492 }493};494SDK.NetworkLog.PageLoad._lastIdentifier = 0;495SDK.NetworkLog.PageLoad._pageLoadForRequestSymbol = Symbol('PageLoadForRequest');496SDK.NetworkLog._requestSymbol = Symbol('_request');497SDK.NetworkLog.PageLoad._dataSaverMessageWasShown = false;498/** @typedef {!{initiators: !Set<!SDK.NetworkRequest>, initiated: !Set<!SDK.NetworkRequest>}} */499SDK.NetworkLog.InitiatorGraph;500SDK.NetworkLog.Events = {501 Reset: Symbol('Reset'),502 RequestAdded: Symbol('RequestAdded'),503 RequestUpdated: Symbol('RequestUpdated')504};505/** @typedef {!{type: !SDK.NetworkRequest.InitiatorType, url: string, lineNumber: number, columnNumber: number, scriptId: ?string, stack: ?Protocol.Runtime.StackTrace}} */506SDK.NetworkLog._InitiatorInfo;507SDK.NetworkLog._initiatorDataSymbol = Symbol('InitiatorData');508SDK.NetworkLog._events = Symbol('SDK.NetworkLog.events');509/** @type {!SDK.NetworkLog} */...

Full Screen

Full Screen

cfadca83-1a52-4d9d-82dd-b8d84e02492b.js

Source:cfadca83-1a52-4d9d-82dd-b8d84e02492b.js Github

copy

Full Screen

1"use strict";2cc._RF.push(module, 'cfadcqDGlJNnYLduNhOAkkr', 'NetWorkManager');3// resources/resources/modules/NetWorkManager.js4"use strict";5var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();6function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }7/**8 * Created by litengfei on 2018/1/18.9 */10var AutoReconnectWsRpcClient = require("AutoReconnectWsRpcClient");11var Users = require("Users");12var EventEmitter = require("EventEmitter");13var Handler = require('Handler');14var NetWorkManager = function () {15 function NetWorkManager() {16 _classCallCheck(this, NetWorkManager);17 }18 _createClass(NetWorkManager, null, [{19 key: "connectAndAuthToHall",20 value: function connectAndAuthToHall(account, pass, url) {21 //cb 2params baseinfo service22 if (NetWorkManager.g_HallService === null) {23 NetWorkManager.g_HallService = new AutoReconnectWsRpcClient();24 NetWorkManager.g_HallService.connect(url);25 cc.log('login');26 NetWorkManager.g_HallService.onClose(function () {27 //连接中断28 NetWorkManager.g_HallServiceIsLogin = false;29 NetWorkManager.events.emit("closeFromHall");30 NetWorkManager.connectAndAuthToHall(account, pass, url);31 });32 }33 NetWorkManager.g_HallService.onReady(function (service) {34 service.proxy.login(account, pass, function (data) {35 if (data.ok && data.suc) {36 NetWorkManager.g_HallServiceIsLogin = true;37 Users.account = account;38 Users.pass = pass;39 Users.nickName = data.info.nickname;40 Users.headUrl = data.info.headimgurl;41 Users.fangka = data.info.score;42 Users.sex = data.info.sex;43 Users.loginToHallData = data.info;44 cc.log('info: ' + data.info);45 NetWorkManager.events.emit("loginToHall", service);46 }47 });48 });49 }50 }, {51 key: "onConnectedToHall",52 value: function onConnectedToHall(cb) {53 //cb 1param service54 if (NetWorkManager.g_HallServiceIsLogin) {55 cb(NetWorkManager.g_HallService);56 return;57 }58 NetWorkManager.events.on("loginToHall", cb);59 cc.log('ceshi');60 }61 }, {62 key: "offConnectedToHall",63 value: function offConnectedToHall(cb) {64 NetWorkManager.events.off(cb);65 }66 }, {67 key: "onClosedFromHall",68 value: function onClosedFromHall(cb) {69 //cb 1param service70 NetWorkManager.events.on("closeFromHall", cb);71 }72 }, {73 key: "offClosedFromHall",74 value: function offClosedFromHall(cb) {75 NetWorkManager.events.off(cb);76 }77 }, {78 key: "clearHallService",79 value: function clearHallService() {80 //清理当前大厅的连接81 NetWorkManager.events = new EventEmitter();82 NetWorkManager.g_HallServiceIsLogin = false;83 if (NetWorkManager.g_HallService) NetWorkManager.g_HallService.clear();84 }85 }, {86 key: "connectAndAuthToGame",87 value: function connectAndAuthToGame(account, pass, url) {88 //cb 2params baseinfo service89 if (NetWorkManager.g_GameService === null) {90 NetWorkManager.g_GameService = new AutoReconnectWsRpcClient();91 NetWorkManager.g_GameService.addRpc(Handler.service);92 NetWorkManager.g_GameService.connect(url);93 NetWorkManager.g_GameService.onClose(function () {94 //连接中断95 NetWorkManager.g_GameServiceIsLogin = false;96 NetWorkManager.gameEvents.emit("closeFromGame");97 NetWorkManager.connectAndAuthToGame(account, pass, url);98 });99 }100 NetWorkManager.g_GameService.onReady(function (service) {101 service.proxy.login(account, pass, function (data) {102 if (data.ok && data.suc) {103 cc.log('登陆游戏服务器成功:');104 cc.log(data);105 NetWorkManager.g_GameServiceIsLogin = true;106 Users.account = account;107 Users.pass = pass;108 Users.nickName = data.info.nickname;109 Users.headUrl = data.info.headimgurl;110 Users.fangka = data.info.score;111 Users.sex = data.info.sex;112 Users.loginToGameData = data;113 NetWorkManager.gameEvents.emit("loginToGame", service);114 } else {115 if (data.codes.code == 1000) {116 NetWorkManager.connectAndAuthToHall(account, pass, Users.hallUrl);117 NetWorkManager.onConnectedToHall(function () {118 if (Users.loginToHallData.isInGame) {119 //跳转到游戏界面120 NetWorkManager.connectAndAuthToGame(Users.account, Users.pass, Users.loginToHallData.gameUrl);121 NetWorkManager.onConnectedToGame(function () {122 var loginData = Users.loginToGameData;123 if (loginData.isInGame) {124 cc.director.loadScene("game");125 } else {126 NetWorkManager.clearGameService();127 }128 });129 } else {130 cc.director.loadScene("hall");131 }132 });133 }134 }135 });136 });137 }138 }, {139 key: "onConnectedToGame",140 value: function onConnectedToGame(cb) {141 //cb 1param service142 if (NetWorkManager.g_GameServiceIsLogin) {143 cb(NetWorkManager.g_GameService);144 return;145 }146 NetWorkManager.gameEvents.on("loginToGame", cb);147 }148 }, {149 key: "offConnectedToGame",150 value: function offConnectedToGame(cb) {151 NetWorkManager.gameEvents.off(cb);152 }153 }, {154 key: "onClosedFromGame",155 value: function onClosedFromGame(cb) {156 //cb 1param service157 NetWorkManager.gameEvents.on("closeFromGame", cb);158 }159 }, {160 key: "offClosedFromGame",161 value: function offClosedFromGame(cb) {162 NetWorkManager.gameEvents.off(cb);163 }164 }, {165 key: "clearGameService",166 value: function clearGameService() {167 //清理当前大厅的连接168 NetWorkManager.gameEvents = new EventEmitter();169 NetWorkManager.g_GameServiceIsLogin = false;170 if (NetWorkManager.g_GameService) {171 NetWorkManager.g_GameService.clear();172 NetWorkManager.g_GameService = null;173 }174 }175 }]);176 return NetWorkManager;177}();178NetWorkManager.g_HallService = null;179NetWorkManager.g_HallServiceIsLogin = false;180NetWorkManager.events = new EventEmitter();181NetWorkManager.g_GameService = null;182NetWorkManager.g_GameServiceIsLogin = false;183NetWorkManager.gameEvents = new EventEmitter();184module.exports = NetWorkManager;...

Full Screen

Full Screen

device.js

Source:device.js Github

copy

Full Screen

1'use strict';2const DBus = require('dbus-as-promised');3const PLazy = require('p-lazy');4module.exports = NetworkManager => {5 class Device extends DBus.InterfaceWrapper {6 constructor(iface) {7 super(iface);8 9 Device.subInterfaces.forEach(name => {10 this[name] = PLazy.from(this._getSubInterface.bind(this, name));11 });12 }13 14 static connect(objPath) {15 return NetworkManager._getInterface(16 Device,17 objPath,18 'org.freedesktop.NetworkManager.Device');19 }20 21 static _addSubInterface(name, cls = DBus.InterfaceWrapper) {22 if (!Device.subInterfaces) {23 Device.subInterfaces = [];24 }25 26 Device.subInterfaces.push(name);27 Device[name] = class extends cls {28 static connect(objPath) {29 return NetworkManager._getInterface(30 Device[name],31 objPath,32 'org.freedesktop.NetworkManager.Device.' + name);33 }34 };35 }36 async _getSubInterface(name) {37 return Device[name].connect(this._iface.objectPath);38 }39 40 Reapply(connection, version_id = 0, ...flags) {41 return this._iface.Reapply(42 connection,43 version_id,44 NetworkManager.fromFlags(NetworkManager.enums.DeviceReapplyFlags, flags));45 }46 47 GetAppliedConnection(...flags) {48 return this._iface.GetAppliedConnection(49 NetworkManager.fromFlags(NetworkManager.enums.GetAppliedConnectionFlags, flags));50 }51 52 async GetCapabilities() {53 let caps = await this.getProperty('Capabilities');54 return NetworkManager.toFlags(NetworkManager.enums.DeviceCapabilities, caps);55 }56 57 async GetState() {58 let state = await this.getProperty('State');59 return NetworkManager.toEnum(NetworkManager.enums.DeviceState, state);60 }61 62 async GetStateReason() {63 let stateReason = await this.getProperty('StateReason');64 let result = {};65 for (let state in stateReason) {66 let reason = stateReason[state];67 68 result[NetworkManager.toEnum(NetworkManager.enums.DeviceState, state)]69 = NetworkManager.toEnum(NetworkManager.enums.DeviceStateReason, reason);70 }71 return result;72 }73 74 async GetDeviceType() {75 let devType = await this.getProperty('DeviceType');76 return NetworkManager.toEnum(NetworkManager.enums.DeviceType, devType);77 }78 79 async GetAvailableConnections() {80 let conns = await this.getProperty('AvailableConnections');81 return Promise.all(conns.map(NetworkManager.Connection.connect));82 }83 84 async GetMetered() {85 let metered = await this.getProperty('Metered');86 return NetworkManager.toEnum(NetworkManager.enums.Metered, metered);87 }88 89 async _interpretSignal(signal, args)90 {91 switch(signal)92 {93 case 'StateChanged':94 return [95 NetworkManager.toEnum(NetworkManager.enums.DeviceState, args[0]),96 NetworkManager.toEnum(NetworkManager.enums.DeviceState, args[1]),97 NetworkManager.toEnum(NetworkManager.enums.DeviceStateReason, args[2])98 ];99 100 default:101 return args;102 }103 }104 }105 // TODO: dynamically discover which of these apply to each particular device object,106 // using bus.introspect.107 Device._addSubInterface('Statistics');108 Device._addSubInterface('Adsl');109 Device._addSubInterface('Bluetooth', class extends DBus.InterfaceWrapper {110 async GetBtCapabilities() {111 let caps = await this.getProperty('BtCapabilities');112 return NetworkManager.toFlags(NetworkManager.enums.BluetoothCapabilities, caps);113 }114 });115 116 Device._addSubInterface('Bond', class extends DBus.InterfaceWrapper {117 async GetSlaves() {118 let slaves = await this.getProperty('Slaves');119 return Promise.all(slaves.map(NetworkManager.Device.connect));120 }121 });122 Device._addSubInterface('Bridge', class extends DBus.InterfaceWrapper {123 async GetSlaves() {124 let slaves = await this.getProperty('Slaves');125 return Promise.all(slaves.map(NetworkManager.Device.connect));126 }127 });128 Device._addSubInterface('Dummy');129 Device._addSubInterface('Generic');130 Device._addSubInterface('Infiniband');131 132 Device._addSubInterface('IPTunnel', class extends DBus.InterfaceWrapper {133 async GetParent() {134 return NetworkManager.Device.connect(await this.getProperty('Parent'));135 }136 });137 Device._addSubInterface('Macsec', class extends DBus.InterfaceWrapper {138 async GetParent() {139 return NetworkManager.Device.connect(await this.getProperty('Parent'));140 }141 });142 143 Device._addSubInterface('Macvlan', class extends DBus.InterfaceWrapper {144 async GetParent() {145 return NetworkManager.Device.connect(await this.getProperty('Parent'));146 }147 });148 149 Device._addSubInterface('Modem', class extends DBus.InterfaceWrapper {150 async GetModemCapabilities() {151 let caps = await this.getProperty('ModemCapabilities');152 return NetworkManager.toFlags(NetworkManager.enums.DeviceModemCapabilities, caps);153 }154 155 async GetCurrentCapabilities() {156 let caps = await this.getProperty('CurrentCapabilities');157 return NetworkManager.toFlags(NetworkManager.enums.DeviceModemCapabilities, caps);158 }159 });160 161 Device._addSubInterface('OlpcMesh', class extends DBus.InterfaceWrapper {162 async GetCompanion() {163 return NetworkManager.Device.connect(await this.getProperty('Companion'));164 }165 });166 167 Device._addSubInterface('Team', class extends DBus.InterfaceWrapper {168 async GetSlaves() {169 let slaves = await this.getProperty('Slaves');170 return Promise.all(slaves.map(NetworkManager.Device.connect));171 }172 });173 174 Device._addSubInterface('Tun');175 176 Device._addSubInterface('Veth', class extends DBus.InterfaceWrapper {177 async GetPeer() {178 return NetworkManager.Device.connect(await this.getProperty('Peer'));179 }180 });181 182 Device._addSubInterface('Vlan', class extends DBus.InterfaceWrapper {183 async GetParent() {184 return NetworkManager.Device.connect(await this.getProperty('Parent'));185 }186 });187 188 Device._addSubInterface('Vxlan', class extends DBus.InterfaceWrapper {189 async GetParent() {190 return NetworkManager.Device.connect(await this.getProperty('Parent'));191 }192 });193 194 Device._addSubInterface('WiMax');195 Device._addSubInterface('Wired');196 Device._addSubInterface('Wireless', class extends DBus.InterfaceWrapper {197 async GetMode() {198 let mode = await this.getProperty('Mode');199 return NetworkManager.toEnum(NetworkManager.enums.NM80211Mode, mode);200 }201 202 async GetAccessPoints() {203 let aps = await this._iface.GetAccessPoints();204 return Promise.all(aps.map(NetworkManager.AccessPoint.connect));205 }206 207 async GetAllAccessPoints() {208 let aps = await this._iface.GetAllAccessPoints();209 return Promise.all(aps.map(NetworkManager.AccessPoint.connect));210 }211 212 async GetActiveAccessPoint() {213 return NetworkManager.AccessPoint.connect(await this.getProperty('ActiveAccessPoint'));214 }215 216 async GetWirelessCapabilities() {217 let caps = await this.getProperty('WirelessCapabilities');218 return NetworkManager.toFlags(NetworkManager.enums.DeviceWifiCapabilities, caps);219 }220 221 async _interpretSignal(signal, args) {222 switch(signal) {223 case 'AccessPointAdded':224 // case 'AccessPointRemoved':225 return [NetworkManager.AccessPoint.connect(args[0])];226 227 default:228 return args;229 }230 }231 });232 233 Device._addSubInterface('PPP', class extends DBus.InterfaceWrapper {234 static connect(objPath) {235 return NetworkManager._getInterface(236 Device.PPP,237 objPath,238 'org.freedesktop.NetworkManager.PPP');239 }240 });241 return Device;...

Full Screen

Full Screen

NetWorkManager.js

Source:NetWorkManager.js Github

copy

Full Screen

1/**2 * Created by litengfei on 2018/1/18.3 */4var AutoReconnectWsRpcClient = require("AutoReconnectWsRpcClient");5var Users = require("Users");6var EventEmitter = require("EventEmitter");7var Handler = require('Handler');8class NetWorkManager{9 static connectAndAuthToHall(account,pass,url) {//cb 2params baseinfo service10 if (NetWorkManager.g_HallService === null) {11 NetWorkManager.g_HallService = new AutoReconnectWsRpcClient();12 NetWorkManager.g_HallService.connect(url);13 cc.log('login');14 NetWorkManager.g_HallService.onClose(function () {15 //连接中断16 NetWorkManager.g_HallServiceIsLogin = false;17 NetWorkManager.events.emit("closeFromHall");18 NetWorkManager.connectAndAuthToHall(account,pass,url);19 })20 }21 NetWorkManager.g_HallService.onReady(function (service) {22 service.proxy.login(account,pass,function (data) {23 if(data.ok&&data.suc){24 NetWorkManager.g_HallServiceIsLogin = true;25 Users.account = account;26 Users.pass = pass;27 Users.nickName = data.info.nickname;28 Users.headUrl = data.info.headimgurl;29 Users.fangka = data.info.score;30 Users.sex = data.info.sex;31 Users.loginToHallData = data.info;32 cc.log('info: '+data.info);33 NetWorkManager.events.emit("loginToHall",service);34 }35 })36 })37 }38 static onConnectedToHall(cb){//cb 1param service39 if(NetWorkManager.g_HallServiceIsLogin){40 cb(NetWorkManager.g_HallService);41 return;42 }43 NetWorkManager.events.on("loginToHall",cb);44 cc.log('ceshi');45 }46 static offConnectedToHall(cb){47 NetWorkManager.events.off(cb);48 }49 static onClosedFromHall(cb){//cb 1param service50 NetWorkManager.events.on("closeFromHall",cb);51 }52 static offClosedFromHall(cb){53 NetWorkManager.events.off(cb);54 }55 static clearHallService() {//清理当前大厅的连接56 NetWorkManager.events = new EventEmitter();57 NetWorkManager.g_HallServiceIsLogin = false;58 if (NetWorkManager.g_HallService) NetWorkManager.g_HallService.clear();59 }60 static connectAndAuthToGame(account,pass,url) {//cb 2params baseinfo service61 if (NetWorkManager.g_GameService === null) {62 NetWorkManager.g_GameService = new AutoReconnectWsRpcClient();63 NetWorkManager.g_GameService.addRpc(Handler.service); 64 NetWorkManager.g_GameService.connect(url);65 NetWorkManager.g_GameService.onClose(function () {66 //连接中断67 NetWorkManager.g_GameServiceIsLogin = false;68 NetWorkManager.gameEvents.emit("closeFromGame");69 NetWorkManager.connectAndAuthToGame(account,pass,url);70 })71 }72 NetWorkManager.g_GameService.onReady(function (service) {73 service.proxy.login(account,pass,function (data) {74 if(data.ok&&data.suc){75 cc.log('登陆游戏服务器成功:');76 cc.log(data);77 NetWorkManager.g_GameServiceIsLogin = true;78 Users.account = account;79 Users.pass = pass;80 Users.nickName = data.info.nickname;81 Users.headUrl = data.info.headimgurl;82 Users.fangka = data.info.score;83 Users.sex = data.info.sex;84 Users.loginToGameData = data;85 NetWorkManager.gameEvents.emit("loginToGame",service);86 }else {87 if(data.codes.code == 1000){88 NetWorkManager.connectAndAuthToHall(account,pass,Users.hallUrl);89 NetWorkManager.onConnectedToHall(function () {90 if(Users.loginToHallData.isInGame){//跳转到游戏界面91 NetWorkManager.connectAndAuthToGame(Users.account,Users.pass,Users.loginToHallData.gameUrl);92 NetWorkManager.onConnectedToGame(function () {93 var loginData = Users.loginToGameData;94 if(loginData.isInGame){95 cc.director.loadScene("game");96 }else{97 NetWorkManager.clearGameService();98 }99 });100 }else{101 cc.director.loadScene("hall");102 }103 });104 }105 }106 });107 });108 }109 static onConnectedToGame(cb){//cb 1param service110 if(NetWorkManager.g_GameServiceIsLogin){111 cb(NetWorkManager.g_GameService);112 return;113 }114 NetWorkManager.gameEvents.on("loginToGame",cb);115 }116 static offConnectedToGame(cb){117 NetWorkManager.gameEvents.off(cb);118 }119 static onClosedFromGame(cb){//cb 1param service120 NetWorkManager.gameEvents.on("closeFromGame",cb);121 }122 static offClosedFromGame(cb){123 NetWorkManager.gameEvents.off(cb);124 }125 static clearGameService() {//清理当前大厅的连接126 NetWorkManager.gameEvents = new EventEmitter();127 NetWorkManager.g_GameServiceIsLogin = false;128 if (NetWorkManager.g_GameService){129 NetWorkManager.g_GameService.clear();130 NetWorkManager.g_GameService = null;131 }132 } 133}134NetWorkManager.g_HallService = null;135NetWorkManager.g_HallServiceIsLogin = false;136NetWorkManager.events = new EventEmitter();137NetWorkManager.g_GameService = null;138NetWorkManager.g_GameServiceIsLogin = false;139NetWorkManager.gameEvents = new EventEmitter();...

Full Screen

Full Screen

network-manager.test.js

Source:network-manager.test.js Github

copy

Full Screen

1'use strict'2const chai = require('chai')3chai.should()4const expect = chai.expect5const NetworkManager = require('../lib/network-manager')6const Connection = require('../lib/connection')7const Connections = require('../lib/connections')8const Device = require('../lib/device')9const Devices = require('../lib/devices')10const Wireless = require('../lib/wireless')11describe ('NetworkManager', () => {12 describe ('Module import', () => {13 it ('Should provide direct submodule access', () => {14 expect(() => {15 const NetworkManager = require('../lib/network-manager')16 const nm = new NetworkManager()17 const connections = new NetworkManager.Connections(nm.dbusType, nm.dbusConfig)18 expect(connections).to.be.instanceOf(Connections)19 const connection = new NetworkManager.Connection(nm.dbusType, nm.dbusConfig, { })20 expect(connection).to.be.instanceOf(Connection)21 const devices = new NetworkManager.Devices(nm.dbusType, nm.dbusConfig)22 expect(devices).to.be.instanceOf(Devices)23 const device = new NetworkManager.Device(nm.dbusType, nm.dbusConfig)24 expect(device).to.be.instanceOf(Device)25 const wireless = new NetworkManager.Wireless(nm.dbusType, nm.dbusConfig)26 expect(wireless).to.be.instanceOf(Wireless)27 const { mergeDbusSettings, maskDbusSettings, dbusSettingsVariantTypes } = NetworkManager.Utils.DbusSettings28 expect(mergeDbusSettings.name).to.equal('mergeDbusSettings')29 expect(maskDbusSettings.name).to.equal('maskDbusSettings')30 expect(dbusSettingsVariantTypes).to.be.instanceOf(Object)31 const { escapeRegExString } = NetworkManager.Utils.Strings32 expect(escapeRegExString.name).to.equal('escapeRegExString')33 }).to.not.throw()34 })35 it ('Should provide module destructuring', () => {36 expect(() => {37 const { NetworkManager, Connection, Device, Devices, Wireless } = require('../lib/network-manager')38 const nm = new NetworkManager()39 new Connections(nm.dbusType, nm.dbusConfig)40 new Connection(nm.dbusType, nm.dbusConfig, { })41 new Devices(nm.dbusType, nm.dbusConfig)42 new Device(nm.dbusType, nm.dbusConfig)43 new Wireless(nm.dbusType, nm.dbusConfig)44 }).to.not.throw()45 })46 })47 describe ('Sub-module access', () => {48 describe ('nm.connections', () => {49 it ('Should provide access to an instance of Connections', () => {50 const nm = new NetworkManager()51 const connections = nm.connections52 expect(connections).to.be.instanceOf(Connections)53 })54 })55 describe ('nm.devices', () => {56 it ('Should provide access to an instance of Devices', () => {57 const nm = new NetworkManager()58 const devices = nm.devices59 expect(devices).to.be.instanceOf(Devices)60 })61 })62 describe ('nm.wireless', () => {63 it ('Should provide access to an instance of Wireless', () => {64 const nm = new NetworkManager()65 const wireless = nm.wireless66 expect(wireless).to.be.instanceOf(Wireless)67 })68 })69 })70})71// describe ('Setting the bus (system bus or session bus) via the constructor', () => {72// it ('Should default to session bus', () => {73// const nm = new NetworkManager()74// // TODO: how can this be tested?75// })76// it ('Should create the bus passed as first parameter', () => {77// const nmSession = new NetworkManager('session')78// // TODO: how can this be tested?79// const nmSystem = new NetworkManager('system')80// // TODO: how can this be tested?81// })82// it ('Should throw an error if the bus type is not supported', () => {83// expect (() => {84// new NetworkManager('unsupported-bus-type')85// }).to.throw(Error)86// })87// })88// describe ('Device factory NetworkManager.getDevice()', () => {89// it ('Should return an object of type \'Device\'', () => {90// const device = NetworkManager.getDevice()91// })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const networkManager = await page.target().createCDPSession();2await networkManager.send('Network.enable');3await networkManager.send('Network.emulateNetworkConditions', {4});5const networkManager = await page.target().createCDPSession();6await networkManager.send('Network.enable');7await networkManager.send('Network.emulateNetworkConditions', {8});9await page.emulateNetworkConditions({10});11await page.emulate({12 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',13 viewport: {14 }15});16await page.emulateMedia({17});

Full Screen

Using AI Code Generation

copy

Full Screen

1const networkManager = await page.target().createCDPSession();2await networkManager.send('Network.enable');3await networkManager.send('Network.setCacheDisabled', { cacheDisabled: true });4await networkManager.send('Network.clearBrowserCache');5await networkManager.send('Network.clearBrowserCookies');6await networkManager.send('Network.setCookies', { cookies: [] });7await networkManager.send('Network.emulateNetworkConditions', {8});9const networkManager = await page.target().createCDPSession();10await networkManager.send('Network.enable');11await networkManager.send('Network.setCacheDisabled', { cacheDisabled: true });12await networkManager.send('Network.clearBrowserCache');13await networkManager.send('Network.clearBrowserCookies');14await networkManager.send('Network.setCookies', { cookies: [] });15await networkManager.send('Network.emulateNetworkConditions', {16});17const puppeteer = require('puppeteer');18const test = async () => {19 const browser = await puppeteer.launch({20 });21 const page = await browser.newPage();22 await page.waitForSelector('#username');23 await page.type('#username', 'tomsmith');24 await page.type('#password', 'SuperSecretPassword!');25 await page.click('.fa-sign-in');26 await page.waitForSelector('.flash.success');27 await page.screenshot({ path: 'login.png' });28 await browser.close();29};30test();31const puppeteer = require('puppeteer');32const test = async () => {33 const browser = await puppeteer.launch({34 });35 const page = await browser.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const networkManager = await page.target().createCDPSession();2await networkManager.send('Network.enable');3networkManager.on('Network.responseReceived', params => {4 console.log('Network.responseReceived', params);5});6await networkManager.send('Network.disable');7await page.on('request', request => {8 console.log('Page.request', request);9});10await page.on('response', response => {11 console.log('Page.response', response);12});13console.log('Page.goto', response);14await browser.on('targetcreated', target => {15 console.log('Browser.targetcreated', target);16});17await browser.on('targetchanged', target => {18 console.log('Browser.targetchanged', target);19});20await browser.on('targetdestroyed', target => {21 console.log('Browser.targetdestroyed', target);22});23const pages = await browser.pages();24console.log('Browser.pages', pages);25await browserContext.on('targetcreated', target => {26 console.log('BrowserContext.targetcreated', target);27});28await browserContext.on('targetchanged', target => {29 console.log('BrowserContext.targetchanged', target);30});31await browserContext.on('targetdestroyed', target => {32 console.log('BrowserContext.targetdestroyed', target);33});34const pages = await browserContext.pages();35console.log('BrowserContext.pages', pages);36await frame.on('request', request => {37 console.log('Frame.request', request);38});39await frame.on('response', response => {40 console.log('Frame.response', response);41});42console.log('Frame.goto', response);43await worker.on('error', error => {44 console.log('Worker.error', error);45});46await worker.on('exit', exitCode => {47 console.log('Worker.exit', exitCode);48});49const response = await worker.evaluate('1 + 2');50console.log('Worker.evaluate', response);

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const networkManager = require('./networkManager')3const { NetworkManager } = require('puppeteer/lib/cjs/puppeteer/common/NetworkManager');4(async () => {5 const browser = await puppeteer.launch({headless: false});6 const page = await browser.newPage();7 const client = await page.target().createCDPSession();8 const networkManager = new NetworkManager(client, page);9 await networkManager.setCacheDisabled(true);10 await browser.close();11})();12const {NetworkManager} = require('puppeteer/lib/cjs/puppeteer/common/NetworkManager');13NetworkManager.prototype.setCacheDisabled = function (disabled) {14 return this._client.send('Network.setCacheDisabled', {cacheDisabled: disabled});15};16class NetworkManager {17 constructor(client, page) {18 this._client = client;19 this._page = page;20 this._extraHTTPHeaders = {};21 this._offline = false;22 }23 setCacheDisabled(disabled) {24 return this._client.send('Network.setCacheDisabled', { cacheDisabled: disabled });25 }26}27class NetworkManager {28 constructor(client, page) {29 this._client = client;30 this._page = page;31 this._extraHTTPHeaders = {};32 this._offline = false;33 }34 async setCacheDisabled(disabled) {35 return this._client.send('Network.setCacheDisabled', { cacheDisabled: disabled });36 }37}38class NetworkManager {39 constructor(client, page) {40 this._client = client;41 this._page = page;42 this._extraHTTPHeaders = {};43 this._offline = false;44 }45 async setCacheDisabled(disabled) {46 return this._client.send('Network.setCacheDisabled', { cacheDisabled: disabled });47 }

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const networkManager = require('puppeteer/lib/NetworkManager');3const {helper} = require('puppeteer/lib/helper');4const {assert} = require('chai');5const {expect} = require('chai');6const {should} = require('chai');7const {assertEqual} = require('chai');8(async() => {9const browser = await puppeteer.launch({headless: false});10const page = await browser.newPage();11await page.waitFor(5000);12await page.screenshot({path: 'google.png'});13await browser.close();14})();15networkManager.requestWillBeSent = function(request) {16 const id = request.requestId;17 const url = request.url;18 const method = request.method;19 const postData = request.postData;20 const headers = request.headers;21 const redirectChain = request.redirectChain;22 const isNavigationRequest = request.isNavigationRequest;23 const type = request.type;24 const timestamp = request.timestamp;25 const frameId = request.frameId;26 const loaderId = request.loaderId;27 const documentURL = request.documentURL;28 const resourceType = request.resourceType;29 const requestWillBeSentExtraInfo = request.requestWillBeSentExtraInfo;30 const response = request.response;31 const frame = request.frame;32 const resourceSize = request.resourceSize;33 const transferSize = request.transferSize;34 const encodedDataLength = request.encodedDataLength;35 const fromDiskCache = request.fromDiskCache;36 const fromServiceWorker = request.fromServiceWorker;37 const fromPrefetchCache = request.fromPrefetchCache;38 const headersText = request.headersText;39 const protocol = request.protocol;40 const remoteAddress = request.remoteAddress;41 const remotePort = request.remotePort;42 const securityState = request.securityState;43 const securityDetails = request.securityDetails;44 const connectionReused = request.connectionReused;45 const connectionId = request.connectionId;46 const hasUserGesture = request.hasUserGesture;47 const initiator = request.initiator;48 const mixedContentType = request.mixedContentType;49 const isLinkPreload = request.isLinkPreload;

Full Screen

Using AI Code Generation

copy

Full Screen

1const networkManager = page.browser().networkManager();2networkManager.setCacheDisabled(true);3await page.setCacheEnabled(false);4const puppeteer = require("puppeteer");5(async () => {6 const browser = await puppeteer.launch({ headless: false });7 const page = await browser.newPage();8 await page.screenshot({ path: "example.png" });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.screenshot({ path: "example.png" });16 await browser.close();

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer 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