@mundogamernetwork/shared-ui 1.18.0 → 1.18.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -0
- package/components/keys/KeyBrowser.vue +4 -9
- package/locales/de.json +6 -0
- package/locales/en.json +6 -0
- package/locales/es.json +6 -0
- package/locales/pt-BR.json +6 -0
- package/locales/ro.json +6 -0
- package/nuxt.config.ts +7 -0
- package/package.json +1 -1
- package/pages/key-campaigns/redeem-key.vue +4 -10
- package/plugins/presence.client.ts +50 -0
- package/utils/keyRequestError.ts +54 -0
- package/utils/presenceHeartbeat.ts +81 -0
package/README.md
CHANGED
|
@@ -51,6 +51,7 @@ Todas filtram por `systemId` (platform_id) e compartilham a mesma estrutura visu
|
|
|
51
51
|
### Plugins
|
|
52
52
|
- **echo.client** - Laravel Echo / Pusher com auto-reconnect
|
|
53
53
|
- **auth.client** - Auto-fetch do usuário ao montar o app
|
|
54
|
+
- **presence.client** - Heartbeat de presença (desligado por padrão, ver "Presença")
|
|
54
55
|
|
|
55
56
|
### Middleware
|
|
56
57
|
- **auth.global** - Proteção de rotas configurável via `protectedRoutes`
|
|
@@ -198,6 +199,30 @@ Também pode ser usado direto: `<MgWhatsNewModal :suppress="meuModalAberto" :blo
|
|
|
198
199
|
- Preview do admin: rota `/whats-new-preview` (noindex). O pai (iframe) envia `postMessage({ type: "mg-whats-new-preview", payload, theme?, lang? })` e recebe `{ type: "mg-whats-new-preview-ready" }`. Para QA: `/whats-new-preview?demo=image|video|embed|text&lang=pt-BR&theme=dark`.
|
|
199
200
|
- Testes: `yarn test` (vitest via npx) cobre markup seguro, rotas bloqueadas, elegibilidade, embeds e idiomas.
|
|
200
201
|
|
|
202
|
+
### Presença (quem está online / quem sumiu)
|
|
203
|
+
|
|
204
|
+
O plugin `presence.client` avisa a API, a cada ~2 minutos e só com a aba visível, que o usuário logado está ativo na plataforma. O network-admin usa isso para mostrar "Online" e "Última atividade" na lista de usuários e para os fluxos de reativação.
|
|
205
|
+
|
|
206
|
+
**Desligado por padrão.** Ligue por front, só depois que a API desse front estiver rodando a versão do api-main que guarda o heartbeat no Redis (antes disso cada ping vira uma escrita no Postgres):
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
// nuxt.config.ts do app
|
|
210
|
+
runtimeConfig: {
|
|
211
|
+
public: {
|
|
212
|
+
mgSharedUi: {
|
|
213
|
+
systemId: '1', // id da plataforma em mg_network_systems (VITE_SYSTEM_ID)
|
|
214
|
+
presence: { enabled: true, intervalSeconds: 120 } // nunca abaixo de 60
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
ou por ambiente, sem mexer no código: `NUXT_PUBLIC_MG_SHARED_UI_PRESENCE_ENABLED=true`.
|
|
221
|
+
|
|
222
|
+
- Chama `POST /public/user-status/heartbeat` com `{ platform_id }`. Sem `systemId` numérico, o plugin não faz nada.
|
|
223
|
+
- Acompanha o login pelo store `auth-store`, então funciona também nos apps que têm cópia própria do store (academy, agency) com o mesmo id.
|
|
224
|
+
- Para ao receber 401/403 e volta no próximo login; falhas de rede ou 5xx são ignoradas.
|
|
225
|
+
|
|
201
226
|
## Sobrescrita (Override)
|
|
202
227
|
|
|
203
228
|
Por ser um Nuxt Layer, qualquer arquivo pode ser sobrescrito no app consumidor. Basta criar o arquivo com o mesmo caminho:
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
type RevealResult,
|
|
11
11
|
} from '../../services/keyService'
|
|
12
12
|
import httpService, { mgApiUrl } from '../../services/httpService'
|
|
13
|
+
import { keyRequestErrorMessage } from '../../utils/keyRequestError'
|
|
13
14
|
|
|
14
15
|
const { t } = useI18n()
|
|
15
16
|
|
|
@@ -140,18 +141,12 @@ async function doRequestKey(pool: KeyCampaign) {
|
|
|
140
141
|
}
|
|
141
142
|
} catch (err: any) {
|
|
142
143
|
const status = err?.response?.status
|
|
143
|
-
|
|
144
|
+
let specific: ReturnType<typeof keyRequestErrorMessage> = null
|
|
144
145
|
|
|
145
146
|
if (status === 401) {
|
|
146
147
|
isAuthenticated.value = false
|
|
147
|
-
} else if (
|
|
148
|
-
requestErrors.value[pool.id] = t(
|
|
149
|
-
} else if (status === 403 && errorCode === 'user_key_blocked') {
|
|
150
|
-
requestErrors.value[pool.id] = t('keys.campaigns.error_user_blocked')
|
|
151
|
-
} else if (status === 403) {
|
|
152
|
-
requestErrors.value[pool.id] = t('keys.campaigns.error_not_eligible')
|
|
153
|
-
} else if (status === 422 && errorCode === 'pending_limit_reached') {
|
|
154
|
-
requestErrors.value[pool.id] = t('keys.campaigns.error_pending_limit')
|
|
148
|
+
} else if ((specific = keyRequestErrorMessage(err))) {
|
|
149
|
+
requestErrors.value[pool.id] = t(specific.key, specific.params ?? {})
|
|
155
150
|
} else {
|
|
156
151
|
requestErrors.value[pool.id] =
|
|
157
152
|
err?.response?.data?.message || t('keys.campaigns.error_request')
|
package/locales/de.json
CHANGED
|
@@ -386,6 +386,12 @@
|
|
|
386
386
|
"error_user_blocked": "Ihr Zugang zu Key-Anfragen wurde vorübergehend gesperrt, da Material-Einreichungen überfällig sind. Bitte reichen Sie Ihre ausstehenden Materialien ein.",
|
|
387
387
|
"error_not_eligible": "Diese Kampagne ist für Ihren aktuellen Plan nicht verfügbar.",
|
|
388
388
|
"error_pending_limit": "Sie haben das gleichzeitige Anfragenlimit Ihres Plans erreicht. Bitte erfüllen Sie Ihre ausstehenden Verpflichtungen, bevor Sie einen neuen Key anfordern.",
|
|
389
|
+
"error_not_open_yet": "Diese Kampagne ist noch nicht geöffnet.",
|
|
390
|
+
"error_closed": "Diese Kampagne ist beendet.",
|
|
391
|
+
"error_country": "Diese Kampagne ist in deinem Land nicht verfügbar.",
|
|
392
|
+
"error_not_approved_creator": "Du bist kein freigegebener Creator für diese Kampagne.",
|
|
393
|
+
"error_tier_locked": "Diese Kampagne erfordert den Plan {tier} oder höher.",
|
|
394
|
+
"error_streamer_level": "Dein Streamer-Level reicht für diese Kampagne nicht aus.",
|
|
389
395
|
"error_session_expired": "Deine Sitzung ist abgelaufen.",
|
|
390
396
|
"error_session_expired_help": "Melde dich erneut an, um diese Anfrage abzuschließen. Deine Eingaben wurden noch nicht gesendet.",
|
|
391
397
|
"login_again": "Erneut anmelden",
|
package/locales/en.json
CHANGED
|
@@ -386,6 +386,12 @@
|
|
|
386
386
|
"error_user_blocked": "Your key request access has been temporarily blocked due to overdue material submissions. Please submit your pending materials to restore access.",
|
|
387
387
|
"error_not_eligible": "This campaign is not available for your current plan.",
|
|
388
388
|
"error_pending_limit": "You have reached the simultaneous request limit for your plan. Please fulfill your pending obligations before requesting a new key.",
|
|
389
|
+
"error_not_open_yet": "This campaign has not opened yet.",
|
|
390
|
+
"error_closed": "This campaign is closed.",
|
|
391
|
+
"error_country": "This campaign is not available in your country.",
|
|
392
|
+
"error_not_approved_creator": "You are not an approved creator for this campaign.",
|
|
393
|
+
"error_tier_locked": "This campaign requires the {tier} plan or higher.",
|
|
394
|
+
"error_streamer_level": "Your streamer level is not high enough for this campaign.",
|
|
389
395
|
"error_session_expired": "Your session has expired.",
|
|
390
396
|
"error_session_expired_help": "Sign in again to finish this request. Nothing you typed was sent yet.",
|
|
391
397
|
"login_again": "Sign in again",
|
package/locales/es.json
CHANGED
|
@@ -386,6 +386,12 @@
|
|
|
386
386
|
"error_user_blocked": "Tu acceso a solicitudes de claves ha sido bloqueado temporalmente por envíos de material pendientes. Envía tus materiales para restaurar el acceso.",
|
|
387
387
|
"error_not_eligible": "Esta campaña no está disponible para tu plan actual.",
|
|
388
388
|
"error_pending_limit": "Has alcanzado el límite de solicitudes simultáneas de tu plan. Cumple con tus obligaciones pendientes antes de solicitar una nueva clave.",
|
|
389
|
+
"error_not_open_yet": "Esta campaña aún no se ha abierto.",
|
|
390
|
+
"error_closed": "Esta campaña está cerrada.",
|
|
391
|
+
"error_country": "Esta campaña no está disponible en tu país.",
|
|
392
|
+
"error_not_approved_creator": "No eres un creador aprobado para esta campaña.",
|
|
393
|
+
"error_tier_locked": "Esta campaña requiere el plan {tier} o superior.",
|
|
394
|
+
"error_streamer_level": "Tu nivel de streamer no es suficiente para esta campaña.",
|
|
389
395
|
"error_session_expired": "Tu sesión ha expirado.",
|
|
390
396
|
"error_session_expired_help": "Inicia sesión de nuevo para completar esta solicitud. Nada de lo que escribiste se envió todavía.",
|
|
391
397
|
"login_again": "Iniciar sesión de nuevo",
|
package/locales/pt-BR.json
CHANGED
|
@@ -386,6 +386,12 @@
|
|
|
386
386
|
"error_user_blocked": "Seu acesso a pedidos de chave está temporariamente bloqueado por materiais não entregues. Envie seus materiais pendentes para restaurar o acesso.",
|
|
387
387
|
"error_not_eligible": "Esta campanha não está disponível para o seu plano atual.",
|
|
388
388
|
"error_pending_limit": "Você atingiu o limite de pedidos simultâneos do seu plano. Entregue o material pendente antes de solicitar uma nova chave.",
|
|
389
|
+
"error_not_open_yet": "Esta campanha ainda não foi aberta.",
|
|
390
|
+
"error_closed": "Esta campanha está encerrada.",
|
|
391
|
+
"error_country": "Esta campanha não está disponível no seu país.",
|
|
392
|
+
"error_not_approved_creator": "Você não é um criador aprovado para esta campanha.",
|
|
393
|
+
"error_tier_locked": "Esta campanha exige o plano {tier} ou superior.",
|
|
394
|
+
"error_streamer_level": "Seu nível de streamer não é suficiente para esta campanha.",
|
|
389
395
|
"error_session_expired": "Sua sessão expirou.",
|
|
390
396
|
"error_session_expired_help": "Entre novamente para concluir esta solicitação. Nada do que você preencheu foi enviado ainda.",
|
|
391
397
|
"login_again": "Entrar novamente",
|
package/locales/ro.json
CHANGED
|
@@ -386,6 +386,12 @@
|
|
|
386
386
|
"error_user_blocked": "Accesul dvs. la solicitările de chei a fost blocat temporar din cauza transmisiilor de materiale restante. Trimiteți materialele dvs. pentru a restabili accesul.",
|
|
387
387
|
"error_not_eligible": "Această campanie nu este disponibilă pentru planul dvs. actual.",
|
|
388
388
|
"error_pending_limit": "Ați atins limita de cereri simultane a planului dvs. Îndepliniți-vă obligațiile restante înainte de a solicita o nouă cheie.",
|
|
389
|
+
"error_not_open_yet": "Această campanie nu s-a deschis încă.",
|
|
390
|
+
"error_closed": "Această campanie este închisă.",
|
|
391
|
+
"error_country": "Această campanie nu este disponibilă în țara ta.",
|
|
392
|
+
"error_not_approved_creator": "Nu ești un creator aprobat pentru această campanie.",
|
|
393
|
+
"error_tier_locked": "Această campanie necesită planul {tier} sau superior.",
|
|
394
|
+
"error_streamer_level": "Nivelul tău de streamer nu este suficient pentru această campanie.",
|
|
389
395
|
"error_session_expired": "Sesiunea ta a expirat.",
|
|
390
396
|
"error_session_expired_help": "Autentifică-te din nou pentru a finaliza această solicitare. Nimic din ce ai completat nu a fost trimis încă.",
|
|
391
397
|
"login_again": "Autentifică-te din nou",
|
package/nuxt.config.ts
CHANGED
|
@@ -157,6 +157,13 @@ export default defineNuxtConfig({
|
|
|
157
157
|
// with no gamification data for its users can set this to false.
|
|
158
158
|
gamification: true,
|
|
159
159
|
},
|
|
160
|
+
// Presence: pings the API every couple of minutes while a signed-in user has a tab open, so the admin can
|
|
161
|
+
// show who is online and who stopped coming back. Off until a front opts in (the front's API must run the
|
|
162
|
+
// api-main version that buffers the heartbeat). Env: NUXT_PUBLIC_MG_SHARED_UI_PRESENCE_ENABLED=true.
|
|
163
|
+
presence: {
|
|
164
|
+
enabled: false,
|
|
165
|
+
intervalSeconds: 120, // never below 60
|
|
166
|
+
},
|
|
160
167
|
// "Novidades da Rede" modal, mounted by <MgBanners />. Routes are path
|
|
161
168
|
// prefixes (locale prefix ignored); allowedRoutes empty = any logged-in
|
|
162
169
|
// route that is not blocked. blockedRoutes add to the built-in list
|
package/package.json
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
buildReLoginUrl,
|
|
14
14
|
} from "../../services/campaignService"
|
|
15
15
|
import { formatEmbargoDateTime } from "../../utils/embargo"
|
|
16
|
+
import { keyRequestErrorMessage } from "../../utils/keyRequestError"
|
|
16
17
|
import { useLoginStore } from "../../stores/login"
|
|
17
18
|
|
|
18
19
|
const route = useRoute()
|
|
@@ -248,22 +249,15 @@ async function submit() {
|
|
|
248
249
|
navigateTo(campaignPath.value)
|
|
249
250
|
}, 2000)
|
|
250
251
|
} catch (e: any) {
|
|
251
|
-
|
|
252
|
-
const errorCode = e?.response?.data?.error_code
|
|
252
|
+
let specific: ReturnType<typeof keyRequestErrorMessage> = null
|
|
253
253
|
if (isSessionExpired(e)) {
|
|
254
254
|
// The API rejected the request as unauthenticated. Never surface the
|
|
255
255
|
// backend's own wording here ("Unauthorized"): it is untranslated and
|
|
256
256
|
// reads as a permission problem when it is really an expired session.
|
|
257
257
|
sessionExpired.value = true
|
|
258
258
|
requestError.value = $i18n.t("keys.campaigns.error_session_expired")
|
|
259
|
-
} else if (
|
|
260
|
-
requestError.value = $i18n.t(
|
|
261
|
-
} else if (status === 403 && errorCode === "user_key_blocked") {
|
|
262
|
-
requestError.value = $i18n.t("keys.campaigns.error_user_blocked")
|
|
263
|
-
} else if (status === 403) {
|
|
264
|
-
requestError.value = $i18n.t("keys.campaigns.error_not_eligible")
|
|
265
|
-
} else if (status === 422 && errorCode === "pending_limit_reached") {
|
|
266
|
-
requestError.value = $i18n.t("keys.campaigns.error_pending_limit")
|
|
259
|
+
} else if ((specific = keyRequestErrorMessage(e))) {
|
|
260
|
+
requestError.value = $i18n.t(specific.key, specific.params ?? {})
|
|
267
261
|
} else {
|
|
268
262
|
const msg = e?.response?.data?.message || e?.message || ""
|
|
269
263
|
requestError.value = msg || $i18n.t("keys.campaigns.error_request")
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { createPresenceHeartbeat } from "../utils/presenceHeartbeat";
|
|
2
|
+
import httpService from "../services/httpService";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Presence: tells the API this user is active on this platform, so the admin can see who is online and who stopped coming
|
|
6
|
+
* back (api-main: POST /public/user-status/heartbeat, buffered in Redis and flushed to Postgres in batches).
|
|
7
|
+
*
|
|
8
|
+
* Off by default. Turn it on per front with `runtimeConfig.public.mgSharedUi.presence.enabled`, or the env var
|
|
9
|
+
* NUXT_PUBLIC_MG_SHARED_UI_PRESENCE_ENABLED=true, once that front's API runs the version of api-main that buffers the
|
|
10
|
+
* heartbeat. The platform is mgSharedUi.systemId (VITE_SYSTEM_ID), the same id the user-status toggle already uses.
|
|
11
|
+
*
|
|
12
|
+
* It follows the persisted auth store by its id ("auth-store") instead of importing the store: a few fronts (academy, agency)
|
|
13
|
+
* keep their own copy of the store, with the same id, and this works with either.
|
|
14
|
+
*/
|
|
15
|
+
export default defineNuxtPlugin({
|
|
16
|
+
name: "shared-ui-presence",
|
|
17
|
+
setup(nuxtApp) {
|
|
18
|
+
try {
|
|
19
|
+
const config = (useRuntimeConfig().public as any).mgSharedUi ?? {};
|
|
20
|
+
const presence = config.presence ?? {};
|
|
21
|
+
if (!presence.enabled) return;
|
|
22
|
+
|
|
23
|
+
const platformId = Number(config.systemId || import.meta.env.VITE_SYSTEM_ID);
|
|
24
|
+
if (!Number.isInteger(platformId) || platformId <= 0) return;
|
|
25
|
+
|
|
26
|
+
const pinia = (nuxtApp as any).$pinia;
|
|
27
|
+
if (!pinia) return;
|
|
28
|
+
|
|
29
|
+
// Never faster than once a minute, whatever a front configures: the API treats ~5 minutes as online.
|
|
30
|
+
const intervalMs = Math.max(60, Number(presence.intervalSeconds) || 120) * 1000;
|
|
31
|
+
|
|
32
|
+
const heartbeat = createPresenceHeartbeat({
|
|
33
|
+
intervalMs,
|
|
34
|
+
isVisible: () => document.visibilityState === "visible",
|
|
35
|
+
send: () => httpService.post("/public/user-status/heartbeat", { platform_id: platformId }),
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
watch(
|
|
39
|
+
() => pinia.state.value["auth-store"]?.signedIn,
|
|
40
|
+
(signedIn) => (signedIn ? heartbeat.start() : heartbeat.stop()),
|
|
41
|
+
{ immediate: true },
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
document.addEventListener("visibilitychange", () => heartbeat.onVisible());
|
|
45
|
+
} catch (e) {
|
|
46
|
+
// Presence must never break a page.
|
|
47
|
+
console.warn("[shared-ui Presence] disabled:", e);
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
});
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which message a failed key request deserves.
|
|
3
|
+
*
|
|
4
|
+
* Every 403 used to read "not available for your current plan", whatever the
|
|
5
|
+
* real reason was: a closed campaign, the wrong country, a creator who is not on
|
|
6
|
+
* the campaign's list, a streamer level that is too low. People were told to
|
|
7
|
+
* upgrade a plan that had nothing to do with it. The API already says why
|
|
8
|
+
* (error_code / reason / requires_tier / requires_streamer_type); this turns
|
|
9
|
+
* that into one i18n key so every page that sends a request answers the same
|
|
10
|
+
* way.
|
|
11
|
+
*
|
|
12
|
+
* Returns the i18n key and its params, or null for errors that have no specific
|
|
13
|
+
* message (the caller keeps its own fallback).
|
|
14
|
+
*/
|
|
15
|
+
export interface KeyRequestErrorMessage {
|
|
16
|
+
key: string
|
|
17
|
+
params?: Record<string, string>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function keyRequestErrorMessage(err: any): KeyRequestErrorMessage | null {
|
|
21
|
+
const status = err?.response?.status
|
|
22
|
+
const data = err?.response?.data ?? {}
|
|
23
|
+
const errorCode: string | undefined = data.error_code
|
|
24
|
+
const reason: string | undefined = data.reason
|
|
25
|
+
|
|
26
|
+
if (status === 409) return { key: "keys.campaigns.error_duplicate" }
|
|
27
|
+
|
|
28
|
+
if (status === 422 && errorCode === "pending_limit_reached") {
|
|
29
|
+
return { key: "keys.campaigns.error_pending_limit" }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (status !== 403) return null
|
|
33
|
+
|
|
34
|
+
if (errorCode === "user_key_blocked") return { key: "keys.campaigns.error_user_blocked" }
|
|
35
|
+
if (errorCode === "campaign_not_open_yet") return { key: "keys.campaigns.error_not_open_yet" }
|
|
36
|
+
if (errorCode === "campaign_closed") return { key: "keys.campaigns.error_closed" }
|
|
37
|
+
|
|
38
|
+
if (errorCode === "access_denied") {
|
|
39
|
+
if (reason === "COUNTRY_NOT_ELIGIBLE") return { key: "keys.campaigns.error_country" }
|
|
40
|
+
if (reason === "NOT_AN_APPROVED_CREATOR") return { key: "keys.campaigns.error_not_approved_creator" }
|
|
41
|
+
// Not signed in (any more): a session problem, not a plan problem.
|
|
42
|
+
if (reason === "UNAUTHENTICATED") return { key: "keys.campaigns.error_session_expired" }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Plan lock: name the plan that is actually required.
|
|
46
|
+
if (data.requires_tier) {
|
|
47
|
+
return { key: "keys.campaigns.error_tier_locked", params: { tier: String(data.requires_tier) } }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (data.requires_streamer_type) return { key: "keys.campaigns.error_streamer_level" }
|
|
51
|
+
|
|
52
|
+
// A 403 we do not recognise keeps the generic message.
|
|
53
|
+
return { key: "keys.campaigns.error_not_eligible" }
|
|
54
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps a signed-in user "present" on a platform by pinging the API about every couple of minutes.
|
|
3
|
+
*
|
|
4
|
+
* The scheduling is kept free of Nuxt and the DOM so it can be tested: the plugin hands it a `send` function and a
|
|
5
|
+
* visibility probe. Rules:
|
|
6
|
+
* - ping right away on start, then every `intervalMs` with a little jitter so a few thousand tabs do not all hit the API on
|
|
7
|
+
* the same second;
|
|
8
|
+
* - never ping a hidden tab; when it becomes visible again, ping at once if the last ping is already stale;
|
|
9
|
+
* - never overlap two pings;
|
|
10
|
+
* - a 401/403 means the session is gone: stop, and let the next sign-in start it again;
|
|
11
|
+
* - any other failure is ignored, presence is a convenience and must never surface an error to the user.
|
|
12
|
+
*/
|
|
13
|
+
export interface PresenceHeartbeatOptions {
|
|
14
|
+
intervalMs: number;
|
|
15
|
+
send: () => Promise<unknown>;
|
|
16
|
+
isVisible: () => boolean;
|
|
17
|
+
/** Random in [0, 1); injectable for tests. */
|
|
18
|
+
random?: () => number;
|
|
19
|
+
now?: () => number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** +/- this fraction of the interval is added to every wait. */
|
|
23
|
+
const JITTER = 0.15;
|
|
24
|
+
|
|
25
|
+
export function createPresenceHeartbeat(options: PresenceHeartbeatOptions) {
|
|
26
|
+
const random = options.random ?? Math.random;
|
|
27
|
+
const now = options.now ?? Date.now;
|
|
28
|
+
|
|
29
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
30
|
+
let running = false;
|
|
31
|
+
let inFlight = false;
|
|
32
|
+
let lastSentAt = 0;
|
|
33
|
+
|
|
34
|
+
const nextDelay = () => Math.round(options.intervalMs * (1 - JITTER + random() * 2 * JITTER));
|
|
35
|
+
|
|
36
|
+
const schedule = () => {
|
|
37
|
+
if (!running) return;
|
|
38
|
+
if (timer) clearTimeout(timer);
|
|
39
|
+
timer = setTimeout(tick, nextDelay());
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const ping = async () => {
|
|
43
|
+
if (inFlight) return;
|
|
44
|
+
inFlight = true;
|
|
45
|
+
lastSentAt = now();
|
|
46
|
+
try {
|
|
47
|
+
await options.send();
|
|
48
|
+
} catch (error: any) {
|
|
49
|
+
const status = error?.response?.status;
|
|
50
|
+
if (status === 401 || status === 403) stop();
|
|
51
|
+
} finally {
|
|
52
|
+
inFlight = false;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
async function tick() {
|
|
57
|
+
if (!running) return;
|
|
58
|
+
if (options.isVisible()) await ping();
|
|
59
|
+
schedule();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function start() {
|
|
63
|
+
if (running) return;
|
|
64
|
+
running = true;
|
|
65
|
+
if (options.isVisible()) void ping();
|
|
66
|
+
schedule();
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function stop() {
|
|
70
|
+
running = false;
|
|
71
|
+
if (timer) clearTimeout(timer);
|
|
72
|
+
timer = null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Call when the tab becomes visible: a tab hidden for a while should not wait out the rest of its timer. */
|
|
76
|
+
function onVisible() {
|
|
77
|
+
if (running && options.isVisible() && now() - lastSentAt >= options.intervalMs / 2) void ping();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return { start, stop, onVisible, isRunning: () => running };
|
|
81
|
+
}
|