aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/socket.js
blob: 757fd4ee53b2c5a8419a311bcc58774324e9944c (plain) (blame)
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
88
89
90
91
92
93
94
95
96
97
98
99
import { get } from 'svelte/store';
import { invoices, invoice, request, newPayment, last, rate, txns, user } from '$lib/store';
import { success, sat } from '$lib/utils';
import { env } from '$env/dynamic/public';
import { invalidate } from '$app/navigation';

let socket, token;

export const auth = () => token && send('login', token) && send('heartbeat');

export const send = (type, data) => {
	socket?.readyState === 1 && socket.send(JSON.stringify({ type, data }));
	return true;
};

export const messages = (data) => ({
	id() {
		last.set(Date.now());
	},

	invoice() {
		invoice.set(data);
	},

	rate() {
		rate.set(data);
	},

	request() {
		request.set(data);
		invalidate('app:invoice');
	},

	async payment() {
		let { amount, invoice } = data;

		if (invoice) invalidate('app:invoice');
		if (get(user)?.account_id !== data.account_id) return;

		let payments = get(txns);
		let i = payments.findIndex((p) => p.id === data.id);
		if (~i) (payments[i] = data), txns.set(payments);
		else newPayment.set(true);

		invalidate((url) => url.pathname === '/payments');

		if (amount > 0) {
			success(`${data.confirmed ? 'Received' : 'Detected'} ${sat(amount)}!`);
		} else {
			success(`Sent ${sat(amount)}!`);
		}
	},

	connected: auth
});

const initialReconnectDelay = 1000;
const maxReconnectDelay = 16000;

let currentReconnectDelay = initialReconnectDelay;

export function connect(t) {
	token = t;

	if (socket) return auth();

  console.log("ENV", env.PUBLIC_SOCKET);
	socket = new WebSocket(env.PUBLIC_SOCKET);
	socket.addEventListener('open', onWebsocketOpen);
	socket.addEventListener('close', onWebsocketClose);
	socket.addEventListener('message', onWebsocketMessage);
}

export function close() {
	if (socket) socket.close();
}

function onWebsocketMessage(msg) {
	let { type, data } = JSON.parse(msg.data);
	messages(data)[type] && messages(data)[type]();
}

function onWebsocketOpen() {
	currentReconnectDelay = initialReconnectDelay;
}

function onWebsocketClose() {
	socket = null;
	setTimeout(() => {
		reconnectToWebsocket();
	}, currentReconnectDelay + Math.floor(Math.random() * 3000));
}

function reconnectToWebsocket() {
	if (currentReconnectDelay < maxReconnectDelay) {
		currentReconnectDelay *= 2;
	}
	connect();
}