index
int64
0
0
repo_id
stringlengths
16
181
file_path
stringlengths
28
270
content
stringlengths
1
11.6M
__index_level_0__
int64
0
10k
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/sharing/getHasSharedCalendars.ts
import { getAllMembers, getCalendarInvitations, getPublicLinks } from '@proton/shared/lib/api/calendars'; import { getApiWithAbort } from '@proton/shared/lib/api/helpers/customConfig'; import { filterOutDeclinedInvitations } from '@proton/shared/lib/calendar/sharing/shareProton/shareProton'; import { Api } from '../../interfaces'; import { CalendarUrlsResponse, CalendarWithOwnMembers, GetAllMembersApiResponse, GetCalendarInvitationsResponse, } from '../../interfaces/calendar'; import { getIsOwnedCalendar } from '../calendar'; const getHasSharedCalendars = async ({ calendars, api, catchErrors, }: { calendars: CalendarWithOwnMembers[]; api: Api; catchErrors?: boolean; }) => { const { signal, abort } = new AbortController(); const apiWithAbort = getApiWithAbort(api, signal); let hasSharedCalendars = false; await Promise.all( calendars .filter((calendar) => getIsOwnedCalendar(calendar)) .map(async ({ ID }) => { try { const [{ CalendarUrls: links }, { Members }, { Invitations }] = await Promise.all([ apiWithAbort<CalendarUrlsResponse>(getPublicLinks(ID)), apiWithAbort<GetAllMembersApiResponse>(getAllMembers(ID)), apiWithAbort<GetCalendarInvitationsResponse>(getCalendarInvitations(ID)), ]); const pendingOrAcceptedInvitations = filterOutDeclinedInvitations(Invitations); if (links.length || Members.length > 1 || pendingOrAcceptedInvitations.length) { hasSharedCalendars = true; abort(); } } catch (e: any) { if (!catchErrors) { const error = e instanceof Error ? e : new Error('Unknown error getting calendar links or members'); throw error; } } }) ); return hasSharedCalendars; }; export default getHasSharedCalendars;
8,400
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/sharing
petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/sharing/shareProton/ShareCalendarSignatureVerificationError.ts
export class ShareCalendarSignatureVerificationError extends Error { senderEmail: string; errors?: Error[]; constructor(senderEmail: string, errors?: Error[]) { super('Authenticity of calendar invite could not be verified'); this.senderEmail = senderEmail; this.errors = errors; Object.setPrototypeOf(this, ShareCalendarSignatureVerificationError.prototype); } }
8,401
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/sharing
petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/sharing/shareProton/shareProton.ts
import { c } from 'ttag'; import { CryptoProxy, VERIFICATION_STATUS, serverTime } from '@proton/crypto'; import { SIGNATURE_CONTEXT } from '@proton/shared/lib/calendar/crypto/constants'; import { ShareCalendarSignatureVerificationError } from '@proton/shared/lib/calendar/sharing/shareProton/ShareCalendarSignatureVerificationError'; import { GetEncryptionPreferences } from '@proton/shared/lib/interfaces/hooks/GetEncryptionPreferences'; import { acceptInvitation, rejectInvitation } from '../../../api/calendars'; import { SECOND } from '../../../constants'; import { getContactDisplayNameEmail } from '../../../contacts/contactEmail'; import { canonicalizeEmail } from '../../../helpers/email'; import { Api, SimpleMap } from '../../../interfaces'; import { CalendarMemberInvitation, MEMBER_INVITATION_STATUS, VisualCalendar } from '../../../interfaces/calendar'; import { ContactEmail } from '../../../interfaces/contacts'; import { GetAddressKeys } from '../../../interfaces/hooks/GetAddressKeys'; import { getPrimaryKey } from '../../../keys'; import { getIsSharedCalendar } from '../../calendar'; import { CALENDAR_PERMISSIONS, CALENDAR_TYPE } from '../../constants'; import { decryptPassphrase, decryptPassphraseSessionKey, signPassphrase } from '../../crypto/keys/calendarKeys'; import { getCanWrite } from '../../permissions'; export const getIsInvitationExpired = ({ ExpirationTime }: CalendarMemberInvitation) => { if (!ExpirationTime) { return false; } return +serverTime() >= ExpirationTime * SECOND; }; export const getPendingInvitations = (invitations: CalendarMemberInvitation[]) => { return invitations.filter(({ Status }) => Status === MEMBER_INVITATION_STATUS.PENDING); }; export const filterOutAcceptedInvitations = (invitations: CalendarMemberInvitation[]) => { return invitations.filter(({ Status }) => Status !== MEMBER_INVITATION_STATUS.ACCEPTED); }; export const filterOutDeclinedInvitations = (invitations: CalendarMemberInvitation[]) => { return invitations.filter(({ Status }) => Status !== MEMBER_INVITATION_STATUS.REJECTED); }; export const filterOutExpiredInvitations = (invitations: CalendarMemberInvitation[]) => { return invitations.filter((invitation) => !getIsInvitationExpired(invitation)); }; export const acceptCalendarShareInvitation = async ({ addressID, calendarID, armoredPassphrase, armoredSignature, senderEmail, getAddressKeys, getEncryptionPreferences, api, skipSignatureVerification, }: { addressID: string; calendarID: string; armoredPassphrase: string; armoredSignature: string; senderEmail: string; getAddressKeys: GetAddressKeys; getEncryptionPreferences: GetEncryptionPreferences; api: Api; skipSignatureVerification?: boolean; }): Promise<boolean> => { // decrypt passphrase const addressKeys = await getAddressKeys(addressID); const privateKeys = addressKeys.map(({ privateKey }) => privateKey); const passphraseSessionKey = await decryptPassphraseSessionKey({ armoredPassphrase, privateKeys }); if (!passphraseSessionKey) { throw new Error('Missing passphrase session key'); } // verify passphrase signature if (!skipSignatureVerification) { const { verifyingPinnedKeys } = await getEncryptionPreferences({ email: senderEmail }); if (verifyingPinnedKeys.length) { const { verified: sessionKeyVerified, errors } = await CryptoProxy.verifyMessage({ armoredSignature, binaryData: passphraseSessionKey.data, verificationKeys: verifyingPinnedKeys, context: { required: true, value: SIGNATURE_CONTEXT.SHARE_CALENDAR_INVITE }, }); if (sessionKeyVerified !== VERIFICATION_STATUS.SIGNED_AND_VALID) { /** * TEMPORARY CODE: needed while there exist old clients not sending signatures with context. * For such clients, the BE gives us a passphrase signature, so we try verifying that * * When not needed anymore, substitute by: * throw new ShareCalendarSignatureVerificationError(senderEmail, errors); */ const { verified: passphraseVerified } = await CryptoProxy.decryptMessage({ armoredMessage: armoredPassphrase, armoredSignature, verificationKeys: verifyingPinnedKeys, sessionKeys: passphraseSessionKey, }); if (passphraseVerified !== VERIFICATION_STATUS.SIGNED_AND_VALID) { throw new ShareCalendarSignatureVerificationError(senderEmail, errors); } } } } // accept invitation const passphrase = await decryptPassphrase({ armoredPassphrase, sessionKey: passphraseSessionKey, }); const { privateKey } = getPrimaryKey(addressKeys) || {}; if (!privateKey) { throw new Error('No primary address key'); } const Signature = await signPassphrase({ passphrase, privateKey }); await api(acceptInvitation(calendarID, addressID, { Signature })); return true; }; export const rejectCalendarShareInvitation = ({ addressID, calendarID, api, }: { addressID: string; calendarID: string; api: Api; }) => { return api(rejectInvitation(calendarID, addressID)); }; export const getSharedCalendarSubHeaderText = (calendar: VisualCalendar, contactEmailsMap: SimpleMap<ContactEmail>) => { // we only need to display the owner for shared calendars if (!getIsSharedCalendar(calendar)) { return; } const { Name: contactName, Email: contactEmail } = contactEmailsMap[canonicalizeEmail(calendar.Owner.Email)] || {}; const email = contactEmail || calendar.Owner.Email; const { nameEmail: ownerName } = getContactDisplayNameEmail({ name: contactName, email, emailDelimiters: ['(', ')'], }); return c('Shared calendar; Info about calendar owner').t`Shared by ${ownerName}`; }; export const getCalendarNameWithOwner = ({ calendarName, ownerEmail, }: { calendarName: string; ownerEmail: string; }) => { return `${calendarName} (${ownerEmail})`; }; export const getCalendarNameSubline = ({ calendarType, displayEmail, memberEmail, memberPermissions, }: { calendarType: CALENDAR_TYPE; displayEmail: boolean; memberEmail: string; memberPermissions: CALENDAR_PERMISSIONS; }) => { const email = displayEmail ? memberEmail : ''; const viewOnlyText = !getCanWrite(memberPermissions) && calendarType === CALENDAR_TYPE.PERSONAL ? c('Info; access rights for shared calendar').t`View only` : ''; if (!email && !viewOnlyText) { return ''; } if (!viewOnlyText) { return email; } if (!email) { return viewOnlyText; } return `${viewOnlyText} • ${email}`; };
8,402
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/sharing
petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/sharing/shareUrl/shareUrl.ts
import { CryptoProxy, PrivateKeyReference, PublicKeyReference } from '@proton/crypto'; import { arrayToBinaryString, decodeBase64, encodeBase64 } from '@proton/crypto/lib/utils'; import { AES256, EVENT_ACTIONS } from '../../../constants'; import { generateRandomBytes, getSHA256Base64String, xorEncryptDecrypt } from '../../../helpers/crypto'; import { stringToUint8Array, uint8ArrayToPaddedBase64URLString, uint8ArrayToString } from '../../../helpers/encoding'; import { Nullable } from '../../../interfaces'; import { ACCESS_LEVEL, CalendarLink, CalendarUrl } from '../../../interfaces/calendar'; import { CalendarUrlEventManager, CalendarUrlEventManagerCreate, CalendarUrlEventManagerDelete, CalendarUrlEventManagerUpdate, } from '../../../interfaces/calendar/EventManager'; export const getIsCalendarUrlEventManagerDelete = ( event: CalendarUrlEventManager ): event is CalendarUrlEventManagerDelete => { return event.Action === EVENT_ACTIONS.DELETE; }; export const getIsCalendarUrlEventManagerCreate = ( event: CalendarUrlEventManager ): event is CalendarUrlEventManagerCreate => { return event.Action === EVENT_ACTIONS.CREATE; }; export const getIsCalendarUrlEventManagerUpdate = ( event: CalendarUrlEventManager ): event is CalendarUrlEventManagerUpdate => { return event.Action === EVENT_ACTIONS.UPDATE; }; export const decryptPurpose = async ({ encryptedPurpose, privateKeys, }: { encryptedPurpose: string; privateKeys: PrivateKeyReference[]; }) => ( await CryptoProxy.decryptMessage({ armoredMessage: encryptedPurpose, decryptionKeys: privateKeys, }) ).data; export const generateEncryptedPurpose = async ({ purpose, publicKey, }: { purpose: string; publicKey: PublicKeyReference; }) => { return ( await CryptoProxy.encryptMessage({ textData: purpose, stripTrailingSpaces: true, encryptionKeys: publicKey }) ).message; }; export const generateEncryptedPassphrase = ({ passphraseKey, passphrase, }: { passphraseKey: Uint8Array; passphrase: string; }) => encodeBase64(xorEncryptDecrypt({ key: uint8ArrayToString(passphraseKey), data: decodeBase64(passphrase) })); export const generateCacheKey = () => uint8ArrayToPaddedBase64URLString(generateRandomBytes(16)); export const generateCacheKeySalt = () => encodeBase64(arrayToBinaryString(generateRandomBytes(8))); export const getCacheKeyHash = ({ cacheKey, cacheKeySalt }: { cacheKey: string; cacheKeySalt: string }) => getSHA256Base64String(`${cacheKeySalt}${cacheKey}`); export const generateEncryptedCacheKey = async ({ cacheKey, publicKeys, }: { cacheKey: string; publicKeys: PublicKeyReference[]; }) => ( await CryptoProxy.encryptMessage({ textData: cacheKey, // stripTrailingSpaces: false encryptionKeys: publicKeys, }) ).message; export const decryptCacheKey = async ({ encryptedCacheKey, privateKeys, }: { encryptedCacheKey: string; privateKeys: PrivateKeyReference[]; }) => ( await CryptoProxy.decryptMessage({ armoredMessage: encryptedCacheKey, decryptionKeys: privateKeys, }) ).data; export const getPassphraseKey = ({ encryptedPassphrase, calendarPassphrase, }: { encryptedPassphrase: Nullable<string>; calendarPassphrase: string; }) => { if (!encryptedPassphrase) { return null; } return stringToUint8Array( xorEncryptDecrypt({ key: decodeBase64(calendarPassphrase), data: decodeBase64(encryptedPassphrase) }) ); }; export const buildLink = ({ urlID, accessLevel, passphraseKey, cacheKey, }: { urlID: string; accessLevel: ACCESS_LEVEL; passphraseKey: Nullable<Uint8Array>; cacheKey: string; }) => { // calendar.proton.me must be hardcoded here as using getAppHref would produce links that wouldn't work const baseURL = `https://calendar.proton.me/api/calendar/v1/url/${urlID}/calendar.ics`; const encodedCacheKey = encodeURIComponent(cacheKey); if (accessLevel === ACCESS_LEVEL.FULL && passphraseKey) { const encodedPassphraseKey = encodeURIComponent(uint8ArrayToPaddedBase64URLString(passphraseKey)); return `${baseURL}?CacheKey=${encodedCacheKey}&PassphraseKey=${encodedPassphraseKey}`; } return `${baseURL}?CacheKey=${encodedCacheKey}`; }; export const getCreatePublicLinkPayload = async ({ accessLevel, publicKeys, passphrase, passphraseID, encryptedPurpose = null, }: { accessLevel: ACCESS_LEVEL; publicKeys: PublicKeyReference[]; passphrase: string; passphraseID: string; encryptedPurpose?: Nullable<string>; }) => { const passphraseKey = await CryptoProxy.generateSessionKeyForAlgorithm(AES256); const encryptedPassphrase = accessLevel === ACCESS_LEVEL.FULL ? generateEncryptedPassphrase({ passphraseKey, passphrase }) : null; const cacheKeySalt = generateCacheKeySalt(); const cacheKey = generateCacheKey(); const cacheKeyHash = await getCacheKeyHash({ cacheKey, cacheKeySalt }); const encryptedCacheKey = await generateEncryptedCacheKey({ cacheKey, publicKeys }); return { payload: { AccessLevel: accessLevel, CacheKeySalt: cacheKeySalt, CacheKeyHash: cacheKeyHash, EncryptedPassphrase: encryptedPassphrase, EncryptedPurpose: encryptedPurpose, EncryptedCacheKey: encryptedCacheKey, PassphraseID: accessLevel === ACCESS_LEVEL.FULL ? passphraseID : null, }, passphraseKey, cacheKey, }; }; export const transformLinkFromAPI = async ({ calendarUrl, privateKeys, calendarPassphrase, onError, }: { calendarUrl: CalendarUrl; privateKeys: PrivateKeyReference[]; calendarPassphrase: string; onError: (e: Error) => void; }): Promise<CalendarLink> => { const { EncryptedPurpose: encryptedPurpose, CalendarUrlID, AccessLevel, EncryptedCacheKey, EncryptedPassphrase, } = calendarUrl; let purpose = null; let link = ''; if (encryptedPurpose) { try { purpose = await decryptPurpose({ encryptedPurpose, privateKeys, }); } catch (e: any) { onError(e); purpose = encryptedPurpose; } } try { const cacheKey = await decryptCacheKey({ encryptedCacheKey: EncryptedCacheKey, privateKeys }); const passphraseKey = getPassphraseKey({ encryptedPassphrase: EncryptedPassphrase, calendarPassphrase }); link = buildLink({ urlID: CalendarUrlID, accessLevel: AccessLevel, passphraseKey, cacheKey, }); } catch (e: any) { onError(e); link = `Error building link: ${e.message}`; } return { ...calendarUrl, purpose, link, }; }; export const transformLinksFromAPI = async ({ calendarUrls, privateKeys, calendarPassphrase, onError, }: { calendarUrls: CalendarUrl[]; privateKeys: PrivateKeyReference[]; calendarPassphrase: string; onError: (e: Error) => void; }) => { return Promise.all( calendarUrls.map((calendarUrl) => transformLinkFromAPI({ calendarUrl, privateKeys, calendarPassphrase, onError, }) ) ); };
8,403
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/subscribe/helpers.ts
import { c } from 'ttag'; import { CALENDAR_APP_NAME, EVENT_ACTIONS, HOUR } from '../../constants'; import { CALENDAR_SUBSCRIPTION_STATUS, Calendar, SubscribedCalendar } from '../../interfaces/calendar'; import { CalendarSubscriptionEventManager, CalendarSubscriptionEventManagerCreate, CalendarSubscriptionEventManagerDelete, CalendarSubscriptionEventManagerUpdate, } from '../../interfaces/calendar/EventManager'; const { OK, INVALID_ICS, ICS_SIZE_EXCEED_LIMIT, SYNCHRONIZING, HTTP_REQUEST_FAILED_BAD_REQUEST, HTTP_REQUEST_FAILED_UNAUTHORIZED, HTTP_REQUEST_FAILED_FORBIDDEN, HTTP_REQUEST_FAILED_NOT_FOUND, HTTP_REQUEST_FAILED_GENERIC, HTTP_REQUEST_FAILED_INTERNAL_SERVER_ERROR, HTTP_REQUEST_FAILED_TIMEOUT, INTERNAL_CALENDAR_URL_NOT_FOUND, INTERNAL_CALENDAR_UNDECRYPTABLE, } = CALENDAR_SUBSCRIPTION_STATUS; export const getIsCalendarSubscriptionEventManagerDelete = ( event: CalendarSubscriptionEventManager ): event is CalendarSubscriptionEventManagerDelete => { return event.Action === EVENT_ACTIONS.DELETE; }; export const getIsCalendarSubscriptionEventManagerCreate = ( event: CalendarSubscriptionEventManager ): event is CalendarSubscriptionEventManagerCreate => { return event.Action === EVENT_ACTIONS.CREATE; }; export const getIsCalendarSubscriptionEventManagerUpdate = ( event: CalendarSubscriptionEventManager ): event is CalendarSubscriptionEventManagerUpdate => { return event.Action === EVENT_ACTIONS.UPDATE; }; export const getCalendarHasSubscriptionParameters = ( calendar: Calendar | SubscribedCalendar ): calendar is SubscribedCalendar => { return !!(calendar as SubscribedCalendar).SubscriptionParameters; }; export const getSyncingInfo = (text: string, longText = '') => ({ label: c('Calendar status').t`Syncing`, text, longText: longText ? longText : `${text}.`, isSyncing: true, }); export const getNotSyncedInfo = (text: string, longText = '') => ({ label: c('Calendar status').t`Not synced`, text, longText: longText ? longText : `${text}.`, isSyncing: false, }); export const getCalendarStatusInfo = (status: CALENDAR_SUBSCRIPTION_STATUS) => { if (status === OK) { return; } if (status === INVALID_ICS) { return getNotSyncedInfo(c('Calendar subscription not synced error').t`Unsupported calendar format`); } if (status === ICS_SIZE_EXCEED_LIMIT) { return getNotSyncedInfo(c('Calendar subscription not synced error').t`Calendar is too big`); } if (status === SYNCHRONIZING) { return getSyncingInfo( c('Calendar subscription not synced error').t`Calendar is syncing`, c('Calendar subscription not synced error') .t`Calendar is syncing: it may take several minutes for all of its events to show up.` ); } if ( [ HTTP_REQUEST_FAILED_BAD_REQUEST, HTTP_REQUEST_FAILED_UNAUTHORIZED, HTTP_REQUEST_FAILED_FORBIDDEN, HTTP_REQUEST_FAILED_NOT_FOUND, INTERNAL_CALENDAR_URL_NOT_FOUND, ].includes(status) ) { return getNotSyncedInfo( c('Calendar subscription not synced error').t`Calendar link is not accessible`, c('Calendar subscription not synced error; long version') .t`Calendar link is not accessible from outside the calendar provider's ecosystem.` ); } if ( [HTTP_REQUEST_FAILED_GENERIC, HTTP_REQUEST_FAILED_INTERNAL_SERVER_ERROR, HTTP_REQUEST_FAILED_TIMEOUT].includes( status ) ) { return getNotSyncedInfo( c('Calendar subscription not synced error').t`Calendar link is temporarily inaccessible`, c('Calendar subscription not synced error; long version') .t`Calendar link is temporarily inaccessible. Please verify that the link from the calendar provider is still valid.` ); } if (status === INTERNAL_CALENDAR_UNDECRYPTABLE) { return getNotSyncedInfo(c('Calendar subscription not synced error').t`Calendar could not be decrypted`); } return getNotSyncedInfo(c('Calendar subscription not synced error').t`Failed to sync calendar`); }; export const getCalendarIsNotSyncedInfo = (calendar: SubscribedCalendar) => { const { Status, LastUpdateTime } = calendar.SubscriptionParameters; if (LastUpdateTime === 0) { return getSyncingInfo( c('Calendar subscription not synced error').t`Calendar is syncing`, c('Calendar subscription not synced error') .t`Calendar is syncing: it may take several minutes for all of its events to show up.` ); } if (Date.now() - LastUpdateTime * 1000 > 12 * HOUR) { return getNotSyncedInfo( c('Calendar subscription not synced error').t`More than 12 hours passed since last update`, c('Calendar subscription not synced error; long version') .t`More than 12 hours passed since last update — ${CALENDAR_APP_NAME} will try to update the calendar in a few hours.` ); } return getCalendarStatusInfo(Status); };
8,404
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar
petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/sync/reencrypt.ts
import { SessionKey } from '@proton/crypto'; import { upgradeP2PInvite } from '../../api/calendars'; import { uint8ArrayToBase64String } from '../../helpers/encoding'; import { Api } from '../../interfaces'; import { CalendarEvent, DecryptedCalendarKey } from '../../interfaces/calendar'; import { getEncryptedSessionKey } from '../crypto/encrypt'; import { getPrimaryCalendarKey } from '../crypto/keys/helpers'; export const reencryptCalendarSharedEvent = async ({ calendarEvent, sharedSessionKey, calendarKeys, api, }: { calendarEvent: CalendarEvent; sharedSessionKey: SessionKey; calendarKeys: DecryptedCalendarKey[]; api: Api; }): Promise<CalendarEvent> => { const { publicKey } = getPrimaryCalendarKey(calendarKeys); const SharedKeyPacket = uint8ArrayToBase64String(await getEncryptedSessionKey(sharedSessionKey, publicKey)); const { Event } = await api<{ Event: CalendarEvent }>( upgradeP2PInvite(calendarEvent.CalendarID, calendarEvent.ID, { SharedKeyPacket }) ); return Event; };
8,405
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/constants.ts
// BACK-END DATA import { BASE_SIZE } from '../constants'; export const VCARD_KEY_FIELDS = [ 'key', 'x-pm-mimetype', 'x-pm-encrypt', 'x-pm-encrypt-untrusted', 'x-pm-sign', 'x-pm-scheme', 'x-pm-tls', ]; export const CLEAR_FIELDS = ['version', 'prodid', 'categories']; export const SIGNED_FIELDS = ['version', 'prodid', 'fn', 'uid', 'email'].concat(VCARD_KEY_FIELDS); export enum CRYPTO_PROCESSING_TYPES { SUCCESS, SIGNATURE_NOT_VERIFIED, FAIL_TO_READ, FAIL_TO_LOAD, FAIL_TO_DECRYPT, } export enum OVERWRITE { // when UID conflict at contact import THROW_ERROR_IF_CONFLICT = 0, OVERWRITE_CONTACT = 1, } export enum CATEGORIES { IGNORE = 0, INCLUDE = 1, } export const OTHER_INFORMATION_FIELDS = [ 'anniversary', 'gender', 'lang', 'tz', 'geo', 'title', 'role', 'photo', 'logo', 'org', 'member', 'url', ]; export enum PGP_SCHEME_TEXT { INLINE = 'PGP/Inline', MIME = 'PGP/MIME', } export enum ADDRESS_COMPONENTS { POST_BOX, EXTENDED, STREET, LOCALITY, REGION, POSTAL_CODE, COUNTRY, } export const CONTACT_IMG_SIZE = 180; export const API_SAFE_INTERVAL = 100; // API request limit: 100 requests / 10 seconds, so 1 request every 100 ms is safe export const QUERY_EXPORT_MAX_PAGESIZE = 50; // in GET API route /contacts/export // Manual limit on number of imported contacts to be sent to the API, so that the response does not take too long export const ADD_CONTACTS_MAX_SIZE = 10; // FRONT-END RESTRICTIONS export const MAX_SIMULTANEOUS_CONTACTS_ENCRYPT = 5; export const MAX_CONTACTS_PER_USER = 10000; export const MAX_IMPORT_CONTACTS_STRING = MAX_CONTACTS_PER_USER.toLocaleString(); export const MAX_IMPORT_FILE_SIZE = 10 * BASE_SIZE ** 2; export const MAX_IMPORT_FILE_SIZE_STRING = '10 MB'; export const MAX_CONTACT_ID_CHARS_DISPLAY = 40; export const MAX_FILENAME_CHARS_DISPLAY = 100; export const CONTACT_NAME_MAX_LENGTH = 190; // We remove one to avoid issue with space when computing the full name export const CONTACT_FIRST_LAST_NAME_MAX_LENGTH = CONTACT_NAME_MAX_LENGTH / 2 - 1; export const UID_PREFIX = 'contact-property';
8,406
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/contactEmail.ts
import { normalize } from '@proton/shared/lib/helpers/string'; export const getContactDisplayNameEmail = ({ name, email, emailDelimiters = ['<', '>'], }: { name?: string; email: string; emailDelimiters?: string[]; }) => { const displayOnlyEmail = !name || normalize(name) === normalize(email); const nameEmail = displayOnlyEmail ? email : `${name} ${emailDelimiters[0]}${email}${emailDelimiters[1]}`; return { nameEmail, displayOnlyEmail, }; };
8,407
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/decrypt.ts
import { c } from 'ttag'; import { CryptoProxy, VERIFICATION_STATUS } from '@proton/crypto'; import { CONTACT_CARD_TYPE } from '../constants'; import { KeysPair } from '../interfaces'; import { Contact, ContactCard } from '../interfaces/contacts'; import { VCardContact } from '../interfaces/contacts/VCard'; import { CRYPTO_PROCESSING_TYPES } from './constants'; import { mergeVCard } from './properties'; import { parseToVCard } from './vcard'; const { SUCCESS, SIGNATURE_NOT_VERIFIED, FAIL_TO_READ, FAIL_TO_DECRYPT } = CRYPTO_PROCESSING_TYPES; const { CLEAR_TEXT, ENCRYPTED_AND_SIGNED, ENCRYPTED, SIGNED } = CONTACT_CARD_TYPE; export interface CryptoProcessingError { type: Exclude<CRYPTO_PROCESSING_TYPES, CRYPTO_PROCESSING_TYPES.SUCCESS>; error: Error; } interface ProcessedContactData { type: CRYPTO_PROCESSING_TYPES; data?: string; signatureTimestamp?: Date; error?: Error; } export const decrypt = async ({ Data }: ContactCard, { privateKeys }: Pick<KeysPair, 'privateKeys'>) => { try { const { data } = await CryptoProxy.decryptMessage({ armoredMessage: Data, decryptionKeys: privateKeys }); if (data && typeof data !== 'string') { throw new Error('Unknown data'); } return { type: SUCCESS, data }; } catch (error: any) { return { type: FAIL_TO_DECRYPT, error }; } }; export const readSigned = async ( { Data, Signature = '' }: ContactCard, { publicKeys }: Pick<KeysPair, 'publicKeys'> ) => { try { if (!Signature) { throw new Error(c('Error').t`Missing signature`); } const { verified, signatureTimestamp } = await CryptoProxy.verifyMessage({ textData: Data, stripTrailingSpaces: true, verificationKeys: publicKeys, armoredSignature: Signature, }); if (verified !== VERIFICATION_STATUS.SIGNED_AND_VALID) { return { data: Data, type: SIGNATURE_NOT_VERIFIED, signatureTimestamp: undefined, error: new Error(c('Error').t`Contact signature not verified`), }; } return { type: SUCCESS, data: Data, signatureTimestamp: signatureTimestamp! }; } catch (error: any) { return { type: SIGNATURE_NOT_VERIFIED, data: Data, signatureTimestamp: undefined, error, }; } }; export const decryptSigned = async ({ Data, Signature }: ContactCard, { publicKeys, privateKeys }: KeysPair) => { try { const { data, verified } = await CryptoProxy.decryptMessage({ armoredMessage: Data, decryptionKeys: privateKeys, verificationKeys: publicKeys, armoredSignature: Signature || undefined, }); if (data && typeof data !== 'string') { throw new Error('Unknown data'); } if (verified !== VERIFICATION_STATUS.SIGNED_AND_VALID) { return { data, type: SIGNATURE_NOT_VERIFIED, error: new Error(c('Error').t`Signature not verified`) }; } return { type: SUCCESS, data }; } catch (error: any) { return { type: FAIL_TO_DECRYPT, error }; } }; const clearText = ({ Data }: ContactCard) => Promise.resolve({ type: SUCCESS, data: Data }); const ACTIONS: { [index: number]: (...params: any) => Promise<ProcessedContactData> } = { [ENCRYPTED_AND_SIGNED]: decryptSigned, [SIGNED]: readSigned, [ENCRYPTED]: decrypt, [CLEAR_TEXT]: clearText, }; export const decryptContact = async ( contact: Contact, { publicKeys, privateKeys }: KeysPair ): Promise<{ vcards: string[]; errors: (CryptoProcessingError | Error)[]; isVerified: boolean }> => { const { Cards } = contact; let isVerified = Cards.some(({ Type }) => [SIGNED, ENCRYPTED_AND_SIGNED].includes(Type)); const decryptedCards = await Promise.all( Cards.map(async (card) => { if (!ACTIONS[card.Type]) { return { type: FAIL_TO_READ, error: new Error('Unknown card type') }; } return ACTIONS[card.Type](card, { publicKeys, privateKeys }); }) ); // remove UIDs put by mistake in encrypted cards const sanitizedCards = decryptedCards.map((card, i) => { if (![ENCRYPTED_AND_SIGNED, ENCRYPTED].includes(Cards[i].Type) || !card.data) { return card; } return { ...card, data: card.data.replace(/\nUID:.*\n/i, '\n') }; }); const { vcards, errors } = sanitizedCards.reduce<{ vcards: string[]; errors: CryptoProcessingError[] }>( (acc, { type, data, error }) => { if (data) { acc.vcards.push(data); } if (error) { if (type === SUCCESS) { throw new Error('Inconsistency detected during contact card processing'); } if (type === SIGNATURE_NOT_VERIFIED) { isVerified = false; } acc.errors.push({ type, error }); } return acc; }, { vcards: [], errors: [] } ); return { isVerified, vcards, errors }; }; export const prepareVCardContact = async ( contact: Contact, { publicKeys, privateKeys }: KeysPair ): Promise<{ vCardContact: VCardContact; errors: (CryptoProcessingError | Error)[]; isVerified: boolean }> => { const { isVerified, vcards, errors } = await decryptContact(contact, { publicKeys, privateKeys }); try { const vCardContacts = vcards.map((vcard) => parseToVCard(vcard)); const vCardContact = mergeVCard(vCardContacts); return { vCardContact, errors, isVerified }; } catch (e: any) { // eslint-disable-next-line no-console console.error('Error in prepare vCard', e); const error = e instanceof Error ? e : new Error('Corrupted vcard data'); return { vCardContact: { fn: [] }, errors: [error], isVerified }; } };
8,408
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/encrypt.ts
import { CryptoProxy } from '@proton/crypto'; import { CONTACT_CARD_TYPE } from '../constants'; import { generateProtonWebUID } from '../helpers/uid'; import { KeyPair } from '../interfaces'; import { Contact, ContactCard } from '../interfaces/contacts/Contact'; import { VCardContact, VCardProperty } from '../interfaces/contacts/VCard'; import { CLEAR_FIELDS, SIGNED_FIELDS } from './constants'; import { createContactPropertyUid, getVCardProperties, hasCategories } from './properties'; import { getFallbackFNValue, prepareForSaving } from './surgery'; import { vCardPropertiesToICAL } from './vcard'; const { CLEAR_TEXT, ENCRYPTED_AND_SIGNED, SIGNED } = CONTACT_CARD_TYPE; interface SplitVCardProperties { toEncryptAndSign: VCardProperty[]; toSign: VCardProperty[]; toClearText: VCardProperty[]; } /** * Split properties for contact cards */ const splitVCardProperties = (properties: VCardProperty[]): SplitVCardProperties => { // we should only create a clear text part if categories are present const splitClearText = hasCategories(properties); return properties.reduce<SplitVCardProperties>( (acc, property) => { const { field } = property; if (splitClearText && CLEAR_FIELDS.includes(field)) { acc.toClearText.push(property); // Notice CLEAR_FIELDS and SIGNED_FIELDS have some overlap. // The repeated fields need to be in the clear-text and signed parts if (SIGNED_FIELDS.includes(field)) { acc.toSign.push(property); } return acc; } if (SIGNED_FIELDS.includes(field)) { acc.toSign.push(property); return acc; } acc.toEncryptAndSign.push(property); return acc; }, { toEncryptAndSign: [], toSign: [], toClearText: [], } ); }; export const prepareCardsFromVCard = ( vCardContact: VCardContact, { privateKey, publicKey }: KeyPair ): Promise<ContactCard[]> => { const promises = []; const publicKeys = [publicKey]; const privateKeys = [privateKey]; const properties = getVCardProperties(vCardContact); const { toEncryptAndSign = [], toSign = [], toClearText = [] } = splitVCardProperties(properties); if (toEncryptAndSign.length > 0) { const textData: string = vCardPropertiesToICAL(toEncryptAndSign).toString(); promises.push( CryptoProxy.encryptMessage({ textData, encryptionKeys: publicKeys, signingKeys: privateKeys, detached: true, }).then(({ message: Data, signature: Signature }) => { const card: ContactCard = { Type: ENCRYPTED_AND_SIGNED, Data, Signature, }; return card; }) ); } // The FN field could be empty on contact creation, this is intentional but we need to compute it from first and last name field if that's the case if (!vCardContact.fn) { const givenName = vCardContact?.n?.value?.givenNames?.[0].trim() ?? ''; const familyName = vCardContact?.n?.value?.familyNames?.[0].trim() ?? ''; const computedFirstAndLastName = `${givenName} ${familyName}` || ''; // Fallback that should never happen since we should always have a first and last name const fallbackEmail = vCardContact.email?.[0]?.value; // Fallback that should never happen since we should always have a first and last name const computedFullName: VCardProperty = { field: 'fn', value: computedFirstAndLastName || fallbackEmail || '', uid: createContactPropertyUid(), }; toSign.push(computedFullName); } if (toSign.length > 0) { const hasUID = toSign.some((property) => property.field === 'uid'); const hasFN = toSign.some((property) => property.field === 'fn'); if (!hasUID) { const defaultUID = generateProtonWebUID(); toSign.push({ field: 'uid', value: defaultUID, uid: createContactPropertyUid() }); } if (!hasFN) { const fallbackFN = getFallbackFNValue(); toSign.push({ field: 'fn', value: fallbackFN, uid: createContactPropertyUid() }); } const textData: string = vCardPropertiesToICAL(toSign).toString(); promises.push( CryptoProxy.signMessage({ textData, stripTrailingSpaces: true, signingKeys: privateKeys, detached: true, }).then((Signature) => { const card: ContactCard = { Type: SIGNED, Data: textData, Signature, }; return card; }) ); } if (toClearText.length > 0) { const Data = vCardPropertiesToICAL(toClearText).toString(); promises.push({ Type: CLEAR_TEXT, Data, Signature: null, }); } return Promise.all(promises); }; export const prepareVCardContact = async ( vCardContact: VCardContact, { privateKey, publicKey }: KeyPair ): Promise<Pick<Contact, 'Cards'>> => { const prepared = prepareForSaving(vCardContact); const Cards = await prepareCardsFromVCard(prepared, { privateKey, publicKey }); return { Cards }; }; export const prepareVCardContacts = async ( vCardContacts: VCardContact[], { privateKey, publicKey }: KeyPair ): Promise<Pick<Contact, 'Cards'>[]> => { if (!privateKey || !publicKey) { return Promise.resolve([]); } return Promise.all(vCardContacts.map((contact) => prepareVCardContact(contact, { privateKey, publicKey }))); };
8,409
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/globalOperations.ts
import { CryptoProxy, VERIFICATION_STATUS } from '@proton/crypto'; import { getContact, updateContact } from '../api/contacts'; import { CONTACT_CARD_TYPE } from '../constants'; import { Api, DecryptedKey, Key } from '../interfaces'; import { Contact } from '../interfaces/contacts'; import { splitKeys } from '../keys/keys'; import { getKeyUsedForContact } from './keyVerifications'; import { resignCards } from './resign'; /** * Process all contacts and update each of them without the content encrypted with the given key */ export const dropDataEncryptedWithAKey = async ( contacts: Contact[], referenceKey: Key, userKeys: DecryptedKey[], api: Api, progressionCallback: (progress: number, updated: number) => void, exitRef: { current: boolean } ) => { let updated = 0; const { privateKeys } = splitKeys(userKeys); for (let i = 0; i < contacts.length && !exitRef.current; i++) { const contactID = contacts[i].ID; const { Contact } = await api<{ Contact: Contact }>(getContact(contactID)); const match = await getKeyUsedForContact(Contact, [referenceKey], true); if (match) { updated++; const Cards = await Promise.all( Contact.Cards.filter( (card) => card.Type !== CONTACT_CARD_TYPE.ENCRYPTED && card.Type !== CONTACT_CARD_TYPE.ENCRYPTED_AND_SIGNED ).map(async (card) => { let { Signature } = card; if (card.Type === CONTACT_CARD_TYPE.SIGNED) { const signature = await CryptoProxy.signMessage({ textData: card.Data, stripTrailingSpaces: true, signingKeys: [privateKeys[0]], detached: true, }); Signature = signature; } return { ...card, Signature }; }) ); await api<{ Contact: Contact }>(updateContact(contactID, { Cards })); // console.log('dropDataEncryptedWithAKey', updateContact(contactID, { Cards })); } progressionCallback(i + 1, updated); } }; /** * Process all contacts and resign each of them with the given key */ export const resignAllContacts = async ( contacts: Contact[], userKeys: DecryptedKey[], api: Api, progressionCallback: (progress: number, updated: number) => void, exitRef: { current: boolean } ) => { let updated = 0; const { publicKeys, privateKeys } = splitKeys(userKeys); for (let i = 0; i < contacts.length && !exitRef.current; i++) { const contactID = contacts[i].ID; const { Contact } = await api<{ Contact: Contact }>(getContact(contactID)); // Should only be one signed card const signedCard = Contact.Cards.find((card) => card.Type === CONTACT_CARD_TYPE.SIGNED); if (!signedCard || !signedCard.Signature) { progressionCallback(i + 1, updated); continue; } const { verified } = await CryptoProxy.verifyMessage({ textData: signedCard.Data, stripTrailingSpaces: true, verificationKeys: publicKeys, armoredSignature: signedCard.Signature, }); if (verified !== VERIFICATION_STATUS.SIGNED_AND_VALID) { updated++; const Cards = await resignCards({ contactCards: Contact.Cards, privateKeys: [privateKeys[0]], }); await api<{ Contact: Contact }>(updateContact(contactID, { Cards })); // console.log('resignAllContacts', updateContact(contactID, { Cards })); } progressionCallback(i + 1, updated); } };
8,410
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/keyPinning.ts
import { c } from 'ttag'; import { CryptoProxy, PrivateKeyReference, PublicKeyReference } from '@proton/crypto'; import isTruthy from '@proton/utils/isTruthy'; import { CONTACT_CARD_TYPE } from '../constants'; import { CANONICALIZE_SCHEME, canonicalizeEmail } from '../helpers/email'; import { generateProtonWebUID } from '../helpers/uid'; import { ContactCard } from '../interfaces/contacts'; import { VCardProperty } from '../interfaces/contacts/VCard'; import { CRYPTO_PROCESSING_TYPES } from './constants'; import { readSigned } from './decrypt'; import { toKeyProperty } from './keyProperties'; import { createContactPropertyUid, getVCardProperties } from './properties'; import { parseToVCard, vCardPropertiesToICAL } from './vcard'; /** * Pin a public key in a contact. Give to it the highest preference * Public keys need to be passed to check signature validity of signed contact cards * Private keys (typically only the primary one) need to be passed to sign the new contact card with the new pinned key */ interface ParamsUpdate { contactCards: ContactCard[]; emailAddress: string; isInternal: boolean; bePinnedPublicKey: PublicKeyReference; publicKeys: PublicKeyReference[]; privateKeys: PrivateKeyReference[]; } export const pinKeyUpdateContact = async ({ contactCards, emailAddress, isInternal, bePinnedPublicKey, publicKeys, privateKeys, }: ParamsUpdate): Promise<ContactCard[]> => { // get the signed card of the contact that contains the key properties. Throw if there are errors const [signedCard, ...otherCards] = contactCards.reduce<ContactCard[]>((acc, card) => { if (card.Type === CONTACT_CARD_TYPE.SIGNED) { acc.unshift(card); } else { acc.push(card); } return acc; }, []); const readSignedCard = await readSigned(signedCard, { publicKeys }); if (readSignedCard.type !== CRYPTO_PROCESSING_TYPES.SUCCESS) { if (readSignedCard.error) { throw readSignedCard.error; } throw new Error('Unknown error'); } const signedVcard = readSignedCard.data; // get the key properties that correspond to the email address const signedVCard = parseToVCard(signedVcard); const signedProperties = getVCardProperties(signedVCard); const emailProperty = signedProperties.find(({ field, value }) => { const scheme = isInternal ? CANONICALIZE_SCHEME.PROTON : CANONICALIZE_SCHEME.DEFAULT; return ( field === 'email' && canonicalizeEmail(value as string, scheme) === canonicalizeEmail(emailAddress, scheme) ); }); const emailGroup = emailProperty?.group as string; const keyProperties = emailGroup ? signedProperties.filter((prop) => { return prop.field === 'key' && prop.group === emailGroup; }) : undefined; if (!keyProperties) { throw new Error(c('Error').t`The key properties for ${emailAddress} could not be extracted`); } // add the new key as the preferred one const shiftedPrefKeyProperties = keyProperties.map((property) => ({ ...property, params: { ...property.params, pref: String(Number(property.params?.pref) + 1), }, })); const newKeyProperties = [ await toKeyProperty({ publicKey: bePinnedPublicKey, group: emailGroup, index: 0 }), ...shiftedPrefKeyProperties, ]; const untouchedSignedProperties = signedProperties.filter( ({ field, group }) => field !== 'key' || group !== emailGroup ); const newSignedProperties = [...untouchedSignedProperties, ...newKeyProperties]; // sign the new properties const toSignVcard: string = vCardPropertiesToICAL(newSignedProperties).toString(); const signature = await CryptoProxy.signMessage({ textData: toSignVcard, stripTrailingSpaces: true, signingKeys: privateKeys, detached: true, }); const newSignedCard = { Type: CONTACT_CARD_TYPE.SIGNED, Data: toSignVcard, Signature: signature, }; return [newSignedCard, ...otherCards]; }; /** * Create a contact with a pinned key. Set encrypt flag to true * Private keys (typically only the primary one) need to be passed to sign the new contact card with the new pinned key */ interface ParamsCreate { emailAddress: string; name?: string; isInternal: boolean; bePinnedPublicKey: PublicKeyReference; privateKeys: PrivateKeyReference[]; } export const pinKeyCreateContact = async ({ emailAddress, name, isInternal, bePinnedPublicKey, privateKeys, }: ParamsCreate): Promise<ContactCard[]> => { const properties: VCardProperty[] = [ { field: 'fn', value: name || emailAddress, uid: createContactPropertyUid() }, { field: 'uid', value: generateProtonWebUID(), uid: createContactPropertyUid() }, { field: 'email', value: emailAddress, group: 'item1', uid: createContactPropertyUid() }, !isInternal && { field: 'x-pm-encrypt', value: 'true', group: 'item1', uid: createContactPropertyUid() }, !isInternal && { field: 'x-pm-sign', value: 'true', group: 'item1', uid: createContactPropertyUid() }, await toKeyProperty({ publicKey: bePinnedPublicKey, group: 'item1', index: 0 }), ].filter(isTruthy); // sign the properties const toSignVcard: string = vCardPropertiesToICAL(properties).toString(); const signature = await CryptoProxy.signMessage({ textData: toSignVcard, stripTrailingSpaces: true, signingKeys: privateKeys, detached: true, }); const newSignedCard = { Type: CONTACT_CARD_TYPE.SIGNED, Data: toSignVcard, Signature: signature, }; return [newSignedCard]; };
8,411
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/keyProperties.ts
import { CryptoProxy, PublicKeyReference } from '@proton/crypto'; import { arrayToBinaryString, binaryStringToArray, decodeBase64, encodeBase64 } from '@proton/crypto/lib/utils'; import isTruthy from '@proton/utils/isTruthy'; import { MIME_TYPES, PGP_SCHEMES } from '../constants'; import { MimeTypeVcard, PinnedKeysConfig } from '../interfaces'; import { VCardContact, VCardProperty } from '../interfaces/contacts/VCard'; import { compareVCardPropertyByPref, createContactPropertyUid } from './properties'; /** * The only values allowed for a PGP scheme stored in a vCard are * '' for default PGP scheme (meaning we should use the PGPScheme from mailSettings when composing email) * 'pgp-mime' for PGP-Inline scheme * 'pgp-mime' for PGP-MIME scheme */ export const getPGPSchemeVcard = (scheme: string): PGP_SCHEMES | undefined => { // ugly code; typescript to be blamed if (Object.values(PGP_SCHEMES).includes(scheme as PGP_SCHEMES)) { return scheme as PGP_SCHEMES; } return undefined; }; /** * The only values allowed for a MIME type stored in a vCard are * '' for automatic format (meaning we should use DraftMIMEType from mailSettings when composing email) * 'text/plain' for plain text format */ export const getMimeTypeVcard = (mimeType: string): MimeTypeVcard | undefined => { return mimeType === MIME_TYPES.PLAINTEXT ? mimeType : undefined; }; export const getKeyVCard = async (keyValue: string): Promise<PublicKeyReference | undefined> => { const [, base64 = ''] = keyValue.split(','); const key = binaryStringToArray(decodeBase64(base64)); if (key.length) { const publicKey = await CryptoProxy.importPublicKey({ binaryKey: key }); return publicKey; } }; /** * Given an array of vCard properties, extract the keys and key-related fields relevant for an email address */ export const getKeyInfoFromProperties = async ( vCardContact: VCardContact, emailGroup: string ): Promise<Omit<PinnedKeysConfig, 'isContactSignatureVerified' | 'isContact'>> => { const getByGroup = <T>(properties: VCardProperty<T>[] = []): VCardProperty<T> | undefined => properties.find(({ group }) => group === emailGroup); const pinnedKeyPromises = (vCardContact.key || []) .filter(({ group }) => group === emailGroup) .sort(compareVCardPropertyByPref) .map(async ({ value }) => getKeyVCard(value)); const pinnedKeys = (await Promise.all(pinnedKeyPromises)).filter(isTruthy); const encryptToPinned = 'x-pm-encrypt' in vCardContact ? getByGroup(vCardContact['x-pm-encrypt'])?.value : undefined; const encryptToUntrusted = 'x-pm-encrypt-untrusted' in vCardContact ? getByGroup(vCardContact['x-pm-encrypt-untrusted'])?.value : undefined; const scheme = getByGroup(vCardContact['x-pm-scheme'])?.value; const mimeType = getByGroup(vCardContact['x-pm-mimetype'])?.value; const sign = getByGroup(vCardContact['x-pm-sign'])?.value; return { pinnedKeys, encryptToPinned, encryptToUntrusted, scheme, mimeType, sign }; }; interface VcardPublicKey { publicKey: PublicKeyReference; group: string; index: number; } /** * Transform a key into a vCard property */ export const toKeyProperty = async ({ publicKey, group, index }: VcardPublicKey): Promise<VCardProperty<string>> => { const binaryKey = await CryptoProxy.exportPublicKey({ key: publicKey, format: 'binary' }); return { field: 'key', value: `data:application/pgp-keys;base64,${encodeBase64(arrayToBinaryString(binaryKey))}`, group, params: { pref: String(index + 1) }, // order is important uid: createContactPropertyUid(), }; };
8,412
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/keyVerifications.ts
import { CryptoProxy, KeyID } from '@proton/crypto'; import { CONTACT_CARD_TYPE } from '../constants'; import { Key } from '../interfaces'; import { Contact } from '../interfaces/contacts'; export interface KeyWithIds { key: Key; ids: KeyID[]; } /** * Get all the key ids of each user keys */ export const getUserKeyIds = async (userKeys: Key[]) => { return Promise.all( userKeys.map(async (userKey) => { const keyInfo = await CryptoProxy.getKeyInfo({ armoredKey: userKey.PrivateKey }); return { key: userKey, ids: keyInfo.keyIDs } as KeyWithIds; }) ); }; /** * Get all key ids of the encryption keys of the cards of a contact * Technically each cards could be encrypted with different keys but it should never happen * So we simplify by returning a flatten array of keys */ export const getContactKeyIds = async (contact: Contact, fromEncryption: boolean) => { const selectedCards = contact?.Cards.filter((card) => fromEncryption ? card.Type === CONTACT_CARD_TYPE.ENCRYPTED_AND_SIGNED || card.Type === CONTACT_CARD_TYPE.ENCRYPTED : card.Type === CONTACT_CARD_TYPE.ENCRYPTED_AND_SIGNED || card.Type === CONTACT_CARD_TYPE.SIGNED ) || []; return ( await Promise.all( selectedCards.map(async (card) => { const keyIDs = fromEncryption ? await CryptoProxy.getMessageInfo({ armoredMessage: card.Data }).then( ({ encryptionKeyIDs }) => encryptionKeyIDs ) : await CryptoProxy.getSignatureInfo({ armoredSignature: card.Signature as string }).then( ({ signingKeyIDs }) => signingKeyIDs ); return keyIDs; }) ) ).flat(); }; /** * Return first match of the keyWithIds in the keyIds list */ export const matchKeys = (keysWithIds: KeyWithIds[], keyIdsToFind: KeyID[]) => { const result = keysWithIds.find(({ ids }) => ids.some((idFromKey) => keyIdsToFind.includes(idFromKey))); return result?.key; }; /** * Get user key used to encrypt this contact considering there is only one */ export const getKeyUsedForContact = async (contact: Contact, userKeys: Key[], fromEncryption: boolean) => { const userKeysIds = await getUserKeyIds(userKeys); const contactKeyIds = await getContactKeyIds(contact, fromEncryption); return matchKeys(userKeysIds, contactKeyIds); };
8,413
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/properties.ts
import generateUID from '../helpers/generateUID'; import { ContactValue } from '../interfaces/contacts'; import { VCardContact, VCardProperty } from '../interfaces/contacts/VCard'; import { UID_PREFIX } from './constants'; import { isMultiValue } from './vcard'; export const FIELDS_WITH_PREF = ['fn', 'email', 'tel', 'adr', 'key', 'photo']; export const getStringContactValue = (value: ContactValue): string => { if (Array.isArray(value)) { return getStringContactValue(value[0]); } // Shouldnt really happen but some boolean gets there as boolean instead of strings return String(value); }; /** * Given a vCard field, return true if we take into consideration its PREF parameters */ export const hasPref = (field: string) => FIELDS_WITH_PREF.includes(field); /** * For a vCard contact, check if it contains categories */ export const hasCategories = (vcardContact: VCardProperty[]) => { return vcardContact.some(({ field, value }) => value && field === 'categories'); }; /** * Extract categories from a vCard contact */ export const getContactCategories = (contact: VCardContact) => { return (contact.categories || []) .map(({ value, group }) => { if (Array.isArray(value)) { return group ? value.map((singleValue) => ({ name: getStringContactValue(singleValue), group })) : value.map((singleValue) => ({ name: getStringContactValue(singleValue) })); } return group ? { name: value, group } : { name: value }; }) .flat(); }; /** * Generate new group name that doesn't exist */ export const generateNewGroupName = (existingGroups: string[] = []): string => { let index = 1; let found = false; while (!found) { if (existingGroups.includes(`item${index}`)) { index++; } else { found = true; } } return `item${index}`; }; /** * Extract emails from a vCard contact */ export const getContactEmails = (contact: VCardContact) => { return (contact.email || []).map(({ value, group }) => { if (!group) { throw new Error('Email properties should have a group'); } return { email: getStringContactValue(value), group, }; }); }; export const createContactPropertyUid = () => generateUID(UID_PREFIX); export const getContactPropertyUid = (uid: string) => Number(uid.replace(`${UID_PREFIX}-`, '')); // TODO: Deprecate this function. See VcardProperty interface export const getVCardProperties = (vCardContact: VCardContact): VCardProperty[] => { return Object.values(vCardContact).flatMap((property) => { if (Array.isArray(property)) { return property; } else { return [property]; } }); }; export const fromVCardProperties = (vCardProperties: VCardProperty[]): VCardContact => { const vCardContact = {} as VCardContact; vCardProperties.forEach((property) => { const field = property.field as keyof VCardContact; if (isMultiValue(field)) { if (!vCardContact[field]) { vCardContact[field] = [] as any; } (vCardContact[field] as VCardProperty[]).push(property); } else { vCardContact[field] = property as any; } }); return vCardContact; }; export const mergeVCard = (vCardContacts: VCardContact[]): VCardContact => { return fromVCardProperties(vCardContacts.flatMap(getVCardProperties)); }; export const updateVCardContact = (vCardContact: VCardContact, vCardProperty: VCardProperty) => { const properties = getVCardProperties(vCardContact); const newProperties = properties.map((property) => (property.uid === vCardProperty.uid ? vCardProperty : property)); return fromVCardProperties(newProperties); }; export const addVCardProperty = (vCardContact: VCardContact, vCardProperty: VCardProperty) => { const properties = getVCardProperties(vCardContact); const newVCardProperty = { ...vCardProperty, uid: createContactPropertyUid() }; properties.push(newVCardProperty); const newVCardContact = fromVCardProperties(properties); return { newVCardProperty, newVCardContact }; }; export const removeVCardProperty = (vCardContact: VCardContact, uid: string) => { let properties = getVCardProperties(vCardContact); const match = properties.find((property) => property.uid === uid); if (!match) { return vCardContact; } properties = properties.filter((property) => property.uid !== uid); // If we remove an email with groups attached to it, remove all groups properties too if (match.field === 'email' && match.group !== undefined) { properties = properties.filter((property) => property.group !== match.group); } // Never remove the last photo property if (match.field === 'photo') { const photoCount = properties.filter((property) => property.field === 'photo').length; if (photoCount === 0) { properties.push({ field: 'photo', value: '', uid: generateUID(UID_PREFIX) }); } } return fromVCardProperties(properties); }; export const compareVCardPropertyByUid = (a: VCardProperty, b: VCardProperty) => { const aUid = getContactPropertyUid(a.uid); const bUid = getContactPropertyUid(b.uid); return aUid > bUid ? 1 : -1; }; export const compareVCardPropertyByPref = (a: VCardProperty, b: VCardProperty) => { const aPref = Number(a.params?.pref); const bPref = Number(b.params?.pref); if (!isNaN(aPref) && !isNaN(bPref) && aPref !== bPref) { return aPref > bPref ? 1 : -1; } return compareVCardPropertyByUid(a, b); }; export const getSortedProperties = (vCardContact: VCardContact, field: string) => { return getVCardProperties(vCardContact) .filter((property) => property.field === field) .sort(compareVCardPropertyByPref); };
8,414
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/property.ts
import { isValid, parseISO } from 'date-fns'; import { VCardDateOrText, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { ContactValue } from '../interfaces/contacts'; import { CONTACT_FIRST_LAST_NAME_MAX_LENGTH, CONTACT_NAME_MAX_LENGTH } from './constants'; import { isDateTextValue, isValidDateValue } from './vcard'; const UNESCAPE_REGEX = /\\\\|\\,|\\;/gi; const UNESCAPE_EXTENDED_REGEX = /\\\\|\\:|\\,|\\;/gi; const BACKSLASH_SEMICOLON_REGEX = /\\;/gi; const ANIMALS = '🐶 🐱 🐭 🐹 🐰 🦊 🐻 🐼'; const SPECIAL_CHARACTER_REGEX = /🐶 🐱 🐭 🐹 🐰 🦊 🐻 🐼/gi; /** * Unescape a vcard value (with \). * If extended is a Boolean === true, we can unescape : too. * ex: for a base64 */ export const unescapeVcardValue = (value = '', extended = false) => { // If we do map(unescapeValue) we still want the default unescape const reg = extended !== true ? UNESCAPE_REGEX : UNESCAPE_EXTENDED_REGEX; return value.replace(reg, (val) => val.substring(1)); }; /** * To avoid problem with the split on ; we need to replace \; first and then re-inject the \; * There is no negative lookbehind in JS regex * See https://github.com/ProtonMail/Angular/issues/6298 */ export const cleanMultipleValue = (value: string = '') => { return value .replace(BACKSLASH_SEMICOLON_REGEX, ANIMALS) .split(';') .map((value) => value.replace(SPECIAL_CHARACTER_REGEX, '\\;')) .map((value) => unescapeVcardValue(value)); }; /** * ICAL library can crash if the value saved in the vCard is improperly formatted * If it crash we get the raw value from jCal key */ const getRawValues = (property: any): string[] => { try { return property.getValues(); } catch (error: any) { const [, , , value = ''] = property.jCal || []; return [value]; } }; /** * Get the value of an ICAL property * * @return currently an array for the fields adr and categories, a string otherwise */ export const getValue = (property: any, field: string): ContactValue => { const values = getRawValues(property).map((val: string | string[] | Date) => { /* To avoid unintended CRLF sequences inside the values of vCard address fields (those are interpreted as field separators unless followed by a space), we sanitize string values ICAL.parse transforms the first occurence of \\r\\n in \\r\n, so we need to sanitize both \\r\n and \\r\\n */ const sanitizeStringValue = (value: string) => value.replaceAll('\\r\n', ' ').replaceAll('\\r\\n', ' ').replaceAll('\\n', ' ').replaceAll('\n', ' '); // adr if (Array.isArray(val)) { if (property.name === 'adr') { return val.map((value) => Array.isArray(value) ? value.map(sanitizeStringValue) : sanitizeStringValue(value) ); } return val; } if (typeof val === 'string') { if (property.name === 'adr') { return sanitizeStringValue(val); } return val; } // date return val.toString(); }); // In some rare situations, ICAL can miss the multiple value nature of an 'adr' or 'org' field // It has been reproduced after a contact import from iOS including the address in a group // For that specific case, we have to split values manually if ((field === 'adr' || field === 'org') && typeof values[0] === 'string') { return cleanMultipleValue(values[0]); } // If one of the adr or org sections contains unescaped `,` // ICAL will return a value of type (string | string[])[] // Which we don't support later in the code // Until we do, we flatten the value by joining these entries if (field === 'adr' || field === 'org') { values[0] = (values[0] as (string | string[])[]).map((entry) => Array.isArray(entry) ? entry.join(', ') : entry ); } if (field === 'categories') { // the ICAL library will parse item1.CATEGORIES:cat1,cat2 with value ['cat1,cat2'], but we expect ['cat1', 'cat2'] const flatValues = values.flat(2); const splitValues = flatValues.map((value) => value.split(',')); return splitValues.flat(); } return values[0]; }; /** * Transform a custom type starting with 'x-' into normal type */ export const clearType = (type = ''): string => type.toLowerCase().replace('x-', ''); /** * Given types in an array, return the first type. If types is a string already, return it */ export const getType = (types: string | string[] = []): string => { if (Array.isArray(types)) { if (!types.length) { return ''; } return types[0]; } return types; }; /** * Tries to get a valid date from a string * Returns a valid date only if string is on a valid ISO or string format * @param text string to convert into a valid date */ export const guessDateFromText = (text: string) => { // Try to get a date from a ISO format (e.g. "2014-02-11T11:30:30") const isoDate = parseISO(text); if (isValid(isoDate)) { return isoDate; } // Try to get a date from a valid string format (e.g. "Jun 9, 2022") const textToDate = new Date(text); if (isValid(textToDate)) { return textToDate; } }; /** * Get a date from a VCardProperty<VCardDateOrText>. * Returns the vCardProperty.date if present and valid * Or tries to return the converted date from vCardProperty.text * If none of the above, return today date * @param vCardProperty birthday or anniversary vCardProperty */ export const getDateFromVCardProperty = ({ value = {} }: VCardProperty<VCardDateOrText>, fallbackDate?: Date) => { if (isValidDateValue(value) && isValid(value.date)) { return value.date; } else if (isDateTextValue(value)) { // Try to convert the text into a valid date const textToDate = guessDateFromText(value.text); if (textToDate) { return textToDate; } } return fallbackDate || new Date(); }; /** * Check that the contact name is valid, the backend has a limit of 190 chars for a contact name */ export const isContactNameValid = (contactName: string) => { return contactName.length <= CONTACT_NAME_MAX_LENGTH; }; export const isFirstLastNameValid = (name: string) => { return name.length <= CONTACT_FIRST_LAST_NAME_MAX_LENGTH; };
8,415
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/resign.ts
import { CryptoProxy, PrivateKeyReference } from '@proton/crypto'; import { CONTACT_CARD_TYPE } from '../constants'; import { ContactCard } from '../interfaces/contacts'; /** * Re-sign contact cards * Private keys (typically only the primary one) need to be passed to re-sign the contact cards * No public key is needed as we don't do signature verification (since we are re-signing anyway) */ interface Params { contactCards: ContactCard[]; privateKeys: PrivateKeyReference[]; } export const resignCards = async ({ contactCards, privateKeys }: Params): Promise<ContactCard[]> => { const signedCards = contactCards.filter((card) => card.Type === CONTACT_CARD_TYPE.SIGNED); const otherCards = contactCards.filter((card) => card.Type !== CONTACT_CARD_TYPE.SIGNED); const reSignedCards = await Promise.all( signedCards.map(async ({ Data }) => { const signature = await CryptoProxy.signMessage({ textData: Data, stripTrailingSpaces: true, signingKeys: privateKeys, detached: true, }); return { Type: CONTACT_CARD_TYPE.SIGNED, Data, Signature: signature, }; }) ); return [...reSignedCards, ...otherCards]; };
8,416
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/surgery.ts
import { isValid } from 'date-fns'; import { c } from 'ttag'; import isTruthy from '@proton/utils/isTruthy'; import { VCardContact, VCardProperty } from '../interfaces/contacts/VCard'; import { FIELDS_WITH_PREF, compareVCardPropertyByPref, createContactPropertyUid, fromVCardProperties, generateNewGroupName, getVCardProperties, } from './properties'; export const getFallbackFNValue = () => { return c('Default display name vcard').t`Unknown`; }; export const prepareForEdition = (vCardContact: VCardContact) => { const result = { ...vCardContact }; if (!result.fn || result.fn.length === 0) { result.fn = [{ field: 'fn', value: '', uid: createContactPropertyUid() }]; } if (!result.photo || result.photo.length === 0) { result.photo = [{ field: 'photo', value: '', uid: createContactPropertyUid() }]; } if (!result.email || result.email.length === 0) { result.email = [{ field: 'email', value: '', uid: createContactPropertyUid() }]; } if (!result.n) { result.n = { field: 'n', value: { familyNames: [''], givenNames: [''], additionalNames: [''], honorificPrefixes: [''], honorificSuffixes: [''], }, uid: createContactPropertyUid(), }; } return result; }; export const prepareForSaving = (vCardContact: VCardContact) => { const properties = getVCardProperties(vCardContact); const newProperties = properties.filter((property) => { if (property.field === 'adr') { return property.value && Object.values(property.value).some(isTruthy); } if (property.field === 'bday' || property.field === 'aniversary') { return property.value.text || (property.value.date && isValid(property.value.date)); } if (property.field === 'gender') { return isTruthy(property.value?.text); } return isTruthy(property.value); }); const result = fromVCardProperties(newProperties); if (result.categories) { // Array-valued categories pose problems to ICAL (even though a vcard with CATEGORIES:ONE,TWO // will be parsed into a value ['ONE', 'TWO'], ICAL.js fails to transform it back). So we convert // an array-valued category into several properties result.categories = result.categories.flatMap((category) => { if (Array.isArray(category.value)) { return category.value.map((value) => ({ ...category, value })); } else { return [category]; } }); } // Add `pref` to email, adr, tel, key to save order (FIELDS_WITH_PREF as (keyof VCardContact)[]).forEach((field) => { if (result[field] && result[field]) { result[field] = (result[field] as VCardProperty[]) .sort(compareVCardPropertyByPref) .map((property, index) => ({ ...property, params: { ...property.params, pref: index + 1 } })) as any; } }); // Add `group` if missing for email. if (result.email) { const existingGroups = result.email.map(({ group }) => group).filter(isTruthy); result.email = result.email.map((property) => { if (property.group) { return property; } else { const group = generateNewGroupName(existingGroups); existingGroups.push(group); return { ...property, group }; } }); } return result; }; /** * Some contacts might miss the "FN" property, but we expect one for the vCard to be valid. * In that case, use the contact email as FN instead. * If no email is found, return undefined */ export const getSupportedContactName = (contact: VCardContact) => { return contact.email?.[0]?.value; };
8,417
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/vcard.ts
import { format, parseISO } from 'date-fns'; import ICAL from 'ical.js'; import isTruthy from '@proton/utils/isTruthy'; import range from '@proton/utils/range'; import { isValidDate } from '../date/date'; import { readFileAsString } from '../helpers/file'; import { VCardAddress, VCardContact, VCardDateOrText, VCardGenderValue, VCardOrg, VCardProperty, VcardNValue, } from '../interfaces/contacts/VCard'; import { getMimeTypeVcard, getPGPSchemeVcard } from './keyProperties'; import { createContactPropertyUid, getStringContactValue } from './properties'; import { getValue } from './property'; export const ONE_OR_MORE_MUST_BE_PRESENT = '1*'; export const EXACTLY_ONE_MUST_BE_PRESENT = '1'; export const EXACTLY_ONE_MAY_BE_PRESENT = '*1'; export const ONE_OR_MORE_MAY_BE_PRESENT = '*'; export const PROPERTIES: { [key: string]: { cardinality: string } } = { fn: { cardinality: ONE_OR_MORE_MUST_BE_PRESENT }, n: { cardinality: EXACTLY_ONE_MAY_BE_PRESENT }, nickname: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, photo: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, bday: { cardinality: EXACTLY_ONE_MAY_BE_PRESENT }, anniversary: { cardinality: EXACTLY_ONE_MAY_BE_PRESENT }, gender: { cardinality: EXACTLY_ONE_MAY_BE_PRESENT }, adr: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, tel: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, email: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, impp: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, lang: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, tz: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, geo: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, title: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, role: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, logo: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, org: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, member: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, related: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, categories: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, note: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, prodid: { cardinality: EXACTLY_ONE_MAY_BE_PRESENT }, rev: { cardinality: EXACTLY_ONE_MAY_BE_PRESENT }, sound: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, uid: { cardinality: EXACTLY_ONE_MAY_BE_PRESENT }, clientpidmap: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, url: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, version: { cardinality: EXACTLY_ONE_MUST_BE_PRESENT }, key: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, fburl: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, caladruri: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, caluri: { cardinality: ONE_OR_MORE_MAY_BE_PRESENT }, }; export const isMultiValue = (field = '') => { const { cardinality = ONE_OR_MORE_MAY_BE_PRESENT } = PROPERTIES[field] || {}; return [ONE_OR_MORE_MUST_BE_PRESENT, ONE_OR_MORE_MAY_BE_PRESENT].includes(cardinality); }; export const isDateType = (type = '') => { return ( type === 'date' || type === 'time' || type === 'date-time' || type === 'date-and-or-time' || type === 'timestamp' ); }; export const isCustomField = (field = '') => field.startsWith('x-'); const getArrayStringValue = (value: undefined | string | string[]) => { if (!value) { return ['']; } if (!Array.isArray(value)) { return [value]; } return value; }; export const isValidDateValue = (dateOrText?: VCardDateOrText): dateOrText is { date: Date } => { return Boolean(dateOrText && 'date' in dateOrText && dateOrText.date && isValidDate(dateOrText.date)); }; export const isDateTextValue = (dateOrText?: VCardDateOrText): dateOrText is { text: string } => { return Boolean(dateOrText && 'text' in dateOrText && dateOrText.text); }; export const icalValueToNValue = (value: string | string[]): VcardNValue => { // According to vCard RFC https://datatracker.ietf.org/doc/html/rfc6350#section-6.2.2 // N is split into 5 strings or string arrays with different meaning at each position if (Array.isArray(value)) { const [familyNames, givenNames, additionalNames, honorificPrefixes, honorificSuffixes] = value; return { familyNames: getArrayStringValue(familyNames), givenNames: getArrayStringValue(givenNames), additionalNames: getArrayStringValue(additionalNames), honorificPrefixes: getArrayStringValue(honorificPrefixes), honorificSuffixes: getArrayStringValue(honorificSuffixes), }; } return { familyNames: [value], givenNames: [''], additionalNames: [''], honorificPrefixes: [''], honorificSuffixes: [''], }; }; export const icalValueToOrgValue = (value: string | string[]): VCardOrg => { /** * According to vCard RFC https://datatracker.ietf.org/doc/html/rfc6350#section-6.6.4 * ORG can be split into several strings. First one is always `organization name`, following ones are `organizational unit names` */ if (Array.isArray(value)) { const [organizationalName, ...organizationalUnitNames] = value; return { organizationalName, ...(organizationalUnitNames.length ? { organizationalUnitNames: getArrayStringValue(organizationalUnitNames) } : {}), }; } return { organizationalName: value, }; }; export const icalValueToInternalAddress = (adr: string | string[]): VCardAddress => { // Input sanitization const value = (Array.isArray(adr) ? adr : [adr]).map((entry) => getStringContactValue(entry)); if (value.length < 7) { value.push(...range(0, 7 - value.length).map(() => '')); } // According to vCard RFC https://datatracker.ietf.org/doc/html/rfc6350#section-6.3.1 // Address is split into 7 strings with different meaning at each position const [postOfficeBox, extendedAddress, streetAddress, locality, region, postalCode, country] = value; return { postOfficeBox, extendedAddress, streetAddress, locality, region, postalCode, country, }; }; /** * Convert from ical.js format to an internal format */ export const icalValueToInternalValue = (name: string, type: string, property: any) => { const value = getValue(property, name) as string | string[]; if (name === 'n') { return icalValueToNValue(value); } if (name === 'adr') { return icalValueToInternalAddress(value); } if (name === 'bday' || name === 'anniversary') { if (isDateType(type)) { return { date: parseISO(value.toString()) }; } else { return { text: value.toString() }; } } if (name === 'gender') { return { text: value.toString() }; } if (name === 'org') { return icalValueToOrgValue(value); } if (['x-pm-encrypt', 'x-pm-encrypt-untrusted', 'x-pm-sign'].includes(name)) { return value === 'true'; } if (name === 'x-pm-scheme') { return getPGPSchemeVcard(value as string); } if (name === 'x-pm-mimetype') { return getMimeTypeVcard(value as string); } if (Array.isArray(value)) { return value.map((value) => { return value; }); } if (isDateType(type)) { return parseISO(value); } return value; }; const getParameters = (type: string, property: any) => { const allParameters = property.toJSON() || []; const parameters = allParameters[1]; const isDefaultType = type === property.getDefaultType(); const result = { ...parameters, }; if (!isDefaultType) { result.type = type; } return result; }; const parseIcalProperty = (property: any, vCardContact: VCardContact) => { const { name: nameWithGroup } = property; if (!nameWithGroup) { return; } const [group, name]: [string | undefined, keyof VCardContact] = nameWithGroup.includes('.') ? nameWithGroup.split('.') : [undefined, nameWithGroup]; const { type } = property; const value = icalValueToInternalValue(name, type, property); const params = getParameters(type, property); const propertyAsObject = { field: name, value, uid: createContactPropertyUid(), ...(Object.keys(params).length && { params }), ...(group ? { group } : {}), }; if (!isMultiValue(name)) { vCardContact[name] = propertyAsObject as any; return; } if (!vCardContact[name]) { vCardContact[name] = [] as any; } // If we encounter an array value for a field, if it contains only an empty string, // we don't want it to be part on contact properties. // E.g. we have "CATEGORIES:" (with nothing before nor behind) in the vCard // => We need to remove it otherwise the contact will not be exportable because "toString" will fail if (Array.isArray(propertyAsObject.value)) { if (propertyAsObject.value.filter((element) => element !== '').length === 0) { return; } } (vCardContact[name] as any[]).push(propertyAsObject); }; export const parseToVCard = (vcard: string): VCardContact => { const icalComponent = new ICAL.Component(ICAL.parse(vcard)); const properties = icalComponent.getAllProperties() as any[]; const vCardContact = {} as VCardContact; properties.forEach((property) => { parseIcalProperty(property, vCardContact); }); return vCardContact; }; export const internalValueToIcalValue = (name: string, value: any) => { if (name === 'n') { const { familyNames = [''], givenNames = [''], additionalNames = [''], honorificPrefixes = [''], honorificSuffixes = [''], } = value; return [familyNames, givenNames, additionalNames, honorificPrefixes, honorificSuffixes]; } if (name === 'adr') { const { postOfficeBox = '', extendedAddress = '', streetAddress = '', locality = '', region = '', postalCode = '', country = '', } = value; return [postOfficeBox, extendedAddress, streetAddress, locality, region, postalCode, country]; } if (name === 'bday' || name === 'anniversary') { const dateValue: VCardDateOrText = value; if (isValidDateValue(dateValue)) { // As we don't allow to edit times, we assume there's no need of keeping the time part return format(dateValue.date, 'yyyyMMdd'); } else if (isDateTextValue(dateValue)) { return dateValue.text; } else { return ''; } } if (name === 'gender') { const genderValue: VCardGenderValue = value; return genderValue.text || ''; } if (name === 'org') { const orgValue: VCardOrg = value; const { organizationalName, organizationalUnitNames = [] } = orgValue; return [...(organizationalName ? [organizationalName] : []), ...organizationalUnitNames]; } return value; }; // TODO: Deprecate this function. See VcardProperty interface export const vCardPropertiesToICAL = (properties: VCardProperty[]) => { // make sure version (we enforce 4.0) is the first property; otherwise invalid vcards can be generated const versionLessProperties = properties.filter(({ field }) => field !== 'version'); const component = new ICAL.Component('vcard'); const versionProperty = new ICAL.Property('version'); versionProperty.setValue('4.0'); component.addProperty(versionProperty); versionLessProperties.forEach(({ field, params, value, group }) => { const fieldWithGroup = [group, field].filter(isTruthy).join('.'); const property = new ICAL.Property(fieldWithGroup); if (['bday', 'anniversary'].includes(field)) { if (!isValidDateValue(value)) { property.resetType('text'); } } const iCalValue = internalValueToIcalValue(field, value); property.setValue(iCalValue); Object.entries(params || {}).forEach(([key, value]) => { property.setParameter(key, value.toString()); }); component.addProperty(property); }); return component; }; const getProperty = (name: keyof VCardContact, { value, params = {}, group }: any) => { if (!value) { return; } const nameWithGroup = [group, name].filter(isTruthy).join('.'); const property = new ICAL.Property(nameWithGroup); if (['bday', 'anniversary'].includes(name) && !(value.date && isValidDate(value.date))) { property.resetType('text'); } if (property.isMultiValue && Array.isArray(value)) { property.setValues(value.map((val) => internalValueToIcalValue(name, val))); } else { property.setValue(internalValueToIcalValue(name, value)); } Object.keys(params).forEach((key) => { property.setParameter(key, params[key]); }); return property; }; export const serialize = (contact: VCardContact) => { const icalComponent = new ICAL.Component('vcard'); // clear any possible previous version (which could be < 4.0) delete contact.version; const versionProperty = new ICAL.Property('version'); versionProperty.setValue('4.0'); icalComponent.addProperty(versionProperty); // Prefer to put FN at the beginning (not required by RFC) const sortedObjectKeys = Object.keys(contact).sort((property1, property2) => { if (property1 === 'fn') { return -1; } else if (property2 === 'fn') { return 1; } else { return 0; } }) as (keyof VCardContact)[]; sortedObjectKeys.forEach((name) => { const jsonProperty = contact[name]; if (Array.isArray(jsonProperty)) { jsonProperty.forEach((property) => { const data = getProperty(name, property); if (!data) { return; } icalComponent.addProperty(data); }); return; } const data = getProperty(name, jsonProperty); if (!data) { return; } icalComponent.addProperty(data); }); return icalComponent.toString(); }; /** * Basic test for the validity of a vCard file read as a string */ const isValid = (vcf = ''): boolean => { const regexMatchBegin = vcf.match(/BEGIN:VCARD/g); const regexMatchEnd = vcf.match(/END:VCARD/g); if (!regexMatchBegin || !regexMatchEnd) { return false; } return regexMatchBegin.length === regexMatchEnd.length; }; /** * Read a vCard file as a string. If there are errors when parsing the csv, throw */ export const readVcf = async (file: File): Promise<string> => { const vcf = await readFileAsString(file); if (!isValid(vcf)) { throw new Error('Error when reading vcf file'); } return vcf; }; /** * Extract array of vcards from a string containing several vcards */ export const extractVcards = (vcf = ''): string[] => { const strippedEndVcards = vcf.split('END:VCARD'); return strippedEndVcards.filter((line) => isTruthy(line.trim())).map((vcard) => `${vcard}END:VCARD`.trim()); }; export const getContactHasName = (contact: VCardContact) => { return !!contact.fn?.[0]?.value; };
8,418
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/errors/ImportContactError.ts
import { c } from 'ttag'; export enum IMPORT_CONTACT_ERROR_TYPE { UNSUPPORTED_VCARD_VERSION, MISSING_FN, ENCRYPTION_ERROR, EXTERNAL_ERROR, } const getErrorMessage = (errorType: IMPORT_CONTACT_ERROR_TYPE, externalError?: Error) => { if (errorType === IMPORT_CONTACT_ERROR_TYPE.UNSUPPORTED_VCARD_VERSION) { return c('Error importing contact').t`vCard versions < 3.0 not supported`; } if (errorType === IMPORT_CONTACT_ERROR_TYPE.MISSING_FN) { return c('Error importing contact').t`Missing FN property`; } if (errorType === IMPORT_CONTACT_ERROR_TYPE.ENCRYPTION_ERROR) { return c('Error importing contact').t`Encryption failed`; } if (errorType === IMPORT_CONTACT_ERROR_TYPE.EXTERNAL_ERROR) { return externalError?.message || ''; } return ''; }; export class ImportContactError extends Error { contactId: string; type: IMPORT_CONTACT_ERROR_TYPE; externalError?: Error; constructor(errorType: IMPORT_CONTACT_ERROR_TYPE, contactId: string, externalError?: Error) { super(getErrorMessage(errorType, externalError)); this.type = errorType; this.contactId = contactId; this.externalError = externalError; Object.setPrototypeOf(this, ImportContactError.prototype); } }
8,419
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/errors/ImportFatalError.ts
import { c } from 'ttag'; export class ImportFatalError extends Error { error: Error; constructor(error: Error) { super(c('Error importing calendar').t`An unexpected error occurred. Import must be restarted.`); this.error = error; Object.setPrototypeOf(this, ImportFatalError.prototype); } }
8,420
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/errors/ImportFileError.ts
import { c } from 'ttag'; import truncate from '@proton/utils/truncate'; import { MAX_FILENAME_CHARS_DISPLAY, MAX_IMPORT_CONTACTS_STRING, MAX_IMPORT_FILE_SIZE_STRING } from '../constants'; export enum IMPORT_ERROR_TYPE { NO_FILE_SELECTED, NO_CSV_OR_VCF_FILE, FILE_EMPTY, FILE_TOO_BIG, FILE_CORRUPTED, NO_CONTACTS, TOO_MANY_CONTACTS, } const getErrorMessage = (errorType: IMPORT_ERROR_TYPE, filename = '') => { const formattedFilename = `"${truncate(filename, MAX_FILENAME_CHARS_DISPLAY)}"`; if (errorType === IMPORT_ERROR_TYPE.NO_FILE_SELECTED) { return c('Error importing contacts').t`An error occurred uploading your file. No file has been selected.`; } if (errorType === IMPORT_ERROR_TYPE.NO_CSV_OR_VCF_FILE) { return c('Error importing contacts') .t`An error occurred uploading your file ${formattedFilename}. No .csv or .vcf file selected`; } if (errorType === IMPORT_ERROR_TYPE.FILE_EMPTY) { return c('Error importing contacts').t`Your file ${formattedFilename} is empty.`; } if (errorType === IMPORT_ERROR_TYPE.FILE_TOO_BIG) { return c('Error importing contacts') .t`An error occurred uploading your file ${formattedFilename}. Maximum file size is ${MAX_IMPORT_FILE_SIZE_STRING}.`; } if (errorType === IMPORT_ERROR_TYPE.NO_CONTACTS) { return c('Error importing contacts').t`Your file ${formattedFilename} has no contacts to be imported.`; } if (errorType === IMPORT_ERROR_TYPE.TOO_MANY_CONTACTS) { return c('Error importing contacts') .t`Your file ${formattedFilename} contains more than ${MAX_IMPORT_CONTACTS_STRING} contacts.`; } if (errorType === IMPORT_ERROR_TYPE.FILE_CORRUPTED) { return c('Error importing contacts') .t`An error occurred reading your file ${ formattedFilename }. Incorrect file format.`; } }; export class ImportFileError extends Error { constructor(errorType: IMPORT_ERROR_TYPE, filename?: string) { super(getErrorMessage(errorType, filename)); Object.setPrototypeOf(this, ImportFileError.prototype); } }
8,421
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/helpers/address.ts
// Remove all commas at the beginning and at the end of the string import { VCardAddress } from '@proton/shared/lib/interfaces/contacts/VCard'; const trimCommas = (string: string) => { return string.replace(/(^,+|,+$)/g, ''); }; /** * Remove all commas at the beginning and end of each contact address field */ export const cleanAddressFromCommas = (address: VCardAddress) => { const { streetAddress, extendedAddress, postalCode, postOfficeBox, locality, region, country } = address; const trimmed: VCardAddress = { streetAddress: trimCommas(streetAddress), extendedAddress: trimCommas(extendedAddress), postalCode: trimCommas(postalCode), postOfficeBox: trimCommas(postOfficeBox), locality: trimCommas(locality), region: trimCommas(region), country: trimCommas(country), }; return trimmed; };
8,422
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/helpers/array.ts
import move from '@proton/utils/move'; /** * Re-order elements in an array inside a group of arrays */ export const moveInGroup = <T>( collection: T[][], groupIndex: number, { oldIndex, newIndex }: { oldIndex: number; newIndex: number } ) => { return collection.map((group, i) => { if (i === groupIndex) { return move(group, oldIndex, newIndex); } return group; }); };
8,423
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/helpers/contactGroup.ts
import { ContactGroupLimitReachedProps } from '@proton/components/containers/contacts/modals/ContactGroupLimitReachedModal'; import { MailSettings } from '../../interfaces'; import { ContactEmail } from '../../interfaces/contacts'; import { DEFAULT_MAILSETTINGS } from '../../mail/mailSettings'; /** * Check that the user can add other contacts to a contact group. */ export const hasReachedContactGroupMembersLimit = ( numbersOfContacts: number, mailSettings?: MailSettings, strict = true ) => { const { RecipientLimit } = mailSettings || DEFAULT_MAILSETTINGS; return strict ? numbersOfContacts < RecipientLimit : numbersOfContacts <= RecipientLimit; }; /** * Contact groups are limited to 100 contacts. When editing a contact, we do not save directly since the contact might not exist. * Instead, we're doing a delayed save. However, we still need to check that adding the contact to the contact group will be a valid operation. * If the change is valid, we return them, otherwise we need to remove the contact group from the changes requested, and display a modal */ export const getContactGroupsDelayedSaveChanges = ({ userContactEmails, changes, initialModel, model, onLimitReached, mailSettings, }: { userContactEmails: ContactEmail[]; changes: { [groupID: string]: boolean }; model: { [groupID: string]: number }; initialModel: { [groupID: string]: number }; onLimitReached?: (props: ContactGroupLimitReachedProps) => void; mailSettings?: MailSettings; }) => { // Get number of contacts in saved contact groups const groupIDs = Object.keys(changes); const cannotAddContactInGroupIDs: string[] = []; groupIDs.forEach((groupID) => { const groupExistingMembers = groupID && userContactEmails.filter(({ LabelIDs = [] }: { LabelIDs: string[] }) => LabelIDs.includes(groupID)); // Check that adding the current contact would not exceed the limit const canAddContact = hasReachedContactGroupMembersLimit(groupExistingMembers.length, mailSettings); if (!canAddContact) { cannotAddContactInGroupIDs.push(groupID); } }); // If some addition were exceeding the limit, we remove them from the change array and display a modal to inform the user if (cannotAddContactInGroupIDs.length > 0) { const updatedChanges = Object.entries(model).reduce<{ [groupID: string]: boolean; }>((acc, [groupID, isChecked]) => { if (isChecked !== initialModel[groupID] && !cannotAddContactInGroupIDs.includes(groupID)) { acc[groupID] = isChecked === 1; } return acc; }, {}); onLimitReached?.({ groupIDs: cannotAddContactInGroupIDs }); return updatedChanges; } else { return changes; } };
8,424
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/helpers/csv.ts
import Papa from 'papaparse'; import { IMPORT_CONTACT_ERROR_TYPE, ImportContactError } from '@proton/shared/lib/contacts/errors/ImportContactError'; import { getContactId, getSupportedContactProperties, splitErrors } from '@proton/shared/lib/contacts/helpers/import'; import isTruthy from '@proton/utils/isTruthy'; import range from '@proton/utils/range'; import { getAllTypes } from '../../helpers/contacts'; import { ParsedCsvContacts, PreVcardProperty, PreVcardsContact, PreVcardsProperty, } from '../../interfaces/contacts/Import'; import { VCardContact, VCardKey, VCardProperty } from '../../interfaces/contacts/VCard'; import { createContactPropertyUid, fromVCardProperties, generateNewGroupName } from '../properties'; import { combine, standarize, toPreVcard } from './csvFormat'; interface PapaParseOnCompleteArgs { data?: string[][]; errors?: any[]; } /** * Get all csv properties and corresponding contacts values from a csv file. * If there are errors when parsing the csv, throw * @dev contacts[i][j] : value for property headers[j] of contact i */ export const readCsv = async (file: File) => { const { headers, contacts: parsedContacts, errors, }: { headers: string[]; contacts: string[][]; errors: any[] } = await new Promise((resolve, reject) => { const onComplete = ({ data = [], errors = [] }: PapaParseOnCompleteArgs = {}) => resolve({ headers: data[0], contacts: data.slice(1), errors }); Papa.parse(file, { // If true, the first row of parsed data will be interpreted as field names. An array of field names will be returned in meta, // and each row of data will be an object of values keyed by field name instead of a simple array. // Rows with a different number of fields from the header row will produce an error. header: false, // If true, numeric and Boolean data will be converted to their type instead of remaining strings. dynamicTyping: false, complete: onComplete, error: reject, // If true, lines that are completely empty will be skipped. An empty line is defined to be one which evaluates to empty string. skipEmptyLines: true, }); }); if (errors.length) { throw new Error('Error when reading csv file'); } // Papaparse will produce data according to the CSV content // There is no security about having same numbers of fields on all lines // So we do a pass of sanitization to clean up data const headersLength = headers.length; const contacts = parsedContacts.map((contact) => { if (contact.length === headersLength) { return contact; } if (contact.length > headersLength) { return contact.slice(0, headersLength); } return [...contact, ...range(0, headersLength - contact.length).map(() => '')]; }); return { headers, contacts }; }; /** * Transform csv properties and csv contacts into pre-vCard contacts. * @param {Object} csvData * @param {Array<String>} csvData.headers Array of csv properties * @param {Array<Array<String>>} csvData.contacts Array of csv contacts * * @return {Array<Array<Object>>} pre-vCard contacts * * @dev Some csv property may be assigned to several pre-vCard contacts, * so an array of new headers is returned together with the pre-vCard contacts */ const parse = ({ headers = [], contacts = [] }: ParsedCsvContacts): PreVcardsProperty[] => { if (!contacts.length) { return []; } const { headers: enrichedHeaders, contacts: standardContacts } = standarize({ headers, contacts }) || {}; if (!enrichedHeaders?.length || !standardContacts?.length) { return []; } const translator = enrichedHeaders.map(toPreVcard); return standardContacts .map((contact) => contact .map((value, i) => translator[i](value)) // some headers can be mapped to several properties, so we need to flatten .flat() ) .map((contact) => contact.filter((preVcard) => !!preVcard)) as PreVcardsProperty[]; }; /** * Transform csv properties and csv contacts into pre-vCard contacts, * re-arranging them in the process * * @dev headers are arranged as headers = [[group of headers to be combined in a vCard], ...] * preVcardContacts is an array of pre-vCard contacts, each of them containing pre-vCards * arranged in the same way as the headers: * preVcardContacts = [[[group of pre-vCard properties to be combined], ...], ...] */ export const prepare = ({ headers = [], contacts = [] }: ParsedCsvContacts) => { const preVcardContacts = parse({ headers, contacts }); if (!preVcardContacts.length) { return []; } // detect csv properties to be combined in preVcardContacts and split header indices const nonCombined: number[] = []; const combined = preVcardContacts[0].reduce<{ [key: string]: number[] }>( (acc, { combineInto, combineIndex: j }, i) => { if (combineInto) { if (!acc[combineInto]) { acc[combineInto] = []; } acc[combineInto][j as number] = i; // combined will look like e.g. // { 'fn-main': [2, <empty item(s)>, 3, 5, 1], 'fn-yomi': [<empty item(s)>, 6, 7] } return acc; } nonCombined.push(i); return acc; }, {} ); for (const combination of Object.keys(combined)) { // remove empty items from arrays in combined combined[combination] = combined[combination].filter((n) => n !== null); } // Arrange pre-vCards respecting the original ordering outside header groups const preparedPreVcardContacts: PreVcardsContact[] = contacts.map(() => []); for (const [i, indices] of Object.values(combined).entries()) { preparedPreVcardContacts.forEach((contact) => contact.push([])); indices.forEach((index) => { preparedPreVcardContacts.forEach((contact, k) => contact[i].push({ ...preVcardContacts[k][index], }) ); }); } for (const index of nonCombined) { preparedPreVcardContacts.forEach((contact, k) => contact.push([preVcardContacts[k][index]])); } return preparedPreVcardContacts; }; /** * Combine pre-vCards properties into a single vCard one * @param preVCards Array of pre-vCards properties * @return vCard property */ export const toVCard = (preVCards: PreVcardProperty[]): VCardProperty<any> | undefined => { if (!preVCards.length) { return; } const types = getAllTypes(); const { pref, field, type, custom } = preVCards[0]; // Need to get the default type if the field has a second dropdown to be displayed const defaultType = types[field]?.[0]?.value as VCardKey | undefined; const params: { [key: string]: string } = {}; if (type !== undefined || defaultType !== undefined) { params.type = (type || defaultType) as string; } if (pref !== undefined) { params.pref = String(pref); } return { field, value: custom ? combine.custom(preVCards) : combine[field](preVCards), params, uid: createContactPropertyUid(), }; }; /** * This helper sanitizes multiple-valued email properties that we may get from a CSV import * The RFC does not allow the EMAIL property to have multiple values: https://datatracker.ietf.org/doc/html/rfc6350#section-6.4.2 * Instead, one should use multiple single-valued email properties */ const sanitizeEmailProperties = (contacts: VCardContact[]): VCardContact[] => { return contacts.map((contact) => { if (!contact.email) { return contact; } const existingGroups = contact.email.map(({ group }) => group).filter(isTruthy); return { ...contact, email: contact.email .flatMap((property) => { if (!Array.isArray(property.value)) { return [property]; } // If the property is an email having an array of emails as value return property.value.map((value) => { return { ...property, value }; }); }) .map((property) => { if (property.group) { return property; } const group = generateNewGroupName(existingGroups); existingGroups.push(group); return { ...property, group }; }), }; }); }; /** * Transform pre-vCards contacts into vCard contacts */ export const toVCardContacts = ( preVcardsContacts: PreVcardsContact[] ): { errors: ImportContactError[]; rest: VCardContact[] } => { const vcards = preVcardsContacts.map((preVcardsContact) => { const contact = fromVCardProperties(preVcardsContact.map(toVCard).filter(isTruthy)); const contactId = getContactId(contact); try { return getSupportedContactProperties(contact); } catch (error: any) { return new ImportContactError(IMPORT_CONTACT_ERROR_TYPE.EXTERNAL_ERROR, contactId, error); } }); const { errors, rest: parsedVcardContacts } = splitErrors(vcards); const contacts = sanitizeEmailProperties(parsedVcardContacts); return { errors, rest: contacts }; };
8,425
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/helpers/csvFormat.ts
import { guessDateFromText } from '@proton/shared/lib/contacts/property'; import capitalize from '@proton/utils/capitalize'; import isTruthy from '@proton/utils/isTruthy'; import { normalize } from '../../helpers/string'; import { ContactValue } from '../../interfaces/contacts'; import { Combine, Display, ParsedCsvContacts, PreVcardProperty, PreVcardsProperty, } from '../../interfaces/contacts/Import'; import { VCardOrg } from '../../interfaces/contacts/VCard'; import { getStringContactValue } from '../properties'; import { icalValueToInternalAddress, icalValueToNValue, icalValueToOrgValue } from '../vcard'; // See './csv.ts' for the definition of pre-vCard and pre-vCards contact // Csv properties to be ignored const beIgnoredCsvProperties = [ 'initials', 'short name', 'maiden name', 'group membership', 'mileage', 'billing information', 'directory server', 'sensitivity', 'priority', 'subject', ]; const beIgnoredCsvPropertiesRegex = [ /e-mail\s?([0-9]*) display name/, // We have to ignore 'E-mail Display Name' and 'E-mail [NUMBER] Display Name' headers ]; /** * For a list of headers and csv contacts extracted from a csv, * check if a given header index has the empty value for all contacts */ const isEmptyHeaderIndex = (index: number, contacts: string[][]) => !contacts.some((values) => values[index] !== ''); /** * Standarize a custom vcard type coming from a csv property * @param {String} csvType * * @return {String} */ const toVcardType = (csvType = '') => { const type = csvType.toLowerCase(); switch (type) { case 'home': return 'home'; case 'business': return 'work'; case 'work': return 'work'; case 'mobile': return 'cell'; case 'cell': return 'cell'; case 'other': return 'other'; case 'main': return 'main'; case 'primary': return 'main'; case 'company main': return 'work'; case 'pager': return 'pager'; case 'home fax': return 'fax'; case 'work fax': return 'fax'; default: return ''; } }; /** * Given csv properties and csv contacts from any csv file, transform the properties * into csv properties from a standard outlook csv. Transform the contacts accordingly */ export const standarize = ({ headers, contacts }: ParsedCsvContacts) => { if (!contacts.length) { return; } // Vcard model does not allow multiple instances of these headers const uniqueHeaders = ['birthday', 'anniversary', 'gender']; const uniqueHeadersEncounteredStatusMap = new Map(); uniqueHeaders.forEach((header) => uniqueHeadersEncounteredStatusMap.set(header, false)); // do a first simple formatting of headers const formattedHeaders = headers.map((header) => header.replace('_', ' ').toLowerCase()); // change name of certain headers into outlook equivalents // remove headers we are not interested in // merge headers 'xxx - type' and 'xxx - value' into one header const { beRemoved, beChanged } = formattedHeaders.reduce<{ beRemoved: { [key: number]: boolean }; beChanged: { [key: number]: string }; }>( (acc, header, i) => { const { beRemoved, beChanged } = acc; const value = contacts[0][i]; if (isEmptyHeaderIndex(i, contacts)) { beRemoved[i] = true; } if ( beIgnoredCsvProperties.includes(header) || header.startsWith('im') || header.includes('event') || beIgnoredCsvPropertiesRegex.some((regex) => regex.test(header)) ) { beRemoved[i] = true; return acc; } // Remove header if we don't allow multiple instances and it has already been encountered if (uniqueHeaders.includes(header)) { if (!uniqueHeadersEncounteredStatusMap.get(header)) { uniqueHeadersEncounteredStatusMap.set(header, true); } else { beRemoved[i] = true; } } if (header === 'address') { beChanged[i] = 'street'; } if (header === 'zip') { beChanged[i] = 'postal code'; } if (header === 'county') { beChanged[i] = 'state'; } /* consecutive headers for address n property are (n is an integer) * address n - type * address n - formatted * address n - street * address n - city * address n - PO box * address n - region * address n - postal code * address n - country * address n - extended address we have to drop the first two headers and change the rest accordingly */ const addressMatch = header.match(/^address\s?\d+? - type$/); if (addressMatch) { const [, pref] = addressMatch; const n = pref || ''; beRemoved[i] = true; beRemoved[i + 1] = true; beChanged[i + 2] = `${capitalize(toVcardType(value))} Street ${n}`.trim(); beChanged[i + 3] = `${capitalize(toVcardType(value))} City ${n}`.trim(); beChanged[i + 4] = `${capitalize(toVcardType(value))} PO Box ${n}`.trim(); beChanged[i + 5] = `${capitalize(toVcardType(value))} State ${n}`.trim(); beChanged[i + 6] = `${capitalize(toVcardType(value))} Postal Code ${n}`.trim(); beChanged[i + 7] = `${capitalize(toVcardType(value))} Country ${n}`.trim(); beChanged[i + 8] = `${capitalize(toVcardType(value))} Extended Address ${n}`.trim(); return acc; } /* consecutive headers for organization n property are (n is an integer) * organization n - type * organization n - name * organization n - yomi name * organization n - title * organization n - department * organization n - symbol * organization n - location * organization n - job description we can simply keep the name, title and department changing the corresponding header */ const organizationMatch = header.match(/^organization\s?\d+? - (\w+)$/); if (organizationMatch) { const [, str] = organizationMatch; if (str === 'name') { beChanged[i] = 'Company'; } else if (str === 'title') { beChanged[i] = 'Job Title'; } else if (str === 'department') { beChanged[i] = 'Department'; } else if (str === 'job description') { beChanged[i] = 'Role'; } else { beRemoved[i] = true; } return acc; } /* consecutive headers for generic property with type are * property - type * property - value we have to erase the first header and change the second one accordingly */ const genericMatch = header.match(/(.*) - type$/i); if (genericMatch) { const [, property] = genericMatch; beRemoved[i] = true; beChanged[i + 1] = `${capitalize(toVcardType(value))} ${property}`.trim(); return acc; } return acc; }, { beRemoved: {}, beChanged: {} } ); const enrichedHeaders = formattedHeaders .map((header, index) => { const original = headers[index]; return { original, standard: beChanged[index] ? beChanged[index] : header }; }) .filter((_header, index) => !beRemoved[index]); const standardContacts = contacts.map((values) => values.filter((_value, j) => !beRemoved[j])); return { headers: enrichedHeaders, contacts: standardContacts }; }; interface TemplateArgs { header: string; value: ContactValue; index?: number; type?: string; pref?: number; } const templates = { fn({ header, value, index }: TemplateArgs) { return { header, value, checked: true, pref: 1, field: 'fn', combineInto: 'fn-main', combineIndex: index, }; }, n({ header, value, index }: TemplateArgs) { return { header, value, checked: true, pref: 1, field: 'n', combineInto: 'n-main', combineIndex: index, }; }, fnYomi({ header, value, index }: TemplateArgs) { return { header, value, checked: true, pref: 2, field: 'fn', combineInto: 'fn-yomi', combineIndex: index, }; }, email({ pref, header, value, type }: TemplateArgs) { const googleSeparator = ' ::: '; if (typeof value === 'string' && value.includes(googleSeparator)) { /* * Google CSV may contain several emails in a field such as * "[email protected] ::: [email protected] ::: [email protected]" * We split the value to create a string[] */ const splitEmails = value.split(googleSeparator).filter(isTruthy); if (splitEmails.length > 1) { return { pref, header, value: splitEmails, checked: true, field: 'email', type, group: pref, }; } } return { pref, header, value, checked: true, field: 'email', type, group: pref, }; }, tel({ pref, header, value, type }: TemplateArgs) { return { pref, header, value, checked: true, field: 'tel', type, }; }, adr({ pref, header, type, value, index }: TemplateArgs) { return { pref, header, value, checked: true, field: 'adr', type, combineInto: `adr-${type}`, combineIndex: index, }; }, org({ pref, header, value, index }: TemplateArgs) { return { pref, header, value, checked: true, field: 'org', combineInto: 'org', combineIndex: index, }; }, }; /** * Given an object with a csv property name (header) in both original and standard form, * return a function that transforms a value for that property into one or several pre-vCard properties * @param {String} enrichedHeader.original * @param {String} enrichedHeader.standard * * * @return {Function} */ export const toPreVcard = ({ original, standard }: { original: string; standard: string }) => { const property = normalize(standard); const header = original; const companyMatch = property.match(/^company\s?(\d*)/); const departmentMatch = property.match(/^department\s?(\d*)/); const emailMatch = property.match(/^(\w+)?\s?e-?mail\s?(\d*)/); const phoneMatch = property.match(/^(\w+\s*\w+)?\s?phone\s?(\d*)$/); const faxMatch = property.match(/^(\w+)?\s?fax\s?(\d*)$/); const pagerMatch = property.match(/^(\w+)?\s?pager\s?(\d*)$/); const telexMatch = property.match(/^callback|telex\s?(\d*)$/); const poBoxMatch = property.match(/^(\w*)\s?po box\s?(\d*)$/); const extAddressMatch = property.match(/^(\w*)\s?extended address\s?(\d*)$/); const streetMatch = property.match(/^(\w*)\s?street\s?(\d*)$/); const cityMatch = property.match(/^(\w*)\s?city\s?(\d*)$/); const stateMatch = property.match(/^(\w*)\s?state\s?(\d*)$/); const postalCodeMatch = property.match(/^(\w*)\s?postal code\s?(\d*)$/); const countryMatch = property.match(/^(\w*)\s?country\s?(\d*)$/); if (['display name', 'name'].includes(property)) { return (value: ContactValue) => [templates.fn({ header, value, index: 1 })]; } if (['last name', 'family name'].includes(property)) { return (value: ContactValue) => [ templates.n({ header, value, index: 0 }), //N field value templates.fn({ header, value, index: 3 }), //FN field value ]; } if (['first name', 'given name'].includes(property)) { return (value: ContactValue) => [ templates.n({ header, value, index: 1 }), //N field value templates.fn({ header, value, index: 1 }), //FN field value ]; } if (['title', 'name prefix'].includes(property)) { return (value: ContactValue) => [templates.fn({ header, value, index: 0 })]; } if (['middle name', 'additional name'].includes(property)) { return (value: ContactValue) => [templates.fn({ header, value, index: 2 })]; } if (['suffix', 'name suffix'].includes(property)) { return (value: ContactValue) => [templates.fn({ header, value, index: 4 })]; } if (['given yomi', 'given name yomi'].includes(property)) { return (value: ContactValue) => templates.fnYomi({ header, value, index: 0 }); } if (['middle name yomi', 'additional name yomi'].includes(property)) { return (value: ContactValue) => templates.fnYomi({ header, value, index: 1 }); } if (['surname yomi', 'family name yomi'].includes(property)) { return (value: ContactValue) => templates.fnYomi({ header, value, index: 2 }); } if (companyMatch) { const pref = companyMatch[1] ? +companyMatch[1] : undefined; return (value: ContactValue) => templates.org({ pref, header, value, index: 0 }); } if (departmentMatch) { const pref = departmentMatch[1] ? +departmentMatch[1] : undefined; return (value: ContactValue) => templates.org({ pref, header, value, index: 1 }); } if (emailMatch) { const type = emailMatch[1] ? emailMatch[1] : undefined; const pref = emailMatch?.[2] ? +emailMatch[2] : undefined; return (value: ContactValue) => templates.email({ pref, header, value, type: type ? toVcardType(type) : '' }); } if (phoneMatch) { const type = phoneMatch[1] ? phoneMatch[1] : undefined; const pref = phoneMatch?.[2] ? +phoneMatch[2] : undefined; return (value: ContactValue) => templates.tel({ pref, header, value, type: type ? toVcardType(type) : '' }); } if (faxMatch) { const pref = faxMatch?.[2] ? +faxMatch[2] : undefined; return (value: ContactValue) => templates.tel({ pref, header, value, type: 'fax' }); } if (pagerMatch) { const pref = pagerMatch?.[2] ? +pagerMatch[2] : undefined; return (value: ContactValue) => templates.tel({ pref, header, value, type: 'pager' }); } if (telexMatch) { const pref = telexMatch[1] ? +telexMatch[1] : undefined; return (value: ContactValue) => templates.tel({ pref, header, value, type: 'other' }); } if (poBoxMatch) { const type = poBoxMatch[1] ? poBoxMatch[1] : undefined; const pref = poBoxMatch?.[2] ? +poBoxMatch[2] : undefined; return (value: ContactValue) => templates.adr({ pref, header, type: toVcardType(type), value, index: 0 }); } if (extAddressMatch) { const type = extAddressMatch[1] ? extAddressMatch[1] : undefined; const pref = extAddressMatch?.[2] ? +extAddressMatch[2] : undefined; return (value: ContactValue) => templates.adr({ pref, header, type: toVcardType(type), value, index: 1 }); } if (streetMatch) { const type = streetMatch[1] ? streetMatch[1] : undefined; const pref = streetMatch?.[2] ? +streetMatch[2] : undefined; return (value: ContactValue) => templates.adr({ pref, header, type: toVcardType(type), value, index: 2 }); } if (cityMatch) { const type = cityMatch[1] ? cityMatch[1] : undefined; const pref = cityMatch?.[2] ? +cityMatch[2] : undefined; return (value: ContactValue) => templates.adr({ pref, header, type: toVcardType(type), value, index: 3 }); } if (stateMatch) { const type = stateMatch[1] ? stateMatch[1] : undefined; const pref = stateMatch?.[2] ? +stateMatch[2] : undefined; return (value: ContactValue) => templates.adr({ pref, header, type: toVcardType(type), value, index: 4 }); } if (postalCodeMatch) { const type = postalCodeMatch[1] ? postalCodeMatch[1] : undefined; const pref = postalCodeMatch?.[2] ? +postalCodeMatch[2] : undefined; return (value: ContactValue) => templates.adr({ pref, header, type: toVcardType(type), value, index: 5 }); } if (countryMatch) { const type = countryMatch[1] ? countryMatch[1] : undefined; const pref = countryMatch?.[2] ? +countryMatch[2] : undefined; return (value: ContactValue) => templates.adr({ pref, header, type: toVcardType(type), value, index: 6 }); } if (property === 'job title') { return (value: ContactValue) => ({ header, value, checked: true, field: 'title', }); } if (property === 'role') { return (value: ContactValue) => ({ header, value, checked: true, field: 'role', }); } if (property === 'birthday') { return (value: ContactValue) => { return { header, value, checked: true, field: 'bday', }; }; } if (property === 'anniversary') { return (value: ContactValue) => { return { header, value, checked: true, field: 'anniversary', }; }; } if (property.includes('web')) { return (value: ContactValue) => ({ header, value, checked: true, field: 'url', }); } if (property === 'photo') { return (value: ContactValue) => ({ header, value, checked: true, field: 'photo', }); } if (property === 'logo') { return (value: ContactValue) => ({ header, value, checked: true, field: 'logo', }); } if (property === 'location') { return (value: ContactValue) => ({ header, value, checked: true, field: 'geo', type: 'main', }); } if (property === 'office location') { return (value: ContactValue) => ({ header, value, checked: true, field: 'geo', type: 'work', }); } if (property === 'gender') { return (value: ContactValue) => ({ header, value, checked: true, field: 'gender', }); } if (property === 'timezone') { return (value: ContactValue) => ({ header, value, checked: true, field: 'tz', }); } if (property === 'organization') { return (value: ContactValue) => ({ header, value, checked: true, field: 'org', }); } if (property === 'language') { return (value: ContactValue) => ({ header, value, checked: true, field: 'lang', }); } if (property === 'member') { return (value: ContactValue) => ({ header, value, checked: true, field: 'member', }); } if (property === 'notes' || property.includes('custom field')) { return (value: ContactValue) => ({ header, value, checked: true, field: 'note', }); } if (property === 'categories') { return (value: ContactValue) => ({ header, value, checked: true, field: 'categories', }); } if (property === 'org') { return (value: VCardOrg) => ({ header, value: [ ...(value.organizationalName ? [value.organizationalName] : []), ...(value.organizationalUnitNames ?? []), ], checked: true, field: 'categories', }); } // convert any other property into custom note return (value: ContactValue) => ({ header, value, checked: true, field: 'note', custom: true, }); }; /** * When there is only one pre-vCard property in a pre-vCards property, get the property */ const getFirstValue = (preVcards: PreVcardProperty[]): string => getStringContactValue(preVcards[0].checked ? preVcards[0].value : '').trim(); const getDateValue = (preVcards: PreVcardProperty[]) => { const text = getFirstValue(preVcards); const date = guessDateFromText(text); return date ? { date } : { text }; }; /** * This object contains the functions that must be used when combining pre-vCard properties into * vCard ones. The keys correspond to the field of the pre-vCards to be combined. */ export const combine: Combine = { fn(preVcards: PreVcardsProperty) { return preVcards.reduce((acc, { value, checked }) => (value && checked ? `${acc} ${value}` : acc), '').trim(); }, // N field follow the following format lastName;firstName;additionalName;prefix;suffix n(preVcards: PreVcardsProperty) { const nField = preVcards.map((item) => (item.checked ? item.value : false)).filter(Boolean) as string[]; return icalValueToNValue(nField); }, adr(preVcards: PreVcardsProperty) { // To avoid unintended CRLF sequences inside the values of vCard address fields (those are interpreted as field separators unless followed by a space), we sanitize string values const sanitizeStringValue = (value: string) => value.replaceAll('\n', ' '); const propertyADR = new Array(7).fill(''); preVcards.forEach(({ value, checked, combineIndex }) => { if (checked) { // Remove unintended CRLF sequences if (typeof value === 'string') { value = sanitizeStringValue(value); } else { value = value.map((val) => sanitizeStringValue(getStringContactValue(val))); } propertyADR[combineIndex || 0] = value; } }); return icalValueToInternalAddress(propertyADR); }, org(preVcards: PreVcardsProperty) { const orgField = preVcards.map((item) => (item.checked ? item.value : false)).filter(Boolean) as string[]; return icalValueToOrgValue(orgField); }, categories(preVcards: PreVcardsProperty) { // we can get several categories separated by ';' return getFirstValue(preVcards).split(';'); }, email: getFirstValue, tel: getFirstValue, photo: getFirstValue, bday: getDateValue, anniversary: getDateValue, title: getFirstValue, role: getFirstValue, note: getFirstValue, url: getFirstValue, gender(preVcards: PreVcardsProperty) { return { text: getFirstValue(preVcards) }; }, lang: getFirstValue, tz: getFirstValue, geo: getFirstValue, logo: getFirstValue, member: getFirstValue, custom(preVcards: PreVcardsProperty) { const { checked, header, value } = preVcards[0]; return checked && value ? `${header}: ${getFirstValue(preVcards)}` : ''; }, }; /** * Because the value of a vCard property is not always a string (sometimes it is an array), * we need an additional function that combines the csv properties into a string to be displayed. * This object contains the functions that take an array of pre-vCards properties to be combined * and returns the value to be displayed. The keys correspond to the field of the pre-vCards to be combined. */ export const display: Display = { fn(preVcards: PreVcardsProperty) { return preVcards.reduce((acc, { value, checked }) => (value && checked ? `${acc} ${value}` : acc), '').trim(); }, n(preVcards: PreVcardsProperty) { return preVcards.reduce((acc, { value, checked }) => (value && checked ? `${acc} ${value}` : acc), '').trim(); }, adr(preVcards: PreVcardsProperty) { const propertyADR = new Array(7).fill(''); preVcards.forEach(({ value, checked, combineIndex }) => { if (checked) { propertyADR[combineIndex || 0] = value; } }); return propertyADR.filter(Boolean).join(', '); }, org(preVcards: PreVcardsProperty) { const propertyORG = new Array(2).fill(''); preVcards.forEach(({ value, checked, combineIndex }) => { if (checked) { propertyORG[combineIndex || 0] = value; } }); return propertyORG.filter(Boolean).join('; '); }, email(preVcards: PreVcardsProperty) { // If the value is an array, display values joined by a comma, otherwise display the value const { value } = preVcards[0]; return Array.isArray(value) ? value.join(', ') : value; }, tel: getFirstValue, photo: getFirstValue, bday: getFirstValue, anniversary: getFirstValue, title: getFirstValue, role: getFirstValue, note: getFirstValue, url: getFirstValue, gender: getFirstValue, lang: getFirstValue, tz: getFirstValue, geo: getFirstValue, logo: getFirstValue, member: getFirstValue, categories: getFirstValue, custom(preVcards: PreVcardsProperty) { const { header, value, checked } = preVcards[0]; return checked && value ? `${header}: ${getFirstValue(preVcards)}` : ''; }, };
8,426
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/helpers/export.ts
import { format } from 'date-fns'; import { getApiWithAbort } from '@proton/shared/lib/api/helpers/customConfig'; import uniqueBy from '@proton/utils/uniqueBy'; import { getContact, queryContactExport } from '../../api/contacts'; import downloadFile from '../../helpers/downloadFile'; import { wait } from '../../helpers/promise'; import { Api, DecryptedKey } from '../../interfaces'; import { Contact, ContactCard } from '../../interfaces/contacts/Contact'; import { VCardContact } from '../../interfaces/contacts/VCard'; import { splitKeys } from '../../keys'; import { API_SAFE_INTERVAL, QUERY_EXPORT_MAX_PAGESIZE } from '../constants'; import { prepareVCardContact } from '../decrypt'; import { serialize } from '../vcard'; export const getFileName = (contact: VCardContact) => { // cover up for the case no FN is present in the contact (we can find such vcards in the DB) const contactName = contact.fn?.[0]?.value || ''; const contactEmail = contact.email?.[0]?.value || ''; const name = contactName || contactEmail; return `${name}-${format(Date.now(), 'yyyy-MM-dd')}.vcf`; }; export const singleExport = (contact: VCardContact) => { const fileName = getFileName(contact); const vcard = serialize(contact); const blob = new Blob([vcard], { type: 'data:text/plain;charset=utf-8;' }); downloadFile(blob, fileName); }; export const exportContact = async (cards: ContactCard[], userKeys: DecryptedKey[]) => { const { publicKeys, privateKeys } = splitKeys(userKeys); const { vCardContact, errors = [] } = await prepareVCardContact({ Cards: cards } as Contact, { publicKeys, privateKeys, }); if (errors.length) { throw new Error('Error decrypting contact'); } const name = getFileName(vCardContact); return { name, vcard: serialize(vCardContact) }; }; /** * Exports contacts including api request and decryption * Beware it requires all contacts in //, don't use this for more than 10 contacts */ export const exportContacts = (contactIDs: string[], userKeys: DecryptedKey[], api: Api) => Promise.all( contactIDs.map(async (contactID) => { const { Contact: { Cards }, } = await api<{ Contact: Contact }>(getContact(contactID)); return exportContact(Cards, userKeys); }) ); /** * Export contacts from a labelID full featured with batch requests, callbacks, abort */ export const exportContactsFromLabel = async ( labelID: string | undefined, count: number, userKeys: DecryptedKey[], signal: AbortSignal, api: Api, callbackSuccess: (contactContent: string) => void, callbackFailure: (contactID: string) => void ) => { const apiWithAbort = getApiWithAbort(api, signal); const apiCalls = Math.ceil(count / QUERY_EXPORT_MAX_PAGESIZE); const results = { success: [] as string[], failures: [] as string[] }; for (let i = 0; i < apiCalls; i++) { let { Contacts: contacts } = (await apiWithAbort( queryContactExport({ LabelID: labelID, Page: i, PageSize: QUERY_EXPORT_MAX_PAGESIZE }) )) as { Contacts: Contact[] }; // API will respond one contact per email (unless fixed in the meantime) // We want to export each contact only once contacts = uniqueBy(contacts, (contact) => contact.ID); for (const { Cards, ID } of contacts) { if (signal.aborted) { return; } try { const { vcard } = await exportContact(Cards, userKeys); // need to check again for signal.aborted because the abort // may have taken place during await prepareContact if (!signal.aborted) { callbackSuccess(vcard); } results.success.push(vcard); } catch (error: any) { // need to check again for signal.aborted because the abort // may have taken place during await prepareContact if (!signal.aborted) { callbackFailure(ID); } results.failures.push(ID); } } // avoid overloading API in the unlikely case exportBatch is too fast await wait(API_SAFE_INTERVAL); } return results; };
8,427
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/helpers/import.ts
import { c } from 'ttag'; import isTruthy from '@proton/utils/isTruthy'; import truncate from '@proton/utils/truncate'; import { CONTACT_CARD_TYPE, FORBIDDEN_LABEL_NAMES } from '../../constants'; import { normalize } from '../../helpers/string'; import { ContactGroup, ContactMetadata, IMPORT_GROUPS_ACTION, ImportCategories, ImportedContact, SimpleEncryptedContact, } from '../../interfaces/contacts'; import { ACCEPTED_EXTENSIONS, EXTENSION, EncryptedContact, ImportContactsModel, } from '../../interfaces/contacts/Import'; import { VCardContact, VCardProperty } from '../../interfaces/contacts/VCard'; import { SimpleMap } from '../../interfaces/utils'; import { MAX_CONTACT_ID_CHARS_DISPLAY } from '../constants'; import { IMPORT_CONTACT_ERROR_TYPE, ImportContactError } from '../errors/ImportContactError'; import { createContactPropertyUid } from '../properties'; import { getSupportedContactName } from '../surgery'; import { getContactHasName, parseToVCard } from '../vcard'; export const getIsAcceptedExtension = (extension: string): extension is ACCEPTED_EXTENSIONS => { return Object.values(EXTENSION).includes(extension as EXTENSION); }; export const getHasPreVcardsContacts = ( model: ImportContactsModel ): model is ImportContactsModel & Required<Pick<ImportContactsModel, 'preVcardsContacts'>> => { return !!model.preVcardsContacts; }; export const naiveExtractPropertyValue = (vcard: string, property: string) => { const contentLineSeparator = vcard.includes('\r\n') ? '\r\n' : '\n'; const contentLineSeparatorLength = contentLineSeparator.length; // Vcard properties typically have parameters and value, e.g.: FN;PID=1.1:J. Doe const indexOfPropertyName = vcard.toLowerCase().indexOf(`${contentLineSeparator}${property.toLowerCase()}`); const indexOfPropertyValue = vcard.indexOf(':', indexOfPropertyName); if (indexOfPropertyName === -1 || indexOfPropertyValue === -1) { return; } // take into account possible folding let indexOfNextField = vcard.indexOf(contentLineSeparator, indexOfPropertyValue); let value = vcard.substring(indexOfPropertyValue + 1, indexOfNextField); while (vcard[indexOfNextField + contentLineSeparatorLength] === ' ') { const oldIndex = indexOfNextField; indexOfNextField = vcard.indexOf(contentLineSeparator, oldIndex + contentLineSeparatorLength); value += vcard.substring(oldIndex + contentLineSeparatorLength + 1, indexOfNextField); } return value; }; /** * Try to get a string that identifies a contact. This will be used in case of errors */ export const getContactId = (vcardOrVCardContact: string | VCardContact) => { // translator: When having an error importing a contact for which we can't find a name, we display an error message `Contact ${contactId}: error description` with contactId = 'unknown' const unknownString = c('Import contact. Contact identifier').t`unknown`; if (typeof vcardOrVCardContact !== 'string') { const fn = vcardOrVCardContact.fn?.[0]?.value; if (fn) { return fn; } const email = vcardOrVCardContact.email?.[0]?.value; if (email) { return email; } return unknownString; } const FNvalue = naiveExtractPropertyValue(vcardOrVCardContact, 'FN'); return FNvalue ? truncate(FNvalue, MAX_CONTACT_ID_CHARS_DISPLAY) : unknownString; }; export const getSupportedContactProperties = (contact: VCardContact) => { if (!getContactHasName(contact)) { const contactId = getContactId(contact); const supportedContactName = getSupportedContactName(contact); if (!supportedContactName) { throw new ImportContactError(IMPORT_CONTACT_ERROR_TYPE.MISSING_FN, contactId); } const supportedFnProperty: VCardProperty<string> = { field: 'fn', uid: createContactPropertyUid(), value: supportedContactName, }; contact.fn = [supportedFnProperty]; } return contact; }; export const getSupportedContact = (vcard: string) => { try { const contactId = getContactId(vcard); if (naiveExtractPropertyValue(vcard, 'VERSION') === '2.1') { throw new ImportContactError(IMPORT_CONTACT_ERROR_TYPE.UNSUPPORTED_VCARD_VERSION, contactId); } return getSupportedContactProperties(parseToVCard(vcard)); } catch (error: any) { if (error instanceof ImportContactError) { throw error; } const contactId = getContactId(vcard); throw new ImportContactError(IMPORT_CONTACT_ERROR_TYPE.EXTERNAL_ERROR, contactId, error); } }; export const getSupportedContacts = (vcards: string[]) => { return vcards .map((vcard) => { try { return getSupportedContact(vcard); } catch (error: any) { if (error instanceof ImportContactError) { return error; } const contactId = getContactId(vcard); return new ImportContactError(IMPORT_CONTACT_ERROR_TYPE.EXTERNAL_ERROR, contactId, error); } }) .filter(isTruthy); }; export const haveCategories = (contacts: ImportedContact[]) => { return contacts.some(({ categories }) => categories.some((category) => category.contactEmailIDs?.length)); }; /** * Extract the info about categories relevant for importing groups, i.e. * extract categories with corresponding contact email ids (if any) for a submitted contact */ export const extractContactImportCategories = ( contact: ContactMetadata, { categories, contactEmails }: EncryptedContact ) => { const withGroup = categories.map(({ name, group }) => { const matchingContactEmailIDs = contactEmails .filter( ({ group: emailGroup }) => // If category group is not defined, we consider it applies to all email group === undefined || // If category group is defined, we consider it has to match with the email group emailGroup === group ) .map(({ email }) => { const { ID } = contact.ContactEmails.find(({ Email }) => Email === email) || {}; return ID; }) .filter(isTruthy); if (!matchingContactEmailIDs.length) { return { name }; } return { name, contactEmailIDs: matchingContactEmailIDs }; }); const categoriesMap = withGroup.reduce<SimpleMap<string[]>>((acc, { name, contactEmailIDs = [] }) => { const category = acc[name]; if (category && contactEmailIDs.length) { category.push(...contactEmailIDs); } else { acc[name] = [...contactEmailIDs]; } return acc; }, {}); return Object.entries(categoriesMap).map(([name, contactEmailIDs]) => ({ name, contactEmailIDs })); }; /** * Given a list of imported contacts, get a list of the categories that can be imported, each of them with * a list of contactEmailIDs or contactIDs plus total number of contacts that would go into the category */ export const getImportCategories = (contacts: ImportedContact[]) => { const allCategoriesMap = contacts.reduce< SimpleMap<Pick<ImportCategories, 'contactEmailIDs' | 'contactIDs' | 'totalContacts'>> >((acc, { contactID, categories, contactEmailIDs: contactEmailIDsOfContact }) => { if ( // No categories to consider !categories.length || // We ignore groups on contact with no emails !contactEmailIDsOfContact.length ) { return acc; } categories.forEach(({ name, contactEmailIDs = [] }) => { const category = acc[name]; if (contactEmailIDs.length === 0) { // We ignore groups on contact if no emails are assigned return; } if (!category) { if (contactEmailIDs.length === contactEmailIDsOfContact.length) { acc[name] = { contactEmailIDs: [], contactIDs: [contactID], totalContacts: 1 }; } else { acc[name] = { contactEmailIDs: [...contactEmailIDs], contactIDs: [], totalContacts: 1 }; } } else if (contactEmailIDs.length === contactEmailIDsOfContact.length) { acc[name] = { contactEmailIDs: category.contactEmailIDs, contactIDs: [...category.contactIDs, contactID], totalContacts: category.totalContacts + 1, }; } else { acc[name] = { contactEmailIDs: [...category.contactEmailIDs, ...contactEmailIDs], contactIDs: category.contactIDs, totalContacts: category.totalContacts + 1, }; } }); return acc; }, {}); return Object.entries(allCategoriesMap) .map(([name, value]) => { if (!value) { return; } return { name, contactEmailIDs: value.contactEmailIDs, contactIDs: value.contactIDs, totalContacts: value.totalContacts, }; }) .filter(isTruthy); }; export const getImportCategoriesModel = (contacts: ImportedContact[], groups: ContactGroup[] = []) => { const categories = getImportCategories(contacts).map((category) => { const existingGroup = groups.find(({ Name }) => Name === category.name); const action = existingGroup && groups.length ? IMPORT_GROUPS_ACTION.MERGE : IMPORT_GROUPS_ACTION.CREATE; const targetGroup = existingGroup || groups[0]; const targetName = existingGroup ? '' : category.name; const result: ImportCategories = { ...category, action, targetGroup, targetName, }; if (action === IMPORT_GROUPS_ACTION.CREATE && FORBIDDEN_LABEL_NAMES.includes(normalize(targetName))) { result.error = c('Error').t`Invalid name`; } return result; }); return categories; }; export const splitErrors = <T>(contacts: (T | ImportContactError)[]) => { return contacts.reduce<{ errors: ImportContactError[]; rest: T[] }>( (acc, contact) => { if (contact instanceof ImportContactError) { acc.errors.push(contact); } else { acc.rest.push(contact); } return acc; }, { errors: [], rest: [] } ); }; /** * Split encrypted contacts depending on having the CATEGORIES property. */ export const splitEncryptedContacts = (contacts: SimpleEncryptedContact[] = []) => contacts.reduce<{ withCategories: SimpleEncryptedContact[]; withoutCategories: SimpleEncryptedContact[] }>( (acc, contact) => { const { contact: { Cards, error }, } = contact; if (error) { return acc; } if (Cards.some(({ Type, Data }) => Type === CONTACT_CARD_TYPE.CLEAR_TEXT && Data.includes('CATEGORIES'))) { acc.withCategories.push(contact); } else { acc.withoutCategories.push(contact); } return acc; }, { withCategories: [], withoutCategories: [] } );
8,428
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/helpers/importCsv.ts
import { getTypeValues } from '../../helpers/contacts'; import { PreVcardProperty, PreVcardsContact } from '../../interfaces/contacts/Import'; import { VCardKey } from '../../interfaces/contacts/VCard'; // See './csv.ts' for the definition of pre-vCard and pre-vCards contact /** * Modify the field (and accordingly the type, if needed) of a pre-vCard */ const modifyPreVcardField = (preVcard: PreVcardProperty, newField: string) => { const types = getTypeValues(); let newType: VCardKey | undefined = undefined; if (types[newField]?.includes(preVcard.type || '')) { newType = preVcard.type; } else if (types[newField]?.length) { newType = types[newField][0] as VCardKey; } return { ...preVcard, field: newField, type: newType, custom: false }; }; /** * Modify the field (and accordingly the type) of a pre-vCard inside a pre-vCards contact */ export const modifyContactField = (preVcardsContact: PreVcardsContact, index: number, newField: string) => { return preVcardsContact.map((preVcards, i) => i !== index ? preVcards : preVcards.map((preVcard) => modifyPreVcardField(preVcard, newField)) ); }; /** * Modify the type of a pre-vCard */ const modifyPreVcardType = (preVcard: PreVcardProperty, newType: string) => ({ ...preVcard, type: newType as VCardKey, }); /** * Modify the type of a pre-vCard inside a pre-vCards contact */ export const modifyContactType = (preVcardsContact: PreVcardsContact, index: number, newField: string) => { return preVcardsContact.map((preVcards, i) => i !== index ? preVcards : preVcards.map((preVcard) => modifyPreVcardType(preVcard, newField)) ); }; /** * Toggle the checked attribute of a pre-vCard inside a pre-vCards contact * @param {Object} preVcardsContact A pre-vCards contact * @param {Number} groupIndex The index of the group of pre-Vcards where the pre-vCard to be modified is * @param {Number} index The index of the pre-vCard within the group of pre-vCards * * @return {Array<Array<Object>>} the pre-vCards contact with the modified pre-vCard */ export const toggleContactChecked = (preVcardsContact: PreVcardsContact, [groupIndex, index]: number[]) => { const toggleFN = preVcardsContact[groupIndex][index].combineInto === 'fn-main'; const groupIndexN = toggleFN ? preVcardsContact.findIndex((group) => group[0].combineInto === 'n') : -1; return preVcardsContact.map((preVcards, i) => { if (i === groupIndex) { return preVcards.map((preVcard, j) => j !== index ? preVcard : { ...preVcard, checked: !preVcard.checked } ); } if (toggleFN && i === groupIndexN) { // When FN components are toggled, we also toggle the corresponding N components const headerFN = preVcardsContact[groupIndex][index].header; const indexN = preVcardsContact[groupIndexN].findIndex(({ header }) => header === headerFN); return preVcards.map((preVcard, j) => j !== indexN ? preVcard : { ...preVcard, checked: !preVcard.checked } ); } return preVcards; }); };
8,429
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/helpers/merge.ts
import isTruthy from '@proton/utils/isTruthy'; import unique from '@proton/utils/unique'; import { normalize } from '../../helpers/string'; import { FormattedContact } from '../../interfaces/contacts/FormattedContact'; import { VCardContact, VCardProperty } from '../../interfaces/contacts/VCard'; import { fromVCardProperties, generateNewGroupName, getStringContactValue, getVCardProperties, hasPref, } from '../properties'; import { getFallbackFNValue, prepareForSaving } from '../surgery'; import { ONE_OR_MORE_MAY_BE_PRESENT, ONE_OR_MORE_MUST_BE_PRESENT, PROPERTIES, isCustomField } from '../vcard'; const getPref = (params: { [key: string]: string | undefined } | undefined) => { const numValue = Number(params?.pref || ''); return isNaN(numValue) ? 0 : numValue; }; /** * Given an array of keys and an object storing an index for each key, * if the object contains any of these keys, return the index stored in the object * for the first of such keys. Otherwise return -1 */ const findKeyIndex = (keys: number[], obj: { [key: number]: number }) => { for (const key of keys) { if (obj[key] !== undefined) { return obj[key]; } } return -1; }; /** * Given a list of connections (a "connection" is a list of keys [key1, key2, ...] connected for some reason), * find recursively all connections and return a new list of connections with no key repeated. * E.g.: [[1, 2, 3], [3, 5], [4, 6]] -> [[1, 2, 3, 5], [4, 6]] * @param connections */ export const linkConnections = (connections: number[][]): number[][] => { let didModify = false; const { newConnections } = connections.reduce<{ connected: { [key: number]: number }; newConnections: number[][]; }>( (acc, connection) => { const { connected, newConnections } = acc; // check if some index in current connection has been connected already const indexFound = findKeyIndex(connection, connected); if (indexFound !== -1) { // add indices in current connection to the connected connection newConnections[indexFound] = unique([...connection, ...newConnections[indexFound]]); for (const key of connection) { // update list of connected indices if (connected[key] === undefined) { connected[key] = indexFound; } } didModify = true; } else { // update list of connected indices for (const key of connection) { connected[key] = newConnections.length; } newConnections.push(connection); } return acc; }, { connected: Object.create(null), newConnections: [] } ); // if some indices previously unconnected have been connected, // run linkConnections again if (didModify) { return linkConnections(newConnections); } // otherwise no more connections to be established return connections; }; /** * Given a list of contacts, extract the ones that can be merged * @param contacts Each contact is an object { ID, emails, Name, LabelIDs } * * @returns List of groups of contacts that can be merged */ export const extractMergeable = (contacts: FormattedContact[] = []) => { const fallbackFN = getFallbackFNValue(); const fallbackNormalizedProtonNames = unique([ 'Unknown', // fallback value used by the back-end (they add the angular brackets) '<Unknown>', fallbackFN, `<${fallbackFN}>`, ]).map((name) => normalize(name)); // detect duplicate names // namesConnections = { name: [contact indices with this name] } const namesConnections = Object.values( contacts.reduce<{ [Name: string]: number[] }>((acc, { Name }, index) => { const name = normalize(Name); if (fallbackNormalizedProtonNames.includes(name)) { // These names have been probably added by us during an import (because we did not have anything better). // So they will most likely not identify identical contacts return acc; } if (!acc[name]) { acc[name] = [index]; } else { acc[name].push(index); } return acc; }, Object.create(null)) ) .map(unique) .filter((connection) => connection.length > 1); // detect duplicate emails // emailConnections = { email: [contact indices with this email] } const emailConnections = Object.values( contacts.reduce<{ [email: string]: number[] }>((acc, { emails }, index) => { emails .map((email) => normalize(email)) .forEach((email) => { if (!acc[email]) { acc[email] = [index]; } else { acc[email].push(index); } }); return acc; }, Object.create(null)) ) .map(unique) .filter((connection) => connection.length > 1); // Now we collect contact indices that go together // either in duplicate names or duplicate emails. const allConnections = linkConnections([...namesConnections, ...emailConnections]); return allConnections.map((indices) => indices.map((index) => contacts[index])); }; /** * Given the value and field of a contact property, and a list of merged properties, * return and object with a Boolean that tells if the value has been merged or is a new value. * In the latter case, return the new value in the object * @dev Normalize strings in all fields but EMAIL */ export const extractNewValue = ( value: any, field: string, mergedValues: any[] = [] ): { isNewValue: boolean; newValue: any | undefined } => { if (field === 'org') { // compare with merged values. Normalize all strings const isRepeatedValue = mergedValues.some((mergedValue) => { const mergedValueAsArray: string[] = [ mergedValue.organizationalName, ...(mergedValue.organizationalUnitNames ?? []), ].filter(isTruthy); // each of the components inside be an array itself const valueAsArray: string[] = [ value?.organizationalName, ...(value?.organizationalUnitNames ?? []), ].filter(isTruthy); // value order is important, that's we why do an exact match check and not just check that one array includes the value of another const isSameValue = valueAsArray.every( (str, index) => normalize(str) === normalize(mergedValueAsArray[index] ?? '') ); return isSameValue; }); return { isNewValue: !isRepeatedValue, newValue: isRepeatedValue ? undefined : value }; } if (field === 'adr') { const isNew = mergedValues.filter((mergedValue) => { return Object.keys(value).every((key) => normalize(value[key]) === normalize(mergedValue[key])); }).length === 0; return { isNewValue: isNew, newValue: isNew ? value : undefined }; } if (['bday', 'anniversary'].includes(field)) { const isNew = mergedValues.filter((mergedValue) => { return ( normalize(value.text) === normalize(mergedValue.text) && value.date?.getTime?.() === mergedValue.date?.getTime?.() ); }).length === 0; return { isNewValue: isNew, newValue: isNew ? value : undefined }; } if (field === 'gender') { const isNew = mergedValues.filter((mergedValue) => { return normalize(value.text) === normalize(mergedValue.text) && value.gender === mergedValue.gender; }).length === 0; return { isNewValue: isNew, newValue: isNew ? value : undefined }; } // for the other fields, value is a string, and mergedValues an array of strings // for EMAIL field, do not normalize, only trim if (field === 'email') { const isNew = !mergedValues .map((val) => getStringContactValue(val).trim()) .includes(getStringContactValue(value).trim()); return { isNewValue: isNew, newValue: isNew ? value : undefined }; } // for the rest of the fields, normalize strings const isNew = !mergedValues .map((c) => normalize(getStringContactValue(c))) .includes(normalize(getStringContactValue(value))); return { isNewValue: isNew, newValue: isNew ? value : undefined }; }; /** * Merge a list of contacts. The contacts must be ordered in terms of preference. * @param contacts Each contact is a list of properties [{ pref, field, group, type, value }] * @return The merged contact */ export const merge = (contacts: VCardContact[] = []): VCardContact => { if (!contacts.length) { return { fn: [] }; } const contactsProperties = contacts .map((contact) => prepareForSaving(contact)) // Extra security to have well formed contact input .map((contact) => getVCardProperties(contact)); const { mergedContact } = contactsProperties.reduce<{ mergedContact: VCardProperty[]; mergedProperties: { [field: string]: any[] }; mergedPropertiesPrefs: { [field: string]: number[] }; mergedGroups: { [email: string]: string }; }>( (acc, contactProperties, index) => { const { mergedContact, mergedProperties, mergedPropertiesPrefs, mergedGroups } = acc; if (index === 0) { // merged contact inherits all properties from the first contact mergedContact.push(...contactProperties); // keep track of merged properties with respective prefs and merged groups for (const { field, value, group, params } of contactProperties) { if (!mergedProperties[field]) { mergedProperties[field] = [value]; if (hasPref(field)) { mergedPropertiesPrefs[field] = [getPref(params)]; } } else { mergedProperties[field].push(value); if (hasPref(field)) { mergedPropertiesPrefs[field].push(getPref(params)); } } // email and groups are in one-to-one correspondence if (field === 'email') { mergedGroups[value as string] = group as string; } } } else { // for the other contacts, keep only non-merged properties // but first prepare to change repeated groups // extract groups in contact to be merged const groups = contactProperties .filter(({ field }) => field === 'email') .map(({ value, group }) => ({ email: value, group })); // establish how groups should be changed const changeGroup = groups.reduce<{ [group: string]: string }>((acc, { email, group }) => { if (Object.values(mergedGroups).includes(group as string)) { const newGroup = mergedGroups[email as string] || generateNewGroupName(Object.values(mergedGroups)); acc[group as string] = newGroup; mergedGroups[email as string] = newGroup; } else { acc[group as string] = group as string; } return acc; }, {}); for (const property of contactProperties) { const { field, group, value, params } = property; const newGroup = group ? changeGroup[group] : group; if (!mergedProperties[field]) { // an unseen property is directly merged mergedContact.push({ ...property, params, group: newGroup }); mergedProperties[field] = [value]; if (hasPref(field)) { mergedPropertiesPrefs[field] = [getPref(params)]; } if (newGroup && field === 'email') { mergedGroups[value as string] = newGroup; } } else { // for properties already seen, // check if there is a new value for it const { isNewValue, newValue } = extractNewValue(value, field, mergedProperties[field]); const newPref = hasPref(field) ? Math.max(...mergedPropertiesPrefs[field]) + 1 : undefined; // check if the new value can be added const canAdd = field !== 'fn' && // Only keep the name of the first contact (isCustomField(field) || [ONE_OR_MORE_MAY_BE_PRESENT, ONE_OR_MORE_MUST_BE_PRESENT].includes( PROPERTIES[field].cardinality )); if (isNewValue && canAdd) { mergedContact.push({ ...property, value: newValue, group: newGroup, params: { ...property.params, pref: String(newPref), }, }); mergedProperties[field].push(newValue); if (hasPref(field)) { mergedPropertiesPrefs[field] = [newPref as number]; } if (newGroup && field === 'email') { mergedGroups[value as string] = newGroup; } } } } } return acc; }, { mergedContact: [], mergedProperties: {}, mergedPropertiesPrefs: {}, mergedGroups: {}, } ); return fromVCardProperties(mergedContact); };
8,430
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts
petrpan-code/ProtonMail/WebClients/packages/shared/lib/contacts/helpers/progress.ts
/** * Calculate progress percentage (0 <= integer <= 100) of a certain process * that involves carrying out several tasks, that can either fail or be successful * @param successful Number of tasks completed successfully * @param failed Number of tasks that failed * @param total Total number of tasks */ export const percentageProgress = (successful: number, failed: number, total: number) => { if (+total === 0) { // assume the process has not started return 0; } // in case successful + failed > total, do not allow progress > 100 return Math.min(Math.floor(((+successful + failed) / total) * 100), 100); }; /** * Combine progresses of several processes with predefined allocation percentages * @param processes Processes to be combined. Format: { allocated, successful, failed, total} * @param processes.allocated Allocated percentage for a process. E.g. 0.25 * * @return Combined progrees */ export const combineProgress = ( processes: { allocated: number; successful: number; failed: number; total: number }[] = [] ) => { const { combinedTotal, combinedAllocations, progresses } = processes.reduce<{ combinedTotal: number; combinedAllocations: number; progresses: number[]; }>( (acc, { allocated, successful, failed, total }) => { acc.combinedTotal += total; acc.combinedAllocations += allocated; acc.progresses.push(percentageProgress(successful, failed, total)); return acc; }, { combinedTotal: 0, combinedAllocations: 0, progresses: [] } ); if (combinedAllocations !== 1 && !!processes.length) { throw new Error('Allocations must add up to one'); } if (!combinedTotal) { return 0; } const combinedProgress = processes.reduce((acc, { allocated, total }, i) => { // set progress to 100 if there are no tasks to be performed for this process, // but there are tasks in other processes const progress = allocated * (!total && !!combinedTotal ? 100 : progresses[i]); return acc + progress; }, 0); return Math.round(combinedProgress); };
8,431
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-fns-utc/differenceInCalendarDays.ts
import { DAY } from '@proton/shared/lib/constants'; import startOfDay from './startOfDay'; const differenceInCalendarDays = (left: Date, right: Date) => { const startOfDayLeft = startOfDay(left); const startOfDayRight = startOfDay(right); const diff = startOfDayLeft.getTime() - startOfDayRight.getTime(); return Math.round(diff / DAY); }; export default differenceInCalendarDays;
8,432
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-fns-utc/differenceInCalendarWeeks.ts
import { WEEK } from '@proton/shared/lib/constants'; import startOfDay from './startOfDay'; const differenceInCalendarWeeks = (left: Date, right: Date) => { const startOfDayLeft = startOfDay(left); const startOfDayRight = startOfDay(right); const diff = startOfDayLeft.getTime() - startOfDayRight.getTime(); return Math.floor(diff / WEEK); }; export default differenceInCalendarWeeks;
8,433
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-fns-utc/differenceInCalendarYears.ts
const differenceInCalendarYears = (left: Date, right: Date) => { return left.getUTCFullYear() - right.getUTCFullYear(); }; export default differenceInCalendarYears;
8,434
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-fns-utc/eachDayOfInterval.ts
const eachDayOfInterval = (start: Date, end: Date) => { const endTime = end.getTime(); if (!(start.getTime() <= endTime)) { throw new RangeError('Invalid interval'); } const dates: Date[] = []; const currentDate = new Date(start); currentDate.setUTCHours(0, 0, 0, 0); const step = 1; while (currentDate.getTime() <= endTime) { dates.push(new Date(currentDate)); currentDate.setUTCDate(currentDate.getUTCDate() + step); currentDate.setUTCHours(0, 0, 0, 0); } return dates; }; export default eachDayOfInterval;
8,435
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-fns-utc/endOfDay.ts
const endOfDay = (date: Date) => { const result = new Date(+date); result.setUTCHours(23, 59, 59, 999); return result; }; export default endOfDay;
8,436
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-fns-utc/endOfWeek.ts
import { WeekStartsOn } from './interface'; interface Options { weekStartsOn: WeekStartsOn; } const endfWeek = (date: Date, options?: Options) => { const weekStartsOn = !options || typeof options.weekStartsOn === 'undefined' ? 0 : options.weekStartsOn; const result = new Date(+date); const day = result.getUTCDay(); const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); result.setUTCDate(date.getUTCDate() + diff); result.setUTCHours(23, 59, 59, 999); return result; }; export default endfWeek;
8,437
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-fns-utc/format.ts
import formatters from 'date-fns/_lib/format/formatters/index'; import longFormatters from 'date-fns/_lib/format/longFormatters'; import defaultLocale from 'date-fns/locale/en-US'; import { WeekStartsOn } from './interface'; /** * We copy here (with some refactor) the code for the format function from the 'date-fns' library. * What the format function from 'date-fns' does for extracting from a date (think of it as a UNIX timestamp) * the hours, day, month, etc that will be displayed, is to create a fake UTC time that mimics local time. * The days, hours, etc are then extracted with the JS functions Date.getUTCDate, Date.getUTCHours, and some * other UTC functions that date-fns has. This is achieved with the following lines of code in src/format/index.js: * * // Convert the date in system timezone to the same date in UTC+00:00 timezone. * // This ensures that when UTC functions will be implemented, locales will be compatible with them. * // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376 * const timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate) * const utcDate = subMilliseconds(originalDate, timezoneOffset) * * We want a format function that treats a UTC date as it is, without artificially transforming it to a fake UTC time * that mimics local time. Because of DST issues, we cannot undo the timezone offset with a wrapper of the format function, * so for our formatUTC function we simply remove the problematic lines above. */ const escapedStringRegExp = /^'([^]*?)'?$/; const doubleQuoteRegExp = /''/g; const formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; const longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; const unescapedLatinCharacterRegExp = /[a-zA-Z]/; const cleanEscapedString = (input: string) => { const matcherResult = input.match(escapedStringRegExp); if (!matcherResult) { return ''; } return matcherResult[1].replace(doubleQuoteRegExp, "'"); }; const toInteger = (dirtyNumber: any) => { if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) { return NaN; } const number = Number(dirtyNumber); if (Number.isNaN(number)) { return number; } return number < 0 ? Math.ceil(number) : Math.floor(number); }; export interface Options { locale?: Locale; weekStartsOn?: WeekStartsOn; firstWeekContainsDate?: number; useAdditionalWeekYearTokens?: boolean; useAdditionalDayOfYearTokens?: boolean; } /** * Same as the format function from date-fns, but formats in the "UTC timezone" */ const formatUTC = (utcDate: Date, formatString: string, options: Options = {}) => { const locale = options.locale || defaultLocale; const localeFirstWeekContainsDate = locale.options?.firstWeekContainsDate; const defaultFirstWeekContainsDate = localeFirstWeekContainsDate === undefined ? 1 : toInteger(localeFirstWeekContainsDate); const firstWeekContainsDate = options.firstWeekContainsDate === undefined ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate); const localeWeekStartsOn = locale?.options?.weekStartsOn; const defaultWeekStartsOn = localeWeekStartsOn === undefined ? 0 : toInteger(localeWeekStartsOn); const weekStartsOn = options.weekStartsOn === undefined ? defaultWeekStartsOn : toInteger(options.weekStartsOn); const formatterOptions = { firstWeekContainsDate, weekStartsOn, locale, _originalDate: utcDate }; const longFormatMatchResult = formatString.match(longFormattingTokensRegExp); if (!longFormatMatchResult) { return ''; } const formattingTokensMatchResult = longFormatMatchResult .map((substring) => { const firstCharacter = substring[0]; if (firstCharacter === 'p' || firstCharacter === 'P') { const longFormatter = longFormatters[firstCharacter]; return longFormatter(substring, locale.formatLong, formatterOptions); } return substring; }) .join('') .match(formattingTokensRegExp); if (!formattingTokensMatchResult) { return ''; } return formattingTokensMatchResult .map((substring) => { // Replace two single quote characters with one single quote character if (substring === "''") { return "'"; } const firstCharacter = substring[0]; if (firstCharacter === "'") { return cleanEscapedString(substring); } const formatter = formatters[firstCharacter]; if (formatter) { return formatter(utcDate, substring, locale.localize, formatterOptions); } if (firstCharacter.match(unescapedLatinCharacterRegExp)) { throw new Error(`Format string contains an unescaped latin alphabet character \`${firstCharacter}\``); } return substring; }) .join(''); }; export default formatUTC;
8,438
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-fns-utc/getWeekNumber.ts
const MILLISECONDS_IN_WEEK = 604800000; const getWeekNumber = (date: Date) => { const start = new Date(date); start.setUTCHours(0, 0, 0, 0); const startOfYear = new Date(0); startOfYear.setUTCFullYear(start.getUTCFullYear()); const diff = Math.max(start.getTime() - startOfYear.getTime(), 0); const result = Math.round(diff / MILLISECONDS_IN_WEEK) + 1; return result > 52 ? 1 : result; }; export default getWeekNumber;
8,439
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-fns-utc/index.ts
/** * Pending date-fn to implement UTC functions https://github.com/date-fns/date-fns/issues/376 */ export { default as eachDayOfInterval } from './eachDayOfInterval'; export { default as startOfDay } from './startOfDay'; export { default as endOfDay } from './endOfDay'; export { default as startOfWeek } from './startOfWeek'; export { default as endOfWeek } from './endOfWeek'; export { default as getWeekNumber } from './getWeekNumber'; export { default as differenceInCalendarDays } from './differenceInCalendarDays'; export { default as differenceInCalendarWeeks } from './differenceInCalendarWeeks'; export { default as differenceInCalendarYears } from './differenceInCalendarYears'; export const startOfYear = (date: Date) => { return new Date(Date.UTC(date.getUTCFullYear(), 0, 1)); }; export const endOfYear = (date: Date) => { return new Date(Date.UTC(date.getUTCFullYear() + 1, 0, 0, 23, 59, 59, 999)); }; export const startOfMonth = (date: Date) => { return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1)); }; export const endOfMonth = (date: Date) => { return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0, 23, 59, 59, 999)); }; export const min = (a: Date, b: Date) => { return +a > +b ? b : a; }; export const max = (a: Date, b: Date) => { return +a > +b ? a : b; }; export const addMilliseconds = (date: Date, amount: number) => new Date(date.getTime() + amount); export const MILLISECONDS_IN_MINUTE = 60000; export const addMinutes = (date: Date, amount: number) => addMilliseconds(date, amount * MILLISECONDS_IN_MINUTE); export const addDays = (date: Date, amount: number) => { const result = new Date(date); result.setUTCDate(date.getUTCDate() + amount); return result; }; export const addWeeks = (date: Date, amount: number) => { return addDays(date, amount * 7); }; export const getDaysInMonth = (date: Date) => { const year = date.getUTCFullYear(); const monthIndex = date.getUTCMonth(); const lastDayOfMonth = new Date(0); lastDayOfMonth.setUTCFullYear(year, monthIndex + 1, 0); lastDayOfMonth.setUTCHours(0, 0, 0, 0); return lastDayOfMonth.getUTCDate(); }; export const addMonths = (date: Date, amount: number) => { const result = new Date(+date); const desiredMonth = date.getUTCMonth() + amount; const dateWithDesiredMonth = new Date(0); dateWithDesiredMonth.setUTCFullYear(date.getUTCFullYear(), desiredMonth, 1); dateWithDesiredMonth.setUTCHours(0, 0, 0, 0); const daysInMonth = getDaysInMonth(dateWithDesiredMonth); // Set the last day of the new month // if the original date was the last day of the longer month result.setUTCMonth(desiredMonth, Math.min(daysInMonth, date.getUTCDate())); return result; }; export const addYears = (date: Date, amount: number) => { return addMonths(date, amount * 12); }; export const isSameYear = (dateLeft: Date, dateRight: Date) => { return dateLeft.getUTCFullYear() === dateRight.getUTCFullYear(); }; export const isSameMonth = (dateLeft: Date, dateRight: Date) => { if (!isSameYear(dateLeft, dateRight)) { return false; } return dateLeft.getUTCMonth() === dateRight.getUTCMonth(); }; export const isSameDay = (dateLeft: Date, dateRight: Date) => { if (!isSameMonth(dateLeft, dateRight)) { return false; } return dateLeft.getUTCDate() === dateRight.getUTCDate(); }; export const isSameHour = (dateLeft: Date, dateRight: Date) => { if (!isSameDay(dateLeft, dateRight)) { return false; } return dateLeft.getUTCHours() === dateRight.getUTCHours(); }; /** * Check if a later date happens on the following day to an earlier date * @param {Date} dateLeft Earlier date * @param {Date} dateRight Later date */ export const isNextDay = (dateLeft: Date, dateRight: Date) => { const tomorrow = new Date(Date.UTC(dateLeft.getUTCFullYear(), dateLeft.getUTCMonth(), dateLeft.getUTCDate() + 1)); return isSameDay(tomorrow, dateRight); }; export { default as format } from './format';
8,440
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-fns-utc/interface.ts
export type WeekStartsOn = 0 | 1 | 2 | 3 | 4 | 5 | 6;
8,441
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-fns-utc/startOfDay.ts
const startOfDay = (date: Date) => { const result = new Date(+date); result.setUTCHours(0, 0, 0, 0); return result; }; export default startOfDay;
8,442
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-fns-utc/startOfWeek.ts
import { WeekStartsOn } from './interface'; interface Options { weekStartsOn: WeekStartsOn; } const startOfWeek = (date: Date, options?: Options) => { const weekStartsOn = !options || typeof options.weekStartsOn === 'undefined' ? 0 : options.weekStartsOn; const result = new Date(+date); const day = result.getUTCDay(); const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; result.setUTCDate(date.getUTCDate() - diff); result.setUTCHours(0, 0, 0, 0); return result; }; export default startOfWeek;
8,443
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date-utc/formatIntlUTCDate.ts
import { formatIntlDate } from '../date/formatIntlDate'; import { fromUTCDate, toLocalDate } from '../date/timezone'; import { localeCode } from '../i18n'; /** * Format UTC date with Intl.DateTimeFormat * @param date date to be formatted * @param options formatting options, e.g. { weekday: 'short', month: 'long', year: 'numeric', timeStyle: 'short' } * @param locale [Optional] locale to be used when formatting. Defaults to the app locale */ export const formatIntlUTCDate = (date: Date, options: Intl.DateTimeFormatOptions, locale = localeCode) => { // Use fake local date built from the UTC date data const localDate = toLocalDate(fromUTCDate(date)); return formatIntlDate(localDate, options, locale); };
8,444
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date/date.ts
import { addMonths, differenceInMilliseconds, eachDayOfInterval, endOfWeek, format, getDaysInMonth, isAfter, startOfWeek, startOfYear, sub, } from 'date-fns'; import { DAY } from '../constants'; interface FormatOptions { locale?: Locale; } export const YEAR_REGEX = /[0-9]{4}/i; /** * Get a list with the names of the days of the week according to current locale, where Sunday is the start of the week. */ export const getFormattedWeekdays = (stringFormat: string, options?: FormatOptions) => { const zeroTime = new Date(0); const weekdays = eachDayOfInterval({ start: startOfWeek(zeroTime), end: endOfWeek(zeroTime) }); return weekdays.map((day) => format(day, stringFormat, options)); }; /** * Get a list with the names of the days of the week according to current locale */ export const getFormattedMonths = (stringFormat: string, options?: FormatOptions) => { const dummyDate = startOfYear(new Date(0)); const dummyMonths = Array.from({ length: 12 }).map((_, i) => addMonths(dummyDate, i)); return dummyMonths.map((date) => format(date, stringFormat, options)); }; /** * Get the index of the start of week day for a given date-fn locale */ export const getWeekStartsOn = (locale?: Locale) => { return locale?.options?.weekStartsOn || 0; }; export const getTimeRemaining = (earlierDate: Date, laterDate: Date) => { const result = { years: 0, months: 0, days: 0, hours: 0, minutes: 0, seconds: 0, firstDateWasLater: false, }; if (earlierDate === laterDate) { return result; } let earlier; let later; if (isAfter(earlierDate, laterDate)) { later = earlierDate; earlier = laterDate; result.firstDateWasLater = true; } else { earlier = earlierDate; later = laterDate; } result.years = later.getFullYear() - earlier.getFullYear(); result.months = later.getMonth() - earlier.getMonth(); result.days = later.getDate() - earlier.getDate(); result.hours = later.getHours() - earlier.getHours(); result.minutes = later.getMinutes() - earlier.getMinutes(); result.seconds = later.getSeconds() - earlier.getSeconds(); if (result.seconds < 0) { result.seconds += 60; result.minutes--; } if (result.minutes < 0) { result.minutes += 60; result.hours--; } if (result.hours < 0) { result.hours += 24; result.days--; } if (result.days < 0) { const daysInLastFullMonth = getDaysInMonth( sub(new Date(`${later.getFullYear()}-${later.getMonth() + 1}`), { months: 1 }) ); if (daysInLastFullMonth < earlier.getDate()) { // 31/01 -> 2/03 result.days += daysInLastFullMonth + (earlier.getDate() - daysInLastFullMonth); } else { result.days += daysInLastFullMonth; } result.months--; } if (result.months < 0) { result.months += 12; result.years--; } return result; }; export const getDifferenceInDays = (earlierDate: Date, laterDate: Date) => { const diff = differenceInMilliseconds(laterDate, earlierDate); return Math.floor(diff / DAY); }; export const isValidDate = (date: Date) => { return date instanceof Date && !Number.isNaN(date.getTime()); };
8,445
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date/formatIntlDate.ts
import { localeCode } from '../i18n'; import { getIntlLocale } from '../i18n/helper'; /** * Format date with Intl.DateTimeFormat * @param date date to be formatted * @param options formatting options, e.g. { weekday: 'short', month: 'long', year: 'numeric', timeStyle: 'short' } * @param locale [Optional] locale to be used when formatting. Defaults to the app locale */ export const formatIntlDate = (date: Date, options: Intl.DateTimeFormatOptions, locale = localeCode) => { const intlLocale = getIntlLocale(locale); // In case the locale is not recognized by Intl, we fallback to en-US const formatter = new Intl.DateTimeFormat([intlLocale, 'en-US'], options); return formatter.format(date); };
8,446
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date/singleCountryTimezoneDatabase.ts
export const singleCountryTimezoneDatabase = { 'Africa/Abidjan': 'CI', 'Africa/Accra': 'GH', 'Africa/Addis_Ababa': 'ET', 'Africa/Algiers': 'DZ', 'Africa/Asmara': 'ER', 'Africa/Bamako': 'ML', 'Africa/Bangui': 'CF', 'Africa/Banjul': 'GM', 'Africa/Bissau': 'GW', 'Africa/Blantyre': 'MW', 'Africa/Brazzaville': 'CG', 'Africa/Bujumbura': 'BI', 'Africa/Cairo': 'EG', 'Africa/Casablanca': 'MA', 'Africa/Ceuta': 'ES', 'Africa/Conakry': 'GN', 'Africa/Dakar': 'SN', 'Africa/Dar_es_Salaam': 'TZ', 'Africa/Djibouti': 'DJ', 'Africa/Douala': 'CM', 'Africa/El_Aaiun': 'EH', 'Africa/Freetown': 'SL', 'Africa/Gaborone': 'BW', 'Africa/Harare': 'ZW', 'Africa/Johannesburg': 'ZA', 'Africa/Juba': 'SS', 'Africa/Kampala': 'UG', 'Africa/Khartoum': 'SD', 'Africa/Kigali': 'RW', 'Africa/Kinshasa': 'CD', 'Africa/Lagos': 'NG', 'Africa/Libreville': 'GA', 'Africa/Lome': 'TG', 'Africa/Luanda': 'AO', 'Africa/Lubumbashi': 'CD', 'Africa/Lusaka': 'ZM', 'Africa/Malabo': 'GQ', 'Africa/Maputo': 'MZ', 'Africa/Maseru': 'LS', 'Africa/Mbabane': 'SZ', 'Africa/Mogadishu': 'SO', 'Africa/Monrovia': 'LR', 'Africa/Nairobi': 'KE', 'Africa/Ndjamena': 'TD', 'Africa/Niamey': 'NE', 'Africa/Nouakchott': 'MR', 'Africa/Ouagadougou': 'BF', 'Africa/Porto-Novo': 'BJ', 'Africa/Sao_Tome': 'ST', 'Africa/Tripoli': 'LY', 'Africa/Tunis': 'TN', 'Africa/Windhoek': 'NA', 'America/Adak': 'US', 'America/Anchorage': 'US', 'America/Anguilla': 'AI', 'America/Antigua': 'AG', 'America/Araguaina': 'BR', 'America/Argentina/Buenos_Aires': 'AR', 'America/Argentina/Catamarca': 'AR', 'America/Argentina/Cordoba': 'AR', 'America/Argentina/Jujuy': 'AR', 'America/Argentina/La_Rioja': 'AR', 'America/Argentina/Mendoza': 'AR', 'America/Argentina/Rio_Gallegos': 'AR', 'America/Argentina/Salta': 'AR', 'America/Argentina/San_Juan': 'AR', 'America/Argentina/San_Luis': 'AR', 'America/Argentina/Tucuman': 'AR', 'America/Argentina/Ushuaia': 'AR', 'America/Aruba': 'AW', 'America/Asuncion': 'PY', 'America/Atikokan': 'CA', 'America/Bahia_Banderas': 'MX', 'America/Bahia': 'BR', 'America/Barbados': 'BB', 'America/Belem': 'BR', 'America/Belize': 'BZ', 'America/Blanc-Sablon': 'CA', 'America/Boa_Vista': 'BR', 'America/Bogota': 'CO', 'America/Boise': 'US', 'America/Cambridge_Bay': 'CA', 'America/Campo_Grande': 'BR', 'America/Cancun': 'MX', 'America/Caracas': 'VE', 'America/Cayenne': 'GF', 'America/Cayman': 'KY', 'America/Chicago': 'US', 'America/Chihuahua': 'MX', 'America/Ciudad_Juarez': 'MX', 'America/Costa_Rica': 'CR', 'America/Creston': 'CA', 'America/Cuiaba': 'BR', 'America/Curacao': 'CW', 'America/Danmarkshavn': 'GL', 'America/Dawson_Creek': 'CA', 'America/Dawson': 'CA', 'America/Denver': 'US', 'America/Detroit': 'US', 'America/Dominica': 'DM', 'America/Edmonton': 'CA', 'America/Eirunepe': 'BR', 'America/El_Salvador': 'SV', 'America/Fort_Nelson': 'CA', 'America/Fortaleza': 'BR', 'America/Glace_Bay': 'CA', 'America/Goose_Bay': 'CA', 'America/Grand_Turk': 'TC', 'America/Grenada': 'GD', 'America/Guadeloupe': 'GP', 'America/Guatemala': 'GT', 'America/Guayaquil': 'EC', 'America/Guyana': 'GY', 'America/Halifax': 'CA', 'America/Havana': 'CU', 'America/Hermosillo': 'MX', 'America/Indiana/Indianapolis': 'US', 'America/Indiana/Knox': 'US', 'America/Indiana/Marengo': 'US', 'America/Indiana/Petersburg': 'US', 'America/Indiana/Tell_City': 'US', 'America/Indiana/Vevay': 'US', 'America/Indiana/Vincennes': 'US', 'America/Indiana/Winamac': 'US', 'America/Inuvik': 'CA', 'America/Iqaluit': 'CA', 'America/Jamaica': 'JM', 'America/Juneau': 'US', 'America/Kentucky/Louisville': 'US', 'America/Kentucky/Monticello': 'US', 'America/Kralendijk': 'BQ', 'America/La_Paz': 'BO', 'America/Lima': 'PE', 'America/Los_Angeles': 'US', 'America/Lower_Princes': 'SX', 'America/Maceio': 'BR', 'America/Managua': 'NI', 'America/Manaus': 'BR', 'America/Marigot': 'MF', 'America/Martinique': 'MQ', 'America/Matamoros': 'MX', 'America/Mazatlan': 'MX', 'America/Menominee': 'US', 'America/Merida': 'MX', 'America/Metlakatla': 'US', 'America/Mexico_City': 'MX', 'America/Miquelon': 'PM', 'America/Moncton': 'CA', 'America/Monterrey': 'MX', 'America/Montevideo': 'UY', 'America/Montserrat': 'MS', 'America/Nassau': 'BS', 'America/New_York': 'US', 'America/Nome': 'US', 'America/Noronha': 'BR', 'America/North_Dakota/Beulah': 'US', 'America/North_Dakota/Center': 'US', 'America/North_Dakota/New_Salem': 'US', 'America/Nuuk': 'GL', 'America/Ojinaga': 'MX', 'America/Panama': 'PA', 'America/Paramaribo': 'SR', 'America/Phoenix': 'US', 'America/Port_of_Spain': 'TT', 'America/Port-au-Prince': 'HT', 'America/Porto_Velho': 'BR', 'America/Puerto_Rico': 'PR', 'America/Punta_Arenas': 'CL', 'America/Rankin_Inlet': 'CA', 'America/Recife': 'BR', 'America/Regina': 'CA', 'America/Resolute': 'CA', 'America/Rio_Branco': 'BR', 'America/Santarem': 'BR', 'America/Santiago': 'CL', 'America/Santo_Domingo': 'DO', 'America/Sao_Paulo': 'BR', 'America/Scoresbysund': 'GL', 'America/Sitka': 'US', 'America/St_Barthelemy': 'BL', 'America/St_Johns': 'CA', 'America/St_Kitts': 'KN', 'America/St_Lucia': 'LC', 'America/St_Thomas': 'VI', 'America/St_Vincent': 'VC', 'America/Swift_Current': 'CA', 'America/Tegucigalpa': 'HN', 'America/Thule': 'GL', 'America/Tijuana': 'MX', 'America/Toronto': 'CA', 'America/Tortola': 'VG', 'America/Vancouver': 'CA', 'America/Whitehorse': 'CA', 'America/Winnipeg': 'CA', 'America/Yakutat': 'US', 'Antarctica/Casey': 'AQ', 'Antarctica/Davis': 'AQ', 'Antarctica/DumontDUrville': 'AQ', 'Antarctica/Macquarie': 'AU', 'Antarctica/Mawson': 'AQ', 'Antarctica/McMurdo': 'AQ', 'Antarctica/Palmer': 'AQ', 'Antarctica/Rothera': 'AQ', 'Antarctica/Syowa': 'AQ', 'Antarctica/Troll': 'AQ', 'Antarctica/Vostok': 'AQ', 'Arctic/Longyearbyen': 'SJ', 'Asia/Aden': 'YE', 'Asia/Almaty': 'KZ', 'Asia/Amman': 'JO', 'Asia/Anadyr': 'RU', 'Asia/Aqtau': 'KZ', 'Asia/Aqtobe': 'KZ', 'Asia/Ashgabat': 'TM', 'Asia/Atyrau': 'KZ', 'Asia/Baghdad': 'IQ', 'Asia/Bahrain': 'BH', 'Asia/Baku': 'AZ', 'Asia/Bangkok': 'TH', 'Asia/Barnaul': 'RU', 'Asia/Beirut': 'LB', 'Asia/Bishkek': 'KG', 'Asia/Brunei': 'BN', 'Asia/Chita': 'RU', 'Asia/Choibalsan': 'MN', 'Asia/Colombo': 'LK', 'Asia/Damascus': 'SY', 'Asia/Dhaka': 'BD', 'Asia/Dili': 'TL', 'Asia/Dubai': 'AE', 'Asia/Dushanbe': 'TJ', 'Asia/Famagusta': 'CY', 'Asia/Gaza': 'PS', 'Asia/Hebron': 'PS', 'Asia/Ho_Chi_Minh': 'VN', 'Asia/Hong_Kong': 'HK', 'Asia/Hovd': 'MN', 'Asia/Irkutsk': 'RU', 'Asia/Jakarta': 'ID', 'Asia/Jayapura': 'ID', 'Asia/Jerusalem': 'IL', 'Asia/Kabul': 'AF', 'Asia/Kamchatka': 'RU', 'Asia/Karachi': 'PK', 'Asia/Kathmandu': 'NP', 'Asia/Khandyga': 'RU', 'Asia/Kolkata': 'IN', 'Asia/Krasnoyarsk': 'RU', 'Asia/Kuala_Lumpur': 'MY', 'Asia/Kuching': 'MY', 'Asia/Kuwait': 'KW', 'Asia/Macau': 'MO', 'Asia/Magadan': 'RU', 'Asia/Makassar': 'ID', 'Asia/Manila': 'PH', 'Asia/Muscat': 'OM', 'Asia/Nicosia': 'CY', 'Asia/Novokuznetsk': 'RU', 'Asia/Novosibirsk': 'RU', 'Asia/Omsk': 'RU', 'Asia/Oral': 'KZ', 'Asia/Phnom_Penh': 'KH', 'Asia/Pontianak': 'ID', 'Asia/Pyongyang': 'KP', 'Asia/Qatar': 'QA', 'Asia/Qostanay': 'KZ', 'Asia/Qyzylorda': 'KZ', 'Asia/Riyadh': 'SA', 'Asia/Sakhalin': 'RU', 'Asia/Samarkand': 'UZ', 'Asia/Seoul': 'KR', 'Asia/Shanghai': 'CN', 'Asia/Singapore': 'SG', 'Asia/Srednekolymsk': 'RU', 'Asia/Taipei': 'TW', 'Asia/Tashkent': 'UZ', 'Asia/Tbilisi': 'GE', 'Asia/Tehran': 'IR', 'Asia/Thimphu': 'BT', 'Asia/Tokyo': 'JP', 'Asia/Tomsk': 'RU', 'Asia/Ulaanbaatar': 'MN', 'Asia/Urumqi': 'CN', 'Asia/Ust-Nera': 'RU', 'Asia/Vientiane': 'LA', 'Asia/Vladivostok': 'RU', 'Asia/Yakutsk': 'RU', 'Asia/Yangon': 'MM', 'Asia/Yekaterinburg': 'RU', 'Asia/Yerevan': 'AM', 'Atlantic/Azores': 'PT', 'Atlantic/Bermuda': 'BM', 'Atlantic/Canary': 'ES', 'Atlantic/Cape_Verde': 'CV', 'Atlantic/Faroe': 'FO', 'Atlantic/Madeira': 'PT', 'Atlantic/Reykjavik': 'IS', 'Atlantic/South_Georgia': 'GS', 'Atlantic/St_Helena': 'SH', 'Atlantic/Stanley': 'FK', 'Australia/Adelaide': 'AU', 'Australia/Brisbane': 'AU', 'Australia/Broken_Hill': 'AU', 'Australia/Darwin': 'AU', 'Australia/Eucla': 'AU', 'Australia/Hobart': 'AU', 'Australia/Lindeman': 'AU', 'Australia/Lord_Howe': 'AU', 'Australia/Melbourne': 'AU', 'Australia/Perth': 'AU', 'Australia/Sydney': 'AU', 'Europe/Amsterdam': 'NL', 'Europe/Andorra': 'AD', 'Europe/Astrakhan': 'RU', 'Europe/Athens': 'GR', 'Europe/Belgrade': 'RS', 'Europe/Berlin': 'DE', 'Europe/Bratislava': 'SK', 'Europe/Brussels': 'BE', 'Europe/Bucharest': 'RO', 'Europe/Budapest': 'HU', 'Europe/Busingen': 'DE', 'Europe/Chisinau': 'MD', 'Europe/Copenhagen': 'DK', 'Europe/Dublin': 'IE', 'Europe/Gibraltar': 'GI', 'Europe/Guernsey': 'GG', 'Europe/Helsinki': 'FI', 'Europe/Isle_of_Man': 'IM', 'Europe/Istanbul': 'TR', 'Europe/Jersey': 'JE', 'Europe/Kaliningrad': 'RU', 'Europe/Kirov': 'RU', 'Europe/Kyiv': 'UA', 'Europe/Lisbon': 'PT', 'Europe/Ljubljana': 'SI', 'Europe/London': 'GB', 'Europe/Luxembourg': 'LU', 'Europe/Madrid': 'ES', 'Europe/Malta': 'MT', 'Europe/Mariehamn': 'AX', 'Europe/Minsk': 'BY', 'Europe/Monaco': 'MC', 'Europe/Moscow': 'RU', 'Europe/Oslo': 'NO', 'Europe/Paris': 'FR', 'Europe/Podgorica': 'ME', 'Europe/Prague': 'CZ', 'Europe/Riga': 'LV', 'Europe/Rome': 'IT', 'Europe/Samara': 'RU', 'Europe/San_Marino': 'SM', 'Europe/Sarajevo': 'BA', 'Europe/Saratov': 'RU', 'Europe/Simferopol': 'RU', 'Europe/Skopje': 'MK', 'Europe/Sofia': 'BG', 'Europe/Stockholm': 'SE', 'Europe/Tallinn': 'EE', 'Europe/Tirane': 'AL', 'Europe/Ulyanovsk': 'RU', 'Europe/Vaduz': 'LI', 'Europe/Vatican': 'VA', 'Europe/Vienna': 'AT', 'Europe/Vilnius': 'LT', 'Europe/Volgograd': 'RU', 'Europe/Warsaw': 'PL', 'Europe/Zagreb': 'HR', 'Europe/Zurich': 'CH', 'Indian/Antananarivo': 'MG', 'Indian/Chagos': 'IO', 'Indian/Christmas': 'CX', 'Indian/Cocos': 'CC', 'Indian/Comoro': 'KM', 'Indian/Kerguelen': 'TF', 'Indian/Mahe': 'SC', 'Indian/Maldives': 'MV', 'Indian/Mauritius': 'MU', 'Indian/Mayotte': 'YT', 'Indian/Reunion': 'RE', 'Pacific/Apia': 'WS', 'Pacific/Auckland': 'NZ', 'Pacific/Bougainville': 'PG', 'Pacific/Chatham': 'NZ', 'Pacific/Chuuk': 'FM', 'Pacific/Easter': 'CL', 'Pacific/Efate': 'VU', 'Pacific/Fakaofo': 'TK', 'Pacific/Fiji': 'FJ', 'Pacific/Funafuti': 'TV', 'Pacific/Galapagos': 'EC', 'Pacific/Gambier': 'PF', 'Pacific/Guadalcanal': 'SB', 'Pacific/Guam': 'GU', 'Pacific/Honolulu': 'US', 'Pacific/Kanton': 'KI', 'Pacific/Kiritimati': 'KI', 'Pacific/Kosrae': 'FM', 'Pacific/Kwajalein': 'MH', 'Pacific/Majuro': 'MH', 'Pacific/Marquesas': 'PF', 'Pacific/Midway': 'UM', 'Pacific/Nauru': 'NR', 'Pacific/Niue': 'NU', 'Pacific/Norfolk': 'NF', 'Pacific/Noumea': 'NC', 'Pacific/Pago_Pago': 'AS', 'Pacific/Palau': 'PW', 'Pacific/Pitcairn': 'PN', 'Pacific/Pohnpei': 'FM', 'Pacific/Port_Moresby': 'PG', 'Pacific/Rarotonga': 'CK', 'Pacific/Saipan': 'MP', 'Pacific/Tahiti': 'PF', 'Pacific/Tarawa': 'KI', 'Pacific/Tongatapu': 'TO', 'Pacific/Wake': 'UM', 'Pacific/Wallis': 'WF', };
8,447
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date/timezone.ts
import { findTimeZone, getTimeZoneLinks, getUTCOffset, getZonedTime } from '@protontech/timezone-support'; import isTruthy from '@proton/utils/isTruthy'; import { getAllowedTimeZones } from '../api/calendars'; import { SECOND } from '../constants'; import { Api } from '../interfaces'; import { DateTime } from '../interfaces/calendar/Date'; import { FALLBACK_ALLOWED_SUPPORTED_TIMEZONES_LIST, MANUAL_TIMEZONE_EQUIVALENCE, MANUAL_TIMEZONE_LINKS, manualFindTimeZone, unsupportedTimezoneLinks, } from './timezoneDatabase'; export const toLocalDate = ({ year = 0, month = 1, day = 0, hours = 0, minutes = 0, seconds = 0, }: Partial<DateTime>) => { return new Date(year, month - 1, day, hours, minutes, seconds); }; export const toUTCDate = ({ year = 0, month = 1, day = 0, hours = 0, minutes = 0, seconds = 0 }: Partial<DateTime>) => { return new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds)); }; export const fromLocalDate = (date: Date) => { return { year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate(), hours: date.getHours(), minutes: date.getMinutes(), seconds: date.getSeconds(), }; }; export const fromUTCDate = (date: Date) => { return { year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate(), hours: date.getUTCHours(), minutes: date.getUTCMinutes(), seconds: date.getUTCSeconds(), }; }; // The list of all IANA time zones that we support is fetched from the BE at app load export let ALLOWED_TIMEZONES_LIST: string[] = [...FALLBACK_ALLOWED_SUPPORTED_TIMEZONES_LIST]; /** * Load from API list of time zones that the BE allows * */ export const loadAllowedTimeZones = async (api: Api) => { const { Timezones } = await api<{ Code: number; Timezones: string[] }>(getAllowedTimeZones()); /* * We remove time zones that we cannot parse. In practice there should never be a need for this, * but because time zone updating is a manual process involving multiple teams, better be extra safe to avoid app crashes. * * The time it takes to run this code is one order of magnitude less than the API call above, * so it doesn't significatively decrease the performance of this function. If we ever need better * performance, there's room for improvement */ const supportedTimeZones = Timezones.map((tzid) => { try { findTimeZone(tzid); return tzid; } catch (e: any) { console.error(`${tzid} not supported`); } }).filter(isTruthy); ALLOWED_TIMEZONES_LIST = supportedTimeZones; }; export const guessTimezone = (timezones: string[]) => { try { const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; // Ensure it belongs in the list const tzid = manualFindTimeZone(timeZone) || findTimeZone(timeZone).name; const supportedTzid = unsupportedTimezoneLinks[tzid] || tzid; if (!timezones.includes(supportedTzid)) { throw new Error('Time zone not allowed'); } return supportedTzid; } catch (error: any) { const date = new Date(); const timezoneOffset = date.getTimezoneOffset(); return timezones.find((tz) => { const { zone } = getZonedTime(date, findTimeZone(tz)); return zone ? zone.offset === timezoneOffset : false; }); } }; /** * Get current timezone id by using Intl * if not available use timezone-support lib and pick the first timezone from the current date timezone offset */ export const getTimezone = () => { const ianaTimezones = ALLOWED_TIMEZONES_LIST; const timezone = guessTimezone(ianaTimezones); // If the guessed timezone is undefined, there's not much we can do if (!timezone) { return ALLOWED_TIMEZONES_LIST[0]; } return timezone; }; /** * Given a date and a timezone, return an object that contains information about the * UTC offset of that date in that timezone. Namely an offset abbreviation (e.g. 'CET') * and the UTC offset itself in minutes */ export const getTimezoneOffset = (nowDate: Date, tzid: string) => { return getUTCOffset(nowDate, findTimeZone(tzid)); }; export const formatTimezoneOffset = (offset: number) => { // offset comes with the opposite sign in the timezone-support library const sign = Math.sign(offset) === 1 ? '-' : '+'; const minutes = Math.abs(offset % 60); const hours = (Math.abs(offset) - minutes) / 60; if (minutes > 0) { const paddedMinutes = minutes < 10 ? `0${minutes}` : `${minutes}`; return `${sign}${hours}:${paddedMinutes}`; } return `${sign}${hours}`; }; export const formatGMTOffsetAbbreviation = (offset: number) => { return `GMT${formatTimezoneOffset(offset)}`; }; interface FormatterProps { utcOffset: string; name: string; } type GetTimeZoneOptions = ( date?: Date, options?: { formatter?: (a1: FormatterProps) => string } ) => { text: string; value: string; key: string; }[]; const getTimeZoneDisplayName = (ianaName: string) => { if (ianaName === 'Europe/Kiev') { // Update Kyiv name before fully transitioning to 2022g return 'Europe/Kyiv'; } return ianaName; }; /** * @return {Array<Object>} [{ text: 'Africa/Nairobi: UTC +03:00', value: 'Africa/Nairobi'}, ...] */ export const getTimeZoneOptions: GetTimeZoneOptions = ( date = new Date(), { formatter = ({ utcOffset, name }: FormatterProps) => `${utcOffset} • ${name}` } = {} ) => { return ALLOWED_TIMEZONES_LIST.map((name) => { const { abbreviation, offset } = getUTCOffset(date, findTimeZone(name)); return { name, offset, abbreviation, }; }) .sort(({ offset: offsetA, name: nameA }, { offset: offsetB, name: nameB }) => { const diff = offsetA - offsetB; if (diff === 0) { return nameA.localeCompare(nameB); } return diff; }) .map(({ name: ianaName, offset }) => { const name = getTimeZoneDisplayName(ianaName); return { text: formatter({ name, utcOffset: `GMT${formatTimezoneOffset(offset)}` }), value: ianaName, key: ianaName, }; }); }; /** * Given two time zone ids, determine if they are equivalent. * */ export const getIsEquivalentTimeZone = (tzid1: string, tzid2: string) => { const equivalentTimeZone1 = MANUAL_TIMEZONE_EQUIVALENCE[tzid1] || tzid1; const equivalentTimeZone2 = MANUAL_TIMEZONE_EQUIVALENCE[tzid2] || tzid2; return equivalentTimeZone1 === equivalentTimeZone2; }; /** * Given a timezone id, try to convert it into an iana timezone supported by the API (cf. description of unsupportedTimezoneLinks function) * No longer supported timezones are converted into supported ones * Alias timezones are converted into canonical-and-supported ones * We try to convert other possible strange timezones, like those produced by Outlook calendar * If no conversion is possible, return undefined */ export const getSupportedTimezone = (tzid: string): string | undefined => { try { const timezone = findTimeZone(tzid).name; return unsupportedTimezoneLinks[timezone] || timezone; } catch (e: any) { // clean tzid of offsets const offsetRegex = /^\((?:UTC|GMT).*\) (.*)$|^(.*) \((?:UTC|GMT).*\)/i; const match = offsetRegex.exec(tzid); const strippedTzid = match ? match[1] || match[2] : tzid; const normalizedTzid = strippedTzid.toLowerCase().replace(/\./g, ''); // try manual conversions const timezone = MANUAL_TIMEZONE_LINKS[normalizedTzid]; if (timezone) { return timezone; } // It might be a globally unique timezone identifier, whose specification is not addressed by the RFC. // We try to match it with one of our supported list by brute force. We should fall here rarely const lowerCaseStrippedTzid = strippedTzid.toLowerCase(); const supportedTimezone = ALLOWED_TIMEZONES_LIST.find((supportedTzid) => lowerCaseStrippedTzid.includes(supportedTzid.toLowerCase()) ); if (supportedTimezone) { return supportedTimezone; } // Try alias timezones const aliasMap = getTimeZoneLinks(); // some alias names have overlap (e.g. GB-Eire and Eire). To find the longest match, we sort them by decreasing length const sortedAlias = Object.keys(aliasMap).sort((a: string, b: string) => b.length - a.length); for (const alias of sortedAlias) { if (lowerCaseStrippedTzid.includes(alias.toLowerCase())) { return aliasMap[alias]; } } } }; const findUTCTransitionIndex = ({ unixTime, untils }: { unixTime: number; untils: number[] }) => { const max = untils.length - 1; for (let i = 0; i < max; i++) { if (unixTime < untils[i]) { return i; } } return max; }; /** * @param moveAmbiguousForward move an ambiguous date like Sunday 27 October 2019 2:00 AM CET, which corresponds to two times because of DST change, to the latest of the two * @param moveInvalidForward move an invalid date like Sunday 31 March 2019 2:00 AM CET, which does not correspond to any time because of DST change, to Sunday 31 March 2019 3:00 AM CET */ const findZoneTransitionIndex = ({ unixTime, untils, offsets, moveAmbiguousForward = true, moveInvalidForward = true, }: { unixTime: number; untils: number[]; offsets: number[]; moveAmbiguousForward?: boolean; moveInvalidForward?: boolean; }) => { const max = untils.length - 1; for (let i = 0; i < max; i++) { const offsetNext = offsets[i + 1]; const offsetPrev = offsets[i ? i - 1 : i]; let offset = offsets[i]; if (offset < offsetNext && moveAmbiguousForward) { offset = offsetNext; } else if (offset > offsetPrev && moveInvalidForward) { offset = offsetPrev; } if (unixTime < untils[i] - offset * 60000) { return i; } } return max; }; interface ConvertZonedDateTimeOptions { moveAmbiguousForward?: boolean; moveInvalidForward?: boolean; } export const convertZonedDateTimeToUTC = (dateTime: DateTime, tzid: string, options?: ConvertZonedDateTimeOptions) => { const timezone = findTimeZone(tzid); const unixTime = Date.UTC( dateTime.year, dateTime.month - 1, dateTime.day, dateTime.hours, dateTime.minutes, dateTime.seconds || 0 ); const idx = findZoneTransitionIndex({ ...options, unixTime, untils: timezone.untils, offsets: timezone.offsets, }); const offset = timezone.offsets[idx]; const date = new Date(unixTime + offset * 60000); return fromUTCDate(date); }; export const convertUTCDateTimeToZone = (dateTime: DateTime, tzid: string) => { const timezone = findTimeZone(tzid); const unixTime = Date.UTC( dateTime.year, dateTime.month - 1, dateTime.day, dateTime.hours, dateTime.minutes, dateTime.seconds || 0 ); const idx = findUTCTransitionIndex({ unixTime, untils: timezone.untils }); const offset = timezone.offsets[idx]; const date = new Date(unixTime - offset * 60000); return fromUTCDate(date); }; export const fromUTCDateToLocalFakeUTCDate = (utcDate: Date, isAllDay: boolean, tzid = 'UTC') => { return isAllDay ? utcDate : toUTCDate(convertUTCDateTimeToZone(fromUTCDate(utcDate), tzid)); }; export const convertTimestampToTimezone = (timestamp: number, timezone: string) => { return convertUTCDateTimeToZone(fromUTCDate(new Date(timestamp * SECOND)), timezone); }; /** * Remove potential underscores from time zone city * E.g. "Los_Angeles" should become "Los Angeles" */ export const getReadableCityTimezone = (timezone: string = '') => { return timezone.replaceAll('_', ' '); }; export type AbbreviatedTimezone = 'offset' | 'city'; /** * Get an abbreviated time zone, from AbbreviatedTimezone type: * - "offset": "Europe/Paris" should return "GMT+1" (winter time) or 'GMT+2' (summer time) * - "city": "EuropesParis" should return "Paris" */ export const getAbbreviatedTimezoneName = (abbreviatedTimezone: AbbreviatedTimezone, timezone: string | undefined) => { if (timezone) { if (abbreviatedTimezone === 'offset') { const timezoneOffset = getTimezoneOffset(new Date(), timezone).offset; const abbreviatedTimezoneName = formatGMTOffsetAbbreviation(timezoneOffset); return abbreviatedTimezoneName; } if (abbreviatedTimezone === 'city') { // Return the city if found e.g "Europe/Paris" should return "Paris" const match = getTimeZoneDisplayName(timezone).match(/(.+?)(?:\/|$)/g); // However, we can also get longer time zones. That's why we need to take the last matched element // e.g. "America/North_Dakota/New_Salem" should return "New Salem" return getReadableCityTimezone(match?.[match?.length - 1]) || timezone; } } }; export const getTimezoneAndOffset = (timezone?: string) => { const timezoneOffset = getAbbreviatedTimezoneName('offset', timezone); const timezoneName = getTimeZoneDisplayName(timezone || ''); return `${timezoneOffset} • ${timezoneName}`; };
8,448
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/date/timezoneDatabase.ts
// Fall back list of supported time zones. It should be updated manually when the BE deploys a new list. // This list is only used as a fallback in case at app load the call to fetch BE time zones fails export const FALLBACK_ALLOWED_SUPPORTED_TIMEZONES_LIST = [ 'Africa/Abidjan', 'Africa/Accra', 'Africa/Nairobi', 'Africa/Algiers', 'Africa/Lagos', 'Africa/Bissau', 'Africa/Maputo', 'Africa/Cairo', 'Africa/Casablanca', 'Africa/Ceuta', 'Africa/El_Aaiun', 'Africa/Johannesburg', 'Africa/Juba', 'Africa/Khartoum', 'Africa/Monrovia', 'Africa/Ndjamena', 'Africa/Sao_Tome', 'Africa/Tripoli', 'Africa/Tunis', 'Africa/Windhoek', 'America/Adak', 'America/Anchorage', 'America/Port_of_Spain', 'America/Araguaina', 'America/Argentina/Buenos_Aires', 'America/Argentina/Catamarca', 'America/Argentina/Cordoba', 'America/Argentina/Jujuy', 'America/Argentina/La_Rioja', 'America/Argentina/Mendoza', 'America/Argentina/Rio_Gallegos', 'America/Argentina/Salta', 'America/Argentina/San_Juan', 'America/Argentina/San_Luis', 'America/Argentina/Tucuman', 'America/Argentina/Ushuaia', 'America/Curacao', 'America/Asuncion', 'America/Atikokan', 'America/Bahia_Banderas', 'America/Bahia', 'America/Barbados', 'America/Belem', 'America/Belize', 'America/Blanc-Sablon', 'America/Boa_Vista', 'America/Bogota', 'America/Boise', 'America/Cambridge_Bay', 'America/Campo_Grande', 'America/Cancun', 'America/Caracas', 'America/Cayenne', 'America/Panama', 'America/Chicago', 'America/Chihuahua', 'America/Costa_Rica', 'America/Creston', 'America/Cuiaba', 'America/Danmarkshavn', 'America/Dawson_Creek', 'America/Dawson', 'America/Denver', 'America/Detroit', 'America/Edmonton', 'America/Eirunepe', 'America/El_Salvador', 'America/Tijuana', 'America/Fort_Nelson', 'America/Fortaleza', 'America/Glace_Bay', 'America/Goose_Bay', 'America/Grand_Turk', 'America/Guatemala', 'America/Guayaquil', 'America/Guyana', 'America/Halifax', 'America/Havana', 'America/Hermosillo', 'America/Indiana/Knox', 'America/Indiana/Marengo', 'America/Indiana/Petersburg', 'America/Indiana/Tell_City', 'America/Indiana/Vevay', 'America/Indiana/Vincennes', 'America/Indiana/Winamac', 'America/Inuvik', 'America/Iqaluit', 'America/Jamaica', 'America/Juneau', 'America/Kentucky/Louisville', 'America/Kentucky/Monticello', 'America/La_Paz', 'America/Lima', 'America/Los_Angeles', 'America/Maceio', 'America/Managua', 'America/Manaus', 'America/Martinique', 'America/Matamoros', 'America/Mazatlan', 'America/Menominee', 'America/Merida', 'America/Metlakatla', 'America/Mexico_City', 'America/Miquelon', 'America/Moncton', 'America/Monterrey', 'America/Montevideo', 'America/Toronto', 'America/Nassau', 'America/New_York', 'America/Nipigon', 'America/Nome', 'America/Noronha', 'America/North_Dakota/Beulah', 'America/North_Dakota/Center', 'America/North_Dakota/New_Salem', 'America/Ojinaga', 'America/Pangnirtung', 'America/Paramaribo', 'America/Phoenix', 'America/Port-au-Prince', 'America/Rio_Branco', 'America/Porto_Velho', 'America/Puerto_Rico', 'America/Punta_Arenas', 'America/Rainy_River', 'America/Rankin_Inlet', 'America/Recife', 'America/Regina', 'America/Resolute', 'America/Santarem', 'America/Santiago', 'America/Santo_Domingo', 'America/Sao_Paulo', 'America/Scoresbysund', 'America/Sitka', 'America/St_Johns', 'America/Swift_Current', 'America/Tegucigalpa', 'America/Thule', 'America/Thunder_Bay', 'America/Vancouver', 'America/Whitehorse', 'America/Winnipeg', 'America/Yakutat', 'America/Yellowknife', 'Antarctica/Casey', 'Antarctica/Davis', 'Antarctica/DumontDUrville', 'Antarctica/Macquarie', 'Antarctica/Mawson', 'Pacific/Auckland', 'Antarctica/Palmer', 'Antarctica/Rothera', 'Antarctica/Syowa', 'Antarctica/Troll', 'Antarctica/Vostok', 'Europe/Oslo', 'Asia/Riyadh', 'Asia/Almaty', 'Asia/Amman', 'Asia/Anadyr', 'Asia/Aqtau', 'Asia/Aqtobe', 'Asia/Ashgabat', 'Asia/Atyrau', 'Asia/Baghdad', 'Asia/Qatar', 'Asia/Baku', 'Asia/Bangkok', 'Asia/Barnaul', 'Asia/Beirut', 'Asia/Bishkek', 'Asia/Brunei', 'Asia/Kolkata', 'Asia/Chita', 'Asia/Choibalsan', 'Asia/Shanghai', 'Asia/Colombo', 'Asia/Dhaka', 'Asia/Damascus', 'Asia/Dili', 'Asia/Dubai', 'Asia/Dushanbe', 'Asia/Famagusta', 'Asia/Gaza', 'Asia/Hebron', 'Asia/Ho_Chi_Minh', 'Asia/Hong_Kong', 'Asia/Hovd', 'Asia/Irkutsk', 'Europe/Istanbul', 'Asia/Jakarta', 'Asia/Jayapura', 'Asia/Jerusalem', 'Asia/Kabul', 'Asia/Kamchatka', 'Asia/Karachi', 'Asia/Urumqi', 'Asia/Kathmandu', 'Asia/Khandyga', 'Asia/Krasnoyarsk', 'Asia/Kuala_Lumpur', 'Asia/Kuching', 'Asia/Macau', 'Asia/Magadan', 'Asia/Makassar', 'Asia/Manila', 'Asia/Nicosia', 'Asia/Novokuznetsk', 'Asia/Novosibirsk', 'Asia/Omsk', 'Asia/Oral', 'Asia/Pontianak', 'Asia/Pyongyang', 'Asia/Qostanay', 'Asia/Qyzylorda', 'Asia/Sakhalin', 'Asia/Samarkand', 'Asia/Seoul', 'Asia/Srednekolymsk', 'Asia/Taipei', 'Asia/Tashkent', 'Asia/Tbilisi', 'Asia/Tehran', 'Asia/Thimphu', 'Asia/Tokyo', 'Asia/Tomsk', 'Asia/Ulaanbaatar', 'Asia/Ust-Nera', 'Asia/Vladivostok', 'Asia/Yakutsk', 'Asia/Yekaterinburg', 'Asia/Yerevan', 'Atlantic/Azores', 'Atlantic/Bermuda', 'Atlantic/Canary', 'Atlantic/Cape_Verde', 'Atlantic/Faroe', 'Atlantic/Madeira', 'Atlantic/Reykjavik', 'Atlantic/South_Georgia', 'Atlantic/Stanley', 'Australia/Sydney', 'Australia/Adelaide', 'Australia/Brisbane', 'Australia/Broken_Hill', 'Australia/Currie', 'Australia/Darwin', 'Australia/Eucla', 'Australia/Hobart', 'Australia/Lord_Howe', 'Australia/Lindeman', 'Australia/Melbourne', 'Australia/Perth', 'Pacific/Easter', 'Europe/Dublin', 'Pacific/Port_Moresby', 'Pacific/Tarawa', 'Indian/Christmas', 'Pacific/Palau', 'Europe/Amsterdam', 'Europe/Andorra', 'Europe/Astrakhan', 'Europe/Athens', 'Europe/London', 'Europe/Belgrade', 'Europe/Berlin', 'Europe/Prague', 'Europe/Brussels', 'Europe/Bucharest', 'Europe/Budapest', 'Europe/Zurich', 'Europe/Chisinau', 'Europe/Copenhagen', 'Europe/Gibraltar', 'Europe/Helsinki', 'Europe/Kaliningrad', 'Europe/Kiev', 'Europe/Kirov', 'Europe/Lisbon', 'Europe/Luxembourg', 'Europe/Madrid', 'Europe/Malta', 'Europe/Minsk', 'Europe/Monaco', 'Europe/Moscow', 'Europe/Paris', 'Europe/Riga', 'Europe/Rome', 'Europe/Samara', 'Europe/Saratov', 'Europe/Simferopol', 'Europe/Sofia', 'Europe/Stockholm', 'Europe/Tallinn', 'Europe/Tirane', 'Europe/Ulyanovsk', 'Europe/Uzhgorod', 'Europe/Vienna', 'Europe/Vilnius', 'Europe/Volgograd', 'Europe/Warsaw', 'Europe/Zaporozhye', 'Indian/Chagos', 'Indian/Cocos', 'Indian/Kerguelen', 'Indian/Mahe', 'Indian/Maldives', 'Indian/Mauritius', 'Indian/Reunion', 'Pacific/Kwajalein', 'Pacific/Chatham', 'Pacific/Apia', 'Pacific/Bougainville', 'Pacific/Chuuk', 'Pacific/Efate', 'Pacific/Fakaofo', 'Pacific/Fiji', 'Pacific/Galapagos', 'Pacific/Gambier', 'Pacific/Guadalcanal', 'Pacific/Guam', 'Pacific/Honolulu', 'Pacific/Kiritimati', 'Pacific/Kosrae', 'Pacific/Majuro', 'Pacific/Marquesas', 'Pacific/Pago_Pago', 'Pacific/Nauru', 'Pacific/Niue', 'Pacific/Norfolk', 'Pacific/Noumea', 'Pacific/Pitcairn', 'Pacific/Pohnpei', 'Pacific/Rarotonga', 'Pacific/Tahiti', 'Pacific/Tongatapu', 'UTC', ]; /* * The list of timezones supported by FE is given by the function listTimezones(), * which returns the timezones in the 2019c iana database. That database is backward-compatible * (the list of timezones keeps changing because humans keep making crazy irrational decisions). * The API does not like backward-compatibility though, and they only support some of those * timezones (loosely based on https://www.php.net/manual/en/timezones.php). The list of timezones * recognized by FE but not supported by BE are the ones that serve as entries for the object below. * The value for each entry is the supported timezone we will re-direct to */ export const unsupportedTimezoneLinks: { [key: string]: string } = { 'America/Indiana/Indianapolis': 'America/New_York', 'America/Fort_Wayne': 'America/New_York', 'America/Godthab': 'Atlantic/Stanley', 'Asia/Singapore': 'Asia/Shanghai', 'Asia/Rangoon': 'Indian/Cocos', 'Asia/Yangon': 'Indian/Cocos', 'Pacific/Funafuti': 'Asia/Kamchatka', 'Pacific/Wake': 'Asia/Kamchatka', 'Pacific/Wallis': 'Asia/Kamchatka', 'Pacific/Enderbury': 'Pacific/Fakaofo', CET: 'Europe/Paris', CST6CDT: 'America/Chicago', EET: 'Europe/Istanbul', EST: 'America/New_York', EST5EDT: 'America/New_York', 'Etc/GMT+1': 'Atlantic/Cape_Verde', 'Etc/GMT+10': 'Pacific/Tahiti', 'Etc/GMT+11': 'Pacific/Niue', 'Etc/GMT+12': 'Pacific/Niue', // no canonical timezone exists for GMT+12 'Etc/GMT+2': 'America/Noronha', 'Etc/GMT+3': 'America/Sao_Paulo', 'Etc/GMT+4': 'America/Caracas', 'Etc/GMT+5': 'America/Lima', 'Etc/GMT+6': 'America/Managua', 'Etc/GMT+7': 'America/Phoenix', 'Etc/GMT+8': 'Pacific/Pitcairn', 'Etc/GMT+9': 'Pacific/Gambier', 'Etc/GMT-0': 'UTC', 'Etc/GMT-1': 'Europe/Paris', 'Etc/GMT-10': 'Australia/Brisbane', 'Etc/GMT-11': 'Australia/Sydney', 'Etc/GMT-12': 'Pacific/Auckland', 'Etc/GMT-13': 'Pacific/Fakaofo', 'Etc/GMT-14': 'Pacific/Kiritimati', 'Etc/GMT-2': 'Africa/Cairo', 'Etc/GMT-3': 'Asia/Baghdad', 'Etc/GMT-4': 'Asia/Dubai', 'Etc/GMT-5': 'Asia/Tashkent', 'Etc/GMT-6': 'Asia/Dhaka', 'Etc/GMT-7': 'Asia/Jakarta', 'Etc/GMT-8': 'Asia/Shanghai', 'Etc/GMT-9': 'Asia/Tokyo', 'Etc/UTC': 'UTC', HST: 'Pacific/Honolulu', MET: 'Europe/Paris', MST: 'Europe/Paris', MST7MDT: 'America/Denver', PST8PDT: 'America/Los_Angeles', WET: 'Europe/Lisbon', // 2022g update 'America/Ciudad_Juarez': 'America/Ojinaga', 'America/Nuuk': 'Atlantic/Stanley', 'Europe/Kyiv': 'Europe/Kiev', 'Australia/Hobart': 'Australia/Currie', 'Pacific/Kanton': 'Pacific/Fakaofo', }; /** * Map of "equivalent" time zones. Our definition of equivalence is as follows: * * Two time zones are considered equivalent if their UTC offsets and their respective changes (due to DST or re-definitions) * match in the period 2010 - 2030. This map is provided by the back-end so that all clients are aligned with it */ export const MANUAL_TIMEZONE_EQUIVALENCE: { [key: string]: string } = { 'Africa/Abidjan': 'Africa/Abidjan', 'Africa/Accra': 'Africa/Abidjan', 'Africa/Bissau': 'Africa/Abidjan', 'Africa/Monrovia': 'Africa/Abidjan', 'America/Danmarkshavn': 'Africa/Abidjan', 'Atlantic/Reykjavik': 'Africa/Abidjan', UTC: 'Africa/Abidjan', 'Africa/Algiers': 'Africa/Algiers', 'Africa/Lagos': 'Africa/Algiers', 'Africa/Ndjamena': 'Africa/Algiers', 'Africa/Tunis': 'Africa/Algiers', 'Africa/Cairo': 'Africa/Cairo', 'Africa/Casablanca': 'Africa/Casablanca', 'Africa/El_Aaiun': 'Africa/Casablanca', 'Africa/Ceuta': 'Africa/Ceuta', 'Europe/Amsterdam': 'Africa/Ceuta', 'Europe/Andorra': 'Africa/Ceuta', 'Europe/Belgrade': 'Africa/Ceuta', 'Europe/Berlin': 'Africa/Ceuta', 'Europe/Brussels': 'Africa/Ceuta', 'Europe/Budapest': 'Africa/Ceuta', 'Europe/Copenhagen': 'Africa/Ceuta', 'Europe/Gibraltar': 'Africa/Ceuta', 'Europe/Luxembourg': 'Africa/Ceuta', 'Europe/Madrid': 'Africa/Ceuta', 'Europe/Malta': 'Africa/Ceuta', 'Europe/Monaco': 'Africa/Ceuta', 'Europe/Oslo': 'Africa/Ceuta', 'Europe/Paris': 'Africa/Ceuta', 'Europe/Prague': 'Africa/Ceuta', 'Europe/Rome': 'Africa/Ceuta', 'Europe/Stockholm': 'Africa/Ceuta', 'Europe/Tirane': 'Africa/Ceuta', 'Europe/Vienna': 'Africa/Ceuta', 'Europe/Warsaw': 'Africa/Ceuta', 'Europe/Zurich': 'Africa/Ceuta', 'Africa/Johannesburg': 'Africa/Johannesburg', 'Africa/Maputo': 'Africa/Johannesburg', 'Africa/Juba': 'Africa/Juba', 'Africa/Nairobi': 'Africa/Juba', 'Antarctica/Syowa': 'Africa/Juba', 'Asia/Baghdad': 'Africa/Juba', 'Asia/Qatar': 'Africa/Juba', 'Asia/Riyadh': 'Africa/Juba', 'Africa/Khartoum': 'Africa/Khartoum', 'Africa/Sao_Tome': 'Africa/Sao_Tome', 'Africa/Tripoli': 'Africa/Tripoli', 'Africa/Windhoek': 'Africa/Windhoek', 'America/Adak': 'America/Adak', 'America/Anchorage': 'America/Anchorage', 'America/Juneau': 'America/Anchorage', 'America/Nome': 'America/Anchorage', 'America/Sitka': 'America/Anchorage', 'America/Yakutat': 'America/Anchorage', 'America/Araguaina': 'America/Araguaina', 'America/Argentina/Buenos_Aires': 'America/Argentina/Buenos_Aires', 'America/Argentina/Catamarca': 'America/Argentina/Buenos_Aires', 'America/Argentina/Cordoba': 'America/Argentina/Buenos_Aires', 'America/Argentina/Jujuy': 'America/Argentina/Buenos_Aires', 'America/Argentina/La_Rioja': 'America/Argentina/Buenos_Aires', 'America/Argentina/Mendoza': 'America/Argentina/Buenos_Aires', 'America/Argentina/Rio_Gallegos': 'America/Argentina/Buenos_Aires', 'America/Argentina/Salta': 'America/Argentina/Buenos_Aires', 'America/Argentina/San_Juan': 'America/Argentina/Buenos_Aires', 'America/Argentina/San_Luis': 'America/Argentina/Buenos_Aires', 'America/Argentina/Tucuman': 'America/Argentina/Buenos_Aires', 'America/Argentina/Ushuaia': 'America/Argentina/Buenos_Aires', 'America/Belem': 'America/Argentina/Buenos_Aires', 'America/Cayenne': 'America/Argentina/Buenos_Aires', 'America/Fortaleza': 'America/Argentina/Buenos_Aires', 'America/Maceio': 'America/Argentina/Buenos_Aires', 'America/Paramaribo': 'America/Argentina/Buenos_Aires', 'America/Recife': 'America/Argentina/Buenos_Aires', 'America/Santarem': 'America/Argentina/Buenos_Aires', 'Antarctica/Rothera': 'America/Argentina/Buenos_Aires', 'America/Asuncion': 'America/Asuncion', 'America/Atikokan': 'America/Atikokan', 'America/Bogota': 'America/Atikokan', 'America/Guayaquil': 'America/Atikokan', 'America/Jamaica': 'America/Atikokan', 'America/Lima': 'America/Atikokan', 'America/Panama': 'America/Atikokan', 'America/Bahia': 'America/Bahia', 'America/Bahia_Banderas': 'America/Bahia_Banderas', 'America/Barbados': 'America/Barbados', 'America/Blanc-Sablon': 'America/Barbados', 'America/Boa_Vista': 'America/Barbados', 'America/Curacao': 'America/Barbados', 'America/Guyana': 'America/Barbados', 'America/La_Paz': 'America/Barbados', 'America/Manaus': 'America/Barbados', 'America/Martinique': 'America/Barbados', 'America/Port_of_Spain': 'America/Barbados', 'America/Porto_Velho': 'America/Barbados', 'America/Puerto_Rico': 'America/Barbados', 'America/Santo_Domingo': 'America/Barbados', 'America/Belize': 'America/Belize', 'America/Costa_Rica': 'America/Belize', 'America/El_Salvador': 'America/Belize', 'America/Guatemala': 'America/Belize', 'America/Managua': 'America/Belize', 'America/Regina': 'America/Belize', 'America/Swift_Current': 'America/Belize', 'America/Tegucigalpa': 'America/Belize', 'Pacific/Galapagos': 'America/Belize', 'America/Boise': 'America/Boise', 'America/Cambridge_Bay': 'America/Boise', 'America/Denver': 'America/Boise', 'America/Edmonton': 'America/Boise', 'America/Inuvik': 'America/Boise', 'America/Ojinaga': 'America/Boise', 'America/Yellowknife': 'America/Boise', 'America/Campo_Grande': 'America/Campo_Grande', 'America/Cuiaba': 'America/Campo_Grande', 'America/Cancun': 'America/Cancun', 'America/Caracas': 'America/Caracas', 'America/Chicago': 'America/Chicago', 'America/Indiana/Knox': 'America/Chicago', 'America/Indiana/Tell_City': 'America/Chicago', 'America/Matamoros': 'America/Chicago', 'America/Menominee': 'America/Chicago', 'America/North_Dakota/Center': 'America/Chicago', 'America/North_Dakota/New_Salem': 'America/Chicago', 'America/Rainy_River': 'America/Chicago', 'America/Rankin_Inlet': 'America/Chicago', 'America/Resolute': 'America/Chicago', 'America/Winnipeg': 'America/Chicago', 'America/Chihuahua': 'America/Chihuahua', 'America/Mazatlan': 'America/Chihuahua', 'America/Creston': 'America/Creston', 'America/Dawson_Creek': 'America/Creston', 'America/Hermosillo': 'America/Creston', 'America/Phoenix': 'America/Creston', 'America/Dawson': 'America/Dawson', 'America/Whitehorse': 'America/Dawson', 'America/Detroit': 'America/Detroit', 'America/Indiana/Marengo': 'America/Detroit', 'America/Indiana/Petersburg': 'America/Detroit', 'America/Indiana/Vevay': 'America/Detroit', 'America/Indiana/Vincennes': 'America/Detroit', 'America/Indiana/Winamac': 'America/Detroit', 'America/Iqaluit': 'America/Detroit', 'America/Kentucky/Louisville': 'America/Detroit', 'America/Kentucky/Monticello': 'America/Detroit', 'America/Nassau': 'America/Detroit', 'America/New_York': 'America/Detroit', 'America/Nipigon': 'America/Detroit', 'America/Pangnirtung': 'America/Detroit', 'America/Thunder_Bay': 'America/Detroit', 'America/Toronto': 'America/Detroit', 'America/Eirunepe': 'America/Eirunepe', 'America/Rio_Branco': 'America/Eirunepe', 'America/Fort_Nelson': 'America/Fort_Nelson', 'America/Glace_Bay': 'America/Glace_Bay', 'America/Halifax': 'America/Glace_Bay', 'America/Moncton': 'America/Glace_Bay', 'America/Thule': 'America/Glace_Bay', 'Atlantic/Bermuda': 'America/Glace_Bay', 'America/Goose_Bay': 'America/Goose_Bay', 'America/Grand_Turk': 'America/Grand_Turk', 'America/Havana': 'America/Havana', 'America/Los_Angeles': 'America/Los_Angeles', 'America/Tijuana': 'America/Los_Angeles', 'America/Vancouver': 'America/Los_Angeles', 'America/Merida': 'America/Merida', 'America/Mexico_City': 'America/Merida', 'America/Monterrey': 'America/Merida', 'America/Metlakatla': 'America/Metlakatla', 'America/Miquelon': 'America/Miquelon', 'America/Montevideo': 'America/Montevideo', 'America/Noronha': 'America/Noronha', 'Atlantic/South_Georgia': 'America/Noronha', 'America/North_Dakota/Beulah': 'America/North_Dakota/Beulah', 'America/Port-au-Prince': 'America/Port-au-Prince', 'America/Punta_Arenas': 'America/Punta_Arenas', 'Antarctica/Palmer': 'America/Punta_Arenas', 'America/Santiago': 'America/Santiago', 'America/Sao_Paulo': 'America/Sao_Paulo', 'America/Scoresbysund': 'America/Scoresbysund', 'Atlantic/Azores': 'America/Scoresbysund', 'America/St_Johns': 'America/St_Johns', 'Antarctica/Casey': 'Antarctica/Casey', 'Antarctica/Davis': 'Antarctica/Davis', 'Antarctica/DumontDUrville': 'Antarctica/DumontDUrville', 'Australia/Brisbane': 'Antarctica/DumontDUrville', 'Australia/Lindeman': 'Antarctica/DumontDUrville', 'Pacific/Chuuk': 'Antarctica/DumontDUrville', 'Pacific/Guam': 'Antarctica/DumontDUrville', 'Pacific/Port_Moresby': 'Antarctica/DumontDUrville', 'Antarctica/Macquarie': 'Antarctica/Macquarie', 'Antarctica/Mawson': 'Antarctica/Mawson', 'Asia/Aqtau': 'Antarctica/Mawson', 'Asia/Aqtobe': 'Antarctica/Mawson', 'Asia/Ashgabat': 'Antarctica/Mawson', 'Asia/Atyrau': 'Antarctica/Mawson', 'Asia/Dushanbe': 'Antarctica/Mawson', 'Asia/Karachi': 'Antarctica/Mawson', 'Asia/Oral': 'Antarctica/Mawson', 'Asia/Samarkand': 'Antarctica/Mawson', 'Asia/Tashkent': 'Antarctica/Mawson', 'Indian/Kerguelen': 'Antarctica/Mawson', 'Indian/Maldives': 'Antarctica/Mawson', 'Antarctica/Troll': 'Antarctica/Troll', 'Antarctica/Vostok': 'Antarctica/Vostok', 'Asia/Almaty': 'Antarctica/Vostok', 'Asia/Bishkek': 'Antarctica/Vostok', 'Asia/Dhaka': 'Antarctica/Vostok', 'Asia/Qostanay': 'Antarctica/Vostok', 'Asia/Thimphu': 'Antarctica/Vostok', 'Asia/Urumqi': 'Antarctica/Vostok', 'Indian/Chagos': 'Antarctica/Vostok', 'Asia/Amman': 'Asia/Amman', 'Asia/Anadyr': 'Asia/Anadyr', 'Asia/Kamchatka': 'Asia/Anadyr', 'Asia/Baku': 'Asia/Baku', 'Asia/Bangkok': 'Asia/Bangkok', 'Asia/Ho_Chi_Minh': 'Asia/Bangkok', 'Asia/Jakarta': 'Asia/Bangkok', 'Asia/Pontianak': 'Asia/Bangkok', 'Indian/Christmas': 'Asia/Bangkok', 'Asia/Barnaul': 'Asia/Barnaul', 'Asia/Beirut': 'Asia/Beirut', 'Asia/Brunei': 'Asia/Brunei', 'Asia/Hong_Kong': 'Asia/Brunei', 'Asia/Kuala_Lumpur': 'Asia/Brunei', 'Asia/Kuching': 'Asia/Brunei', 'Asia/Macau': 'Asia/Brunei', 'Asia/Makassar': 'Asia/Brunei', 'Asia/Manila': 'Asia/Brunei', 'Asia/Shanghai': 'Asia/Brunei', 'Asia/Taipei': 'Asia/Brunei', 'Australia/Perth': 'Asia/Brunei', 'Asia/Chita': 'Asia/Chita', 'Asia/Choibalsan': 'Asia/Choibalsan', 'Asia/Ulaanbaatar': 'Asia/Choibalsan', 'Asia/Colombo': 'Asia/Colombo', 'Asia/Kolkata': 'Asia/Colombo', 'Asia/Damascus': 'Asia/Damascus', 'Asia/Dili': 'Asia/Dili', 'Asia/Jayapura': 'Asia/Dili', 'Asia/Seoul': 'Asia/Dili', 'Asia/Tokyo': 'Asia/Dili', 'Pacific/Palau': 'Asia/Dili', 'Asia/Dubai': 'Asia/Dubai', 'Asia/Tbilisi': 'Asia/Dubai', 'Indian/Mahe': 'Asia/Dubai', 'Indian/Mauritius': 'Asia/Dubai', 'Indian/Reunion': 'Asia/Dubai', 'Asia/Famagusta': 'Asia/Famagusta', 'Asia/Gaza': 'Asia/Gaza', 'Asia/Hebron': 'Asia/Hebron', 'Asia/Hovd': 'Asia/Hovd', 'Asia/Irkutsk': 'Asia/Irkutsk', 'Asia/Jerusalem': 'Asia/Jerusalem', 'Asia/Kabul': 'Asia/Kabul', 'Asia/Kathmandu': 'Asia/Kathmandu', 'Asia/Khandyga': 'Asia/Khandyga', 'Asia/Krasnoyarsk': 'Asia/Krasnoyarsk', 'Asia/Magadan': 'Asia/Magadan', 'Asia/Nicosia': 'Asia/Nicosia', 'Europe/Athens': 'Asia/Nicosia', 'Europe/Bucharest': 'Asia/Nicosia', 'Europe/Helsinki': 'Asia/Nicosia', 'Europe/Kiev': 'Asia/Nicosia', 'Europe/Riga': 'Asia/Nicosia', 'Europe/Sofia': 'Asia/Nicosia', 'Europe/Tallinn': 'Asia/Nicosia', 'Europe/Uzhgorod': 'Asia/Nicosia', 'Europe/Vilnius': 'Asia/Nicosia', 'Europe/Zaporozhye': 'Asia/Nicosia', 'Asia/Novokuznetsk': 'Asia/Novokuznetsk', 'Asia/Novosibirsk': 'Asia/Novosibirsk', 'Asia/Omsk': 'Asia/Omsk', 'Asia/Pyongyang': 'Asia/Pyongyang', 'Asia/Qyzylorda': 'Asia/Qyzylorda', 'Asia/Sakhalin': 'Asia/Sakhalin', 'Asia/Srednekolymsk': 'Asia/Srednekolymsk', 'Asia/Tehran': 'Asia/Tehran', 'Asia/Tomsk': 'Asia/Tomsk', 'Asia/Ust-Nera': 'Asia/Ust-Nera', 'Asia/Vladivostok': 'Asia/Vladivostok', 'Asia/Yakutsk': 'Asia/Yakutsk', 'Asia/Yekaterinburg': 'Asia/Yekaterinburg', 'Asia/Yerevan': 'Asia/Yerevan', 'Atlantic/Canary': 'Atlantic/Canary', 'Atlantic/Faroe': 'Atlantic/Canary', 'Atlantic/Madeira': 'Atlantic/Canary', 'Europe/Dublin': 'Atlantic/Canary', 'Europe/Lisbon': 'Atlantic/Canary', 'Europe/London': 'Atlantic/Canary', 'Atlantic/Cape_Verde': 'Atlantic/Cape_Verde', 'Atlantic/Stanley': 'Atlantic/Stanley', 'Australia/Adelaide': 'Australia/Adelaide', 'Australia/Broken_Hill': 'Australia/Adelaide', 'Australia/Darwin': 'Australia/Darwin', 'Australia/Eucla': 'Australia/Eucla', 'Australia/Hobart': 'Australia/Hobart', 'Australia/Melbourne': 'Australia/Hobart', 'Australia/Sydney': 'Australia/Hobart', 'Australia/Lord_Howe': 'Australia/Lord_Howe', 'Europe/Astrakhan': 'Europe/Astrakhan', 'Europe/Ulyanovsk': 'Europe/Astrakhan', 'Europe/Chisinau': 'Europe/Chisinau', 'Europe/Istanbul': 'Europe/Istanbul', 'Europe/Kaliningrad': 'Europe/Kaliningrad', 'Europe/Kirov': 'Europe/Kirov', 'Europe/Moscow': 'Europe/Kirov', 'Europe/Minsk': 'Europe/Minsk', 'Europe/Samara': 'Europe/Samara', 'Europe/Saratov': 'Europe/Saratov', 'Europe/Simferopol': 'Europe/Simferopol', 'Europe/Volgograd': 'Europe/Volgograd', 'Indian/Cocos': 'Indian/Cocos', 'Pacific/Apia': 'Pacific/Apia', 'Pacific/Auckland': 'Pacific/Auckland', 'Pacific/Bougainville': 'Pacific/Bougainville', 'Pacific/Chatham': 'Pacific/Chatham', 'Pacific/Easter': 'Pacific/Easter', 'Pacific/Efate': 'Pacific/Efate', 'Pacific/Guadalcanal': 'Pacific/Efate', 'Pacific/Kosrae': 'Pacific/Efate', 'Pacific/Noumea': 'Pacific/Efate', 'Pacific/Pohnpei': 'Pacific/Efate', 'Pacific/Fakaofo': 'Pacific/Fakaofo', 'Pacific/Fiji': 'Pacific/Fiji', 'Pacific/Gambier': 'Pacific/Gambier', 'Pacific/Honolulu': 'Pacific/Honolulu', 'Pacific/Rarotonga': 'Pacific/Honolulu', 'Pacific/Tahiti': 'Pacific/Honolulu', 'Pacific/Kiritimati': 'Pacific/Kiritimati', 'Pacific/Kwajalein': 'Pacific/Kwajalein', 'Pacific/Majuro': 'Pacific/Kwajalein', 'Pacific/Nauru': 'Pacific/Kwajalein', 'Pacific/Tarawa': 'Pacific/Kwajalein', 'Pacific/Marquesas': 'Pacific/Marquesas', 'Pacific/Niue': 'Pacific/Niue', 'Pacific/Pago_Pago': 'Pacific/Niue', 'Pacific/Norfolk': 'Pacific/Norfolk', 'Pacific/Pitcairn': 'Pacific/Pitcairn', 'Pacific/Tongatapu': 'Pacific/Tongatapu', }; export const MANUAL_TIMEZONE_LINKS: { [key: string]: string } = { 'abu dhabi, muscat': 'Asia/Muscat', acre: 'America/Rio_Branco', 'adelaide, central australia': 'Australia/Adelaide', afghanistan: 'Asia/Kabul', 'afghanistan standard time': 'Asia/Kabul', 'africa central': 'Africa/Maputo', 'africa eastern': 'Africa/Nairobi', 'africa farwestern': 'Africa/El_Aaiun', 'africa southern': 'Africa/Johannesburg', 'africa western': 'Africa/Lagos', aktyubinsk: 'Asia/Aqtobe', alaska: 'America/Anchorage', 'alaska hawaii': 'America/Anchorage', alaskan: 'America/Anchorage', 'alaskan standard time': 'America/Anchorage', 'aleutian standard time': 'America/Adak', almaty: 'Asia/Almaty', 'almaty, novosibirsk, north central asia': 'Asia/Almaty', 'altai standard time': 'Asia/Barnaul', amazon: 'America/Manaus', 'america central': 'America/Chicago', 'america eastern': 'America/New_York', 'america mountain': 'America/Denver', 'america pacific': 'America/Los_Angeles', 'amsterdam, berlin, bern, rome, stockholm, vienna': 'Europe/Berlin', anadyr: 'Asia/Anadyr', apia: 'Pacific/Apia', aqtau: 'Asia/Aqtau', aqtobe: 'Asia/Aqtobe', arab: 'Asia/Kuwait', 'arab standard time': 'Asia/Riyadh', 'arab, kuwait, riyadh': 'Asia/Kuwait', arabian: 'Asia/Muscat', 'arabian standard time': 'Asia/Dubai', arabic: 'Asia/Baghdad', 'arabic standard time': 'Asia/Baghdad', argentina: 'America/Argentina/Buenos_Aires', 'argentina standard time': 'America/Argentina/Buenos_Aires', 'argentina western': 'America/Argentina/San_Luis', arizona: 'America/Phoenix', armenia: 'Asia/Yerevan', armenian: 'Asia/Yerevan', 'armenian standard time': 'Asia/Yerevan', ashkhabad: 'Asia/Ashgabat', 'astana, dhaka': 'Asia/Dhaka', 'astrakhan standard time': 'Europe/Astrakhan', 'athens, istanbul, minsk': 'Europe/Athens', atlantic: 'America/Halifax', 'atlantic standard time': 'America/Halifax', 'atlantic time (canada)': 'America/Halifax', 'auckland, wellington': 'Pacific/Auckland', 'aus central': 'Australia/Darwin', 'aus central standard time': 'Australia/Darwin', 'aus central w standard time': 'Australia/Eucla', 'aus eastern': 'Australia/Sydney', 'aus eastern standard time': 'Australia/Sydney', 'australia central': 'Australia/Adelaide', 'australia centralwestern': 'Australia/Eucla', 'australia eastern': 'Australia/Sydney', 'australia western': 'Australia/Perth', azerbaijan: 'Asia/Baku', 'azerbaijan standard time': 'Asia/Baku', azerbijan: 'Asia/Baku', azores: 'Atlantic/Azores', 'azores standard time': 'Atlantic/Azores', baghdad: 'Asia/Baghdad', 'bahia standard time': 'America/Bahia', baku: 'Asia/Baku', 'baku, tbilisi, yerevan': 'Asia/Baku', 'bangkok, hanoi, jakarta': 'Asia/Bangkok', bangladesh: 'Asia/Dhaka', 'bangladesh standard time': 'Asia/Dhaka', 'beijing, chongqing, hong kong sar, urumqi': 'Asia/Shanghai', 'belarus standard time': 'Europe/Minsk', 'belgrade, pozsony, budapest, ljubljana, prague': 'Europe/Prague', bering: 'America/Adak', bhutan: 'Asia/Thimphu', 'bogota, lima, quito': 'America/Bogota', bolivia: 'America/La_Paz', borneo: 'Asia/Kuching', 'bougainville standard time': 'Pacific/Bougainville', brasilia: 'America/Sao_Paulo', 'brisbane, east australia': 'Australia/Brisbane', british: 'Europe/London', brunei: 'Asia/Brunei', 'brussels, copenhagen, madrid, paris': 'Europe/Paris', bucharest: 'Europe/Bucharest', 'buenos aires': 'America/Argentina/Buenos_Aires', cairo: 'Africa/Cairo', 'canada central': 'America/Edmonton', 'canada central standard time': 'America/Regina', 'canberra, melbourne, sydney, hobart (year 2000 only)': 'Australia/Sydney', 'cape verde': 'Atlantic/Cape_Verde', 'cape verde is': 'Atlantic/Cape_Verde', 'cape verde standard time': 'Atlantic/Cape_Verde', 'caracas, la paz': 'America/Caracas', 'casablanca, monrovia': 'Africa/Casablanca', casey: 'Antarctica/Casey', caucasus: 'Asia/Yerevan', 'caucasus standard time': 'Asia/Yerevan', 'cen australia': 'Australia/Adelaide', 'cen australia standard time': 'Australia/Adelaide', central: 'America/Chicago', 'central america': 'America/Guatemala', 'central america standard time': 'America/Guatemala', 'central asia': 'Asia/Dhaka', 'central asia standard time': 'Asia/Almaty', 'central brazilian': 'America/Manaus', 'central brazilian standard time': 'America/Cuiaba', 'central europe': 'Europe/Prague', 'central europe standard time': 'Europe/Budapest', 'central european': 'Europe/Sarajevo', 'central european standard time': 'Europe/Warsaw', 'central pacific': 'Asia/Magadan', 'central pacific standard time': 'Pacific/Guadalcanal', 'central standard time': 'America/Chicago', 'central standard time (mexico)': 'America/Mexico_City', 'central time (us & canada)': 'America/Chicago', chamorro: 'Pacific/Saipan', chatham: 'Pacific/Chatham', 'chatham islands standard time': 'Pacific/Chatham', chile: 'America/Santiago', china: 'Asia/Shanghai', 'china standard time': 'Asia/Shanghai', choibalsan: 'Asia/Choibalsan', christmas: 'Indian/Christmas', cocos: 'Indian/Cocos', colombia: 'America/Bogota', cook: 'Pacific/Rarotonga', cuba: 'America/Havana', 'cuba standard time': 'America/Havana', dacca: 'Asia/Dhaka', darwin: 'Australia/Darwin', dateline: 'Pacific/Auckland', 'dateline standard time': 'Pacific/Niue', davis: 'Antarctica/Davis', dominican: 'America/Santo_Domingo', dumontdurville: 'Antarctica/DumontDUrville', dushanbe: 'Asia/Dushanbe', 'dutch guiana': 'America/Paramaribo', 'e africa': 'Africa/Nairobi', 'e africa standard time': 'Africa/Nairobi', 'e australia': 'Australia/Brisbane', 'e australia standard time': 'Australia/Brisbane', 'e europe': 'Europe/Minsk', 'e europe standard time': 'Europe/Chisinau', 'e south america': 'America/Belem', 'e south america standard time': 'America/Sao_Paulo', 'east africa, nairobi': 'Africa/Nairobi', 'east timor': 'Asia/Dili', easter: 'Pacific/Easter', 'easter island standard time': 'Pacific/Easter', eastern: 'America/New_York', 'eastern standard time': 'America/New_York', 'eastern standard time (mexico)': 'America/Cancun', 'eastern time (us & canada)': 'America/New_York', ecuador: 'America/Guayaquil', egypt: 'Africa/Cairo', 'egypt standard time': 'Africa/Cairo', ekaterinburg: 'Asia/Yekaterinburg', 'ekaterinburg standard time': 'Asia/Yekaterinburg', 'eniwetok, kwajalein, dateline time': 'Pacific/Kwajalein', 'europe central': 'Europe/Paris', 'europe eastern': 'Europe/Bucharest', 'europe further eastern': 'Europe/Minsk', 'europe western': 'Atlantic/Canary', falkland: 'Atlantic/Stanley', fiji: 'Pacific/Fiji', 'fiji islands standard time': 'Pacific/Fiji', 'fiji islands, kamchatka, marshall is': 'Pacific/Fiji', 'fiji standard time': 'Pacific/Fiji', fle: 'Europe/Helsinki', 'fle standard time': 'Europe/Kiev', 'french guiana': 'America/Cayenne', 'french southern': 'Indian/Kerguelen', frunze: 'Asia/Bishkek', galapagos: 'Pacific/Galapagos', gambier: 'Pacific/Gambier', georgia: 'Asia/Tbilisi', georgian: 'Asia/Tbilisi', 'georgian standard time': 'Asia/Tbilisi', 'gilbert islands': 'Pacific/Tarawa', gmt: 'Europe/London', 'gmt standard time': 'Europe/London', 'goose bay': 'America/Goose_Bay', greenland: 'Atlantic/Stanley', 'greenland central': 'America/Scoresbysund', 'greenland eastern': 'America/Scoresbysund', 'greenland standard time': 'Atlantic/Stanley', 'greenland western': 'Atlantic/Stanley', greenwich: 'Atlantic/Reykjavik', 'greenwich mean time; dublin, edinburgh, london': 'Europe/London', 'greenwich mean time: dublin, edinburgh, lisbon, london': 'Europe/Lisbon', 'greenwich standard time': 'Atlantic/Reykjavik', gtb: 'Europe/Athens', 'gtb standard time': 'Europe/Bucharest', guam: 'Pacific/Guam', 'guam, port moresby': 'Pacific/Guam', gulf: 'Asia/Dubai', guyana: 'America/Guyana', 'haiti standard time': 'America/Port-au-Prince', 'harare, pretoria': 'Africa/Harare', hawaii: 'Pacific/Honolulu', 'hawaii aleutian': 'Pacific/Honolulu', hawaiian: 'Pacific/Honolulu', 'hawaiian standard time': 'Pacific/Honolulu', 'helsinki, riga, tallinn': 'Europe/Helsinki', 'hobart, tasmania': 'Australia/Hobart', 'hong kong': 'Asia/Hong_Kong', hovd: 'Asia/Hovd', india: 'Asia/Kolkata', 'india standard time': 'Asia/Kolkata', 'indian ocean': 'Indian/Chagos', 'indiana (east)': 'America/Indiana/Indianapolis', indochina: 'Asia/Bangkok', 'indonesia central': 'Asia/Makassar', 'indonesia eastern': 'Asia/Jayapura', 'indonesia western': 'Asia/Jakarta', iran: 'Asia/Tehran', 'iran standard time': 'Asia/Tehran', irish: 'Europe/Dublin', irkutsk: 'Asia/Irkutsk', 'irkutsk, ulaan bataar': 'Asia/Irkutsk', 'islamabad, karachi, tashkent': 'Asia/Karachi', israel: 'Asia/Jerusalem', 'israel standard time': 'Asia/Jerusalem', 'israel, jerusalem standard time': 'Asia/Jerusalem', japan: 'Asia/Tokyo', jordan: 'Asia/Amman', 'jordan standard time': 'Asia/Amman', kabul: 'Asia/Kabul', 'kaliningrad standard time': 'Europe/Kaliningrad', kamchatka: 'Asia/Kamchatka', 'kamchatka standard time': 'Asia/Kamchatka', karachi: 'Asia/Karachi', 'kathmandu, nepal': 'Asia/Kathmandu', 'kazakhstan eastern': 'Asia/Almaty', 'kazakhstan western': 'Asia/Aqtobe', kizilorda: 'Asia/Qyzylorda', 'kolkata, chennai, mumbai, new delhi, india standard time': 'Asia/Kolkata', korea: 'Asia/Seoul', 'korea standard time': 'Asia/Seoul', kosrae: 'Pacific/Kosrae', krasnoyarsk: 'Asia/Krasnoyarsk', 'kuala lumpur, singapore': 'Asia/Shanghai', kuybyshev: 'Europe/Samara', kwajalein: 'Pacific/Kwajalein', kyrgystan: 'Asia/Bishkek', lanka: 'Asia/Colombo', liberia: 'Africa/Monrovia', 'libya standard time': 'Africa/Tripoli', 'line islands': 'Pacific/Kiritimati', 'line islands standard time': 'Pacific/Kiritimati', 'lord howe': 'Australia/Lord_Howe', 'lord howe standard time': 'Australia/Lord_Howe', macau: 'Asia/Macau', macquarie: 'Antarctica/Macquarie', magadan: 'Asia/Magadan', 'magadan standard time': 'Asia/Magadan', 'magadan, solomon is, new caledonia': 'Asia/Magadan', 'magallanes standard time': 'America/Punta_Arenas', malaya: 'Asia/Kuala_Lumpur', malaysia: 'Asia/Kuching', maldives: 'Indian/Maldives', marquesas: 'Pacific/Marquesas', 'marquesas standard time': 'Pacific/Marquesas', 'marshall islands': 'Pacific/Majuro', mauritius: 'Indian/Mauritius', 'mauritius standard time': 'Indian/Mauritius', mawson: 'Antarctica/Mawson', mexico: 'America/Mexico_City', 'mexico city, tegucigalpa': 'America/Mexico_City', 'mexico pacific': 'America/Mazatlan', 'mexico standard time': 'America/Mexico_City', 'mexico standard time 2': 'America/Chihuahua', 'mid-atlantic': 'America/Noronha', 'mid-atlantic standard time': 'Atlantic/Cape_Verde', 'middle east': 'Asia/Beirut', 'middle east standard time': 'Asia/Beirut', 'midway island, samoa': 'Pacific/Midway', mongolia: 'Asia/Ulaanbaatar', montevideo: 'America/Montevideo', 'montevideo standard time': 'America/Montevideo', morocco: 'Africa/Casablanca', 'morocco standard time': 'Africa/Casablanca', moscow: 'Europe/Moscow', 'moscow, st petersburg, volgograd': 'Europe/Moscow', mountain: 'America/Denver', 'mountain standard time': 'America/Denver', 'mountain standard time (mexico)': 'America/Chihuahua', 'mountain time (us & canada)': 'America/Denver', myanmar: 'Indian/Cocos', 'myanmar standard time': 'Indian/Cocos', 'n central asia': 'Asia/Almaty', 'n central asia standard time': 'Asia/Novosibirsk', namibia: 'Africa/Windhoek', 'namibia standard time': 'Africa/Windhoek', nauru: 'Pacific/Nauru', nepal: 'Asia/Kathmandu', 'nepal standard time': 'Asia/Kathmandu', 'new caledonia': 'Pacific/Noumea', 'new zealand': 'Pacific/Auckland', 'new zealand standard time': 'Pacific/Auckland', newfoundland: 'America/St_Johns', 'newfoundland and labrador standard time': 'America/St_Johns', 'newfoundland standard time': 'America/St_Johns', niue: 'Pacific/Niue', norfolk: 'Pacific/Norfolk', 'norfolk standard time': 'Pacific/Norfolk', noronha: 'America/Noronha', 'north asia': 'Asia/Krasnoyarsk', 'north asia east': 'Asia/Irkutsk', 'north asia east standard time': 'Asia/Irkutsk', 'north asia standard time': 'Asia/Krasnoyarsk', 'north korea standard time': 'Asia/Pyongyang', 'north mariana': 'Pacific/Saipan', novosibirsk: 'Asia/Novosibirsk', "nuku'alofa, tonga": 'Pacific/Tongatapu', omsk: 'Asia/Omsk', 'omsk standard time': 'Asia/Omsk', oral: 'Asia/Oral', 'osaka, sapporo, tokyo': 'Asia/Tokyo', pacific: 'America/Los_Angeles', 'pacific sa': 'America/Santiago', 'pacific sa standard time': 'America/Santiago', 'pacific standard time': 'America/Los_Angeles', 'pacific standard time (mexico)': 'America/Tijuana', 'pacific time (us & canada)': 'America/Los_Angeles', 'pacific time (us & canada); tijuana': 'America/Los_Angeles', pakistan: 'Asia/Karachi', 'pakistan standard time': 'Asia/Karachi', palau: 'Pacific/Palau', 'papua new guinea': 'Pacific/Port_Moresby', paraguay: 'America/Asuncion', 'paraguay standard time': 'America/Asuncion', 'paris, madrid, brussels, copenhagen': 'Europe/Paris', 'perth, western australia': 'Australia/Perth', peru: 'America/Lima', philippines: 'Asia/Manila', 'phoenix islands': 'Pacific/Fakaofo', 'pierre miquelon': 'America/Miquelon', pitcairn: 'Pacific/Pitcairn', 'prague, central europe': 'Europe/Prague', pyongyang: 'Asia/Pyongyang', qyzylorda: 'Asia/Qyzylorda', 'qyzylorda standard time': 'Asia/Qyzylorda', rangoon: 'Indian/Cocos', reunion: 'Indian/Reunion', romance: 'Europe/Paris', 'romance standard time': 'Europe/Paris', rothera: 'Antarctica/Rothera', 'russia time zone 10': 'Asia/Srednekolymsk', 'russia time zone 11': 'Asia/Kamchatka', 'russia time zone 3': 'Europe/Samara', russian: 'Europe/Moscow', 'russian standard time': 'Europe/Moscow', 'sa eastern': 'America/Belem', 'sa eastern standard time': 'America/Cayenne', 'sa pacific': 'America/Bogota', 'sa pacific standard time': 'America/Bogota', 'sa western': 'America/La_Paz', 'sa western standard time': 'America/La_Paz', 'saint pierre standard time': 'America/Miquelon', sakhalin: 'Asia/Sakhalin', 'sakhalin standard time': 'Asia/Sakhalin', samara: 'Europe/Samara', samarkand: 'Asia/Samarkand', samoa: 'Pacific/Apia', 'samoa standard time': 'Pacific/Apia', santiago: 'America/Santiago', 'sao tome standard time': 'Africa/Sao_Tome', 'sarajevo, skopje, sofija, vilnius, warsaw, zagreb': 'Europe/Sarajevo', 'saratov standard time': 'Europe/Saratov', saskatchewan: 'America/Edmonton', 'se asia': 'Asia/Bangkok', 'se asia standard time': 'Asia/Bangkok', 'seoul, korea standard time': 'Asia/Seoul', seychelles: 'Indian/Mahe', shevchenko: 'Asia/Aqtau', singapore: 'Asia/Shanghai', 'singapore standard time': 'Asia/Shanghai', solomon: 'Pacific/Guadalcanal', 'south africa': 'Africa/Harare', 'south africa standard time': 'Africa/Johannesburg', 'south georgia': 'Atlantic/South_Georgia', 'sri jayawardenepura, sri lanka': 'Asia/Colombo', 'sri lanka': 'Asia/Colombo', 'sri lanka standard time': 'Asia/Colombo', 'sudan standard time': 'Africa/Khartoum', suriname: 'America/Paramaribo', sverdlovsk: 'Asia/Yekaterinburg', syowa: 'Antarctica/Syowa', 'syria standard time': 'Asia/Damascus', tahiti: 'Pacific/Tahiti', taipei: 'Asia/Taipei', 'taipei standard time': 'Asia/Taipei', tajikistan: 'Asia/Dushanbe', tashkent: 'Asia/Tashkent', tasmania: 'Australia/Hobart', 'tasmania standard time': 'Australia/Hobart', tbilisi: 'Asia/Tbilisi', tehran: 'Asia/Tehran', 'tocantins standard time': 'America/Araguaina', tokelau: 'Pacific/Fakaofo', tokyo: 'Asia/Tokyo', 'tokyo standard time': 'Asia/Tokyo', 'tomsk standard time': 'Asia/Tomsk', tonga: 'Pacific/Tongatapu', 'tonga standard time': 'Pacific/Tongatapu', 'transbaikal standard time': 'Asia/Chita', 'transitional islamic state of afghanistan standard time': 'Asia/Kabul', turkey: 'Europe/Istanbul', 'turkey standard time': 'Europe/Istanbul', turkmenistan: 'Asia/Ashgabat', 'turks and caicos standard time': 'America/Grand_Turk', tuvalu: 'Pacific/Funafuti', 'ulaanbaatar standard time': 'Asia/Ulaanbaatar', 'universal coordinated time': 'UTC', uralsk: 'Asia/Oral', uruguay: 'America/Montevideo', urumqi: 'Asia/Urumqi', 'us eastern': 'America/Indiana/Indianapolis', 'us eastern standard time': 'America/New_York', 'us mountain': 'America/Phoenix', 'us mountain standard time': 'America/Phoenix', utc: 'UTC', 'utc-02': 'America/Noronha', 'utc-08': 'Pacific/Pitcairn', 'utc-09': 'Pacific/Gambier', 'utc-11': 'Pacific/Niue', 'utc+12': 'Pacific/Auckland', 'utc+13': 'Pacific/Fakaofo', uzbekistan: 'Asia/Tashkent', vanuatu: 'Pacific/Efate', venezuela: 'America/Caracas', 'venezuela standard time': 'America/Caracas', vladivostok: 'Asia/Vladivostok', 'vladivostok standard time': 'Asia/Vladivostok', volgograd: 'Europe/Volgograd', 'volgograd standard time': 'Europe/Volgograd', vostok: 'Antarctica/Vostok', 'w australia': 'Australia/Perth', 'w australia standard time': 'Australia/Perth', 'w central africa': 'Africa/Lagos', 'w central africa standard time': 'Africa/Lagos', 'w europe': 'Europe/Amsterdam', 'w europe standard time': 'Europe/Berlin', 'w mongolia standard time': 'Asia/Hovd', wake: 'Pacific/Wake', wallis: 'Pacific/Wallis', 'west asia': 'Asia/Tashkent', 'west asia standard time': 'Asia/Tashkent', 'west bank standard time': 'Asia/Hebron', 'west central africa': 'Africa/Luanda', 'west pacific': 'Pacific/Guam', 'west pacific standard time': 'Pacific/Port_Moresby', yakutsk: 'Asia/Yakutsk', 'yakutsk standard time': 'Asia/Yakutsk', yekaterinburg: 'Asia/Yekaterinburg', yerevan: 'Asia/Yerevan', yukon: 'America/Yakutat', 'coordinated universal time-11': 'Pacific/Pago_Pago', 'aleutian islands': 'America/Adak', 'marquesas islands': 'Pacific/Marquesas', 'coordinated universal time-09': 'America/Anchorage', 'baja california': 'America/Tijuana', 'coordinated universal time-08': 'Pacific/Pitcairn', 'chihuahua, la paz, mazatlan': 'America/Chihuahua', 'easter island': 'Pacific/Easter', 'guadalajara, mexico city, monterrey': 'America/Mexico_City', 'bogota, lima, quito, rio branco': 'America/Bogota', chetumal: 'America/Cancun', haiti: 'America/Port-au-Prince', havana: 'America/Havana', 'turks and caicos': 'America/Grand_Turk', asuncion: 'America/Asuncion', caracas: 'America/Caracas', cuiaba: 'America/Cuiaba', 'georgetown, la paz, manaus, san juan': 'America/La_Paz', araguaina: 'America/Araguaina', 'cayenne, fortaleza': 'America/Cayenne', 'city of buenos aires': 'America/Argentina/Buenos_Aires', 'punta arenas': 'America/Punta_Arenas', 'saint pierre and miquelon': 'America/Miquelon', salvador: 'America/Bahia', 'coordinated universal time-02': 'America/Noronha', 'mid-atlantic - old': 'America/Noronha', 'cabo verde is': 'Atlantic/Cape_Verde', 'coordinated universal time': 'UTC', 'dublin, edinburgh, lisbon, london': 'Europe/London', 'monrovia, reykjavik': 'Atlantic/Reykjavik', 'belgrade, bratislava, budapest, ljubljana, prague': 'Europe/Budapest', casablanca: 'Africa/Casablanca', 'sao tome': 'Africa/Sao_Tome', 'sarajevo, skopje, warsaw, zagreb': 'Europe/Warsaw', amman: 'Asia/Amman', 'athens, bucharest': 'Europe/Bucharest', beirut: 'Asia/Beirut', chisinau: 'Europe/Chisinau', damascus: 'Asia/Damascus', 'gaza, hebron': 'Asia/Hebron', jerusalem: 'Asia/Jerusalem', kaliningrad: 'Europe/Kaliningrad', khartoum: 'Africa/Khartoum', tripoli: 'Africa/Tripoli', windhoek: 'Africa/Windhoek', istanbul: 'Europe/Istanbul', 'kuwait, riyadh': 'Asia/Riyadh', minsk: 'Europe/Minsk', 'moscow, st petersburg': 'Europe/Moscow', nairobi: 'Africa/Nairobi', 'astrakhan, ulyanovsk': 'Europe/Astrakhan', 'izhevsk, samara': 'Europe/Samara', 'port louis': 'Indian/Mauritius', saratov: 'Europe/Saratov', 'ashgabat, tashkent': 'Asia/Tashkent', 'islamabad, karachi': 'Asia/Karachi', 'chennai, kolkata, mumbai, new delhi': 'Asia/Kolkata', 'sri jayawardenepura': 'Asia/Colombo', kathmandu: 'Asia/Kathmandu', astana: 'Asia/Almaty', dhaka: 'Asia/Dhaka', 'yangon (rangoon)': 'Indian/Cocos', 'barnaul, gorno-altaysk': 'Asia/Barnaul', tomsk: 'Asia/Tomsk', 'beijing, chongqing, hong kong, urumqi': 'Asia/Shanghai', perth: 'Australia/Perth', ulaanbaatar: 'Asia/Ulaanbaatar', eucla: 'Australia/Eucla', chita: 'Asia/Chita', seoul: 'Asia/Seoul', adelaide: 'Australia/Adelaide', brisbane: 'Australia/Brisbane', 'canberra, melbourne, sydney': 'Australia/Sydney', hobart: 'Australia/Hobart', 'lord howe island': 'Australia/Lord_Howe', 'bougainville island': 'Pacific/Bougainville', chokurdakh: 'Asia/Srednekolymsk', 'norfolk island': 'Pacific/Norfolk', 'solomon is, new caledonia': 'Pacific/Guadalcanal', 'anadyr, petropavlovsk-kamchatsky': 'Asia/Kamchatka', 'coordinated universal time+12': 'Pacific/Tarawa', 'petropavlovsk-kamchatsky - old': 'Asia/Anadyr', 'chatham islands': 'Pacific/Chatham', 'coordinated universal time+13': 'Pacific/Fakaofo', "nuku'alofa": 'Pacific/Tongatapu', 'kiritimati island': 'Pacific/Kiritimati', 'helsinki, kyiv, riga, sofia, tallinn, vilnius': 'Europe/Helsinki', }; /** * This is a "hack" function that tries to transform IANA time zones detected by the browser into * one supported by us. Returns undefined if no conversion is available */ export const manualFindTimeZone = (tzid: string) => { return MANUAL_TIMEZONE_LINKS[tzid.toLowerCase()]; };
8,449
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/drawer/calendar.ts
import { Dispatch, SetStateAction } from 'react'; import { getAppHref } from '../apps/helper'; import { getLinkToCalendarEvent } from '../calendar/helper'; import { APPS, APP_NAMES } from '../constants'; import { addParentAppToUrl, postMessageToIframe } from './helpers'; import { DRAWER_APPS, DRAWER_EVENTS, IframeSrcMap } from './interfaces'; const { PROTONCALENDAR: calendarApp } = APPS; interface OpenCalendarEventProps { currentApp: APP_NAMES; setAppInView: Dispatch<SetStateAction<DRAWER_APPS | undefined>>; iframeSrcMap: IframeSrcMap; setIframeSrcMap: Dispatch<SetStateAction<IframeSrcMap>>; localID?: number; calendarID: string; eventID: string; recurrenceID?: number; } export const openCalendarEventInDrawer = ({ currentApp, setAppInView, iframeSrcMap, setIframeSrcMap, localID, calendarID, eventID, recurrenceID, }: OpenCalendarEventProps) => { if (!iframeSrcMap[calendarApp]) { const linkTo = getLinkToCalendarEvent({ calendarID, eventID, recurrenceID }); const appHref = getAppHref(linkTo, calendarApp, localID); setAppInView(calendarApp); setIframeSrcMap((map) => ({ ...map, [calendarApp]: addParentAppToUrl(appHref, currentApp, false), })); } else { postMessageToIframe( { type: DRAWER_EVENTS.CALENDAR_OPEN_EVENT, payload: { calendarID, eventID, recurrenceID }, }, calendarApp ); } setAppInView(calendarApp); };
8,450
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/drawer/constants.ts
export const LOCALSTORAGE_DRAWER_KEY = 'PreviouslyOpenedAppInDrawer';
8,451
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/drawer/helpers.ts
import { isURLProtonInternal } from '@proton/components/helpers/url'; import { LOCALSTORAGE_DRAWER_KEY } from '@proton/shared/lib/drawer/constants'; import { getAppHref } from '../apps/helper'; import { getLocalIDFromPathname } from '../authentication/pathnameHelper'; import { APPS, APPS_CONFIGURATION, APP_NAMES } from '../constants'; import window from '../window'; import { DRAWER_ACTION, DRAWER_APPS, DRAWER_EVENTS, DRAWER_NATIVE_APPS } from './interfaces'; const { PROTONMAIL, PROTONCALENDAR, PROTONDRIVE } = APPS; export const drawerAuthorizedApps = [ APPS_CONFIGURATION[PROTONMAIL].subdomain, APPS_CONFIGURATION[PROTONCALENDAR].subdomain, APPS_CONFIGURATION[PROTONDRIVE].subdomain, ] as string[]; export const authorizedApps: string[] = [APPS.PROTONMAIL, APPS.PROTONCALENDAR, APPS.PROTONDRIVE]; export const drawerNativeApps: DRAWER_APPS[] = [DRAWER_NATIVE_APPS.CONTACTS, DRAWER_NATIVE_APPS.QUICK_SETTINGS]; export const drawerIframeApps: DRAWER_APPS[] = [APPS.PROTONCALENDAR]; export const getLocalStorageUserDrawerKey = (userID: string) => `${LOCALSTORAGE_DRAWER_KEY}-${userID}`; export const getIsNativeDrawerApp = (app: string): app is DRAWER_APPS => { const tsDrawerNativeApps: string[] = [...drawerNativeApps]; return tsDrawerNativeApps.includes(app); }; export const getIsIframedDrawerApp = (app: string): app is DRAWER_APPS & APP_NAMES => { const tsDrawerIframeApps: string[] = [...drawerIframeApps]; return tsDrawerIframeApps.includes(app); }; export const getIsDrawerApp = (app: string): app is DRAWER_APPS => { return getIsNativeDrawerApp(app) || getIsIframedDrawerApp(app); }; export const isAuthorizedDrawerUrl = (url: string) => { try { const originURL = new URL(url); // Get subdomain of the url => e.g. mail, calendar, drive const appFromUrl = originURL.hostname.split('.')[0]; return isURLProtonInternal(url) && drawerAuthorizedApps.includes(appFromUrl); } catch { // the URL constructor will throw if no URL can be built out of url return false; } }; export const getIsAuthorizedApp = (appName: string): appName is APP_NAMES => { return authorizedApps.includes(appName); }; export const getIsDrawerPostMessage = (event: MessageEvent): event is MessageEvent<DRAWER_ACTION> => { const origin = event.origin; // sandboxed iframes might have a "null" origin instead of a valid one // so we need to handle this case, otherwise we will get an error if (!origin || origin === 'null') { return false; } /** * The message is a "valid" side app message if * - The message is coming from an authorized app * - event.data is defined * - event.data.type is part of the SIDE_APP_EVENT enum */ return isAuthorizedDrawerUrl(origin) && event.data && Object.values(DRAWER_EVENTS).includes(event.data.type); }; export const postMessageFromIframe = (message: DRAWER_ACTION, parentApp: APP_NAMES) => { if (!getIsAuthorizedApp(parentApp)) { return; } const parentUrl = getAppHref('/', parentApp, getLocalIDFromPathname(window.location.pathname)); window.parent?.postMessage(message, parentUrl); }; export const postMessageToIframe = (message: DRAWER_ACTION, iframedApp: DRAWER_APPS) => { if (!getIsAuthorizedApp(iframedApp)) { return; } const iframe = document.querySelector('[id^=drawer-app-iframe]') as HTMLIFrameElement | null; const targetOrigin = getAppHref('/', iframedApp, getLocalIDFromPathname(window.location.pathname)); iframe?.contentWindow?.postMessage(message, targetOrigin); }; /** * Allow to add the parent app in a URL we will open in the Drawer * From the child application, we need to know who is the parent. For that, we add it in the URL we want to open * Depending on the case you might want to replace path or not * * - "replacePath === true": You want to replace the path by the app * e.g. url = "https://calendar.proton.pink/u/0/event?Action=VIEW&EventID=eventID&RecurrenceID=1670835600" and currentApp = "proton-mail" * ==> https://calendar.proton.pink/u/0/mail?Action=VIEW&EventID=eventID&RecurrenceID=1670835600 * "event" has been replaced by "mail" * - "replacePath === false": You want to add your app to the path * e.g. url = "https://calendar.proton.pink/u/0/something" and currentApp = "proton-mail" * ==> "https://calendar.proton.pink/u/0/mail/something" * "mail" has been added to the path */ export const addParentAppToUrl = (url: string, currentApp: APP_NAMES, replacePath = true) => { const targetUrl = new URL(url); const splitPathname = targetUrl.pathname.split('/').filter((el) => el !== ''); const currentAppSubdomain = APPS_CONFIGURATION[currentApp].subdomain; // splitPathname[0] & splitPathname[1] corresponds to the user local id /u/localID // splitPathname[2] should be the parentApp name // If we find parentApp, we don't need to add it to the pathname if (splitPathname[2] !== currentAppSubdomain) { // In some cases, we want to replace completely this param (e.g. Calendar "view" parameter needs to be mail instead of week) if (replacePath) { splitPathname.splice(2, 1, currentAppSubdomain); } else { splitPathname.splice(2, 0, currentAppSubdomain); } targetUrl.pathname = splitPathname.join('/'); } return targetUrl.href; }; export const getDisplayContactsInDrawer = (app: APP_NAMES) => { return app === APPS.PROTONMAIL || app === APPS.PROTONCALENDAR || app === APPS.PROTONDRIVE; }; export const getDisplaySettingsInDrawer = (app: APP_NAMES) => { return app === APPS.PROTONMAIL || app === APPS.PROTONCALENDAR || app === APPS.PROTONDRIVE; }; export const closeDrawerFromChildApp = (parentApp: APP_NAMES, currentApp: APP_NAMES, closeDefinitely?: boolean) => { if (!getIsIframedDrawerApp(currentApp)) { throw new Error('Cannot close non-iframed app'); } postMessageFromIframe( { type: DRAWER_EVENTS.CLOSE, payload: { app: currentApp, closeDefinitely }, }, parentApp ); }; export const isAppInView = (currentApp: DRAWER_APPS, appInView?: DRAWER_APPS) => { return appInView ? appInView === currentApp : false; }; export const getDisplayDrawerApp = (currentApp: APP_NAMES, toOpenApp: DRAWER_APPS) => { if (toOpenApp === APPS.PROTONCALENDAR) { return currentApp === APPS.PROTONMAIL || currentApp === APPS.PROTONDRIVE; } else if (toOpenApp === DRAWER_NATIVE_APPS.CONTACTS) { return getDisplayContactsInDrawer(currentApp); } else if (toOpenApp === DRAWER_NATIVE_APPS.QUICK_SETTINGS) { return getDisplaySettingsInDrawer(currentApp); } };
8,452
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/drawer/interfaces.ts
import { ThemeColor } from '@proton/colors/types'; import { IconName } from '@proton/components/components'; import { APPS } from '@proton/shared/lib/constants'; import { Environment } from '@proton/shared/lib/interfaces'; import { User as tsUser } from '../interfaces'; import { VCardContact } from '../interfaces/contacts/VCard'; import { ThemeSetting } from '../themes/themes'; export enum DRAWER_NATIVE_APPS { QUICK_SETTINGS = 'quick-settings', CONTACTS = 'contacts', } export type DRAWER_APPS = | typeof APPS.PROTONCALENDAR | typeof DRAWER_NATIVE_APPS.QUICK_SETTINGS | typeof DRAWER_NATIVE_APPS.CONTACTS; export type IframeSrcMap = Partial<Record<DRAWER_APPS, string | undefined>>; export interface OpenDrawerArgs { app: DRAWER_APPS; path?: string; } export interface DrawerLocalStorageValue { app: DRAWER_APPS; url?: string; } /** * Events sent from or to the drawer app */ export enum DRAWER_EVENTS { // Global inside iframe events CLOSE = 'close', SHOW = 'show', SWITCH = 'switch', READY = 'ready', SESSION = 'session', API_REQUEST = 'api-request', API_RESPONSE = 'api-response', ABORT_REQUEST = 'api-request-abort', CHILD_URL_UPDATE = 'child-url-update', // Global outside iframe events CALL_EVENT_MANAGER_FROM_OUTSIDE = 'outside-call-event-manager', UPDATE_THEME = 'outside-update-theme', // Calendar inside iframe events // Calendar outside iframe events CALENDAR_OPEN_EVENT = 'outside-calendar-open-event', CALL_CALENDAR_EVENT_MANAGER = 'outside-call-calendar-event-manager', SET_WIDGET_EVENT = 'outside-set-widget-event', UNSET_WIDGET_EVENT = 'outside-unset-widget-event', // Calendar to mail events REQUEST_OPEN_EVENTS = 'outside-request-open-events', REFRESH_WIDGET = 'outside-refresh-widget', OPEN_CONTACT_MODAL = 'open-contact-modal', } // Global inside iframe events interface CLOSE { type: DRAWER_EVENTS.CLOSE; payload?: { app: DRAWER_APPS; closeDefinitely?: boolean; }; } interface SHOW { type: DRAWER_EVENTS.SHOW; } interface SWITCH { type: DRAWER_EVENTS.SWITCH; payload: { nextUrl: string; }; } interface READY { type: DRAWER_EVENTS.READY; } interface SESSION { type: DRAWER_EVENTS.SESSION; payload: { UID: string; keyPassword?: string; User: tsUser; persistent: boolean; trusted: boolean; tag?: Environment; }; } interface API_REQUEST { type: DRAWER_EVENTS.API_REQUEST; payload: { id: string; arg: object; appVersion: string; hasAbortController?: boolean; }; } interface API_RESPONSE { type: DRAWER_EVENTS.API_RESPONSE; payload: { id: string; success: boolean; isApiError?: boolean; data: any; serverTime: Date; output?: 'raw'; }; } interface API_ABORT_REQUEST { type: DRAWER_EVENTS.ABORT_REQUEST; payload: { id: string; }; } interface CHILD_URL_UPDATE { type: DRAWER_EVENTS.CHILD_URL_UPDATE; payload: { url: string; app: DRAWER_APPS; }; } // Global outside iframe events interface CALL_EVENT_MANAGER_OUTSIDE { type: DRAWER_EVENTS.CALL_EVENT_MANAGER_FROM_OUTSIDE; } interface DRAWER_UPDATE_THEME { type: DRAWER_EVENTS.UPDATE_THEME; payload: { themeSetting: ThemeSetting; }; } // Calendar inside iframe events // Calendar outside iframe events interface CALENDAR_OPEN_EVENT { type: DRAWER_EVENTS.CALENDAR_OPEN_EVENT; payload: { calendarID: string; eventID: string; recurrenceID?: number; }; } interface CALENDAR_CALL_EVENT_MANAGER { type: DRAWER_EVENTS.CALL_CALENDAR_EVENT_MANAGER; payload: { calendarID: string; }; } interface SET_WIDGET_EVENT { type: DRAWER_EVENTS.SET_WIDGET_EVENT; payload: { messageID: string; UID: string; }; } interface UNSET_WIDGET_EVENT { type: DRAWER_EVENTS.UNSET_WIDGET_EVENT; payload: { messageID: string; UID: string; }; } interface REQUEST_OPEN_EVENTS { type: DRAWER_EVENTS.REQUEST_OPEN_EVENTS; } interface REFRESH_WIDGET { type: DRAWER_EVENTS.REFRESH_WIDGET; payload: { UID: string; ModifyTime: number; }; } type OPEN_CONTACT_MODAL = | { type: DRAWER_EVENTS.OPEN_CONTACT_MODAL; payload: { contactID: string; }; } | { type: DRAWER_EVENTS.OPEN_CONTACT_MODAL; payload: { vCardContact: VCardContact; }; }; export type DRAWER_ACTION = | CLOSE | SHOW | SWITCH | READY | SESSION | API_REQUEST | API_RESPONSE | API_ABORT_REQUEST | CHILD_URL_UPDATE | CALL_EVENT_MANAGER_OUTSIDE | DRAWER_UPDATE_THEME | CALENDAR_OPEN_EVENT | CALENDAR_CALL_EVENT_MANAGER | SET_WIDGET_EVENT | UNSET_WIDGET_EVENT | REQUEST_OPEN_EVENTS | REFRESH_WIDGET | OPEN_CONTACT_MODAL; /** * QUICK SETTINGS */ export const KEY_TRANSPARENCY_REMINDER_UPDATE = 'KEY_TRANSPARENCY_REMINDER_UPDATE'; export interface QuickSettingsReminders { icon?: IconName; color?: ThemeColor; text?: string; callback: () => void; testID: string; }
8,453
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/drive/constants.ts
import { SORT_DIRECTION } from '../constants'; import { isMobile } from '../helpers/browser'; import { LayoutSetting, SortSetting, UserSettings } from '../interfaces/drive/userSettings'; export const MB = 1024 * 1024; export const FOLDER_PAGE_SIZE = 150; export const BATCH_REQUEST_SIZE = 50; export const FILE_CHUNK_SIZE = 4 * MB; export const MEMORY_DOWNLOAD_LIMIT = (isMobile() ? 100 : 500) * MB; export const HARDWARE_CONCURRENCY = (typeof window !== 'undefined' && window.navigator?.hardwareConcurrency) || 1; // openpgp.js creates hardwareConcurrency of web workers to do decryption. // Using less threads for download means we don't use available potential. // Using more threads will not speed things up much because thread in this // context is not real thread but concurrently running downloads in the main // thread. // In the future, with the openpgp.js v5, we will create web workers manually. // That will allow us to create more workers and keep download and decryption // part in the same thread to save some data exchanges between threads. // We could really allow more workers than available CPUs, because decryption // is done on the stream as data comes in, i.e., not that heavy operation. // Of course, we cannot allow, lets say, twice as many workers per download // of one file but for all downloads to not kill user's device. Ideally, we // want to make download of one file as fast as possible, but limit it to the // same speed with more ongoing downloads or uploads. export const MAX_THREADS_PER_DOWNLOAD = HARDWARE_CONCURRENCY; export const MAX_THREADS_PER_REQUEST = 5; export const DEFAULT_SORT_FIELD = 'ModifyTime'; export const DEFAULT_SORT_ORDER: SORT_DIRECTION = SORT_DIRECTION.DESC; export const DEFAULT_USER_SETTINGS: UserSettings = { Layout: LayoutSetting.List, Sort: SortSetting.ModifiedDesc, RevisionRetentionDays: 0, }; export const UPLOAD_TIMEOUT = 90000; export const DOWNLOAD_TIMEOUT = 90000; export const DOWNLOAD_RETRIES_ON_TIMEOUT = 3; export const EXPENSIVE_REQUEST_TIMEOUT = 60000; export const MAX_NAME_LENGTH = 255; export const MIN_SHARED_URL_PASSWORD_LENGTH = 8; export const SHARE_GENERATED_PASSWORD_LENGTH = 12; export const DEFAULT_SHARE_MAX_ACCESSES = 0; // Zero means unlimited. export const MAX_SAFE_UPLOADING_FILE_COUNT = 500; export const MAX_SAFE_UPLOADING_FILE_SIZE = 5 * 1024 * 1024 * 1024; // GB export const CUSTOM_DATA_FORMAT = 'pd-custom'; export const THUMBNAIL_MAX_SIDE = 512; // in pixels export const THUMBNAIL_MAX_SIZE = 60 * 1024; // in bytes, 60kB export const HD_THUMBNAIL_MAX_SIDE = 1920; // in pixels export const HD_THUMBNAIL_MAX_SIZE = 1024 * 1024; // in bytes, 1mB export const THUMBNAIL_QUALITIES = [0.7, 0.5, 0.3, 0.1, 0]; // Used qualities to stick under THUMBNAIL_MAX_SIZE. export const VIDEO_THUMBNAIL_MAX_TIME_LOCATION: number = 300; // In seconds export enum LinkURLType { FOLDER = 'folder', FILE = 'file', } export enum EVENT_TYPES { DELETE = 0, CREATE = 1, UPDATE = 2, UPDATE_METADATA = 3, } export enum EXPIRATION_DAYS { NEVER = 'never', ONE = '1', FIFTEEN = '15', THIRTY = '30', SIXTY = '60', NINETY = '90', } /** * @deprecated common to different products, should be removed and use `API_CODES` from _/lib/constants.ts_ instead */ export enum RESPONSE_CODE { SUCCESS = 1000, NOT_ALLOWED = 2011, INVALID_REQUIREMENT = 2000, INVALID_LINK_TYPE = 2001, ALREADY_EXISTS = 2500, NOT_FOUND = 2501, INVALID_ID = 2061, } export enum SupportedMimeTypes { aac = 'audio/aac', apk = 'application/vnd.android.package-archive', apng = 'image/apng', arc = 'application/x-freearc', avi = 'video/x-msvideo', avif = 'image/avif', bmp = 'image/bmp', bzip2 = 'application/x-bzip2', cr3 = 'image/x-canon-cr3', docx = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', eot = 'application/vnd.ms-fontobject', epub = 'application/epub+zip', flac = 'audio/x-flac', flv = 'video/x-flv', gif = 'image/gif', gzip = 'application/gzip', heic = 'image/heic', heics = 'image/heic-sequence', heif = 'image/heif', heifs = 'image/heif-sequence', ico = 'image/x-icon', jpg = 'image/jpeg', keynote = 'application/vnd.apple.keynote', m4a = 'audio/x-m4a', m4v = 'video/x-m4v', midi = 'audio/midi', mp1s = 'video/MP1S', mp2p = 'video/MP2P', mp2t = 'video/mp2t', mp4a = 'audio/mp4', mp4v = 'video/mp4', mpeg = 'audio/mpeg', mpg = 'video/mpeg', numbers = 'application/vnd.apple.numbers', odp = 'application/vnd.oasis.opendocument.presentation', ods = 'application/vnd.oasis.opendocument.spreadsheet', odt = 'application/vnd.oasis.opendocument.text', oga = 'audio/ogg', ogg = 'application/ogg', ogv = 'video/ogg', opus = 'audio/opus', otf = 'font/otf', pages = 'application/vnd.apple.pages', pdf = 'application/pdf', png = 'image/png', pptx = 'application/vnd.openxmlformats-officedocument.presentationml.presentation', qcp = 'audio/qcelp', qt = 'video/quicktime', rar = 'application/vnd.rar', rtf = 'application/rtf', svg = 'image/svg+xml', swf = 'application/x-shockwave-flash', tar = 'application/x-tar', tiff = 'image/tiff', ttf = 'font/ttf', v3g2 = 'video/3gpp2', v3gp = 'video/3gpp', wav = 'audio/wav', webp = 'image/webp', woff = 'font/woff', woff2 = 'font/woff2', x7zip = 'application/x-7z-compressed', xlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', xml = 'text/xml', zip = 'application/zip', vdnMicrosoftIcon = 'image/vnd.microsoft.icon', } export const EXTRA_EXTENSION_TYPES: { [ext: string]: string } = { py: 'text/x-python', ts: 'application/typescript', }; export const fileDescriptions: { [type: string]: string } = { 'application/java-archive': 'Java Archive (JAR)', 'application/javascript': 'JavaScript', 'application/json': 'JSON format', 'application/ld+json': 'JSON-LD format', 'application/msword': 'Microsoft Word', 'application/octet-stream': 'Binary', 'application/typescript': 'TypeScript', 'application/vnd.amazon.ebook': 'Amazon Kindle eBook format', 'application/vnd.apple.installer+xml': 'Apple Installer Package', 'application/vnd.mozilla.xul+xml': 'XUL', 'application/vnd.ms-excel': 'Microsoft Excel', 'application/vnd.ms-powerpoint': 'Microsoft PowerPoint', 'application/vnd.visio': 'Microsoft Visio', 'application/x-abiword': 'AbiWord document', 'application/x-bzip': 'BZip archive', 'application/x-csh': 'C-Shell script', 'application/x-freearc': 'Archive document', 'application/x-httpd-php': 'Hypertext Preprocessor (Personal Home Page)', 'application/x-sh': 'Bourne shell script', 'application/xhtml+xml': 'XHTML', 'application/xml': 'XML', 'audio/3gpp': '3GPP audio/video container', 'audio/3gpp2': '3GPP2 audio/video container', 'audio/webm': 'WEBM audio', 'audio/x-midi': 'Musical Instrument Digital Interface (MIDI)', [SupportedMimeTypes.vdnMicrosoftIcon]: 'Icon format', 'text/calendar': 'iCalendar format', 'text/css': 'Cascading Style Sheets (CSS)', 'text/csv': 'Comma-separated values (CSV)', 'text/html': 'HyperText Markup Language (HTML)', 'text/javascript': 'JavaScript', 'text/plain': 'Text', 'text/x-csh': 'C-Shell script', 'text/x-python': 'Python', 'video/webm': 'WEBM video', [SupportedMimeTypes.aac]: 'AAC audio', [SupportedMimeTypes.apng]: 'Animated Portable Network Graphics', [SupportedMimeTypes.apk]: 'Android Package', [SupportedMimeTypes.avi]: 'AVI: Audio Video Interleave', [SupportedMimeTypes.bmp]: 'Windows OS/2 Bitmap Graphics', [SupportedMimeTypes.bzip2]: 'BZip2 archive', [SupportedMimeTypes.docx]: 'Microsoft Word (OpenXML)', [SupportedMimeTypes.eot]: 'MS Embedded OpenType fonts', [SupportedMimeTypes.epub]: 'Electronic publication (EPUB)', [SupportedMimeTypes.flv]: 'Flash Video', [SupportedMimeTypes.gif]: 'Graphics Interchange Format (GIF)', [SupportedMimeTypes.gzip]: 'GZip Compressed Archive', [SupportedMimeTypes.ico]: 'Icon format', [SupportedMimeTypes.jpg]: 'JPEG images', [SupportedMimeTypes.keynote]: 'Apple Keynote', [SupportedMimeTypes.midi]: 'Musical Instrument Digital Interface (MIDI)', [SupportedMimeTypes.mp2t]: 'MPEG transport stream', [SupportedMimeTypes.mpeg]: 'MP3 audio', [SupportedMimeTypes.mpg]: 'MPEG Video', [SupportedMimeTypes.numbers]: 'Apple Numbers', [SupportedMimeTypes.odp]: 'OpenDocument presentation document', [SupportedMimeTypes.ods]: 'OpenDocument spreadsheet document', [SupportedMimeTypes.odt]: 'OpenDocument text document', [SupportedMimeTypes.oga]: 'OGG audio', [SupportedMimeTypes.ogg]: 'OGG', [SupportedMimeTypes.ogv]: 'OGG video', [SupportedMimeTypes.opus]: 'Opus audio', [SupportedMimeTypes.otf]: 'OpenType font', [SupportedMimeTypes.pages]: 'Apple Pages', [SupportedMimeTypes.pdf]: 'Adobe Portable Document Format (PDF)', [SupportedMimeTypes.png]: 'Portable Network Graphics', [SupportedMimeTypes.pptx]: 'Microsoft PowerPoint (OpenXML)', [SupportedMimeTypes.rar]: 'RAR archive', [SupportedMimeTypes.rtf]: 'Rich Text Format (RTF)', [SupportedMimeTypes.svg]: 'Scalable Vector Graphics (SVG)', [SupportedMimeTypes.swf]: 'Small web format (SWF)', [SupportedMimeTypes.tar]: 'Tape Archive (TAR)', [SupportedMimeTypes.tiff]: 'Tagged Image File Format (TIFF)', [SupportedMimeTypes.ttf]: 'TrueType Font', [SupportedMimeTypes.v3g2]: '3GPP2 audio/video container', [SupportedMimeTypes.v3gp]: '3GPP audio/video container', [SupportedMimeTypes.wav]: 'Waveform Audio Format', [SupportedMimeTypes.webp]: 'WEBP image', [SupportedMimeTypes.woff]: 'Web Open Font Format (WOFF)', [SupportedMimeTypes.woff2]: 'Web Open Font Format (WOFF)', [SupportedMimeTypes.x7zip]: '7-zip archive', [SupportedMimeTypes.xlsx]: 'Microsoft Excel (OpenXML)', [SupportedMimeTypes.xml]: 'XML', [SupportedMimeTypes.zip]: 'ZIP archive', }; export const DS_STORE = '.DS_Store'; // Delete once sharing between members is fully implemented. export const MEMBER_SHARING_ENABLED = false; export const PHOTOS_PAGE_SIZE = 500; // Accepted files for photos. This value must be used in input `accept` attribute export const PHOTOS_ACCEPTED_INPUT = `image/*,video/*,${SupportedMimeTypes.heic},${SupportedMimeTypes.heif}`;
8,454
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/drive/translations.ts
import { c } from 'ttag'; export const getNumAccessesTooltipMessage = () => c('Info').t`The download count includes both actual downloads and instances when files are previewed.`; export const getSizeTooltipMessage = () => c('Info') .t`The encrypted data is slightly larger due to the overhead of the encryption and signatures, which ensure the security of your data.`;
8,455
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/drive/urls.ts
import { getStaticURL } from '@proton/shared/lib/helpers/url'; export const DRIVE_LANDING_PAGE = getStaticURL('/drive'); export const DRIVE_PRICING_PAGE = getStaticURL('/drive/pricing?product=drive '); export const DRIVE_IOS_APP = 'https://apps.apple.com/app/proton-drive-cloud-storage/id1509667851'; export const DRIVE_ANDROID_APP = 'https://play.google.com/store/apps/details?id=me.proton.android.drive';
8,456
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/drive
petrpan-code/ProtonMail/WebClients/packages/shared/lib/drive/utils/share.ts
import { ShareFlags } from '../../interfaces/drive/share'; export const isMainShare = (meta: { Flags?: number }) => { return !!(typeof meta.Flags !== 'undefined' && meta.Flags & ShareFlags.MainShare); };
8,457
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/eventManager/eventManager.ts
import noop from '@proton/utils/noop'; import { getEvents } from '../api/events'; import { FIBONACCI_LIST, INTERVAL_EVENT_TIMER } from '../constants'; import createListeners, { Listener } from '../helpers/listeners'; import { onceWithQueue } from '../helpers/onceWithQueue'; import { Api } from '../interfaces'; export enum EVENT_ID_KEYS { DEFAULT = 'EventID', CALENDAR = 'CalendarModelEventID', } type EventResponse = { [key in EVENT_ID_KEYS]: string; } & { More: 0 | 1; }; interface EventManagerConfig { /** Function to call the API */ api: Api; /** Initial event ID to begin from */ eventID: string; /** Maximum interval time to wait between each call */ interval?: number; /** Event polling endpoint override */ query?: (eventID: string) => object; eventIDKey?: EVENT_ID_KEYS; } export type SubscribeFn = <A extends any[], R = void>(listener: Listener<A, R>) => () => void; export interface EventManager { setEventID: (eventID: string) => void; getEventID: () => string | undefined; start: () => void; stop: () => void; call: () => Promise<void>; reset: () => void; subscribe: SubscribeFn; } /** * Create the event manager process. */ const createEventManager = ({ api, eventID: initialEventID, interval = INTERVAL_EVENT_TIMER, query = getEvents, eventIDKey = EVENT_ID_KEYS.DEFAULT, }: EventManagerConfig): EventManager => { const listeners = createListeners<[EventResponse]>(); if (!initialEventID) { throw new Error('eventID must be provided.'); } let STATE: { retryIndex: number; lastEventID?: string; timeoutHandle?: ReturnType<typeof setTimeout>; abortController?: AbortController; } = { retryIndex: 0, lastEventID: initialEventID, timeoutHandle: undefined, abortController: undefined, }; const setEventID = (eventID: string) => { STATE.lastEventID = eventID; }; const getEventID = () => { return STATE.lastEventID; }; const setRetryIndex = (index: number) => { STATE.retryIndex = index; }; const getRetryIndex = () => { return STATE.retryIndex; }; const increaseRetryIndex = () => { const index = getRetryIndex(); // Increase the retry index when the call fails to not spam. if (index < FIBONACCI_LIST.length - 1) { setRetryIndex(index + 1); } }; /** * Start the event manager, does nothing if it is already started. */ const start = () => { const { timeoutHandle, retryIndex } = STATE; if (timeoutHandle) { return; } const ms = interval * FIBONACCI_LIST[retryIndex]; // eslint-disable-next-line STATE.timeoutHandle = setTimeout(call, ms); }; /** * Stop the event manager, does nothing if it's already stopped. */ const stop = () => { const { timeoutHandle, abortController } = STATE; if (abortController) { abortController.abort(); delete STATE.abortController; } if (timeoutHandle) { clearTimeout(timeoutHandle); delete STATE.timeoutHandle; } }; /** * Stop the event manager and reset its state. */ const reset = () => { stop(); STATE = { retryIndex: 0 }; listeners.clear(); }; /** * Call the event manager. Either does it immediately, or queues the call until after the current call has finished. */ const call = onceWithQueue(async () => { try { stop(); const abortController = new AbortController(); STATE.abortController = abortController; for (;;) { const eventID = getEventID(); if (!eventID) { throw new Error('EventID undefined'); } let result: EventResponse; try { result = await api<EventResponse>({ ...query(eventID), signal: abortController.signal, silence: true, }); } catch (error: any) { if (error.name === 'AbortError') { return; } throw error; } await Promise.all(listeners.notify(result)).catch(noop); const { More, [eventIDKey]: nextEventID } = result; setEventID(nextEventID); setRetryIndex(0); if (!More) { break; } } delete STATE.abortController; start(); } catch (error: any) { delete STATE.abortController; increaseRetryIndex(); start(); throw error; } }); return { setEventID, getEventID, start, stop, call, reset, subscribe: listeners.subscribe as SubscribeFn, }; }; export default createEventManager;
8,458
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/eventManager
petrpan-code/ProtonMail/WebClients/packages/shared/lib/eventManager/calendar/calendarBootstrap.ts
import { CalendarKey, CalendarMember, CalendarSettings as tsCalendarSettings } from '../../interfaces/calendar'; import { CalendarMemberEventManager } from '../../interfaces/calendar/EventManager'; import { getIsCalendarMemberEventManagerCreate, getIsCalendarMemberEventManagerDelete, getIsCalendarMemberEventManagerUpdate, } from './helpers'; /** * Find the calendar id for an event, since it's not always returned. */ const findCalendarID = (calendarBootstrapCache: Map<string, any>, cb: (value: any) => boolean) => { for (const [calendarID, record] of calendarBootstrapCache) { // The old bootstrapped result if (record && record.value && cb(record.value)) { return calendarID; } } }; /** * Assumes that updates to the calendar bootstrap cache do not trigger UI updates * In other words, that the bootstrap is only used through callbacks but not needed to re-render UI * In consequence, no setCache is invoked, the cache is mutated directly */ export const updateBootstrapKeysAndSettings = ( { CalendarKeys = [], CalendarSettings = [], }: { CalendarKeys: { ID: string; Key: CalendarKey }[]; CalendarSettings: { CalendarSettings: tsCalendarSettings }[]; }, calendarBootstrapCache: Map<string, any>, calendarKeysCache: Map<string, any> ) => { if (!calendarBootstrapCache) { return; } if (CalendarSettings.length) { for (const { CalendarSettings: newValue } of CalendarSettings) { const oldRecord = calendarBootstrapCache.get(newValue.CalendarID); if (oldRecord && oldRecord.value) { // Mutation on purpose oldRecord.value.CalendarSettings = newValue; } } } if (CalendarKeys.length) { const deleteCalendarFromCache = (calendarID: string) => { if (calendarBootstrapCache) { calendarBootstrapCache.delete(calendarID); } if (calendarKeysCache) { calendarKeysCache.delete(calendarID); } }; CalendarKeys.forEach(({ ID: KeyID, Key }) => { // When a new calendar key is received, the entire calendar cache is invalidated. // TODO: Merge the bootstrapped version. if (Key && Key.CalendarID) { deleteCalendarFromCache(Key.CalendarID); return; } const calendarID = findCalendarID(calendarBootstrapCache, ({ Keys }) => { return Array.isArray(Keys) && Keys.find(({ ID: otherID }) => otherID === KeyID); }); if (calendarID) { deleteCalendarFromCache(Key.CalendarID); } }); } }; /** * Assumes that updates to the calendar bootstrap cache do not trigger UI updates * In other words, that the bootstrap is only used through callbacks but not needed to re-render UI * In consequence, no setCache is invoked, the cache is mutated directly */ export const updateBootstrapMembers = ( calendarBootstrapCache: Map<string, any>, { CalendarMembers = [], }: { CalendarMembers?: CalendarMemberEventManager[]; } ) => { if (!calendarBootstrapCache) { return; } if (CalendarMembers.length) { CalendarMembers.forEach((event) => { if (getIsCalendarMemberEventManagerDelete(event)) { const { ID: memberID } = event; const calendarID = findCalendarID(calendarBootstrapCache, ({ Members }) => { return Members.find(({ ID }: { ID: string }) => ID === memberID); }); if (!calendarID) { return; } const oldRecord = calendarBootstrapCache.get(calendarID); const oldMembers = oldRecord.value.Members as CalendarMember[]; const memberIndex = oldMembers.findIndex(({ ID }) => memberID === ID); if (memberIndex !== -1) { return; } // Mutation on purpose oldMembers.splice(memberIndex, 1); } else { const { ID, Member } = event; const oldRecord = calendarBootstrapCache.get(Member.CalendarID); if (!oldRecord?.value) { return; } const oldMembers = oldRecord.value.Members as CalendarMember[]; const memberIndex = oldMembers.findIndex(({ ID: memberID }) => memberID === ID); if (getIsCalendarMemberEventManagerCreate(event)) { if (memberIndex !== -1) { return; } // Mutation on purpose oldMembers.push(Member); } else if (getIsCalendarMemberEventManagerUpdate(event)) { if (memberIndex === -1) { return; } // Mutation on purpose oldMembers.splice(memberIndex, 1, event.Member); } } }); } };
8,459
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/eventManager
petrpan-code/ProtonMail/WebClients/packages/shared/lib/eventManager/calendar/calendarUserSettings.ts
import { CalendarUserSettingsModel } from '../../models'; import { STATUS } from '../../models/cache'; const calendarUserSettingsModelKey = CalendarUserSettingsModel.key; export const updateCalendarsUserSettings = (cache: Map<string, any>, data: any) => { if (data[calendarUserSettingsModelKey]) { const { value: oldValue, status } = cache.get(calendarUserSettingsModelKey) || {}; if (status === STATUS.RESOLVED) { cache.set(calendarUserSettingsModelKey, { status: STATUS.RESOLVED, value: CalendarUserSettingsModel.update(oldValue, data[calendarUserSettingsModelKey]), }); } } };
8,460
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/eventManager
petrpan-code/ProtonMail/WebClients/packages/shared/lib/eventManager/calendar/calendarsWithMembers.ts
import { CalendarWithOwnMembers } from '../../interfaces/calendar'; import { CalendarEventManager, CalendarMemberEventManager } from '../../interfaces/calendar/EventManager'; import { STATUS } from '../../models/cache'; import { CALENDARS_CACHE_KEY } from '../../models/calendarsModel'; import { findMemberIndices, getIsCalendarEventManagerCreate, getIsCalendarEventManagerDelete, getIsCalendarEventManagerUpdate, getIsCalendarMemberEventManagerCreate, getIsCalendarMemberEventManagerDelete, getIsCalendarMemberEventManagerUpdate, } from './helpers'; export const updateCalendarsWithMembers = ( cache: Map<string, any>, { Calendars = [], CalendarMembers = [], }: { Calendars?: CalendarEventManager[]; CalendarMembers?: CalendarMemberEventManager[]; }, ownAddressIDs: string[], stopManagers?: (ids: string[]) => void ) => { const { value: oldCalendarsWithMembers, status } = cache.get(CALENDARS_CACHE_KEY) || {}; if (status !== STATUS.RESOLVED) { return; } const updateCalendars = !!Calendars.length; const updateMembers = !!CalendarMembers.length; if (!updateCalendars && !updateMembers) { return; } const newCalendarsWithMembers: CalendarWithOwnMembers[] = [...oldCalendarsWithMembers]; if (updateCalendars) { for (const event of Calendars) { if (getIsCalendarEventManagerDelete(event)) { const index = newCalendarsWithMembers.findIndex(({ ID }) => ID === event.ID); if (index !== -1) { newCalendarsWithMembers.splice(index, 1); } stopManagers?.([event.ID]); } else if (getIsCalendarEventManagerCreate(event)) { const { ID: calendarID, Calendar } = event; const index = newCalendarsWithMembers.findIndex(({ ID }) => ID === calendarID); if (index !== -1) { // The calendar already exists for a creation event. Ignore it. continue; } newCalendarsWithMembers.push({ ...Calendar }); } else if (getIsCalendarEventManagerUpdate(event)) { const { ID: calendarID, Calendar } = event; const index = newCalendarsWithMembers.findIndex(({ ID }) => ID === calendarID); if (index !== -1) { // update only the calendar part. Members updated below if needed const oldCalendarWithMembers = oldCalendarsWithMembers[index]; newCalendarsWithMembers.splice(index, 1, { ...oldCalendarWithMembers, ...Calendar }); } } } } if (updateMembers) { for (const event of CalendarMembers) { if (getIsCalendarMemberEventManagerDelete(event)) { const [calendarIndex, memberIndex] = findMemberIndices(event.ID, newCalendarsWithMembers); if (calendarIndex !== -1 && memberIndex !== -1) { const { CalendarID, AddressID } = newCalendarsWithMembers[calendarIndex].Members[memberIndex]!; if (ownAddressIDs.includes(AddressID)) { // the user is the member removed -> remove the calendar newCalendarsWithMembers.splice(calendarIndex, 1); stopManagers?.([CalendarID]); } else { // otherwise a member of one of an owned calendar got removed -> remove the member newCalendarsWithMembers[calendarIndex].Members.splice(memberIndex, 1); } } } else { const [calendarIndex, memberIndex] = findMemberIndices( event.ID, newCalendarsWithMembers, event.Member.CalendarID ); // If the targeted calendar cannot be found, ignore this update. It will be dealt with when the calendar update happens. if (calendarIndex === -1) { continue; } if (getIsCalendarMemberEventManagerCreate(event)) { if (memberIndex !== -1) { continue; } newCalendarsWithMembers[calendarIndex].Members.push(event.Member); } else if (getIsCalendarMemberEventManagerUpdate(event)) { if (memberIndex === -1) { continue; } newCalendarsWithMembers[calendarIndex].Members.splice(memberIndex, 1, event.Member); } } } } cache.set(CALENDARS_CACHE_KEY, { status: STATUS.RESOLVED, value: newCalendarsWithMembers, }); };
8,461
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib/eventManager
petrpan-code/ProtonMail/WebClients/packages/shared/lib/eventManager/calendar/helpers.ts
import { EVENT_ACTIONS } from '../../constants'; import { CalendarWithOwnMembers } from '../../interfaces/calendar'; import { CalendarEventManager, CalendarEventManagerCreate, CalendarEventManagerDelete, CalendarEventManagerUpdate, CalendarMemberEventManager, CalendarMemberEventManagerCreate, CalendarMemberEventManagerDelete, CalendarMemberEventManagerUpdate, } from '../../interfaces/calendar/EventManager'; export const getIsCalendarEventManagerDelete = (event: CalendarEventManager): event is CalendarEventManagerDelete => { return event.Action === EVENT_ACTIONS.DELETE; }; export const getIsCalendarEventManagerCreate = (event: CalendarEventManager): event is CalendarEventManagerCreate => { return event.Action === EVENT_ACTIONS.CREATE; }; export const getIsCalendarEventManagerUpdate = (event: CalendarEventManager): event is CalendarEventManagerUpdate => { return event.Action === EVENT_ACTIONS.UPDATE; }; export const getIsCalendarMemberEventManagerDelete = ( event: CalendarMemberEventManager ): event is CalendarMemberEventManagerDelete => { return event.Action === EVENT_ACTIONS.DELETE; }; export const getIsCalendarMemberEventManagerCreate = ( event: CalendarMemberEventManager ): event is CalendarMemberEventManagerCreate => { return event.Action === EVENT_ACTIONS.CREATE; }; export const getIsCalendarMemberEventManagerUpdate = ( event: CalendarMemberEventManager ): event is CalendarMemberEventManagerUpdate => { return event.Action === EVENT_ACTIONS.UPDATE; }; export const findMemberIndices = ( memberID: string, calendarsWithMembers: CalendarWithOwnMembers[], memberCalendarID?: string ) => { let calendarIndex = -1; let memberIndex = -1; calendarsWithMembers.forEach(({ ID, Members }, i) => { if (ID === memberCalendarID) { calendarIndex = i; } Members.forEach(({ ID }, j) => { if (ID === memberID) { memberIndex = j; calendarIndex = i; } }); }); return [calendarIndex, memberIndex]; };
8,462
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/fetch/ApiError.ts
export class ApiError extends Error { response?: Response; status: number; data?: any; config: any; constructor(message: string, status: number, name: string) { super(message); Object.setPrototypeOf(this, ApiError.prototype); this.status = status; this.name = name; } } export const createApiError = (name: string, response: Response, config: any, data?: any) => { const { statusText, status } = response; const error = new ApiError(statusText, status, name); error.response = response; error.data = data; error.config = config; return error; }; export const serializeApiErrorData = (error: ApiError) => { /** * We are only interested in the data here, so we strip almost everything else. In particular: * * error.response is typically not serializable * * error.config might not be serializable either (for instance it can include (aborted) abort controllers) */ return { name: error.name, status: error.status, statusText: error.response?.statusText || error.message, data: error.data, }; }; export const deserializeApiErrorData = ({ name, status, statusText, data, }: ReturnType<typeof serializeApiErrorData>) => { const error = new ApiError(statusText, status, name); error.data = data; return error; }; export enum CUSTOM_FETCH_ERROR_STATUS_CODE { NO_NETWORK_CONNECTION = 0, TIMEOUT = -1, } export const createOfflineError = (config: any) => { const error = new ApiError( 'No network connection', CUSTOM_FETCH_ERROR_STATUS_CODE.NO_NETWORK_CONNECTION, 'OfflineError' ); error.config = config; return error; }; export const createTimeoutError = (config: any) => { const error = new ApiError('Request timed out', CUSTOM_FETCH_ERROR_STATUS_CODE.TIMEOUT, 'TimeoutError'); error.config = config; return error; };
8,463
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/fetch/fetch.js
import { DEFAULT_TIMEOUT } from '../constants'; import { createOfflineError, createTimeoutError } from './ApiError'; import { checkStatus, createUrl, serializeData } from './helpers'; const fetchHelper = ({ url: urlString, params, signal, timeout = DEFAULT_TIMEOUT, ...rest }) => { const abortController = new AbortController(); let isTimeout = false; const config = { mode: 'cors', credentials: 'include', redirect: 'follow', signal: abortController.signal, ...rest, }; const url = createUrl(urlString, params); const timeoutHandle = setTimeout(() => { isTimeout = true; abortController.abort(); }, timeout); const otherAbortCallback = () => { abortController.abort(); clearTimeout(timeoutHandle); }; signal?.addEventListener('abort', otherAbortCallback); return fetch(url, config) .catch((e) => { if (isTimeout) { throw createTimeoutError(config); } if (e?.name === 'AbortError') { throw e; } // Assume any other error is offline error. throw createOfflineError(config); }) .then((response) => { clearTimeout(timeoutHandle); return checkStatus(response, config); }) .finally(() => { signal?.removeEventListener('abort', otherAbortCallback); }); }; export default ({ data, headers, input = 'json', ...config }) => { const { headers: dataHeaders, body } = serializeData(data, input); return fetchHelper({ ...config, headers: { ...headers, ...dataHeaders, }, body, }); };
8,464
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/fetch/headers.ts
import { HumanVerificationMethodType } from '../interfaces'; interface Headers { [key: string]: any; } interface MergeHeaderArgs { headers?: Headers; [key: string]: any; } export const mergeHeaders = ({ headers: configHeaders, ...restConfig }: MergeHeaderArgs, headers: Headers) => ({ ...restConfig, headers: { ...configHeaders, ...headers, }, }); export const getAppVersionHeaders = (clientID: string, appVersion: string) => { if (process.env.NODE_ENV !== 'production') { appVersion = `${appVersion.replace(/-.*/, '')}-dev`; } return { 'x-pm-appversion': `${clientID}@${appVersion}`, }; }; export const getUIDHeaderValue = (headers: Headers) => headers?.['x-pm-uid']; export const getUIDHeaders = (UID: string) => ({ 'x-pm-uid': UID, }); export const getAuthHeaders = (UID: string, AccessToken: string) => ({ 'x-pm-uid': UID, Authorization: `Bearer ${AccessToken}`, }); export const getLocaleHeaders = (localeCode: string) => ({ 'x-pm-locale': localeCode, }); export const withAuthHeaders = (UID: string, AccessToken: string, config: any) => mergeHeaders(config, getAuthHeaders(UID, AccessToken)); export const withUIDHeaders = (UID: string, config: any) => mergeHeaders(config, getUIDHeaders(UID)); export const withLocaleHeaders = (localeCode: string, config: any) => mergeHeaders(config, getLocaleHeaders(localeCode)); export const getVerificationHeaders = ( token: string | undefined, tokenType: HumanVerificationMethodType | undefined ) => { if (!token || !tokenType) { return {}; } return { 'x-pm-human-verification-token': token, 'x-pm-human-verification-token-type': tokenType, }; }; export const getDeviceVerificationHeaders = (challengeB64: string) => { return { 'X-PM-DV': challengeB64, }; }; export const getOwnershipVerificationHeaders = (value: 'lax') => { return { 'X-PM-OV': value, }; }; export const getCroHeaders = (paymentToken: string | undefined) => { if (!paymentToken) { return {}; } return { 'x-pm-payment-info-token': paymentToken, }; }; export const withVerificationHeaders = ( token: string | undefined, tokenType: HumanVerificationMethodType | undefined, config: any ) => { return mergeHeaders(config, getVerificationHeaders(token, tokenType)); };
8,465
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/fetch/helpers.ts
import window from '../window'; import { createApiError } from './ApiError'; const appendQueryParams = (url: URL, params: { [key: string]: any }) => { Object.keys(params).forEach((key) => { const value = params[key]; if (typeof value === 'undefined') { return; } url.searchParams.append(key, value); }); }; export const createUrl = (urlString: string, params: { [key: string]: any } = {}) => { let url: URL; if (typeof window !== 'undefined') { url = new URL(urlString, window.location.origin); } else { url = new URL(urlString); } appendQueryParams(url, params); return url; }; export const checkStatus = (response: Response, config: any) => { const { status } = response; if (status >= 200 && status < 300) { return response; } return response .json() .catch(() => { return {}; }) .then((data) => { throw createApiError('StatusCodeError', response, config, data); }); }; export const getDateHeader = (headers: Headers) => { const dateHeader = headers?.get?.('date'); if (!dateHeader) { return; } const newServerTime = new Date(dateHeader); if (Number.isNaN(+newServerTime)) { return; } return newServerTime; }; export const serializeFormData = (data: { [key: string]: any }) => { const formData = new FormData(); Object.keys(data).forEach((key) => { if (Array.isArray(data[key])) { data[key].forEach((val: any) => formData.append(key, val)); } else { formData.append(key, data[key]); } }); return formData; }; export const serializeData = (data: any, input: string) => { if (!data) { return {}; } if (input === 'json') { return { body: JSON.stringify(data), headers: { 'Content-Type': 'application/json', }, }; } if (input === 'form') { return { body: serializeFormData(data), }; } return {}; };
8,466
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/address.ts
import unary from '@proton/utils/unary'; import { ADDRESS_RECEIVE, ADDRESS_SEND, ADDRESS_STATUS, ADDRESS_TYPE } from '../constants'; import { Address, Recipient } from '../interfaces'; import { ContactEmail } from '../interfaces/contacts'; import { canonicalizeInternalEmail } from './email'; export const getIsAddressEnabled = (address: Address) => { return address.Status === ADDRESS_STATUS.STATUS_ENABLED; }; export const getIsAddressDisabled = (address: Address) => { return address.Status === ADDRESS_STATUS.STATUS_DISABLED; }; export const getIsAddressActive = (address: Address) => { return ( address.Status === ADDRESS_STATUS.STATUS_ENABLED && address.Receive === ADDRESS_RECEIVE.RECEIVE_YES && address.Send === ADDRESS_SEND.SEND_YES ); }; export const getActiveAddresses = (addresses: Address[]): Address[] => { return addresses.filter(unary(getIsAddressActive)); }; export const hasAddresses = (addresses: Address[] | undefined): boolean => { return Array.isArray(addresses) && addresses.length > 0; }; export const getIsAddressExternal = ({ Type }: Address) => { return Type === ADDRESS_TYPE.TYPE_EXTERNAL; }; export const getHasOnlyExternalAddresses = (addresses: Address[]) => { return addresses.length >= 1 && addresses.every((address) => getIsAddressExternal(address)); }; export const contactToRecipient = (contact: Partial<ContactEmail> = {}, groupPath?: string): Partial<Recipient> => ({ Name: contact.Name, Address: contact.Email, ContactID: contact.ContactID, Group: groupPath, }); export const findUserAddress = (userEmail?: string, addresses: Address[] = []) => { if (!userEmail) { return undefined; } const canonicalUserEmail = canonicalizeInternalEmail(userEmail); return addresses.find(({ Email }) => canonicalizeInternalEmail(Email) === canonicalUserEmail); }; export const getSelfSendAddresses = (ownAddresses: Address[]) => { // For custom domains, Proton Mail allows to have multiple sub-users with the same email address // as long as only one of them is enabled. This poses problems when a sub-user // with a disabled address wants to send email to the same address enabled in another sub-user. // Because of this case, it's better to consider disabled addresses as non self return ownAddresses.filter(({ Receive }) => !!Receive); }; export const getPrimaryAddress = (addresses: Address[]) => { const [address] = getActiveAddresses(addresses); if (!address) { return undefined; } return address; };
8,467
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/bitset.ts
import JSBI from 'jsbi'; /** * Set bit on the number */ export const setBit = (number = 0, mask: number): number => number | mask; /** * Toggle a bit from the number */ export const toggleBit = (number = 0, mask: number): number => number ^ mask; /** * Clear a bit from the number */ export const clearBit = (number = 0, mask: number): number => number & ~mask; /** * Check if a bit is set in the number */ export const hasBit = (number = 0, mask: number): boolean => (number & mask) === mask; export const hasBitBigInt = (number = JSBI.BigInt(0), mask: JSBI): boolean => JSBI.equal(JSBI.bitwiseAnd(number, JSBI.BigInt(mask)), JSBI.BigInt(mask)); /** * Get all bits which are toggled on in the respective bitmap */ export const getBits = (bitmap: number) => { const size = Math.floor(Math.log2(bitmap)) + 1; const bits: number[] = []; for (let i = 0; i <= size; i++) { const bit = 2 ** i; if (hasBit(bitmap, bit)) { bits.push(bit); } } return bits; };
8,468
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/blackfriday.ts
import { isWithinInterval } from 'date-fns'; import { PlanIDs } from '@proton/shared/lib/interfaces'; import { BLACK_FRIDAY, COUPON_CODES, CYCLE, PLANS } from '../constants'; export const isBlackFridayPeriod = () => { return isWithinInterval(new Date(), { start: BLACK_FRIDAY.START, end: BLACK_FRIDAY.END }); }; export const isCyberMonday = () => { return isWithinInterval(new Date(), { start: BLACK_FRIDAY.CYBER_START, end: BLACK_FRIDAY.CYBER_END }); }; export const canUpsellToVPNPassBundle = (planIDs: PlanIDs, cycle: CYCLE, couponCode?: string) => { if ( planIDs[PLANS.VPN] && [CYCLE.FIFTEEN, CYCLE.THIRTY].includes(cycle) && couponCode === COUPON_CODES.BLACK_FRIDAY_2023 ) { return true; } return false; };
8,469
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/boolean.ts
/** * This function is the same as (bool) => +bool, * but the return type is 0 | 1 instead of number */ export const booleanToNumber = (bool: boolean): 0 | 1 => { return bool ? 1 : 0; };
8,470
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/browser.ts
import UAParser from 'ua-parser-js'; const uaParser = new UAParser(); const ua = uaParser.getResult(); export const hasModulesSupport = () => { const script = document.createElement('script'); return 'noModule' in script; }; export const isFileSaverSupported = () => !!new Blob(); export const textToClipboard = (text = '', target = document.body) => { const oldActiveElement = document.activeElement as HTMLElement; if (navigator.clipboard) { void navigator.clipboard.writeText(text); } else { const dummy = document.createElement('textarea'); target.appendChild(dummy); dummy.value = text; dummy.select(); document.execCommand('copy'); target.removeChild(dummy); } oldActiveElement?.focus?.(); }; export const getOS = () => { const { name = 'other', version = '' } = ua.os; return { name, version }; }; export const isIos11 = () => { const { name, version } = getOS(); return name.toLowerCase() === 'ios' && parseInt(version, 10) === 11; }; export const isAndroid = () => { const { name } = getOS(); return name.toLowerCase().includes('android'); }; export const isSafari = () => ua.browser.name === 'Safari' || ua.browser.name === 'Mobile Safari'; export const isSafari11 = () => isSafari() && ua.browser.major === '11'; export const isMinimumSafariVersion = (version: number) => isSafari() && Number(ua.browser.version) >= version; export const isSafariMobile = () => ua.browser.name === 'Mobile Safari'; export const isIE11 = () => ua.browser.name === 'IE' && ua.browser.major === '11'; export const isEdge = () => ua.browser.name === 'Edge'; export const isEdgeChromium = () => isEdge() && ua.engine.name === 'Blink'; export const isBrave = () => ua.browser.name === 'Brave'; export const isFirefox = () => ua.browser.name === 'Firefox'; export const isMaybeTorLessThan11 = () => { const isMaybeTor = isFirefox() && /\.0$/.test(ua.browser.version || '') && // The Firefox minor revision is omitted. Intl.DateTimeFormat().resolvedOptions().timeZone === 'UTC' && // The timezone is set to UTC !Object.prototype.hasOwnProperty.call(window, 'Components') && // It strips out Components navigator.plugins.length === 0; // 0 plugins are returned // Starting from tor browser 11, tor is based on firefox 91 return isMaybeTor && !!ua.browser.major && +ua.browser.major < 91; }; export const isChrome = () => ua.browser.name === 'Chrome'; export const isJSDom = () => navigator.userAgent.includes('jsdom'); export const isMac = () => ua.os.name === 'Mac OS'; export const isWindows = () => ua.os.name === 'Windows'; export const hasTouch = typeof document === 'undefined' ? false : 'ontouchstart' in document.documentElement; export const hasCookie = () => navigator.cookieEnabled; export const getBrowser = () => ua.browser; export const getDevice = () => ua.device; export const isMobile = () => { const { type } = getDevice(); return type === 'mobile'; }; export const isDesktop = () => { const { type } = getDevice(); return !type; }; export const getIsIframe = () => window.self !== window.top; export const metaKey = isMac() ? '⌘' : 'Ctrl'; export const altKey = isMac() ? 'Option' : 'Alt'; export const shiftKey = 'Shift'; export const getActiveXObject = (name: string) => { try { // @ts-ignore return new ActiveXObject(name); } catch (error: any) { return undefined; } }; export const isIos = () => // @ts-expect-error window.MSStream cf. https://racase.com.np/javascript-how-to-detect-if-device-is-ios/ (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) || ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator.platform) || // iPad on iOS 13 detection (navigator.userAgent.includes('Mac') && 'ontouchend' in document); export const isIpad = () => isSafari() && navigator.maxTouchPoints && navigator.maxTouchPoints > 2; export const hasAcrobatInstalled = () => !!(getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl')); export const hasPDFSupport = () => { // mimeTypes is deprecated in favor of pdfViewerEnabled. return ( (navigator.mimeTypes && 'application/pdf' in navigator.mimeTypes) || navigator.pdfViewerEnabled || (isFirefox() && isDesktop()) || isIos() || hasAcrobatInstalled() ); }; export const replaceUrl = (url = '') => document.location.replace(url); export const redirectTo = (url = '') => replaceUrl(`${document.location.origin}${url}`); /** * Detect browser requiring direct action * Like opening a new tab */ export const requireDirectAction = () => isSafari() || isFirefox() || isEdge(); /** * Open an URL inside a new tab/window and remove the referrer * @links { https://mathiasbynens.github.io/rel-noopener/} */ export const openNewTab = (url: string) => { if (isIE11()) { const otherWindow = window.open(); if (!otherWindow) { return; } otherWindow.opener = null; otherWindow.location.href = url; return; } const anchor = document.createElement('a'); anchor.setAttribute('rel', 'noreferrer nofollow noopener'); anchor.setAttribute('target', '_blank'); anchor.href = url; return anchor.click(); }; // On safari < 14 the Version cookie is sent for index.html file but // not sent for asset requests due to https://bugs.webkit.org/show_bug.cgi?id=171566 export const doesNotSupportEarlyAccessVersion = () => isSafari() && Number(ua.browser.major) < 14; export const getHasWebAuthnSupport = () => { try { return !!navigator?.credentials?.create; } catch (e) { return false; } };
8,471
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/cache.ts
import createListeners, { Listeners } from './listeners'; export interface Cache<K, V> extends Pick<Listeners<[K, V | undefined], void>, 'subscribe'>, Map<K, V> { clearListeners: () => void; } /** * Wraps a map with support for subscribe/unsubscribe on changes. */ const createCache = <K, V>(map = new Map<K, V>()): Cache<K, V> => { const listeners = createListeners<[K, V | undefined], void>(); return { get size() { return map.size; }, forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any) { return map.forEach(callbackfn, thisArg); }, has: (key: K) => map.has(key), get: (key: K) => map.get(key), entries: () => map.entries(), keys: () => map.keys(), values: () => map.values(), [Symbol.iterator]: () => map[Symbol.iterator](), get [Symbol.toStringTag]() { return map[Symbol.toStringTag]; }, clear: () => map.clear(), delete: (key: K) => { const r = map.delete(key); listeners.notify(key, undefined); return r; }, set(key: K, value: V) { map.set(key, value); listeners.notify(key, value); return this; }, subscribe: listeners.subscribe, clearListeners: listeners.clear, }; }; export default createCache;
8,472
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/checkout.ts
import { c, msgid } from 'ttag'; import { get2FAAuthenticatorText, getDevicesText, getLoginsAndNotesText, getUnlimitedHideMyEmailAliasesText, } from '@proton/components/containers/payments/features/pass'; import { getVpnConnections, getVpnServers } from '@proton/shared/lib/vpn/features'; import { ADDON_NAMES, CALENDAR_SHORT_APP_NAME, CYCLE, DEFAULT_CYCLE, DRIVE_SHORT_APP_NAME, FAMILY_MAX_USERS, MAIL_SHORT_APP_NAME, MEMBER_ADDON_PREFIX, PLANS, PLAN_TYPES, VPN_SHORT_APP_NAME, } from '../constants'; import { Plan, PlanIDs, PlansMap, Pricing, Subscription, SubscriptionCheckResponse, VPNServersCountData, getPlanMaxIPs, } from '../interfaces'; import { FREE_PLAN } from '../subscription/freePlans'; import humanSize from './humanSize'; import { getPlanFromCheckout } from './planIDs'; import { INCLUDED_IP_PRICING, customCycles, getPricingPerMember } from './subscription'; export const getDiscountText = () => { return c('Info') .t`Price includes all applicable cycle-based discounts and non-expired coupons saved to your account.`; }; export const getUserTitle = (users: number) => { return c('Checkout row').ngettext(msgid`${users} user`, `${users} users`, users); }; const getAddonQuantity = (addon: Plan, quantity: number) => { if (addon.Name.startsWith('1domain')) { return quantity * (addon.MaxDomains || 0); } if (addon.Name.startsWith(MEMBER_ADDON_PREFIX)) { return quantity * (addon.MaxMembers || 0); } if (addon.Name.startsWith('1ip')) { return quantity * getPlanMaxIPs(addon); } return 0; }; export const getAddonTitle = (addonName: ADDON_NAMES, quantity: number) => { if (addonName.startsWith('1domain')) { const domains = quantity; return c('Addon').ngettext(msgid`${domains} custom domain`, `${domains} custom domains`, domains); } if (addonName.startsWith(MEMBER_ADDON_PREFIX)) { const users = quantity; return c('Addon').ngettext(msgid`${users} user`, `${users} users`, users); } if (addonName.startsWith('1ip')) { const ips = quantity; return c('Addon').ngettext(msgid`${ips} server`, `${ips} servers`, ips); } return ''; }; export interface AddonDescription { name: ADDON_NAMES; title: string; quantity: number; pricing: Pricing; } export interface SubscriptionCheckoutData { couponDiscount: number | undefined; planName: PLANS | null; planTitle: string; usersTitle: string; users: number; addons: AddonDescription[]; withDiscountPerCycle: number; withoutDiscountPerMonth: number; withDiscountPerMonth: number; membersPerMonth: number; addonsPerMonth: number; discountPerCycle: number; discountPercent: number; } export type RequiredCheckResponse = Pick< SubscriptionCheckResponse, 'Amount' | 'AmountDue' | 'Cycle' | 'CouponDiscount' | 'Proration' | 'Credit' | 'Coupon' | 'Gift' >; export const getUsersAndAddons = (planIDs: PlanIDs, plansMap: PlansMap) => { const plan = getPlanFromCheckout(planIDs, plansMap); let users = plan?.MaxMembers || 1; const usersPricing = plan ? getPricingPerMember(plan) : null; const memberAddonsNumber = Object.entries(planIDs).reduce((acc, [planName, quantity]) => { const planOrAddon = plansMap[planName as keyof typeof plansMap]; if (planOrAddon?.Type === PLAN_TYPES.ADDON && planOrAddon.Name.startsWith(MEMBER_ADDON_PREFIX)) { acc += quantity; } return acc; }, 0); users += memberAddonsNumber; const addonsMap = Object.entries(planIDs).reduce<{ [addonName: string]: AddonDescription; }>((acc, [planName, quantity]) => { const planOrAddon = plansMap[planName as keyof typeof plansMap]; if (planOrAddon?.Type !== PLAN_TYPES.ADDON || planOrAddon.Name.startsWith(MEMBER_ADDON_PREFIX)) { return acc; } const name = planOrAddon.Name as ADDON_NAMES; const title = getAddonTitle(name, quantity); acc[name] = { name, title, quantity: getAddonQuantity(planOrAddon, quantity), pricing: planOrAddon.Pricing, }; return acc; }, {}); // VPN Business plan includes 1 IP by default. Each addons adds +1 IP. // So if users has business plan but doesn't have IP addons, then they still must have 1 IP for price // calculation purposes. if (plan?.Name === PLANS.VPN_BUSINESS) { const { IP_VPN_BUSINESS: IP } = ADDON_NAMES; const addon = addonsMap[IP]; if (addon) { addon.quantity += 1; } else { addonsMap[IP] = { name: IP, quantity: 1, pricing: plansMap[IP]?.Pricing ?? INCLUDED_IP_PRICING, title: '', }; } addonsMap[IP].title = getAddonTitle(IP, addonsMap[IP].quantity); } const addons: AddonDescription[] = Object.values(addonsMap); const planName = (plan?.Name as PLANS) ?? null; const planTitle = plan?.Title ?? ''; return { planName, planTitle, users, usersPricing, addons, }; }; export const getCheckout = ({ planIDs, plansMap, checkResult, }: { planIDs: PlanIDs; plansMap: PlansMap; checkResult?: RequiredCheckResponse; }): SubscriptionCheckoutData => { const usersAndAddons = getUsersAndAddons(planIDs, plansMap); const amount = checkResult?.Amount || 0; const cycle = checkResult?.Cycle || CYCLE.MONTHLY; const couponDiscount = Math.abs(checkResult?.CouponDiscount || 0); const withDiscountPerCycle = amount - couponDiscount; const withoutDiscountPerMonth = Object.entries(planIDs).reduce((acc, [planName, quantity]) => { const plan = plansMap[planName as keyof typeof plansMap]; const defaultMonthly = plan?.DefaultPricing?.[CYCLE.MONTHLY] ?? 0; const monthly = plan?.Pricing?.[CYCLE.MONTHLY] ?? 0; // Offers might affect Pricing both ways, increase and decrease. // So if the Pricing increases, then we don't want to use the lower DefaultPricing as basis // for discount calculations const price = Math.max(monthly, defaultMonthly); return acc + price * quantity; }, 0); const withoutDiscountPerCycle = withoutDiscountPerMonth * cycle; const withoutDiscountPerNormalCycle = withoutDiscountPerMonth * cycle; const discountPerCycle = Math.min(withoutDiscountPerCycle - withDiscountPerCycle, withoutDiscountPerCycle); const discountPerNormalCycle = Math.min( withoutDiscountPerNormalCycle - withDiscountPerCycle, withoutDiscountPerNormalCycle ); const discountPercent = withoutDiscountPerNormalCycle > 0 ? Math.round(100 * (discountPerNormalCycle / withoutDiscountPerNormalCycle)) : 0; const addonsPerMonth = usersAndAddons.addons.reduce((acc, { quantity, pricing }) => { return acc + ((pricing[cycle] || 0) * quantity) / cycle; }, 0); const membersPerCycle = usersAndAddons.usersPricing?.[cycle] ?? null; const membersPerMonth = membersPerCycle !== null ? (membersPerCycle / cycle) * usersAndAddons.users : amount / cycle - addonsPerMonth; return { couponDiscount: checkResult?.CouponDiscount, planName: usersAndAddons.planName, planTitle: usersAndAddons.planTitle, addons: usersAndAddons.addons, usersTitle: getUserTitle(usersAndAddons.users || 1), // VPN and free plan has no users users: usersAndAddons.users || 1, withoutDiscountPerMonth, withDiscountPerCycle, withDiscountPerMonth: withDiscountPerCycle / cycle, membersPerMonth, addonsPerMonth, discountPerCycle, discountPercent, }; }; export type Included = | { type: 'text'; text: string; } | { type: 'value'; text: string; value: string | number; }; export const getPremiumPasswordManagerText = () => { return c('bf2023: Deal details').t`Premium Password Manager`; }; export const getWhatsIncluded = ({ planIDs, plansMap, vpnServers, }: { planIDs: PlanIDs; plansMap: PlansMap; vpnServers: VPNServersCountData; }): Included[] => { const vpnPassBundle = planIDs[PLANS.VPN_PASS_BUNDLE]; if (vpnPassBundle) { return [ { type: 'text', text: c('bf2023: Deal details').t`Premium ${VPN_SHORT_APP_NAME}`, }, { type: 'text', text: getPremiumPasswordManagerText(), }, ]; } const unlimited = planIDs[PLANS.BUNDLE]; const unlimitedPlan = plansMap[PLANS.BUNDLE]; if (unlimited && unlimitedPlan) { const storage = humanSize(unlimitedPlan.MaxSpace, undefined, undefined, 0); return [ { type: 'text', text: storage, }, { type: 'text', text: c('bf2023: Deal details').t`Premium ${MAIL_SHORT_APP_NAME} & ${CALENDAR_SHORT_APP_NAME}`, }, { type: 'text', text: c('bf2023: Deal details').t`Premium ${VPN_SHORT_APP_NAME}`, }, { type: 'text', text: c('bf2023: Deal details').t`Premium ${DRIVE_SHORT_APP_NAME}`, }, { type: 'text', text: getPremiumPasswordManagerText(), }, ]; } const vpn = planIDs[PLANS.VPN]; if (vpn !== undefined && vpn > 0) { return [ { type: 'text', text: getVpnServers(vpnServers.paid.servers), }, { type: 'text', text: c('specialoffer: Deal details').t`Highest VPN speed`, }, { type: 'text', text: c('specialoffer: Deal details').t`Secure streaming`, }, { type: 'text', text: getVpnConnections(10), }, ]; } const passPremium = planIDs[PLANS.PASS_PLUS]; if (passPremium !== undefined && passPremium > 0) { return [ { type: 'text', text: getLoginsAndNotesText(), }, { type: 'text', text: getDevicesText(), }, { type: 'text', text: getUnlimitedHideMyEmailAliasesText(), }, { type: 'text', text: get2FAAuthenticatorText(), }, ]; } const summary = Object.entries(planIDs).reduce( (acc, [planNameValue, quantity]) => { const planName = planNameValue as keyof PlansMap; const plan = plansMap[planName]; if (!plan || !quantity || quantity <= 0) { return acc; } acc.addresses += plan.MaxAddresses * quantity; acc.domains += plan.MaxDomains * quantity; acc.space += plan.MaxSpace * quantity; acc.vpn += plan.MaxVPN * quantity; return acc; }, { space: 0, addresses: 0, domains: 0, vpn: 0 } ); const family = planIDs[PLANS.FAMILY]; if (family !== undefined && family > 0) { const storage = humanSize(summary.space || FREE_PLAN.MaxSpace, undefined, undefined, 0); return [ { type: 'text', text: c('Info').t`Up to ${FAMILY_MAX_USERS} users`, }, { type: 'text', text: c('Info').t`${storage} storage`, }, { type: 'text', text: c('bf2023: Deal details').t`Premium ${MAIL_SHORT_APP_NAME} & ${CALENDAR_SHORT_APP_NAME}`, }, { type: 'text', text: c('bf2023: Deal details').t`Premium ${VPN_SHORT_APP_NAME}`, }, { type: 'text', text: c('bf2023: Deal details').t`Premium ${DRIVE_SHORT_APP_NAME}`, }, { type: 'text', text: getPremiumPasswordManagerText(), }, ]; } return [ { type: 'value', text: c('Info').t`Total storage`, value: humanSize(summary.space || FREE_PLAN.MaxSpace, undefined, undefined, 0), }, { type: 'value', text: c('Info').t`Total email addresses`, value: summary.addresses || FREE_PLAN.MaxAddresses }, { type: 'value', text: c('Info').t`Total supported domains`, value: summary.domains || FREE_PLAN.MaxDomains }, { type: 'value', text: c('Info').t`Total VPN connections`, value: summary.vpn || FREE_PLAN.MaxVPN }, ]; }; export const getOptimisticCheckResult = ({ planIDs, plansMap, cycle, }: { cycle: CYCLE; planIDs: PlanIDs; plansMap: PlansMap; }): RequiredCheckResponse => { const { amount } = Object.entries(planIDs).reduce( (acc, [planName, quantity]) => { const plan = plansMap?.[planName as keyof typeof plansMap]; const price = plan?.Pricing?.[cycle]; if (!plan || !price) { return acc; } acc.amount += quantity * price; return acc; }, { amount: 0 } ); return { Amount: amount, AmountDue: amount, CouponDiscount: 0, Cycle: cycle, Proration: 0, Credit: 0, Coupon: null, Gift: 0, }; }; export const getCheckResultFromSubscription = ( subscription: Subscription | undefined | null ): RequiredCheckResponse => { const Amount = subscription?.Amount || 0; const Discount = subscription?.Discount || 0; const Cycle = subscription?.Cycle || DEFAULT_CYCLE; // In subscription, Amount includes discount, which is different from the check call. // Here we add them together to be like the check call. const amount = Amount + Math.abs(Discount); return { Amount: amount, AmountDue: amount, Cycle, CouponDiscount: Discount, Proration: 0, Credit: 0, Coupon: null, Gift: 0, }; }; export const getIsCustomCycle = (cycle: CYCLE) => { return customCycles.includes(cycle); };
8,473
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/contactGroups.ts
import { ContactGroup } from '../interfaces/contacts'; export const orderContactGroups = (contactGroups: ContactGroup[]) => { return [...contactGroups].sort((contactGroupA, contactGroupB) => contactGroupA.Name.localeCompare(contactGroupB.Name) ); };
8,474
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/contacts.ts
import { c } from 'ttag'; import { encodeImageUri, forgeImageURL } from '@proton/shared/lib/helpers/image'; import { isBase64Image } from '@proton/shared/lib/helpers/validators'; export const getAllFields = () => [ // translator: this field is used to specify the display name of the contact (e.g. Jane Appleseed) { text: c('Contact field label').t`Display name`, value: 'fn' }, // translator: this field is used to specify the first name of the contact (e.g. Jane) { text: c('Contact field label').t`First name`, value: 'firstName' }, // translator: this field is used to specify the last name of the contact (e.g. Appleseed) { text: c('Contact field label').t`Last name`, value: 'lastName' }, // translator: this field is used to specify the email of the contact (e.g. [email protected]) { text: c('Contact field label').t`Email`, value: 'email' }, // translator: this field is used to specify the phone number of the contact { text: c('Contact field label').t`Phone`, value: 'tel' }, // translator: this field is used to specify the address of the contact { text: c('Contact field label').t`Address`, value: 'adr' }, // translator: this field is used to add a picture for the contact { text: c('Contact field label').t`Photo`, value: 'photo' }, // translator: this field is used to specify the organization's name of the contact { text: c('Contact field label').t`Organization`, value: 'org' }, // translator: this field is used to specify the birth date of the contact { text: c('Contact field label').t`Birthday`, value: 'bday' }, // translator: this field is used to specify the anniversary date of the contact (e.g. marriage, or equivalent) { text: c('Contact field label').t`Anniversary`, value: 'anniversary' }, // translator: this field is used to specify the position or job of the contact { text: c('Contact field label').t`Title`, value: 'title' }, // translator: this field is used to specify the specific role of the contact given the type of relationship with the user { text: c('Contact field label').t`Role`, value: 'role' }, // translator: this field is used to add a note about the contact { text: c('Contact field label').t`Note`, value: 'note' }, // translator: this field is used to add a URL for the contact { text: c('Contact field label').t`URL`, value: 'url' }, // translator: this field is used to specify the gender of the contact { text: c('Contact field label').t`Gender`, value: 'gender' }, // translator: this field is used to specify the primary language of the contact { text: c('Contact field label').t`Language`, value: 'lang' }, // translator: this field is used to specify the timezone of the contact { text: c('Contact field label').t`Time zone`, value: 'tz' }, // translator: this field is used to specify geographic information about the contact (e.g. latitude + longitude) { text: c('Contact field label').t`Geo`, value: 'geo' }, // translator: this field is used to add a logo for the contact { text: c('Contact field label').t`Logo`, value: 'logo' }, // translator: this field is used to specify the group a contact would be a member of { text: c('Contact field label').t`Member`, value: 'member' }, ]; export const getEditableFields = () => [ { text: c('Contact field label').t`Name`, value: 'fn' }, { text: c('Contact field label').t`Email`, value: 'email' }, { text: c('Contact field label').t`Phone`, value: 'tel' }, { text: c('Contact field label').t`Address`, value: 'adr' }, { text: c('Contact field label').t`Photo`, value: 'photo' }, { text: c('Contact field label').t`Organization`, value: 'org' }, // translator: this field is used to specify the birth date of the contact { text: c('Contact field label').t`Birthday`, value: 'bday' }, // translator: this field is used to specify the anniversary date of the contact (e.g. marriage, or equivalent) { text: c('Contact field label').t`Anniversary`, value: 'anniversary' }, { text: c('Contact field label').t`Title`, value: 'title' }, { text: c('Contact field label').t`Role`, value: 'role' }, { text: c('Contact field label').t`Member`, value: 'member' }, { text: c('Contact field label').t`Note`, value: 'note' }, { text: c('Contact field label').t`URL`, value: 'url' }, { text: c('Contact field label').t`Gender`, value: 'gender' }, { text: c('Contact field label').t`Language`, value: 'lang' }, { text: c('Contact field label').t`Time zone`, value: 'tz' }, { text: c('Contact field label').t`Geo`, value: 'geo' }, { text: c('Contact field label').t`Logo`, value: 'logo' }, ]; export const getOtherInformationFields = () => [ { text: c('Contact field label').t`Photo`, value: 'photo' }, { text: c('Contact field label').t`Organization`, value: 'org' }, // translator: this field is used to specify the anniversary date of the contact (e.g. marriage, or equivalent) { text: c('Contact field label').t`Anniversary`, value: 'anniversary' }, { text: c('Contact field label').t`Title`, value: 'title' }, { text: c('Contact field label').t`Role`, value: 'role' }, { text: c('Contact field label').t`Member`, value: 'member' }, { text: c('Contact field label').t`URL`, value: 'url' }, { text: c('Contact field label').t`Gender`, value: 'gender' }, { text: c('Contact field label').t`Language`, value: 'lang' }, { text: c('Contact field label').t`Time zone`, value: 'tz' }, { text: c('Contact field label').t`Geo`, value: 'geo' }, { text: c('Contact field label').t`Logo`, value: 'logo' }, ]; // The first and last name fields are here since they are splitted from the N field export const getAllFieldLabels = () => ({ lastName: c('Contact field label').t`Last name`, firstName: c('Contact field label').t`First name`, n: c('Contact field label').t`Name`, fn: c('Contact field label').t`Display name`, email: c('Contact field label').t`Email`, tel: c('Contact field label').t`Phone`, adr: c('Contact field label').t`Address`, photo: c('Contact field label').t`Photo`, org: c('Contact field label').t`Organization`, // translator: this field is used to specify the birth date of the contact bday: c('Contact field label').t`Birthday`, // translator: this field is used to specify the anniversary date of the contact (e.g. marriage, or equivalent) anniversary: c('Contact field label').t`Anniversary`, title: c('Contact field label').t`Title`, role: c('Contact field label').t`Role`, note: c('Contact field label').t`Note`, url: c('Contact field label').t`URL`, gender: c('Contact field label').t`Gender`, lang: c('Contact field label').t`Language`, tz: c('Contact field label').t`Time zone`, geo: c('Contact field label').t`Geo`, logo: c('Contact field label').t`Logo`, member: c('Contact field label').t`Member`, }); export const getTypeLabels = () => ({ work: c('Contact type label').t`Work`, home: c('Contact type label').t`Personal`, cell: c('Contact type label').t`Mobile`, main: c('Contact type label').t`Main`, // translator: Yomi name is a field for entering the phonetic equivalent for Japanese names yomi: c('Contact type label').t`Yomi`, other: c('Contact type label').t`Other`, fax: c('Contact type label').t`Fax`, // translator: https://en.wikipedia.org/wiki/Pager pager: c('Contact type label').t`Pager`, }); export const getAllTypes: () => { [key: string]: { text: string; value: string }[] } = () => ({ fn: [], n: [], email: [ { text: c('Property type').t`Email`, value: '' }, { text: c('Property type').t`Home`, value: 'home' }, { text: c('Property type').t`Work`, value: 'work' }, { text: c('Property type').t`Other`, value: 'other' }, ], tel: [ { text: c('Property type').t`Phone`, value: '' }, { text: c('Property type').t`Home`, value: 'home' }, { text: c('Property type').t`Work`, value: 'work' }, { text: c('Property type').t`Other`, value: 'other' }, { text: c('Property type').t`Mobile`, value: 'cell' }, { text: c('Property type').t`Main`, value: 'main' }, { text: c('Property type').t`Fax`, value: 'fax' }, { text: c('Property type').t`Pager`, value: 'pager' }, ], adr: [ { text: c('Property type').t`Address`, value: '' }, { text: c('Property type').t`Home`, value: 'home' }, { text: c('Property type').t`Work`, value: 'work' }, { text: c('Property type').t`Other`, value: 'other' }, ], bday: [], anniversary: [], gender: [], lang: [], tz: [], geo: [], title: [], role: [], logo: [], photo: [], org: [], member: [], note: [], url: [], }); export const getTypeValues: () => { [key: string]: string[] } = () => ({ fn: [], email: ['', 'home', 'work', 'other'], tel: ['', 'home', 'work', 'other', 'cell', 'main', 'fax', 'pager'], adr: ['', 'home', 'work', 'other'], bday: [], anniversary: [], gender: [], lang: [], tz: [], geo: [], title: [], role: [], logo: [], org: [], member: [], note: [], url: [], photo: [], }); /** * Get the source of the contact image (can be contact profile image, Logo or Photo fields) * It will allow to load the image normally if a base 64 or using the Proton proxy is disabled * Else we will forge the url to load it through the Proton proxy */ export const getContactImageSource = (apiUrl: string, url: string, uid: string, useProxy: boolean) => { // If the image is not a base64 but a URL, then we want to load the image through the proxy if (!isBase64Image(url) && useProxy) { const encodedImageUrl = encodeImageUri(url); return forgeImageURL(apiUrl, encodedImageUrl, uid); } return url; };
8,475
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/cookies.ts
import isTruthy from '@proton/utils/isTruthy'; export const getCookies = (): string[] => { try { return document.cookie.split(';').map((item) => item.trim()); } catch (e: any) { return []; } }; export const getCookie = (name: string, cookies = document.cookie) => { return `; ${cookies}`.match(`;\\s*${name}=([^;]+)`)?.[1]; }; export enum CookieSameSiteAttribute { Lax = 'lax', Strict = 'strict', None = 'none', } export interface SetCookieArguments { cookieName: string; cookieValue: string | undefined; cookieDomain?: string; expirationDate?: string; path?: string; secure?: boolean; samesite?: CookieSameSiteAttribute; } export const setCookie = ({ cookieName, cookieValue: maybeCookieValue, expirationDate: maybeExpirationDate, path, cookieDomain, samesite, secure = true, }: SetCookieArguments) => { const cookieValue = maybeCookieValue === undefined ? '' : maybeCookieValue; let expirationDate = maybeExpirationDate; if (expirationDate === 'max') { /* https://en.wikipedia.org/wiki/Year_2038_problem */ expirationDate = new Date(2147483647000).toUTCString(); } expirationDate = maybeCookieValue === undefined ? new Date(0).toUTCString() : expirationDate; document.cookie = [ `${cookieName}=${cookieValue}`, expirationDate && `expires=${expirationDate}`, cookieDomain && `domain=${cookieDomain}`, path && `path=${path}`, secure && 'secure', samesite && `samesite=${samesite}`, ] .filter(isTruthy) .join(';'); }; export const deleteCookie = (cookieName: string) => { setCookie({ cookieName, cookieValue: undefined, path: '/', }); };
8,476
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/crossTab.ts
import { uint8ArrayToBase64String } from './encoding'; import { removeItem, setItem } from './storage'; export const PASSWORD_CHANGE_MESSAGE_TYPE = 'password-change'; const CROSS_TAB_EVENT_KEY = 'cte'; let id: string | undefined; const generateId = () => { return uint8ArrayToBase64String(crypto.getRandomValues(new Uint8Array(6))); }; export const sendMessageToTabs = (type: string, data: any) => { if (!id) { id = generateId(); } setItem(CROSS_TAB_EVENT_KEY, JSON.stringify({ id, type, data })); removeItem(CROSS_TAB_EVENT_KEY); }; export const getIsSelf = (otherId: string) => otherId === id; export const getMessage = (event: StorageEvent) => { if (event.key !== CROSS_TAB_EVENT_KEY || !event.newValue) { return; } try { const parsedData = JSON.parse(event.newValue); if (!parsedData?.type) { return; } return { id: parsedData.id, type: parsedData.type, data: parsedData.data, }; } catch (e: any) { return undefined; } };
8,477
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/crypto.ts
import { CryptoProxy } from '@proton/crypto'; import { arrayToBinaryString, arrayToHexString, binaryStringToArray } from '@proton/crypto/lib/utils'; import { stringToUint8Array, uint8ArrayToBase64String, uint8ArrayToString } from './encoding'; export const getSHA256String = async (data: string) => { const value = await CryptoProxy.computeHash({ algorithm: 'SHA256', data: binaryStringToArray(data) }); return arrayToHexString(value); }; export const getSHA256BinaryString = async (data: string) => { const value = await CryptoProxy.computeHash({ algorithm: 'SHA256', data: binaryStringToArray(data) }); return arrayToBinaryString(value); }; export const getSHA256Base64String = async (data: string) => { const value = await CryptoProxy.computeHash({ algorithm: 'SHA256', data: binaryStringToArray(data) }); return uint8ArrayToBase64String(value); }; export const generateRandomBytes = (numberOfBytes: number) => crypto.getRandomValues(new Uint8Array(numberOfBytes)); export const xorEncryptDecrypt = ({ key, data }: { key: string; data: string }) => { if (key.length !== data.length) { throw new Error('The length of the key and data do not match.'); } const Uint8Key = stringToUint8Array(key); const Uint8Data = stringToUint8Array(data); const xored = new Uint8Array(Uint8Data.length); for (let j = 0; j < Uint8Data.length; j++) { xored[j] = +Uint8Key[j] ^ +Uint8Data[j]; } return uint8ArrayToString(xored); };
8,478
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/desktop.ts
import UAParser from 'ua-parser-js'; import { isMac } from './browser'; const uaParser = new UAParser(); const ua = uaParser.getResult(); export const isElectronApp = () => { return /electron/i.test(ua.ua); }; export const isElectronOnMac = () => { return isElectronApp() && isMac(); };
8,479
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/desktopNotification.ts
import Push from 'push.js'; import noop from '@proton/utils/noop'; Push.config({ serviceWorker: './assets/serviceWorker.min.js', // Sets a custom service worker script }); export enum Status { DENIED = 'denied', DEFAULT = 'default', GRANTED = 'granted', } export const getStatus = (): Status => { const permission = Push.Permission.get(); switch (permission) { case Status.DENIED: return Status.DENIED; case Status.GRANTED: return Status.GRANTED; default: return Status.DEFAULT; } }; export const isEnabled = (): boolean => Push.Permission.has(); export const clear = () => Push.clear(); export const request = (onGranted: () => void = noop, onDenied: () => void = noop) => { try { Push.Permission.request(onGranted, onDenied); } catch (err: any) { onDenied(); /** * Hotfix to fix requesting the permission on non-promisified requests. * TypeError: undefined is not an object (evaluating 'this._win.Notification.requestPermission().then') * https://github.com/Nickersoft/push.js/issues/117 */ } }; /** * Create a desktop notification * @param title * @param params https://pushjs.org/docs/options */ export const create = async (title = '', params = {}) => { if (!isEnabled()) { return; } return Push.create(title, params); };
8,480
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/dom.ts
import tinycolor from 'tinycolor2'; interface ScriptInfo { path: string; integrity?: string; } interface Callback { (event?: Event, error?: string | Event): void; } const loadScriptHelper = ({ path, integrity }: ScriptInfo, cb: Callback) => { const script = document.createElement('script'); script.src = path; if (integrity) { script.integrity = integrity; } script.onload = (e) => { cb(e); script.remove(); }; script.onerror = (e) => cb(undefined, e); document.head.appendChild(script); }; export const loadScript = (path: string, integrity?: string) => { return new Promise<Event>((resolve, reject) => { loadScriptHelper({ path, integrity }, (event, error) => { if (error || !event) { return reject(error); } return resolve(event); }); }); }; /** * Returns whether the element is a node. * See {@link https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType} */ export const isElement = (node: Node | null) => node && node.nodeType === 1; /** * Returns the node if it's an element or the parent element if not */ export const getElement = (node: Node | null) => (isElement(node) ? (node as Element) : node?.parentElement || null); /** * From https://stackoverflow.com/a/42543908 */ export const getScrollParent = (element: HTMLElement | null | undefined, includeHidden = false) => { if (!element) { return document.body; } const style = getComputedStyle(element); const excludeStaticParent = style.position === 'absolute'; const overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/; if (style.position === 'fixed') { return document.body; } for (let parent = element.parentElement; parent; parent = parent.parentElement) { const style = getComputedStyle(parent); if (excludeStaticParent && style.position === 'static') { continue; } if (overflowRegex.test(style.overflow + style.overflowY + style.overflowX)) { return parent; } } return document.body; }; /** * get computed root font size, to manage properly some elements in pixels * value is dynamic */ let rootFontSizeCache: number | undefined = undefined; const getRootFontSize = () => { return parseFloat(window.getComputedStyle(document.querySelector('html') as Element).getPropertyValue('font-size')); }; export const rootFontSize = (reset?: boolean) => { if (rootFontSizeCache === undefined || reset === true) { rootFontSizeCache = getRootFontSize(); } return rootFontSizeCache; }; /** * Firefox <58 does not support block: 'nearest' and just throws */ export const scrollIntoView = (element: HTMLElement | undefined | null, extra?: boolean | ScrollIntoViewOptions) => { if (!element) { return; } try { element.scrollIntoView(extra); // eslint-disable-next-line no-empty } catch (e: any) {} }; export const hasChildren = (node?: ChildNode) => { return node && node.childNodes && node.childNodes.length > 0; }; export const getMaxDepth = (node: ChildNode) => { let maxDepth = 0; for (const child of node.childNodes) { if (hasChildren(child)) { const depth = getMaxDepth(child); if (depth > maxDepth) { maxDepth = depth; } } } return maxDepth + 1; }; export const checkContrast = (node: ChildNode, window: Window): boolean => { if (node.nodeType === Node.ELEMENT_NODE) { const style = window.getComputedStyle(node as Element); const color = style.color ? tinycolor(style.color) : tinycolor('#fff'); const background = style.backgroundColor ? tinycolor(style.backgroundColor) : tinycolor('#000'); const result = (color?.isDark() && (background?.isLight() || background?.getAlpha() === 0)) || (color?.isLight() && background?.isDark()); if (!result) { return false; } } return [...node.childNodes].every((node) => checkContrast(node, window)); }; export const getIsEventModified = (event: MouseEvent) => { return event.metaKey || event.altKey || event.ctrlKey || event.shiftKey; }; export const isVisible = (element: HTMLElement | null) => { if (!element) { return false; } const style = getComputedStyle(element); const { offsetWidth, offsetHeight } = element; const { width, height } = element.getBoundingClientRect(); if (style.display === 'none') { return false; } if (style.visibility !== 'visible') { return false; } if ((style.opacity as any) === 0) { return false; } if (offsetWidth + offsetHeight + height + width === 0) { return false; } return true; }; export const parseStringToDOM = (content: string, type: DOMParserSupportedType = 'text/html') => { const parser = new DOMParser(); return parser.parseFromString(content, type); };
8,481
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/downloadFile.ts
import saveAs from 'file-saver'; import { isFileSaverSupported } from './browser'; const downloadFile = (blob: Blob | undefined, filename: string | undefined) => { if (!isFileSaverSupported()) { throw new Error('Download requires a newer browser.'); } saveAs(blob, filename); }; export default downloadFile;
8,482
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/email.ts
/** * Validate the local part of an email string according to the RFC https://tools.ietf.org/html/rfc5321#section-4.1.2; * see also https://tools.ietf.org/html/rfc3696#page-5 and https://en.wikipedia.org/wiki/Email_address#Local-part * * NOTE: Email providers respect the RFC only loosely. We do not want to invalidate addresses that would be accepted by the BE. * It is not fully guaranteed that this helper is currently accepting everything that the BE accepts. * * Examples of RFC rules violated in the wild: * * Local parts should have a maximum length of 64 octets */ import isTruthy from '@proton/utils/isTruthy'; export enum CANONICALIZE_SCHEME { DEFAULT, PLUS, GMAIL, PROTON, } export const PROTONMAIL_DOMAINS = ['protonmail.com', 'protonmail.ch', 'pm.me', 'proton.me']; export const validateLocalPart = (localPart: string) => { // remove comments first const match = localPart.match(/(^\(.+?\))?([^()]*)(\(.+?\)$)?/); if (!match) { return false; } const uncommentedPart = match[2]; if (/^".+"$/.test(uncommentedPart)) { // case of a quoted string // The only characters non-allowed are \ and " unless preceded by a backslash const quotedText = uncommentedPart.slice(1, -1); const chunks = quotedText .split('\\"') .map((chunk) => chunk.split('\\\\')) .flat(); return !chunks.some((chunk) => /"|\\/.test(chunk)); } return !/[^a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]|^\.|\.$|\.\./.test(uncommentedPart); }; /** * Validate the domain of an email string according to the preferred name syntax of the RFC https://tools.ietf.org/html/rfc1034. * Actually almost anything is allowed as domain name https://tools.ietf.org/html/rfc2181#section-11, but we stick * to the preferred one, allowing undescores which are common in the wild. * See also https://en.wikipedia.org/wiki/Email_address#Domain */ export const validateDomain = (domain: string) => { if (domain.length > 255) { return false; } if (/\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]/.test(domain)) { return true; } const dnsLabels = domain.toLowerCase().split('.').filter(isTruthy); if (dnsLabels.length < 2) { return false; } const topLevelDomain = dnsLabels.pop() as string; if (!/^[a-z0-9]+$/.test(topLevelDomain)) { return false; } return !dnsLabels.some((label) => { return /[^a-z0-9-_]|^-|-$/.test(label); }); }; /** * Split an email into local part plus domain. */ export const getEmailParts = (email: string): [localPart: string, domain: string] => { const endIdx = email.lastIndexOf('@'); if (endIdx === -1) { return [email, '']; } return [email.slice(0, endIdx), email.slice(endIdx + 1)]; }; /** * Validate an email string according to the RFC https://tools.ietf.org/html/rfc5322; * see also https://en.wikipedia.org/wiki/Email_address */ export const validateEmailAddress = (email: string) => { const [localPart, domain] = getEmailParts(email); if (!localPart || !domain) { return false; } return validateLocalPart(localPart) && validateDomain(domain); }; export const removePlusAliasLocalPart = (localPart = '') => { const [cleanLocalPart] = localPart.split('+'); return cleanLocalPart; }; /** * Add plus alias part for an email */ export const addPlusAlias = (email = '', plus = '') => { const atIndex = email.indexOf('@'); const plusIndex = email.indexOf('+'); if (atIndex === -1 || plusIndex > -1) { return email; } const name = email.substring(0, atIndex); const domain = email.substring(atIndex, email.length); return `${name}+${plus}${domain}`; }; /** * Canonicalize an email address following one of the known schemes * Emails that have the same canonical form end up in the same inbox * See https://confluence.protontech.ch/display/MBE/Canonize+email+addresses */ export const canonicalizeEmail = (email: string, scheme = CANONICALIZE_SCHEME.DEFAULT) => { const [localPart, domain] = getEmailParts(email); const at = email[email.length - domain.length - 1] === '@' ? '@' : ''; if (scheme === CANONICALIZE_SCHEME.PROTON) { const cleanLocalPart = removePlusAliasLocalPart(localPart); const normalizedLocalPart = cleanLocalPart.replace(/[._-]/g, '').toLowerCase(); const normalizedDomain = domain.toLowerCase(); return `${normalizedLocalPart}${at}${normalizedDomain}`; } if (scheme === CANONICALIZE_SCHEME.GMAIL) { const cleanLocalPart = removePlusAliasLocalPart(localPart); const normalizedLocalPart = cleanLocalPart.replace(/[.]/g, '').toLowerCase(); const normalizedDomain = domain.toLowerCase(); return `${normalizedLocalPart}${at}${normalizedDomain}`; } if (scheme === CANONICALIZE_SCHEME.PLUS) { const cleanLocalPart = removePlusAliasLocalPart(localPart); const normalizedLocalPart = cleanLocalPart.toLowerCase(); const normalizedDomain = domain.toLowerCase(); return `${normalizedLocalPart}${at}${normalizedDomain}`; } return email.toLowerCase(); }; export const canonicalizeInternalEmail = (email: string) => canonicalizeEmail(email, CANONICALIZE_SCHEME.PROTON); /** * Canonicalize an email by guessing the scheme that should be applied * Notice that this helper will not apply the Proton scheme on custom domains; * Only the back-end knows about custom domains, but they also apply the default scheme in those cases. */ export const canonicalizeEmailByGuess = (email: string) => { const [, domain] = getEmailParts(email); const normalizedDomain = domain.toLowerCase(); if (PROTONMAIL_DOMAINS.includes(normalizedDomain)) { return canonicalizeEmail(email, CANONICALIZE_SCHEME.PROTON); } if (['gmail.com', 'googlemail.com', 'google.com'].includes(normalizedDomain)) { return canonicalizeEmail(email, CANONICALIZE_SCHEME.GMAIL); } if ( ['hotmail.com', 'hotmail.co.uk', 'hotmail.fr', 'outlook.com', 'yandex.ru', 'mail.ru'].includes(normalizedDomain) ) { return canonicalizeEmail(email, CANONICALIZE_SCHEME.PLUS); } return canonicalizeEmail(email, CANONICALIZE_SCHEME.DEFAULT); }; const extractStringItems = (str: string) => { // filter(isTruthy) wouldn't result in TS understanding that the return of this function is of type string[], so we expand it return str.split(',').filter((item) => isTruthy(item)); }; /** * Try to decode an URI string with the native decodeURI function. * Return the original string if decoding fails */ const decodeURISafe = (str: string) => { try { return decodeURI(str); } catch (e: any) { return str; } }; /** * Extract "to address" and headers from a mailto URL https://tools.ietf.org/html/rfc6068 */ export const parseMailtoURL = (mailtoURL: string, decode = true) => { const mailtoString = 'mailto:'; const toString = 'to='; if (!mailtoURL.toLowerCase().startsWith(mailtoString)) { throw new Error('Malformed mailto URL'); } const url = mailtoURL.substring(mailtoString.length); const [tos, hfields = ''] = url.split('?'); const addressTos = extractStringItems(tos).map((to) => (decode ? decodeURISafe(to) : to)); const headers = hfields.split('&').filter(isTruthy); const headerTos = headers .filter((header) => header.toLowerCase().startsWith('to=')) .map((headerTo) => extractStringItems(headerTo.substring(toString.length))) .flat() .map((to) => (decode ? decodeURISafe(to) : to)); return { to: [...addressTos, ...headerTos] }; }; export const buildMailTo = (email = '') => `mailto:${email}`; export const getEmailTo = (str: string, decode?: boolean) => { try { const { to: [emailTo = ''], } = parseMailtoURL(str, decode); return emailTo; } catch (e: any) { return str; } }; export function extractEmailFromUserID(userID: string): string | undefined { const [, email] = /<([^>]*)>/.exec(userID) || []; return email; }
8,483
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/encoding.ts
import { arrayToBinaryString, binaryStringToArray, decodeBase64, encodeBase64 } from '@proton/crypto/lib/utils'; export const uint8ArrayToString = arrayToBinaryString; export const stringToUint8Array = binaryStringToArray; export const uint8ArrayToBase64String = (array: Uint8Array) => encodeBase64(uint8ArrayToString(array)); export const base64StringToUint8Array = (string: string) => stringToUint8Array(decodeBase64(string) || ''); /** * Encode a binary string in the so-called base64 URL (https://tools.ietf.org/html/rfc4648#section-5) * @dev Each character in a binary string can only be one of the characters in a reduced 255 ASCII alphabet. I.e. morally each character is one byte * @dev This function will fail if the argument contains characters which are not in this alphabet * @dev This encoding works by converting groups of three "bytes" into groups of four base64 characters (2 ** 6 ** 4 is also three bytes) * @dev Therefore, if the argument string has a length not divisible by three, the returned string will be padded with one or two '=' characters */ export const encodeBase64URL = (str: string, removePadding = true) => { const base64String = encodeBase64(str).replace(/\+/g, '-').replace(/\//g, '_'); return removePadding ? base64String.replace(/=/g, '') : base64String; }; /** * Convert a string encoded in base64 URL into a binary string * @param str */ export const decodeBase64URL = (str: string) => { return decodeBase64((str + '==='.slice((str.length + 3) % 4)).replace(/-/g, '+').replace(/_/g, '/')); }; export const uint8ArrayToPaddedBase64URLString = (array: Uint8Array) => encodeBase64URL(uint8ArrayToString(array), false); export const validateBase64string = (str: string, useVariantAlphabet?: boolean) => { const regex = useVariantAlphabet ? /^[-_A-Za-z0-9]*={0,3}$/ : /^[+/A-Za-z0-9]*={0,3}$/; return regex.test(str); }; /** * Automatic password reset parameter encoder */ export const encodeAutomaticResetParams = (json: any) => { const jsonString = JSON.stringify(json); return encodeBase64URL(jsonString); }; /** * Automatic password reset parameter decoder */ export const decodeAutomaticResetParams = (base64String: string) => { const decodedString = decodeBase64URL(base64String); return JSON.parse(decodedString); };
8,484
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/events.ts
export const isKeyboardEvent = (event: Event): event is KeyboardEvent => { if ('key' in event) { return true; } return false; }; export const isDragEvent = (event: Event): event is DragEvent => { if ('dataTransfer' in event) { return true; } return false; }; const assignKeyboardKeys = (customEvent: CustomEvent, event: Event) => { const KEYBOARD_EVENT_RELATED_KEYS = [ 'altKey', 'charCode', 'ctrlKey', 'code', 'key', 'keyCode', 'locale', 'location', 'metaKey', 'repeat', 'shiftKey', ]; KEYBOARD_EVENT_RELATED_KEYS.forEach((key) => { // @ts-expect-error customEvent[key] = event[key]; }); }; export const cloneEvent = (event: Event) => { const clonedEvent = new CustomEvent(event.type, { bubbles: true }); if (isDragEvent(event)) { // @ts-expect-error 'dataTransfert' key is not present in customEvent interface clonedEvent.dataTransfer = event.dataTransfer; } if (isKeyboardEvent(event)) { assignKeyboardKeys(clonedEvent, event); } return clonedEvent; };
8,485
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/file.ts
import { base64StringToUint8Array, uint8ArrayToString } from './encoding'; /** * Convert file to encoded base 64 string */ export const toBase64 = async (file: Blob, isValid: (file: Blob) => boolean = () => true) => { if (file && !isValid(file)) { throw new Error('Invalid file format'); } return new Promise<string>((resolve, reject) => { const reader = new FileReader(); reader.onload = ({ target }) => { if (!target?.result) { return reject(new Error('Invalid file')); } resolve(target.result as string); }; reader.onerror = reject; reader.onabort = reject; reader.readAsDataURL(file); }); }; /** * Read the content of a blob and returns its value as a buffer */ export const readFileAsBuffer = (file: File) => { return new Promise<ArrayBuffer>((resolve, reject) => { const reader = new FileReader(); reader.onload = ({ target }) => { if (!target?.result) { return reject(new Error('Invalid file')); } resolve(target.result as ArrayBuffer); }; reader.onerror = reject; reader.onabort = reject; reader.readAsArrayBuffer(file); }); }; /** * Read the content of a blob and returns its value as a text string */ export const readFileAsString = (file: File, encoding?: string) => { return new Promise<string>((resolve, reject) => { const reader = new FileReader(); reader.onload = ({ target }) => { if (!target?.result) { return reject(new Error('Invalid file')); } resolve(target.result as string); }; reader.onerror = reject; reader.onabort = reject; reader.readAsText(file, encoding); }); }; /** * Read the content of a blob and returns its value as a binary string. * Not using readAsBinaryString because it's deprecated. */ export const readFileAsBinaryString = async (file: File) => { const arrayBuffer = await readFileAsBuffer(file); // eslint-disable-next-line new-cap return uint8ArrayToString(new Uint8Array(arrayBuffer)); }; /** * Convert a blob url to the matching blob * @link https://stackoverflow.com/a/42508185 */ export const blobURLtoBlob = (url: string) => { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'blob'; xhr.onerror = reject; xhr.onload = () => { if (xhr.status === 200) { return resolve(xhr.response); } reject(xhr); }; xhr.send(); }); }; /** * Read the base64 portion of a data url. */ export const readDataUrl = (url = '') => { const error = 'The given url is not a data url.'; if (url.substring(0, 5) !== 'data:') { throw new Error(error); } const [, base64] = url.split(','); if (!base64) { throw new Error(error); } return base64StringToUint8Array(base64); }; /** * Split a filename into [name, extension] */ export const splitExtension = (filename = '') => { const endIdx = filename.lastIndexOf('.'); if (endIdx === -1) { return [filename, '']; } return [filename.slice(0, endIdx), filename.slice(endIdx + 1)]; };
8,486
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/filters.ts
import { Filter } from '@proton/components/containers/filters/interfaces'; import { FILTER_STATUS, FREE_USER_ACTIVE_FILTERS_LIMIT } from '@proton/shared/lib/constants'; import { UserModel } from '@proton/shared/lib/interfaces'; export const hasReachedFiltersLimit = (user: UserModel, userFilters: Filter[]) => { const { hasPaidMail } = user; const enabledFilters = userFilters.filter((filter) => filter.Status === FILTER_STATUS.ENABLED); return !hasPaidMail && enabledFilters.length >= FREE_USER_ACTIVE_FILTERS_LIMIT; };
8,487
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/folder.ts
import { Label, UserModel } from '@proton/shared/lib/interfaces'; import orderBy from '@proton/utils/orderBy'; import range from '@proton/utils/range'; import { FREE_USER_FOLDERS_LIMIT, FREE_USER_LABELS_LIMIT, ROOT_FOLDER } from '../constants'; import { Folder, FolderWithSubFolders } from '../interfaces/Folder'; export const order = (folders: Folder[] = []) => orderBy(folders, 'Order'); export const getParents = (folders: Folder[] = []) => { return folders.reduce<{ [key: string]: Folder[] }>((acc, item) => { const { ParentID = ROOT_FOLDER } = item; acc[ParentID] = acc[ParentID] || []; acc[ParentID].push(item); return acc; }, {}); }; export const buildTreeview = (folders: FolderWithSubFolders[] = []) => { const parents = getParents(folders); const build = (parentID: string | number = ROOT_FOLDER): FolderWithSubFolders[] => { if (!Array.isArray(parents[parentID])) { return []; } return order(parents[parentID]).map((item) => ({ ...item, subfolders: build(item.ID), })); }; return build(); }; export const formatFolderName = (time = 0, name = '', separator = ' ') => `${range(0, time) .map(() => separator) .join('')}${name}`; export const hasReachedFolderLimit = (user: UserModel, userFolders: Folder[]) => { const { hasPaidMail } = user; return !hasPaidMail && userFolders.length >= FREE_USER_FOLDERS_LIMIT; }; export const hasReachedLabelLimit = (user: UserModel, userLabels: Label[]) => { const { hasPaidMail } = user; return !hasPaidMail && userLabels.length >= FREE_USER_LABELS_LIMIT; };
8,488
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/formValidators.ts
import { c, msgid } from 'ttag'; import { validateEmailAddress } from './email'; import { REGEX_USERNAME, REGEX_USERNAME_END, REGEX_USERNAME_START, isNumber } from './validators'; export const requiredValidator = (value: any) => value === undefined || value === null || value?.trim?.() === '' ? c('Error').t`This field is required` : ''; export const usernameCharacterValidator = (value: string) => !REGEX_USERNAME.test(value) ? c('Error').t`Try using only letters, numerals, and _.-` : ''; export const usernameStartCharacterValidator = (value: string) => !REGEX_USERNAME_START.test(value) ? c('Error').t`Username must begin with a letter or digit` : ''; export const usernameEndCharacterValidator = (value: string) => !REGEX_USERNAME_END.test(value) ? c('Error').t`Username must end with a letter or digit` : ''; const defaultUsernameLength = 40; export const usernameLengthValidator = (value: string, n = defaultUsernameLength) => value.length > defaultUsernameLength ? c('Validation').ngettext( msgid`Try a shorter username (${n} character max)`, `Try a shorter username (${n} characters max)`, n ) : ''; export const minLengthValidator = (value: string, minimumLength: number) => value.length < minimumLength ? c('Error').t`This field requires a minimum of ${minimumLength} characters.` : ''; export const maxLengthValidator = (value: string, maximumLength: number) => value.length > maximumLength ? c('Error').t`This field exceeds the maximum of ${maximumLength} characters.` : ''; export const emailValidator = (value: string) => (!validateEmailAddress(value) ? c('Error').t`Email is not valid` : ''); export const numberValidator = (value: string) => (!isNumber(value) ? c('Error').t`Not a valid number` : ''); export const confirmPasswordValidator = (a: string, b: string) => (a !== b ? c('Error').t`Passwords do not match` : ''); export const confirmEmailValidator = (a: string, b: string) => a !== b ? c('Error').t`The email addresses do not match` : ''; export const usernameValidator = (a: string, b: string) => (a !== b ? c('Error').t`Incorrect username` : ''); export const defaultMinPasswordLength = 8; export const getMinPasswordLengthMessage = (length = defaultMinPasswordLength) => c('Validation').ngettext( msgid`Password must contain at least ${length} character`, `Password must contain at least ${length} characters`, length ); export const passwordLengthValidator = (a: string, length = defaultMinPasswordLength) => a.length < length ? getMinPasswordLengthMessage() : '';
8,489
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/generateUID.ts
let current = 0; const generateUID = (prefix?: string) => `${prefix || 'id'}-${current++}`; export default generateUID;
8,490
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/getUsername.ts
import { Address, User, UserType } from '../interfaces'; import { getIsAddressEnabled } from './address'; export default function getUsername(user: User, addresses: Address[]) { const primaryAddress = addresses?.find(getIsAddressEnabled); return user.Type === UserType.EXTERNAL && primaryAddress ? primaryAddress.Email : user.Name; }
8,491
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/humanPrice.ts
import { Currency } from '../interfaces'; /** * Make amount readable * 600 -> 6, 650 -> 6.50, 633 -> 6.33 */ const humanPrice = (amount: number = 0, divisor: number = 100) => { const fixedValue = Number(amount / divisor).toFixed(2); return fixedValue.replace('.00', '').replace('-', ''); }; export default humanPrice; export const humanPriceWithCurrency = (amount: number, currency: Currency, divisor?: number) => { if (typeof amount !== 'number' || typeof currency !== 'string') { throw new Error('humanPriceWithCurrency: Invalid parameters'); } const value = humanPrice(amount, divisor); const isNegative = amount < 0; const prefix = isNegative ? '-' : ''; if (currency === 'EUR') { return `${prefix}${value} €`; } if (currency === 'CHF') { return `${prefix}CHF ${value}`; } if (currency === 'USD') { return `${prefix}$${value}`; } return `${prefix}${value}`; };
8,492
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/humanSize.ts
import { c, msgid } from 'ttag'; import { BASE_SIZE } from '../constants'; export const sizeUnits = { B: 1, KB: BASE_SIZE, MB: BASE_SIZE * BASE_SIZE, GB: BASE_SIZE * BASE_SIZE * BASE_SIZE, TB: BASE_SIZE * BASE_SIZE * BASE_SIZE * BASE_SIZE, }; export type SizeUnits = keyof typeof sizeUnits; export const getSizeFormat = (key: SizeUnits, n: number) => { if (key === 'B') { return c('file size format').ngettext(msgid`byte`, `bytes`, n); } if (key === 'KB') { return c('file size format').t`KB`; } if (key === 'MB') { return c('file size format').t`MB`; } if (key === 'GB') { return c('file size format').t`GB`; } if (key === 'TB') { return c('file size format').t`TB`; } throw new Error('Unknown unit'); }; export const getLongSizeFormat = (key: SizeUnits, n: number) => { if (key === 'B') { return c('file size format, long').ngettext(msgid`Byte`, `Bytes`, n); } if (key === 'KB') { return c('file size format, long').ngettext(msgid`Kilobyte`, `Kilobytes`, n); } if (key === 'MB') { return c('file size format, long').ngettext(msgid`Megabyte`, `Megabytes`, n); } if (key === 'GB') { return c('file size format, long').ngettext(msgid`Gigabyte`, `Gigabytes`, n); } if (key === 'TB') { return c('file size format, long').ngettext(msgid`Terabyte`, `Terabytes`, n); } throw new Error('Unknown unit'); }; export const getUnit = (bytes: number): SizeUnits => { if (bytes < sizeUnits.KB) { return 'B'; } if (bytes < sizeUnits.MB) { return 'KB'; } if (bytes < sizeUnits.GB) { return 'MB'; } return 'GB'; }; const transformTo = (bytes: number, unit: SizeUnits, withoutUnit: boolean, fractionDigits = 2) => { const value = (bytes / sizeUnits[unit]).toFixed(fractionDigits); const suffix = withoutUnit ? '' : ` ${getSizeFormat(unit, Number(value))}`; return value + suffix; }; const humanSize = (bytes = 0, forceUnit?: SizeUnits, withoutUnit = false, maybeFractionDigits?: number) => { const unit = forceUnit || getUnit(bytes); const fractionDigits = maybeFractionDigits === undefined && unit === 'B' ? 0 : maybeFractionDigits; return transformTo(bytes, unit, withoutUnit, fractionDigits); }; export default humanSize; /** * shortHumanSize makes the compact size version. That is, it rounds it to * zero or one kilobyte for size smaller than one kilobyte, and it drops * the fractional part for sizes smaller than gigabyte--only for bigger files * it shows one fractional digit. Examples: * * 12 bytes -> 0 KB * 567 bytes -> 1 KB * 12.34 MB -> 12 MB * 12.34 GB -> 12.3 GB */ export const shortHumanSize = (bytes = 0) => { if (bytes < sizeUnits.KB) { return humanSize(bytes, 'KB', false, 0); } if (bytes < sizeUnits.GB) { return humanSize(bytes, undefined, false, 0); } return humanSize(bytes, undefined, false, 1); }; /** * Produces always readable version in bytes. Useful for titles where we * might want to display the exact size. */ export const bytesSize = (bytes = 0) => { return `${bytes} ${getSizeFormat('B', bytes)}`; };
8,493
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/image.ts
import { getImage } from '../api/images'; import { REGEX_IMAGE_EXTENSION } from '../constants'; import { createUrl } from '../fetch/helpers'; import { toBase64 } from './file'; /** * Use to encode Image URI when loading images */ export const encodeImageUri = (url: string) => { // Only replace spaces for the moment return url.trim().replaceAll(' ', '%20'); }; /** * Forge a url to load an image through the Proton proxy */ export const forgeImageURL = (apiUrl: string, url: string, uid: string) => { const config = getImage(url, 0, uid); const prefixedUrl = `${apiUrl}/${config.url}`; // api/ is required to set the AUTH cookie const urlToLoad = createUrl(prefixedUrl, config.params); return urlToLoad.toString(); }; /** * Convert url to Image */ export const toImage = (url: string, crossOrigin = true): Promise<HTMLImageElement> => { return new Promise((resolve, reject) => { if (!url) { return reject(new Error('url required')); } const image = new Image(); image.onload = () => { resolve(image); }; image.onerror = reject; /** * allow external images to be used in a canvas as if they were loaded * from the current origin without sending any user credentials. * (otherwise canvas.toDataURL in resizeImage will throw complaining that the canvas is tainted) * An error will be thrown if the requested resource hasn't specified an appropriate CORS policy * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image * * However, on contact side, we are now using the proxy to load images. * If the user choose explicitly not to use it or load the image using its default URL because loading through proxy failed, * we consider that he really wants to load the image. * Removing the crossOrigin attribute will allow us to load the image on more cases. */ if (crossOrigin) { image.crossOrigin = 'anonymous'; } image.referrerPolicy = 'no-referrer'; image.src = url; }); }; interface ResizeImageProps { /** * Base64 representation of image to be resized. */ original: string; /** * Maximum amount of pixels for the width of the resized image. */ maxWidth?: number; /** * Maximum amount of pixels for the height of the resized image. */ maxHeight?: number; /** * Mime type of the resulting resized image. */ finalMimeType?: string; /** * A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. */ encoderOptions?: number; /** * If both maxHeight and maxWidth are specified, pick the smaller resize factor. */ bigResize?: boolean; /** * Does the image needs to be loaded with the crossOrigin attribute */ crossOrigin?: boolean; } /** * Resizes a picture to a maximum height/width (preserving height/width ratio). When both dimensions are specified, * two resizes are possible: we pick the one with the bigger resize factor (so that both max dimensions are respected in the resized image) * @dev If maxWidth or maxHeight are equal to zero, the corresponding dimension is ignored */ export const resizeImage = async ({ original, maxWidth = 0, maxHeight = 0, finalMimeType = 'image/jpeg', encoderOptions = 1, bigResize = false, crossOrigin = true, }: ResizeImageProps) => { const image = await toImage(original, crossOrigin); // Resize the image let { width, height } = image; const canvas = document.createElement('canvas'); const [widthRatio, heightRatio] = [maxWidth && width / maxWidth, maxHeight && height / maxHeight].map(Number); if (widthRatio <= 1 && heightRatio <= 1) { return image.src; } const invert = maxWidth && maxHeight && bigResize; if (widthRatio >= heightRatio === !invert) { height /= widthRatio; width = maxWidth; } else { width /= heightRatio; height = maxHeight; } canvas.width = width; canvas.height = height; // eslint-disable-next-line no-unused-expressions canvas.getContext('2d')?.drawImage(image, 0, 0, width, height); return canvas.toDataURL(finalMimeType, encoderOptions); }; /** * Extract the mime and base64 str from a base64 image. */ const extractBase64Image = (str = '') => { const [mimeInfo = '', base64 = ''] = (str || '').split(','); const [, mime = ''] = mimeInfo.match(/:(.*?);/) || []; return { mime, base64 }; }; /** * Convert a base 64 str to an uint8 array. */ const toUint8Array = (base64str: string) => { const bstr = atob(base64str); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return u8arr; }; /** * Convert a data URL to a Blob Object */ export const toFile = (base64str: string, filename = 'file') => { const { base64, mime } = extractBase64Image(base64str); return new File([toUint8Array(base64)], filename, { type: mime }); }; /** * Convert a data URL to a Blob Object */ export const toBlob = (base64str: string) => { const { base64, mime } = extractBase64Image(base64str); return new Blob([toUint8Array(base64)], { type: mime }); }; /** * Down size image to reach the max size limit */ export const downSize = async (base64str: string, maxSize: number, mimeType = 'image/jpeg', encoderOptions = 1) => { const process = async (source: string, maxWidth: number, maxHeight: number): Promise<string> => { const resized = await resizeImage({ original: source, maxWidth, maxHeight, finalMimeType: mimeType, encoderOptions, }); const { size } = new Blob([resized]); if (size <= maxSize) { return resized; } return process(resized, Math.round(maxWidth * 0.9), Math.round(maxHeight * 0.9)); }; const { height, width } = await toImage(base64str); return process(base64str, width, height); }; /** * Returns true if the URL is an inline embedded image. */ export const isInlineEmbedded = (src = '') => src.startsWith('data:'); /** * Returns true if the URL is an embedded image. */ export const isEmbedded = (src = '') => src.startsWith('cid:'); /** * Resize image file */ export const resize = async (fileImage: File, maxSize: number) => { const base64str = await toBase64(fileImage); return downSize(base64str, maxSize, fileImage.type); }; /** * Prepare image source to be display */ export const formatImage = (value = '') => { if ( !value || REGEX_IMAGE_EXTENSION.test(value) || value.startsWith('data:') || value.startsWith('http://') || value.startsWith('https://') ) { return value; } return `data:image/png;base64,${value}`; };
8,494
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/incomingDefaults.ts
import { INCOMING_DEFAULTS_LOCATION } from '../constants'; import { IncomingDefault } from '../interfaces'; /** * Check if an email address is inside email in incomingDefaults */ const isAddressIncluded = ( incomingDefaults: IncomingDefault[] = [], emailAddress: string, location?: INCOMING_DEFAULTS_LOCATION ): IncomingDefault | undefined => incomingDefaults.find(({ Location, Email }: IncomingDefault) => { if ((location && Location !== location) || !emailAddress) { return false; } if (Email) { return Email === emailAddress; } return false; }); export const isBlockedIncomingDefaultAddress = (incomingDefaults: IncomingDefault[], emailAddress: string): boolean => { const foundItem = isAddressIncluded(incomingDefaults, emailAddress, INCOMING_DEFAULTS_LOCATION.BLOCKED); return !!foundItem; }; export const getBlockedIncomingDefaultByAddress = ( incomingDefaults: IncomingDefault[], emailAddress: string ): IncomingDefault | undefined => { const foundItem = isAddressIncluded(incomingDefaults, emailAddress, INCOMING_DEFAULTS_LOCATION.BLOCKED); return foundItem; };
8,495
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/isDeepEqual.ts
export { default } from 'lodash/isEqual'; // Using lodash for now...
8,496
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/listeners.ts
export type Listener<A extends any[], R> = (...args: A) => R; export interface Listeners<A extends any[], R> { notify: (...args: A) => R[]; subscribe: (listener: Listener<A, R>) => () => void; clear: () => void; } const createListeners = <A extends any[], R = void>(): Listeners<A, R> => { let listeners: Listener<A, R>[] = []; const notify = (...args: A) => { return listeners.map((listener) => { return listener(...args); }); }; const subscribe = (listener: Listener<A, R>) => { listeners.push(listener); return () => { listeners.splice(listeners.indexOf(listener), 1); }; }; const clear = () => { listeners = []; }; return { notify, subscribe, clear, }; }; export default createListeners;
8,497
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/lru.ts
interface Args<K, V> { max: number; onDispose?: ([key, value]: [K, V | undefined]) => void; } function createLRU<K, V>({ max, onDispose }: Args<K, V>): Map<K, V> { const map = new Map<K, V>(); const getOldestKey = () => map.keys().next().value; return { get size() { return map.size; }, forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any) { return map.forEach(callbackfn, thisArg); }, clear: () => map.clear(), has: (key: K) => map.has(key), delete: (key: K) => map.delete(key), entries: () => map.entries(), keys: () => map.keys(), values: () => map.values(), [Symbol.iterator]: () => map[Symbol.iterator](), get [Symbol.toStringTag]() { return map[Symbol.toStringTag]; }, set: (key: K, value: V) => { if (map.has(key)) { map.delete(key); } else if (map.size === max) { const keyToDispose = getOldestKey(); const valueToDispose = map.get(keyToDispose); map.delete(keyToDispose); if (onDispose) { onDispose([keyToDispose, valueToDispose]); } } map.set(key, value); return map; }, get: (key: K) => { const item = map.get(key); if (!item) { return undefined; } map.delete(key); map.set(key, item); return item; }, }; } export default createLRU;
8,498
0
petrpan-code/ProtonMail/WebClients/packages/shared/lib
petrpan-code/ProtonMail/WebClients/packages/shared/lib/helpers/metrics.ts
import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { metrics } from '../api/metrics'; import { TelemetryReport, sendMultipleTelemetryData, sendTelemetryData } from '../api/telemetry'; import { METRICS_LOG, SECOND } from '../constants'; import { Api } from '../interfaces'; import { wait } from './promise'; // Make the metrics false by default to avoid (rare) cases where we could have sendMetricReport or sendTelemetryReport // before setting this metricsEnabled value with the user setting. // In that scenario we would send something but the user might not want this. let metricsEnabled = false; /** * Delay an operation by a random number of seconds between 1 second and the specified * number of seconds. If none is provided, the default is 180 seconds, i.e. 3 minutes */ export const randomDelay = async (delayInSeconds: number = 180) => { await wait(SECOND * Math.floor(delayInSeconds * Math.random() + 1)); }; /** * Send metrics report (/metrics endpoint) */ export const sendMetricsReport = async (api: Api, Log: METRICS_LOG, Title?: string, Data?: any) => { if (!metricsEnabled) { return; } // We delay sending the metrics report because this helper is used in some privacy-sensitive // use-cases, e.g. encrypted search, in which we don't want the server to be able to use the // metric report as a distinguisher to correlate user actions, e.g. performing an encrypted // search and fetching an email shortly after await randomDelay(); void api(metrics({ Log, Title, Data })); }; interface SendTelemetryReportArgs extends TelemetryReport { api: Api; silence?: boolean; } /** * Send a telemetry report (/data/v1/stats endpoint) */ export const sendTelemetryReport = async ({ api, measurementGroup, event, values, dimensions, silence = true, }: SendTelemetryReportArgs) => { const possiblySilentApi = silence ? getSilentApi(api) : api; if (!metricsEnabled) { return; } try { void (await possiblySilentApi( sendTelemetryData({ MeasurementGroup: measurementGroup, Event: event, Values: values, Dimensions: dimensions, }) )); } catch { // fail silently } }; interface SendMultipleTelemetryReportsArgs { api: Api; reports: TelemetryReport[]; silence?: boolean; } /** * Send multiple telemetry reports (/data/v1/stats/multiple endpoint) */ export const sendMultipleTelemetryReports = async ({ api, reports, silence = true, }: SendMultipleTelemetryReportsArgs) => { const possiblySilentApi = silence ? getSilentApi(api) : api; if (!metricsEnabled) { return; } try { void (await possiblySilentApi(sendMultipleTelemetryData({ reports }))); } catch { // fail silently } }; export const setMetricsEnabled = (enabled: boolean) => { metricsEnabled = enabled; };
8,499