storebound/apps/desktop/src/lib/notify.ts

110 lines
6.1 KiB
TypeScript

// What deserves a desktop notification after a read (Settings > Notifications). Pure: compares the previous read with
// the new one and never fires on a first read (nothing to compare with = no flood).
import type { PortfolioResult } from '../api';
import { sameVersion } from '../../../../cli/lib/portfolio';
import { healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type Review } from './model';
/** Which Settings > Notifications toggle a release change belongs to. */
export type ReleaseKind = 'rejected' | 'approved' | 'live' | 'halted' | 'state';
export interface ReleaseChange { project: string; name: string; store: 'ios' | 'android'; version: string; from: string; to: string; kind: ReleaseKind; /** The store's reason text, when the status carries one. */ reason?: string }
/** The notification kind of a transition into phase `to`.*/
export function releaseKind(to: string): ReleaseKind {
if (to === 'rejected') return 'rejected';
if (to === 'approved') return 'approved';
if (to === 'live' || to === 'rollout') return 'live';
if (to === 'halted') return 'halted';
return 'state';
}
/** Phase changes of the same version on the same store that the owner waits for: review in / out, approved, rejected, live, halted. */
export function releaseChanges(prev: PortfolioResult | null | undefined, next: PortfolioResult): ReleaseChange[] {
if (!prev) return [];
const WATCH = new Set(['review', 'sent', 'released', 'approved', 'rejected', 'live', 'halted']);
const out: ReleaseChange[] = [];
for (const a of next.apps) {
const before = prev.apps.find(p => p.project === a.project);
if (!before || before.release.source !== 'live' || a.release.source !== 'live') continue;
for (const r of a.release.all ?? []) {
if (!r.version) continue;
const old = (before.release.all ?? []).find(x => x.store === r.store && (x.version === r.version || sameVersion(x.version, r.version)));
if (!old || old.phase === r.phase) continue;
// a version the developer withdrew on their own is not a store decision
if (r.state === 'DEVELOPER_REJECTED') continue;
if (WATCH.has(r.phase) || WATCH.has(old.phase)) {
const reason = typeof r.reason === 'string' && r.reason.trim() ? r.reason.trim().slice(0, 160) : undefined;
out.push({ project: a.project, name: a.app?.name ?? a.project, store: r.store, version: r.version, from: old.phase, to: r.phase, kind: releaseKind(r.phase), ...(reason ? { reason } : {}) });
}
}
}
return out;
}
/** New 1-2 star reviews since the previous read. */
export function newLowReviews(prev: Review[] | null | undefined, next: Review[]): Review[] {
if (!prev) return [];
const seen = new Set(prev.map(r => `${r.store}:${r.id}`));
return next.filter(r => r.rating <= 2 && !seen.has(`${r.store}:${r.id}`));
}
/** Crash or ANR rate that went over the Play bad behavior threshold since the previous read. */
export function crashCrossed(prev: HealthSnapshot | null | undefined, next: HealthSnapshot): ('crash' | 'anr')[] {
if (!prev?.play || isError(prev.play) || !next.play || isError(next.play)) return [];
const out: ('crash' | 'anr')[] = [];
const was = { crash: healthSeries(prev.play.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash), anr: healthSeries(prev.play.anr, 'userPerceivedAnrRate', PLAY_THRESHOLDS.anr) };
const now = { crash: healthSeries(next.play.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash), anr: healthSeries(next.play.anr, 'userPerceivedAnrRate', PLAY_THRESHOLDS.anr) };
for (const k of ['crash', 'anr'] as const) if (now[k].tone === 'bad' && was[k].tone !== 'bad') out.push(k);
return out;
}
// ---- when a notification may show: kind toggle, quiet hours, mute ----
export interface QuietHours { enabled: boolean; from: string; to: string }
export interface NotifyPrefs { reviewState: boolean; rejected: boolean; approved: boolean; live: boolean; lowReviews: boolean; crash: boolean; quietHours: QuietHours }
export type NoticeKind = ReleaseKind | 'lowReviews' | 'crash' | 'test';
/** The toggle of a notification kind ("halted" shares the crash toggle: both are "something is going wrong"). */
export function kindEnabled(n: NotifyPrefs, kind: NoticeKind): boolean {
switch (kind) {
case 'rejected': return n.rejected;
case 'approved': return n.approved;
case 'live': return n.live;
case 'halted': case 'crash': return n.crash;
case 'state': return n.reviewState;
case 'lowReviews': return n.lowReviews;
case 'test': return true;
}
}
const minutesOf = (hhmm: string): number | null => {
const m = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(hhmm);
return m ? Number(m[1]) * 60 + Number(m[2]) : null;
};
/** True inside the quiet window (it may cross midnight: 23:00-08:00). Off, equal ends or a bad time = never quiet. */
export function inQuietHours(q: QuietHours, now: Date): boolean {
if (!q.enabled) return false;
const from = minutesOf(q.from), to = minutesOf(q.to);
if (from === null || to === null || from === to) return false;
const cur = now.getHours() * 60 + now.getMinutes();
return from < to ? cur >= from && cur < to : cur >= from || cur < to;
}
/** "Mute for 1 hour": muted while `muteUntil` (epoch ms) is in the future. */
export const isMuted = (muteUntil: number, now = Date.now()): boolean => muteUntil > now;
/** Whether a notification of `kind` may show now. A test notification ignores quiet hours and mute (it checks delivery). */
export function mayNotify(n: NotifyPrefs, kind: NoticeKind, o: { now?: Date; muteUntil?: number } = {}): boolean {
if (kind === 'test') return true;
const now = o.now ?? new Date();
return kindEnabled(n, kind) && !inQuietHours(n.quietHours, now) && !isMuted(o.muteUntil ?? 0, now.getTime());
}
/**
* Delay before the next background pass: the interval with +-10% jitter, doubled for every failure in a row (at most
* x16, capped at 2 hours before the jitter). `rand` is in [0, 1).
*/
export function nextReadDelay(everyMinutes: number, failures: number, rand = Math.random()): number {
const base = everyMinutes * 60_000 * 2 ** Math.min(Math.max(failures, 0), 4);
return Math.round(Math.min(base, 2 * 3_600_000) * (0.9 + rand * 0.2));
}