1 import { useEffect } from 'react';
3 import { differenceInDays, getUnixTime } from 'date-fns';
5 import { useApi } from '@proton/components';
7 import type { IPCInboxHostUpdateListenerRemover } from './desktopTypes';
8 import { addIPCHostUpdateListener, emptyListener, hasInboxDesktopFeature } from './ipcHelpers';
18 const HOUR_INTERVAL = 3600000;
20 const getUnixTimeNow = () => {
21 return getUnixTime(new Date());
24 const isAtLeastDayAgo = (lastUnixTime: number) => {
25 const nowMs = getUnixTimeNow() * 1000;
26 const lastMs = lastUnixTime * 1000;
27 return differenceInDays(nowMs, lastMs) > 0;
30 const checkMailtoTelemetryIsNeeded = () => {
31 if (!hasInboxDesktopFeature('MailtoTelemetry')) {
35 const data = getDefaultMailto();
36 if (!isAtLeastDayAgo(data.lastReport.timestamp)) {
40 void checkDefaultMailto();
43 const checkDailyStatIsNeeded = () => {
44 if (!hasInboxDesktopFeature('StatsTelemetry')) {
48 const data = getDailyStats();
49 if (!isAtLeastDayAgo(data.lastReport)) {
53 void checkDailyStats();
56 // useInboxDesktopHeartbeat is for sending desktop app statistics once per day.
57 export const useInboxDesktopHeartbeat = () => {
61 // This won't be needed eventually. During transition we don't want to
62 // use default mailto telemetry, so we disable the flag in electron.
63 const defaultMailtoChecked: IPCInboxHostUpdateListenerRemover = hasInboxDesktopFeature('MailtoTelemetry')
64 ? addIPCHostUpdateListener('defaultMailtoChecked', (payload) =>
65 sendMailtoTelemetry(api, payload, getUnixTimeNow())
69 const statsTelemetryChecked: IPCInboxHostUpdateListenerRemover = hasInboxDesktopFeature('StatsTelemetry')
70 ? addIPCHostUpdateListener('dailyStatsChecked', (payload) =>
71 sendDailyTelemetry(api, payload, getUnixTimeNow())
75 checkDailyStatIsNeeded();
76 checkMailtoTelemetryIsNeeded();
77 const intervalFunction = setInterval(() => {
78 checkDailyStatIsNeeded();
79 checkMailtoTelemetryIsNeeded();
83 statsTelemetryChecked.removeListener();
84 defaultMailtoChecked.removeListener();
85 clearInterval(intervalFunction);
90 export const getUnixTimeNowTestOnly = getUnixTimeNow;
91 export const isAtLeastDayAgoTestOnly = isAtLeastDayAgo;