-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlanyard.js
87 lines (71 loc) · 2.65 KB
/
lanyard.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"use strict";
const CONSTANTS = {
API_URL: "https://api.lanyard.rest/v1",
WEBSOCKET_URL: "wss://api.lanyard.rest/socket",
HEARTBEAT_PERIOD: 1000 * 30
}
async function lanyard(opts) {
if (!opts) throw new Error("Specify an options object");
if (!opts.userId) throw new Error("Specify a user ID");
if (opts.socket) {
if (!opts.onPresenceUpdate) throw new Error("Specify onPresenceUpdate callback");
const supportsWebSocket = "WebSocket" in window || "MozWebSocket" in window;
if (!supportsWebSocket) throw new Error( "Browser doesn't support WebSocket connections.",);
const socket = new WebSocket(CONSTANTS.WEBSOCKET_URL);
const subscription = typeof opts.userId == "string" ? "subscribe_to_id" : "subscribe_to_ids"
let heartbeat = null
socket.addEventListener("open", () => {
socket.send(
JSON.stringify({
op: 2,
d: {
[subscription]: opts.userId,
},
}),
);
heartbeat = setInterval(() => {
socket.send(
JSON.stringify({
op: 3,
}),
);
}, CONSTANTS.HEARTBEAT_PERIOD);
});
socket.addEventListener("message", ({ data }) => {
const { t, d } = JSON.parse(data)
if (t === "INIT_STATE" || t === "PRESENCE_UPDATE") {
opts.onPresenceUpdate(d)
}
});
socket.onclose = (event) => {
try {
console.log("Socket closed")
clearInterval(heartbeat)
setTimeout(() => {
console.log("Trying to reconnect")
lanyard(opts)
}, 3000)
} catch(err) {
console.log("Socket closed")
}
console.log(event)
};
return socket;
} else {
if (typeof opts.userId == "string") {
const res = await fetch(`${CONSTANTS.API_URL}/users/${opts.userId}`);
const body = await res.json();
if (!body.success) throw new Error(body.error?.message || "An invalid error occured");
return body.data;
} else {
const val = [];
for (const userId of opts.userId) {
const res = await fetch(`${CONSTANTS.API_URL}/users/${userId}`);
const body = await res.json();
if (!body.success) throw new Error(body.error?.message || "An invalid error occured");
val.push(body.data)
}
return val;
}
}
}