Update selected item color in Pass menu
[ProtonMail-WebClient.git] / packages / pass / store / sagas / rules / website-rules.saga.ts
blob6916132c5eac9226294afc6429d34439883028e2
1 import { select } from 'redux-saga/effects';
3 import { WEBSITE_RULES_URL } from '@proton/pass/constants';
4 import { validateRules } from '@proton/pass/lib/extension/utils/website-rules';
5 import { resolveWebsiteRules } from '@proton/pass/store/actions/creators/rules';
6 import { websiteRulesRequest } from '@proton/pass/store/actions/requests';
7 import { createRequestSaga } from '@proton/pass/store/request/sagas';
8 import type { RequestEntry, RequestStatus } from '@proton/pass/store/request/types';
9 import { selectRequest } from '@proton/pass/store/selectors';
10 import type { Maybe } from '@proton/pass/types';
11 import { msToEpoch } from '@proton/pass/utils/time/epoch';
13 /* Don't fetch if the rules were not modified since our last fetch */
14 const revalidateWebsiteRules = async (lastRequestedAt: number): Promise<boolean> => {
15     if (lastRequestedAt === 0) return true;
16     const header = (await fetch(WEBSITE_RULES_URL, { method: 'HEAD' })).headers.get('Last-Modified');
17     const lastModified = header ? msToEpoch(new Date(header).getTime()) : 0;
18     if (lastRequestedAt >= lastModified) return false;
20     return true;
23 export default createRequestSaga({
24     actions: resolveWebsiteRules,
25     call: function* (_, { getStorage }) {
26         const lastRequest: Maybe<RequestEntry<RequestStatus>> = yield select(selectRequest(websiteRulesRequest()));
27         const lastRequestedAt = lastRequest?.status === 'success' ? lastRequest.requestedAt : 0;
29         if (yield revalidateWebsiteRules(lastRequestedAt)) {
30             const response: Response = yield fetch(WEBSITE_RULES_URL);
31             const rules: unknown = yield response.json();
32             if (validateRules(rules)) yield getStorage?.().setItem('websiteRules', JSON.stringify(rules));
33         }
35         return true;
36     },
37 });