File size: 2,380 Bytes
2f48928
 
 
 
 
 
 
 
 
 
4498c94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f48928
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'use client';

import { io, Socket } from 'socket.io-client';

let socket: Socket | null = null;

export function getSocket(): Socket {
  if (!socket) {
    socket = io({ path: '/socket.io', autoConnect: true, reconnection: true });

    // if the access token expired while idle, the reconnect handshake is rejected —
    // refresh the session and try again so realtime never silently dies
    let refreshingAuth = false;
    socket.on('connect_error', async (err) => {
      if (refreshingAuth || !/unauthorized/i.test(err.message)) return;
      refreshingAuth = true;
      try {
        const res = await fetch('/api/auth/refresh', { method: 'POST' });
        if (res.ok) socket?.connect();
      } catch { /* next reconnect attempt will retry */ }
      finally {
        setTimeout(() => { refreshingAuth = false; }, 3000);
      }
    });

    // away/active presence based on tab visibility + idle
    let idleTimer: ReturnType<typeof setTimeout> | null = null;
    const setAway = () => socket?.emit('presence:set', 'away');
    const setActive = () => {
      socket?.emit('presence:set', 'online');
      if (idleTimer) clearTimeout(idleTimer);
      idleTimer = setTimeout(setAway, 10 * 60 * 1000); // 10 min idle → away
    };
    if (typeof document !== 'undefined') {
      document.addEventListener('visibilitychange', () => (document.hidden ? setAway() : setActive()));
      ['mousemove', 'keydown', 'click'].forEach((ev) =>
        document.addEventListener(ev, throttle(setActive, 30_000), { passive: true }),
      );
      setActive();
    }
  }
  return socket;
}

export function disconnectSocket() {
  socket?.disconnect();
  socket = null;
}

function throttle<T extends (...args: never[]) => void>(fn: T, ms: number): T {
  let last = 0;
  return ((...args: never[]) => {
    const now = Date.now();
    if (now - last > ms) {
      last = now;
      fn(...args);
    }
  }) as T;
}

/** Browser push notification (Chrome Notification API) when tab is unfocused. */
export function maybeDesktopNotify(title: string, body: string) {
  if (typeof window === 'undefined' || !('Notification' in window)) return;
  if (!document.hidden) return;
  if (Notification.permission === 'granted') {
    new Notification(title, { body, icon: '/favicon.ico' });
  } else if (Notification.permission === 'default') {
    Notification.requestPermission();
  }
}