2026-05-28 19:28:52 -04:00
|
|
|
import { useEffect, useRef } from 'react';
|
2026-10-12 12:35:26 -04:00
|
|
|
import { SetPresence } from 'matrix-js-sdk';
|
2026-10-19 01:04:27 -04:00
|
|
|
import { PresenceDeduper, PresenceWrite, writePresence } from '../utils/presenceWrite';
|
2026-05-28 19:28:52 -04:00
|
|
|
import { useMatrixClient } from './useMatrixClient';
|
2026-09-24 11:50:13 -04:00
|
|
|
import { getLastLocalStatusWrite, pickHeartbeatStatus } from '../utils/ownStatusSync';
|
2026-05-28 19:28:52 -04:00
|
|
|
import { useSetting } from '../state/hooks/settings';
|
|
|
|
|
import { settingsAtom } from '../state/settings';
|
2026-10-19 01:04:27 -04:00
|
|
|
import {
|
|
|
|
|
BUSY_PRESENCE,
|
|
|
|
|
BUSY_PRESENCE_FEATURE,
|
|
|
|
|
isBusyPresenceSupported,
|
|
|
|
|
setBusyPresenceSupported,
|
|
|
|
|
} from '../utils/busyPresence';
|
2026-05-28 19:28:52 -04:00
|
|
|
|
2026-05-30 23:29:29 -04:00
|
|
|
const IDLE_TIMEOUT_MS = 10 * 60 * 1000;
|
|
|
|
|
const ACTIVITY_THROTTLE_MS = 1000;
|
2026-05-28 19:28:52 -04:00
|
|
|
|
2026-07-02 21:40:07 -04:00
|
|
|
export type PresenceSetting = 'auto' | 'online' | 'idle' | 'dnd' | 'invisible';
|
2026-10-19 01:04:27 -04:00
|
|
|
export type PresenceState = 'online' | 'unavailable' | 'offline' | typeof BUSY_PRESENCE;
|
2026-07-02 21:40:07 -04:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Single source of truth for mapping the user's presence preference to the
|
2026-10-19 01:04:27 -04:00
|
|
|
* Matrix presence value: auto/online → 'online', idle → 'unavailable', dnd →
|
|
|
|
|
* MSC3026 busy (or 'unavailable' where the server lacks it),
|
2026-07-02 21:40:07 -04:00
|
|
|
* invisible (or the hidePresence override) → 'offline'. Shared with the Profile
|
|
|
|
|
* status writer so setting/clearing a status message never overrides the user's
|
|
|
|
|
* chosen presence (e.g. outing an Invisible user as online).
|
|
|
|
|
*/
|
|
|
|
|
export function presenceStateFromSetting(
|
|
|
|
|
presenceStatus: PresenceSetting,
|
|
|
|
|
hidePresence: boolean,
|
|
|
|
|
): PresenceState {
|
|
|
|
|
if (hidePresence || presenceStatus === 'invisible') return 'offline';
|
2026-10-19 01:04:27 -04:00
|
|
|
// [Gitea #283] DND is MSC3026 busy where the server supports it, so status
|
|
|
|
|
// writes (save / clear / auto-clear) don't downgrade it to "unavailable".
|
|
|
|
|
if (presenceStatus === 'dnd') return isBusyPresenceSupported() ? BUSY_PRESENCE : 'unavailable';
|
|
|
|
|
if (presenceStatus === 'idle') return 'unavailable';
|
2026-07-02 21:40:07 -04:00
|
|
|
return 'online';
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-28 19:28:52 -04:00
|
|
|
export function usePresenceUpdater() {
|
|
|
|
|
const mx = useMatrixClient();
|
|
|
|
|
const [hidePresence] = useSetting(settingsAtom, 'hidePresence');
|
2026-05-30 23:29:29 -04:00
|
|
|
const [presenceStatus] = useSetting(settingsAtom, 'presenceStatus');
|
2026-05-28 19:28:52 -04:00
|
|
|
|
|
|
|
|
const idleTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
|
|
|
|
const isIdleRef = useRef(false);
|
|
|
|
|
const lastActivityRef = useRef(0);
|
2026-09-19 17:41:09 -04:00
|
|
|
const deduperRef = useRef(new PresenceDeduper());
|
2026-05-28 19:28:52 -04:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
2026-06-10 21:31:58 -04:00
|
|
|
const userId = mx.getUserId();
|
2026-09-19 17:41:09 -04:00
|
|
|
const deduper = deduperRef.current;
|
|
|
|
|
// A manual status save changes what the next heartbeat should carry.
|
|
|
|
|
deduper.reset();
|
2026-06-10 21:31:58 -04:00
|
|
|
|
2026-06-14 00:47:14 -04:00
|
|
|
// Read status from localStorage at call time so manual updates from the
|
|
|
|
|
// Profile settings are never overwritten by a stale closure value.
|
|
|
|
|
const readStatus = () =>
|
|
|
|
|
userId ? (localStorage.getItem(`lotus-status-msg-${userId}`) ?? '') : '';
|
|
|
|
|
|
2026-06-24 08:22:00 -04:00
|
|
|
// Log presence failures without leaking PII (user id, token, status message).
|
|
|
|
|
const warnPresenceFailure = (presence: string, err: unknown) => {
|
|
|
|
|
const reason =
|
|
|
|
|
err instanceof Error ? err.message : typeof err === 'string' ? err : 'unknown error';
|
|
|
|
|
console.warn(`Failed to set presence to "${presence}":`, reason);
|
|
|
|
|
};
|
|
|
|
|
|
2026-09-19 17:41:09 -04:00
|
|
|
// Synapse allows ONE presence write per 10 s per user (rc_presence, shared
|
|
|
|
|
// by all devices) and /sync already keeps us online — only send when the
|
|
|
|
|
// state or status actually changes, so a manual status save isn't 429'd
|
|
|
|
|
// by a heartbeat that changed nothing.
|
|
|
|
|
const send = (write: PresenceWrite, label: string) => {
|
|
|
|
|
if (!deduper.shouldSend(write)) return Promise.resolve();
|
2026-10-19 01:04:27 -04:00
|
|
|
return writePresence(mx, write)
|
2026-09-19 17:41:09 -04:00
|
|
|
.then(() => deduper.sent(write))
|
|
|
|
|
.catch((err) => warnPresenceFailure(label, err));
|
|
|
|
|
};
|
2026-09-24 11:50:13 -04:00
|
|
|
// #187 DP3: a device never sees its own presence changes made on other
|
|
|
|
|
// devices, so its saved status could be one another device already
|
|
|
|
|
// cleared. Ask the server what the status is now before re-sending it, and
|
|
|
|
|
// bring the local copy in line (falls back to the local copy on failure).
|
|
|
|
|
const resolveStatus = async (): Promise<string> => {
|
|
|
|
|
const local = readStatus();
|
|
|
|
|
if (!userId) return local;
|
|
|
|
|
const server = await mx.getPresence(userId).catch(() => undefined);
|
|
|
|
|
const status = pickHeartbeatStatus({
|
|
|
|
|
local,
|
|
|
|
|
server,
|
|
|
|
|
lastLocalWriteAt: getLastLocalStatusWrite(),
|
|
|
|
|
now: Date.now(),
|
|
|
|
|
});
|
|
|
|
|
if (status !== local) {
|
|
|
|
|
if (status) localStorage.setItem(`lotus-status-msg-${userId}`, status);
|
|
|
|
|
else {
|
|
|
|
|
localStorage.removeItem(`lotus-status-msg-${userId}`);
|
|
|
|
|
localStorage.removeItem(`lotus-status-expiry-${userId}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return status;
|
|
|
|
|
};
|
|
|
|
|
|
2026-10-12 12:35:26 -04:00
|
|
|
// [Gitea #282] A one-off PUT /presence doesn't stick: the SDK long-polls
|
|
|
|
|
// /sync with set_presence=online by default and Synapse treats every sync
|
|
|
|
|
// as "online", so Invisible / Idle / DND flipped back within seconds. Tell
|
|
|
|
|
// the sync loop which presence to report too (as Element does).
|
|
|
|
|
const syncPresence = (presence: SetPresence) => {
|
|
|
|
|
mx.setSyncPresence(presence).catch(() => undefined);
|
|
|
|
|
};
|
|
|
|
|
|
2026-09-24 11:50:13 -04:00
|
|
|
const setOnline = async () => {
|
2026-10-12 12:35:26 -04:00
|
|
|
syncPresence(SetPresence.Online);
|
2026-09-24 11:50:13 -04:00
|
|
|
const status = await resolveStatus();
|
2026-09-19 17:41:09 -04:00
|
|
|
return send({ presence: 'online', ...(status ? { status_msg: status } : {}) }, 'online');
|
2026-06-14 00:47:14 -04:00
|
|
|
};
|
2026-09-24 11:50:13 -04:00
|
|
|
const setUnavailable = async (statusMsg?: string) => {
|
2026-10-12 12:35:26 -04:00
|
|
|
syncPresence(SetPresence.Unavailable);
|
2026-09-24 11:50:13 -04:00
|
|
|
const status = await resolveStatus();
|
2026-09-19 17:41:09 -04:00
|
|
|
return send(
|
|
|
|
|
{
|
2026-06-10 22:55:32 -04:00
|
|
|
presence: 'unavailable',
|
2026-06-15 20:50:00 -04:00
|
|
|
...(statusMsg ? { status_msg: statusMsg } : status ? { status_msg: status } : {}),
|
2026-09-19 17:41:09 -04:00
|
|
|
},
|
|
|
|
|
'unavailable',
|
|
|
|
|
);
|
2026-06-14 00:47:14 -04:00
|
|
|
};
|
2026-10-12 12:35:26 -04:00
|
|
|
const setOffline = () => {
|
|
|
|
|
syncPresence(SetPresence.Offline);
|
|
|
|
|
return send({ presence: 'offline', status_msg: '' }, 'offline');
|
|
|
|
|
};
|
2026-05-28 19:28:52 -04:00
|
|
|
|
2026-05-30 23:29:29 -04:00
|
|
|
// Manual presence overrides — no activity tracking needed.
|
|
|
|
|
if (hidePresence || presenceStatus === 'invisible') {
|
|
|
|
|
setOffline();
|
|
|
|
|
return undefined;
|
|
|
|
|
}
|
|
|
|
|
if (presenceStatus === 'online') {
|
|
|
|
|
setOnline();
|
|
|
|
|
return undefined;
|
|
|
|
|
}
|
|
|
|
|
if (presenceStatus === 'idle') {
|
|
|
|
|
setUnavailable();
|
|
|
|
|
return undefined;
|
|
|
|
|
}
|
|
|
|
|
if (presenceStatus === 'dnd') {
|
2026-10-19 01:04:27 -04:00
|
|
|
// [Gitea #283] Real "busy" presence where supported: the status text
|
|
|
|
|
// stays yours. /sync reporting "online" doesn't override busy on
|
|
|
|
|
// Synapse, so the sync loop can stay online. Older servers keep the
|
|
|
|
|
// legacy unavailable + "dnd" text encoding.
|
|
|
|
|
mx.doesServerSupportUnstableFeature(BUSY_PRESENCE_FEATURE)
|
|
|
|
|
.catch(() => false)
|
|
|
|
|
.then(async (busy) => {
|
|
|
|
|
setBusyPresenceSupported(busy);
|
|
|
|
|
if (!busy) {
|
|
|
|
|
setUnavailable('dnd');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
syncPresence(SetPresence.Online);
|
|
|
|
|
const status = await resolveStatus();
|
|
|
|
|
send({ presence: BUSY_PRESENCE, ...(status ? { status_msg: status } : {}) }, 'busy');
|
|
|
|
|
});
|
2026-05-28 19:28:52 -04:00
|
|
|
return undefined;
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-30 23:29:29 -04:00
|
|
|
// presenceStatus === 'auto' — original activity-tracking behavior.
|
2026-05-28 19:28:52 -04:00
|
|
|
const startIdleTimer = () => {
|
|
|
|
|
clearTimeout(idleTimerRef.current);
|
2026-06-10 21:31:58 -04:00
|
|
|
idleTimerRef.current = setTimeout(() => {
|
2026-05-28 19:28:52 -04:00
|
|
|
isIdleRef.current = true;
|
|
|
|
|
setUnavailable();
|
|
|
|
|
}, IDLE_TIMEOUT_MS);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const handleActivity = () => {
|
|
|
|
|
const now = Date.now();
|
|
|
|
|
if (now - lastActivityRef.current < ACTIVITY_THROTTLE_MS) return;
|
|
|
|
|
lastActivityRef.current = now;
|
|
|
|
|
|
|
|
|
|
if (isIdleRef.current && !document.hidden) {
|
|
|
|
|
isIdleRef.current = false;
|
|
|
|
|
setOnline();
|
|
|
|
|
}
|
|
|
|
|
startIdleTimer();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const handleVisibilityChange = () => {
|
|
|
|
|
if (document.hidden) {
|
|
|
|
|
clearTimeout(idleTimerRef.current);
|
|
|
|
|
setUnavailable();
|
|
|
|
|
} else {
|
|
|
|
|
isIdleRef.current = false;
|
|
|
|
|
lastActivityRef.current = Date.now();
|
|
|
|
|
setOnline();
|
|
|
|
|
startIdleTimer();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const handlePageHide = () => {
|
|
|
|
|
const token = mx.getAccessToken();
|
2026-06-09 22:56:06 -04:00
|
|
|
const baseUrl = mx.getHomeserverUrl();
|
2026-05-28 19:28:52 -04:00
|
|
|
if (!userId || !token || !baseUrl) return;
|
|
|
|
|
|
2026-06-24 08:22:00 -04:00
|
|
|
// Reliable delivery during page teardown: navigator.sendBeacon cannot set the
|
|
|
|
|
// Authorization header required by the authenticated Matrix presence endpoint, so
|
|
|
|
|
// it isn't usable here. fetch(..., { keepalive: true }) lets the request outlive the
|
|
|
|
|
// page and is the correct mechanism for an authed endpoint. (keepalive bodies are
|
|
|
|
|
// capped at 64KB, which this tiny payload is well under.)
|
2026-10-11 22:04:57 -04:00
|
|
|
// [Gitea #339] Synapse treats a missing status_msg as "clear it", so a bare
|
|
|
|
|
// { presence: 'offline' } wiped the user's custom status for everyone whenever
|
|
|
|
|
// any tab closed or reloaded. Send the current status along with it.
|
|
|
|
|
const status = readStatus();
|
2026-05-28 19:28:52 -04:00
|
|
|
fetch(`${baseUrl}/_matrix/client/v3/presence/${encodeURIComponent(userId)}/status`, {
|
|
|
|
|
method: 'PUT',
|
|
|
|
|
headers: {
|
|
|
|
|
Authorization: `Bearer ${token}`,
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
},
|
2026-10-11 22:04:57 -04:00
|
|
|
body: JSON.stringify({ presence: 'offline', ...(status ? { status_msg: status } : {}) }),
|
2026-05-28 19:28:52 -04:00
|
|
|
keepalive: true,
|
2026-06-24 08:22:00 -04:00
|
|
|
}).catch((err) => warnPresenceFailure('offline (pagehide)', err));
|
2026-05-28 19:28:52 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
setOnline();
|
|
|
|
|
startIdleTimer();
|
|
|
|
|
|
|
|
|
|
const activityEvents = ['mousemove', 'keydown', 'touchstart', 'click', 'scroll'] as const;
|
|
|
|
|
activityEvents.forEach((e) => window.addEventListener(e, handleActivity, { passive: true }));
|
|
|
|
|
document.addEventListener('visibilitychange', handleVisibilityChange);
|
|
|
|
|
window.addEventListener('pagehide', handlePageHide);
|
|
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
clearTimeout(idleTimerRef.current);
|
|
|
|
|
activityEvents.forEach((e) => window.removeEventListener(e, handleActivity));
|
|
|
|
|
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
|
|
|
|
window.removeEventListener('pagehide', handlePageHide);
|
|
|
|
|
};
|
2026-05-30 23:29:29 -04:00
|
|
|
}, [mx, hidePresence, presenceStatus]);
|
2026-05-28 19:28:52 -04:00
|
|
|
}
|