Created
April 30, 2018 20:19
-
-
Save cuylerstuwe/3b5c664709dd46f41ac2d4ad740bf02b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var PandaCrazy = (function createPandaCrazy() { | |
| let _lastSentPingTime; | |
| let _lastReceivedPongTime; | |
| let _onlineSinceLastPing; | |
| let _pcListener; | |
| const MAX_WAIT_FOR_PANDA_CRAZY_RESPONSE_MS = 1000; | |
| function ping() { | |
| _lastSentPingTime = Date.now(); | |
| localStorage.setItem("JR_message_ping_pandacrazy", `{"theTarget": "${Math.random()}"}`); | |
| } | |
| function hasIndicatedOnlineSinceLastPing() { | |
| if(_lastSentPingTime !== undefined && _lastReceivedPongTime !== undefined) { | |
| return _lastReceivedPongTime >= _lastSentPingTime; | |
| } | |
| else { | |
| return undefined; | |
| } | |
| } | |
| function online() { | |
| function respondToStorage(resolve, reject, e) { | |
| if(e.key.includes("JR_message_pong") && Boolean(e.newValue)) { | |
| _lastReceivedPongTime = Date.now(); | |
| let pongData = JSON.parse(e.newValue); | |
| let lag = Number(pongData.time) - Number(_lastReceivedPongTime); | |
| if(hasIndicatedOnlineSinceLastPing()) { | |
| resolve("online"); | |
| } | |
| } | |
| } | |
| let isOnlinePromise = new Promise((resolve, reject) => { | |
| setTimeout(() => {reject("timeout");}, MAX_WAIT_FOR_PANDA_CRAZY_RESPONSE_MS); | |
| if(_pcListener) {window.removeEventListener("storage", _pcListener);} | |
| _pcListener = respondToStorage.bind(window, resolve, reject); | |
| window.addEventListener("storage", _pcListener); | |
| }); | |
| ping(); | |
| return isOnlinePromise; | |
| } | |
| function addJob(gid, once, metadata) { | |
| let commandString = once ? "addOnceJob" : "addJob"; | |
| localStorage.setItem("JR_message_pandacrazy", JSON.stringify({ | |
| time: Date.now(), | |
| command: commandString, | |
| data: { | |
| groupId: gid, | |
| title: (metadata ? metadata.hitTitle || metadata.title : undefined), | |
| requesterName: (metadata ? metadata.requesterName : undefined), | |
| requesterId: (metadata ? metadata.requesterID || metadata.requesterId || metadata.rid : undefined), | |
| pay: (metadata ? metadata.hitValue || metadata.pay : undefined), | |
| duration: (metadata ? metadata.duration : undefined), | |
| hitsAvailable: (metadata ? metadata.hitsAvailable : undefined) | |
| } | |
| })); | |
| } | |
| function startJob(gid) { | |
| localStorage.setItem("JR_message_pandacrazy", JSON.stringify({ | |
| time: Date.now(), | |
| command: "startcollect", | |
| data: { | |
| groupId: gid | |
| } | |
| })); | |
| } | |
| return { | |
| addJob, | |
| startJob, | |
| ping, | |
| online | |
| }; | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment