From 69ebf017ffcc157fb6b9407d1f9673412099968b Mon Sep 17 00:00:00 2001 From: Beaudan Date: Wed, 6 Feb 2019 09:45:11 +1100 Subject: [PATCH] Reworked loki_p2p_api to not use the window object, which means it needs to be instantiated after the storage is ready so that your pubkey can be passed in to the constructor. This makes it more modular and allows for easier testing --- js/background.js | 7 +++++++ js/modules/loki_p2p_api.js | 19 +++++++++++++------ preload.js | 4 +--- 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/js/background.js b/js/background.js index 50ff93c31..b25fc5d41 100644 --- a/js/background.js +++ b/js/background.js @@ -219,6 +219,13 @@ return; } first = false; + window.lokiP2pAPI = new window.LokiP2pAPI( + textsecure.storage.user.getNumber() + ); + window.lokiP2pAPI.on( + 'pingContact', + window.libloki.api.sendOnlineBroadcastMessage + ); // These make key operations available to IPC handlers created in preload.js window.Events = { diff --git a/js/modules/loki_p2p_api.js b/js/modules/loki_p2p_api.js index 6fc18f10d..f8d9563d9 100644 --- a/js/modules/loki_p2p_api.js +++ b/js/modules/loki_p2p_api.js @@ -1,16 +1,23 @@ -/* global setTimeout, clearTimeout, window */ +/* global setTimeout, clearTimeout */ const EventEmitter = require('events'); class LokiP2pAPI extends EventEmitter { - constructor() { + constructor(ourKey) { super(); this.contactP2pDetails = {}; + this.ourKey = ourKey; } - updateContactP2pDetails(pubKey, address, port, fromP2p = false) { + reset() { + Object.keys(this.contactP2pDetails).forEach(key => { + clearTimeout(this.contactP2pDetails[key].pingTimer); + delete this.contactP2pDetails[key]; + }); + } + + updateContactP2pDetails(pubKey, address, port, isOnline = false) { // Stagger the timers so the friends don't ping each other at the same time - this.ourKey = this.ourKey || window.textsecure.storage.user.getNumber(); const timerDuration = pubKey < this.ourKey ? 60 * 1000 // 1 minute @@ -28,7 +35,7 @@ class LokiP2pAPI extends EventEmitter { pingTimer: null, }; - if (fromP2p) { + if (isOnline) { this.setContactOnline(pubKey); return; } @@ -73,7 +80,7 @@ class LokiP2pAPI extends EventEmitter { if (!this.contactP2pDetails[pubKey]) { return; } - window.libloki.api.sendOnlineBroadcastMessage(pubKey, true); + this.emit('pingContact', pubKey, true); } } diff --git a/preload.js b/preload.js index fb3dc298a..1e2fd0468 100644 --- a/preload.js +++ b/preload.js @@ -276,9 +276,7 @@ window.LokiSnodeAPI = new LokiSnodeAPI({ swarmServerPort: config.swarmServerPort, }); -const LokiP2pAPI = require('./js/modules/loki_p2p_api'); - -window.lokiP2pAPI = new LokiP2pAPI(); +window.LokiP2pAPI = require('./js/modules/loki_p2p_api'); const LokiMessageAPI = require('./js/modules/loki_message_api');