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 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/createSecureSessionStorage.ts | import { load, save } from '../helpers/secureSessionStorage';
import createStore from '../helpers/store';
const createSecureSessionStorage = () => {
const store = createStore(load());
if ('onpagehide' in window) {
const handlePageShow = () => {
// This does not need to do anything. The main purpose is just to reset window.name and sessionStorage to fix the Safari 13.1 described below
load();
};
const handlePageHide = () => {
// Cannot use !event.persisted because Safari 13.1 does not send that when you are navigating on the same domain
save(store.getState());
};
window.addEventListener('pageshow', handlePageShow, true);
window.addEventListener('pagehide', handlePageHide, true);
} else {
const handleUnload = () => {
save(store.getState());
};
// This gets narrowed to never because of the onpagehide
// @ts-ignore
window.addEventListener('unload', handleUnload, true);
}
return store;
};
export type SecureSessionStorage = ReturnType<typeof createSecureSessionStorage>;
export default createSecureSessionStorage;
| 8,300 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/cryptoHelper.ts | import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays';
const IV_LENGTH = 16;
export const ENCRYPTION_ALGORITHM = 'AES-GCM';
export const getKey = (key: Uint8Array, keyUsage: KeyUsage[] = ['decrypt', 'encrypt']) => {
return crypto.subtle.importKey('raw', key.buffer, ENCRYPTION_ALGORITHM, false, keyUsage);
};
export const encryptData = async (key: CryptoKey, data: Uint8Array) => {
const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
const cipher = await crypto.subtle.encrypt(
{
name: ENCRYPTION_ALGORITHM,
iv,
},
key,
data
);
return mergeUint8Arrays([iv, new Uint8Array(cipher)]);
};
export const decryptData = async (key: CryptoKey, data: Uint8Array) => {
const iv = data.slice(0, IV_LENGTH);
const cipher = data.slice(IV_LENGTH, data.length);
const result = await crypto.subtle.decrypt({ name: ENCRYPTION_ALGORITHM, iv }, key, cipher);
return new Uint8Array(result);
};
| 8,301 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/error.ts | // eslint-disable-next-line max-classes-per-file
export class InvalidPersistentSessionError extends Error {
constructor(message?: string) {
super(['Invalid persistent session', message].filter(Boolean).join(':'));
Object.setPrototypeOf(this, InvalidPersistentSessionError.prototype);
}
}
export class InvalidForkProduceError extends Error {
constructor(message?: string) {
super(['Invalid fork production', message].filter(Boolean).join(':'));
Object.setPrototypeOf(this, InvalidForkProduceError.prototype);
}
}
export class InvalidForkConsumeError extends Error {
constructor(message?: string) {
super(['Invalid fork consumption', message].filter(Boolean).join(':'));
Object.setPrototypeOf(this, InvalidForkConsumeError.prototype);
}
}
| 8,302 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/interface.ts | import { AuthenticationCredentialsPayload, AuthenticationOptions, RegisteredKey } from '../webauthn/interface';
export interface Fido2Response {
AuthenticationOptions: AuthenticationOptions;
RegisteredKeys: RegisteredKey[];
}
export type Fido2Data = AuthenticationCredentialsPayload;
export interface TwoFaResponse {
Enabled: number;
FIDO2: Fido2Response | null;
TOTP: number;
}
export interface AuthResponse {
AccessToken: string;
ExpiresIn: number;
TokenType: string;
Scope: string;
UID: string;
UserID: string;
RefreshToken: string;
EventID: string;
TemporaryPassword: 0 | 1;
PasswordMode: number;
LocalID: number;
TwoFactor: number;
'2FA': TwoFaResponse;
}
export interface PushForkResponse {
Selector: string;
}
export interface PullForkResponse {
Payload: string;
LocalID: number;
UID: string;
AccessToken: string;
RefreshToken: string;
ExpiresIn: number;
TokenType: string;
UserID: string;
}
export interface RefreshSessionResponse {
AccessToken: string;
ExpiresIn: number;
TokenType: string;
Scope: string;
UID: string;
RefreshToken: string;
}
export interface LocalSessionResponse {
Username?: string;
DisplayName: string;
LocalID: number;
UserID: string;
PrimaryEmail?: string;
}
export type AuthVersion = 0 | 1 | 2 | 3 | 4;
export interface ChallengePayload {
[key: string]: string;
}
export interface InfoResponse {
Modulus: string;
ServerEphemeral: string;
Version: AuthVersion;
Salt: string;
SRPSession: string;
}
export interface SSOInfoResponse {
SSOChallengeToken: string;
}
export interface InfoAuthedResponse extends InfoResponse {
'2FA': TwoFaResponse;
}
export interface ModulusResponse {
Modulus: string;
ModulusID: string;
}
export interface LocalKeyResponse {
ClientKey: string;
}
export interface MemberAuthResponse {
UID: string;
LocalID: number;
}
| 8,303 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/loginWithFallback.ts | import { getAuthVersionWithFallback } from '@proton/srp';
import { PASSWORD_WRONG_ERROR, auth, getInfo } from '../api/auth';
import { Api } from '../interfaces';
import { srpAuth } from '../srp';
import { AuthResponse, AuthVersion, ChallengePayload, InfoResponse } from './interface';
/**
* Provides authentication with fallback behavior in case the user's auth version is unknown.
*/
interface Arguments {
api: Api;
credentials: { username: string; password: string };
initialAuthInfo?: InfoResponse;
payload?: ChallengePayload;
persistent: boolean;
}
const loginWithFallback = async ({ api, credentials, initialAuthInfo, payload, persistent }: Arguments) => {
let state: { authInfo?: InfoResponse; lastAuthVersion?: AuthVersion } = {
authInfo: initialAuthInfo,
lastAuthVersion: undefined,
};
const { username } = credentials;
const data = { Username: username, Payload: payload };
do {
const { authInfo = await api<InfoResponse>(getInfo(username)), lastAuthVersion } = state;
const { version, done } = getAuthVersionWithFallback(authInfo, username, lastAuthVersion);
try {
// If it's not the last fallback attempt, suppress the wrong password notification from the API.
const suppress = done ? undefined : { suppress: [PASSWORD_WRONG_ERROR] };
const srpConfig = {
...auth(data, persistent),
...suppress,
};
const result = await srpAuth({
api,
credentials,
config: srpConfig,
info: authInfo,
version,
}).then((response): Promise<AuthResponse> => response.json());
return {
authVersion: version,
result,
};
} catch (e: any) {
if (e.data && e.data.Code === PASSWORD_WRONG_ERROR && !done) {
state = {
lastAuthVersion: version,
};
continue; // eslint-disable-line
}
throw e;
}
} while (true); // eslint-disable-line
};
export default loginWithFallback;
| 8,304 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/logout.ts | import { getAppHref } from '@proton/shared/lib/apps/helper';
import { PersistedSession } from '@proton/shared/lib/authentication/SessionInterface';
import { APPS } from '@proton/shared/lib/constants';
import { decodeBase64URL, encodeBase64URL } from '@proton/shared/lib/helpers/encoding';
interface PassedSession {
id: string;
s: boolean;
}
export const serializeLogoutURL = (
persistedSessions: PersistedSession[],
clearDeviceRecoveryData: boolean | undefined
) => {
const url = new URL(getAppHref(`/switch`, APPS.PROTONACCOUNT));
url.searchParams.set('flow', 'logout');
if (clearDeviceRecoveryData) {
url.searchParams.set('clear-recovery', JSON.stringify(clearDeviceRecoveryData));
}
const hashParams = new URLSearchParams();
const sessions = persistedSessions.map((persistedSession): PassedSession => {
return {
id: persistedSession.UserID,
s: persistedSession.isSubUser,
};
});
hashParams.set('sessions', encodeBase64URL(JSON.stringify(sessions)));
url.hash = hashParams.toString();
return url;
};
const parseSessions = (sessions: string | null) => {
try {
const result = JSON.parse(decodeBase64URL(sessions || ''));
if (Array.isArray(result)) {
return result.map((session): PassedSession => {
return {
id: session.id,
s: session.s === true,
};
});
}
return [];
} catch (e) {
return [];
}
};
export const parseLogoutURL = (url: URL) => {
const searchParams = new URLSearchParams(url.search);
const hashParams = new URLSearchParams(url.hash.slice(1));
const sessions = parseSessions(hashParams.get('sessions'));
return {
flow: searchParams.get('flow'),
clearDeviceRecoveryData: searchParams.get('clear-recovery') === 'true',
sessions,
};
};
| 8,305 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/memberLogin.js | /**
* Opens a window to login to a non-private member.
* @param {String} UID
* @param {String} mailboxPassword - The admin mailbox password
* @param {String} url - Absolute URL path
* @param {Number} [timeout]
* @return {Promise}
*/
export default ({ UID, mailboxPassword, url: urlString, timeout = 20000 }) => {
return new Promise((resolve, reject) => {
const url = new URL(urlString);
const child = window.open(`${url}`, '_blank');
const receive = ({ origin, data, source }) => {
if (origin !== url.origin || source !== child) {
return;
}
if (data === 'ready') {
child.postMessage({ UID, mailboxPassword }, url.origin);
window.removeEventListener('message', receive);
resolve();
}
};
window.addEventListener('message', receive, false);
setTimeout(() => {
window.removeEventListener('message', receive);
reject();
}, timeout);
});
};
| 8,306 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/mutate.ts | import type { AuthenticationStore } from '@proton/shared/lib/authentication/createAuthenticationStore';
import { persistSessionWithPassword } from '@proton/shared/lib/authentication/persistedSessionHelper';
import { isSSOMode } from '@proton/shared/lib/constants';
import { PASSWORD_CHANGE_MESSAGE_TYPE, sendMessageToTabs } from '@proton/shared/lib/helpers/crossTab';
import { Api, User } from '@proton/shared/lib/interfaces';
import { isSubUser } from '@proton/shared/lib/user/helpers';
const mutatePassword = async ({
authentication,
keyPassword,
User,
api,
}: {
authentication: AuthenticationStore;
keyPassword: string;
api: Api;
User: User;
}) => {
// Don't mutate the password when signed in as sub-user
if (isSubUser(User)) {
return;
}
const localID = authentication.getLocalID?.();
if (!isSSOMode || localID === undefined) {
authentication.setPassword(keyPassword);
return;
}
try {
authentication.setPassword(keyPassword);
await persistSessionWithPassword({
api,
keyPassword,
User,
UID: authentication.getUID(),
LocalID: localID,
persistent: authentication.getPersistent(),
trusted: authentication.getTrusted(),
});
sendMessageToTabs(PASSWORD_CHANGE_MESSAGE_TYPE, { localID, status: true });
} catch (e: any) {
sendMessageToTabs(PASSWORD_CHANGE_MESSAGE_TYPE, { localID, status: false });
// If persisting the password fails for some reason.
throw e;
}
};
export default mutatePassword;
| 8,307 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/pathnameHelper.ts | import { PUBLIC_PATH } from '../constants';
import { stripLeadingAndTrailingSlash } from '../helpers/string';
import { getValidatedLocalID } from './sessionForkValidation';
export const getLocalIDPath = (u?: number) => (u === undefined ? undefined : `u/${u}`);
export const getLocalIDFromPathname = (pathname: string) => {
const maybeLocalID = pathname.match(/^\/?u\/(\d{0,6})\/?/);
return getValidatedLocalID(maybeLocalID?.[1]);
};
export const getBasename = (localID?: number) => {
const publicPathBase = stripLeadingAndTrailingSlash(PUBLIC_PATH);
if (localID === undefined) {
return publicPathBase ? `/${publicPathBase}` : undefined;
}
const localIDPathBase = getLocalIDPath(localID);
const joined = [publicPathBase, localIDPathBase].filter(Boolean).join('/');
return joined ? `/${joined}` : undefined;
};
export const stripLocalBasenameFromPathname = (pathname: string) => {
const localID = getLocalIDFromPathname(pathname);
const basename = getBasename(localID);
if (basename) {
return pathname.slice(basename.length);
}
return pathname;
};
| 8,308 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/persistedSessionHelper.ts | import { updateVersionCookie, versionCookieAtLoad } from '@proton/components/hooks/useEarlyAccess';
import { PersistedSessionWithLocalID } from '@proton/shared/lib/authentication/SessionInterface';
import { getIsIframe } from '@proton/shared/lib/helpers/browser';
import { captureMessage } from '@proton/shared/lib/helpers/sentry';
import isTruthy from '@proton/utils/isTruthy';
import noop from '@proton/utils/noop';
import { getLocalKey, getLocalSessions, revoke, setLocalKey } from '../api/auth';
import { getIs401Error } from '../api/helpers/apiErrorHelper';
import { InactiveSessionError } from '../api/helpers/withApiHandlers';
import { getUser } from '../api/user';
import { getAppFromPathnameSafe } from '../apps/slugHelper';
import { SECOND, isSSOMode } from '../constants';
import { getIsAuthorizedApp, getIsDrawerPostMessage, postMessageFromIframe } from '../drawer/helpers';
import { DRAWER_EVENTS } from '../drawer/interfaces';
import { withUIDHeaders } from '../fetch/headers';
import { base64StringToUint8Array, uint8ArrayToBase64String } from '../helpers/encoding';
import { Api, User as tsUser } from '../interfaces';
import { getKey } from './cryptoHelper';
import { InvalidPersistentSessionError } from './error';
import { LocalKeyResponse, LocalSessionResponse } from './interface';
import {
getDecryptedPersistedSessionBlob,
getPersistedSession,
getPersistedSessions,
removePersistedSession,
setPersistedSessionWithBlob,
} from './persistedSessionStorage';
export type ResumedSessionResult = {
UID: string;
LocalID: number;
keyPassword?: string;
User: tsUser;
persistent: boolean;
trusted: boolean;
};
export const logRemoval = (e: any = {}, UID: string, context: string) => {
if (e.status === 401) {
return;
}
captureMessage(`Removing session due to `, {
extra: {
reason: `${e.name} - ${e.message} - ${e.status || 0}`,
UID,
context,
},
});
};
const handleDrawerApp = (localID: number) => {
let timeout: ReturnType<typeof setTimeout> | undefined;
let resolve: (arg: undefined | ResumedSessionResult) => void = () => {};
const promise = new Promise<undefined | ResumedSessionResult>((res) => {
resolve = res;
});
const isIframe = getIsIframe();
const parentApp = getAppFromPathnameSafe(window.location.pathname);
const handler = (event: MessageEvent) => {
if (!getIsDrawerPostMessage(event)) {
return;
}
if (event.data.type === DRAWER_EVENTS.SESSION) {
const { UID, keyPassword, User, persistent, trusted, tag } = event.data.payload;
window.removeEventListener('message', handler);
if (timeout) {
clearTimeout(timeout);
}
// When opening the drawer, we might need to set the tag of the app we are opening
// Otherwise we will not open the correct version of the app (default instead of beta or alpha)
if (tag && versionCookieAtLoad !== tag) {
updateVersionCookie(tag, undefined);
window.location.reload();
}
resolve({ UID, keyPassword, User, persistent, trusted, LocalID: localID });
}
};
if (parentApp && getIsAuthorizedApp(parentApp) && isIframe) {
postMessageFromIframe({ type: DRAWER_EVENTS.READY }, parentApp);
window.addEventListener('message', handler);
// Resolve the promise if the parent app does not respond
timeout = setTimeout(() => {
resolve(undefined);
}, SECOND);
} else {
resolve(undefined);
}
return promise;
};
export const resumeSession = async (api: Api, localID: number): Promise<ResumedSessionResult> => {
const res = await handleDrawerApp(localID);
// If we got a res, it means that we are in a drawer app. We don't need to make the whole resumeSession part
if (res) {
return res;
}
const persistedSession = getPersistedSession(localID);
if (!persistedSession) {
throw new InvalidPersistentSessionError('Missing persisted session or UID');
}
const {
UID: persistedUID,
UserID: persistedUserID,
blob: persistedSessionBlobString,
persistent,
trusted,
} = persistedSession;
// User with password
if (persistedSessionBlobString) {
try {
const [ClientKey, persistedUser] = await Promise.all([
api<LocalKeyResponse>(withUIDHeaders(persistedUID, getLocalKey())).then(({ ClientKey }) => ClientKey),
api<{ User: tsUser }>(withUIDHeaders(persistedUID, getUser())).then(({ User }) => User),
]);
const rawKey = base64StringToUint8Array(ClientKey);
const key = await getKey(rawKey);
const { keyPassword } = await getDecryptedPersistedSessionBlob(key, persistedSessionBlobString);
if (persistedUserID !== persistedUser.ID) {
throw InactiveSessionError();
}
return { UID: persistedUID, LocalID: localID, keyPassword, User: persistedUser, persistent, trusted };
} catch (e: any) {
if (getIs401Error(e)) {
logRemoval(e, persistedUID, 'resume 401');
await api(withUIDHeaders(persistedUID, revoke())).catch(noop);
removePersistedSession(localID, persistedUID);
throw new InvalidPersistentSessionError('Session invalid');
}
if (e instanceof InvalidPersistentSessionError) {
logRemoval(e, persistedUID, 'invalid blob');
await api(withUIDHeaders(persistedUID, revoke())).catch(noop);
removePersistedSession(localID, persistedUID);
throw e;
}
throw e;
}
}
try {
// User without password
const { User } = await api<{ User: tsUser }>(withUIDHeaders(persistedUID, getUser()));
if (persistedUserID !== User.ID) {
throw InactiveSessionError();
}
return { UID: persistedUID, LocalID: localID, User, persistent, trusted };
} catch (e: any) {
if (getIs401Error(e)) {
logRemoval(e, persistedUID, 'resume 401 - 2');
await api(withUIDHeaders(persistedUID, revoke())).catch(noop);
removePersistedSession(localID, persistedUID);
throw new InvalidPersistentSessionError('Session invalid');
}
throw e;
}
};
interface PersistSessionWithPasswordArgs {
api: Api;
keyPassword: string;
User: tsUser;
UID: string;
LocalID: number;
persistent: boolean;
trusted: boolean;
}
export const persistSessionWithPassword = async ({
api,
keyPassword,
User,
UID,
LocalID,
persistent,
trusted,
}: PersistSessionWithPasswordArgs) => {
const rawKey = crypto.getRandomValues(new Uint8Array(32));
const key = await getKey(rawKey);
const base64StringKey = uint8ArrayToBase64String(rawKey);
await api<LocalKeyResponse>(setLocalKey(base64StringKey));
await setPersistedSessionWithBlob(LocalID, key, {
UID,
UserID: User.ID,
keyPassword,
isSubUser: !!User.OrganizationPrivateKey,
persistent,
trusted,
});
};
interface PersistLoginArgs {
api: Api;
User: tsUser;
keyPassword?: string;
persistent: boolean;
trusted: boolean;
AccessToken: string;
RefreshToken: string;
UID: string;
LocalID: number;
}
export const persistSession = async ({
api,
keyPassword,
User,
UID,
LocalID,
persistent,
trusted,
}: PersistLoginArgs) => {
if (isSSOMode) {
await persistSessionWithPassword({
api,
UID,
User,
LocalID,
keyPassword: keyPassword || '',
persistent,
trusted,
});
}
};
export const getActiveSessionByUserID = (UserID: string, isSubUser: boolean) => {
return getPersistedSessions().find((persistedSession) => {
const isSameUserID = persistedSession.UserID === UserID;
const isSameSubUser = persistedSession.isSubUser === isSubUser;
return isSameUserID && isSameSubUser;
});
};
export interface LocalSessionPersisted {
remote: LocalSessionResponse;
persisted: PersistedSessionWithLocalID;
}
const getNonExistingSessions = async (
api: Api,
persistedSessions: PersistedSessionWithLocalID[],
localSessions: LocalSessionPersisted[]
): Promise<LocalSessionPersisted[]> => {
const localSessionsSet = new Set(
localSessions.map((localSessionPersisted) => localSessionPersisted.persisted.localID)
);
const nonExistingSessions = persistedSessions.filter((persistedSession) => {
return !localSessionsSet.has(persistedSession.localID);
}, []);
if (!nonExistingSessions.length) {
return [];
}
const result = await Promise.all(
nonExistingSessions.map(async (persistedSession) => {
const result = await api<{ User: tsUser }>(withUIDHeaders(persistedSession.UID, getUser())).catch((e) => {
if (getIs401Error(e)) {
logRemoval(e, persistedSession.UID, 'non-existing-sessions');
removePersistedSession(persistedSession.localID, persistedSession.UID);
}
});
if (!result?.User) {
return undefined;
}
const User = result.User;
const remoteSession: LocalSessionResponse = {
Username: User.Name,
DisplayName: User.DisplayName,
PrimaryEmail: User.Email,
UserID: User.ID,
LocalID: persistedSession.localID,
};
return {
remote: remoteSession,
persisted: persistedSession,
};
})
);
return result.filter(isTruthy);
};
export type GetActiveSessionsResult = { session?: ResumedSessionResult; sessions: LocalSessionPersisted[] };
export const getActiveSessions = async (api: Api): Promise<GetActiveSessionsResult> => {
const persistedSessions = getPersistedSessions();
const persistedSessionsMap = Object.fromEntries(
persistedSessions.map((persistedSession) => [persistedSession.localID, persistedSession])
);
for (const persistedSession of persistedSessions) {
try {
const validatedSession = await resumeSession(api, persistedSession.localID);
const { Sessions = [] } = await api<{
Sessions: LocalSessionResponse[];
}>(withUIDHeaders(validatedSession.UID, getLocalSessions()));
// The returned sessions have to exist in localstorage to be able to activate
const maybeActiveSessions = Sessions.map((remoteSession) => {
return {
persisted: persistedSessionsMap[remoteSession.LocalID],
remote: remoteSession,
};
}).filter((value): value is LocalSessionPersisted => !!value.persisted);
const nonExistingSessions = await getNonExistingSessions(api, persistedSessions, maybeActiveSessions);
if (nonExistingSessions.length) {
captureMessage('Unexpected non-existing sessions', {
extra: {
length: nonExistingSessions.length,
ids: nonExistingSessions.map((session) => ({
id: `${session.remote.Username || session.remote.PrimaryEmail || session.remote.UserID}`,
lid: session.remote.LocalID,
})),
},
});
}
return {
session: validatedSession,
sessions: [...maybeActiveSessions, ...nonExistingSessions],
};
} catch (e: any) {
if (e instanceof InvalidPersistentSessionError || getIs401Error(e)) {
// Session expired, try another session
continue;
}
// If a network error, throw here to show the error screen
throw e;
}
}
return {
session: undefined,
sessions: [],
};
};
export const maybeResumeSessionByUser = async (
api: Api,
User: tsUser,
isSubUser: boolean = !!User.OrganizationPrivateKey
) => {
const maybePersistedSession = getActiveSessionByUserID(User.ID, isSubUser);
if (!maybePersistedSession) {
return;
}
try {
return await resumeSession(api, maybePersistedSession.localID);
} catch (e: any) {
if (!(e instanceof InvalidPersistentSessionError)) {
throw e;
}
}
};
| 8,309 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/persistedSessionStorage.ts | import isTruthy from '@proton/utils/isTruthy';
import { removeLastRefreshDate } from '../api/helpers/refreshStorage';
import { getItem, removeItem, setItem } from '../helpers/storage';
import { PersistedSession, PersistedSessionBlob, PersistedSessionWithLocalID } from './SessionInterface';
import { InvalidPersistentSessionError } from './error';
import { getDecryptedBlob, getEncryptedBlob } from './sessionBlobCryptoHelper';
import { getValidatedLocalID } from './sessionForkValidation';
const STORAGE_PREFIX = 'ps-';
const getKey = (localID: number) => `${STORAGE_PREFIX}${localID}`;
export const getPersistedSession = (localID: number): PersistedSession | undefined => {
const itemValue = getItem(getKey(localID));
if (!itemValue) {
return;
}
try {
const parsedValue = JSON.parse(itemValue);
return {
UserID: parsedValue.UserID || '',
UID: parsedValue.UID || '',
blob: parsedValue.blob || '',
isSubUser: parsedValue.isSubUser || false,
persistent: typeof parsedValue.persistent === 'boolean' ? parsedValue.persistent : true, // Default to true (old behavior)
trusted: parsedValue.trusted || false,
};
} catch (e: any) {
return undefined;
}
};
export const removePersistedSession = (localID: number, UID: string) => {
const oldSession = getPersistedSession(localID);
if (oldSession?.UID) {
removeLastRefreshDate(oldSession.UID);
}
if (oldSession?.UID && UID !== oldSession.UID) {
return;
}
removeItem(getKey(localID));
};
export const getPersistedSessions = (): PersistedSessionWithLocalID[] => {
const localStorageKeys = Object.keys(localStorage);
return localStorageKeys
.filter((key) => key.startsWith(STORAGE_PREFIX))
.map((key) => {
const localID = getValidatedLocalID(key.slice(STORAGE_PREFIX.length));
if (localID === undefined) {
return;
}
const result = getPersistedSession(localID);
if (!result) {
return;
}
return {
...result,
localID,
};
})
.filter(isTruthy);
};
export const getPersistedSessionBlob = (blob: string): PersistedSessionBlob | undefined => {
try {
const parsedValue = JSON.parse(blob);
return {
keyPassword: parsedValue.keyPassword || '',
};
} catch (e: any) {
return undefined;
}
};
export const getDecryptedPersistedSessionBlob = async (
key: CryptoKey,
persistedSessionBlobString: string
): Promise<PersistedSessionBlob> => {
const blob = await getDecryptedBlob(key, persistedSessionBlobString).catch(() => {
throw new InvalidPersistentSessionError('Failed to decrypt persisted blob');
});
const persistedSessionBlob = getPersistedSessionBlob(blob);
if (!persistedSessionBlob) {
throw new InvalidPersistentSessionError('Failed to parse persisted blob');
}
return persistedSessionBlob;
};
export const setPersistedSessionWithBlob = async (
localID: number,
key: CryptoKey,
data: {
UserID: string;
UID: string;
keyPassword: string;
isSubUser: boolean;
persistent: boolean;
trusted: boolean;
}
) => {
const persistedSession: PersistedSession = {
UserID: data.UserID,
UID: data.UID,
isSubUser: data.isSubUser,
blob: await getEncryptedBlob(key, JSON.stringify({ keyPassword: data.keyPassword })),
persistent: data.persistent,
trusted: data.trusted,
};
setItem(getKey(localID), JSON.stringify(persistedSession));
};
| 8,310 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/sessionBlobCryptoHelper.ts | import {
base64StringToUint8Array,
stringToUint8Array,
uint8ArrayToBase64String,
uint8ArrayToString,
} from '../helpers/encoding';
import { decryptData, encryptData } from './cryptoHelper';
export const getEncryptedBlob = async (key: CryptoKey, data: string) => {
const result = await encryptData(key, stringToUint8Array(data));
return uint8ArrayToBase64String(result);
};
export const getDecryptedBlob = async (key: CryptoKey, blob: string) => {
const result = await decryptData(key, base64StringToUint8Array(blob));
return uint8ArrayToString(result);
};
| 8,311 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/sessionForkBlob.ts | import { getDecryptedBlob, getEncryptedBlob } from './sessionBlobCryptoHelper';
interface ForkEncryptedBlob {
keyPassword: string;
}
export const getForkEncryptedBlob = async (key: CryptoKey, data: ForkEncryptedBlob) => {
return getEncryptedBlob(key, JSON.stringify(data));
};
export const getForkDecryptedBlob = async (key: CryptoKey, data: string): Promise<ForkEncryptedBlob | undefined> => {
const string = await getDecryptedBlob(key, data);
const parsedValue = JSON.parse(string);
return {
keyPassword: parsedValue.keyPassword || '',
};
};
| 8,312 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/sessionForkValidation.ts | import { APP_NAMES, FORKABLE_APPS } from '../constants';
import { decodeBase64URL, stringToUint8Array } from '../helpers/encoding';
import { FORK_TYPE } from './ForkInterface';
export const getValidatedApp = (app = ''): APP_NAMES | undefined => {
if (FORKABLE_APPS.has(app as any)) {
return app as APP_NAMES;
}
};
export const getValidatedLocalID = (localID = '') => {
if (!localID) {
return;
}
const maybeLocalID = parseInt(localID, 10);
if (Number.isInteger(maybeLocalID) && maybeLocalID >= 0 && maybeLocalID <= 100000000) {
return maybeLocalID;
}
};
export const getValidatedRawKey = (str: string) => {
try {
return stringToUint8Array(decodeBase64URL(str));
} catch (e: any) {
return undefined;
}
};
export const getValidatedForkType = (str: string) => {
if (Object.values(FORK_TYPE).includes(str as FORK_TYPE)) {
return str as FORK_TYPE;
}
};
| 8,313 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/sessionForking.ts | import { getPathFromLocation } from '@proton/shared/lib/helpers/url';
import getRandomString from '@proton/utils/getRandomString';
import noop from '@proton/utils/noop';
import { pullForkSession, pushForkSession, revoke, setCookies } from '../api/auth';
import { OAuthForkResponse, postOAuthFork } from '../api/oauth';
import { getUser } from '../api/user';
import { getAppHref, getClientID } from '../apps/helper';
import { ExtensionMessageResponse, sendExtensionMessage } from '../browser/extension';
import { APPS, APP_NAMES, SSO_PATHS } from '../constants';
import { withAuthHeaders, withUIDHeaders } from '../fetch/headers';
import { replaceUrl } from '../helpers/browser';
import { encodeBase64URL, uint8ArrayToString } from '../helpers/encoding';
import { Api, User as tsUser } from '../interfaces';
import { Extension, FORK_TYPE } from './ForkInterface';
import { getKey } from './cryptoHelper';
import { InvalidForkConsumeError, InvalidPersistentSessionError } from './error';
import { PullForkResponse, PushForkResponse } from './interface';
import { persistSession, resumeSession } from './persistedSessionHelper';
import { getForkDecryptedBlob, getForkEncryptedBlob } from './sessionForkBlob';
import {
getValidatedApp,
getValidatedForkType,
getValidatedLocalID,
getValidatedRawKey,
} from './sessionForkValidation';
interface ExtensionForkPayload {
selector: string;
keyPassword: string | undefined;
persistent: boolean;
trusted: boolean;
state: string;
}
export type ExtensionForkResultPayload = {
title?: string;
message: string;
};
export type ExtensionForkResult = ExtensionMessageResponse<ExtensionForkResultPayload>;
export type ExtensionForkMessage = { type: 'fork'; payload: ExtensionForkPayload };
export type ExtensionAuthenticatedMessage = { type: 'auth-ext' };
export const produceExtensionFork = async ({
extension,
payload,
}: {
extension: Extension;
payload: ExtensionForkPayload;
}): Promise<ExtensionForkResult> =>
sendExtensionMessage<ExtensionForkMessage, ExtensionForkResultPayload>(
{ type: 'fork', payload },
{
extensionId: extension.ID,
onFallbackMessage: (evt) =>
evt.data.fork === 'success' /* support legacy VPN fallback message */
? {
type: 'success',
payload: evt.data.payload,
}
: undefined,
}
);
interface ForkState {
url: string;
}
export const requestFork = (fromApp: APP_NAMES, localID?: number, type?: FORK_TYPE) => {
const state = encodeBase64URL(uint8ArrayToString(crypto.getRandomValues(new Uint8Array(32))));
const searchParams = new URLSearchParams();
searchParams.append('app', fromApp);
searchParams.append('state', state);
if (localID !== undefined) {
searchParams.append('u', `${localID}`);
}
if (type !== undefined) {
searchParams.append('t', type);
}
const url = type === FORK_TYPE.SWITCH ? getAppHref('/', fromApp) : window.location.href;
const forkStateData: ForkState = { url };
sessionStorage.setItem(`f${state}`, JSON.stringify(forkStateData));
return replaceUrl(getAppHref(`${SSO_PATHS.AUTHORIZE}?${searchParams.toString()}`, APPS.PROTONACCOUNT));
};
export interface OAuthProduceForkParameters {
clientID: string;
oaSession: string;
}
interface ProduceOAuthForkArguments extends OAuthProduceForkParameters {
api: Api;
UID: string;
}
export const produceOAuthFork = async ({ api, UID, oaSession, clientID }: ProduceOAuthForkArguments) => {
const {
Data: { RedirectUri },
} = await api<{ Data: OAuthForkResponse }>(
withUIDHeaders(
UID,
postOAuthFork({
ClientID: clientID,
OaSession: oaSession,
})
)
);
return replaceUrl(RedirectUri);
};
export interface ProduceForkParameters {
state: string;
app: APP_NAMES;
type?: FORK_TYPE;
plan?: string;
independent: boolean;
}
export interface ProduceForkParametersFull extends ProduceForkParameters {
localID: number;
}
export const getProduceForkParameters = (): Partial<ProduceForkParametersFull> &
Required<Pick<ProduceForkParametersFull, 'independent'>> => {
const searchParams = new URLSearchParams(window.location.search);
const app = searchParams.get('app') || '';
const state = searchParams.get('state') || '';
const localID = searchParams.get('u') || '';
const type = searchParams.get('t') || '';
const plan = searchParams.get('plan') || '';
const independent = searchParams.get('independent') || '0';
return {
state: state.slice(0, 100),
localID: getValidatedLocalID(localID),
app: getValidatedApp(app),
type: getValidatedForkType(type),
plan,
independent: independent === '1' || independent === 'true',
};
};
interface ProduceForkArguments {
api: Api;
UID: string;
keyPassword?: string;
app: APP_NAMES;
state: string;
persistent: boolean;
trusted: boolean;
type?: FORK_TYPE;
independent: boolean;
}
export const produceFork = async ({
api,
UID,
keyPassword,
state,
app,
type,
persistent,
trusted,
independent,
}: ProduceForkArguments) => {
const rawKey = crypto.getRandomValues(new Uint8Array(32));
const base64StringKey = encodeBase64URL(uint8ArrayToString(rawKey));
const payload = keyPassword ? await getForkEncryptedBlob(await getKey(rawKey), { keyPassword }) : undefined;
const childClientID = getClientID(app);
const { Selector } = await api<PushForkResponse>(
withUIDHeaders(
UID,
pushForkSession({
Payload: payload,
ChildClientID: childClientID,
Independent: independent ? 1 : 0,
})
)
);
const toConsumeParams = new URLSearchParams();
toConsumeParams.append('selector', Selector);
toConsumeParams.append('state', state);
toConsumeParams.append('sk', base64StringKey);
if (persistent) {
toConsumeParams.append('p', '1');
}
if (trusted) {
toConsumeParams.append('tr', '1');
}
if (type !== undefined) {
toConsumeParams.append('t', type);
}
return replaceUrl(getAppHref(`${SSO_PATHS.FORK}#${toConsumeParams.toString()}`, app));
};
const getForkStateData = (data?: string | null): ForkState | undefined => {
if (!data) {
return undefined;
}
try {
const { url } = JSON.parse(data);
return {
url,
};
} catch (e: any) {
return undefined;
}
};
export const getConsumeForkParameters = () => {
const hashParams = new URLSearchParams(window.location.hash.slice(1));
const selector = hashParams.get('selector') || '';
const state = hashParams.get('state') || '';
const base64StringKey = hashParams.get('sk') || '';
const type = hashParams.get('t') || '';
const persistent = hashParams.get('p') || '';
const trusted = hashParams.get('tr') || '';
return {
state: state.slice(0, 100),
selector,
key: base64StringKey.length ? getValidatedRawKey(base64StringKey) : undefined,
type: getValidatedForkType(type),
persistent: persistent === '1',
trusted: trusted === '1',
};
};
export const removeHashParameters = () => {
window.location.hash = '';
};
interface ConsumeForkArguments {
api: Api;
selector: string;
state: string;
key: Uint8Array;
persistent: boolean;
trusted: boolean;
}
export const consumeFork = async ({ selector, api, state, key, persistent, trusted }: ConsumeForkArguments) => {
const stateData = getForkStateData(sessionStorage.getItem(`f${state}`));
if (!stateData) {
throw new InvalidForkConsumeError(`Missing state ${state}`);
}
const { url: previousUrl } = stateData;
if (!previousUrl) {
throw new InvalidForkConsumeError('Missing url');
}
const url = new URL(previousUrl);
const path = getPathFromLocation(url);
const { UID, AccessToken, RefreshToken, Payload, LocalID } = await api<PullForkResponse>(pullForkSession(selector));
const authApi = <T>(config: any) => api<T>(withAuthHeaders(UID, AccessToken, config));
try {
// Resume and use old session if it exists
const validatedSession = await resumeSession(api, LocalID);
// Revoke the discarded forked session
await authApi(revoke({ Child: 1 })).catch(noop);
return {
...validatedSession,
path,
} as const;
} catch (e: any) {
// If existing session is invalid. Fall through to continue using the new fork.
if (!(e instanceof InvalidPersistentSessionError)) {
throw e;
}
}
let keyPassword: string | undefined;
if (Payload) {
try {
const data = await getForkDecryptedBlob(await getKey(key), Payload);
keyPassword = data?.keyPassword;
} catch (e: any) {
throw new InvalidForkConsumeError('Failed to decrypt payload');
}
}
const User = await authApi<{ User: tsUser }>(getUser()).then(({ User }) => User);
const result = {
User,
UID,
LocalID,
keyPassword,
persistent,
trusted,
AccessToken,
RefreshToken,
};
await persistSession({ api: authApi, ...result });
await authApi(setCookies({ UID, RefreshToken, State: getRandomString(24), Persistent: persistent }));
return {
...result,
path,
} as const;
};
| 8,314 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authlog/AuthLog.ts | export enum AUTH_LOG_EVENTS {
LOGIN_FAILURE_PASSWORD = 0,
LOGIN_SUCCESS,
LOGOUT,
LOGIN_FAILURE_2FA,
LOGIN_SUCCESS_AWAIT_2FA,
LOGIN_SUCCESS_FORBIDDEN,
LOGIN_SUCCESS_MNEMONIC,
LOGIN_FAILURE_MNEMONIC,
LOGIN_SUCCESS_ADMIN,
LOGIN_BLOCKED,
LOGIN_SUCCESS_AWAIT_VERIFY = 80,
LOGIN_ATTEMPT,
REAUTH_FAILURE_PASSWORD = 10,
REAUTH_FAILURE_2FA,
REAUTH_SUCCESS,
CHANGE_ACCOUNT_PASSWORD = 20,
CHANGE_MAILBOX_PASSWORD,
RESET_ACCOUNT,
CHANGE_MNEMONIC,
RESET_ACCOUNT_MNEMONIC,
CHANGE_EMAIL,
CHANGE_PHONE,
ENABLE_HIGH_SECURITY,
DISABLE_HIGH_SECURITY,
ENABLE_MAILBOX_PASSWORD = 30,
DISABLE_MAILBOX_PASSWORD,
ENABLE_TOTP,
DISABLE_TOTP,
ADD_U2F,
REMOVE_U2F,
DISABLE_MNEMONIC,
RESET_BACKUP_SECRET,
USER_KEY_CREATION = 40,
USER_KEY_DELETION,
USER_KEY_REACTIVATION,
ADDRESS_KEY_CREATION = 50,
ADDRESS_KEY_DELETION,
ADDRESS_KEY_REACTIVATION,
ENABLE_EMAIL_RECOVERY = 60,
ENABLE_PHONE_RECOVERY,
DISABLE_EMAIL_RECOVERY,
DISABLE_PHONE_RECOVERY,
REVOKE_ALL_SESSIONS = 70,
REVOKE_SINGLE_SESSION,
}
export enum AuthLogStatus {
Success = 'success',
Attempt = 'attempt',
Failure = 'failure',
}
export enum ProtectionType {
BLOCKED = 1,
CAPTCHA = 2,
OWNERSHIP_VERIFICATION = 3,
DEVICE_VERIFICATION = 4,
/**
* AuthLog action was protected by anti-abuse systems
* and was evaluated as safe.
*/
OK = 5,
}
export interface AuthLog {
AppVersion: string | null;
Description: string;
Device: string;
Event: AUTH_LOG_EVENTS;
IP: string;
InternetProvider: string | null;
Location: string | null;
ProtectionDesc: string | null;
Protection: ProtectionType | null;
Status: AuthLogStatus;
Time: number;
}
| 8,315 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authlog/index.ts | export * from './AuthLog';
| 8,316 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/broadcast/broadcast.ts | const getClient = () => {
const {
navigator: { standalone, userAgent },
} = window as any;
const lowercaseUserAgent = userAgent.toLowerCase();
const safari = /safari/.test(lowercaseUserAgent);
const ios = /iphone|ipod|ipad/.test(lowercaseUserAgent);
if (ios) {
if (!standalone && safari) {
// browser
} else if (standalone && !safari) {
// standalone
} else if (!standalone && !safari) {
// uiwebview
return 'ios';
}
}
if (typeof (window as any).AndroidInterface !== 'undefined') {
return 'android';
}
if ((window as any).chrome && (window as any).chrome.webview) {
return 'webview';
}
return 'web';
};
const broadcast = <T>(message: T) => {
const client = getClient();
const serialized = JSON.stringify(message);
switch (client) {
case 'ios': {
(window as any).webkit.messageHandlers.iOS.postMessage(serialized);
break;
}
case 'android': {
(window as any).AndroidInterface.dispatch(serialized);
break;
}
case 'webview': {
// This is an embedded chrome browser. It uses different message passing mechanism.
// (window as any).chrome.webview.postMessage(message);
break;
}
case 'web': {
window.parent.postMessage(serialized, '*');
break;
}
default:
}
};
export default broadcast;
| 8,317 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/broadcast/helper.ts | import { getApiError, getApiErrorMessage } from '../api/helpers/apiErrorHelper';
import { GenericErrorPayload } from './interface';
export const getGenericErrorPayload = (e: any): GenericErrorPayload => {
const apiError = getApiError(e);
return {
message: getApiErrorMessage(e) || e.message || 'Unknown error',
...apiError,
};
};
| 8,318 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/broadcast/index.ts | import broadcast from './broadcast';
export * from './interface';
export * from './helper';
export default broadcast;
| 8,319 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/broadcast/interface.ts | export interface GenericErrorPayload {
status?: number;
message: string;
code?: number;
details?: any;
}
| 8,320 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/browser/credentials.ts | export async function storeCredentials(id: string, password: string) {
if (!navigator.credentials) {
return; // Feature not available
}
try {
// @ts-ignore
const cred = new window.PasswordCredential({
id,
password,
});
await navigator.credentials.store(cred);
} catch (e: any) {
// Firefox will crash because it thinks publicKey is mandatory inside cred.
// Even if the spec says otherwise
// Current API inside Firefox
}
}
| 8,321 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/browser/extension.ts | import getRandomString from '@proton/utils/getRandomString';
export type ExtensionMessage<T = {}> = { type: string } & T;
/* extension communicating with account should
* conform to this message response type */
export type ExtensionMessageResponse<P extends {}> =
| { type: 'success'; payload: P }
| { type: 'error'; payload?: P; error?: string };
/* message fallback should contain the initial message's
* type as a property in order to ensure we're dealing
* with the appropriate response message */
export type ExtensionMessageFallbackResponse<P extends {}> = ExtensionMessageResponse<P> & {
token: string;
};
export const sendMessageSupported = () =>
'chrome' in window && (window as any).chrome?.runtime?.sendMessage !== undefined;
/* Extension messaging must account for Chrome & Firefox specifics :
* Chrome : we can leverage the `externally_connectable` permissions
* Firefox : we have to result to fallback postMessaging via content
* script injections */
export const sendExtensionMessage = async <T extends ExtensionMessage, R extends {} = {}>(
message: T,
options: {
extensionId: string;
maxTimeout?: number;
onFallbackMessage?: (event: MessageEvent<any>) => ExtensionMessageResponse<R> | undefined;
}
): Promise<ExtensionMessageResponse<R>> => {
let timeout: NodeJS.Timeout;
const token = getRandomString(16);
return new Promise<ExtensionMessageResponse<R>>((resolve) => {
/* in order to support legacy message formats : allow
* intercepting event via `options.onFallbackMessage` */
const onFallbackMessage = (event: MessageEvent<ExtensionMessageFallbackResponse<R>>) => {
const externalMessage = (event.data as any).extension === undefined;
if (event.source === window && externalMessage) {
const intercepted = options?.onFallbackMessage?.(event);
const valid = intercepted !== undefined || event.data?.token === token;
if (valid) {
clearTimeout(timeout);
window.removeEventListener('message', onFallbackMessage);
resolve(intercepted ?? event.data);
}
}
};
timeout = setTimeout(() => {
window.removeEventListener('message', onFallbackMessage);
resolve({ type: 'error', error: 'Extension timed out' });
}, options.maxTimeout ?? 15_000);
if (sendMessageSupported()) {
const browser = (window as any).chrome;
return browser.runtime.sendMessage(options.extensionId, message, (result: any) => {
clearTimeout(timeout);
resolve(
browser.runtime.lastError
? {
type: 'error',
error: browser.runtime.lastError.message,
}
: result
);
});
}
window.postMessage({ extension: options.extensionId, token, ...message }, '/');
window.addEventListener('message', onFallbackMessage);
});
};
| 8,322 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/busy/busy.ts | import noop from '@proton/utils/noop';
import { traceError } from '../helpers/sentry';
import { ProtonConfig } from '../interfaces';
let uid = 0;
let busies = [] as number[];
const unregister = (id: number) => {
busies = busies.filter((busy) => busy !== id);
};
const register = () => {
const id = uid++;
busies.push(id);
return () => {
unregister(id);
};
};
const getIsBusy = () => {
return busies.length > 0;
};
export default {
unregister,
register,
getIsBusy,
};
export const dialogRootClassName = 'modal-container';
export const modalTwoRootClassName = 'modal-two';
export const modalTwoBackdropRootClassName = 'modal-two-backdrop';
export const dropdownRootClassName = 'dropdown';
const textInputSelectors = ['email', 'number', 'password', 'search', 'tel', 'text', 'url'].map(
(type) => `input[type=${type}]`
);
const allTextInputsSelector = `input:not([type]), textarea, ${textInputSelectors.join(',')}`;
export const isDialogOpen = () => document.querySelector(`.${dialogRootClassName}, [role="dialog"]`) !== null;
export const isModalOpen = () => document.querySelector(`.${modalTwoRootClassName}`) !== null;
export const isModalBackdropOpen = () => document.querySelector(`.${modalTwoBackdropRootClassName}`) !== null;
export const isDropdownOpen = () => document.querySelector(`.${dropdownRootClassName}`) !== null;
export const isEditing = () => {
const { activeElement } = document;
if (activeElement === null) {
return false;
}
if (
(activeElement.closest('form') ||
activeElement.closest('iframe') ||
activeElement.closest('[contenteditable]')) !== null
) {
return true;
}
return false;
};
export const domIsBusy = () => {
/*
* These verifications perform some dom querying operations so in
* order to not unnecessarily waste performance we return early
* should any of the conditions fail before evaluating all of them
*/
if (isDialogOpen()) {
return true;
}
if (isModalOpen()) {
return true;
}
if (isDropdownOpen()) {
return true;
}
const allInputs = document.querySelectorAll<HTMLInputElement>(allTextInputsSelector);
const allTextInputsAreEmpty = Array.from(allInputs).every((element) => !element.value);
if (!allTextInputsAreEmpty) {
return true;
}
return isEditing();
};
const THIRTY_MINUTES = 30 * 60 * 1000;
const isDifferent = (a?: string, b?: string) => !!a && !!b && b !== a;
export const newVersionUpdater = (config: ProtonConfig) => {
const { VERSION_PATH, COMMIT } = config;
let reloadTimeoutId: number | null = null;
let versionIntervalId: number | null = null;
const getVersion = () => fetch(VERSION_PATH).then((response) => response.json());
const isNewVersionAvailable = async () => {
try {
const { commit } = await getVersion();
return isDifferent(commit, COMMIT);
} catch (error: any) {
traceError(error);
}
};
const clearReload = () => {
if (reloadTimeoutId) {
window.clearTimeout(reloadTimeoutId);
reloadTimeoutId = null;
}
};
const clearVersionCheck = () => {
if (versionIntervalId) {
window.clearInterval(versionIntervalId);
versionIntervalId = null;
}
};
/*
* Instead of immediately reloading as soon as we detect the user to
* not be busy and also having left the tab / browser / window, we
* schedule a reload in case the user only left for a little while
* and is about to come back soon.
*/
const scheduleReload = () => {
clearReload();
reloadTimeoutId = window.setTimeout(() => {
// If the user turns out to be busy here for some reason, abort the reload, and await a new visibilitychange event
if (domIsBusy() || getIsBusy()) {
return;
}
window.location.reload();
}, THIRTY_MINUTES);
};
const handleVisibilityChange = () => {
const documentIsVisible = document.visibilityState === 'visible';
if (documentIsVisible) {
clearReload();
return;
}
if (domIsBusy() || getIsBusy()) {
return;
}
scheduleReload();
};
const registerVisibilityChangeListener = () => {
document.addEventListener('visibilitychange', handleVisibilityChange);
};
const checkForNewVersion = async () => {
if (await isNewVersionAvailable()) {
clearVersionCheck();
registerVisibilityChangeListener();
}
};
versionIntervalId = window.setInterval(() => {
checkForNewVersion().catch(noop);
}, THIRTY_MINUTES);
};
| 8,323 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/busy/index.ts | export { default } from './busy';
export * from './busy';
| 8,324 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/alarms.ts | import truncate from '@proton/utils/truncate';
import uniqueBy from '@proton/utils/uniqueBy';
import { MINUTE } from '../constants';
import { convertUTCDateTimeToZone, fromUTCDate, getTimezoneOffset, toUTCDate } from '../date/timezone';
import { omit } from '../helpers/object';
import {
NotificationModel,
VcalDurationValue,
VcalValarmRelativeComponent,
VcalVeventComponent,
} from '../interfaces/calendar';
import getAlarmMessageText from './alarms/getAlarmMessageText';
import { getValarmTrigger } from './alarms/getValarmTrigger';
import { normalizeDurationToUnit } from './alarms/trigger';
import { NOTIFICATION_TYPE_API, NOTIFICATION_UNITS, NOTIFICATION_WHEN } from './constants';
import { getDisplayTitle } from './helper';
import { getMillisecondsFromTriggerString } from './vcal';
import { propertyToUTCDate } from './vcalConverter';
import {getIsAllDay} from './veventHelper';
/**
* Given a raw event, (optionally) its starting date, the date now and a timezone id,
* generate a notification message for the event
*/
interface Arguments {
component: VcalVeventComponent;
start?: Date;
now: Date;
tzid: string;
formatOptions: any;
}
export const getAlarmMessage = ({ component, start, now, tzid, formatOptions }: Arguments) => {
const { dtstart, summary } = component;
const title = truncate(getDisplayTitle(summary?.value), 100);
const utcStartDate = start || propertyToUTCDate(dtstart);
// To determine if the event is happening in timezoned today, tomorrow, this month or this year,
// we pass fake UTC dates to the getAlarmMessage helper
const startFakeUTCDate = toUTCDate(convertUTCDateTimeToZone(fromUTCDate(utcStartDate), tzid));
const nowFakeUTCDate = toUTCDate(convertUTCDateTimeToZone(fromUTCDate(now), tzid));
const isAllDay = getIsAllDay(component);
return getAlarmMessageText({
title,
isAllDay,
startFakeUTCDate,
nowFakeUTCDate,
formatOptions,
});
};
/**
* Given the UNIX timestamp for the occurrence of an alarm, and the trigger string of this alarm,
* return the timestamp in milliseconds the occurrence of the corresponding event.
* The computation must take into account possible DST shifts
*/
interface Params {
Occurrence: number;
Trigger: string;
tzid: string;
}
export const getNextEventTime = ({ Occurrence, Trigger, tzid }: Params) => {
const alarmTime = Occurrence * 1000;
const eventTime = alarmTime - getMillisecondsFromTriggerString(Trigger);
const offsetAlarmTime = getTimezoneOffset(new Date(alarmTime), tzid).offset;
const offsetEventTime = getTimezoneOffset(new Date(eventTime), tzid).offset;
const offsetDifference = offsetAlarmTime - offsetEventTime;
// correct eventTime in case we jumped across an odd number of DST changes
return eventTime - offsetDifference * MINUTE;
};
/**
* Filter out future notifications
*/
export const filterFutureNotifications = (notifications: NotificationModel[]) => {
return notifications.filter(({ when, value }) => {
if (when === NOTIFICATION_WHEN.BEFORE) {
return true;
}
return value === 0;
});
};
export const sortNotificationsByAscendingTrigger = (notifications: NotificationModel[]) =>
[...notifications].sort((a: NotificationModel, b: NotificationModel) => {
const triggerA = getValarmTrigger(a);
const triggerB = getValarmTrigger(b);
const triggerAMinutes =
normalizeDurationToUnit(triggerA, NOTIFICATION_UNITS.MINUTE) * (triggerA.isNegative ? -1 : 1);
const triggerBMinutes =
normalizeDurationToUnit(triggerB, NOTIFICATION_UNITS.MINUTE) * (triggerB.isNegative ? -1 : 1);
return triggerAMinutes - triggerBMinutes;
});
const sortNotificationsByAscendingValue = (a: NotificationModel, b: NotificationModel) =>
(a.value || 0) - (b.value || 0);
const uniqueNotificationComparator = (notification: NotificationModel) => {
const trigger = getValarmTrigger(notification);
return `${notification.type}-${
normalizeDurationToUnit(trigger, NOTIFICATION_UNITS.MINUTE) * (trigger.isNegative ? -1 : 1)
}`;
};
export const dedupeNotifications = (notifications: NotificationModel[]) => {
const sortedNotifications = [...notifications].sort(sortNotificationsByAscendingValue);
return uniqueBy(sortedNotifications, uniqueNotificationComparator);
};
const getSmallestNonZeroNumericValueFromDurationValue = (object: VcalDurationValue) =>
Math.min(...Object.values(omit(object, ['isNegative'])).filter(Boolean));
const sortAlarmsByAscendingTriggerValue = (a: VcalValarmRelativeComponent, b: VcalValarmRelativeComponent) => {
const aMin = getSmallestNonZeroNumericValueFromDurationValue(a.trigger.value);
const bMin = getSmallestNonZeroNumericValueFromDurationValue(b.trigger.value);
return aMin - bMin;
};
const uniqueAlarmComparator = (alarm: VcalValarmRelativeComponent) => {
const triggerValue = alarm.trigger.value;
const isTriggerNegative = 'isNegative' in triggerValue && triggerValue.isNegative;
return `${alarm.action.value}-${
normalizeDurationToUnit(triggerValue, NOTIFICATION_UNITS.MINUTE) * (isTriggerNegative ? -1 : 1)
}`;
};
/*
* ATTENTION
* This function will deduplicate alarms with any type of relative trigger,
* but if you expect it to pick the nicest triggers (i.e. 2 days instead of 1 day and 24 hours)
* you must pass normalized triggers
*/
export const dedupeAlarmsWithNormalizedTriggers = (alarms: VcalValarmRelativeComponent[]) => {
const sortedAlarms = [...alarms].sort(sortAlarmsByAscendingTriggerValue);
return uniqueBy(sortedAlarms, uniqueAlarmComparator);
};
export const isEmailNotification = ({ type }: NotificationModel) => type === NOTIFICATION_TYPE_API.EMAIL;
| 8,325 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/api.ts | import { getEventByUID } from '../api/calendars';
import { Api } from '../interfaces';
import { CalendarEvent, GetEventByUIDArguments } from '../interfaces/calendar';
import { CALENDAR_TYPE } from './constants';
const MAX_ITERATIONS = 100;
export const getPaginatedEventsByUID = async ({
api,
uid,
recurrenceID,
max = MAX_ITERATIONS,
calendarType,
}: {
api: Api;
uid: string;
recurrenceID?: number;
max?: number;
calendarType?: CALENDAR_TYPE;
}) => {
const pageSize = 100;
let pageNumber = 0;
let result: CalendarEvent[] = [];
while (pageNumber < max) {
const params: GetEventByUIDArguments = {
UID: uid,
RecurrenceID: recurrenceID,
Page: pageNumber,
PageSize: pageSize,
};
if (calendarType !== undefined) {
params.CalendarType = calendarType;
}
const page = await api<{ Events: CalendarEvent[] }>(getEventByUID(params));
result = result.concat(page.Events);
if (page.Events.length !== pageSize) {
break;
}
pageNumber++;
}
return result;
};
export const reformatApiErrorMessage = (message: string) => {
if (message.toLowerCase().endsWith('. please try again')) {
return message.slice(0, -18);
}
return message;
};
| 8,326 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/apiModels.ts | import { RequireSome } from '../interfaces';
import { CalendarCreateOrUpdateEventBlobData, CalendarEvent } from '../interfaces/calendar';
export const getHasSharedEventContent = (
data: CalendarCreateOrUpdateEventBlobData
): data is RequireSome<CalendarCreateOrUpdateEventBlobData, 'SharedEventContent'> => !!data.SharedEventContent;
export const getHasSharedKeyPacket = (
data: CalendarCreateOrUpdateEventBlobData
): data is RequireSome<CalendarCreateOrUpdateEventBlobData, 'SharedKeyPacket'> => !!data.SharedKeyPacket;
export const getHasDefaultNotifications = ({ Notifications }: CalendarEvent) => {
return !Notifications;
};
export const getIsAutoAddedInvite = (
event: CalendarEvent
): event is CalendarEvent & { AddressKeyPacket: string; AddressID: string } =>
!!event.AddressKeyPacket && !!event.AddressID;
| 8,327 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/attendees.ts | import { CryptoProxy } from '@proton/crypto';
import { arrayToHexString, binaryStringToArray } from '@proton/crypto/lib/utils';
import groupWith from '@proton/utils/groupWith';
import isTruthy from '@proton/utils/isTruthy';
import unary from '@proton/utils/unary';
import { CONTACT_NAME_MAX_LENGTH } from '../contacts/constants';
import { buildMailTo, canonicalizeEmailByGuess, getEmailTo, validateEmailAddress } from '../helpers/email';
import { omit } from '../helpers/object';
import { normalize, truncatePossiblyQuotedString } from '../helpers/string';
import {
Attendee,
AttendeeModel,
VcalAttendeeProperty,
VcalOrganizerProperty,
VcalPmVeventComponent,
VcalVeventComponent,
} from '../interfaces/calendar';
import { GetCanonicalEmailsMap } from '../interfaces/hooks/GetCanonicalEmailsMap';
import { RequireSome, SimpleMap } from '../interfaces/utils';
import { ATTENDEE_STATUS_API, ICAL_ATTENDEE_ROLE, ICAL_ATTENDEE_RSVP, ICAL_ATTENDEE_STATUS } from './constants';
import { getAttendeeHasToken, getAttendeePartstat, getAttendeesHaveToken } from './vcalHelper';
export const generateAttendeeToken = async (normalizedEmail: string, uid: string) => {
const uidEmail = `${uid}${normalizedEmail}`;
const byteArray = binaryStringToArray(uidEmail);
const hash = await CryptoProxy.computeHash({ algorithm: 'unsafeSHA1', data: byteArray });
return arrayToHexString(hash);
};
export const toApiPartstat = (partstat?: string) => {
if (partstat === ICAL_ATTENDEE_STATUS.TENTATIVE) {
return ATTENDEE_STATUS_API.TENTATIVE;
}
if (partstat === ICAL_ATTENDEE_STATUS.ACCEPTED) {
return ATTENDEE_STATUS_API.ACCEPTED;
}
if (partstat === ICAL_ATTENDEE_STATUS.DECLINED) {
return ATTENDEE_STATUS_API.DECLINED;
}
return ATTENDEE_STATUS_API.NEEDS_ACTION;
};
export const toIcsPartstat = (partstat?: ATTENDEE_STATUS_API) => {
if (partstat === ATTENDEE_STATUS_API.TENTATIVE) {
return ICAL_ATTENDEE_STATUS.TENTATIVE;
}
if (partstat === ATTENDEE_STATUS_API.ACCEPTED) {
return ICAL_ATTENDEE_STATUS.ACCEPTED;
}
if (partstat === ATTENDEE_STATUS_API.DECLINED) {
return ICAL_ATTENDEE_STATUS.DECLINED;
}
return ICAL_ATTENDEE_STATUS.NEEDS_ACTION;
};
export const fromInternalAttendee = ({
parameters: { 'x-pm-token': token = '', partstat, ...restParameters } = {},
...rest
}: VcalAttendeeProperty) => {
return {
attendee: {
parameters: {
...restParameters,
'x-pm-token': token,
},
...rest,
},
clear: {
token,
status: toApiPartstat(partstat),
},
};
};
export const toInternalAttendee = (
{ attendee: attendees = [] }: Pick<VcalVeventComponent, 'attendee'>,
clear: Attendee[] = []
): VcalAttendeeProperty[] => {
return attendees.map((attendee) => {
if (!attendee.parameters) {
return attendee;
}
const token = attendee.parameters['x-pm-token'];
const extra = clear.find(({ Token }) => Token === token);
if (!token || !extra) {
return attendee;
}
const partstat = toIcsPartstat(extra.Status);
return {
...attendee,
parameters: {
...attendee.parameters,
partstat,
},
};
});
};
export const getAttendeeEmail = (attendee: VcalAttendeeProperty | VcalOrganizerProperty) => {
const { cn, email } = attendee.parameters || {};
const emailTo = getEmailTo(attendee.value);
if (validateEmailAddress(emailTo)) {
return emailTo;
}
if (email && validateEmailAddress(email)) {
return email;
}
if (cn && validateEmailAddress(cn)) {
return cn;
}
return emailTo;
};
export const withPartstat = (attendee: VcalAttendeeProperty, partstat?: ICAL_ATTENDEE_STATUS) => ({
...attendee,
parameters: {
...attendee.parameters,
partstat,
},
});
export const modifyAttendeesPartstat = (
attendees: VcalAttendeeProperty[],
partstatMap: SimpleMap<ICAL_ATTENDEE_STATUS>
) => {
const emailsToModify = Object.keys(partstatMap);
return attendees.map((attendee) => {
const email = getAttendeeEmail(attendee);
if (!emailsToModify.includes(email)) {
return attendee;
}
return withPartstat(attendee, partstatMap[email]);
});
};
export const getSupportedOrganizer = (organizer: VcalOrganizerProperty) => {
const { parameters: { cn } = {} } = organizer;
const emailAddress = getAttendeeEmail(organizer);
const supportedOrganizer: RequireSome<VcalAttendeeProperty, 'parameters'> = {
value: buildMailTo(emailAddress),
parameters: {
cn: truncatePossiblyQuotedString(cn ?? emailAddress, CONTACT_NAME_MAX_LENGTH),
},
};
return supportedOrganizer;
};
export const getSupportedAttendee = (attendee: VcalAttendeeProperty) => {
const { parameters: { cn, role, partstat, rsvp, 'x-pm-token': token } = {} } = attendee;
const emailAddress = getAttendeeEmail(attendee);
const supportedAttendee: RequireSome<VcalAttendeeProperty, 'parameters'> = {
value: buildMailTo(emailAddress),
parameters: {
cn: truncatePossiblyQuotedString(cn ?? emailAddress, CONTACT_NAME_MAX_LENGTH),
},
};
const normalizedUppercasedRole = normalize(role).toUpperCase();
if (
normalizedUppercasedRole === ICAL_ATTENDEE_ROLE.REQUIRED ||
normalizedUppercasedRole === ICAL_ATTENDEE_ROLE.OPTIONAL
) {
supportedAttendee.parameters.role = normalizedUppercasedRole;
}
if (normalize(rsvp) === 'true') {
supportedAttendee.parameters.rsvp = 'TRUE';
}
if (partstat) {
supportedAttendee.parameters.partstat = getAttendeePartstat(attendee);
}
if (token?.length === 40) {
supportedAttendee.parameters['x-pm-token'] = token;
}
return supportedAttendee;
};
export const getCanonicalEmails = async (
attendees: VcalAttendeeProperty[] = [],
getCanonicalEmailsMap: GetCanonicalEmailsMap
) => {
return Object.values(await getCanonicalEmailsMap(attendees.map(unary(getAttendeeEmail)))).filter(isTruthy);
};
export const withPmAttendees = async (
vevent: VcalVeventComponent,
getCanonicalEmailsMap: GetCanonicalEmailsMap,
ignoreErrors = false
): Promise<VcalPmVeventComponent> => {
const { uid, attendee: vcalAttendee } = vevent;
if (!vcalAttendee?.length) {
return omit(vevent, ['attendee']);
}
const attendeesWithEmail = vcalAttendee.map((attendee) => {
const emailAddress = getAttendeeEmail(attendee);
return {
attendee,
emailAddress,
};
});
const emailsWithoutToken = attendeesWithEmail
.filter(({ attendee }) => !attendee.parameters?.['x-pm-token'])
.map(({ emailAddress }) => emailAddress);
const canonicalEmailMap = await getCanonicalEmailsMap(emailsWithoutToken);
const pmAttendees = await Promise.all(
attendeesWithEmail.map(async ({ attendee, emailAddress }) => {
const supportedAttendee = getSupportedAttendee(attendee);
if (getAttendeeHasToken(supportedAttendee)) {
return supportedAttendee;
}
const canonicalEmail = canonicalEmailMap[emailAddress];
if (!canonicalEmail && !ignoreErrors) {
throw new Error('No canonical email provided');
}
// If the participant has an invalid email and we ignore errors, we fall back to the provided email address
const token = await generateAttendeeToken(canonicalEmail || emailAddress, uid.value);
return {
...supportedAttendee,
parameters: {
...supportedAttendee.parameters,
'x-pm-token': token,
},
};
})
);
return {
...vevent,
attendee: pmAttendees,
};
};
export const getEquivalentAttendees = (attendees?: VcalAttendeeProperty[]) => {
if (!attendees?.length) {
return;
}
if (getAttendeesHaveToken(attendees)) {
const attendeesWithToken = attendees.map((attendee) => ({
token: attendee.parameters['x-pm-token'],
email: getAttendeeEmail(attendee),
}));
const equivalentAttendees = groupWith((a, b) => a.token === b.token, attendeesWithToken).map((group) =>
group.map(({ email }) => email)
);
return equivalentAttendees.length < attendees.length
? equivalentAttendees.filter((group) => group.length > 1)
: undefined;
}
// not all attendees have token, so we're gonna canonicalize emails and compare based on that
const attendeesWithCanonicalEmail = attendees.map((attendee) => {
const email = getAttendeeEmail(attendee);
const canonicalEmail = canonicalizeEmailByGuess(email);
return { email, canonicalEmail };
});
const equivalentAttendees = groupWith(
(a, b) => a.canonicalEmail === b.canonicalEmail,
attendeesWithCanonicalEmail
).map((group) => group.map(({ email }) => email));
return equivalentAttendees.length < attendees.length
? equivalentAttendees.filter((group) => group.length > 1)
: undefined;
};
const { REQUIRED } = ICAL_ATTENDEE_ROLE;
const { TRUE } = ICAL_ATTENDEE_RSVP;
const { NEEDS_ACTION } = ICAL_ATTENDEE_STATUS;
export const emailToAttendee = (email: string): AttendeeModel => ({
email,
cn: email,
role: REQUIRED,
partstat: NEEDS_ACTION,
rsvp: TRUE,
});
| 8,328 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/author.ts | import { PublicKeyReference } from '@proton/crypto';
import { captureMessage } from '@proton/shared/lib/helpers/sentry';
import { ContactEmail } from '@proton/shared/lib/interfaces/contacts';
import { GetVerificationPreferences } from '@proton/shared/lib/interfaces/hooks/GetVerificationPreferences';
import isTruthy from '@proton/utils/isTruthy';
import unique from '@proton/utils/unique';
import { canonicalizeInternalEmail } from '../helpers/email';
import { Address } from '../interfaces';
import { CalendarEvent, CalendarEventData } from '../interfaces/calendar';
import { GetAddressKeys } from '../interfaces/hooks/GetAddressKeys';
import { SimpleMap } from '../interfaces/utils';
import { getKeyHasFlagsToVerify } from '../keys';
import { getActiveKeys } from '../keys/getActiveKeys';
import { CALENDAR_CARD_TYPE } from './constants';
const { SIGNED, ENCRYPTED_AND_SIGNED } = CALENDAR_CARD_TYPE;
export const withNormalizedAuthor = (x: CalendarEventData) => ({
...x,
Author: canonicalizeInternalEmail(x.Author),
});
export const withNormalizedAuthors = (x: CalendarEventData[]) => {
if (!x) {
return [];
}
return x.map(withNormalizedAuthor);
};
interface GetAuthorPublicKeysMap {
event: CalendarEvent;
addresses: Address[];
getAddressKeys: GetAddressKeys;
getVerificationPreferences: GetVerificationPreferences;
contactEmailsMap: SimpleMap<ContactEmail>;
}
export const getAuthorPublicKeysMap = async ({
event,
addresses,
getAddressKeys,
getVerificationPreferences,
contactEmailsMap,
}: GetAuthorPublicKeysMap) => {
const publicKeysMap: SimpleMap<PublicKeyReference | PublicKeyReference[]> = {};
const authors = unique(
[...event.SharedEvents, ...event.CalendarEvents]
.map(({ Author, Type }) => {
if (![SIGNED, ENCRYPTED_AND_SIGNED].includes(Type)) {
// no need to fetch keys in this case
return;
}
return canonicalizeInternalEmail(Author);
})
.filter(isTruthy)
);
const normalizedAddresses = addresses.map((address) => ({
...address,
normalizedEmailAddress: canonicalizeInternalEmail(address.Email),
}));
const promises = authors.map(async (author) => {
const ownAddress = normalizedAddresses.find(({ normalizedEmailAddress }) => normalizedEmailAddress === author);
if (ownAddress) {
const decryptedKeys = await getAddressKeys(ownAddress.ID);
const addressKeys = await getActiveKeys(
ownAddress,
ownAddress.SignedKeyList,
ownAddress.Keys,
decryptedKeys
);
publicKeysMap[author] = addressKeys
.filter((decryptedKey) => {
return getKeyHasFlagsToVerify(decryptedKey.flags);
})
.map((key) => key.publicKey);
} else {
try {
const { verifyingKeys } = await getVerificationPreferences({ email: author, contactEmailsMap });
publicKeysMap[author] = verifyingKeys;
} catch (error: any) {
// We're seeing too many unexpected offline errors in the GET /keys route.
// We log them to Sentry and ignore them here (no verification will take place in these cases)
const { ID, CalendarID } = event;
const errorMessage = error?.message || 'Unknown error';
captureMessage('Unexpected error verifying event signature', {
extra: { message: errorMessage, eventID: ID, calendarID: CalendarID },
});
}
}
});
await Promise.all(promises);
return publicKeysMap;
};
| 8,329 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/badges.ts | import { c } from 'ttag';
import { BadgeType } from '@proton/components/components/badge/Badge';
import { SubscribedCalendar, VisualCalendar } from '../interfaces/calendar';
import { getIsCalendarDisabled, getIsCalendarProbablyActive, getIsSubscribedCalendar } from './calendar';
import { getCalendarHasSubscriptionParameters, getCalendarIsNotSyncedInfo } from './subscribe/helpers';
export enum CALENDAR_STATUS_TYPE {
DEFAULT,
ACTIVE,
DISABLED,
SYNCING,
NOT_SYNCED,
}
export interface CalendarStatusBadge {
statusType: CALENDAR_STATUS_TYPE;
badgeType: BadgeType;
text: string;
tooltipText?: string;
className?: string;
}
export const getDefaultCalendarBadge = (): CalendarStatusBadge => ({
statusType: CALENDAR_STATUS_TYPE.DEFAULT,
badgeType: 'primary',
text: c('Calendar status').t`Default`,
});
export const getActiveCalendarBadge = (): CalendarStatusBadge => ({
statusType: CALENDAR_STATUS_TYPE.ACTIVE,
badgeType: 'success',
text: c('Calendar status').t`Active`,
});
export const getDisabledCalendarBadge = (): CalendarStatusBadge => ({
statusType: CALENDAR_STATUS_TYPE.DISABLED,
badgeType: 'light',
text: c('Calendar status').t`Disabled`,
});
export const getNotSyncedCalendarBadge = ({
text,
tooltipText,
}: {
text: string;
tooltipText: string;
}): CalendarStatusBadge => ({
statusType: CALENDAR_STATUS_TYPE.NOT_SYNCED,
badgeType: 'warning',
text,
tooltipText,
});
export const getCalendarStatusBadges = (calendar: VisualCalendar | SubscribedCalendar, defaultCalendarID?: string) => {
const isDisabled = getIsCalendarDisabled(calendar);
const isActive = getIsCalendarProbablyActive(calendar);
const isDefault = calendar.ID === defaultCalendarID;
const isSubscribed = getIsSubscribedCalendar(calendar);
const isNotSyncedInfo = getCalendarHasSubscriptionParameters(calendar)
? getCalendarIsNotSyncedInfo(calendar)
: undefined;
const badges: CalendarStatusBadge[] = [];
if (isDefault) {
badges.push(getDefaultCalendarBadge());
}
if (isActive) {
badges.push(getActiveCalendarBadge());
}
if (isDisabled) {
badges.push(getDisabledCalendarBadge());
}
if (isSubscribed && isNotSyncedInfo) {
badges.push(getNotSyncedCalendarBadge({ text: isNotSyncedInfo.label, tooltipText: isNotSyncedInfo.text }));
}
return { isDisabled, isActive, isDefault, isSubscribed, isNotSyncedInfo, badges };
};
| 8,330 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/calendar.ts | import isTruthy from '@proton/utils/isTruthy';
import unary from '@proton/utils/unary';
import { updateCalendarSettings, updateMember } from '../api/calendars';
import { hasBit, toggleBit } from '../helpers/bitset';
import { Address, Api } from '../interfaces';
import {
Calendar,
CalendarCreateData,
CalendarNotificationSettings,
CalendarSettings,
CalendarUserSettings,
CalendarWithOwnMembers,
SubscribedCalendar,
VisualCalendar,
} from '../interfaces/calendar';
import { GetAddressKeys } from '../interfaces/hooks/GetAddressKeys';
import { GetAddresses } from '../interfaces/hooks/GetAddresses';
import { getHasUserReachedCalendarsLimit } from './calendarLimits';
import { CALENDAR_FLAGS, CALENDAR_TYPE, SETTINGS_VIEW } from './constants';
import { reactivateCalendarsKeys } from './crypto/keys/reactivateCalendarKeys';
import { getMemberAndAddress } from './members';
import { getCanWrite } from './permissions';
export const getIsCalendarActive = ({ Flags } = { Flags: 0 }) => {
return hasBit(Flags, CALENDAR_FLAGS.ACTIVE);
};
export const getIsCalendarDisabled = ({ Flags } = { Flags: 0 }) => {
return hasBit(Flags, CALENDAR_FLAGS.SELF_DISABLED) || hasBit(Flags, CALENDAR_FLAGS.SUPER_OWNER_DISABLED);
};
export const getDoesCalendarNeedReset = ({ Flags } = { Flags: 0 }) => {
return hasBit(Flags, CALENDAR_FLAGS.RESET_NEEDED);
};
export const getDoesCalendarHaveInactiveKeys = ({ Flags } = { Flags: 0 }) => {
return hasBit(Flags, CALENDAR_FLAGS.UPDATE_PASSPHRASE);
};
export const getDoesCalendarNeedUserAction = ({ Flags } = { Flags: 0 }) => {
return getDoesCalendarNeedReset({ Flags }) || getDoesCalendarHaveInactiveKeys({ Flags });
};
export const getIsCalendarProbablyActive = (calendar = { Flags: 0 }) => {
// Calendars are treated as "active" if flags are undefined, this can happen when a new calendar was created and received through the event manager.
// In this case, we assume everything went well and treat it as an active calendar.
return calendar.Flags === undefined || (!getIsCalendarDisabled(calendar) && getIsCalendarActive(calendar));
};
export const getProbablyActiveCalendars = <T extends Calendar>(calendars: T[] = []): T[] => {
return calendars.filter(unary(getIsCalendarProbablyActive));
};
export const getIsPersonalCalendar = (calendar: VisualCalendar | SubscribedCalendar): calendar is VisualCalendar => {
return calendar.Type === CALENDAR_TYPE.PERSONAL;
};
export const getIsOwnedCalendar = (calendar: CalendarWithOwnMembers) => {
return calendar.Owner.Email === calendar.Members[0].Email;
};
export const getIsSharedCalendar = (calendar: VisualCalendar) => {
return getIsPersonalCalendar(calendar) && !getIsOwnedCalendar(calendar);
};
export const getIsSubscribedCalendar = (
calendar: Calendar | VisualCalendar | SubscribedCalendar
): calendar is SubscribedCalendar => {
return calendar.Type === CALENDAR_TYPE.SUBSCRIPTION;
};
export const getPersonalCalendars = <T extends Calendar>(calendars: T[] = []): T[] => {
return calendars.filter(unary(getIsPersonalCalendar));
};
export const getIsCalendarWritable = (calendar: VisualCalendar) => {
return getCanWrite(calendar.Permissions) && getIsPersonalCalendar(calendar);
};
export const getWritableCalendars = (calendars: VisualCalendar[]) => {
return calendars.filter(unary(getIsCalendarWritable));
};
export const getIsHolidaysCalendar = (calendar: VisualCalendar) => {
return calendar.Type === CALENDAR_TYPE.HOLIDAYS;
};
export const getIsUnknownCalendar = (calendar: VisualCalendar) => {
const knownTypes = [CALENDAR_TYPE.PERSONAL, CALENDAR_TYPE.SUBSCRIPTION, CALENDAR_TYPE.HOLIDAYS];
return !knownTypes.includes(calendar.Type);
};
export const getShowDuration = (calendar: VisualCalendar) => {
return getIsCalendarWritable(calendar) && getIsPersonalCalendar(calendar) && getIsOwnedCalendar(calendar);
};
export const groupCalendarsByTaxonomy = (calendars: VisualCalendar[] = []) => {
return calendars.reduce<{
ownedPersonalCalendars: VisualCalendar[];
sharedCalendars: VisualCalendar[];
subscribedCalendars: VisualCalendar[];
holidaysCalendars: VisualCalendar[];
unknownCalendars: VisualCalendar[];
}>(
(acc, calendar) => {
if (getIsSubscribedCalendar(calendar)) {
acc.subscribedCalendars.push(calendar);
} else if (getIsPersonalCalendar(calendar)) {
const calendarsGroup = getIsOwnedCalendar(calendar) ? acc.ownedPersonalCalendars : acc.sharedCalendars;
calendarsGroup.push(calendar);
} else if (getIsHolidaysCalendar(calendar)) {
acc.holidaysCalendars.push(calendar);
} else {
acc.unknownCalendars.push(calendar);
}
return acc;
},
{
ownedPersonalCalendars: [],
sharedCalendars: [],
subscribedCalendars: [],
holidaysCalendars: [],
unknownCalendars: [],
}
);
};
export const getOwnedPersonalCalendars = (calendars: VisualCalendar[] = []) => {
return groupCalendarsByTaxonomy(calendars).ownedPersonalCalendars;
};
export const getSharedCalendars = (calendars: VisualCalendar[] = []) => {
return groupCalendarsByTaxonomy(calendars).sharedCalendars;
};
export const getSubscribedCalendars = (calendars: VisualCalendar[] = []) => {
return groupCalendarsByTaxonomy(calendars).subscribedCalendars;
};
enum CALENDAR_WEIGHT {
PERSONAL = 0,
SUBSCRIBED = 1,
SHARED = 2,
HOLIDAYS = 3,
UNKNOWN = 4,
}
const getCalendarWeight = (calendar: VisualCalendar) => {
if (getIsPersonalCalendar(calendar)) {
return getIsOwnedCalendar(calendar) ? CALENDAR_WEIGHT.PERSONAL : CALENDAR_WEIGHT.SHARED;
}
if (getIsSubscribedCalendar(calendar)) {
return CALENDAR_WEIGHT.SUBSCRIBED;
}
if (getIsHolidaysCalendar(calendar)) {
return CALENDAR_WEIGHT.HOLIDAYS;
}
return CALENDAR_WEIGHT.UNKNOWN;
};
/**
* Returns calendars sorted by weight and first member priority
*
* @param calendars calendars to sort
* @returns sorted calendars
*/
export const sortCalendars = (calendars: VisualCalendar[]) => {
return [...calendars].sort((cal1, cal2) => {
return getCalendarWeight(cal1) - getCalendarWeight(cal2) || cal1.Priority - cal2.Priority;
});
};
const getPreferredCalendar = (calendars: VisualCalendar[] = [], defaultCalendarID: string | null = '') => {
if (!calendars.length) {
return;
}
return calendars.find(({ ID }) => ID === defaultCalendarID) || calendars[0];
};
export const getPreferredActiveWritableCalendar = (
calendars: VisualCalendar[] = [],
defaultCalendarID: string | null = ''
) => {
return getPreferredCalendar(getProbablyActiveCalendars(getWritableCalendars(calendars)), defaultCalendarID);
};
export const getDefaultCalendar = (calendars: VisualCalendar[] = [], defaultCalendarID: string | null = '') => {
// only active owned personal calendars can be default
return getPreferredCalendar(getProbablyActiveCalendars(getOwnedPersonalCalendars(calendars)), defaultCalendarID);
};
export const getVisualCalendar = <T>(calendar: CalendarWithOwnMembers & T): VisualCalendar & T => {
const [member] = calendar.Members;
return {
...calendar,
Name: member.Name,
Description: member.Description,
Color: member.Color,
Display: member.Display,
Email: member.Email,
Flags: member.Flags,
Permissions: member.Permissions,
Priority: member.Priority,
};
};
export const getVisualCalendars = <T>(calendars: (CalendarWithOwnMembers & T)[]): (VisualCalendar & T)[] =>
calendars.map((calendar) => getVisualCalendar(calendar));
export const getCanCreateCalendar = ({
calendars,
ownedPersonalCalendars,
disabledCalendars,
isFreeUser,
}: {
calendars: VisualCalendar[];
ownedPersonalCalendars: VisualCalendar[];
disabledCalendars: VisualCalendar[];
isFreeUser: boolean;
}) => {
const { isCalendarsLimitReached } = getHasUserReachedCalendarsLimit(calendars, isFreeUser);
if (isCalendarsLimitReached) {
return false;
}
// TODO: The following if condition is very flaky. We should check that somewhere else
const activeCalendars = getProbablyActiveCalendars(ownedPersonalCalendars);
const totalActionableCalendars = activeCalendars.length + disabledCalendars.length;
if (totalActionableCalendars < ownedPersonalCalendars.length) {
// calendar keys need to be reactivated before being able to create a calendar
return false;
}
return true;
};
export const getCalendarWithReactivatedKeys = async ({
calendar,
api,
silenceApi = true,
addresses,
getAddressKeys,
successCallback,
handleError,
}: {
calendar: VisualCalendar;
api: Api;
silenceApi?: boolean;
addresses: Address[];
getAddressKeys: GetAddressKeys;
successCallback?: () => void;
handleError?: (error: any) => void;
}) => {
if (getDoesCalendarHaveInactiveKeys(calendar)) {
try {
const possiblySilentApi = <T>(config: any) => api<T>({ ...config, silence: silenceApi });
await reactivateCalendarsKeys({
calendars: [calendar],
api: possiblySilentApi,
addresses,
getAddressKeys,
});
successCallback?.();
return {
...calendar,
Flags: toggleBit(calendar.Flags, CALENDAR_FLAGS.UPDATE_PASSPHRASE),
Members: calendar.Members.map((member) => {
const newMember = { ...member };
if (newMember.Email === calendar.Email) {
newMember.Flags = toggleBit(calendar.Flags, CALENDAR_FLAGS.UPDATE_PASSPHRASE);
}
return newMember;
}),
};
} catch (e) {
handleError?.(e);
return calendar;
}
}
return calendar;
};
export const DEFAULT_CALENDAR_USER_SETTINGS: CalendarUserSettings = {
WeekLength: 7,
DisplayWeekNumber: 1,
DefaultCalendarID: null,
AutoDetectPrimaryTimezone: 1,
PrimaryTimezone: 'UTC',
DisplaySecondaryTimezone: 0,
SecondaryTimezone: null,
ViewPreference: SETTINGS_VIEW.WEEK,
InviteLocale: null,
AutoImportInvite: 0,
};
const getHasChangedCalendarMemberData = (calendarPayload: CalendarCreateData, calendar: VisualCalendar) => {
const { Name: oldName, Description: oldDescription, Color: oldColor, Display: oldDisplay } = calendar;
const { Name: newName, Description: newDescription, Color: newColor, Display: newDisplay } = calendarPayload;
return (
oldColor.toLowerCase() !== newColor.toLowerCase() ||
oldDisplay !== newDisplay ||
oldName !== newName ||
oldDescription !== newDescription
);
};
const getHasChangedCalendarNotifications = (
newNotifications: CalendarNotificationSettings[],
oldNotifications: CalendarNotificationSettings[]
) => {
return (
newNotifications.length !== oldNotifications.length ||
newNotifications.some(
({ Type: newType, Trigger: newTrigger }) =>
!oldNotifications.find(
({ Type: oldType, Trigger: oldTrigger }) => oldType === newType && oldTrigger === newTrigger
)
)
);
};
const getHasChangedCalendarSettings = (
newSettings: Required<
Pick<CalendarSettings, 'DefaultEventDuration' | 'DefaultPartDayNotifications' | 'DefaultFullDayNotifications'>
>,
oldSettings?: CalendarSettings
) => {
if (!oldSettings) {
// we should not fall in here. If we do, assume changes are needed
return true;
}
const {
DefaultEventDuration: newDuration,
DefaultPartDayNotifications: newPartDayNotifications,
DefaultFullDayNotifications: newFullDayNotifications,
} = newSettings;
const {
DefaultEventDuration: oldDuration,
DefaultPartDayNotifications: oldPartDayNotifications,
DefaultFullDayNotifications: oldFullDayNotifications,
} = oldSettings;
return (
newDuration !== oldDuration ||
getHasChangedCalendarNotifications(newPartDayNotifications, oldPartDayNotifications) ||
getHasChangedCalendarNotifications(newFullDayNotifications, oldFullDayNotifications)
);
};
export const updateCalendar = async (
calendar: VisualCalendar,
calendarPayload: CalendarCreateData,
calendarSettingsPayload: Required<
Pick<CalendarSettings, 'DefaultEventDuration' | 'DefaultPartDayNotifications' | 'DefaultFullDayNotifications'>
>,
readCalendarBootstrap: (calendarID: string) => any,
getAddresses: GetAddresses,
api: Api
) => {
const calendarID = calendar.ID;
const { Color, Display, Description, Name } = calendarPayload;
const [{ ID: memberID }] = getMemberAndAddress(await getAddresses(), calendar.Members);
const hasChangedMemberData = getHasChangedCalendarMemberData(calendarPayload, calendar);
const hasChangedSettings = getHasChangedCalendarSettings(
calendarSettingsPayload,
readCalendarBootstrap(calendarID)?.CalendarSettings
);
await Promise.all(
[
hasChangedMemberData && api(updateMember(calendarID, memberID, { Display, Color, Description, Name })),
hasChangedSettings && api(updateCalendarSettings(calendarID, calendarSettingsPayload)),
].filter(isTruthy)
);
};
| 8,331 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/calendarLimits.ts | import { c } from 'ttag';
import { BRAND_NAME, MAIL_SHORT_APP_NAME } from '../constants';
import { VisualCalendar } from '../interfaces/calendar';
import { getOwnedPersonalCalendars } from './calendar';
import { MAX_CALENDARS_FREE, MAX_CALENDARS_PAID } from './constants';
export const getHasUserReachedCalendarsLimit = (calendars: VisualCalendar[], isFreeUser: boolean) => {
const ownedPersonalCalendars = getOwnedPersonalCalendars(calendars);
const maxPersonalCalendars = isFreeUser ? MAX_CALENDARS_FREE : MAX_CALENDARS_PAID;
// we enforce users to have at least one owned personal calendar
const isCalendarsLimitReached = calendars.length >= maxPersonalCalendars && ownedPersonalCalendars.length > 0;
return {
isCalendarsLimitReached,
isOtherCalendarsLimitReached:
isCalendarsLimitReached || calendars.length - ownedPersonalCalendars.length >= maxPersonalCalendars - 1,
};
};
export const getCalendarsLimitReachedText = (isFreeUser: boolean) => {
const maxReachedText = c('Limit of calendars reached')
.t`You've reached the maximum number of calendars available in your plan.`;
const addNewCalendarText = isFreeUser
? c('Limit of calendars reached')
.t`To add a new calendar, remove another calendar or upgrade your ${BRAND_NAME} plan to a ${MAIL_SHORT_APP_NAME} paid plan.`
: c('Limit of calendars reached').t`To add a new calendar, remove an existing one.`;
return {
maxReachedText,
addNewCalendarText,
combinedText: `${maxReachedText} ${addNewCalendarText}`,
};
};
export const willUserReachCalendarsLimit = (
calendars: VisualCalendar[],
calendarsToCreateCount: number,
isFreeUser: boolean
) => {
const maxCalendars = isFreeUser ? MAX_CALENDARS_FREE : MAX_CALENDARS_PAID;
const isCalendarsLimitReached = calendars.length + calendarsToCreateCount > maxCalendars;
return isCalendarsLimitReached;
};
| 8,332 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/constants.ts | import { ACCENT_COLORS } from '../colors';
import { BASE_SIZE } from '../constants';
export const MAX_CALENDARS_FREE = 3;
export const MAX_CALENDARS_PAID = 25; // Only paid mail
export const MAX_CALENDARS_FAMILY = 150;
export const MAX_DEFAULT_NOTIFICATIONS = 5;
export const MAX_NOTIFICATIONS = 10;
export const MAX_ATTENDEES = 100;
export const MAX_CALENDAR_MEMBERS = 49;
export const MAX_LINKS_PER_CALENDAR = 5;
export enum CALENDAR_CARD_TYPE {
CLEAR_TEXT = 0,
ENCRYPTED = 1,
SIGNED = 2,
ENCRYPTED_AND_SIGNED = 3,
}
export enum CALENDAR_PERMISSIONS {
SUPER_OWNER = 1,
OWNER = 2,
ADMIN = 4,
READ_MEMBER_LIST = 8,
WRITE = 16,
READ = 32,
AVAILABILITY = 64,
}
export enum ATTENDEE_PERMISSIONS {
SEE = 1,
INVITE = 2,
SEE_AND_INVITE = 3,
EDIT = 4,
DELETE = 8,
}
export const DEFAULT_ATTENDEE_PERMISSIONS = ATTENDEE_PERMISSIONS.SEE;
export enum CALENDAR_FLAGS {
INACTIVE = 0,
ACTIVE = 1,
UPDATE_PASSPHRASE = 2,
RESET_NEEDED = 4,
INCOMPLETE_SETUP = 8,
LOST_ACCESS = 16,
SELF_DISABLED = 32,
SUPER_OWNER_DISABLED = 64,
}
export enum CALENDAR_TYPE {
PERSONAL = 0,
SUBSCRIPTION = 1,
HOLIDAYS = 2,
}
export enum CALENDAR_STATUS {
ACTIVE = 1,
DELETED = 2,
}
export enum CALENDAR_DISPLAY {
HIDDEN = 0,
VISIBLE = 1,
}
export enum ICAL_CALSCALE {
GREGORIAN = 'GREGORIAN',
}
export enum ICAL_METHOD {
PUBLISH = 'PUBLISH',
REQUEST = 'REQUEST',
REPLY = 'REPLY',
CANCEL = 'CANCEL',
COUNTER = 'COUNTER',
DECLINECOUNTER = 'DECLINECOUNTER',
ADD = 'ADD',
REFRESH = 'REFRESH',
}
export const ICAL_METHODS_ATTENDEE = [ICAL_METHOD.REPLY, ICAL_METHOD.COUNTER, ICAL_METHOD.REFRESH];
export const ICAL_METHODS_ORGANIZER = [
ICAL_METHOD.REQUEST,
ICAL_METHOD.CANCEL,
ICAL_METHOD.ADD,
ICAL_METHOD.DECLINECOUNTER,
];
export enum ICAL_EVENT_STATUS {
TENTATIVE = 'TENTATIVE',
CONFIRMED = 'CONFIRMED',
CANCELLED = 'CANCELLED',
}
export enum ICAL_ATTENDEE_RSVP {
TRUE = 'TRUE',
FALSE = 'FALSE',
}
export enum ICAL_ATTENDEE_ROLE {
REQUIRED = 'REQ-PARTICIPANT', // Indicates a participant whose participation is required
OPTIONAL = 'OPT-PARTICIPANT', // Indicates a participant whose participation is optional
NON = 'NON-PARTICIPANT', // Indicates a participant who is copied for information purposes only
}
export enum ICAL_ATTENDEE_STATUS {
NEEDS_ACTION = 'NEEDS-ACTION',
ACCEPTED = 'ACCEPTED',
DECLINED = 'DECLINED',
TENTATIVE = 'TENTATIVE',
DELEGATED = 'DELEGATED',
}
export enum ICAL_ALARM_ACTION {
DISPLAY = 'DISPLAY',
EMAIL = 'EMAIL',
AUDIO = 'AUDIO',
}
export enum ATTENDEE_STATUS_API {
NEEDS_ACTION = 0,
TENTATIVE = 1,
DECLINED = 2,
ACCEPTED = 3,
}
export const MAX_ICAL_SEQUENCE = 2 ** 31;
export const MAX_CHARS_API = {
UID: 191,
CALENDAR_NAME: 100,
CALENDAR_DESCRIPTION: 255,
TITLE: 255,
EVENT_DESCRIPTION: 3000,
LOCATION: 255,
};
export const MAX_CHARS_CLEARTEXT = {
PURPOSE: 500,
};
export const MINIMUM_DATE = new Date(1970, 0, 1);
export const MINIMUM_DATE_UTC = new Date(
Date.UTC(MINIMUM_DATE.getFullYear(), MINIMUM_DATE.getMonth(), MINIMUM_DATE.getDate())
);
export const MAXIMUM_DATE = new Date(2037, 11, 31);
export const MAXIMUM_DATE_UTC = new Date(
Date.UTC(MAXIMUM_DATE.getFullYear(), MAXIMUM_DATE.getMonth(), MAXIMUM_DATE.getDate())
);
export enum FREQUENCY {
ONCE = 'ONCE',
DAILY = 'DAILY',
WEEKLY = 'WEEKLY',
MONTHLY = 'MONTHLY',
YEARLY = 'YEARLY',
CUSTOM = 'CUSTOM',
OTHER = 'OTHER',
}
export const FREQUENCY_INTERVALS_MAX = {
[FREQUENCY.ONCE]: 1000 - 1,
[FREQUENCY.DAILY]: 1000 - 1,
[FREQUENCY.WEEKLY]: 5000 - 1,
[FREQUENCY.MONTHLY]: 1000 - 1,
[FREQUENCY.YEARLY]: 100 - 1,
[FREQUENCY.CUSTOM]: 1000 - 1,
[FREQUENCY.OTHER]: 1,
};
export const FREQUENCY_COUNT_MAX = 50 - 1;
export const FREQUENCY_COUNT_MAX_INVITATION = 500 - 1;
export enum DAILY_TYPE {
ALL_DAYS = 0,
}
export enum WEEKLY_TYPE {
ON_DAYS = 0,
}
export enum MONTHLY_TYPE {
ON_MONTH_DAY = 0,
ON_NTH_DAY = 1,
ON_MINUS_NTH_DAY = -1,
}
export enum YEARLY_TYPE {
BY_MONTH_ON_MONTH_DAY = 0,
}
export enum END_TYPE {
NEVER = 'NEVER',
AFTER_N_TIMES = 'COUNT',
UNTIL = 'UNTIL',
}
export const ICAL_EXTENSIONS = ['ics', 'ical', 'ifb', 'icalendar'];
export const ICAL_MIME_TYPE = 'text/calendar';
export const DEFAULT_CALENDAR = {
name: 'My calendar',
color: ACCENT_COLORS[0],
description: '',
};
export enum VIEWS {
DAY = 1,
WEEK,
MONTH,
YEAR,
AGENDA,
CUSTOM,
MAIL,
DRIVE,
SEARCH,
}
export enum ACTION_VIEWS {
VIEW = 'VIEW',
}
export enum NOTIFICATION_WHEN {
BEFORE = '-',
AFTER = '',
}
export enum NOTIFICATION_UNITS {
WEEK = 1,
DAY = 2,
HOUR = 3,
MINUTE = 4,
}
export const NOTIFICATION_UNITS_MAX = {
[NOTIFICATION_UNITS.WEEK]: 1000 - 1,
[NOTIFICATION_UNITS.DAY]: 7000 - 1,
[NOTIFICATION_UNITS.HOUR]: 1000 - 1,
[NOTIFICATION_UNITS.MINUTE]: 10000 - 1,
};
export const DEFAULT_EVENT_DURATION = 30;
export const COLORS = {
BLACK: '#000',
WHITE: '#FFF',
};
export enum SAVE_CONFIRMATION_TYPES {
SINGLE = 1,
RECURRING,
}
export enum DELETE_CONFIRMATION_TYPES {
SINGLE = 1,
RECURRING,
}
export enum RECURRING_TYPES {
ALL = 1,
FUTURE,
SINGLE,
}
export const MAX_IMPORT_EVENTS = 15000;
export const MAX_IMPORT_EVENTS_STRING = MAX_IMPORT_EVENTS.toLocaleString();
export const MAX_IMPORT_FILE_SIZE = 10 * BASE_SIZE ** 2;
export const MAX_IMPORT_FILE_SIZE_STRING = '10 MB';
export const MAX_UID_CHARS_DISPLAY = 43;
export const MAX_FILENAME_CHARS_DISPLAY = 100;
export const IMPORT_CALENDAR_FAQ_URL = '/how-to-import-calendar-to-proton-calendar';
export const IMPORT_CALENDAR_UNSUPPORTED_FAQ_URL = `${IMPORT_CALENDAR_FAQ_URL}/#data-not-supported`;
export const TITLE_INPUT_ID = 'event-title-input';
export const FREQUENCY_INPUT_ID = 'event-frequency-input';
export const LOCATION_INPUT_ID = 'event-location-input';
export const NOTIFICATION_INPUT_ID = 'event-notification-input';
export const CALENDAR_INPUT_ID = 'event-calendar-input';
export const DESCRIPTION_INPUT_ID = 'event-description-input';
export const DATE_INPUT_ID = 'event-date-input';
export const PARTICIPANTS_INPUT_ID = 'event-participants-input';
export const MEMBERS_INPUT_ID = 'shared-members-input';
export enum IMPORT_ERROR_TYPE {
NO_FILE_SELECTED,
NO_ICS_FILE,
FILE_EMPTY,
FILE_TOO_BIG,
FILE_CORRUPTED,
INVALID_CALENDAR,
INVALID_METHOD,
NO_EVENTS,
TOO_MANY_EVENTS,
}
export const SHARED_SIGNED_FIELDS = [
'uid',
'dtstamp',
'dtstart',
'dtend',
'recurrence-id',
'rrule',
'exdate',
'organizer',
'sequence',
] as const;
export const SHARED_ENCRYPTED_FIELDS = ['uid', 'dtstamp', 'created', 'description', 'summary', 'location'] as const;
export const CALENDAR_SIGNED_FIELDS = ['uid', 'dtstamp', 'status', 'transp'] as const;
export const CALENDAR_ENCRYPTED_FIELDS = ['uid', 'dtstamp', 'comment'] as const;
export const USER_SIGNED_FIELDS = ['uid', 'dtstamp'] as const;
export const USER_ENCRYPTED_FIELDS = [] as const;
export const ATTENDEES_SIGNED_FIELDS = [] as const;
export const ATTENDEES_ENCRYPTED_FIELDS = ['uid', 'attendee'] as const;
export const REQUIRED_SET = new Set(['uid', 'dtstamp'] as const);
// Set of taken keys to put the rest
export const TAKEN_KEYS = [
...new Set([
...SHARED_SIGNED_FIELDS,
...SHARED_ENCRYPTED_FIELDS,
...CALENDAR_SIGNED_FIELDS,
...CALENDAR_ENCRYPTED_FIELDS,
...USER_SIGNED_FIELDS,
...USER_ENCRYPTED_FIELDS,
...ATTENDEES_ENCRYPTED_FIELDS,
...ATTENDEES_SIGNED_FIELDS,
]),
] as const;
export enum NOTIFICATION_TYPE_API {
EMAIL = 0,
DEVICE = 1,
}
export enum EVENT_VERIFICATION_STATUS {
SUCCESSFUL = 1,
NOT_VERIFIED = 0,
FAILED = -1,
}
export enum SETTINGS_VIEW {
DAY = 0,
WEEK = 1,
MONTH = 2,
YEAR = 3,
PLANNING = 4,
}
export enum CALENDAR_VALIDATION_MODE {
DOWNLOAD_ONLY = 0,
DOWNLOAD_AND_PARSE = 1,
}
export const CALENDAR_SETTINGS_ROUTE = {
GENERAL: '/general',
CALENDARS: '/calendars',
INTEROPS: '/import-export',
};
export const CALENDAR_SETTINGS_SECTION_ID = {
TIME_ZONE: 'time-zone',
LAYOUT: 'layout',
INVITATIONS: 'invitations',
THEME: 'theme',
PERSONAL_CALENDARS: 'my-calendars',
OTHER_CALENDARS: 'other-calendars',
IMPORT: 'import',
EXPORT: 'export',
SHARE: 'share',
SHARE_PRIVATELY: 'share-privately',
SHARE_PUBLICLY: 'share-publicly',
};
| 8,333 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/deserialize.ts | import { PrivateKeyReference, PublicKeyReference, SessionKey } from '@proton/crypto';
import { getIsAddressActive, getIsAddressExternal } from '../helpers/address';
import { canonicalizeInternalEmail } from '../helpers/email';
import { base64StringToUint8Array } from '../helpers/encoding';
import { Address, Nullable } from '../interfaces';
import {
CalendarEvent,
CalendarNotificationSettings,
CalendarSettings,
VcalAttendeeProperty,
VcalOrganizerProperty,
VcalVeventComponent,
} from '../interfaces/calendar';
import { SimpleMap } from '../interfaces/utils';
import { toSessionKey } from '../keys/sessionKey';
import { modelToValarmComponent } from './alarms/modelToValarm';
import { apiNotificationsToModel } from './alarms/notificationsToModel';
import { getAttendeeEmail, toInternalAttendee } from './attendees';
import { ICAL_ATTENDEE_STATUS } from './constants';
import {
decryptAndVerifyCalendarEvent,
getAggregatedEventVerificationStatus,
getDecryptedSessionKey,
} from './crypto/decrypt';
import { unwrap } from './helper';
import { parseWithFoldingRecovery } from './icsSurgery/ics';
import { getAttendeePartstat, getIsEventComponent } from './vcalHelper';
export const readSessionKey = (
KeyPacket?: Nullable<string>,
privateKeys?: PrivateKeyReference | PrivateKeyReference[]
) => {
if (!KeyPacket || !privateKeys) {
return;
}
return getDecryptedSessionKey(base64StringToUint8Array(KeyPacket), privateKeys);
};
/**
* Read the session keys.
*/
export const readSessionKeys = async ({
calendarEvent,
decryptedSharedKeyPacket,
privateKeys,
}: {
calendarEvent: Pick<CalendarEvent, 'SharedKeyPacket' | 'AddressKeyPacket' | 'CalendarKeyPacket'>;
decryptedSharedKeyPacket?: string;
privateKeys?: PrivateKeyReference | PrivateKeyReference[];
}) => {
const sharedsessionKeyPromise = decryptedSharedKeyPacket
? Promise.resolve(toSessionKey(decryptedSharedKeyPacket))
: readSessionKey(calendarEvent.AddressKeyPacket || calendarEvent.SharedKeyPacket, privateKeys);
const calendarSessionKeyPromise = readSessionKey(calendarEvent.CalendarKeyPacket, privateKeys);
return Promise.all([sharedsessionKeyPromise, calendarSessionKeyPromise]);
};
const fromApiNotifications = ({
notifications: apiNotifications,
isAllDay,
calendarSettings,
}: {
notifications: Nullable<CalendarNotificationSettings[]>;
isAllDay: boolean;
calendarSettings: CalendarSettings;
}) => {
const modelAlarms = apiNotificationsToModel({ notifications: apiNotifications, isAllDay, calendarSettings });
return modelAlarms.map((alarm) => modelToValarmComponent(alarm));
};
export const getSelfAddressData = ({
organizer,
attendees = [],
addresses = [],
}: {
organizer?: VcalOrganizerProperty;
attendees?: VcalAttendeeProperty[];
addresses?: Address[];
}) => {
if (!organizer) {
// it is not an invitation
return {
isOrganizer: false,
isAttendee: false,
};
}
const internalAddresses = addresses.filter((address) => !getIsAddressExternal(address));
const ownCanonicalizedEmailsMap = internalAddresses.reduce<SimpleMap<string>>((acc, { Email }) => {
acc[Email] = canonicalizeInternalEmail(Email);
return acc;
}, {});
const organizerEmail = canonicalizeInternalEmail(getAttendeeEmail(organizer));
const organizerAddress = internalAddresses.find(({ Email }) => ownCanonicalizedEmailsMap[Email] === organizerEmail);
if (organizerAddress) {
return {
isOrganizer: true,
isAttendee: false,
selfAddress: organizerAddress,
};
}
const canonicalAttendeeEmails = attendees.map((attendee) => canonicalizeInternalEmail(getAttendeeEmail(attendee)));
// split active and inactive addresses
const { activeAddresses, inactiveAddresses } = internalAddresses.reduce<{
activeAddresses: Address[];
inactiveAddresses: Address[];
}>(
(acc, address) => {
const addresses = getIsAddressActive(address) ? acc.activeAddresses : acc.inactiveAddresses;
addresses.push(address);
return acc;
},
{ activeAddresses: [], inactiveAddresses: [] }
);
// start checking active addresses
const { selfActiveAttendee, selfActiveAddress, selfActiveAttendeeIndex } = activeAddresses.reduce<{
selfActiveAttendee?: VcalAttendeeProperty;
selfActiveAttendeeIndex?: number;
selfActiveAddress?: Address;
answeredAttendeeFound: boolean;
}>(
(acc, address) => {
if (acc.answeredAttendeeFound) {
return acc;
}
const canonicalSelfEmail = ownCanonicalizedEmailsMap[address.Email];
const index = canonicalAttendeeEmails.findIndex((email) => email === canonicalSelfEmail);
if (index === -1) {
return acc;
}
const attendee = attendees[index];
const partstat = getAttendeePartstat(attendee);
const answeredAttendeeFound = partstat !== ICAL_ATTENDEE_STATUS.NEEDS_ACTION;
if (answeredAttendeeFound || !(acc.selfActiveAttendee && acc.selfActiveAddress)) {
return {
selfActiveAttendee: attendee,
selfActiveAddress: address,
selfActiveAttendeeIndex: index,
answeredAttendeeFound,
};
}
return acc;
},
{ answeredAttendeeFound: false }
);
if (selfActiveAttendee && selfActiveAddress) {
return {
isOrganizer: false,
isAttendee: true,
selfAttendee: selfActiveAttendee,
selfAddress: selfActiveAddress,
selfAttendeeIndex: selfActiveAttendeeIndex,
};
}
// check inactive addresses
const { selfInactiveAttendee, selfInactiveAddress, selfInactiveAttendeeIndex } = inactiveAddresses.reduce<{
selfInactiveAttendee?: VcalAttendeeProperty;
selfInactiveAttendeeIndex?: number;
selfInactiveAddress?: Address;
answeredAttendeeFound: boolean;
}>(
(acc, address) => {
if (acc.answeredAttendeeFound) {
return acc;
}
const canonicalSelfEmail = ownCanonicalizedEmailsMap[address.Email];
const index = canonicalAttendeeEmails.findIndex((email) => email === canonicalSelfEmail);
if (index === -1) {
return acc;
}
const attendee = attendees[index];
const partstat = getAttendeePartstat(attendee);
const answeredAttendeeFound = partstat !== ICAL_ATTENDEE_STATUS.NEEDS_ACTION;
if (answeredAttendeeFound || !(acc.selfInactiveAttendee && acc.selfInactiveAddress)) {
return {
selfInactiveAttendee: attendee,
selfInactiveAttendeeIndex: index,
selfInactiveAddress: address,
answeredAttendeeFound,
};
}
return acc;
},
{ answeredAttendeeFound: false }
);
return {
isOrganizer: false,
isAttendee: !!selfInactiveAttendee,
selfAttendee: selfInactiveAttendee,
selfAddress: selfInactiveAddress,
selfAttendeeIndex: selfInactiveAttendeeIndex,
};
};
const readCalendarAlarms = (
{ Notifications, FullDay }: Pick<CalendarEvent, 'Notifications' | 'FullDay'>,
calendarSettings: CalendarSettings
) => {
return {
valarmComponents: fromApiNotifications({
notifications: Notifications || null,
isAllDay: !!FullDay,
calendarSettings,
}),
hasDefaultNotifications: !Notifications,
};
};
/**
* Read the parts of a calendar event into an internal vcal component.
*/
interface ReadCalendarEventArguments {
event: Pick<
CalendarEvent,
| 'SharedEvents'
| 'CalendarEvents'
| 'AttendeesEvents'
| 'Attendees'
| 'Notifications'
| 'FullDay'
| 'CalendarID'
| 'ID'
>;
publicKeysMap?: SimpleMap<PublicKeyReference | PublicKeyReference[]>;
sharedSessionKey?: SessionKey;
calendarSessionKey?: SessionKey;
calendarSettings: CalendarSettings;
addresses: Address[];
encryptingAddressID?: string;
}
export const readCalendarEvent = async ({
event: {
SharedEvents = [],
CalendarEvents = [],
AttendeesEvents = [],
Attendees = [],
Notifications,
FullDay,
CalendarID: calendarID,
ID: eventID,
},
publicKeysMap = {},
addresses,
sharedSessionKey,
calendarSessionKey,
calendarSettings,
encryptingAddressID,
}: ReadCalendarEventArguments) => {
const decryptedEventsResults = await Promise.all([
Promise.all(SharedEvents.map((e) => decryptAndVerifyCalendarEvent(e, publicKeysMap, sharedSessionKey))),
Promise.all(CalendarEvents.map((e) => decryptAndVerifyCalendarEvent(e, publicKeysMap, calendarSessionKey))),
Promise.all(AttendeesEvents.map((e) => decryptAndVerifyCalendarEvent(e, publicKeysMap, sharedSessionKey))),
]);
const [decryptedSharedEvents, decryptedCalendarEvents, decryptedAttendeesEvents] = decryptedEventsResults.map(
(decryptedEvents) => decryptedEvents.map(({ data }) => data)
);
const verificationStatusArray = decryptedEventsResults
.map((decryptedEvents) => decryptedEvents.map(({ verificationStatus }) => verificationStatus))
.flat();
const verificationStatus = getAggregatedEventVerificationStatus(verificationStatusArray);
const vevent = [...decryptedSharedEvents, ...decryptedCalendarEvents].reduce<VcalVeventComponent>((acc, event) => {
if (!event) {
return acc;
}
const parsedComponent = parseWithFoldingRecovery(unwrap(event), { calendarID, eventID });
if (!getIsEventComponent(parsedComponent)) {
return acc;
}
return { ...acc, ...parsedComponent };
}, {} as VcalVeventComponent);
const { valarmComponents, hasDefaultNotifications } = readCalendarAlarms(
{ Notifications, FullDay },
calendarSettings
);
const veventAttendees = decryptedAttendeesEvents.reduce<VcalAttendeeProperty[]>((acc, event) => {
if (!event) {
return acc;
}
const parsedComponent = parseWithFoldingRecovery(unwrap(event), { calendarID, eventID });
if (!getIsEventComponent(parsedComponent)) {
return acc;
}
return acc.concat(toInternalAttendee(parsedComponent, Attendees));
}, []);
if (valarmComponents.length) {
vevent.components = valarmComponents;
}
if (veventAttendees.length) {
vevent.attendee = veventAttendees;
}
const selfAddressData = getSelfAddressData({
organizer: vevent.organizer,
attendees: veventAttendees,
addresses,
});
const encryptionData = {
encryptingAddressID,
sharedSessionKey,
calendarSessionKey,
};
return { veventComponent: vevent, hasDefaultNotifications, verificationStatus, selfAddressData, encryptionData };
};
| 8,334 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/exdate.ts | import { toUTCDate } from '../date/timezone';
import { DateTimeValue } from '../interfaces/calendar';
import { VcalDateOrDateTimeProperty, VcalDateProperty, VcalDateTimeProperty } from '../interfaces/calendar/VcalModel';
import { getDateProperty, getDateTimeProperty } from './vcalConverter';
export const createExdateMap = (exdate: VcalDateOrDateTimeProperty[] = []) => {
return exdate.reduce<{ [key: number]: boolean }>((acc, dateProperty: any) => {
const localExclude = toUTCDate(dateProperty.value);
acc[+localExclude] = true;
return acc;
}, {});
};
export const toExdate = (dateObject: DateTimeValue, isAllDay: boolean, tzid = 'UTC'): VcalDateOrDateTimeProperty => {
if (isAllDay) {
return getDateProperty(dateObject) as VcalDateProperty;
}
return getDateTimeProperty(dateObject, tzid) as VcalDateTimeProperty;
};
| 8,335 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/formatData.ts | import { CalendarNotificationSettings, CreateOrUpdateCalendarEventData } from '@proton/shared/lib/interfaces/calendar';
import isTruthy from '@proton/utils/isTruthy';
import { uint8ArrayToBase64String } from '../helpers/encoding';
import { SimpleMap } from '../interfaces';
import { AttendeeClearPartResult } from '../interfaces/calendar/Attendee';
import { EncryptPartResult, SignPartResult } from '../interfaces/calendar/PartResult';
import { CALENDAR_CARD_TYPE } from './constants';
const { ENCRYPTED_AND_SIGNED, SIGNED } = CALENDAR_CARD_TYPE;
/**
* Format the data into what the API expects.
*/
interface FormatDataArguments {
sharedSignedPart?: SignPartResult;
sharedEncryptedPart?: EncryptPartResult;
sharedSessionKey?: Uint8Array;
calendarSignedPart?: SignPartResult;
calendarEncryptedPart?: EncryptPartResult;
calendarSessionKey?: Uint8Array;
attendeesEncryptedPart?: EncryptPartResult;
attendeesClearPart?: AttendeeClearPartResult[];
removedAttendeesEmails?: string[];
attendeesEncryptedSessionKeysMap?: SimpleMap<Uint8Array>;
notificationsPart?: CalendarNotificationSettings[];
}
export const formatData = ({
sharedSignedPart,
sharedEncryptedPart,
sharedSessionKey,
calendarSignedPart,
calendarEncryptedPart,
calendarSessionKey,
notificationsPart,
attendeesEncryptedPart,
attendeesClearPart,
removedAttendeesEmails,
attendeesEncryptedSessionKeysMap,
}: FormatDataArguments) => {
const result: Omit<CreateOrUpdateCalendarEventData, 'Permissions'> = {
Notifications: notificationsPart || null,
};
if (sharedSessionKey) {
result.SharedKeyPacket = uint8ArrayToBase64String(sharedSessionKey);
}
if (sharedSignedPart && sharedEncryptedPart) {
result.SharedEventContent = [
{
Type: SIGNED,
Data: sharedSignedPart.data,
Signature: sharedSignedPart.signature,
},
{
Type: ENCRYPTED_AND_SIGNED,
Data: uint8ArrayToBase64String(sharedEncryptedPart.dataPacket),
Signature: sharedEncryptedPart.signature,
},
];
}
if (calendarEncryptedPart && calendarSessionKey) {
result.CalendarKeyPacket = uint8ArrayToBase64String(calendarSessionKey);
}
if (calendarSignedPart || calendarEncryptedPart) {
result.CalendarEventContent = [
calendarSignedPart && {
Type: SIGNED,
Data: calendarSignedPart.data,
Signature: calendarSignedPart.signature,
},
calendarEncryptedPart && {
Type: ENCRYPTED_AND_SIGNED,
Data: uint8ArrayToBase64String(calendarEncryptedPart.dataPacket),
Signature: calendarEncryptedPart.signature,
},
].filter(isTruthy);
}
if (attendeesEncryptedPart) {
result.AttendeesEventContent = [
{
Type: ENCRYPTED_AND_SIGNED,
Data: uint8ArrayToBase64String(attendeesEncryptedPart.dataPacket),
Signature: attendeesEncryptedPart.signature,
},
];
}
if (attendeesClearPart) {
result.Attendees = attendeesClearPart.map(({ token, status }) => ({
Token: token,
Status: status,
}));
}
if (removedAttendeesEmails?.length) {
result.RemovedAttendeeAddresses = removedAttendeesEmails;
}
if (attendeesEncryptedSessionKeysMap) {
result.AddedProtonAttendees = Object.keys(attendeesEncryptedSessionKeysMap)
.map((email) => {
const sharedEncryptedSessionKey = attendeesEncryptedSessionKeysMap[email];
if (!sharedEncryptedSessionKey) {
return;
}
return { Email: email, AddressKeyPacket: uint8ArrayToBase64String(sharedEncryptedSessionKey) };
})
.filter(isTruthy);
}
return result;
};
| 8,336 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/getComponentFromCalendarEvent.ts | import { CalendarEvent, SharedVcalVeventComponent } from '../interfaces/calendar';
import { CALENDAR_CARD_TYPE } from './constants';
import { unwrap } from './helper';
import { parse } from './vcal';
const { CLEAR_TEXT, SIGNED } = CALENDAR_CARD_TYPE;
const getComponentFromCalendarEvent = (eventData: CalendarEvent): SharedVcalVeventComponent => {
const unencryptedPart = eventData.SharedEvents.find(({ Type }) => [CLEAR_TEXT, SIGNED].includes(Type));
if (!unencryptedPart) {
throw new Error('Missing unencrypted part');
}
return parse(unwrap(unencryptedPart.Data)) as SharedVcalVeventComponent;
};
export default getComponentFromCalendarEvent;
| 8,337 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/getMemberWithAdmin.ts | import { hasBit } from '../helpers/bitset';
import { Address as AddressInterface } from '../interfaces';
import { CalendarMember as MemberInterface } from '../interfaces/calendar';
import { CALENDAR_PERMISSIONS } from './constants';
export const getMemberAddressWithAdminPermissions = (Members: MemberInterface[], Addresses: AddressInterface[]) => {
const Member = Members.find(({ Email: MemberEmail, Permissions }) => {
return hasBit(Permissions, CALENDAR_PERMISSIONS.ADMIN) && Addresses.find(({ Email }) => MemberEmail === Email);
});
if (!Member) {
throw new Error('Member with admin permission not found');
}
const Address = Addresses.find(({ Email }) => Member.Email === Email);
if (!Address) {
throw new Error('Address for member not found');
}
return {
Member,
Address,
};
};
| 8,338 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/getSettings.ts | import { CalendarUserSettings } from '../interfaces/calendar';
import { SETTINGS_VIEW, VIEWS } from './constants';
export const getAutoDetectPrimaryTimezone = (calendarUserSettings: CalendarUserSettings) => {
return !!calendarUserSettings.AutoDetectPrimaryTimezone;
};
export const getDisplaySecondaryTimezone = (calendarUserSettings: CalendarUserSettings) => {
return !!calendarUserSettings.DisplaySecondaryTimezone;
};
export const getSecondaryTimezone = (calendarUserSettings: CalendarUserSettings) => {
return calendarUserSettings.SecondaryTimezone;
};
export const getDisplayWeekNumbers = (calendarUserSettings: CalendarUserSettings) => {
return !!calendarUserSettings.DisplayWeekNumber;
};
export const getDefaultCalendarID = (calendarUserSettings: CalendarUserSettings) => {
// DefaultCalendarID is either null or a string
return calendarUserSettings.DefaultCalendarID || undefined;
};
export const getInviteLocale = (calendarUserSettings: CalendarUserSettings) => {
// InviteLocale is either null or a string
return calendarUserSettings.InviteLocale || undefined;
};
export const getDefaultTzid = (calendarUserSettings: CalendarUserSettings, defaultTimezone: string) => {
const primaryTimezone = calendarUserSettings.PrimaryTimezone;
return primaryTimezone || defaultTimezone;
};
const SETTINGS_VIEW_CONVERSION = {
[SETTINGS_VIEW.YEAR]: VIEWS.WEEK,
[SETTINGS_VIEW.PLANNING]: VIEWS.WEEK,
[SETTINGS_VIEW.MONTH]: VIEWS.MONTH,
[SETTINGS_VIEW.WEEK]: VIEWS.WEEK,
[SETTINGS_VIEW.DAY]: VIEWS.DAY,
};
export const getDefaultView = (calendarUserSettings: CalendarUserSettings) => {
return SETTINGS_VIEW_CONVERSION[calendarUserSettings?.ViewPreference] || VIEWS.WEEK;
};
| 8,339 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/helper.ts | import { c } from 'ttag';
import { CryptoProxy } from '@proton/crypto';
import { arrayToHexString, binaryStringToArray } from '@proton/crypto/lib/utils';
import { API_CODES } from '../constants';
import { encodeBase64URL, uint8ArrayToString } from '../helpers/encoding';
import {
SyncMultipleApiResponses,
SyncMultipleApiSuccessResponses,
VcalDateOrDateTimeProperty,
VcalDateTimeProperty,
} from '../interfaces/calendar';
import { ACTION_VIEWS, MAXIMUM_DATE_UTC, MAX_CHARS_API, MINIMUM_DATE_UTC } from './constants';
import { propertyToUTCDate } from './vcalConverter';
import { getIsPropertyAllDay } from './vcalHelper';
export const HASH_UID_PREFIX = 'sha1-uid-';
export const ORIGINAL_UID_PREFIX = 'original-uid-';
export const getIsSuccessSyncApiResponse = (
response: SyncMultipleApiResponses
): response is SyncMultipleApiSuccessResponses => {
const {
Response: { Code, Event },
} = response;
return Code === API_CODES.SINGLE_SUCCESS && !!Event;
};
/**
* Generates a calendar UID of the form '[email protected]'
* RandomBase64String has a length of 28 characters
*/
export const generateProtonCalendarUID = () => {
// by convention we generate 21 bytes of random data
const randomBytes = crypto.getRandomValues(new Uint8Array(21));
const base64String = encodeBase64URL(uint8ArrayToString(randomBytes));
// and we encode them in base 64
return `${base64String}@proton.me`;
};
export const generateVeventHashUID = async (binaryString: string, uid = '', legacyFormat = false) => {
const hash = arrayToHexString(
await CryptoProxy.computeHash({ algorithm: 'unsafeSHA1', data: binaryStringToArray(binaryString) })
);
const hashUid = `${HASH_UID_PREFIX}${hash}`;
if (!uid) {
return hashUid;
}
const join = '-';
const uidLength = uid.length;
const availableLength = MAX_CHARS_API.UID - ORIGINAL_UID_PREFIX.length - hashUid.length - join.length;
const croppedUID = uid.substring(uidLength - availableLength, uidLength);
return legacyFormat
? `${hashUid}${join}${ORIGINAL_UID_PREFIX}${croppedUID}`
: `${ORIGINAL_UID_PREFIX}${croppedUID}${join}${hashUid}`;
};
export const getOriginalUID = (uid = '') => {
if (!uid) {
return '';
}
const regexWithOriginalUid = new RegExp(`^${ORIGINAL_UID_PREFIX}(.+)-${HASH_UID_PREFIX}[abcdef\\d]{40}`);
const regexWithOriginalUidLegacyFormat = new RegExp(
`^${HASH_UID_PREFIX}[abcdef\\d]{40}-${ORIGINAL_UID_PREFIX}(.+)`
);
const [, match] = uid.match(regexWithOriginalUid) || uid.match(regexWithOriginalUidLegacyFormat) || [];
if (match) {
return match;
}
const regexWithoutOriginalUid = new RegExp(`^${HASH_UID_PREFIX}[abcdef\\d]{40}$`);
if (regexWithoutOriginalUid.test(uid)) {
return '';
}
return uid;
};
export const getHasLegacyHashUID = (uid = '') => {
if (!uid) {
return false;
}
return new RegExp(`^${HASH_UID_PREFIX}[abcdef\\d]{40}-${ORIGINAL_UID_PREFIX}`).test(uid);
};
export const getSupportedUID = (uid: string) => {
const uidLength = uid.length;
return uid.substring(uidLength - MAX_CHARS_API.UID, uidLength);
};
const getIsWellFormedDateTime = (property: VcalDateTimeProperty) => {
return property.value.isUTC || !!property.parameters!.tzid;
};
export const getIsWellFormedDateOrDateTime = (property: VcalDateOrDateTimeProperty) => {
return getIsPropertyAllDay(property) || getIsWellFormedDateTime(property);
};
export const getIsDateOutOfBounds = (property: VcalDateOrDateTimeProperty) => {
const dateUTC: Date = propertyToUTCDate(property);
return +dateUTC < +MINIMUM_DATE_UTC || +dateUTC > +MAXIMUM_DATE_UTC;
};
/**
* Try to guess from the event uid if an event was generated by Proton. In pple there are two possibilities
* * Old uids of the form 'proton-calendar-350095ea-4368-26f0-4fc9-60a56015b02e' and derived ones from "this and future" editions
* * New uids of the form '[email protected]' and derived ones from "this and future" editions
*/
export const getIsProtonUID = (uid = '') => {
return uid.endsWith('@proton.me') || uid.startsWith('proton-calendar-');
};
export const getDisplayTitle = (title = '') => {
return title.trim() || c('Event title').t`(no title)`;
};
/**
* Check whether an object has more keys than a set of keys.
*/
export const hasMoreThan = (set: Set<string>, properties: { [key: string]: any } = {}) => {
return Object.keys(properties).some((key) => !set.has(key));
};
export const wrap = (res: string, prodId?: string) => {
// Wrap in CRLF according to the rfc
return prodId
? `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:${prodId}\r\n${res}\r\nEND:VCALENDAR`
: `BEGIN:VCALENDAR\r\nVERSION:2.0\r\n${res}\r\nEND:VCALENDAR`;
};
export const unwrap = (res: string) => {
if (res.slice(0, 15) !== 'BEGIN:VCALENDAR') {
return res;
}
const startIdx = res.indexOf('BEGIN:', 1);
if (startIdx === -1 || startIdx === 0) {
return '';
}
const endIdx = res.lastIndexOf('END:VCALENDAR');
return res.slice(startIdx, endIdx).trim();
};
export const getLinkToCalendarEvent = ({
calendarID,
eventID,
recurrenceID,
}: {
calendarID: string;
eventID: string;
recurrenceID?: number;
}) => {
const params = new URLSearchParams();
params.set('Action', ACTION_VIEWS.VIEW);
params.set('EventID', eventID);
params.set('CalendarID', calendarID);
if (recurrenceID) {
params.set('RecurrenceID', `${recurrenceID}`);
}
return `/event?${params.toString()}`;
};
export const naiveGetIsDecryptionError = (error: any) => {
// We sometimes need to detect if an error produced while reading an event is due to a failed decryption.
// We don't have a great way of doing this as the error comes from openpgp
const errorMessage = error?.message || '';
return errorMessage.toLowerCase().includes('decrypt');
};
| 8,340 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/members.ts | import { Address as AddressInterface } from '../interfaces';
import { CalendarMember as MemberInterface } from '../interfaces/calendar';
export const getMemberAndAddress = (
Addresses: AddressInterface[] = [],
Members: MemberInterface[] = [],
Author = ''
): [MemberInterface, AddressInterface] => {
if (!Members.length) {
throw new Error('No members');
}
if (!Addresses.length) {
throw new Error('No addresses');
}
// First try to find self by author to use the same address.
const selfAddress = Addresses.find((Address) => Address.Email === Author);
const selfMember = selfAddress ? Members.find((Member) => Member.Email === selfAddress.Email) : undefined;
if (selfMember && selfAddress) {
return [selfMember, selfAddress];
}
// Otherwise just use the first member. It is assumed the list of members only contain yourself.
const [defaultMember] = Members;
const Address = Addresses.find(({ Email }) => defaultMember.Email === Email);
if (!Address) {
throw new Error('Self as member not found');
}
return [defaultMember, Address];
};
| 8,341 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/permissions.ts | import { CALENDAR_PERMISSIONS } from '@proton/shared/lib/calendar/constants';
import { hasBit } from '@proton/shared/lib/helpers/bitset';
const { SUPER_OWNER, OWNER, ADMIN, READ_MEMBER_LIST, WRITE, READ, AVAILABILITY } = CALENDAR_PERMISSIONS;
export const MEMBER_PERMISSIONS = {
OWNS: SUPER_OWNER + OWNER + ADMIN + READ_MEMBER_LIST + WRITE + READ + AVAILABILITY,
EDIT: WRITE + READ + AVAILABILITY,
FULL_VIEW: READ + AVAILABILITY,
LIMITED: AVAILABILITY,
};
export const getCanWrite = (permissions: CALENDAR_PERMISSIONS) => {
return hasBit(permissions, WRITE);
};
| 8,342 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/plans.ts | import { PLAN_SERVICES, PLAN_TYPES } from '../constants';
import { hasBit } from '../helpers/bitset';
import { Api, Plan, PlanIDs } from '../interfaces';
import { CalendarWithOwnMembers } from '../interfaces/calendar';
import { MAX_CALENDARS_FREE } from './constants';
import getHasSharedCalendars from './sharing/getHasSharedCalendars';
export const willHavePaidMail = (planIDs: PlanIDs, plans: Plan[]) => {
const newPlanName = Object.keys(planIDs).find((planName) =>
plans.find((plan) => plan.Type === PLAN_TYPES.PLAN && plan.Name === planName)
);
const newPlan = plans.find((plan) => plan.Name === newPlanName);
return hasBit(newPlan?.Services, PLAN_SERVICES.MAIL);
};
export const getShouldCalendarPreventSubscripitionChange = async ({
hasPaidMail,
willHavePaidMail,
api,
getCalendars,
}: {
hasPaidMail: boolean;
willHavePaidMail: boolean;
api: Api;
getCalendars: () => Promise<CalendarWithOwnMembers[] | undefined>;
}) => {
if (!hasPaidMail || willHavePaidMail) {
// We only prevent subscription change when downgrading the paid-mail condition
return false;
}
const calendars = (await getCalendars()) || [];
const hasSharedCalendars = await getHasSharedCalendars({ calendars, api, catchErrors: true });
return calendars.length > MAX_CALENDARS_FREE || hasSharedCalendars;
};
| 8,343 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/sanitize.ts | import DOMPurify from 'dompurify';
DOMPurify.addHook('afterSanitizeAttributes', (node) => {
if (node.tagName === 'A') {
node.setAttribute('rel', 'noopener noreferrer');
node.setAttribute('target', '_blank');
}
});
export const restrictedCalendarSanitize = (source: string) => {
return DOMPurify.sanitize(source, {
ALLOWED_TAGS: ['a', 'b', 'em', 'br', 'i', 'u', 'ul', 'ol', 'li', 'span', 'p'],
ALLOWED_ATTR: ['href'],
});
};
export const stripAllTags = (source: string) => {
const html = restrictedCalendarSanitize(source);
const div = document.createElement('DIV');
div.style.whiteSpace = 'pre-wrap';
div.innerHTML = html;
div.querySelectorAll('a').forEach((element) => {
element.innerText = element.href || element.innerText;
});
// Append it to force a layout pass so that innerText returns newlines
document.body.appendChild(div);
const result = div.innerText;
document.body.removeChild(div);
return result;
};
| 8,344 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/serialize.ts | import { PrivateKeyReference, PublicKeyReference, SessionKey } from '@proton/crypto';
import { VcalVeventComponent } from '../interfaces/calendar';
import { SimpleMap } from '../interfaces/utils';
import { CALENDAR_CARD_TYPE } from './constants';
import {
createSessionKey,
encryptPart,
getEncryptedSessionKey,
getEncryptedSessionKeysMap,
signPart,
} from './crypto/encrypt';
import { formatData } from './formatData';
import { getIsEventComponent } from './vcalHelper';
import { getVeventParts } from './veventHelper';
const { ENCRYPTED_AND_SIGNED, SIGNED, CLEAR_TEXT } = CALENDAR_CARD_TYPE;
/**
* Split the properties of the component into parts.
*/
const getParts = (eventComponent: VcalVeventComponent) => {
if (!getIsEventComponent(eventComponent)) {
throw new Error('Type other than vevent not supported');
}
return getVeventParts(eventComponent);
};
/**
* Create a calendar event by encrypting and serializing an internal vcal component.
*/
interface CreateCalendarEventArguments {
eventComponent: VcalVeventComponent;
publicKey: PublicKeyReference;
privateKey: PrivateKeyReference;
sharedSessionKey?: SessionKey;
calendarSessionKey?: SessionKey;
isCreateEvent: boolean;
isSwitchCalendar: boolean;
hasDefaultNotifications: boolean;
isAttendee?: boolean;
removedAttendeesEmails?: string[];
addedAttendeesPublicKeysMap?: SimpleMap<PublicKeyReference>;
}
export const createCalendarEvent = async ({
eventComponent,
publicKey,
privateKey,
sharedSessionKey: oldSharedSessionKey,
calendarSessionKey: oldCalendarSessionKey,
isCreateEvent,
isSwitchCalendar,
hasDefaultNotifications,
isAttendee,
removedAttendeesEmails = [],
addedAttendeesPublicKeysMap,
}: CreateCalendarEventArguments) => {
const { sharedPart, calendarPart, notificationsPart, attendeesPart } = getParts(eventComponent);
const isCreateOrSwitchCalendar = isCreateEvent || isSwitchCalendar;
const isAttendeeSwitchingCalendar = isSwitchCalendar && isAttendee;
// If there is no encrypted calendar part, a calendar session key is not needed.
const shouldHaveCalendarKey = !!calendarPart[ENCRYPTED_AND_SIGNED];
const [calendarSessionKey, sharedSessionKey] = await Promise.all([
shouldHaveCalendarKey ? oldCalendarSessionKey || createSessionKey(publicKey) : undefined,
oldSharedSessionKey || createSessionKey(publicKey),
]);
const [
encryptedCalendarSessionKey,
encryptedSharedSessionKey,
sharedSignedPart,
sharedEncryptedPart,
calendarSignedPart,
calendarEncryptedPart,
attendeesEncryptedPart,
attendeesEncryptedSessionKeysMap,
] = await Promise.all([
// If we're updating an event (but not switching calendar), no need to encrypt again the session keys
isCreateOrSwitchCalendar && calendarSessionKey
? getEncryptedSessionKey(calendarSessionKey, publicKey)
: undefined,
isCreateOrSwitchCalendar ? getEncryptedSessionKey(sharedSessionKey, publicKey) : undefined,
// attendees are not allowed to change the SharedEventContent, so they shouldn't send it (API will complain otherwise)
isAttendeeSwitchingCalendar ? undefined : signPart(sharedPart[SIGNED], privateKey),
isAttendeeSwitchingCalendar
? undefined
: encryptPart(sharedPart[ENCRYPTED_AND_SIGNED], privateKey, sharedSessionKey),
signPart(calendarPart[SIGNED], privateKey),
calendarSessionKey && encryptPart(calendarPart[ENCRYPTED_AND_SIGNED], privateKey, calendarSessionKey),
// attendees are not allowed to change the SharedEventContent, so they shouldn't send it (API will complain otherwise)
isAttendeeSwitchingCalendar
? undefined
: encryptPart(attendeesPart[ENCRYPTED_AND_SIGNED], privateKey, sharedSessionKey),
getEncryptedSessionKeysMap(sharedSessionKey, addedAttendeesPublicKeysMap),
]);
return formatData({
sharedSignedPart,
sharedEncryptedPart,
sharedSessionKey: encryptedSharedSessionKey,
calendarSignedPart,
calendarEncryptedPart,
calendarSessionKey: encryptedCalendarSessionKey,
notificationsPart: hasDefaultNotifications ? undefined : notificationsPart,
attendeesEncryptedPart,
attendeesClearPart: isAttendeeSwitchingCalendar ? undefined : attendeesPart[CLEAR_TEXT],
removedAttendeesEmails,
attendeesEncryptedSessionKeysMap,
});
};
| 8,345 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/settingsRoutes.ts | import { getSlugFromApp } from '@proton/shared/lib/apps/slugHelper';
import { CALENDAR_SETTINGS_ROUTE } from '@proton/shared/lib/calendar/constants';
import { APPS } from '@proton/shared/lib/constants';
import { validateBase64string } from '@proton/shared/lib/helpers/encoding';
interface GetPathOptions {
fullPath?: boolean;
sectionId?: string;
}
const getPathWithOptions = (relativePath: string, options?: GetPathOptions) => {
const { fullPath, sectionId } = options || {};
let path = `${relativePath}`;
if (fullPath) {
path = `/${getSlugFromApp(APPS.PROTONCALENDAR)}${path}`;
}
if (sectionId) {
path = `${path}#${sectionId}`;
}
return path;
};
export const getGeneralSettingsPath = (options?: GetPathOptions) => {
return getPathWithOptions(CALENDAR_SETTINGS_ROUTE.GENERAL, options);
};
export const getCalendarsSettingsPath = (options?: GetPathOptions) => {
return getPathWithOptions(CALENDAR_SETTINGS_ROUTE.CALENDARS, options);
};
export const getInteroperabilityOperationsPath = (options?: GetPathOptions) => {
return getPathWithOptions(CALENDAR_SETTINGS_ROUTE.INTEROPS, options);
};
export const getCalendarSubpagePath = (calendarID: string, options?: GetPathOptions) => {
return getPathWithOptions(`${getCalendarsSettingsPath()}/${calendarID}`, options);
};
export const getIsCalendarSubpage = (pathname: string, calendarsSectionTo: string) => {
// The calendar subpage is accessed via /calendar/calendars/calendarId
const calendarsSectionPath = `/${getSlugFromApp(APPS.PROTONCALENDAR)}${calendarsSectionTo}`;
const regexString = `^${calendarsSectionPath}/(.*)`.replaceAll('/', '\\/');
const match = (new RegExp(regexString).exec(pathname) || [])[1];
if (!match) {
return false;
}
return validateBase64string(match, true);
};
| 8,346 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/urlify.ts | // eslint-disable-next-line no-useless-escape
const URL_REGEX = /(\b(?:https|ftps|file|mailto|tel|sms):(?:(?!["<>\^`{|}])\S)+)/gi;
const A_TAG_REGEX = /(<a[^>]+>.+?<\/a>)/gi;
const urlify = (string: string) =>
string
.split(A_TAG_REGEX)
.map((piece) => {
if (piece.match(A_TAG_REGEX)) {
return piece;
}
return piece.replace(URL_REGEX, '<a href="$1">$1</a>');
})
.join('');
export default urlify;
| 8,347 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/valarmHelper.ts | import { buildMailTo } from '../helpers/email';
import { VcalValarmComponent } from '../interfaces/calendar';
import { ICAL_ALARM_ACTION } from './constants';
import { getSupportedAlarmAction } from './icsSurgery/valarm';
/**
* Helper that takes a vAlarm as it's persisted in our database and returns one that is RFC-compatible for PUBLISH method
*
* A description field, as well as summary and attendee fields for email alarms, are mandatory on RFC-5545 (https://datatracker.ietf.org/doc/html/rfc5545#section-3.6.6).
* Although we don't store them internally, we need to add them when exporting to other providers. According to the RFC:
*/
export const withMandatoryPublishFields = (
valarm: VcalValarmComponent,
eventTitle: string,
calendarEmail: string
): VcalValarmComponent => {
if (getSupportedAlarmAction(valarm.action).value === ICAL_ALARM_ACTION.EMAIL) {
return {
summary: { value: eventTitle }, // <<contains the text to be used as the message subject>>
description: { value: eventTitle }, // <<contains the text to be used as the message body>>
attendee: [{ value: buildMailTo(calendarEmail) }], // <<contain the email address of attendees to receive the message>>
...valarm,
};
}
return {
description: { value: eventTitle }, // <<contains the text to be displayed when the alarm is triggered>>
...valarm,
};
};
| 8,348 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/vcal.ts | /**
* This file needs to be improved in terms of typing. They were rushed due to time constraints.
*/
import ICAL from 'ical.js';
import { parseWithRecovery } from '@proton/shared/lib/calendar/icsSurgery/ics';
import { DAY, HOUR, MINUTE, SECOND, WEEK } from '../constants';
import {
VcalCalendarComponent,
VcalCalendarComponentWithMaybeErrors,
VcalDateOrDateTimeValue,
VcalDateTimeValue,
VcalDateValue,
VcalDurationValue,
VcalErrorComponent,
VcalRrulePropertyValue,
VcalValarmComponent,
VcalVcalendar,
VcalVcalendarWithMaybeErrors,
VcalVeventComponent,
VcalVeventComponentWithMaybeErrors,
} from '../interfaces/calendar';
import { UNIQUE_PROPERTIES } from './vcalDefinition';
import { getIsVcalErrorComponent } from './vcalHelper';
const getIcalDateValue = (value: any, tzid: string | undefined, isDate: boolean) => {
const icalTimezone = value.isUTC ? ICAL.Timezone.utcTimezone : ICAL.Timezone.localTimezone;
const icalData = {
year: value.year,
month: value.month,
day: value.day,
hour: value.hours || 0,
minute: value.minutes || 0,
second: value.seconds || 0,
isDate,
};
return ICAL.Time.fromData(icalData, icalTimezone);
};
const getIcalPeriodValue = (value: any, tzid: string | undefined) => {
return ICAL.Period.fromData({
// periods must be of date-time
start: value.start ? getIcalDateValue(value.start, tzid, false) : undefined,
end: value.end ? getIcalDateValue(value.end, tzid, false) : undefined,
duration: value.duration ? ICAL.Duration.fromData(value.duration) : undefined,
});
};
const getIcalDurationValue = (value?: any) => {
return ICAL.Duration.fromData(value);
};
const getIcalUntilValue = (value?: any) => {
if (!value) {
return;
}
return getIcalDateValue(value, '', typeof value.hours === 'undefined');
};
export const internalValueToIcalValue = (type: string, value: any, { tzid }: { tzid?: string } = {}) => {
if (Array.isArray(value)) {
return value;
}
if (typeof value === 'string') {
return value;
}
if (type === 'date' || type === 'date-time') {
return getIcalDateValue(value, tzid, type === 'date');
}
if (type === 'duration') {
return getIcalDurationValue(value);
}
if (type === 'period') {
return getIcalPeriodValue(value, tzid);
}
if (type === 'recur') {
if (!value.until) {
return ICAL.Recur.fromData(value);
}
const until = getIcalUntilValue(value.until);
return ICAL.Recur.fromData({ ...value, until });
}
return value.toString();
};
const getInternalDateValue = (value: any): VcalDateValue => {
return {
year: value.year,
month: value.month,
day: value.day,
};
};
export const getInternalDateTimeValue = (value: any): VcalDateTimeValue => {
return {
...getInternalDateValue(value),
hours: value.hour,
minutes: value.minute,
seconds: value.second,
isUTC: value.zone.tzid === 'UTC',
};
};
const getInternalDurationValue = (value: any): VcalDurationValue => {
return {
weeks: value.weeks,
days: value.days,
hours: value.hours,
minutes: value.minutes,
seconds: value.seconds,
isNegative: value.isNegative,
};
};
const getInternalUntil = (value?: any): VcalDateOrDateTimeValue | undefined => {
if (!value) {
return;
}
return value.icaltype === 'date' ? getInternalDateValue(value) : getInternalDateTimeValue(value);
};
const getInternalRecur = (value?: any): VcalRrulePropertyValue | undefined => {
if (!value) {
return;
}
const result = {
...value.toJSON(),
};
// COUNT = 0 gets ignored in the above step
if (value.count === 0) {
result.count = 0;
}
const until = getInternalUntil(value.until);
if (until) {
result.until = until;
}
return result;
};
/**
* Convert from ical.js format to an internal format
*/
export const icalValueToInternalValue = (type: string, value: any) => {
if (Array.isArray(value)) {
return value;
}
if (typeof value === 'string' || type === 'integer') {
return value;
}
if (type === 'date') {
return getInternalDateValue(value);
}
if (type === 'date-time') {
return getInternalDateTimeValue(value);
}
if (type === 'duration') {
return getInternalDurationValue(value);
}
if (type === 'period') {
const result: any = {};
if (value.start) {
result.start = getInternalDateTimeValue(value.start);
}
if (value.end) {
result.end = getInternalDateTimeValue(value.end);
}
if (value.duration) {
result.duration = getInternalDurationValue(value.duration);
}
return result;
}
if (type === 'recur') {
return getInternalRecur(value);
}
return value.toString();
};
/**
* Get an ical property.
*/
const getProperty = (name: string, { value, parameters }: any) => {
const property = new ICAL.Property(name);
const { type: specificType, ...restParameters } = parameters || {};
if (specificType) {
property.resetType(specificType);
}
const type = specificType || property.type;
if (property.isMultiValue && Array.isArray(value)) {
property.setValues(value.map((val) => internalValueToIcalValue(type, val, restParameters)));
} else {
property.setValue(internalValueToIcalValue(type, value, restParameters));
}
Object.keys(restParameters).forEach((key) => {
property.setParameter(key, restParameters[key]);
});
return property;
};
const addInternalProperties = (component: any, properties: any) => {
Object.keys(properties).forEach((name) => {
const jsonProperty = properties[name];
if (Array.isArray(jsonProperty)) {
jsonProperty.forEach((property) => {
component.addProperty(getProperty(name, property));
});
return;
}
component.addProperty(getProperty(name, jsonProperty));
});
return component;
};
const fromInternalComponent = (properties: any) => {
const { component: name, components, ...restProperties } = properties;
const component = addInternalProperties(new ICAL.Component(name), restProperties);
if (Array.isArray(components)) {
components.forEach((otherComponent) => {
component.addSubcomponent(fromInternalComponent(otherComponent));
});
}
return component;
};
export const serialize = (component: any) => {
return fromInternalComponent(component).toString();
};
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 checkIfDateOrDateTimeValid = (dateOrDateTimeString: string, isDateType = false) => {
if (/--/.test(dateOrDateTimeString)) {
// just to be consistent with error messages from ical.js
const message = isDateType ? 'could not extract integer from' : 'invalid date-time value';
throw new Error(message);
}
};
const fromIcalProperties = (properties = []) => {
if (properties.length === 0) {
return;
}
return properties.reduce<{ [key: string]: any }>((acc, property: any) => {
const { name } = property;
if (!name) {
return acc;
}
const { type } = property;
if (['date-time', 'date'].includes(type)) {
checkIfDateOrDateTimeValid(property.toJSON()[3], type === 'date');
}
const values = property.getValues().map((value: any) => icalValueToInternalValue(type, value));
const parameters = getParameters(type, property);
const propertyAsObject = {
value: property.isMultiValue ? values : values[0],
...(Object.keys(parameters).length && { parameters }),
};
if (UNIQUE_PROPERTIES.has(name)) {
acc[name] = propertyAsObject;
return acc;
}
if (!acc[name]) {
acc[name] = [];
}
// Exdate can be both an array and multivalue, force it to only be an array
if (name === 'exdate') {
const normalizedValues = values.map((value: any) => ({ ...propertyAsObject, value }));
acc[name] = acc[name].concat(normalizedValues);
} else {
acc[name].push(propertyAsObject);
}
return acc;
}, {});
};
export const fromIcalComponent = (component: any) => {
const components = component.getAllSubcomponents().map(fromIcalComponent);
return {
component: component.name,
...(components.length && { components }),
...fromIcalProperties(component ? component.getAllProperties() : undefined),
} as VcalCalendarComponent;
};
export const fromIcalComponentWithMaybeErrors = (
component: any
): VcalCalendarComponentWithMaybeErrors | VcalErrorComponent => {
const components = component.getAllSubcomponents().map((subcomponent: any) => {
try {
return fromIcalComponentWithMaybeErrors(subcomponent);
} catch (error: any) {
return { error, icalComponent: subcomponent };
}
});
return {
component: component.name,
...(components.length && { components }),
...fromIcalProperties(component ? component.getAllProperties() : undefined),
} as VcalCalendarComponentWithMaybeErrors;
};
/**
* Parse vCalendar String and return a component
*/
export const parse = (vcal = ''): VcalCalendarComponent => {
if (!vcal) {
return {} as VcalCalendarComponent;
}
return fromIcalComponent(new ICAL.Component(ICAL.parse(vcal))) as VcalCalendarComponent;
};
/**
* Same as the parseWithRecovery function, but catching errors in individual components.
* This is useful in case we can parse some events but not all in a given ics
*/
export const parseWithRecoveryAndMaybeErrors = (
vcal: string,
retry?: {
retryLineBreaks?: boolean;
retryEnclosing?: boolean;
retryDateTimes?: boolean;
retryOrganizer?: boolean;
}
): VcalVcalendarWithMaybeErrors | VcalCalendarComponentWithMaybeErrors => {
try {
return parseWithRecovery(vcal, retry) as VcalVcalendar;
} catch (e) {
return fromIcalComponentWithMaybeErrors(new ICAL.Component(ICAL.parse(vcal))) as
| VcalVcalendarWithMaybeErrors
| VcalCalendarComponentWithMaybeErrors;
}
};
export const getVeventWithoutErrors = (
veventWithMaybeErrors: VcalVeventComponentWithMaybeErrors
): VcalVeventComponent => {
const filteredComponents: VcalValarmComponent[] | undefined = veventWithMaybeErrors.components?.filter(
(component): component is VcalValarmComponent => !getIsVcalErrorComponent(component)
);
return {
...veventWithMaybeErrors,
components: filteredComponents,
};
};
export const fromRruleString = (rrule = '') => {
return getInternalRecur(ICAL.Recur.fromString(rrule));
};
/**
* Parse a trigger string (e.g. '-PT15M') and return an object indicating its duration
*/
export const fromTriggerString = (trigger = '') => {
return getInternalDurationValue(ICAL.Duration.fromString(trigger));
};
export const toTriggerString = (value: VcalDurationValue): string => {
return getIcalDurationValue(value).toString();
};
/**
* Transform a duration object into milliseconds
*/
export const durationToMilliseconds = ({
isNegative = false,
weeks = 0,
days = 0,
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0,
}) => {
const lapse = weeks * WEEK + days * DAY + hours * HOUR + minutes * MINUTE + seconds * SECOND + milliseconds;
return isNegative ? -lapse : lapse;
};
/**
* Parse a trigger string (e.g. '-PT15M') and return its duration in milliseconds
*/
export const getMillisecondsFromTriggerString = (trigger = '') => {
return durationToMilliseconds(fromTriggerString(trigger));
};
| 8,349 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/vcalConfig.ts | import { getClientID } from '../apps/helper';
import { ProtonConfig } from '../interfaces';
/**
* Given an app config the prodId is fixed, so it's convenient to have
* it as a mutable export, then set it when the app is loaded
*/
export let prodId = '';
export const setVcalProdId = (value: string) => {
prodId = value;
};
export const getProdIdFromNameAndVersion = (id: string, version: string) => `-//Proton AG//${id} ${version}//EN`;
export const getProdId = (config: ProtonConfig) => {
const { APP_NAME, APP_VERSION: appVersion } = config;
const clientID = getClientID(APP_NAME);
return getProdIdFromNameAndVersion(clientID, appVersion);
};
| 8,350 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/vcalConverter.ts | import mod from '@proton/utils/mod';
import { addDays, isNextDay } from '../date-fns-utc';
import {
convertUTCDateTimeToZone,
convertZonedDateTimeToUTC,
fromUTCDate,
toLocalDate,
toUTCDate,
} from '../date/timezone';
import { buildMailTo, canonicalizeEmail, getEmailTo } from '../helpers/email';
import {
DateTime,
Participant,
VcalAttendeeProperty,
VcalDateOrDateTimeProperty,
VcalDateOrDateTimeValue,
VcalDateProperty,
VcalDateTimeProperty,
VcalDays,
VcalDaysKeys,
VcalOrganizerProperty,
VcalVeventComponent,
} from '../interfaces/calendar';
import { getAttendeeEmail } from './attendees';
import { getIsPropertyAllDay, getPropertyTzid } from './vcalHelper';
export const dateToProperty = ({
year = 1,
month = 1,
day = 1,
}: {
year: number;
month: number;
day: number;
}): VcalDateProperty => {
return {
value: { year, month, day },
parameters: { type: 'date' },
};
};
export const dateTimeToProperty = (
{ year = 1, month = 1, day = 1, hours = 0, minutes = 0, seconds = 0 }: DateTime,
isUTC = false,
tzid?: string
): VcalDateTimeProperty => {
const value = { year, month, day, hours, minutes, seconds, isUTC };
if (!tzid || isUTC) {
return {
value,
};
}
return {
value,
parameters: {
tzid,
},
};
};
export const getDateProperty = ({ year, month, day }: { year: number; month: number; day: number }) => {
return dateToProperty({ year, month, day });
};
export const getDateTimeProperty = (zonelessTime: DateTime, tzid = '') => {
const isUTC = (tzid || '').toLowerCase().includes('utc');
return dateTimeToProperty(zonelessTime, isUTC, isUTC ? undefined : tzid);
};
export const getDateOrDateTimeProperty = (property: VcalDateOrDateTimeProperty, start: Date) => {
if (getIsPropertyAllDay(property)) {
return getDateProperty(fromUTCDate(start));
}
return getDateTimeProperty(fromUTCDate(start), getPropertyTzid(property));
};
export const propertyToLocalDate = (property: VcalDateOrDateTimeProperty) => {
if (getIsPropertyAllDay(property)) {
return toLocalDate(property.value);
}
if (property.value.isUTC || !property.parameters?.tzid) {
return toUTCDate(property.value);
}
// For dates with a timezone, convert the relative date time to UTC time
return toUTCDate(convertZonedDateTimeToUTC(property.value, property.parameters.tzid));
};
export const propertyToUTCDate = (property: VcalDateOrDateTimeProperty) => {
if (getIsPropertyAllDay(property) || property.value.isUTC || !property.parameters?.tzid) {
return toUTCDate(property.value);
}
// For dates with a timezone, convert the relative date time to UTC time
return toUTCDate(convertZonedDateTimeToUTC(property.value, property.parameters.tzid));
};
interface GetDtendPropertyArgs {
dtstart: VcalDateOrDateTimeProperty;
dtend?: VcalDateOrDateTimeProperty;
}
export const getDtendProperty = ({ dtstart, dtend }: GetDtendPropertyArgs) => {
if (dtend) {
return dtend;
}
if (getIsPropertyAllDay(dtstart)) {
const utcEnd = addDays(toUTCDate(dtstart.value), 1);
return getDateProperty(fromUTCDate(utcEnd));
}
return getDateTimeProperty(dtstart.value, getPropertyTzid(dtstart));
};
export const dayToNumericDay = (day: VcalDaysKeys): VcalDays | undefined => {
return VcalDays[day];
};
export const numericDayToDay = (number: VcalDays): VcalDaysKeys => {
if (number in VcalDays) {
return VcalDays[number] as VcalDaysKeys;
}
return VcalDays[mod(number, 7)] as VcalDaysKeys;
};
export const getDateTimePropertyInDifferentTimezone = (
property: VcalDateOrDateTimeProperty,
tzid: string,
isAllDay?: boolean
) => {
if (isAllDay === true || getIsPropertyAllDay(property)) {
return getDateProperty(property.value);
}
const utcDate = propertyToUTCDate(property);
const zonedDate = convertUTCDateTimeToZone(fromUTCDate(utcDate), tzid);
return getDateTimeProperty(zonedDate, tzid);
};
export const getAllDayInfo = (dtstart: VcalDateOrDateTimeProperty, dtend?: VcalDateOrDateTimeProperty) => {
const isAllDay = getIsPropertyAllDay(dtstart);
if (!isAllDay) {
return { isAllDay: false, isSingleAllDay: false };
}
if (!dtend) {
return { isAllDay: true, isSingleAllDay: true };
}
// For all-day events, we need fake UTC dates to determine if the event lasts a single day
const fakeUTCStart = toUTCDate(dtstart.value);
const fakeUTCEnd = toUTCDate(dtend.value);
// account for non-RFC-compliant all-day events with DTSTART = DTEND
return { isAllDay: true, isSingleAllDay: isNextDay(fakeUTCStart, fakeUTCEnd) || +fakeUTCStart === +fakeUTCEnd };
};
export interface UntilDateArgument {
year: number;
month: number;
day: number;
}
export const getUntilProperty = (
untilDateTime: UntilDateArgument,
isAllDay: boolean,
tzid = 'UTC'
): VcalDateOrDateTimeValue => {
// According to the RFC, we should use UTC dates if and only if the event is not all-day.
if (isAllDay) {
// we should use a floating date in this case
return {
year: untilDateTime.year,
month: untilDateTime.month,
day: untilDateTime.day,
};
}
// Pick end of day in the event start date timezone
const zonedEndOfDay = { ...untilDateTime, hours: 23, minutes: 59, seconds: 59 };
const utcEndOfDay = convertZonedDateTimeToUTC(zonedEndOfDay, tzid);
return { ...utcEndOfDay, isUTC: true };
};
export const extractEmailAddress = ({ value, parameters }: VcalAttendeeProperty | VcalOrganizerProperty) => {
const email = value || parameters?.cn;
return email && getEmailTo(email);
};
export const buildVcalOrganizer = (email: string, cn?: string) => {
return {
value: buildMailTo(email),
parameters: {
cn: cn || email,
},
};
};
export const buildVcalAttendee = (email: string) => {
return {
value: buildMailTo(email),
parameters: {
cn: email,
},
};
};
export const getHasModifiedDtstamp = (newVevent: VcalVeventComponent, oldVevent: VcalVeventComponent) => {
const { dtstamp: newDtstamp } = newVevent;
const { dtstamp: oldDtstamp } = oldVevent;
if (!newDtstamp || !oldDtstamp) {
return undefined;
}
return +propertyToUTCDate(newDtstamp) !== +propertyToUTCDate(oldDtstamp);
};
export const getHasStartChanged = (newVevent: VcalVeventComponent, oldVevent: VcalVeventComponent) =>
+propertyToUTCDate(oldVevent.dtstart) !== +propertyToUTCDate(newVevent.dtstart);
export const getHasModifiedDateTimes = (newVevent: VcalVeventComponent, oldVevent: VcalVeventComponent) => {
const isStartPreserved = !getHasStartChanged(newVevent, oldVevent);
const isEndPreserved =
+propertyToUTCDate(getDtendProperty(newVevent)) === +propertyToUTCDate(getDtendProperty(oldVevent));
return !isStartPreserved || !isEndPreserved;
};
const getIsEquivalentAttendee = (newAttendee: VcalAttendeeProperty, oldAttendee: VcalAttendeeProperty) => {
if (newAttendee.value !== oldAttendee.value) {
return false;
}
if (newAttendee.parameters?.partstat !== oldAttendee.parameters?.partstat) {
return false;
}
if (newAttendee.parameters?.role !== oldAttendee.parameters?.role) {
return false;
}
return true;
};
export const getHasModifiedAttendees = ({
veventIcs,
veventApi,
attendeeIcs,
attendeeApi,
}: {
veventIcs: VcalVeventComponent;
veventApi: VcalVeventComponent;
attendeeIcs: Participant;
attendeeApi: Participant;
}) => {
const { attendee: attendeesIcs } = veventIcs;
const { attendee: attendeesApi } = veventApi;
if (!attendeesIcs) {
return !!attendeesApi;
}
if (!attendeesApi || attendeesApi.length !== attendeesIcs.length) {
return true;
}
// We check if attendees other than the invitation attendees have been modified
const otherAttendeesIcs = attendeesIcs.filter(
(attendee) => canonicalizeEmail(getAttendeeEmail(attendee)) !== canonicalizeEmail(attendeeIcs.emailAddress)
);
const otherAttendeesApi = attendeesApi.filter(
(attendee) => canonicalizeEmail(getAttendeeEmail(attendee)) !== canonicalizeEmail(attendeeApi.emailAddress)
);
return otherAttendeesIcs.reduce((acc, attendee) => {
if (acc === true) {
return true;
}
const index = otherAttendeesApi.findIndex((oldAttendee) => getIsEquivalentAttendee(oldAttendee, attendee));
if (index === -1) {
return true;
}
otherAttendeesApi.splice(index, 1);
return false;
}, false);
};
| 8,351 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/vcalDefinition.ts | export const PROPERTIES = new Set([
'version',
'prodid',
'calscale',
'method',
'name',
'refresh-interval',
'source',
'color',
'image',
'conference',
'attach',
'categories',
'class',
'comment',
'description',
'geo',
'location',
'percent-complete',
'priority',
'resources',
'status',
'summary',
'completed',
'dtend',
'due',
'dtstart',
'duration',
'freebusy',
'transp',
'tzid',
'tzname',
'tzoffsetfrom',
'tzoffsetto',
'tzurl',
'attendee',
'contact',
'organizer',
'recurrence-id',
'related-to',
'url',
'uid',
'exdate',
'exrule',
'rdate',
'rrule',
'action',
'repeat',
'trigger',
'created',
'dtstamp',
'last-modified',
'sequence',
'request-status',
]);
export const UNIQUE_PROPERTIES = new Set([
'id',
'uid',
'dtstamp',
'class',
'created',
'description',
'geo',
'last-modified',
'recurrence-id',
'location',
'organizer',
'priority',
'sequence',
'status',
'summary',
'transp',
'trigger',
'action',
'url',
'rrule',
'dtstart',
'dtend',
'duration',
'repeat',
'attach',
'due',
'tzid',
'prodid',
'x-wr-calname',
'x-wr-timezone',
'x-pm-session-key',
'x-pm-shared-event-id',
'x-pm-proton-reply',
'x-yahoo-yid',
'x-yahoo-user-status',
'version',
'calscale',
'method',
'refresh-interval',
'color',
]);
| 8,352 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/vcalHelper.ts | import { normalize } from '../helpers/string';
import {
VcalAttendeeProperty,
VcalAttendeePropertyWithCn,
VcalAttendeePropertyWithPartstat,
VcalAttendeePropertyWithRole,
VcalAttendeePropertyWithToken,
VcalCalendarComponent,
VcalCalendarComponentWithMaybeErrors,
VcalDateOrDateTimeProperty,
VcalDateOrDateTimeValue,
VcalDateProperty,
VcalDateTimeValue,
VcalErrorComponent,
VcalStringProperty,
VcalVcalendar,
VcalVcalendarWithMaybeErrors,
VcalVeventComponent,
VcalVeventComponentWithMaybeErrors,
VcalVfreebusyComponentWithMaybeErrors,
VcalVjournalComponentWithMaybeErrors,
VcalVtimezoneComponent,
VcalVtodoComponentWithMaybeErrors,
VcalXOrIanaComponent,
} from '../interfaces/calendar';
import {
ICAL_ATTENDEE_ROLE,
ICAL_ATTENDEE_STATUS,
ICAL_EVENT_STATUS,
ICAL_METHOD,
ICAL_METHODS_ATTENDEE,
ICAL_METHODS_ORGANIZER,
} from './constants';
export const getIsPropertyAllDay = (property: VcalDateOrDateTimeProperty): property is VcalDateProperty => {
return property.parameters?.type === 'date' ?? false;
};
export const getPropertyTzid = (property: VcalDateOrDateTimeProperty) => {
if (getIsPropertyAllDay(property)) {
return;
}
return property.value.isUTC ? 'UTC' : property.parameters?.tzid;
};
export const getIsDateTimeValue = (value: VcalDateOrDateTimeValue): value is VcalDateTimeValue => {
return (value as VcalDateTimeValue).hours !== undefined;
};
export const getIsCalendar = (vcalComponent: VcalCalendarComponent): vcalComponent is VcalVcalendar => {
return (vcalComponent as VcalVcalendar)?.component?.toLowerCase() === 'vcalendar';
};
export const getIsVcalErrorComponent = (
component: VcalErrorComponent | VcalCalendarComponentWithMaybeErrors
): component is VcalErrorComponent => {
return 'error' in component;
};
export const getVcalendarHasNoErrorComponents = (
vcalendar: VcalVcalendarWithMaybeErrors
): vcalendar is VcalVcalendar => {
return (vcalendar.components || []).every((component) => !getIsVcalErrorComponent(component));
};
export function getIsEventComponent(vcalComponent: VcalCalendarComponent): vcalComponent is VcalVeventComponent;
export function getIsEventComponent(
vcalComponent: VcalCalendarComponentWithMaybeErrors
): vcalComponent is VcalVeventComponentWithMaybeErrors {
return vcalComponent?.component?.toLowerCase() === 'vevent';
}
export const getIsTodoComponent = (
vcalComponent: VcalCalendarComponentWithMaybeErrors
): vcalComponent is VcalVtodoComponentWithMaybeErrors => {
return vcalComponent?.component?.toLowerCase() === 'vtodo';
};
export const getIsJournalComponent = (
vcalComponent: VcalCalendarComponentWithMaybeErrors
): vcalComponent is VcalVjournalComponentWithMaybeErrors => {
return vcalComponent?.component?.toLowerCase() === 'vjournal';
};
export const getIsFreebusyComponent = (
vcalComponent: VcalCalendarComponentWithMaybeErrors
): vcalComponent is VcalVfreebusyComponentWithMaybeErrors => {
return vcalComponent?.component?.toLowerCase() === 'vfreebusy';
};
export const getIsTimezoneComponent = (
vcalComponent: VcalCalendarComponent
): vcalComponent is VcalVtimezoneComponent => {
return vcalComponent?.component?.toLowerCase() === 'vtimezone';
};
export const getIsAlarmComponent = (vcalComponent: VcalCalendarComponent): vcalComponent is VcalVtimezoneComponent => {
return vcalComponent?.component?.toLowerCase() === 'valarm';
};
export const getIsXOrIanaComponent = (vcalComponent: VcalCalendarComponent): vcalComponent is VcalXOrIanaComponent => {
const name = vcalComponent?.component?.toLowerCase();
return !['vcalendar', 'vevent', 'vtodo', 'vjournal', 'vfreebusy', 'vtimezone'].includes(name);
};
export const getHasUid = (
vevent: VcalVeventComponent
): vevent is VcalVeventComponent & Required<Pick<VcalVeventComponent, 'uid'>> => {
return !!vevent.uid?.value;
};
export const getHasDtStart = (
vevent: VcalVeventComponent
): vevent is VcalVeventComponent & Required<Pick<VcalVeventComponent, 'dtstart'>> => {
return !!vevent.dtstart?.value;
};
export const getHasDtend = (
vevent: VcalVeventComponent
): vevent is VcalVeventComponent & Required<Pick<VcalVeventComponent, 'dtend'>> => {
return !!vevent.dtend;
};
export const getHasRecurrenceId = (
vevent: VcalVeventComponent
): vevent is VcalVeventComponent & Required<Pick<VcalVeventComponent, 'recurrence-id'>> => {
return !!vevent['recurrence-id'];
};
export const getHasAttendee = (
vevent: VcalVeventComponent
): vevent is VcalVeventComponent & Required<Pick<VcalVeventComponent, 'attendee'>> => {
return !!vevent.attendee;
};
export const getHasAttendees = (
vevent: VcalVeventComponent
): vevent is VcalVeventComponent & Required<Pick<VcalVeventComponent, 'attendee'>> => {
return !!vevent.attendee?.length;
};
export const getAttendeeHasCn = (attendee: VcalAttendeeProperty): attendee is VcalAttendeePropertyWithCn => {
return !!attendee.parameters?.cn;
};
export const getAttendeesHaveCn = (
vcalAttendee: VcalAttendeeProperty[]
): vcalAttendee is VcalAttendeePropertyWithCn[] => {
return !vcalAttendee.some((vcalAttendee) => !getAttendeeHasCn(vcalAttendee));
};
export const getAttendeeHasToken = (attendee: VcalAttendeeProperty): attendee is VcalAttendeePropertyWithToken => {
return !!attendee.parameters?.['x-pm-token'];
};
export const getAttendeesHaveToken = (
vcalAttendee: VcalAttendeeProperty[]
): vcalAttendee is VcalAttendeePropertyWithToken[] => {
return !vcalAttendee.some((vcalAttendee) => !getAttendeeHasToken(vcalAttendee));
};
export const getAttendeeHasPartStat = (
attendee: VcalAttendeeProperty
): attendee is VcalAttendeePropertyWithPartstat => {
return !!attendee.parameters?.partstat;
};
export const getAttendeeHasRole = (attendee: VcalAttendeeProperty): attendee is VcalAttendeePropertyWithRole => {
return !!attendee.parameters?.role;
};
export const getIcalMethod = (method?: VcalStringProperty) => {
if (!method) {
return ICAL_METHOD.PUBLISH;
}
const normalizedValue = normalize(method.value);
const matchesNormalizedValue = (icalMethod: ICAL_METHOD) => normalize(icalMethod) === normalizedValue;
return Object.values(ICAL_METHOD).find(matchesNormalizedValue);
};
export const getIsValidMethod = (method: ICAL_METHOD, isOrganizerMode: boolean) => {
if (method === ICAL_METHOD.DECLINECOUNTER) {
// we should never encounter DECLINECOUNTER for the moment
return false;
}
return isOrganizerMode ? ICAL_METHODS_ATTENDEE.includes(method) : ICAL_METHODS_ORGANIZER.includes(method);
};
export const getVeventStatus = <T extends { status?: VcalVeventComponent['status'] }>({ status }: T) => {
if (Object.values(ICAL_EVENT_STATUS).some((icalStatus) => icalStatus === status?.value)) {
return status?.value as ICAL_EVENT_STATUS;
}
return ICAL_EVENT_STATUS.CONFIRMED;
};
export const getIsVeventCancelled = (vevent: VcalVeventComponent) => {
return getVeventStatus(vevent) === ICAL_EVENT_STATUS.CANCELLED;
};
export const getAttendeePartstat = (attendee: Partial<VcalAttendeeProperty> = {}, xYahooUserStatus?: string) => {
const partstat = attendee.parameters?.partstat;
if (partstat === ICAL_ATTENDEE_STATUS.NEEDS_ACTION && xYahooUserStatus) {
// Yahoo Calendar does not follow the RFC and encodes the partstat in a custom property
if (xYahooUserStatus === 'BUSY') {
return ICAL_ATTENDEE_STATUS.ACCEPTED;
}
if (xYahooUserStatus === 'TENTATIVE') {
return ICAL_ATTENDEE_STATUS.TENTATIVE;
}
if (xYahooUserStatus === 'FREE') {
return ICAL_ATTENDEE_STATUS.DECLINED;
}
}
if (Object.values(ICAL_ATTENDEE_STATUS).some((icalPartstat) => icalPartstat === partstat)) {
return partstat as ICAL_ATTENDEE_STATUS;
}
return ICAL_ATTENDEE_STATUS.NEEDS_ACTION;
};
export const getAttendeeRole = (attendee: Partial<VcalAttendeeProperty> = {}) => {
const role = attendee.parameters?.role;
if (Object.values(ICAL_ATTENDEE_ROLE).some((icalRole) => icalRole === role)) {
return role as ICAL_ATTENDEE_ROLE;
}
return ICAL_ATTENDEE_ROLE.REQUIRED;
};
export const getAttendeeToken = (attendee: Partial<VcalAttendeeProperty> = {}) => {
return attendee?.parameters?.['x-pm-token'];
};
export const getIsYahooEvent = (veventComponent: VcalVeventComponent) => {
return !!(veventComponent['x-yahoo-yid'] || veventComponent['x-yahoo-user-status']);
};
export const getIsProtonReply = (veventComponent: VcalVeventComponent) => {
const stringifiedValue = veventComponent['x-pm-proton-reply']?.value;
if (!stringifiedValue) {
return;
}
return stringifiedValue === 'true';
};
export const getPmSharedEventID = (veventComponent: VcalVeventComponent) => {
return veventComponent['x-pm-shared-event-id']?.value;
};
export const getPmSharedSessionKey = (veventComponent: VcalVeventComponent) => {
return veventComponent['x-pm-session-key']?.value;
};
| 8,353 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/veventHelper.ts | import { serverTime } from '@proton/crypto';
import { absoluteToRelativeTrigger, getIsAbsoluteTrigger } from '@proton/shared/lib/calendar/alarms/trigger';
import { DAY } from '../constants';
import { fromUTCDate, toUTCDate } from '../date/timezone';
import { omit, pick } from '../helpers/object';
import {
AttendeeClearPartResult,
AttendeePart,
CalendarEventData,
VcalDateOrDateTimeProperty,
VcalValarmComponent,
VcalVeventComponent,
} from '../interfaces/calendar';
import { RequireOnly } from '../interfaces/utils';
import { fromInternalAttendee } from './attendees';
import {
CALENDAR_CARD_TYPE,
CALENDAR_ENCRYPTED_FIELDS,
CALENDAR_SIGNED_FIELDS,
NOTIFICATION_TYPE_API,
REQUIRED_SET,
SHARED_ENCRYPTED_FIELDS,
SHARED_SIGNED_FIELDS,
TAKEN_KEYS,
USER_ENCRYPTED_FIELDS,
USER_SIGNED_FIELDS,
} from './constants';
import { generateProtonCalendarUID, getDisplayTitle, hasMoreThan, wrap } from './helper';
import { withMandatoryPublishFields as withVAlarmMandatoryPublishFields } from './valarmHelper';
import { parse, serialize, toTriggerString } from './vcal';
import { prodId } from './vcalConfig';
import { dateTimeToProperty, propertyToUTCDate } from './vcalConverter';
import { getIsCalendar, getIsEventComponent, getIsPropertyAllDay, getIsVeventCancelled } from './vcalHelper';
const { ENCRYPTED_AND_SIGNED, SIGNED, CLEAR_TEXT } = CALENDAR_CARD_TYPE;
export const getIsAllDay = ({ dtstart }: Pick<VcalVeventComponent, 'dtstart'>) => {
return getIsPropertyAllDay(dtstart);
};
export const getUidValue = (component: VcalVeventComponent) => {
return component.uid.value;
};
export const getIsRecurring = ({ rrule }: Pick<VcalVeventComponent, 'rrule'>) => {
return !!rrule;
};
export const getRecurrenceId = ({ 'recurrence-id': recurrenceId }: Pick<VcalVeventComponent, 'recurrence-id'>) => {
return recurrenceId;
};
export const getRecurrenceIdDate = (component: VcalVeventComponent) => {
const rawRecurrenceId = getRecurrenceId(component);
if (!rawRecurrenceId || !rawRecurrenceId.value) {
return;
}
return toUTCDate(rawRecurrenceId.value);
};
export const getSequence = (event: VcalVeventComponent) => {
const sequence = +(event.sequence?.value || 0);
return Math.max(sequence, 0);
};
export const getReadableCard = (cards: CalendarEventData[]) => {
return cards.find(({ Type }) => [CLEAR_TEXT, SIGNED].includes(Type));
};
export const getIsEventCancelled = <T extends { CalendarEvents: CalendarEventData[] }>(event: T) => {
const calendarClearTextPart = getReadableCard(event.CalendarEvents);
if (!calendarClearTextPart) {
return;
}
const vcalPart = parse(calendarClearTextPart.Data);
const vevent = getIsCalendar(vcalPart) ? vcalPart.components?.find(getIsEventComponent) : undefined;
if (!vevent) {
return;
}
return getIsVeventCancelled(vevent);
};
export const withUid = <T>(properties: VcalVeventComponent & T): VcalVeventComponent & T => {
if (properties.uid) {
return properties;
}
return {
...properties,
uid: { value: generateProtonCalendarUID() },
};
};
export const withDtstamp = <T>(
properties: RequireOnly<VcalVeventComponent, 'uid' | 'component' | 'dtstart'> & T,
timestamp?: number
): VcalVeventComponent & T => {
if (properties.dtstamp) {
return properties as VcalVeventComponent & T;
}
const timestampToUse = timestamp !== undefined ? timestamp : +serverTime();
return {
...properties,
dtstamp: dateTimeToProperty(fromUTCDate(new Date(timestampToUse)), true),
};
};
export const withSummary = <T>(properties: VcalVeventComponent & T): VcalVeventComponent & T => {
if (properties.summary) {
return properties;
}
return {
...properties,
summary: { value: '' },
};
};
/**
* Helper that takes a vEvent as it could be persisted in our database and returns one that is RFC-compatible for PUBLISH method
*
* According to RFC-5546, summary field is mandatory on vEvent for PUBLISH method (https://datatracker.ietf.org/doc/html/rfc5546#section-3.2.1)
* We also want to add RFC-5545 mandatory fields for vAlarms that we would not have already set persisted in our database
*
* @param properties properties of the vEvent
* @param email email associated with the calendar containing the vevent
* @returns an RFC-compatible vEvent for PUBLISH method
*/
export const withMandatoryPublishFields = <T>(
properties: VcalVeventComponent & T,
email: string
): VcalVeventComponent & T => {
const eventTitle = getDisplayTitle(properties.summary?.value);
return withSummary({
...properties,
components: properties.components?.map((component) =>
withVAlarmMandatoryPublishFields(component, eventTitle, email)
),
});
};
type VeventWithRequiredDtStart<T> = RequireOnly<VcalVeventComponent, 'dtstart'> & T;
export const withoutRedundantDtEnd = <T>(
properties: VeventWithRequiredDtStart<T>
): VeventWithRequiredDtStart<T> | Omit<VeventWithRequiredDtStart<T>, 'dtend'> => {
const utcDtStart = +propertyToUTCDate(properties.dtstart);
const utcDtEnd = properties.dtend ? +propertyToUTCDate(properties.dtend) : undefined;
// All day events date ranges are stored non-inclusively, so if a full day event has same start and end day, we can ignore it
const ignoreDtend =
!utcDtEnd ||
(getIsAllDay(properties) ? Math.floor((utcDtEnd - utcDtStart) / DAY) <= 1 : utcDtStart === utcDtEnd);
if (ignoreDtend) {
return omit(properties, ['dtend']);
}
return properties;
};
/**
* Used to removed `rrule` field in Reply ICS for invite single edit when recurrence-id is filled
*/
export const withoutRedundantRrule = <T>(
properties: VcalVeventComponent & T
): (VcalVeventComponent & T) | Omit<VcalVeventComponent & T, 'rrule'> => {
if (Boolean(properties['recurrence-id']) && Boolean(properties.rrule)) {
return omit(properties, ['rrule']);
}
return properties;
};
export const withRequiredProperties = <T>(properties: VcalVeventComponent & T): VcalVeventComponent & T => {
return withDtstamp(withUid(properties));
};
export const getSharedPart = (properties: VcalVeventComponent) => {
return {
[SIGNED]: pick(properties, SHARED_SIGNED_FIELDS),
[ENCRYPTED_AND_SIGNED]: pick(properties, SHARED_ENCRYPTED_FIELDS),
};
};
export const getCalendarPart = (properties: VcalVeventComponent) => {
return {
[SIGNED]: pick(properties, CALENDAR_SIGNED_FIELDS),
[ENCRYPTED_AND_SIGNED]: pick(properties, CALENDAR_ENCRYPTED_FIELDS),
};
};
export const getUserPart = (veventProperties: VcalVeventComponent) => {
return {
[SIGNED]: pick(veventProperties, USER_SIGNED_FIELDS),
[ENCRYPTED_AND_SIGNED]: pick(veventProperties, USER_ENCRYPTED_FIELDS),
};
};
export const getAttendeesPart = (
veventProperties: VcalVeventComponent
): {
[CLEAR_TEXT]: AttendeeClearPartResult[];
[ENCRYPTED_AND_SIGNED]: Partial<VcalVeventComponent>;
} => {
const formattedAttendees: { [CLEAR_TEXT]: AttendeeClearPartResult[]; attendee: AttendeePart[] } = {
[CLEAR_TEXT]: [],
attendee: [],
};
if (Array.isArray(veventProperties.attendee)) {
for (const attendee of veventProperties.attendee) {
const { clear, attendee: newAttendee } = fromInternalAttendee(attendee);
formattedAttendees[CLEAR_TEXT].push(clear);
formattedAttendees.attendee.push(newAttendee);
}
}
if (!formattedAttendees.attendee.length) {
return {
[ENCRYPTED_AND_SIGNED]: {},
[CLEAR_TEXT]: [],
};
}
const result: Pick<VcalVeventComponent, 'uid' | 'attendee'> = {
uid: veventProperties.uid,
attendee: formattedAttendees.attendee,
};
return {
[ENCRYPTED_AND_SIGNED]: result,
[CLEAR_TEXT]: formattedAttendees[CLEAR_TEXT],
};
};
const toResult = (veventProperties: Partial<VcalVeventComponent>, veventComponents: VcalValarmComponent[] = []) => {
// Add PRODID to identify the author of the last event modification
return wrap(
serialize({
...veventProperties,
component: 'vevent',
components: veventComponents,
}),
prodId
);
};
/**
* Ignores the result if the vevent does not contain anything more than the required set (uid, dtstamp, and children).
*/
const toResultOptimized = (
veventProperties: Partial<VcalVeventComponent>,
veventComponents: VcalValarmComponent[] = []
) => {
return hasMoreThan(REQUIRED_SET, veventProperties) || veventComponents.length
? toResult(veventProperties, veventComponents)
: undefined;
};
export const toApiNotifications = (components?: VcalValarmComponent[], dtstart?: VcalDateOrDateTimeProperty) => {
if (!components) {
return [];
}
return components.map(({ trigger, action }) => {
const Type =
action.value.toLowerCase() === 'email' ? NOTIFICATION_TYPE_API.EMAIL : NOTIFICATION_TYPE_API.DEVICE;
if (getIsAbsoluteTrigger(trigger)) {
if (!dtstart) {
throw new Error('Cannot convert absolute trigger without DTSTART');
}
const relativeTrigger = {
value: absoluteToRelativeTrigger(trigger, dtstart),
};
return {
Type,
Trigger: toTriggerString(relativeTrigger.value),
};
}
return {
Type,
Trigger: toTriggerString(trigger.value),
};
});
};
/**
* Split the internal vevent component into the parts expected by the API.
*/
export const getVeventParts = ({ components, ...properties }: VcalVeventComponent) => {
const restProperties = omit(properties, TAKEN_KEYS);
const sharedPart = getSharedPart(properties);
const calendarPart = getCalendarPart(properties);
const personalPart = getUserPart(properties);
const attendeesPart = getAttendeesPart(properties);
return {
sharedPart: {
[SIGNED]: toResult(sharedPart[SIGNED]),
// Store all the rest of the properties in the shared encrypted part
[ENCRYPTED_AND_SIGNED]: toResult({
...sharedPart[ENCRYPTED_AND_SIGNED],
...restProperties,
}),
},
calendarPart: {
[SIGNED]: toResultOptimized(calendarPart[SIGNED]),
[ENCRYPTED_AND_SIGNED]: toResultOptimized(calendarPart[ENCRYPTED_AND_SIGNED]),
},
personalPart: {
// Assume all sub-components are valarm that go in the personal part
[SIGNED]: toResultOptimized(personalPart[SIGNED], components),
// Nothing to encrypt for now
[ENCRYPTED_AND_SIGNED]: undefined,
},
attendeesPart: {
// Nothing to sign for now
[SIGNED]: undefined,
[ENCRYPTED_AND_SIGNED]: toResultOptimized(attendeesPart[ENCRYPTED_AND_SIGNED]),
[CLEAR_TEXT]: attendeesPart[CLEAR_TEXT],
},
notificationsPart: toApiNotifications(components),
};
};
| 8,354 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/vtimezoneHelper.ts | import isTruthy from '@proton/utils/isTruthy';
import { SimpleMap } from '../interfaces';
import { VcalVeventComponent } from '../interfaces/calendar';
import { GetVTimezonesMap } from '../interfaces/hooks/GetVTimezonesMap';
import { getPropertyTzid } from './vcalHelper';
interface Params {
vevents?: VcalVeventComponent[];
tzids?: string[];
getVTimezonesMap: GetVTimezonesMap;
}
export const getUniqueVtimezones = async ({ vevents = [], tzids = [], getVTimezonesMap }: Params) => {
const uniqueTzidsMap = [...tzids, ...vevents].reduce<SimpleMap<boolean>>((acc, item) => {
if (typeof item === 'string') {
acc[item] = true;
return acc;
}
const { dtstart, dtend } = item;
const startTzid = getPropertyTzid(dtstart);
if (startTzid) {
acc[startTzid] = true;
}
const endTzid = dtend ? getPropertyTzid(dtend) : undefined;
if (endTzid) {
acc[endTzid] = true;
}
return acc;
}, {});
const vtimezoneObjects = Object.values(await getVTimezonesMap(Object.keys(uniqueTzidsMap))).filter(isTruthy);
return vtimezoneObjects.map(({ vtimezone }) => vtimezone);
};
| 8,355 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/alarms/getAlarmMessageText.ts | import { c } from 'ttag';
import { MINUTE } from '../../constants';
import { format as formatUTC, isNextDay, isSameDay, isSameMonth, isSameYear } from '../../date-fns-utc';
interface Arguments {
isAllDay: boolean;
title: string;
startFakeUTCDate: Date;
nowFakeUTCDate: Date;
formatOptions: any;
}
const getAlarmMessageText = ({ title, isAllDay, startFakeUTCDate, nowFakeUTCDate, formatOptions }: Arguments) => {
const formattedHour = formatUTC(startFakeUTCDate, 'p', formatOptions);
// because of browser timer imprecision, allow for a 1 minute margin to determine simultaneity
const isNow = Math.abs(+startFakeUTCDate - +nowFakeUTCDate) <= MINUTE / 2;
const isInFuture = startFakeUTCDate > nowFakeUTCDate;
if (isNow) {
return c('Alarm notification').t`${title} starts now`;
}
if (!isInFuture) {
if (isSameDay(nowFakeUTCDate, startFakeUTCDate)) {
if (isAllDay) {
return c('Alarm notification').t`${title} starts today`;
}
return c('Alarm notification').t`${title} started at ${formattedHour}`;
}
if (isNextDay(startFakeUTCDate, nowFakeUTCDate)) {
if (isAllDay) {
return c('Alarm notification').t`${title} started yesterday`;
}
return c('Alarm notification').t`${title} started yesterday at ${formattedHour}`;
}
if (isSameMonth(nowFakeUTCDate, startFakeUTCDate)) {
const formattedDate = formatUTC(startFakeUTCDate, 'eeee do', formatOptions);
if (isAllDay) {
return c('Alarm notification').t`${title} started on ${formattedDate}`;
}
return c('Alarm notification').t`${title} started on ${formattedDate} at ${formattedHour}`;
}
if (isSameYear(nowFakeUTCDate, startFakeUTCDate)) {
const formattedDate = formatUTC(startFakeUTCDate, 'eeee do MMMM', formatOptions);
if (isAllDay) {
return c('Alarm notification').t`${title} started on ${formattedDate}`;
}
return c('Alarm notification').t`${title} started on ${formattedDate} at ${formattedHour}`;
}
if (isAllDay) {
const formattedDateWithoutTime = formatUTC(startFakeUTCDate, 'PPPP', formatOptions);
return c('Alarm notification').t`${title} started on ${formattedDateWithoutTime}`;
}
const formattedDateWithTime = formatUTC(startFakeUTCDate, 'PPPPp', formatOptions);
return c('Alarm notification').t`${title} started on ${formattedDateWithTime}`;
}
if (isSameDay(nowFakeUTCDate, startFakeUTCDate)) {
if (isAllDay) {
return c('Alarm notification').t`${title} starts today`;
}
return c('Alarm notification').t`${title} starts at ${formattedHour}`;
}
if (isNextDay(nowFakeUTCDate, startFakeUTCDate)) {
if (isAllDay) {
return c('Alarm notification').t`${title} starts tomorrow`;
}
return c('Alarm notification').t`${title} starts tomorrow at ${formattedHour}`;
}
if (isSameMonth(nowFakeUTCDate, startFakeUTCDate)) {
const formattedDate = formatUTC(startFakeUTCDate, 'eeee do', formatOptions);
if (isAllDay) {
return c('Alarm notification').t`${title} starts on ${formattedDate}`;
}
return c('Alarm notification').t`${title} starts on ${formattedDate} at ${formattedHour}`;
}
if (isSameYear(nowFakeUTCDate, startFakeUTCDate)) {
const formattedDate = formatUTC(startFakeUTCDate, 'eeee do MMMM', formatOptions);
if (isAllDay) {
return c('Alarm notification').t`${title} starts on ${formattedDate}`;
}
return c('Alarm notification').t`${title} starts on ${formattedDate} at ${formattedHour}`;
}
if (isAllDay) {
const formattedDateWithoutTime = formatUTC(startFakeUTCDate, 'PPPP', formatOptions);
return c('Alarm notification').t`${title} starts on ${formattedDateWithoutTime}`;
}
const formattedDateWithTime = formatUTC(startFakeUTCDate, 'PPPPp', formatOptions);
return c('Alarm notification').t`${title} starts on ${formattedDateWithTime}`;
};
export default getAlarmMessageText;
| 8,356 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/alarms/getNotificationString.ts | import { c, msgid } from 'ttag';
import { fromLocalDate, toUTCDate } from '../../date/timezone';
import { NotificationModel } from '../../interfaces/calendar';
import { NOTIFICATION_UNITS, NOTIFICATION_WHEN } from '../constants';
const getNotificationString = (notification: NotificationModel, formatTime: (date: Date) => string) => {
const { value = 0, unit, when, at, isAllDay } = notification;
if (!isAllDay || !at) {
if (value === 0) {
return c('Notifications').t`At time of event`;
}
if (when === NOTIFICATION_WHEN.BEFORE) {
if (unit === NOTIFICATION_UNITS.MINUTE) {
return c('Notifications').ngettext(msgid`${value} minute before`, `${value} minutes before`, value);
}
if (unit === NOTIFICATION_UNITS.HOUR) {
return c('Notifications').ngettext(msgid`${value} hour before`, `${value} hours before`, value);
}
if (unit === NOTIFICATION_UNITS.DAY) {
return c('Notifications').ngettext(msgid`${value} day before`, `${value} days before`, value);
}
if (unit === NOTIFICATION_UNITS.WEEK) {
return c('Notifications').ngettext(msgid`${value} week before`, `${value} weeks before`, value);
}
}
if (when === NOTIFICATION_WHEN.AFTER) {
if (unit === NOTIFICATION_UNITS.MINUTE) {
return c('Notifications').ngettext(msgid`${value} minute after`, `${value} minutes after`, value);
}
if (unit === NOTIFICATION_UNITS.HOUR) {
return c('Notifications').ngettext(msgid`${value} hour after`, `${value} hours after`, value);
}
if (unit === NOTIFICATION_UNITS.DAY) {
return c('Notifications').ngettext(msgid`${value} day after`, `${value} days after`, value);
}
if (unit === NOTIFICATION_UNITS.WEEK) {
return c('Notifications').ngettext(msgid`${value} week after`, `${value} weeks after`, value);
}
}
return c('Notifications').t`Unknown`;
}
const modifiedAt = toUTCDate(fromLocalDate(at));
const time = formatTime(modifiedAt);
if (value === 0) {
return c('Notifications').t`On the same day at ${time}`;
}
if (when === NOTIFICATION_WHEN.BEFORE) {
if (unit === NOTIFICATION_UNITS.MINUTE) {
return c('Notifications').ngettext(
msgid`${value} minute before at ${time}`,
`${value} minutes before at ${time}`,
value
);
}
if (unit === NOTIFICATION_UNITS.HOUR) {
return c('Notifications').ngettext(
msgid`${value} hour before at ${time}`,
`${value} hours before at ${time}`,
value
);
}
if (unit === NOTIFICATION_UNITS.DAY) {
return c('Notifications').ngettext(
msgid`${value} day before at ${time}`,
`${value} days before at ${time}`,
value
);
}
if (unit === NOTIFICATION_UNITS.WEEK) {
return c('Notifications').ngettext(
msgid`${value} week before at ${time}`,
`${value} weeks before at ${time}`,
value
);
}
}
if (when === NOTIFICATION_WHEN.AFTER) {
if (unit === NOTIFICATION_UNITS.MINUTE) {
return c('Notifications').ngettext(
msgid`${value} minute after at ${time}`,
`${value} minutes after at ${time}`,
value
);
}
if (unit === NOTIFICATION_UNITS.HOUR) {
return c('Notifications').ngettext(
msgid`${value} hour after at ${time}`,
`${value} hours after at ${time}`,
value
);
}
if (unit === NOTIFICATION_UNITS.DAY) {
return c('Notifications').ngettext(
msgid`${value} day after at ${time}`,
`${value} days after at ${time}`,
value
);
}
if (unit === NOTIFICATION_UNITS.WEEK) {
return c('Notifications').ngettext(
msgid`${value} week after at ${time}`,
`${value} weeks after at ${time}`,
value
);
}
}
};
export default getNotificationString;
| 8,357 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/alarms/getValarmTrigger.ts | import { NotificationModel } from '../../interfaces/calendar/Notification';
import { NOTIFICATION_UNITS, NOTIFICATION_WHEN } from '../constants';
import { transformBeforeAt } from './trigger';
const getValarmTriggerUnit = (unit: NOTIFICATION_UNITS) => {
return (
{
[NOTIFICATION_UNITS.WEEK]: 'weeks',
[NOTIFICATION_UNITS.DAY]: 'days',
[NOTIFICATION_UNITS.HOUR]: 'hours',
[NOTIFICATION_UNITS.MINUTE]: 'minutes',
}[unit] || 'days'
);
};
const getAllDayValarmTrigger = ({
isNegative,
unit,
value = 0,
at,
}: {
isNegative: boolean;
unit: NOTIFICATION_UNITS;
value?: number;
at: Date;
}) => {
const modifiedAt = isNegative ? transformBeforeAt(at) : at;
const hours = modifiedAt.getHours();
const minutes = modifiedAt.getMinutes();
const modifyNegativeDay = isNegative && (minutes > 0 || hours > 0);
const [weeks, days] = (() => {
const weeksValue = unit === NOTIFICATION_UNITS.WEEK ? value : 0;
const daysValue = unit === NOTIFICATION_UNITS.DAY ? value : 0;
if (modifyNegativeDay && weeksValue === 0) {
return [0, daysValue - 1];
}
if (modifyNegativeDay && weeksValue >= 1) {
return [weeksValue - 1, 6];
}
return [weeksValue, daysValue];
})();
return {
weeks: Math.max(0, weeks),
days: Math.max(0, days),
hours,
minutes,
seconds: 0,
isNegative,
};
};
const getPartDayValarmTrigger = ({
isNegative,
unit,
value = 0,
}: {
isNegative: boolean;
unit: NOTIFICATION_UNITS;
value?: number;
}) => {
return {
weeks: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
[getValarmTriggerUnit(unit)]: value,
isNegative,
};
};
export const getValarmTrigger = ({ isAllDay, unit, when, value, at }: NotificationModel) => {
const isNegative = when === NOTIFICATION_WHEN.BEFORE;
if (isAllDay) {
if (!at) {
throw new Error('Missing at');
}
return getAllDayValarmTrigger({ isNegative, unit, value, at });
}
return getPartDayValarmTrigger({ isNegative, unit, value });
};
| 8,358 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/alarms/modelToNotifications.ts | import { NotificationModel } from '../../interfaces/calendar';
import { getValarmTrigger } from '../alarms/getValarmTrigger';
import { toTriggerString } from '../vcal';
export const modelToNotifications = (notifications: NotificationModel[] = []) => {
return notifications.map((notificationModel) => ({
Type: notificationModel.type,
Trigger: toTriggerString(getValarmTrigger(notificationModel)),
}));
};
| 8,359 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/alarms/modelToValarm.ts | import { NotificationModel } from '../../interfaces/calendar';
import { VcalValarmComponent } from '../../interfaces/calendar/VcalModel';
import { ICAL_ALARM_ACTION, NOTIFICATION_TYPE_API } from '../constants';
import { getValarmTrigger } from './getValarmTrigger';
export const modelToValarmComponent = (notificationModel: NotificationModel): VcalValarmComponent => {
return {
component: 'valarm',
trigger: {
value: getValarmTrigger(notificationModel),
},
action: {
value:
notificationModel.type === NOTIFICATION_TYPE_API.EMAIL
? ICAL_ALARM_ACTION.EMAIL
: ICAL_ALARM_ACTION.DISPLAY,
},
};
};
| 8,360 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/alarms/notificationDefaults.ts | import { NOTIFICATION_TYPE_API } from '../constants';
import { fromTriggerString } from '../vcal';
import { triggerToModel } from './notificationModel';
export const DEFAULT_PART_DAY_NOTIFICATIONS = [
{
Type: NOTIFICATION_TYPE_API.DEVICE,
Trigger: '-PT15M',
},
{
Type: NOTIFICATION_TYPE_API.EMAIL,
Trigger: '-PT15M',
},
];
export const DEFAULT_FULL_DAY_NOTIFICATIONS = [
{
Type: NOTIFICATION_TYPE_API.DEVICE,
Trigger: '-PT15H',
},
{
Type: NOTIFICATION_TYPE_API.EMAIL,
Trigger: '-PT15H',
},
];
export const DEFAULT_PART_DAY_NOTIFICATION = {
id: '1',
...triggerToModel({
isAllDay: false,
type: NOTIFICATION_TYPE_API.DEVICE,
trigger: fromTriggerString('-PT15M'),
}),
};
export const DEFAULT_FULL_DAY_NOTIFICATION = {
id: '2',
...triggerToModel({
isAllDay: true,
type: NOTIFICATION_TYPE_API.DEVICE,
trigger: fromTriggerString('-PT15H'),
}),
};
| 8,361 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/alarms/notificationModel.ts | import { NotificationModel, VcalDurationValue } from '../../interfaces/calendar';
import { normalizeRelativeTrigger, transformBeforeAt } from '../alarms/trigger';
import { NOTIFICATION_TYPE_API, NOTIFICATION_UNITS, NOTIFICATION_WHEN } from '../constants';
const getInt = (value: any) => parseInt(value, 10) || 0;
interface TriggerToModelShared {
when: NOTIFICATION_WHEN;
type: NOTIFICATION_TYPE_API;
weeks: number;
days: number;
hours: number;
minutes: number;
}
const allDayTriggerToModel = ({ type, when, weeks, days, hours, minutes }: TriggerToModelShared) => {
const isNegative = when === NOTIFICATION_WHEN.BEFORE;
const at = new Date(2000, 0, 1, hours, minutes);
const modifiedAt = isNegative ? transformBeforeAt(at) : at;
const modifyNegativeDay = isNegative && (modifiedAt.getHours() > 0 || modifiedAt.getMinutes() > 0);
const [value, unit] = (() => {
// Transform for example -P1W6DT10H10M into 2 weeks at...
if (weeks >= 0 && days === 6 && modifyNegativeDay) {
return [weeks + 1, NOTIFICATION_UNITS.WEEK];
}
// Otherwise, if there is something in the week, and even if there are days in the trigger, the client will truncate this into a week notification since the selector is not more advanced than that.
if (weeks > 0) {
return [weeks, NOTIFICATION_UNITS.WEEK];
}
// Finally just return it as a day notification.
return [days + +modifyNegativeDay, NOTIFICATION_UNITS.DAY];
})();
return {
unit,
type,
when,
value,
at: modifiedAt,
isAllDay: true,
};
};
const partDayTriggerToModel = ({ type, when, weeks, days, hours, minutes }: TriggerToModelShared) => {
const [value, unit] = (() => {
if (weeks) {
return [weeks, NOTIFICATION_UNITS.WEEK];
}
if (days) {
return [days, NOTIFICATION_UNITS.DAY];
}
if (hours) {
return [hours, NOTIFICATION_UNITS.HOUR];
}
return [minutes, NOTIFICATION_UNITS.MINUTE];
})();
return {
unit,
type,
when,
value,
isAllDay: false,
};
};
interface TriggerToModel {
isAllDay: boolean;
type: NOTIFICATION_TYPE_API;
trigger: Partial<VcalDurationValue>;
}
export const triggerToModel = ({
isAllDay,
type,
trigger: { weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, isNegative = false },
}: TriggerToModel): Omit<NotificationModel, 'id'> => {
const parsedTrigger = {
weeks: getInt(weeks),
days: getInt(days),
hours: getInt(hours),
minutes: getInt(minutes),
seconds: getInt(seconds),
isNegative,
};
const normalizedTrigger = normalizeRelativeTrigger(parsedTrigger, isAllDay);
const when = isNegative ? NOTIFICATION_WHEN.BEFORE : NOTIFICATION_WHEN.AFTER;
if (isAllDay) {
return allDayTriggerToModel({ type, when, ...normalizedTrigger });
}
return partDayTriggerToModel({ type, when, ...normalizedTrigger });
};
export const getDeviceNotifications = (notifications: NotificationModel[]) => {
return notifications.filter(({ type }) => type === NOTIFICATION_TYPE_API.DEVICE);
};
| 8,362 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/alarms/notificationsToModel.ts | import generateUID from '../../helpers/generateUID';
import { Nullable } from '../../interfaces';
import { CalendarNotificationSettings, CalendarSettings } from '../../interfaces/calendar';
import { filterFutureNotifications } from '../alarms';
import { fromTriggerString } from '../vcal';
import { triggerToModel } from './notificationModel';
export const notificationsToModel = (notifications: CalendarNotificationSettings[] = [], isAllDay: boolean) => {
const modelNotifications = notifications.map(({ Type, Trigger }) => ({
id: generateUID('notification'),
...triggerToModel({
isAllDay,
type: Type,
trigger: fromTriggerString(Trigger),
}),
}));
// Filter out future alarms
return filterFutureNotifications(modelNotifications);
};
export const apiNotificationsToModel = ({
notifications: apiNotifications,
isAllDay,
calendarSettings,
}: {
notifications: Nullable<CalendarNotificationSettings[]>;
isAllDay: boolean;
calendarSettings: CalendarSettings;
}) => {
const { DefaultPartDayNotifications, DefaultFullDayNotifications } = calendarSettings;
const defaultNotifications = isAllDay ? DefaultFullDayNotifications : DefaultPartDayNotifications;
return notificationsToModel(apiNotifications || defaultNotifications, isAllDay);
};
| 8,363 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/alarms/trigger.ts | import { differenceInMinutes } from 'date-fns';
import isTruthy from '@proton/utils/isTruthy';
import {
VcalDateOrDateTimeProperty,
VcalDateTimeProperty,
VcalDurationValue,
VcalTriggerProperty,
} from '../../interfaces/calendar';
import { propertyToUTCDate } from '../vcalConverter';
import { getIsPropertyAllDay } from '../vcalHelper';
const MINUTE = 60;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const WEEK = 7 * DAY;
export const transformBeforeAt = (at: Date) => {
const minutes = 60 - (at.getMinutes() || 60);
const hours = 24 - (at.getHours() || 24) - (minutes > 0 ? 1 : 0);
return new Date(at.getFullYear(), at.getMonth(), at.getDate(), hours, minutes);
};
export const getIsAbsoluteTrigger = (trigger: VcalTriggerProperty): trigger is VcalDateTimeProperty => {
return (trigger as VcalDateTimeProperty).parameters?.type === 'date-time';
};
export const absoluteToRelativeTrigger = (trigger: VcalDateTimeProperty, dtstart: VcalDateOrDateTimeProperty) => {
const utcStartDate = propertyToUTCDate(dtstart);
const triggerDate = propertyToUTCDate(trigger);
const durationInMinutes = differenceInMinutes(utcStartDate, triggerDate);
const duration = Math.abs(durationInMinutes * MINUTE);
const weeks = Math.floor(duration / WEEK);
const days = Math.floor((duration % WEEK) / DAY);
const hours = Math.floor((duration % DAY) / HOUR);
const minutes = Math.floor((duration % HOUR) / MINUTE);
return { weeks, days, hours, minutes, seconds: 0, isNegative: durationInMinutes >= 0 };
};
/**
* If you import this function, notice unit has to be in seconds, not milliseconds
*/
export const normalizeDurationToUnit = (duration: Partial<VcalDurationValue>, unit: number) => {
const normalizedUnits = [
Math.floor(((duration.weeks || 0) * WEEK) / unit),
Math.floor(((duration.days || 0) * DAY) / unit),
Math.floor(((duration.hours || 0) * HOUR) / unit),
Math.floor(((duration.minutes || 0) * MINUTE) / unit),
Math.floor((duration.seconds || 0) / unit),
];
return normalizedUnits.reduce((acc, curr) => acc + curr, 0);
};
export const normalizeRelativeTrigger = (duration: VcalDurationValue, isAllDay: boolean) => {
const { minutes, hours, weeks, days, isNegative } = duration;
if (isAllDay) {
// the API admits all trigger components for all-day events,
// but we do not support arbitrary combinations of non-zero values for weeks and days
const isMidNightAlarm = hours === 0 && minutes === 0;
const mustKeepWeeks = !isNegative || isMidNightAlarm ? days === 0 : days === 6;
return mustKeepWeeks
? { ...duration, seconds: 0 }
: { ...duration, weeks: 0, days: days + 7 * weeks, seconds: 0 };
}
// We only admit one trigger component for part-day events
// If that's the case already, no need to normalize
if ([minutes, hours, weeks, days].filter(isTruthy).length <= 1) {
return { ...duration, seconds: 0 };
}
// Otherwise, normalize to a single component
const result = { weeks: 0, days: 0, hours: 0, minutes: 0, seconds: 0, isNegative };
const totalMinutes = normalizeDurationToUnit(duration, MINUTE);
if (totalMinutes % 60 !== 0) {
return { ...result, minutes: totalMinutes };
}
const totalHours = Math.floor(totalMinutes / 60);
if (totalHours % 24 !== 0) {
return { ...result, hours: totalHours };
}
const totalDays = Math.floor(totalHours / 24);
if (totalDays % 7 !== 0) {
return { ...result, days: totalDays };
}
const totalWeeks = Math.floor(totalDays / 7);
return { ...result, weeks: totalWeeks };
};
export const normalizeTrigger = (trigger: VcalTriggerProperty, dtstart: VcalDateOrDateTimeProperty) => {
const duration = getIsAbsoluteTrigger(trigger) ? absoluteToRelativeTrigger(trigger, dtstart) : trigger.value;
return normalizeRelativeTrigger(duration, getIsPropertyAllDay(dtstart));
};
| 8,364 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto/constants.ts | export const SIGNATURE_CONTEXT = {
SHARE_CALENDAR_INVITE: 'calendar.sharing.invite'
};
| 8,365 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto/decrypt.ts | import { CryptoProxy, PrivateKeyReference, PublicKeyReference, SessionKey, VERIFICATION_STATUS } from '@proton/crypto';
import { stringToUtf8Array, utf8ArrayToString } from '@proton/crypto/lib/utils';
import { captureMessage } from '@proton/shared/lib/helpers/sentry';
import { base64StringToUint8Array } from '../../helpers/encoding';
import { CalendarEventData } from '../../interfaces/calendar';
import { SimpleMap } from '../../interfaces/utils';
import { CALENDAR_CARD_TYPE, EVENT_VERIFICATION_STATUS } from '../constants';
export const getEventVerificationStatus = (status: VERIFICATION_STATUS | undefined, hasPublicKeys: boolean) => {
if (!hasPublicKeys || status === undefined) {
return EVENT_VERIFICATION_STATUS.NOT_VERIFIED;
}
return status === VERIFICATION_STATUS.SIGNED_AND_VALID
? EVENT_VERIFICATION_STATUS.SUCCESSFUL
: EVENT_VERIFICATION_STATUS.FAILED;
};
/**
* Given an array with signature verification status values, which correspond to verifying different parts of a component,
* return an aggregated signature verification status for the component.
*/
export const getAggregatedEventVerificationStatus = (arr: (EVENT_VERIFICATION_STATUS | undefined)[]) => {
if (!arr.length) {
return EVENT_VERIFICATION_STATUS.NOT_VERIFIED;
}
if (arr.some((verification) => verification === EVENT_VERIFICATION_STATUS.FAILED)) {
return EVENT_VERIFICATION_STATUS.FAILED;
}
if (arr.every((verification) => verification === EVENT_VERIFICATION_STATUS.SUCCESSFUL)) {
return EVENT_VERIFICATION_STATUS.SUCCESSFUL;
}
return EVENT_VERIFICATION_STATUS.NOT_VERIFIED;
};
export const getDecryptedSessionKey = async (
data: Uint8Array,
privateKeys: PrivateKeyReference | PrivateKeyReference[]
) => {
return CryptoProxy.decryptSessionKey({ binaryMessage: data, decryptionKeys: privateKeys });
};
export const getNeedsLegacyVerification = (verifiedBinary: VERIFICATION_STATUS, textData: string) => {
if (verifiedBinary !== VERIFICATION_STATUS.SIGNED_AND_INVALID) {
return false;
}
if (/ \r\n/.test(textData)) {
// if there are trailing spaces using the RFC-compliant line separator, those got stripped by clients signing
// as-text with the stripTrailingSpaces option enabled. We need legacy verification.
return true;
}
const textDataWithoutCRLF = textData.replaceAll(`\r\n`, '');
// if there are "\n" end-of-lines we need legacy verification as those got normalized by clients signing as-text
return /\n/.test(textDataWithoutCRLF);
};
const getVerifiedLegacy = async ({
textData,
signature,
publicKeys,
}: {
textData: string;
signature: string;
publicKeys: PublicKeyReference | PublicKeyReference[];
}) => {
/**
* Verification of an ical card may have failed because the signature is a legacy one,
* done as text and therefore using OpenPGP normalization (\n -> \r\n) + stripping trailing spaces.
*
* We try to verify the signature in the legacy way and log the fact in Sentry
*/
captureMessage('Fallback to legacy signature verification of calendar event', { level: 'info' });
const { verified: verifiedLegacy } = await CryptoProxy.verifyMessage({
textData,
stripTrailingSpaces: true,
verificationKeys: publicKeys,
armoredSignature: signature,
});
return verifiedLegacy;
};
export const verifySignedCard = async (
dataToVerify: string,
signature: string,
publicKeys: PublicKeyReference | PublicKeyReference[]
) => {
const { verified: verifiedBinary } = await CryptoProxy.verifyMessage({
binaryData: stringToUtf8Array(dataToVerify), // not 'utf8' to avoid issues with trailing spaces and automatic normalisation of EOLs to \n
verificationKeys: publicKeys,
armoredSignature: signature,
});
const verified = getNeedsLegacyVerification(verifiedBinary, dataToVerify)
? await getVerifiedLegacy({ textData: dataToVerify, signature, publicKeys })
: verifiedBinary;
const hasPublicKeys = Array.isArray(publicKeys) ? !!publicKeys.length : !!publicKeys;
const verificationStatus = getEventVerificationStatus(verified, hasPublicKeys);
return { data: dataToVerify, verificationStatus };
};
export const decryptCard = async (
dataToDecrypt: Uint8Array,
signature: string | null,
publicKeys: PublicKeyReference | PublicKeyReference[],
sessionKey: SessionKey
) => {
const { data: decryptedData, verified: verifiedBinary } = await CryptoProxy.decryptMessage({
binaryMessage: dataToDecrypt,
format: 'binary', // even though we convert to utf8 later, we can't use 'utf8' here as that would entail automatic normalisation of EOLs to \n
verificationKeys: publicKeys,
armoredSignature: signature || undefined,
sessionKeys: [sessionKey],
});
const decryptedText = utf8ArrayToString(decryptedData);
const verified =
signature && getNeedsLegacyVerification(verifiedBinary, decryptedText)
? await getVerifiedLegacy({ textData: decryptedText, signature, publicKeys })
: verifiedBinary;
const hasPublicKeys = Array.isArray(publicKeys) ? !!publicKeys.length : !!publicKeys;
const verificationStatus = getEventVerificationStatus(verified, hasPublicKeys);
return { data: utf8ArrayToString(decryptedData), verificationStatus };
};
export const decryptAndVerifyCalendarEvent = (
{ Type, Data, Signature, Author }: CalendarEventData,
publicKeysMap: SimpleMap<PublicKeyReference | PublicKeyReference[]>,
sessionKey: SessionKey | undefined
): Promise<{ data: string; verificationStatus: EVENT_VERIFICATION_STATUS }> => {
const publicKeys = publicKeysMap[Author] || [];
if (Type === CALENDAR_CARD_TYPE.CLEAR_TEXT) {
return Promise.resolve({ data: Data, verificationStatus: EVENT_VERIFICATION_STATUS.NOT_VERIFIED });
}
if (Type === CALENDAR_CARD_TYPE.ENCRYPTED) {
if (!sessionKey) {
throw new Error('Cannot decrypt without session key');
}
return decryptCard(base64StringToUint8Array(Data), Signature, [], sessionKey);
}
if (Type === CALENDAR_CARD_TYPE.SIGNED) {
if (!Signature) {
throw new Error('Signed card is missing signature');
}
return verifySignedCard(Data, Signature, publicKeys);
}
if (Type === CALENDAR_CARD_TYPE.ENCRYPTED_AND_SIGNED) {
if (!Signature) {
throw new Error('Encrypted and signed card is missing signature');
}
if (!sessionKey) {
throw new Error('Cannot decrypt without session key');
}
return decryptCard(base64StringToUint8Array(Data), Signature, publicKeys, sessionKey);
}
throw new Error('Unknow event card type');
};
| 8,366 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto/encrypt.ts | import { CryptoProxy, PrivateKeyReference, PublicKeyReference, SessionKey } from '@proton/crypto';
import { stringToUtf8Array } from '@proton/crypto/lib/utils';
import { SimpleMap } from '../../interfaces';
import { EncryptPartResult, SignPartResult } from '../../interfaces/calendar';
export function signPart(dataToSign: string, signingKey: PrivateKeyReference): Promise<SignPartResult>;
export function signPart(
dataToSign: string | undefined,
signingKey: PrivateKeyReference
): Promise<SignPartResult | undefined>;
export async function signPart(
dataToSign: string | undefined,
signingKey: PrivateKeyReference
): Promise<SignPartResult | undefined> {
if (!dataToSign) {
return;
}
const signature = await CryptoProxy.signMessage({
binaryData: stringToUtf8Array(dataToSign),
signingKeys: [signingKey],
detached: true,
});
return {
data: dataToSign,
signature,
};
}
export function encryptPart(
dataToEncrypt: string,
signingKey: PrivateKeyReference,
sessionKey: SessionKey
): Promise<EncryptPartResult>;
export function encryptPart(
dataToEncrypt: string | undefined,
signingKey: PrivateKeyReference,
sessionKey: SessionKey
): Promise<EncryptPartResult | undefined>;
export async function encryptPart(
dataToEncrypt: string | undefined,
signingKey: PrivateKeyReference,
sessionKey: SessionKey
): Promise<EncryptPartResult | undefined> {
if (!dataToEncrypt) {
return;
}
const { message: encryptedData, signature: binarySignature } = await CryptoProxy.encryptMessage({
binaryData: stringToUtf8Array(dataToEncrypt),
signingKeys: [signingKey],
sessionKey,
format: 'binary',
detached: true,
});
return {
dataPacket: encryptedData,
signature: await CryptoProxy.getArmoredSignature({ binarySignature }),
};
}
export const getEncryptedSessionKey = async ({ data, algorithm }: SessionKey, publicKey: PublicKeyReference) => {
const encryptedSessionKey = await CryptoProxy.encryptSessionKey({
data,
algorithm,
encryptionKeys: [publicKey],
format: 'binary',
});
return encryptedSessionKey;
};
export const createSessionKey = async (publicKey: PublicKeyReference) =>
CryptoProxy.generateSessionKey({ recipientKeys: publicKey });
export const getEncryptedSessionKeysMap = async (
sessionKey: SessionKey,
publicKeyMap: SimpleMap<PublicKeyReference> = {}
) => {
const emails = Object.keys(publicKeyMap);
if (!emails.length) {
return;
}
const result: SimpleMap<Uint8Array> = {};
await Promise.all(
emails.map(async (email) => {
const publicKey = publicKeyMap[email];
if (!publicKey) {
return;
}
result[email] = await getEncryptedSessionKey(sessionKey, publicKey);
})
);
return result;
};
| 8,367 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto/keys/calendarKeys.ts | import { c } from 'ttag';
import {
CryptoProxy,
PrivateKeyReference,
PublicKeyReference,
SessionKey,
VERIFICATION_STATUS,
toPublicKeyReference,
} from '@proton/crypto';
import { SIGNATURE_CONTEXT } from '@proton/shared/lib/calendar/crypto/constants';
import isTruthy from '@proton/utils/isTruthy';
import { ENCRYPTION_CONFIGS, ENCRYPTION_TYPES } from '../../../constants';
import { uint8ArrayToBase64String } from '../../../helpers/encoding';
import { EncryptionConfig, SimpleMap } from '../../../interfaces';
import { CreateOrResetCalendarPayload, DecryptedCalendarKey, CalendarKey as tsKey } from '../../../interfaces/calendar';
import { getEncryptedSessionKey } from '../encrypt';
export const generatePassphrase = () => {
const value = crypto.getRandomValues(new Uint8Array(32));
return uint8ArrayToBase64String(value);
};
/**
* The calendar key is generated with less user info to not confuse if the key is exported.
*/
export const generateCalendarKey = async ({
passphrase,
encryptionConfig,
}: {
passphrase: string;
encryptionConfig: EncryptionConfig;
}) => {
const privateKey = await CryptoProxy.generateKey({
userIDs: [{ name: 'Calendar key' }],
...encryptionConfig,
});
const privateKeyArmored = await CryptoProxy.exportPrivateKey({ privateKey: privateKey, passphrase });
return { privateKey, privateKeyArmored };
};
export const signPassphrase = ({ passphrase, privateKey }: { passphrase: string; privateKey: PrivateKeyReference }) => {
return CryptoProxy.signMessage({ textData: passphrase, signingKeys: privateKey, detached: true });
};
export const encryptPassphrase = async ({
passphrase,
privateKey,
publicKey,
}: {
passphrase: string;
privateKey: PrivateKeyReference;
publicKey: PublicKeyReference;
}): Promise<{
keyPacket: string;
dataPacket: string;
signature: string;
}> => {
const sessionKey = await CryptoProxy.generateSessionKey({ recipientKeys: publicKey });
// we encrypt using `sessionKey` directly instead of `encryptionKeys` so that returned message only includes
// symmetrically encrypted data
const { message: encryptedData, signature: binarySignature } = await CryptoProxy.encryptMessage({
textData: passphrase, // stripTrailingSpaces: false
sessionKey,
signingKeys: privateKey,
detached: true,
format: 'binary',
});
// encrypt to the public key separately to get a separate serialized session key
const encryptedSessionKey = await CryptoProxy.encryptSessionKey({
...sessionKey,
encryptionKeys: publicKey,
format: 'binary',
});
return {
keyPacket: uint8ArrayToBase64String(encryptedSessionKey),
dataPacket: uint8ArrayToBase64String(encryptedData),
signature: await CryptoProxy.getArmoredSignature({ binarySignature }),
};
};
export function encryptPassphraseSessionKey({
sessionKey,
publicKey,
signingKey,
}: {
sessionKey: SessionKey;
publicKey: PublicKeyReference;
signingKey: PrivateKeyReference;
}): Promise<{ encryptedSessionKey: string; armoredSignature: string }>;
export function encryptPassphraseSessionKey({
sessionKey,
memberPublicKeys,
signingKey,
}: {
sessionKey: SessionKey;
memberPublicKeys: SimpleMap<PublicKeyReference>;
signingKey: PrivateKeyReference;
}): Promise<{ encryptedSessionKeyMap: SimpleMap<string>; armoredSignature: string }>;
export function encryptPassphraseSessionKey({
sessionKey,
memberPublicKeys,
signingKey,
}: {
sessionKey: SessionKey;
memberPublicKeys: SimpleMap<PublicKeyReference>;
signingKey: PrivateKeyReference;
}): Promise<{ encryptedSessionKey?: string; encryptedSessionKeyMap?: SimpleMap<string>; armoredSignature: string }>;
export async function encryptPassphraseSessionKey({
sessionKey,
publicKey,
memberPublicKeys,
signingKey,
}: {
sessionKey: SessionKey;
publicKey?: PublicKeyReference;
memberPublicKeys?: SimpleMap<PublicKeyReference>;
signingKey: PrivateKeyReference;
}) {
const armoredSignaturePromise = CryptoProxy.signMessage({
binaryData: sessionKey.data,
signingKeys: signingKey,
detached: true,
format: 'armored',
context: { critical: true, value: SIGNATURE_CONTEXT.SHARE_CALENDAR_INVITE },
});
if (publicKey) {
const [armoredSignature, encryptedSessionKey] = await Promise.all([
armoredSignaturePromise,
uint8ArrayToBase64String(await getEncryptedSessionKey(sessionKey, publicKey)),
]);
return {
encryptedSessionKey,
armoredSignature,
};
} else if (memberPublicKeys) {
const encryptedSessionKeysPromise = Promise.all(
Object.entries(memberPublicKeys).map(async ([id, publicKey]) => {
if (!publicKey) {
throw new Error('Missing public key for member');
}
const keyPacket = uint8ArrayToBase64String(await getEncryptedSessionKey(sessionKey, publicKey));
return [id, keyPacket];
})
);
const [armoredSignature, encryptedSessionKeys] = await Promise.all([
armoredSignaturePromise,
encryptedSessionKeysPromise,
]);
return {
encryptedSessionKeyMap: Object.fromEntries(encryptedSessionKeys),
armoredSignature,
};
}
throw new Error('Missing parameters to encrypt session key');
}
/**
* Decrypts a calendar passphrase with either some private keys or a session key
*/
export const decryptPassphrase = async ({
armoredPassphrase,
sessionKey,
armoredSignature,
privateKeys,
publicKeys,
}: {
armoredPassphrase: string;
sessionKey?: SessionKey;
armoredSignature?: string;
privateKeys?: PrivateKeyReference[];
publicKeys?: PublicKeyReference[];
}) => {
const { data: decryptedPassphrase, verified } = await CryptoProxy.decryptMessage({
armoredMessage: armoredPassphrase,
armoredSignature,
decryptionKeys: privateKeys,
verificationKeys: publicKeys,
sessionKeys: sessionKey,
});
if (publicKeys?.length && verified !== VERIFICATION_STATUS.SIGNED_AND_VALID) {
const error = new Error(c('Error').t`Signature verification failed`);
error.name = 'SignatureError';
throw error;
}
return decryptedPassphrase;
};
/**
* Retrieves the decrypted session key that encrypts a calendar passphrase with a private key
*/
export const decryptPassphraseSessionKey = ({
armoredPassphrase,
privateKeys,
}: {
armoredPassphrase: string;
privateKeys: PrivateKeyReference[];
}) => {
return CryptoProxy.decryptSessionKey({
armoredMessage: armoredPassphrase,
decryptionKeys: privateKeys,
});
};
/**
* Decrypt the calendar keys.
* @param Keys - the calendar keys as coming from the API
* @param passphrasesMap - The decrypted passphrases map
*/
export const getDecryptedCalendarKeys = async (
Keys: tsKey[],
passphrasesMap: { [key: string]: string | undefined } = {}
): Promise<DecryptedCalendarKey[]> => {
const process = async (Key: tsKey) => {
try {
const { PrivateKey, PassphraseID } = Key;
const passphrase = passphrasesMap[PassphraseID] || '';
const privateKey = await CryptoProxy.importPrivateKey({ armoredKey: PrivateKey, passphrase });
const publicKey = await toPublicKeyReference(privateKey);
return {
Key,
privateKey,
publicKey,
};
} catch (e: any) {
return undefined;
}
};
return Promise.all(Keys.map(process)).then((result) => {
return result.filter(isTruthy);
});
};
export const generateCalendarKeyPayload = async ({
addressID,
privateKey,
publicKey,
}: {
addressID: string;
privateKey: PrivateKeyReference;
publicKey: PublicKeyReference;
}): Promise<CreateOrResetCalendarPayload> => {
const passphrase = generatePassphrase();
const encryptionConfig = ENCRYPTION_CONFIGS[ENCRYPTION_TYPES.CURVE25519];
const [{ privateKeyArmored: PrivateKey }, { dataPacket: DataPacket, keyPacket: KeyPacket, signature: Signature }] =
await Promise.all([
generateCalendarKey({ passphrase, encryptionConfig }),
encryptPassphrase({ passphrase, privateKey, publicKey }),
]);
return {
AddressID: addressID,
Signature,
PrivateKey,
Passphrase: {
DataPacket,
KeyPacket,
},
};
};
| 8,368 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto/keys/helpers.ts | import { c } from 'ttag';
import isTruthy from '@proton/utils/isTruthy';
import noop from '@proton/utils/noop';
import { hasBit } from '../../../helpers/bitset';
import { uint8ArrayToBase64String } from '../../../helpers/encoding';
import { Address, DecryptedKey } from '../../../interfaces';
import {
CalendarEvent,
CalendarKeyFlags,
CalendarMember,
CalendarSetupData,
CreateOrResetCalendarPayload,
DecryptedCalendarKey,
} from '../../../interfaces/calendar';
import { GetAddressKeys } from '../../../interfaces/hooks/GetAddressKeys';
import { GetCalendarKeys } from '../../../interfaces/hooks/GetCalendarKeys';
import { getPrimaryKey, splitKeys } from '../../../keys';
import { toSessionKey } from '../../../keys/sessionKey';
import { getIsAutoAddedInvite } from '../../apiModels';
import { readSessionKeys } from '../../deserialize';
export const getPrimaryCalendarKey = (calendarKeys: DecryptedCalendarKey[]) => {
const primaryKey = calendarKeys.find(({ Key: { Flags } }) => hasBit(Flags, CalendarKeyFlags.PRIMARY));
if (!primaryKey) {
throw new Error('Calendar primary key not found');
}
return primaryKey;
};
export const getCalendarEventDecryptionKeys = async ({
calendarEvent,
addressKeys,
calendarKeys,
getAddressKeys,
getCalendarKeys,
}: {
calendarEvent: CalendarEvent;
addressKeys?: DecryptedKey[];
calendarKeys?: DecryptedCalendarKey[];
getAddressKeys?: GetAddressKeys;
getCalendarKeys?: GetCalendarKeys;
}) => {
const { CalendarID } = calendarEvent;
if (getIsAutoAddedInvite(calendarEvent)) {
if (!addressKeys && !getAddressKeys) {
return;
}
return splitKeys(addressKeys || (await getAddressKeys?.(calendarEvent.AddressID))).privateKeys;
}
if (!calendarKeys && !getCalendarKeys) {
return;
}
return splitKeys(calendarKeys || (await getCalendarKeys?.(CalendarID))).privateKeys;
};
export const getCreationKeys = async ({
calendarEvent,
newAddressKeys,
oldAddressKeys,
newCalendarKeys,
oldCalendarKeys,
decryptedSharedKeyPacket,
}: {
calendarEvent?: CalendarEvent;
newAddressKeys: DecryptedKey[];
oldAddressKeys?: DecryptedKey[];
newCalendarKeys: DecryptedCalendarKey[];
oldCalendarKeys?: DecryptedCalendarKey[];
decryptedSharedKeyPacket?: string;
}) => {
const primaryAddressKey = getPrimaryKey(newAddressKeys);
const primaryPrivateAddressKey = primaryAddressKey ? primaryAddressKey.privateKey : undefined;
if (!primaryPrivateAddressKey) {
throw new Error(c('Error').t`Address primary private key not found`);
}
const { publicKey: primaryPublicCalendarKey } = getPrimaryCalendarKey(newCalendarKeys);
if (!calendarEvent) {
return {
publicKey: primaryPublicCalendarKey,
privateKey: primaryPrivateAddressKey,
sharedSessionKey: decryptedSharedKeyPacket ? toSessionKey(decryptedSharedKeyPacket) : undefined,
};
}
const privateKeys = await getCalendarEventDecryptionKeys({
calendarEvent,
addressKeys: oldAddressKeys,
calendarKeys: oldCalendarKeys || newCalendarKeys,
});
const [sharedSessionKey, calendarSessionKey] = await readSessionKeys({
calendarEvent,
privateKeys,
decryptedSharedKeyPacket,
});
return {
publicKey: primaryPublicCalendarKey,
privateKey: primaryPrivateAddressKey,
sharedSessionKey,
calendarSessionKey,
};
};
export const getSharedSessionKey = async ({
calendarEvent,
calendarKeys,
getAddressKeys,
getCalendarKeys,
}: {
calendarEvent: CalendarEvent;
calendarKeys?: DecryptedCalendarKey[];
getAddressKeys?: GetAddressKeys;
getCalendarKeys?: GetCalendarKeys;
}) => {
try {
// we need to decrypt the sharedKeyPacket in Event to obtain the decrypted session key
const privateKeys = calendarKeys
? splitKeys(calendarKeys).privateKeys
: await getCalendarEventDecryptionKeys({ calendarEvent, getAddressKeys, getCalendarKeys });
if (!privateKeys) {
return;
}
const [sessionKey] = await readSessionKeys({ calendarEvent, privateKeys });
return sessionKey;
} catch (e: any) {
noop();
}
};
export const getBase64SharedSessionKey = async ({
calendarEvent,
calendarKeys,
getAddressKeys,
getCalendarKeys,
}: {
calendarEvent: CalendarEvent;
calendarKeys?: DecryptedCalendarKey[];
getAddressKeys?: GetAddressKeys;
getCalendarKeys?: GetCalendarKeys;
}) => {
const sessionKey = await getSharedSessionKey({ calendarEvent, calendarKeys, getAddressKeys, getCalendarKeys });
return sessionKey ? uint8ArrayToBase64String(sessionKey.data) : undefined;
};
export const getAddressesMembersMap = (Members: CalendarMember[], Addresses: Address[]) => {
return Members.reduce<{ [key: string]: Address }>((acc, Member) => {
const Address = Addresses.find(({ Email }) => Email === Member.Email);
if (!Address) {
return acc;
}
acc[Member.ID] = Address;
return acc;
}, {});
};
export const isCalendarSetupData = (
payload: CreateOrResetCalendarPayload | CalendarSetupData
): payload is CalendarSetupData => isTruthy(payload.Passphrase.KeyPacket);
| 8,369 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto/keys/reactivateCalendarKeys.ts | import { useGetAddressKeys } from '@proton/components';
import { CryptoProxy } from '@proton/crypto';
import { getAllCalendarKeys, getPassphrases, queryMembers, reactivateCalendarKey } from '../../../api/calendars';
import { Address, Api } from '../../../interfaces';
import { Calendar, CalendarKey, CalendarMember, Passphrase, ReenableKeyResponse } from '../../../interfaces/calendar';
import { splitKeys } from '../../../keys';
import { getMemberAddressWithAdminPermissions } from '../../getMemberWithAdmin';
import { decryptPassphrase } from './calendarKeys';
interface ReactivateCalendarsKeysArgumentsShared {
api: Api;
getAddressKeys: ReturnType<typeof useGetAddressKeys>;
addresses: Address[];
}
interface ReactivateCalendarsKeysArguments extends ReactivateCalendarsKeysArgumentsShared {
calendars: Calendar[];
}
interface ReactivateCalendarKeysArguments extends ReactivateCalendarsKeysArgumentsShared {
ID: string;
}
const reactivateCalendarKeys = async ({
api,
ID: CalendarID,
getAddressKeys,
addresses,
}: ReactivateCalendarKeysArguments) => {
const [{ Keys = [] }, { Passphrases = [] }, { Members = [] }] = await Promise.all([
api<{ Keys: CalendarKey[] }>(getAllCalendarKeys(CalendarID)),
api<{ Passphrases: Passphrase[] }>(getPassphrases(CalendarID)),
api<{ Members: CalendarMember[] }>(queryMembers(CalendarID)),
]);
const { Member: selfMember, Address: selfAddress } = getMemberAddressWithAdminPermissions(Members, addresses);
const addressKeys = await getAddressKeys(selfAddress.ID);
const { privateKeys, publicKeys } = splitKeys(addressKeys);
const decryptedPrimaryPassphrase = await (() => {
const targetPassphrase = Passphrases.find(({ Flags }) => Flags === 1);
if (!targetPassphrase) {
throw new Error('Passphrase not found');
}
const { MemberPassphrases = [] } = targetPassphrase;
const memberPassphrase = MemberPassphrases.find(({ MemberID }) => MemberID === selfMember.ID);
if (!memberPassphrase) {
throw new Error('Member passphrase not found');
}
const { Passphrase, Signature } = memberPassphrase;
return decryptPassphrase({
armoredPassphrase: Passphrase,
armoredSignature: Signature,
privateKeys,
publicKeys,
});
})();
return Promise.all(
Keys.filter(({ Flags }) => Flags === 0).map(async ({ PassphraseID, PrivateKey, ID: KeyID }) => {
try {
const targetPassphrase = Passphrases.find(
({ ID: otherPassphraseID }) => otherPassphraseID === PassphraseID
);
if (!targetPassphrase) {
throw new Error('Passphrase not found');
}
const { MemberPassphrases = [] } = targetPassphrase;
const memberPassphrase = MemberPassphrases.find(({ MemberID }) => MemberID === selfMember.ID);
if (!memberPassphrase) {
throw new Error('Member passphrase not found');
}
const { Passphrase, Signature } = memberPassphrase;
const decryptedPassphrase = await decryptPassphrase({
armoredPassphrase: Passphrase,
armoredSignature: Signature,
privateKeys,
publicKeys,
});
const privateKey = await CryptoProxy.importPrivateKey({
armoredKey: PrivateKey,
passphrase: decryptedPassphrase,
});
const armoredEncryptedKey = await CryptoProxy.exportPrivateKey({
privateKey: privateKey,
passphrase: decryptedPrimaryPassphrase,
});
return await api<ReenableKeyResponse>(
reactivateCalendarKey(CalendarID, KeyID, { PrivateKey: armoredEncryptedKey })
);
} catch (e: any) {
console.error(e);
}
})
);
};
export const reactivateCalendarsKeys = async ({
api,
calendars,
getAddressKeys,
addresses,
}: ReactivateCalendarsKeysArguments) => {
return Promise.all(
calendars.map(async (calendar) => {
return reactivateCalendarKeys({
api,
ID: calendar.ID,
getAddressKeys,
addresses,
});
})
);
};
| 8,370 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto/keys/resetCalendarKeys.ts | import { useGetAddressKeys } from '@proton/components';
import { resetCalendars } from '../../../api/calendars';
import { Api } from '../../../interfaces';
import { VisualCalendar } from '../../../interfaces/calendar';
import { getPrimaryKey } from '../../../keys';
import { generateCalendarKeyPayload } from './calendarKeys';
interface ResetCalendarKeysArguments {
calendars: VisualCalendar[];
api: Api;
getAddressKeys: ReturnType<typeof useGetAddressKeys>;
}
export const resetCalendarKeys = async ({ calendars, api, getAddressKeys }: ResetCalendarKeysArguments) => {
const calendarsResult = await Promise.all(
calendars.map(async ({ Members: [{ AddressID: addressID }] }) => {
const { privateKey: primaryAddressKey, publicKey: primaryAddressPublicKey } =
getPrimaryKey(await getAddressKeys(addressID)) || {};
if (!primaryAddressKey || !primaryAddressPublicKey) {
throw new Error('Calendar owner is missing keys');
}
return generateCalendarKeyPayload({
addressID,
privateKey: primaryAddressKey,
publicKey: primaryAddressPublicKey,
});
})
);
const resetPayload = calendars.reduce((acc, { ID: calendarID }, i) => {
return {
...acc,
[calendarID]: calendarsResult[i],
};
}, {});
return api(
resetCalendars({
CalendarKeys: resetPayload,
})
);
};
| 8,371 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto/keys/resetHelper.ts | import { c } from 'ttag';
import { useGetAddressKeys, useGetAddresses } from '@proton/components';
import { getSilentApi } from '../../../api/helpers/customConfig';
import getHasSharedCalendars from '../../../calendar/sharing/getHasSharedCalendars';
import { Api } from '../../../interfaces';
import { VisualCalendar } from '../../../interfaces/calendar';
import { CalendarsModel } from '../../../models';
import { loadModels } from '../../../models/helper';
import { getIsOwnedCalendar } from '../../calendar';
import { reactivateCalendarsKeys } from './reactivateCalendarKeys';
import { resetCalendarKeys } from './resetCalendarKeys';
interface ProcessArguments {
api: Api;
cache: any;
getAddresses: ReturnType<typeof useGetAddresses>;
getAddressKeys: ReturnType<typeof useGetAddressKeys>;
calendarsToReset?: VisualCalendar[];
calendarsToReactivate?: VisualCalendar[];
calendarsToClean?: VisualCalendar[];
}
export const process = async ({
api,
cache,
getAddresses,
getAddressKeys,
calendarsToReset = [],
calendarsToReactivate = [],
calendarsToClean = [],
}: ProcessArguments) => {
const addresses = await getAddresses();
if (!addresses.length) {
throw new Error(c('Error').t`Please create an address first.`);
}
let hasSharedCalendars = false;
if (calendarsToReset.length > 0 || calendarsToClean.length > 0) {
// Non-owners can't reset calendar keys
// Even if calendarsToReset is empty, we want to call the reset endpoint in order to clean shared/holidays calendars
const calendars = calendarsToReset.filter((calendar) => getIsOwnedCalendar(calendar));
const [hasShared] = await Promise.all([
getHasSharedCalendars({
calendars,
api: getSilentApi(api),
catchErrors: true,
}),
resetCalendarKeys({
calendars,
api,
getAddressKeys,
}),
]);
hasSharedCalendars = hasShared;
}
if (calendarsToReactivate.length > 0) {
await reactivateCalendarsKeys({
api,
calendars: calendarsToReactivate,
getAddressKeys,
addresses,
});
}
// Refresh the calendar model to be able to get the new flags since it's not updated through the event manager
await loadModels([CalendarsModel], { api, cache, useCache: false });
return hasSharedCalendars;
};
| 8,372 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto/keys/setupCalendarHelper.ts | import { c } from 'ttag';
import { useGetAddressKeys } from '@proton/components';
import { createCalendar, updateCalendarUserSettings } from '../../../api/calendars';
import { getRandomAccentColor } from '../../../colors';
import { getTimezone } from '../../../date/timezone';
import { getActiveAddresses } from '../../../helpers/address';
import { Address, Api } from '../../../interfaces';
import { CalendarWithOwnMembers } from '../../../interfaces/calendar';
import { getPrimaryKey } from '../../../keys';
import { DEFAULT_CALENDAR } from '../../constants';
import { setupCalendarKey } from './setupCalendarKeys';
interface Args {
addresses: Address[];
api: Api;
getAddressKeys: ReturnType<typeof useGetAddressKeys>;
}
const setupCalendarHelper = async ({ addresses, api, getAddressKeys }: Args) => {
const activeAddresses = getActiveAddresses(addresses);
if (!activeAddresses.length) {
throw new Error(c('Error').t`No valid address found`);
}
const [{ ID: addressID }] = activeAddresses;
const { privateKey: primaryAddressKey } = getPrimaryKey(await getAddressKeys(addressID)) || {};
if (!primaryAddressKey) {
throw new Error(c('Error').t`Primary address key is not decrypted.`);
}
const { Calendar } = await api<{ Calendar: CalendarWithOwnMembers }>(
createCalendar({
Name: DEFAULT_CALENDAR.name,
Color: getRandomAccentColor(),
Description: DEFAULT_CALENDAR.description,
Display: 1,
AddressID: addressID,
})
);
const updatedCalendarUserSettings = {
PrimaryTimezone: getTimezone(),
AutoDetectPrimaryTimezone: 1,
};
const [
{
Passphrase: { Flags },
},
] = await Promise.all([
setupCalendarKey({
api,
calendarID: Calendar.ID,
addressID,
getAddressKeys,
}),
api(updateCalendarUserSettings(updatedCalendarUserSettings)),
]);
// There is only one member in the calendar at this point
const calendarWithUpdatedFlags = {
...Calendar,
Members: [
{
...Calendar.Members[0],
Flags,
},
],
};
return {
calendar: calendarWithUpdatedFlags,
updatedCalendarUserSettings,
};
};
export default setupCalendarHelper;
| 8,373 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto/keys/setupCalendarKeys.ts | import { c } from 'ttag';
import { useGetAddressKeys } from '@proton/components/hooks';
import { setupCalendar } from '../../../api/calendars';
import { Api } from '../../../interfaces';
import { CalendarSetupResponse, CalendarWithOwnMembers } from '../../../interfaces/calendar';
import { getPrimaryKey } from '../../../keys';
import { generateCalendarKeyPayload } from './calendarKeys';
import { isCalendarSetupData } from './helpers';
export const setupCalendarKey = async ({
calendarID,
api,
addressID,
getAddressKeys,
}: {
api: Api;
getAddressKeys: ReturnType<typeof useGetAddressKeys>;
calendarID: string;
addressID: string;
}) => {
const { privateKey, publicKey } = getPrimaryKey(await getAddressKeys(addressID)) || {};
if (!privateKey || !publicKey) {
throw new Error(c('Error').t`Primary address key is not decrypted`);
}
const calendarKeyPayload = await generateCalendarKeyPayload({
addressID,
privateKey,
publicKey,
});
if (!isCalendarSetupData(calendarKeyPayload)) {
throw new Error(c('Error').t`Missing key packet`);
}
return api<CalendarSetupResponse>(setupCalendar(calendarID, calendarKeyPayload));
};
export const setupCalendarKeys = async ({
api,
calendars,
getAddressKeys,
}: {
api: Api;
calendars: CalendarWithOwnMembers[];
getAddressKeys: ReturnType<typeof useGetAddressKeys>;
}) => {
return Promise.all(
calendars.map(async ({ ID: calendarID, Members }) => {
const addressID = Members[0]?.AddressID;
if (!addressID) {
return;
}
return setupCalendarKey({ calendarID, api, getAddressKeys, addressID });
})
);
};
| 8,374 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/crypto/keys/setupHolidaysCalendarHelper.ts | import {joinHolidaysCalendar} from '../../../api/calendars';
import {Address, Api} from '../../../interfaces';
import {CalendarNotificationSettings, HolidaysDirectoryCalendar} from '../../../interfaces/calendar';
import {GetAddressKeys} from '../../../interfaces/hooks/GetAddressKeys';
import {getJoinHolidaysCalendarData} from '../../holidaysCalendar/holidaysCalendar';
interface Props {
holidaysCalendar: HolidaysDirectoryCalendar;
color: string;
notifications: CalendarNotificationSettings[];
addresses: Address[];
getAddressKeys: GetAddressKeys;
api: Api;
}
const setupHolidaysCalendarHelper = async ({ holidaysCalendar, color, notifications, addresses, getAddressKeys, api }: Props) => {
const { calendarID, addressID, payload } = await getJoinHolidaysCalendarData({
holidaysCalendar,
addresses,
getAddressKeys,
color,
notifications,
});
return api(joinHolidaysCalendar(calendarID, addressID, payload));
};
export default setupHolidaysCalendarHelper;
| 8,375 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/export/createExportIcs.ts | import { RequireSome } from '../../interfaces';
import { VcalVcalendar, VcalVeventComponent, VcalVtimezoneComponent, VisualCalendar } from '../../interfaces/calendar';
import { ICAL_METHOD } from '../constants';
import { serialize } from '../vcal';
interface CreateExportIcsParams {
prodId: string;
eventsWithSummary: VcalVeventComponent[];
vtimezones?: VcalVtimezoneComponent[];
calendar: VisualCalendar;
defaultTzid: string;
}
type ExportVcal = RequireSome<VcalVcalendar, 'components'> & {
'X-WR-TIMEZONE': { value: string };
'X-WR-CALNAME': { value: string };
'X-WR-CALDESC'?: { value: string };
};
export const createExportIcs = ({
calendar,
prodId,
eventsWithSummary,
vtimezones = [],
defaultTzid,
}: CreateExportIcsParams): string => {
const exportVcal: ExportVcal = {
component: 'vcalendar',
components: [...vtimezones, ...eventsWithSummary],
prodid: { value: prodId },
version: { value: '2.0' },
method: { value: ICAL_METHOD.PUBLISH },
calscale: { value: 'GREGORIAN' },
'X-WR-TIMEZONE': { value: defaultTzid },
'X-WR-CALNAME': { value: calendar.Name },
};
if (calendar.Description) {
exportVcal['X-WR-CALDESC'] = { value: calendar.Description };
}
return serialize(exportVcal);
};
| 8,376 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/export/export.ts | import { fromUnixTime } from 'date-fns';
import { c } from 'ttag';
import { CryptoProxy } from '@proton/crypto';
import { withSupportedSequence } from '@proton/shared/lib/calendar/icsSurgery/vevent';
import isTruthy from '@proton/utils/isTruthy';
import partition from '@proton/utils/partition';
import unique from '@proton/utils/unique';
import { getEvent, queryEventsIDs } from '../../api/calendars';
import { getSilentApi } from '../../api/helpers/customConfig';
import { SECOND } from '../../constants';
import formatUTC from '../../date-fns-utc/format';
import { WeekStartsOn } from '../../date-fns-utc/interface';
import {
formatGMTOffsetAbbreviation,
fromUTCDate,
fromUTCDateToLocalFakeUTCDate,
getTimezoneOffset,
} from '../../date/timezone';
import { dateLocale } from '../../i18n';
import { Address, Api, Key } from '../../interfaces';
import {
CalendarEvent,
CalendarSettings,
EXPORT_EVENT_ERROR_TYPES,
ExportError,
VcalVeventComponent,
VisualCalendar,
} from '../../interfaces/calendar';
import { CalendarEventsIDsQuery } from '../../interfaces/calendar/Api';
import { GetAddressKeys } from '../../interfaces/hooks/GetAddressKeys';
import { GetCalendarKeys } from '../../interfaces/hooks/GetCalendarKeys';
import { getIsAutoAddedInvite } from '../apiModels';
import { withNormalizedAuthors } from '../author';
import { getIsOwnedCalendar } from '../calendar';
import { getCalendarEventDecryptionKeys } from '../crypto/keys/helpers';
import { readCalendarEvent, readSessionKeys } from '../deserialize';
import { getTimezonedFrequencyString } from '../recurrence/getFrequencyString';
import { fromRruleString } from '../vcal';
import { getDateProperty } from '../vcalConverter';
import { withMandatoryPublishFields } from '../veventHelper';
export const getHasCalendarEventMatchingSigningKeys = async (event: CalendarEvent, keys: Key[]) => {
const allEventSignatures = [...event.SharedEvents, ...event.CalendarEvents, ...event.AttendeesEvents].flatMap(
(event) => (event.Signature ? [event.Signature] : [])
);
const allSignaturesKeyInfo = await Promise.all(
allEventSignatures.map((armoredSignature) => CryptoProxy.getSignatureInfo({ armoredSignature }))
);
const allSigningKeyIDs = unique(allSignaturesKeyInfo.flatMap(({ signingKeyIDs }) => signingKeyIDs));
for (const { PrivateKey: armoredKey } of keys) {
const { keyIDs } = await CryptoProxy.getKeyInfo({ armoredKey });
const isSigningKey = keyIDs.some((keyID) => allSigningKeyIDs.includes(keyID));
if (isSigningKey) {
return true;
}
}
return false;
};
export interface GetErrorProps {
event: CalendarEvent;
errorType: EXPORT_EVENT_ERROR_TYPES;
weekStartsOn: WeekStartsOn;
defaultTzid: string;
}
export const getError = ({ event, errorType, weekStartsOn, defaultTzid }: GetErrorProps): ExportError => {
const { StartTime, RRule, FullDay } = event;
const startDate = new Date(StartTime * SECOND);
const fakeUTCStartDate = fromUTCDateToLocalFakeUTCDate(startDate, !!FullDay, defaultTzid);
const startDateString = formatUTC(fakeUTCStartDate, FullDay ? 'P' : 'Pp', { locale: dateLocale });
const { offset } = getTimezoneOffset(startDate, defaultTzid);
const offsetString = formatGMTOffsetAbbreviation(offset);
const timeString = `${startDateString}${FullDay ? '' : ` ${offsetString}`}`;
const rruleValueFromString = RRule ? fromRruleString(RRule) : undefined;
const utcStartDate = fromUnixTime(StartTime);
const dtstart = getDateProperty(fromUTCDate(utcStartDate));
if (rruleValueFromString) {
const rruleString = getTimezonedFrequencyString({ value: rruleValueFromString }, dtstart, {
currentTzid: defaultTzid,
locale: dateLocale,
weekStartsOn,
});
return [c('Error when exporting event from calendar').t`Event from ${timeString}, ${rruleString}`, errorType];
}
return [c('Error when exporting event from calendar').t`Event @ ${timeString}`, errorType];
};
const getDecryptionErrorType = async (event: CalendarEvent, keys: Key[]) => {
try {
const HasMatchingKeys = await getHasCalendarEventMatchingSigningKeys(event, keys);
if (HasMatchingKeys) {
return EXPORT_EVENT_ERROR_TYPES.PASSWORD_RESET;
}
return EXPORT_EVENT_ERROR_TYPES.DECRYPTION_ERROR;
} catch {
return EXPORT_EVENT_ERROR_TYPES.DECRYPTION_ERROR;
}
};
const decryptEvent = async ({
event,
calendarEmail,
calendarSettings,
defaultTzid,
weekStartsOn,
addresses,
getAddressKeys,
getCalendarKeys,
}: {
event: CalendarEvent;
calendarEmail: string;
calendarSettings: CalendarSettings;
addresses: Address[];
getAddressKeys: GetAddressKeys;
getCalendarKeys: GetCalendarKeys;
weekStartsOn: WeekStartsOn;
defaultTzid: string;
}) => {
const defaultParams = { event, defaultTzid, weekStartsOn };
const eventDecryptionKeys = await getCalendarEventDecryptionKeys({
calendarEvent: event,
getAddressKeys,
getCalendarKeys,
});
try {
const [sharedSessionKey, calendarSessionKey] = await readSessionKeys({
calendarEvent: event,
privateKeys: eventDecryptionKeys,
});
const { CalendarID, ID, SharedEvents, CalendarEvents, AttendeesEvents, Attendees, Notifications, FullDay } =
event;
const { veventComponent } = await readCalendarEvent({
event: {
SharedEvents: withNormalizedAuthors(SharedEvents),
CalendarEvents: withNormalizedAuthors(CalendarEvents),
AttendeesEvents: withNormalizedAuthors(AttendeesEvents),
Attendees,
Notifications,
FullDay,
CalendarID,
ID,
},
calendarSettings,
sharedSessionKey,
calendarSessionKey,
addresses,
encryptingAddressID: getIsAutoAddedInvite(event) ? event.AddressID : undefined,
});
return withSupportedSequence(withMandatoryPublishFields(veventComponent, calendarEmail));
} catch (error: any) {
const inactiveKeys = addresses.flatMap(({ Keys }) => Keys.filter(({ Active }) => !Active));
return getError({
...defaultParams,
errorType: await getDecryptionErrorType(event, inactiveKeys),
});
}
};
const tryDecryptEvent = async ({
calendar,
event,
calendarSettings,
defaultTzid,
weekStartsOn,
addresses,
getAddressKeys,
getCalendarKeys,
}: {
calendar: VisualCalendar;
event: CalendarEvent;
calendarSettings: CalendarSettings;
addresses: Address[];
getAddressKeys: GetAddressKeys;
getCalendarKeys: GetCalendarKeys;
weekStartsOn: WeekStartsOn;
defaultTzid: string;
}) => {
// ignore auto-added invites in shared calendars (they can't be decrypted and we don't display them in the UI)
if (!getIsOwnedCalendar(calendar) && getIsAutoAddedInvite(event)) {
return null;
}
return decryptEvent({
event,
calendarEmail: calendar.Email,
calendarSettings,
defaultTzid,
weekStartsOn,
addresses,
getAddressKeys,
getCalendarKeys,
});
};
const fetchAndTryDecryptEvent = async ({
api,
eventID,
calendar,
calendarSettings,
defaultTzid,
weekStartsOn,
addresses,
getAddressKeys,
getCalendarKeys,
}: {
api: Api;
eventID: string;
calendar: VisualCalendar;
calendarSettings: CalendarSettings;
addresses: Address[];
getAddressKeys: GetAddressKeys;
getCalendarKeys: GetCalendarKeys;
weekStartsOn: WeekStartsOn;
defaultTzid: string;
}) => {
const { Event: event } = await getSilentApi(api)<{ Event: CalendarEvent }>(getEvent(calendar.ID, eventID));
return tryDecryptEvent({
event,
calendar,
calendarSettings,
defaultTzid,
weekStartsOn,
addresses,
getAddressKeys,
getCalendarKeys,
});
};
interface ProcessData {
calendar: VisualCalendar;
addresses: Address[];
getAddressKeys: GetAddressKeys;
getCalendarKeys: GetCalendarKeys;
api: Api;
signal: AbortSignal;
onProgress: (
calendarEventIDs: string[],
veventComponents: VcalVeventComponent[],
exportErrors: ExportError[]
) => void;
totalToProcess: number;
calendarSettings: CalendarSettings;
weekStartsOn: WeekStartsOn;
defaultTzid: string;
}
export const processInBatches = async ({
calendar,
api,
signal,
onProgress,
addresses,
totalToProcess,
getAddressKeys,
getCalendarKeys,
calendarSettings,
weekStartsOn,
defaultTzid,
}: ProcessData): Promise<[VcalVeventComponent[], ExportError[], number]> => {
const PAGE_SIZE = 100;
const batchesLength = Math.ceil(totalToProcess / PAGE_SIZE);
const processed: VcalVeventComponent[] = [];
const errors: ExportError[] = [];
const promises: Promise<void>[] = [];
let totalEventsFetched = 0;
let lastId;
for (let i = 0; i < batchesLength; i++) {
if (signal.aborted) {
return [[], [], totalToProcess];
}
const params: CalendarEventsIDsQuery = {
Limit: PAGE_SIZE,
AfterID: lastId,
};
const IDs = (await api<{ IDs: string[] }>(queryEventsIDs(calendar.ID, params))).IDs;
if (signal.aborted) {
return [[], [], totalToProcess];
}
onProgress(IDs, [], []);
lastId = IDs[IDs.length - 1];
totalEventsFetched += IDs.length;
const promise = Promise.all(
IDs.map((eventID) =>
fetchAndTryDecryptEvent({
api,
eventID,
calendar,
calendarSettings,
defaultTzid,
weekStartsOn,
addresses,
getAddressKeys,
getCalendarKeys,
})
)
)
.then((veventsOrErrors) => {
const veventsOrErrorsNonNull: (VcalVeventComponent | ExportError)[] = veventsOrErrors.filter(isTruthy);
const [veventComponents, exportErrors] = partition<VcalVeventComponent, ExportError>(
veventsOrErrorsNonNull,
(item): item is VcalVeventComponent => !Array.isArray(item)
);
processed.push(...veventComponents);
errors.push(...exportErrors);
onProgress([], veventComponents, exportErrors);
})
.catch((e) => {
const exportErrors: ExportError[] = IDs.map(() => [
e.message,
EXPORT_EVENT_ERROR_TYPES.DECRYPTION_ERROR,
]);
errors.push(...exportErrors);
onProgress([], [], exportErrors);
});
promises.push(promise);
}
await Promise.all(promises);
return [processed, errors, totalEventsFetched];
};
| 8,377 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/holidaysCalendar/holidaysCalendar.ts | import { SessionKey } from '@proton/crypto';
import { encryptPassphraseSessionKey, signPassphrase } from '@proton/shared/lib/calendar/crypto/keys/calendarKeys';
import { Address } from '@proton/shared/lib/interfaces';
import { CalendarNotificationSettings, HolidaysDirectoryCalendar } from '@proton/shared/lib/interfaces/calendar';
import unique from '@proton/utils/unique';
import { getPrimaryAddress } from '../../helpers/address';
import { base64StringToUint8Array } from '../../helpers/encoding';
import { getLanguageCode, getNaiveCountryCode } from '../../i18n/helper';
import { GetAddressKeys } from '../../interfaces/hooks/GetAddressKeys';
/**
* Get all holidays calendars corresponding to a certain time zone
*/
export const getHolidaysCalendarsFromTimeZone = (calendars: HolidaysDirectoryCalendar[], tzid: string) => {
return calendars.filter(({ Timezones }) => Timezones.includes(tzid));
};
/**
* Get all holidays calendars with the same country code and sort them by language.
* We might get several holidays calendars in the same country, but with different languages.
*/
export const getHolidaysCalendarsFromCountryCode = (
holidayCalendars: HolidaysDirectoryCalendar[],
countryCode: string
) => {
return holidayCalendars
.filter(({ CountryCode }) => CountryCode === countryCode)
.sort((a, b) => a.Language.localeCompare(b.Language));
};
/**
* Given a list of country codes, find the preferred one based on language preferences. Result can be undefined.
* See `getSuggestedHolidaysCalendar` for more details on the logic.
*/
export const findPreferredCountryCode = (codes: string[], languageTags: string[]) => {
if (codes.length === 1) {
return codes[0];
}
for (const tag of languageTags) {
const languageCountryCode = getNaiveCountryCode(tag);
const preferredCountryCode = codes.find((code) => code === languageCountryCode);
if (preferredCountryCode) {
return preferredCountryCode;
}
}
};
/**
* Given a list of holidays directory calendars, find the preferred one based on language preferences. Result can be undefined.
* See `getSuggestedHolidaysCalendar` for more details on the logic.
*/
export const findPreferredCalendarByLanguageTag = (calendars: HolidaysDirectoryCalendar[], languageTags: string[]) => {
if (calendars.length === 1) {
return calendars[0];
}
for (const tag of languageTags) {
const code = getLanguageCode(tag);
const preferredCalendar = calendars.find(({ LanguageCode }) => code === LanguageCode.toLowerCase());
if (preferredCalendar) {
return preferredCalendar;
}
}
};
/**
* Given a list of holidays directory calendars belonging to one country, find the preferred one based on language preferences. Result can be undefined.
* See `getSuggestedHolidaysCalendar` for more details on the logic.
*/
export const findHolidaysCalendarByCountryCodeAndLanguageTag = (
calendars: HolidaysDirectoryCalendar[],
countryCode: string,
languageTags: string[]
) => {
const calendarsFromCountry = getHolidaysCalendarsFromCountryCode(calendars, countryCode);
return findPreferredCalendarByLanguageTag(calendarsFromCountry, languageTags) || calendarsFromCountry[0];
};
/**
* Given the user time zone preference, user language preference for the Proton web-apps,
* and a list of language tags (RFC-5646) expressing the user language preference,
* we try to find a calendar that matches those in a directory of holidays calendars.
* The logic for matching is as follows:
*
* * First filter the calendars that are compatible with the user time zone.
*
* * Then try to match a country:
* * * If the filtering above returned the empty array, return undefined.
* * * If the filtered calendars all belong to one country, pick that country.
* * * If there are several countries in the filtered calendars, use the language tags to find a match. Return first match if any
* * * [We don't user the Proton language preference here because we assume there's more granularity in
* * * the language tags passed. E.g. at the moment a user can't choose nl_BE as Proton language]
* * * If there's no match, return undefined.
*
* * If we got a country match, some calendars (calendar <-> language) will be associated to it:
* * * If the country has just one associated calendar (<-> language), pick that one.
* * * If the country has multiple associated calendars (<-> languages):
* * * * If the Proton language matches one of the languages, pick that one.
* * * * If no match, if any of the language tags matches one of the languages (we try in the order of preference given), pick that one.
* * * * If no match, pick the first language in the list.
*/
export const getSuggestedHolidaysCalendar = (
calendars: HolidaysDirectoryCalendar[],
tzid: string,
protonLanguage: string,
languageTags: string[]
) => {
// Get all calendars in the same time zone as the user
const calendarsFromTimeZone = getHolidaysCalendarsFromTimeZone(calendars, tzid);
if (!calendarsFromTimeZone.length) {
return;
}
const countryCodes = unique(calendarsFromTimeZone.map(({ CountryCode }) => CountryCode));
const countryCode = findPreferredCountryCode(countryCodes, languageTags);
if (!countryCode) {
return;
}
return findHolidaysCalendarByCountryCodeAndLanguageTag(calendarsFromTimeZone, countryCode, [
protonLanguage,
...languageTags,
]);
};
export const getJoinHolidaysCalendarData = async ({
holidaysCalendar,
addresses,
getAddressKeys,
color,
notifications,
}: {
holidaysCalendar: HolidaysDirectoryCalendar;
addresses: Address[];
getAddressKeys: GetAddressKeys;
color: string;
notifications: CalendarNotificationSettings[];
}) => {
const {
CalendarID,
Passphrase,
SessionKey: { Key, Algorithm },
} = holidaysCalendar;
const primaryAddress = getPrimaryAddress(addresses);
if (!primaryAddress) {
throw new Error('No primary address');
}
const primaryAddressKey = (await getAddressKeys(primaryAddress.ID))[0];
if (!primaryAddressKey) {
throw new Error('No primary address key');
}
const { privateKey, publicKey } = primaryAddressKey;
const [{ encryptedSessionKey }, signature] = await Promise.all([
encryptPassphraseSessionKey({
sessionKey: { data: base64StringToUint8Array(Key), algorithm: Algorithm } as SessionKey,
publicKey,
signingKey: privateKey,
}),
signPassphrase({ passphrase: Passphrase, privateKey }),
]);
return {
calendarID: CalendarID,
addressID: primaryAddress.ID,
payload: {
PassphraseKeyPacket: encryptedSessionKey,
Signature: signature,
Color: color,
DefaultFullDayNotifications: notifications,
},
};
};
| 8,378 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/icsSurgery/EventInvitationError.ts | import { c } from 'ttag';
import { ICAL_ATTENDEE_STATUS, ICAL_METHOD, ICAL_METHODS_ATTENDEE } from '../constants';
export enum EVENT_INVITATION_ERROR_TYPE {
INVITATION_INVALID,
INVITATION_UNSUPPORTED,
INVALID_METHOD,
NO_COMPONENT,
NO_VEVENT,
PARSING_ERROR,
DECRYPTION_ERROR,
FETCHING_ERROR,
UPDATING_ERROR,
EVENT_CREATION_ERROR,
EVENT_UPDATE_ERROR,
CANCELLATION_ERROR,
UNEXPECTED_ERROR,
EXTERNAL_ERROR,
}
const {
INVITATION_INVALID,
INVITATION_UNSUPPORTED,
INVALID_METHOD,
NO_COMPONENT,
NO_VEVENT,
PARSING_ERROR,
DECRYPTION_ERROR,
FETCHING_ERROR,
UPDATING_ERROR,
EVENT_CREATION_ERROR,
EVENT_UPDATE_ERROR,
CANCELLATION_ERROR,
UNEXPECTED_ERROR,
EXTERNAL_ERROR,
} = EVENT_INVITATION_ERROR_TYPE;
export const getErrorMessage = (errorType: EVENT_INVITATION_ERROR_TYPE, config?: EventInvitationErrorConfig) => {
const isUnknown = !config?.method;
const isImport = config?.method === ICAL_METHOD.PUBLISH;
const isResponse = config?.method && ICAL_METHODS_ATTENDEE.includes(config?.method);
const isProtonInvite = !!config?.isProtonInvite;
if (errorType === INVITATION_INVALID) {
if (isUnknown) {
return c('Attached ics file error').t`Invalid ICS file`;
}
if (isImport) {
return c('Attached ics file error').t`Invalid event`;
}
return isResponse
? c('Event invitation error').t`Invalid response`
: c('Event invitation error').t`Invalid invitation`;
}
if (errorType === INVITATION_UNSUPPORTED) {
if (isImport) {
return c('Attached ics file error').t`Unsupported event`;
}
return isResponse
? c('Event invitation error').t`Unsupported response`
: c('Event invitation error').t`Unsupported invitation`;
}
if (errorType === NO_COMPONENT) {
return c('Attached ics file error').t`Empty ICS file`;
}
if (errorType === NO_VEVENT) {
return c('Attached ics file error').t`Unsupported calendar component`;
}
if (errorType === INVALID_METHOD) {
if (isUnknown) {
return c('Attached ics file error').t`Invalid method`;
}
// Here we invert response <-> invitation as we take the perspective of the sender
return isResponse
? c('Event invitation error').t`Invalid invitation`
: c('Event invitation error').t`Invalid response`;
}
if (errorType === PARSING_ERROR) {
return c('Event invitation error').t`Attached ICS file could not be read`;
}
if (errorType === DECRYPTION_ERROR) {
return c('Event invitation error').t`Attached ICS file could not be decrypted`;
}
if (errorType === FETCHING_ERROR) {
return c('Event invitation error').t`We could not retrieve the event from your calendar`;
}
if (errorType === UPDATING_ERROR) {
return c('Event invitation error').t`We could not update the event in your calendar`;
}
if (errorType === EVENT_CREATION_ERROR) {
return isProtonInvite
? c('Event invitation error').t`The event could not be added to your calendar. No answer was sent`
: c('Event invitation error').t`Your answer was sent, but the event could not be added to your calendar`;
}
if (errorType === EVENT_UPDATE_ERROR) {
return isProtonInvite
? c('Event invitation error').t`The event could not be updated in your calendar. No answer was sent`
: c('Event invitation error').t`Your answer was sent, but the event could not be updated in your calendar`;
}
if (errorType === CANCELLATION_ERROR) {
return c('Event invitation error').t`We could not cancel the event in your calendar`;
}
if (errorType === UNEXPECTED_ERROR) {
return c('Event invitation error').t`Unexpected error`;
}
if (errorType === EXTERNAL_ERROR) {
return config?.externalError?.message || '';
}
return '';
};
interface EventInvitationErrorConfig {
externalError?: Error;
partstat?: ICAL_ATTENDEE_STATUS;
timestamp?: number;
isProtonInvite?: boolean;
method?: ICAL_METHOD;
originalUniqueIdentifier?: string;
}
export class EventInvitationError extends Error {
type: EVENT_INVITATION_ERROR_TYPE;
partstat?: ICAL_ATTENDEE_STATUS;
timestamp?: number;
isProtonInvite?: boolean;
externalError?: Error;
method?: ICAL_METHOD;
originalUniqueIdentifier?: string;
constructor(errorType: EVENT_INVITATION_ERROR_TYPE, config?: EventInvitationErrorConfig) {
super(getErrorMessage(errorType, config));
this.type = errorType;
this.partstat = config?.partstat;
this.timestamp = config?.timestamp;
this.isProtonInvite = config?.isProtonInvite;
this.externalError = config?.externalError;
this.method = config?.method;
this.originalUniqueIdentifier = config?.originalUniqueIdentifier;
Object.setPrototypeOf(this, EventInvitationError.prototype);
}
getConfig() {
return {
type: this.type,
partstat: this.partstat,
timestamp: this.timestamp,
isProtonInvite: this.isProtonInvite,
externalError: this.externalError,
method: this.method,
originalUniqueIdentifier: this.originalUniqueIdentifier,
};
}
}
export const cloneEventInvitationErrorWithConfig = (
error: EventInvitationError,
config: EventInvitationErrorConfig
) => {
const newConfig = {
...error.getConfig(),
...config,
};
return new EventInvitationError(error.type, newConfig);
};
| 8,379 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/icsSurgery/ImportEventError.ts | import { c } from 'ttag';
export enum IMPORT_EVENT_ERROR_TYPE {
WRONG_FORMAT,
NON_GREGORIAN,
TODO_FORMAT,
JOURNAL_FORMAT,
FREEBUSY_FORMAT,
TIMEZONE_FORMAT,
TIMEZONE_IGNORE,
VEVENT_INVALID,
VEVENT_UNSUPPORTED,
UNEXPECTED_FLOATING_TIME,
ALLDAY_INCONSISTENCY,
DTSTART_MISSING,
DTSTART_MALFORMED,
DTSTART_OUT_OF_BOUNDS,
DTEND_MALFORMED,
DTEND_OUT_OF_BOUNDS,
X_WR_TIMEZONE_UNSUPPORTED,
TZID_UNSUPPORTED,
RRULE_MALFORMED,
RRULE_UNSUPPORTED,
SINGLE_EDIT_UNSUPPORTED,
NOTIFICATION_OUT_OF_BOUNDS,
VALIDATION_ERROR,
ENCRYPTION_ERROR,
PARENT_EVENT_MISSING,
EXTERNAL_ERROR,
NO_OCCURRENCES,
}
const getErrorMessage = (errorType: IMPORT_EVENT_ERROR_TYPE, externalError?: Error) => {
if (errorType === IMPORT_EVENT_ERROR_TYPE.NO_OCCURRENCES) {
return c('Error importing event').t`Recurring event has no occurrences`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.WRONG_FORMAT) {
return c('Error importing event').t`Component with wrong format`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.NON_GREGORIAN) {
return c('Error importing event').t`Non-Gregorian`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.TODO_FORMAT) {
return c('Error importing event').t`To-do entry`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.JOURNAL_FORMAT) {
return c('Error importing event').t`Journal entry`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.FREEBUSY_FORMAT) {
return c('Error importing event').t`Free-busy time information`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.TIMEZONE_FORMAT) {
return c('Error importing event').t`Custom time zone`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.TIMEZONE_IGNORE) {
return 'Timezone component ignored';
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.VEVENT_INVALID) {
return c('Error importing event').t`Invalid event`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.VEVENT_UNSUPPORTED) {
return c('Error importing event').t`Unsupported event`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.ALLDAY_INCONSISTENCY) {
return c('Error importing event').t`Malformed all-day event`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.DTSTART_MISSING) {
return c('Error importing event').t`Missing start time`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.DTSTART_MALFORMED) {
return c('Error importing event').t`Malformed start time`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.UNEXPECTED_FLOATING_TIME) {
return c('Error importing event').t`Floating times not supported`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.DTSTART_OUT_OF_BOUNDS) {
return c('Error importing event').t`Start time out of bounds`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.DTEND_MALFORMED) {
return c('Error importing event').t`Malformed end time`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.DTEND_OUT_OF_BOUNDS) {
return c('Error importing event').t`End time out of bounds`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.X_WR_TIMEZONE_UNSUPPORTED) {
return c('Error importing event').t`Calendar time zone not supported`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.TZID_UNSUPPORTED) {
return c('Error importing event').t`Time zone not supported`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.RRULE_MALFORMED) {
return c('Error importing event').t`Malformed recurring event`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.RRULE_UNSUPPORTED) {
return c('Error importing event').t`Recurring rule not supported`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.SINGLE_EDIT_UNSUPPORTED) {
return c('Error importing event').t`Edited event not supported`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.NOTIFICATION_OUT_OF_BOUNDS) {
return c('Error importing event').t`Notification out of bounds`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.VALIDATION_ERROR) {
return c('Error importing event').t`Event validation failed`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.ENCRYPTION_ERROR) {
return c('Error importing event').t`Encryption failed`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.PARENT_EVENT_MISSING) {
return c('Error importing event').t`Original recurring event could not be found`;
}
if (errorType === IMPORT_EVENT_ERROR_TYPE.EXTERNAL_ERROR) {
return externalError?.message || '';
}
return '';
};
export class ImportEventError extends Error {
component: string;
componentId: string;
type: IMPORT_EVENT_ERROR_TYPE;
externalError?: Error;
constructor(errorType: IMPORT_EVENT_ERROR_TYPE, component: string, componentId: string, externalError?: Error) {
super(getErrorMessage(errorType, externalError));
this.type = errorType;
this.component = component;
this.componentId = componentId;
this.externalError = externalError;
Object.setPrototypeOf(this, ImportEventError.prototype);
}
}
| 8,380 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/icsSurgery/ics.ts | import { parse } from '@proton/shared/lib/calendar/vcal';
import { PROPERTIES } from '@proton/shared/lib/calendar/vcalDefinition';
import { VcalCalendarComponent } from '@proton/shared/lib/interfaces/calendar';
import { captureMessage } from '../../helpers/sentry';
/**
* If a vcalendar ics does not have the proper enclosing, add it
*/
export const reformatVcalEnclosing = (vcal = '') => {
let sanitized = vcal;
if (!sanitized.startsWith('BEGIN:VCALENDAR')) {
sanitized = `BEGIN:VCALENDAR\r\n${sanitized}`;
}
if (!sanitized.endsWith('END:VCALENDAR')) {
sanitized = `${sanitized}\r\nEND:VCALENDAR`;
}
return sanitized;
};
/**
* Naively extract lines in a vcalendar string
*/
const getNaiveLines = (vcal = '', separator = '\r\n') => {
const separatedLines = vcal.split(separator);
if (separator === '\n') {
return separatedLines;
}
// split possible remaining line breaks
return separatedLines.flatMap((line) => line.split('\n'));
};
/**
* Extract naively the vcal field in a vcal line
*/
const getNaiveField = (line: string) => {
const splitByParamsLine = line.split(';');
if (splitByParamsLine.length > 1) {
return splitByParamsLine[0];
}
const splitByValue = line.split(':');
if (splitByValue.length > 1) {
return splitByValue[0];
}
return '';
};
/**
* Unfold lines assuming they were folded properly
*/
export const unfoldLines = (vcal = '', separator = '\r\n') => {
const separatedLines = vcal.split(separator);
return separatedLines.reduce((acc, line) => {
if (line.startsWith(' ')) {
return `${acc}${line.slice(1)}`;
}
return acc ? `${acc}${separator}${line}` : line;
}, '');
};
/**
* Naively try to reformat badly formatted line breaks in a vcalendar string
*/
export const reformatLineBreaks = (vcal = '') => {
// try to guess the line separator of the ics (some providers use '\n' instead of the RFC-compliant '\r\n')
const separator = vcal.includes('\r\n') ? '\r\n' : '\n';
const lines = getNaiveLines(vcal, separator);
return lines.reduce((acc, line) => {
const field = getNaiveField(line);
if (!field) {
// if not a field line, it should be folded
return `${acc}${separator} ${line}`;
}
// make sure we did not get a false positive for the field line
const lowerCaseField = field.toLowerCase();
if (
PROPERTIES.has(lowerCaseField) ||
lowerCaseField.startsWith('x-') ||
['begin', 'end'].includes(lowerCaseField)
) {
// field lines should not be folded
return acc ? `${acc}${separator}${line}` : line;
}
// fall back to folding
return `${acc}${separator} ${line}`;
}, '');
};
/**
* Fix errors in the formatting of date-times:
* * Add missing VALUE=DATE for date values
* * Complete with zeroes incomplete date-times
* * Trim spaces
* * Transforms ISO (and partial ISO) formatting and removes milliseconds
* * Remove duplicate Zulu markers
*/
export const reformatDateTimes = (vcal = '') => {
const separator = vcal.includes('\r\n') ? '\r\n' : '\n';
const unfoldedVcal = unfoldLines(vcal, separator);
const unfoldedLines = unfoldedVcal.split(separator);
return unfoldedLines
.map((line) => {
const field = getNaiveField(line).trim().toLowerCase();
if (['dtstart', 'dtend', 'dtstamp', 'last-modified', 'created', 'recurrence-id'].includes(field)) {
// In case the line matches the ISO standard, we replace it by the ICS standard
// We do the replacement in two steps to account for providers that use a partial ISO
const partiallyStandardizedLine = line.replace(/(\d\d\d\d)-(\d\d)-(\d\d)(.*)/, `$1$2$3$4`);
const standardizedLine = partiallyStandardizedLine.replace(
/(\d{8})[Tt](\d\d):(\d\d):(\d\d).*?([Zz]*$)/,
`$1T$2$3$4$5`
);
const parts = standardizedLine
.split(':')
// trim possible spaces in the parts
.map((part) => part.trim());
const totalParts = parts.length;
if (totalParts === 2 && /^\d{8}$/.test(parts[1])) {
// it's a date value
return parts[0].includes(';VALUE=DATE')
? `${parts[0]}:${parts[1]}`
: `${parts[0]};VALUE=DATE:${parts[1]}`;
}
return parts
.map((part, i) => {
if (i < totalParts - 1) {
return part;
} else {
// naively the value will be here
const match = part.match(/[Zz]+$/);
const endingZs = match ? match[0].length : 0;
const isUTC = !!endingZs;
const dateTime = isUTC ? part.slice(0, -endingZs) : part;
const [date = '', time = ''] = dateTime.split(/[Tt]/);
if (date.length !== 8) {
// we cannot recover; we do no surgery and an error will be thrown
return part;
}
if (time.length < 6) {
const completeDateTime = `${date}T${time.padEnd(6, '0')}`;
return isUTC ? `${completeDateTime}Z` : completeDateTime;
}
if (time.length > 6) {
const reducedDateTime = `${date}T${time.slice(0, 6)}`;
return isUTC ? `${reducedDateTime}Z` : reducedDateTime;
}
return isUTC ? `${date}T${time}Z` : `${date}T${time}`;
}
})
.join(':');
} else {
return line;
}
})
.join(separator);
};
export const pruneOrganizer = (vcal = '') => {
const separator = vcal.includes('\r\n') ? '\r\n' : '\n';
const unfoldedVcal = unfoldLines(vcal, separator);
const unfoldedLines = unfoldedVcal.split(separator);
const withPrunedOrganizer = unfoldedLines.filter((line) => !line.startsWith('ORGANIZER')).join(separator);
return withPrunedOrganizer;
};
/**
* Same as the parse function, but trying to recover performing ICS surgery directly on the vcal string
*/
export const parseWithRecovery = (
vcal: string,
retry: {
retryLineBreaks?: boolean;
retryEnclosing?: boolean;
retryDateTimes?: boolean;
retryOrganizer?: boolean;
} = { retryLineBreaks: true, retryEnclosing: true, retryDateTimes: true, retryOrganizer: true },
reportToSentryData?: { calendarID: string; eventID: string }
): VcalCalendarComponent => {
const { retryLineBreaks, retryEnclosing, retryDateTimes, retryOrganizer } = retry;
try {
return parse(vcal);
} catch (e: any) {
const reportIfNeeded = (text: string, errorMessage: string) => {
if (reportToSentryData) {
captureMessage(text, {
level: 'info',
extra: {
...reportToSentryData,
errorMessage,
},
});
}
};
const message = e.message.toLowerCase();
// try to recover from line break errors
const couldBeLineBreakError =
message.includes('missing parameter value') || message.includes('invalid line (no token ";" or ":")');
if (couldBeLineBreakError && retryLineBreaks) {
reportIfNeeded('Unparseable event due to bad folding', message);
const reformattedVcal = reformatLineBreaks(vcal);
return parseWithRecovery(reformattedVcal, { ...retry, retryLineBreaks: false });
}
// try to recover from enclosing errors
if (message.includes('invalid ical body') && retryEnclosing) {
reportIfNeeded('Unparseable event due to enclosing errors', message);
const reformattedVcal = reformatVcalEnclosing(vcal);
return parseWithRecovery(reformattedVcal, { ...retry, retryEnclosing: false });
}
// try to recover from datetimes error
const couldBeDateTimeError =
message.includes('invalid date-time value') || message.includes('could not extract integer from');
if (couldBeDateTimeError && retryDateTimes) {
reportIfNeeded('Unparseable event due to badly formatted datetime', message);
const reformattedVcal = reformatDateTimes(vcal);
return parseWithRecovery(reformattedVcal, { ...retry, retryDateTimes: false });
}
// try to recover from organizer error
const couldBeOrganizerError = message.includes("missing parameter value in 'organizer");
if (couldBeOrganizerError && retryOrganizer) {
reportIfNeeded('Unparseable event due badly formatted organizer', message);
const reformattedVcal = pruneOrganizer(vcal);
return parseWithRecovery(reformattedVcal, { ...retry, retryOrganizer: false });
}
throw e;
}
};
/**
* Helper needed to parse events in our own DB due to other clients saving events with bad folding
*/
export const parseWithFoldingRecovery = (
vcal: string,
reportToSentryData?: { calendarID: string; eventID: string }
) => {
return parseWithRecovery(vcal, { retryLineBreaks: true }, reportToSentryData);
};
| 8,381 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/icsSurgery/valarm.ts | import { DAY_IN_SECONDS } from '@proton/shared/lib/constants';
import isTruthy from '@proton/utils/isTruthy';
import { normalize } from '../../helpers/string';
import {
DateTimeValue,
VcalDateOrDateTimeProperty,
VcalStringProperty,
VcalValarmComponent,
VcalValarmRelativeComponent,
} from '../../interfaces/calendar';
import { getIsAbsoluteTrigger, normalizeDurationToUnit, normalizeTrigger } from '../alarms/trigger';
import { ICAL_ALARM_ACTION, MAX_NOTIFICATIONS, NOTIFICATION_UNITS, NOTIFICATION_UNITS_MAX } from '../constants';
import { getIsDateTimeValue, getIsPropertyAllDay } from '../vcalHelper';
const { DISPLAY, EMAIL, AUDIO } = ICAL_ALARM_ACTION;
export const getSupportedAlarmAction = (action: VcalStringProperty) => {
if (normalize(action.value) === 'email') {
return { value: EMAIL };
}
return { value: DISPLAY };
};
/**
* Determine if a VALARM component is correct according to the RFC
*/
export const getIsValidAlarm = (alarm: VcalValarmComponent) => {
const { action, trigger, duration, repeat } = alarm;
const supportedActions: string[] = [DISPLAY, EMAIL, AUDIO];
if (!supportedActions.includes(action?.value)) {
return false;
}
if (!trigger) {
return false;
}
// absolute triggers should have the right format
if (getIsAbsoluteTrigger(trigger) && !getIsDateTimeValue(trigger.value as DateTimeValue)) {
return false;
}
// duration and repeat must be both present or absent
if (+!duration ^ +!repeat) {
return false;
}
return true;
};
/**
* Given a VALARM component, try to transform it into something that we support.
* Return undefined otherwise
*/
export const getSupportedAlarm = (
alarm: VcalValarmComponent,
dtstart: VcalDateOrDateTimeProperty
): VcalValarmRelativeComponent | undefined => {
if (!getIsValidAlarm(alarm)) {
return;
}
const supportedAction = getSupportedAlarmAction(alarm.action);
const { trigger } = alarm;
if (!getIsAbsoluteTrigger(trigger) && trigger.parameters?.related?.toLocaleLowerCase() === 'end') {
return;
}
const normalizedTrigger = normalizeTrigger(trigger, dtstart);
const triggerDurationInSeconds = normalizeDurationToUnit(normalizedTrigger, 1);
const inFuture = getIsPropertyAllDay(dtstart)
? !normalizedTrigger.isNegative && triggerDurationInSeconds >= DAY_IN_SECONDS
: !normalizedTrigger.isNegative && triggerDurationInSeconds !== 0;
const nonSupportedTrigger =
normalizedTrigger.seconds !== 0 ||
normalizedTrigger.minutes > NOTIFICATION_UNITS_MAX[NOTIFICATION_UNITS.MINUTE] ||
normalizedTrigger.hours > NOTIFICATION_UNITS_MAX[NOTIFICATION_UNITS.HOUR] ||
normalizedTrigger.days > NOTIFICATION_UNITS_MAX[NOTIFICATION_UNITS.DAY] ||
normalizedTrigger.weeks > NOTIFICATION_UNITS_MAX[NOTIFICATION_UNITS.WEEK];
if (inFuture || nonSupportedTrigger) {
return;
}
return {
component: 'valarm',
action: supportedAction,
trigger: { value: normalizedTrigger },
};
};
export const getSupportedAlarms = (valarms: VcalValarmComponent[], dtstart: VcalDateOrDateTimeProperty) => {
return valarms
.map((alarm) => getSupportedAlarm(alarm, dtstart))
.filter(isTruthy)
.slice(0, MAX_NOTIFICATIONS);
};
| 8,382 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/icsSurgery/vcal.ts | import { normalize } from '../../helpers/string';
import { VcalStringProperty } from '../../interfaces/calendar';
import { ICAL_CALSCALE } from '../constants';
export const getSupportedStringValue = (property?: VcalStringProperty) => {
const trimmedValue = property?.value?.trim();
if (!trimmedValue) {
// return undefined for empty strings
return;
}
return trimmedValue;
};
export const getSupportedCalscale = (calscale?: VcalStringProperty) => {
if (!calscale) {
return ICAL_CALSCALE.GREGORIAN;
}
return normalize(calscale.value) === normalize(ICAL_CALSCALE.GREGORIAN) ? ICAL_CALSCALE.GREGORIAN : undefined;
};
| 8,383 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/icsSurgery/vevent.ts | import { addDays, fromUnixTime } from 'date-fns';
import truncate from '@proton/utils/truncate';
import unique from '@proton/utils/unique';
import { RequireOnly } from '../../../lib/interfaces';
import { DAY } from '../../constants';
import { convertUTCDateTimeToZone, fromUTCDate, getSupportedTimezone } from '../../date/timezone';
import {
IcalJSDateOrDateTimeProperty,
VcalDateOrDateTimeProperty,
VcalDateTimeValue,
VcalDurationValue,
VcalFloatingDateTimeProperty,
VcalVeventComponent,
} from '../../interfaces/calendar';
import { dedupeAlarmsWithNormalizedTriggers } from '../alarms';
import { getAttendeeEmail, getSupportedAttendee, getSupportedOrganizer } from '../attendees';
import { ICAL_METHOD, MAX_CHARS_API, MAX_ICAL_SEQUENCE } from '../constants';
import { getIsDateOutOfBounds, getIsWellFormedDateOrDateTime, getSupportedUID } from '../helper';
import { getHasConsistentRrule, getHasOccurrences, getSupportedRrule } from '../recurrence/rrule';
import { durationToMilliseconds } from '../vcal';
import {
dateTimeToProperty,
dateToProperty,
getDateTimeProperty,
getDateTimePropertyInDifferentTimezone,
propertyToUTCDate,
} from '../vcalConverter';
import { getIsPropertyAllDay, getPropertyTzid } from '../vcalHelper';
import { EVENT_INVITATION_ERROR_TYPE, EventInvitationError } from './EventInvitationError';
import { IMPORT_EVENT_ERROR_TYPE, ImportEventError } from './ImportEventError';
import { getSupportedAlarms } from './valarm';
import { getSupportedStringValue } from './vcal';
export const getDtendPropertyFromDuration = (
dtstart: VcalDateOrDateTimeProperty,
duration: VcalDurationValue | number
) => {
const startDateUTC = propertyToUTCDate(dtstart);
const durationInMs = typeof duration === 'number' ? duration : durationToMilliseconds(duration);
const timestamp = +startDateUTC + durationInMs;
const end = fromUTCDate(fromUnixTime(timestamp / 1000));
if (getIsPropertyAllDay(dtstart)) {
// The all-day event lasts one day, we don't need DTEND in this case
if (durationInMs <= DAY) {
return;
}
const shouldAddDay = !!(durationInMs <= 0 || end.hours || end.minutes || end.seconds);
const finalEnd = shouldAddDay
? fromUTCDate(addDays(propertyToUTCDate({ value: { ...end, isUTC: true } }), 1))
: { ...end };
return dateToProperty(finalEnd);
}
if (durationInMs <= 0) {
// The part-day event has zero duration, we don't need DTEND in this case
return;
}
const tzid = getPropertyTzid(dtstart);
return getDateTimeProperty(convertUTCDateTimeToZone(end, tzid!), tzid!);
};
export const getSupportedDtstamp = (dtstamp: IcalJSDateOrDateTimeProperty | undefined, timestamp: number) => {
// as per RFC, the DTSTAMP value MUST be specified in the UTC time format. But that's not what we always receive from external providers
const value = dtstamp?.value;
const tzid = dtstamp?.parameters?.tzid;
if (!value) {
return dateTimeToProperty(fromUTCDate(new Date(timestamp)), true);
}
if (tzid) {
const supportedTzid = getSupportedTimezone(tzid);
if (!supportedTzid) {
// generate a new DTSTAMP
return dateTimeToProperty(fromUTCDate(new Date(timestamp)), true);
}
// we try to guess what the external provider meant
const guessedProperty = {
value: {
year: value.year,
month: value.month,
day: value.day,
hours: (value as VcalDateTimeValue)?.hours || 0,
minutes: (value as VcalDateTimeValue)?.minutes || 0,
seconds: (value as VcalDateTimeValue)?.seconds || 0,
isUTC: (value as VcalDateTimeValue)?.isUTC === true,
},
parameters: {
tzid: supportedTzid,
},
};
return dateTimeToProperty(fromUTCDate(propertyToUTCDate(guessedProperty)), true);
}
return dateTimeToProperty(fromUTCDate(propertyToUTCDate(dtstamp as VcalDateOrDateTimeProperty)), true);
};
export const withSupportedDtstamp = <T>(
properties: RequireOnly<VcalVeventComponent, 'uid' | 'component' | 'dtstart'> & T,
timestamp: number
): VcalVeventComponent & T => {
return {
...properties,
dtstamp: getSupportedDtstamp(properties.dtstamp, timestamp),
};
};
export const getSupportedDateOrDateTimeProperty = ({
property,
component,
componentId = '',
hasXWrTimezone,
calendarTzid,
isRecurring = false,
isInvite,
guessTzid,
}: {
property: VcalDateOrDateTimeProperty | VcalFloatingDateTimeProperty;
component: string;
componentId?: string;
hasXWrTimezone: boolean;
calendarTzid?: string;
isRecurring?: boolean;
method?: ICAL_METHOD;
isInvite?: boolean;
guessTzid?: string;
}) => {
if (getIsPropertyAllDay(property)) {
return dateToProperty(property.value);
}
const partDayProperty = property;
// account for non-RFC-compliant Google Calendar exports
// namely localize Zulu date-times for non-recurring events with x-wr-timezone if present and accepted by us
if (partDayProperty.value.isUTC && !isRecurring && hasXWrTimezone && calendarTzid) {
const localizedDateTime = convertUTCDateTimeToZone(partDayProperty.value, calendarTzid);
return getDateTimeProperty(localizedDateTime, calendarTzid);
}
const partDayPropertyTzid = getPropertyTzid(partDayProperty);
// A floating date-time property
if (!partDayPropertyTzid) {
if (!hasXWrTimezone) {
if (guessTzid) {
return getDateTimeProperty(partDayProperty.value, guessTzid);
}
if (isInvite) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED);
}
// we should never reach here as guessTzid should be always defined for import
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.UNEXPECTED_FLOATING_TIME, 'vevent', componentId);
}
if (hasXWrTimezone && !calendarTzid) {
if (isInvite) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.X_WR_TIMEZONE_UNSUPPORTED, 'vevent', componentId);
}
return getDateTimeProperty(partDayProperty.value, calendarTzid);
}
const supportedTzid = getSupportedTimezone(partDayPropertyTzid);
if (!supportedTzid) {
if (isInvite) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.TZID_UNSUPPORTED, component, componentId);
}
return getDateTimeProperty(partDayProperty.value, supportedTzid);
};
export const getLinkedDateTimeProperty = ({
property,
component,
linkedIsAllDay,
linkedTzid,
componentId = '',
isInvite,
}: {
property: VcalDateOrDateTimeProperty;
component: string;
componentId?: string;
linkedIsAllDay: boolean;
linkedTzid?: string;
isInvite?: boolean;
}): VcalDateOrDateTimeProperty => {
if (linkedIsAllDay) {
return dateToProperty(property.value);
}
if (getIsPropertyAllDay(property)) {
if (isInvite) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.ALLDAY_INCONSISTENCY, component, componentId);
}
const supportedTzid = getPropertyTzid(property);
if (!supportedTzid || !linkedTzid) {
if (isInvite) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED);
}
// should never be reached
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.UNEXPECTED_FLOATING_TIME, component, componentId);
}
if (linkedTzid !== supportedTzid) {
// the linked date-time property should have the same tzid as dtstart
return getDateTimePropertyInDifferentTimezone(property, linkedTzid, linkedIsAllDay);
}
return getDateTimeProperty(property.value, linkedTzid);
};
export const getSupportedSequenceValue = (sequence = 0) => {
/**
* According to the RFC (https://datatracker.ietf.org/doc/html/rfc5545#section-3.8.7.4), the sequence property can
* have INTEGER values, and the valid range for an integer is that of a 32-byte integer: -2147483648 to 2147483647,
* cf. https://www.rfc-editor.org/rfc/rfc5545#section-3.3.8
*
* Our BE does not support negative values, and we should not save anything bigger than 2147483687. We transform
* negative values into 0 and take the modulo of bigger ones.
*/
if (sequence < 0) {
return 0;
}
if (sequence >= MAX_ICAL_SEQUENCE) {
return sequence % MAX_ICAL_SEQUENCE;
}
return sequence;
};
export const withSupportedSequence = (vevent: VcalVeventComponent) => {
const supportedSequence = getSupportedSequenceValue(vevent.sequence?.value);
return {
...vevent,
sequence: { value: supportedSequence },
};
};
/**
* Perform ICS surgery on a VEVENT component
*/
export const getSupportedEvent = ({
method = ICAL_METHOD.PUBLISH,
vcalVeventComponent,
hasXWrTimezone,
calendarTzid,
guessTzid,
componentId = '',
isEventInvitation,
generatedHashUid = false,
}: {
method?: ICAL_METHOD;
vcalVeventComponent: VcalVeventComponent;
hasXWrTimezone: boolean;
calendarTzid?: string;
guessTzid?: string;
componentId?: string;
isEventInvitation?: boolean;
generatedHashUid?: boolean;
}): VcalVeventComponent => {
const isPublish = method === ICAL_METHOD.PUBLISH;
const isInvitation = isEventInvitation && !isPublish;
try {
// common surgery
const {
component,
components,
uid,
dtstamp,
dtstart,
dtend,
rrule,
exdate,
description,
summary,
location,
sequence,
'recurrence-id': recurrenceId,
organizer,
attendee,
duration,
'x-pm-session-key': sharedSessionKey,
'x-pm-shared-event-id': sharedEventID,
'x-pm-proton-reply': protonReply,
'x-yahoo-yid': xYahooID,
'x-yahoo-user-status': xYahooUserStatus,
} = vcalVeventComponent;
const [trimmedSummaryValue, trimmedDescriptionValue, trimmedLocationValue] = [
summary,
description,
location,
].map(getSupportedStringValue);
const isRecurring = !!rrule || !!recurrenceId;
const validated: VcalVeventComponent = {
component,
uid: { value: getSupportedUID(uid.value) },
dtstamp: { ...dtstamp },
dtstart: { ...dtstart },
sequence: { value: getSupportedSequenceValue(sequence?.value) },
};
let ignoreRrule = false;
if (trimmedSummaryValue) {
validated.summary = {
...summary,
value: truncate(trimmedSummaryValue, MAX_CHARS_API.TITLE),
};
}
if (trimmedDescriptionValue) {
validated.description = {
...description,
value: truncate(trimmedDescriptionValue, MAX_CHARS_API.EVENT_DESCRIPTION),
};
}
if (trimmedLocationValue) {
validated.location = {
...location,
value: truncate(trimmedLocationValue, MAX_CHARS_API.LOCATION),
};
}
validated.dtstart = getSupportedDateOrDateTimeProperty({
property: dtstart,
component: 'vevent',
componentId,
hasXWrTimezone,
calendarTzid,
isRecurring,
isInvite: isEventInvitation,
guessTzid,
});
const isAllDayStart = getIsPropertyAllDay(validated.dtstart);
const startTzid = getPropertyTzid(validated.dtstart);
if (!getIsWellFormedDateOrDateTime(validated.dtstart)) {
if (isEventInvitation) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.DTSTART_MALFORMED, 'vevent', componentId);
}
if (getIsDateOutOfBounds(validated.dtstart)) {
if (isEventInvitation) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.DTSTART_OUT_OF_BOUNDS, 'vevent', componentId);
}
if (dtend) {
const supportedDtend = getSupportedDateOrDateTimeProperty({
property: dtend,
component: 'vevent',
componentId,
hasXWrTimezone,
calendarTzid,
isRecurring,
isInvite: isEventInvitation,
guessTzid,
});
if (!getIsWellFormedDateOrDateTime(supportedDtend)) {
if (isEventInvitation) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.DTEND_MALFORMED, 'vevent', componentId);
}
const startDateUTC = propertyToUTCDate(validated.dtstart);
const endDateUTC = propertyToUTCDate(supportedDtend);
// allow a non-RFC-compliant all-day event with DTSTART = DTEND
const modifiedEndDateUTC =
!getIsPropertyAllDay(dtend) || +startDateUTC === +endDateUTC ? endDateUTC : addDays(endDateUTC, -1);
const eventDuration = +modifiedEndDateUTC - +startDateUTC;
if (eventDuration > 0) {
validated.dtend = supportedDtend;
}
} else if (duration) {
const dtendFromDuration = getDtendPropertyFromDuration(validated.dtstart, duration.value);
if (dtendFromDuration) {
validated.dtend = dtendFromDuration;
}
}
if (validated.dtend && getIsDateOutOfBounds(validated.dtend)) {
if (isEventInvitation) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.DTEND_OUT_OF_BOUNDS, 'vevent', componentId);
}
const isAllDayEnd = validated.dtend ? getIsPropertyAllDay(validated.dtend) : undefined;
if (isAllDayEnd !== undefined && +isAllDayStart ^ +isAllDayEnd) {
if (isEventInvitation) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.ALLDAY_INCONSISTENCY, 'vevent', componentId);
}
if (exdate) {
if (!rrule) {
if (isEventInvitation) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.RRULE_MALFORMED, 'vevent', componentId);
}
const supportedExdate = exdate.map((property) =>
getSupportedDateOrDateTimeProperty({
property,
component: 'vevent',
componentId,
hasXWrTimezone,
calendarTzid,
isRecurring,
isInvite: isEventInvitation,
guessTzid,
})
);
validated.exdate = supportedExdate.map((property) =>
getLinkedDateTimeProperty({
property,
component: 'vevent',
componentId,
linkedIsAllDay: isAllDayStart,
linkedTzid: startTzid,
isInvite: isEventInvitation,
})
);
}
// Do not keep recurrence ids when we generated a hash UID, as the RECURRENCE-ID is meaningless then
if (recurrenceId && !generatedHashUid) {
if (rrule) {
if (method === ICAL_METHOD.REPLY) {
// the external provider forgot to remove the RRULE
ignoreRrule = true;
} else {
if (isEventInvitation) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.SINGLE_EDIT_UNSUPPORTED, 'vevent', componentId);
}
}
// RECURRENCE-ID cannot be linked with DTSTART of the parent event at this point since we do not have access to it
validated['recurrence-id'] = getSupportedDateOrDateTimeProperty({
property: recurrenceId,
component: 'vevent',
componentId,
hasXWrTimezone,
calendarTzid,
isRecurring,
isInvite: isEventInvitation,
guessTzid,
});
}
if (rrule && !ignoreRrule) {
const supportedRrule = getSupportedRrule({ ...validated, rrule }, isInvitation, guessTzid);
if (!supportedRrule) {
if (isEventInvitation) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.RRULE_UNSUPPORTED, 'vevent', componentId);
}
validated.rrule = supportedRrule;
if (!getHasConsistentRrule(validated)) {
if (isEventInvitation) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.RRULE_MALFORMED, 'vevent', componentId);
}
if (!getHasOccurrences(validated)) {
if (isEventInvitation) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.NO_OCCURRENCES, 'vevent', componentId);
}
}
// import-specific surgery
if (!isInvitation) {
if (!isEventInvitation && isPublish) {
const alarms = components?.filter(({ component }) => component === 'valarm') || [];
const supportedAlarms = getSupportedAlarms(alarms, dtstart);
const dedupedAlarms = dedupeAlarmsWithNormalizedTriggers(supportedAlarms);
if (dedupedAlarms.length) {
validated.components = dedupedAlarms;
}
}
}
// invite-specific surgery
if (isInvitation) {
if (sharedSessionKey) {
validated['x-pm-session-key'] = { ...sharedSessionKey };
}
if (sharedEventID) {
validated['x-pm-shared-event-id'] = { ...sharedEventID };
}
if (protonReply) {
validated['x-pm-proton-reply'] = { ...protonReply };
}
if (xYahooID) {
// Needed to interpret non RFC-compliant Yahoo REPLY ics's
validated['x-yahoo-yid'] = { ...xYahooID };
}
if (xYahooUserStatus) {
// Needed to interpret non RFC-compliant Yahoo REPLY ics's
validated['x-yahoo-user-status'] = { ...xYahooUserStatus };
}
if (organizer) {
validated.organizer = getSupportedOrganizer(organizer);
} else {
// The ORGANIZER field is mandatory in an invitation
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID);
}
if (attendee) {
const attendeeEmails = attendee.map((att) => getAttendeeEmail(att));
if (unique(attendeeEmails).length !== attendeeEmails.length) {
// Do not accept invitations with repeated emails as they will cause problems.
// Usually external providers don't allow this to happen
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED);
}
validated.attendee = attendee.map((vcalAttendee) => getSupportedAttendee(vcalAttendee));
}
}
return validated;
} catch (e: any) {
if (e instanceof ImportEventError || e instanceof EventInvitationError) {
throw e;
}
if (isEventInvitation) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED, { externalError: e });
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.VALIDATION_ERROR, 'vevent', componentId || '');
}
};
| 8,384 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/import/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,385 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/import/ImportFileError.ts | import { c, msgid } from 'ttag';
import truncate from '@proton/utils/truncate';
import {
IMPORT_ERROR_TYPE,
MAX_FILENAME_CHARS_DISPLAY,
MAX_IMPORT_EVENTS_STRING,
MAX_IMPORT_FILE_SIZE_STRING,
} from '../constants';
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 calendar').t`An error occurred uploading your file. No file has been selected.`;
}
if (errorType === IMPORT_ERROR_TYPE.NO_ICS_FILE) {
return c('Error importing calendar')
.t`An error occurred uploading your file ${formattedFilename}. Only ICS file formats are allowed.`;
}
if (errorType === IMPORT_ERROR_TYPE.FILE_EMPTY) {
return c('Error importing calendar').t`Your file ${formattedFilename} is empty.`;
}
if (errorType === IMPORT_ERROR_TYPE.FILE_TOO_BIG) {
return c('Error importing calendar')
.t`An error occurred uploading your file ${formattedFilename}. Maximum file size is ${MAX_IMPORT_FILE_SIZE_STRING}.`;
}
if (errorType === IMPORT_ERROR_TYPE.INVALID_CALENDAR) {
return c('Error importing calendar').t`Your file ${formattedFilename} is not a calendar.`;
}
if (errorType === IMPORT_ERROR_TYPE.INVALID_METHOD) {
return c('Error importing calendar')
.t`Your file ${formattedFilename} has an invalid method and cannot be imported.`;
}
if (errorType === IMPORT_ERROR_TYPE.NO_EVENTS) {
return c('Error importing calendar').t`Your file ${formattedFilename} has no events to be imported.`;
}
if (errorType === IMPORT_ERROR_TYPE.TOO_MANY_EVENTS) {
return c('Error importing calendar').ngettext(
msgid`Your file ${formattedFilename} contains more than ${MAX_IMPORT_EVENTS_STRING} event.`,
`Your file ${formattedFilename} contains more than ${MAX_IMPORT_EVENTS_STRING} events.`,
MAX_IMPORT_EVENTS_STRING
);
}
if (errorType === IMPORT_ERROR_TYPE.FILE_CORRUPTED) {
return c('Error importing calendar')
.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,386 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/import/encryptAndSubmit.ts | import { getHasSharedEventContent, getHasSharedKeyPacket } from '@proton/shared/lib/calendar/apiModels';
import chunk from '@proton/utils/chunk';
import { syncMultipleEvents } from '../../api/calendars';
import { HOUR, SECOND } from '../../constants';
import { HTTP_ERROR_CODES } from '../../errors';
import { wait } from '../../helpers/promise';
import { Api, DecryptedKey } from '../../interfaces';
import {
DecryptedCalendarKey,
EncryptedEvent,
ImportedEvent,
SyncMultipleApiResponse,
SyncMultipleApiResponses,
VcalVeventComponent,
} from '../../interfaces/calendar';
import { CreateCalendarEventSyncData } from '../../interfaces/calendar/Api';
import { DEFAULT_ATTENDEE_PERMISSIONS } from '../constants';
import { getCreationKeys } from '../crypto/keys/helpers';
import { getIsSuccessSyncApiResponse } from '../helper';
import { IMPORT_EVENT_ERROR_TYPE, ImportEventError } from '../icsSurgery/ImportEventError';
import { createCalendarEvent } from '../serialize';
import { getComponentIdentifier, splitErrors } from './import';
const BATCH_SIZE = 10;
const encryptEvent = async ({
eventComponent,
addressKeys,
calendarKeys,
hasDefaultNotifications,
}: {
eventComponent: VcalVeventComponent;
addressKeys: DecryptedKey[];
calendarKeys: DecryptedCalendarKey[];
hasDefaultNotifications: boolean;
}) => {
const componentId = getComponentIdentifier(eventComponent);
try {
const data = await createCalendarEvent({
eventComponent,
isCreateEvent: true,
isSwitchCalendar: false,
hasDefaultNotifications,
...(await getCreationKeys({ newAddressKeys: addressKeys, newCalendarKeys: calendarKeys })),
});
if (!getHasSharedKeyPacket(data) || !getHasSharedEventContent(data)) {
throw new Error('Missing shared data');
}
return { data, component: eventComponent };
} catch (error: any) {
return new ImportEventError(IMPORT_EVENT_ERROR_TYPE.ENCRYPTION_ERROR, 'vevent', componentId);
}
};
const submitEvents = async (
events: EncryptedEvent[],
calendarID: string,
memberID: string,
api: Api,
overwrite?: boolean,
withJails?: boolean
): Promise<SyncMultipleApiResponses[]> => {
try {
const Events = events.map(
({ data }): CreateCalendarEventSyncData => ({
Overwrite: overwrite ? 1 : 0,
Event: { Permissions: DEFAULT_ATTENDEE_PERMISSIONS, ...data },
})
);
const { Responses } = await api<SyncMultipleApiResponse>({
...syncMultipleEvents(calendarID, { MemberID: memberID, IsImport: 1, Events }),
timeout: HOUR,
silence: true,
ignoreHandler: withJails ? [HTTP_ERROR_CODES.TOO_MANY_REQUESTS] : undefined,
});
return Responses;
} catch (error: any) {
if (withJails && error?.status === HTTP_ERROR_CODES.TOO_MANY_REQUESTS) {
throw error;
}
return events.map((event, index) => ({
Index: index,
Response: { Code: 0, Error: `${error}` },
}));
}
};
const processResponses = (responses: SyncMultipleApiResponses[], events: EncryptedEvent[]) => {
return responses.map((response): ImportedEvent | ImportEventError => {
const {
Index,
Response: { Error: errorMessage },
} = response;
if (getIsSuccessSyncApiResponse(response)) {
return {
...events[Index],
response,
};
}
const error = new Error(errorMessage);
const component = events[Index]?.component;
const componentId = component ? getComponentIdentifier(component) : '';
return new ImportEventError(IMPORT_EVENT_ERROR_TYPE.EXTERNAL_ERROR, 'vevent', componentId, error);
});
};
interface ProcessData {
events: { eventComponent: VcalVeventComponent; hasDefaultNotifications: boolean }[];
calendarID: string;
memberID: string;
addressKeys: DecryptedKey[];
calendarKeys: DecryptedCalendarKey[];
api: Api;
overwrite?: boolean;
signal?: AbortSignal;
onProgress?: (encrypted: EncryptedEvent[], imported: EncryptedEvent[], errors: ImportEventError[]) => void;
}
export const processInBatches = async ({
events,
calendarID,
memberID,
addressKeys,
calendarKeys,
api,
overwrite = true,
signal,
onProgress,
}: ProcessData) => {
const batches = chunk(events, BATCH_SIZE);
const promises = [];
const imported: ImportedEvent[][] = [];
const errored: ImportEventError[][] = [];
for (let i = 0; i < batches.length; i++) {
// The API requests limit for the submit route is 40 calls per 10 seconds
// We play it safe by enforcing a 300ms minimum wait between API calls. During this wait we encrypt the events
if (signal?.aborted) {
return {
importedEvents: [],
importErrors: [],
};
}
const batchedEvents = batches[i];
const [result] = await Promise.all([
Promise.all(
batchedEvents.map(({ eventComponent, hasDefaultNotifications }) =>
encryptEvent({
eventComponent,
addressKeys,
calendarKeys,
hasDefaultNotifications,
})
)
),
wait(300),
]);
const { errors, rest: encrypted } = splitErrors(result);
if (signal?.aborted) {
return {
importedEvents: [],
importErrors: [],
};
}
onProgress?.(encrypted, [], errors);
if (errors.length) {
errored.push(errors);
}
if (encrypted.length) {
const promise = submitEvents(encrypted, calendarID, memberID, api, overwrite).then((responses) => {
const processedResponses = processResponses(responses, encrypted);
const { errors, rest: importedSuccess } = splitErrors(processedResponses);
imported.push(importedSuccess);
errored.push(errors);
if (!signal?.aborted) {
onProgress?.([], importedSuccess, errors);
}
});
promises.push(promise);
}
}
await Promise.all(promises);
return {
importedEvents: imported.flat(),
importErrors: errored.flat(),
};
};
/**
* The following helper works as follows:
* * We encrypt and submit in parallel. As events are encrypted (in batches), they are moved to the import queue.
* * Batches of encrypted events are submitted at a constant rate
* (which under normal circumstances should be jail-safe).
* * If a jail is hit, all ongoing submissions are paused and we wait a retry-after period
* (defined as the max of all possible retry-after received from those submissions).
* * The submission process is resumed at a lower rate
* */
export const processWithJails = async ({
events,
calendarID,
memberID,
overwrite = true,
addressKeys,
calendarKeys,
api,
signal,
onProgress,
}: ProcessData) => {
const queueToEncrypt = chunk(events, BATCH_SIZE);
const queueToImport: EncryptedEvent[][] = [];
const imported: ImportedEvent[][] = [];
const errored: ImportEventError[][] = [];
// The API requests limit for the submit route is normally 40 calls per 10 seconds
// We start with a relax period that respects this limit.
let relaxTime = 300;
const encrypt = async () => {
while (queueToEncrypt.length && !signal?.aborted) {
const [eventsToEncrypt] = queueToEncrypt;
const result = await Promise.all(
eventsToEncrypt.map(({ eventComponent, hasDefaultNotifications }) =>
encryptEvent({
eventComponent,
hasDefaultNotifications,
addressKeys,
calendarKeys,
})
)
);
queueToEncrypt.splice(0, 1);
const { errors, rest: encrypted } = splitErrors(result);
queueToImport.push(encrypted);
if (!signal?.aborted) {
onProgress?.(encrypted, [], errors);
}
if (errors.length) {
errored.push(errors);
}
}
};
const submit = async (): Promise<void> => {
let paused = false;
const retryAfters: number[] = [];
const promises = [];
while ((queueToImport.length || queueToEncrypt.length) && !signal?.aborted && !paused) {
const [eventsToImport] = queueToImport;
if (!eventsToImport) {
// encryption might not be finished yet, give it some time
await wait(relaxTime);
return submit();
}
queueToImport.splice(0, 1);
promises.push(
submitEvents(eventsToImport, calendarID, memberID, api, overwrite, true)
.then((responses) => {
const processedResponses = processResponses(responses, eventsToImport);
const { errors, rest: importedSuccess } = splitErrors(processedResponses);
imported.push(importedSuccess);
errored.push(errors);
if (!signal?.aborted) {
onProgress?.([], importedSuccess, errors);
}
})
// it should be safe to change the value of paused in this loop because it can only be changed to true
// eslint-disable-next-line @typescript-eslint/no-loop-func
.catch((error: any) => {
// the only error we can get here is the TOO_MANY_REQUESTS one. All others are caught by submitEvents
paused = true;
queueToImport.push(eventsToImport);
retryAfters.push(parseInt(error?.response?.headers.get('retry-after') || '0', 10) * SECOND);
})
);
await wait(relaxTime);
}
// wait until all ongoing promises are finished
await Promise.all(promises);
if (paused) {
// A jail was hit. Wait for a safe retry after period, then resume the process at a lower rate
await wait(Math.max(...retryAfters));
relaxTime *= 1.5;
return submit();
}
};
await Promise.all([encrypt(), submit()]);
return {
importedEvents: imported.flat(),
importErrors: errored.flat(),
};
};
| 8,387 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/import/import.ts | import { c } from 'ttag';
import { serverTime } from '@proton/crypto';
import isTruthy from '@proton/utils/isTruthy';
import truncate from '@proton/utils/truncate';
import unique from '@proton/utils/unique';
import { getEventByUID } from '../../api/calendars';
import formatUTC, { Options as FormatOptions } from '../../date-fns-utc/format';
import { getSupportedTimezone, toUTCDate } from '../../date/timezone';
import { readFileAsString } from '../../helpers/file';
import { dateLocale } from '../../i18n';
import { Api, SimpleMap } from '../../interfaces';
import {
CalendarEvent,
ImportCalendarModel,
ImportedEvent,
VcalCalendarComponentWithMaybeErrors,
VcalErrorComponent,
VcalVcalendarWithMaybeErrors,
VcalVeventComponent,
VcalVtimezoneComponent,
} from '../../interfaces/calendar';
import { ICAL_METHOD, IMPORT_ERROR_TYPE, MAX_CALENDARS_PAID, MAX_IMPORT_EVENTS } from '../constants';
import getComponentFromCalendarEvent from '../getComponentFromCalendarEvent';
import { generateVeventHashUID, getOriginalUID } from '../helper';
import { IMPORT_EVENT_ERROR_TYPE, ImportEventError } from '../icsSurgery/ImportEventError';
import { getSupportedCalscale } from '../icsSurgery/vcal';
import { getLinkedDateTimeProperty, getSupportedEvent, withSupportedDtstamp } from '../icsSurgery/vevent';
import { getVeventWithoutErrors, parseWithRecoveryAndMaybeErrors, serialize } from '../vcal';
import {
getHasDtStart,
getHasRecurrenceId,
getIcalMethod,
getIsEventComponent,
getIsFreebusyComponent,
getIsJournalComponent,
getIsPropertyAllDay,
getIsTimezoneComponent,
getIsTodoComponent,
getIsVcalErrorComponent,
getPropertyTzid,
} from '../vcalHelper';
import { ImportFileError } from './ImportFileError';
export const parseIcs = async (ics: File) => {
const filename = ics.name;
try {
const icsAsString = await readFileAsString(ics);
if (!icsAsString) {
throw new ImportFileError(IMPORT_ERROR_TYPE.FILE_EMPTY, filename);
}
const parsedVcalendar = parseWithRecoveryAndMaybeErrors(icsAsString) as VcalVcalendarWithMaybeErrors;
if (parsedVcalendar.component?.toLowerCase() !== 'vcalendar') {
throw new ImportFileError(IMPORT_ERROR_TYPE.INVALID_CALENDAR, filename);
}
const { method, components, calscale, 'x-wr-timezone': xWrTimezone } = parsedVcalendar;
const supportedCalscale = getSupportedCalscale(calscale);
const supportedMethod = getIcalMethod(method);
if (!supportedMethod) {
throw new ImportFileError(IMPORT_ERROR_TYPE.INVALID_METHOD, filename);
}
if (!components?.length) {
throw new ImportFileError(IMPORT_ERROR_TYPE.NO_EVENTS, filename);
}
if (components.length > MAX_IMPORT_EVENTS) {
throw new ImportFileError(IMPORT_ERROR_TYPE.TOO_MANY_EVENTS, filename);
}
return { components, calscale: supportedCalscale, xWrTimezone: xWrTimezone?.value, method: supportedMethod };
} catch (e: any) {
if (e instanceof ImportFileError) {
throw e;
}
throw new ImportFileError(IMPORT_ERROR_TYPE.FILE_CORRUPTED, filename);
}
};
/**
* Get a string that can identify an imported component
*/
export const getComponentIdentifier = (
vcalComponent: VcalCalendarComponentWithMaybeErrors | VcalErrorComponent,
options: FormatOptions = { locale: dateLocale }
) => {
if (getIsVcalErrorComponent(vcalComponent)) {
return '';
}
if (getIsTimezoneComponent(vcalComponent)) {
return vcalComponent.tzid.value || '';
}
const uid = 'uid' in vcalComponent ? vcalComponent.uid?.value : undefined;
const originalUid = getOriginalUID(uid);
if (originalUid) {
return originalUid;
}
if (getIsEventComponent(vcalComponent)) {
const { summary, dtstart } = vcalComponent;
const shortTitle = truncate(summary?.value || '');
if (shortTitle) {
return shortTitle;
}
if (dtstart?.value) {
const format = getIsPropertyAllDay(dtstart) ? 'PP' : 'PPpp';
return formatUTC(toUTCDate(dtstart.value), format, options);
}
return c('Error importing event').t`No UID, title or start time`;
}
return '';
};
const extractGuessTzid = (components: (VcalCalendarComponentWithMaybeErrors | VcalErrorComponent)[]) => {
const vtimezones = components.filter((componentOrError): componentOrError is VcalVtimezoneComponent => {
if (getIsVcalErrorComponent(componentOrError)) {
return false;
}
return getIsTimezoneComponent(componentOrError);
});
if (vtimezones.length === 1) {
// we do not have guarantee that the VcalVtimezoneComponent's in vtimezones are propper, so better use optional chaining
const guessTzid = vtimezones[0]?.tzid?.value;
return guessTzid ? getSupportedTimezone(guessTzid) : undefined;
}
};
interface ExtractSupportedEventArgs {
method: ICAL_METHOD;
vcalComponent: VcalCalendarComponentWithMaybeErrors | VcalErrorComponent;
hasXWrTimezone: boolean;
formatOptions?: FormatOptions;
calendarTzid?: string;
guessTzid: string;
}
export const extractSupportedEvent = async ({
method,
vcalComponent: vcalComponentWithMaybeErrors,
hasXWrTimezone,
formatOptions,
calendarTzid,
guessTzid,
}: ExtractSupportedEventArgs) => {
const componentId = getComponentIdentifier(vcalComponentWithMaybeErrors, formatOptions);
const isInvitation = method !== ICAL_METHOD.PUBLISH;
if (getIsVcalErrorComponent(vcalComponentWithMaybeErrors)) {
throw new ImportEventError(
IMPORT_EVENT_ERROR_TYPE.EXTERNAL_ERROR,
'',
componentId,
vcalComponentWithMaybeErrors.error
);
}
if (getIsTodoComponent(vcalComponentWithMaybeErrors)) {
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.TODO_FORMAT, 'vtodo', componentId);
}
if (getIsJournalComponent(vcalComponentWithMaybeErrors)) {
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.JOURNAL_FORMAT, 'vjournal', componentId);
}
if (getIsFreebusyComponent(vcalComponentWithMaybeErrors)) {
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.FREEBUSY_FORMAT, 'vfreebusy', componentId);
}
if (getIsTimezoneComponent(vcalComponentWithMaybeErrors)) {
if (!getSupportedTimezone(vcalComponentWithMaybeErrors.tzid.value)) {
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.TIMEZONE_FORMAT, 'vtimezone', componentId);
}
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.TIMEZONE_IGNORE, 'vtimezone', componentId);
}
if (!getIsEventComponent(vcalComponentWithMaybeErrors)) {
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.WRONG_FORMAT, 'vunknown', componentId);
}
const vcalComponent = getVeventWithoutErrors(vcalComponentWithMaybeErrors);
if (!getHasDtStart(vcalComponent)) {
throw new ImportEventError(IMPORT_EVENT_ERROR_TYPE.DTSTART_MISSING, 'vevent', componentId);
}
const validVevent = withSupportedDtstamp(vcalComponent, +serverTime());
const generateHashUid = !validVevent.uid?.value || isInvitation;
if (generateHashUid) {
validVevent.uid = {
value: await generateVeventHashUID(serialize(vcalComponent), vcalComponent?.uid?.value),
};
}
return getSupportedEvent({
vcalVeventComponent: validVevent,
hasXWrTimezone,
calendarTzid,
guessTzid,
method,
isEventInvitation: false,
generatedHashUid: generateHashUid,
componentId,
});
};
export const getSupportedEvents = async ({
components,
method,
formatOptions,
calscale,
xWrTimezone,
primaryTimezone,
}: {
components: (VcalCalendarComponentWithMaybeErrors | VcalErrorComponent)[];
method: ICAL_METHOD;
formatOptions?: FormatOptions;
calscale?: string;
xWrTimezone?: string;
primaryTimezone: string;
}) => {
if (calscale?.toLowerCase() !== 'gregorian') {
return [new ImportEventError(IMPORT_EVENT_ERROR_TYPE.NON_GREGORIAN, 'vcalendar', '')];
}
const hasXWrTimezone = !!xWrTimezone;
const calendarTzid = xWrTimezone ? getSupportedTimezone(xWrTimezone) : undefined;
const guessTzid = extractGuessTzid(components) || primaryTimezone;
const supportedEvents = await Promise.all(
components.map(async (vcalComponent) => {
try {
const supportedEvent = await extractSupportedEvent({
method,
vcalComponent,
calendarTzid,
hasXWrTimezone,
formatOptions,
guessTzid,
});
return supportedEvent;
} catch (e: any) {
if (e instanceof ImportEventError && e.type === IMPORT_EVENT_ERROR_TYPE.TIMEZONE_IGNORE) {
return;
}
return e;
}
})
);
return supportedEvents.filter(isTruthy);
};
/**
* Split an array of events into those which have a recurrence id and those which don't
*/
export const splitByRecurrenceId = (events: VcalVeventComponent[]) => {
return events.reduce<{
withoutRecurrenceId: VcalVeventComponent[];
withRecurrenceId: (VcalVeventComponent & Required<Pick<VcalVeventComponent, 'recurrence-id'>>)[];
}>(
(acc, event) => {
if (!getHasRecurrenceId(event)) {
acc.withoutRecurrenceId.push(event);
} else {
acc.withRecurrenceId.push(event);
}
return acc;
},
{ withoutRecurrenceId: [], withRecurrenceId: [] }
);
};
export const splitErrors = <T>(events: (T | ImportEventError)[]) => {
return events.reduce<{ errors: ImportEventError[]; rest: T[] }>(
(acc, event) => {
if (event instanceof ImportEventError) {
acc.errors.push(event);
} else {
acc.rest.push(event);
}
return acc;
},
{ errors: [], rest: [] }
);
};
// Separate errors that we want to hide
export const splitHiddenErrors = (errors: ImportEventError[]) => {
return errors.reduce<{ hidden: ImportEventError[]; visible: ImportEventError[] }>(
(acc, error) => {
if (error.type === IMPORT_EVENT_ERROR_TYPE.NO_OCCURRENCES) {
// Importing an event without occurrences is the same as not importing it
acc.hidden.push(error);
} else {
acc.visible.push(error);
}
return acc;
},
{ hidden: [], visible: [] }
);
};
const getParentEventFromApi = async (uid: string, api: Api, calendarId: string) => {
try {
const { Events } = await api<{ Events: CalendarEvent[] }>({
...getEventByUID({
UID: uid,
Page: 0,
PageSize: MAX_CALENDARS_PAID,
}),
silence: true,
});
const [parentEvent] = Events.filter(({ CalendarID }) => CalendarID === calendarId);
if (!parentEvent) {
return;
}
const parentComponent = getComponentFromCalendarEvent(parentEvent);
if (getHasRecurrenceId(parentComponent)) {
// it wouldn't be a parent then
return;
}
return {
vcalComponent: parentComponent,
calendarEvent: parentEvent,
};
} catch {
return undefined;
}
};
interface GetSupportedEventsWithRecurrenceIdArgs {
eventsWithRecurrenceId: (VcalVeventComponent & Required<Pick<VcalVeventComponent, 'recurrence-id'>>)[];
parentEvents: ImportedEvent[];
calendarId: string;
api: Api;
}
export const getSupportedEventsWithRecurrenceId = async ({
eventsWithRecurrenceId,
parentEvents,
calendarId,
api,
}: GetSupportedEventsWithRecurrenceIdArgs) => {
// map uid -> parent event
const mapParentEvents = parentEvents.reduce<
SimpleMap<{
vcalComponent: VcalVeventComponent;
calendarEvent: CalendarEvent;
}>
>((acc, event) => {
acc[event.component.uid.value] = {
vcalComponent: event.component,
calendarEvent: event.response.Response.Event,
};
return acc;
}, {});
// complete the map with parent events in the DB
const uidsToFetch = unique(
eventsWithRecurrenceId.filter(({ uid }) => !mapParentEvents[uid.value]).map(({ uid }) => uid.value)
);
const result = await Promise.all(uidsToFetch.map((uid) => getParentEventFromApi(uid, api, calendarId)));
result.forEach((parentEvent, i) => {
mapParentEvents[uidsToFetch[i]] = parentEvent;
});
return eventsWithRecurrenceId.map((event) => {
const uid = event.uid.value;
const componentId = getComponentIdentifier(event);
const parentEvent = mapParentEvents[uid];
if (!parentEvent) {
return new ImportEventError(IMPORT_EVENT_ERROR_TYPE.PARENT_EVENT_MISSING, 'vevent', componentId);
}
const parentComponent = parentEvent.vcalComponent;
if (!parentComponent.rrule) {
return new ImportEventError(IMPORT_EVENT_ERROR_TYPE.SINGLE_EDIT_UNSUPPORTED, 'vevent', componentId);
}
const recurrenceId = event['recurrence-id'];
try {
const parentDtstart = parentComponent.dtstart;
const supportedRecurrenceId = getLinkedDateTimeProperty({
property: recurrenceId,
component: 'vevent',
linkedIsAllDay: getIsPropertyAllDay(parentDtstart),
linkedTzid: getPropertyTzid(parentDtstart),
componentId,
});
return { ...event, 'recurrence-id': supportedRecurrenceId };
} catch (e: any) {
if (e instanceof ImportEventError) {
return e;
}
return new ImportEventError(IMPORT_EVENT_ERROR_TYPE.VALIDATION_ERROR, 'vevent', componentId);
}
});
};
export const extractTotals = (model: ImportCalendarModel) => {
const { eventsParsed, totalEncrypted, totalImported, visibleErrors, hiddenErrors } = model;
const totalToImport = eventsParsed.length + hiddenErrors.length;
const totalToProcess = 2 * totalToImport; // count encryption and submission equivalently for the progress
const totalEncryptedFake = totalEncrypted + hiddenErrors.length;
const totalImportedFake = totalImported + hiddenErrors.length;
const totalVisibleErrors = visibleErrors.length;
const totalProcessed = totalEncryptedFake + totalImportedFake + totalVisibleErrors;
return {
totalToImport,
totalToProcess,
totalImported: totalImportedFake,
totalProcessed,
};
};
| 8,388 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/mailIntegration/AddAttendeeError.ts | import { c, msgid } from 'ttag';
import { MAX_ATTENDEES } from '@proton/shared/lib/calendar/constants';
export enum ADD_EVENT_ERROR_TYPE {
TOO_MANY_PARTICIPANTS,
}
const getErrorMessage = (errorType: ADD_EVENT_ERROR_TYPE, maxAttendees = MAX_ATTENDEES) => {
if (errorType === ADD_EVENT_ERROR_TYPE.TOO_MANY_PARTICIPANTS) {
return c('Error adding participants to a calendar event').ngettext(
msgid`At most ${maxAttendees} participant is allowed per invitation`,
`At most ${maxAttendees} participants are allowed per invitation`,
maxAttendees
);
}
return '';
};
export class AddAttendeeError extends Error {
type: ADD_EVENT_ERROR_TYPE;
externalError?: Error;
constructor(errorType: ADD_EVENT_ERROR_TYPE, externalError?: Error, maxAttendees?: number) {
super(getErrorMessage(errorType, maxAttendees));
this.type = errorType;
this.externalError = externalError;
Object.setPrototypeOf(this, AddAttendeeError.prototype);
}
}
| 8,389 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/mailIntegration/invite.ts | import { c } from 'ttag';
import { getIsAddressExternal } from '@proton/shared/lib/helpers/address';
import isTruthy from '@proton/utils/isTruthy';
import unary from '@proton/utils/unary';
import { MIME_TYPES } from '../../constants';
import { addDays, format as formatUTC } from '../../date-fns-utc';
import { Options } from '../../date-fns-utc/format';
import { formatTimezoneOffset, getTimezoneOffset, toUTCDate } from '../../date/timezone';
import {
buildMailTo,
canonicalizeEmail,
canonicalizeEmailByGuess,
canonicalizeInternalEmail,
} from '../../helpers/email';
import { omit, pick } from '../../helpers/object';
import { getCurrentUnixTimestamp } from '../../helpers/time';
import { dateLocale } from '../../i18n';
import { Address } from '../../interfaces';
import {
Attendee,
CalendarEvent,
CalendarSettings,
Participant,
VcalAttendeeProperty,
VcalComponentKeys,
VcalOrganizerProperty,
VcalStringProperty,
VcalValarmComponent,
VcalVcalendar,
VcalVeventComponent,
VcalVtimezoneComponent,
} from '../../interfaces/calendar';
import { ContactEmail } from '../../interfaces/contacts';
import { GetVTimezonesMap } from '../../interfaces/hooks/GetVTimezonesMap';
import { RequireSome } from '../../interfaces/utils';
import { getSupportedPlusAlias } from '../../mail/addresses';
import { MESSAGE_FLAGS } from '../../mail/constants';
import { RE_PREFIX, formatSubject } from '../../mail/messages';
import { getAttendeeEmail, toIcsPartstat } from '../attendees';
import { ICAL_ALARM_ACTION, ICAL_ATTENDEE_STATUS, ICAL_METHOD, NOTIFICATION_TYPE_API } from '../constants';
import { getSelfAddressData } from '../deserialize';
import { getDisplayTitle } from '../helper';
import { getSupportedStringValue } from '../icsSurgery/vcal';
import { getIsRruleEqual } from '../recurrence/rruleEqual';
import { fromTriggerString, serialize } from '../vcal';
import { getAllDayInfo, getHasModifiedDateTimes, propertyToUTCDate } from '../vcalConverter';
import { getAttendeePartstat, getAttendeeRole, getIsAlarmComponent, getPropertyTzid } from '../vcalHelper';
import {
getIsAllDay,
getIsEventCancelled,
getSequence,
withDtstamp,
withSummary,
withoutRedundantDtEnd,
withoutRedundantRrule,
} from '../veventHelper';
export const getParticipantHasAddressID = (
participant: Participant
): participant is RequireSome<Participant, 'addressID'> => {
return !!participant.addressID;
};
export const getParticipant = ({
participant,
contactEmails,
selfAddress,
selfAttendee,
emailTo,
index,
calendarAttendees,
xYahooUserStatus,
}: {
participant: VcalAttendeeProperty | VcalOrganizerProperty;
contactEmails: ContactEmail[];
selfAddress?: Address;
selfAttendee?: VcalAttendeeProperty;
emailTo?: string;
index?: number;
calendarAttendees?: Attendee[];
xYahooUserStatus?: string;
}): Participant => {
const emailAddress = getAttendeeEmail(participant);
const canonicalInternalEmail = canonicalizeInternalEmail(emailAddress);
const canonicalEmail = canonicalizeEmailByGuess(emailAddress);
const isSelf = selfAddress && canonicalizeInternalEmail(selfAddress.Email) === canonicalInternalEmail;
const isYou = emailTo ? canonicalizeInternalEmail(emailTo) === canonicalInternalEmail : isSelf;
const contact = contactEmails.find(({ Email }) => canonicalizeEmail(Email) === canonicalEmail);
const participantName = participant?.parameters?.cn || emailAddress;
const displayName = (isSelf && selfAddress?.DisplayName) || contact?.Name || participantName;
const result: Participant = {
vcalComponent: participant,
name: participantName,
emailAddress,
partstat: getAttendeePartstat(participant, xYahooUserStatus),
displayName: isYou ? c('Participant name').t`You` : displayName,
displayEmail: emailAddress,
};
const { role, email, 'x-pm-token': token } = (participant as VcalAttendeeProperty).parameters || {};
const calendarAttendee = token ? calendarAttendees?.find(({ Token }) => Token === token) : undefined;
if (role) {
result.role = getAttendeeRole(participant);
}
if (email) {
result.displayEmail = email;
}
if (token) {
result.token = token;
}
if (calendarAttendee) {
result.updateTime = calendarAttendee.UpdateTime;
result.attendeeID = calendarAttendee.ID;
}
if (selfAddress && selfAttendee && isSelf) {
result.addressID = selfAddress.ID;
// Use Proton form of the email address (important for sending email)
result.emailAddress = getSupportedPlusAlias({
selfAttendeeEmail: getAttendeeEmail(selfAttendee),
selfAddressEmail: selfAddress.Email,
});
// Use Proton name when sending out the email
result.name = selfAddress.DisplayName || participantName;
}
if (index !== undefined) {
result.attendeeIndex = index;
}
return result;
};
/**
* Build ad-hoc participant data for a party crasher
* (to fake a party crasher actually being in the ICS)
*/
export const buildPartyCrasherParticipantData = (
originalTo: string,
ownAddresses: Address[],
contactEmails: ContactEmail[],
attendees: VcalAttendeeProperty[]
): { participant?: Participant; selfAttendee: VcalAttendeeProperty; selfAddress: Address } | undefined => {
let isCatchAllPartyCrasher = false;
const selfInternalAddresses = ownAddresses.filter((address) => !getIsAddressExternal(address));
const canonicalizedOriginalTo = canonicalizeInternalEmail(originalTo);
let selfAddress = selfInternalAddresses.find(
({ Email }) => canonicalizeInternalEmail(Email) === canonicalizedOriginalTo
);
if (!selfAddress) {
const catchAllAddress = selfInternalAddresses.find(({ CatchAll }) => CatchAll);
if (catchAllAddress) {
// if any address is catch-all, that will be detected as party crasher
isCatchAllPartyCrasher = true;
selfAddress = catchAllAddress;
} else {
return;
}
}
const fakeOriginalTo = isCatchAllPartyCrasher ? selfAddress.Email : originalTo;
const selfAttendee: VcalAttendeeProperty = {
value: buildMailTo(fakeOriginalTo),
parameters: {
cn: originalTo,
partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION,
},
};
return {
participant: getParticipant({
participant: selfAttendee,
selfAddress,
selfAttendee,
contactEmails,
index: attendees.length,
emailTo: fakeOriginalTo,
}),
selfAttendee,
selfAddress,
};
};
interface CreateInviteVeventParams {
method: ICAL_METHOD;
attendeesTo?: VcalAttendeeProperty[];
vevent: VcalVeventComponent;
keepDtstamp?: boolean;
}
export const createInviteVevent = ({ method, attendeesTo, vevent, keepDtstamp }: CreateInviteVeventParams) => {
if ([ICAL_METHOD.REPLY, ICAL_METHOD.CANCEL].includes(method) && attendeesTo?.length) {
const propertiesToKeepForCancel: (keyof VcalVeventComponent)[] = ['x-pm-shared-event-id'];
const propertiesToKeepForReply: (keyof VcalVeventComponent)[] = ['x-pm-proton-reply'];
const keepDtStampProperty: (keyof VcalVeventComponent)[] = ['dtstamp'];
// only put RFC-mandatory fields to make reply as short as possible
// rrule, summary and location are also included for a better UI in the external provider widget
const propertiesToKeep: (keyof VcalVeventComponent)[] = [
'uid',
'dtstart',
'dtend',
'sequence',
'recurrence-id',
'organizer',
'rrule',
'location',
'summary',
...(keepDtstamp ? keepDtStampProperty : []),
...(method === ICAL_METHOD.CANCEL ? propertiesToKeepForCancel : []),
...(method === ICAL_METHOD.REPLY ? propertiesToKeepForReply : []),
];
const attendee = attendeesTo.map(({ value, parameters }) => {
const { partstat } = parameters || {};
if (method === ICAL_METHOD.REPLY) {
if (!partstat) {
throw new Error('Cannot reply without participant status');
}
return {
value,
parameters: { partstat },
};
}
return { value };
});
const veventWithoutRedundantDtEnd = withoutRedundantDtEnd(
withDtstamp({
...pick(vevent, propertiesToKeep),
component: 'vevent',
attendee,
})
);
return method === ICAL_METHOD.REPLY
? withoutRedundantRrule(veventWithoutRedundantDtEnd)
: veventWithoutRedundantDtEnd;
}
if (method === ICAL_METHOD.REQUEST) {
// strip alarms
const propertiesToOmit: (keyof VcalVeventComponent)[] = ['components', 'x-pm-proton-reply'];
// use current time as dtstamp unless indicated otherwise
if (!keepDtstamp) {
propertiesToOmit.push('dtstamp');
}
// SUMMARY is mandatory in a REQUEST ics
const veventWithSummary = withSummary(vevent);
return withoutRedundantDtEnd(withDtstamp(omit(veventWithSummary, propertiesToOmit) as VcalVeventComponent));
}
};
interface CreateInviteIcsParams {
method: ICAL_METHOD;
prodId: string;
vevent: VcalVeventComponent;
attendeesTo?: VcalAttendeeProperty[];
vtimezones?: VcalVtimezoneComponent[];
sharedEventID?: string;
keepDtstamp?: boolean;
}
export const createInviteIcs = ({
method,
prodId,
attendeesTo,
vevent,
vtimezones,
keepDtstamp,
}: CreateInviteIcsParams): string => {
// use current time as dtstamp
const inviteVevent = createInviteVevent({ method, vevent, attendeesTo, keepDtstamp });
if (!inviteVevent) {
throw new Error('Invite vevent failed to be created');
}
const inviteVcal: RequireSome<VcalVcalendar, 'components'> = {
component: 'vcalendar',
components: [inviteVevent],
prodid: { value: prodId },
version: { value: '2.0' },
method: { value: method },
calscale: { value: 'GREGORIAN' },
};
if (vtimezones?.length) {
inviteVcal.components = [...vtimezones, ...inviteVcal.components];
}
return serialize(inviteVcal);
};
export const findAttendee = (email: string, attendees: VcalAttendeeProperty[] = []) => {
// treat all emails as internal. This is not fully correct (TO BE IMPROVED),
// but it's better to have some false positives rather than many false negatives
const canonicalEmail = canonicalizeInternalEmail(email);
const index = attendees.findIndex(
(attendee) => canonicalizeInternalEmail(getAttendeeEmail(attendee)) === canonicalEmail
);
const attendee = index !== -1 ? attendees[index] : undefined;
return { index, attendee };
};
export const getVeventWithDefaultCalendarAlarms = (vevent: VcalVeventComponent, calendarSettings: CalendarSettings) => {
const { components } = vevent;
const isAllDay = getIsAllDay(vevent);
const notifications = isAllDay
? calendarSettings.DefaultFullDayNotifications
: calendarSettings.DefaultPartDayNotifications;
const valarmComponents = notifications.map<VcalValarmComponent>(({ Trigger, Type }) => ({
component: 'valarm',
action: { value: Type === NOTIFICATION_TYPE_API.EMAIL ? ICAL_ALARM_ACTION.EMAIL : ICAL_ALARM_ACTION.DISPLAY },
trigger: { value: fromTriggerString(Trigger) },
}));
return {
...vevent,
components: components ? components.concat(valarmComponents) : valarmComponents,
};
};
export const getInvitedVeventWithAlarms = ({
vevent,
partstat,
calendarSettings,
oldHasDefaultNotifications,
oldPartstat,
}: {
vevent: VcalVeventComponent;
partstat: ICAL_ATTENDEE_STATUS;
calendarSettings?: CalendarSettings;
oldHasDefaultNotifications?: boolean;
oldPartstat?: ICAL_ATTENDEE_STATUS;
}) => {
const { components } = vevent;
const alarmComponents = components?.filter((component) => getIsAlarmComponent(component));
const otherComponents = components?.filter((component) => !getIsAlarmComponent(component));
if ([ICAL_ATTENDEE_STATUS.DECLINED, ICAL_ATTENDEE_STATUS.NEEDS_ACTION].includes(partstat)) {
// remove all alarms in this case
if (otherComponents?.length) {
return {
vevent: { ...vevent, components: otherComponents },
hasDefaultNotifications: false,
};
}
return {
vevent: { ...vevent, components: [] },
hasDefaultNotifications: false,
};
}
const leaveAlarmsUntouched = oldPartstat
? [ICAL_ATTENDEE_STATUS.ACCEPTED, ICAL_ATTENDEE_STATUS.TENTATIVE].includes(oldPartstat) ||
!!alarmComponents?.length
: false;
if (leaveAlarmsUntouched) {
return {
vevent,
hasDefaultNotifications: oldHasDefaultNotifications || false,
};
}
// otherwise add default calendar alarms
if (!calendarSettings) {
throw new Error('Cannot retrieve calendar default notifications');
}
return {
vevent: getVeventWithDefaultCalendarAlarms(vevent, calendarSettings),
hasDefaultNotifications: true,
};
};
export const getSelfAttendeeToken = (vevent?: VcalVeventComponent, addresses: Address[] = []) => {
if (!vevent?.attendee) {
return;
}
const { selfAddress, selfAttendeeIndex } = getSelfAddressData({
organizer: vevent.organizer,
attendees: vevent.attendee,
addresses,
});
if (!selfAddress || selfAttendeeIndex === undefined) {
return;
}
return vevent.attendee[selfAttendeeIndex].parameters?.['x-pm-token'];
};
export const generateVtimezonesComponents = async (
{ dtstart, dtend, 'recurrence-id': recurrenceId, exdate = [] }: VcalVeventComponent,
getVTimezones: GetVTimezonesMap
): Promise<VcalVtimezoneComponent[]> => {
const timezones = [dtstart, dtend, recurrenceId, ...exdate]
.filter(isTruthy)
.map(unary(getPropertyTzid))
.filter(isTruthy);
const vtimezonesObject = await getVTimezones(timezones);
return Object.values(vtimezonesObject)
.filter(isTruthy)
.map(({ vtimezone }) => vtimezone);
};
const getFormattedDateInfo = (vevent: VcalVeventComponent, options: Options = { locale: dateLocale }) => {
const { dtstart, dtend } = vevent;
const { isAllDay, isSingleAllDay } = getAllDayInfo(dtstart, dtend);
if (isAllDay) {
return {
formattedStart: formatUTC(toUTCDate(dtstart.value), 'cccc PPP', options),
formattedEnd: dtend ? formatUTC(addDays(toUTCDate(dtend.value), -1), 'cccc PPP', options) : undefined,
isAllDay,
isSingleAllDay,
};
}
const formattedStartDateTime = formatUTC(toUTCDate(dtstart.value), 'cccc PPPp', options);
const formattedEndDateTime = dtend ? formatUTC(toUTCDate(dtend.value), 'cccc PPPp', options) : undefined;
const { offset: startOffset } = getTimezoneOffset(propertyToUTCDate(dtstart), getPropertyTzid(dtstart) || 'UTC');
const { offset: endOffset } = dtend
? getTimezoneOffset(propertyToUTCDate(dtend), getPropertyTzid(dtend) || 'UTC')
: { offset: 0 };
const formattedStartOffset = `GMT${formatTimezoneOffset(startOffset)}`;
const formattedEndOffset = `GMT${formatTimezoneOffset(endOffset)}`;
return {
formattedStart: `${formattedStartDateTime} (${formattedStartOffset})`,
formattedEnd: formattedEndDateTime ? `${formattedEndDateTime} (${formattedEndOffset})` : undefined,
isAllDay,
isSingleAllDay,
};
};
export const generateEmailSubject = ({
method,
vevent,
isCreateEvent,
dateFormatOptions,
}: {
method: ICAL_METHOD;
vevent: VcalVeventComponent;
isCreateEvent?: boolean;
dateFormatOptions?: Options;
}) => {
const { formattedStart, isSingleAllDay } = getFormattedDateInfo(vevent, dateFormatOptions);
const { REQUEST, CANCEL, REPLY } = ICAL_METHOD;
if (method === REQUEST) {
if (isSingleAllDay) {
return isCreateEvent
? c('Email subject').t`Invitation for an event on ${formattedStart}`
: c('Email subject').t`Update for an event on ${formattedStart}`;
}
return isCreateEvent
? c('Email subject').t`Invitation for an event starting on ${formattedStart}`
: c('Email subject').t`Update for an event starting on ${formattedStart}`;
}
if (method === CANCEL) {
return isSingleAllDay
? c('Email subject').t`Cancellation of an event on ${formattedStart}`
: c('Email subject').t`Cancellation of an event starting on ${formattedStart}`;
}
if (method === REPLY) {
return isSingleAllDay
? formatSubject(c('Email subject').t`Invitation for an event on ${formattedStart}`, RE_PREFIX)
: formatSubject(c('Email subject').t`Invitation for an event starting on ${formattedStart}`, RE_PREFIX);
}
throw new Error('Unexpected method');
};
const getWhenText = (vevent: VcalVeventComponent, dateFormatOptions?: Options) => {
const { formattedStart, formattedEnd, isAllDay, isSingleAllDay } = getFormattedDateInfo(vevent, dateFormatOptions);
if (isAllDay) {
return isSingleAllDay || !formattedEnd
? c('Email body for invitation (date part)').t`When: ${formattedStart} (all day)`
: c('Email body for invitation (date part)').t`When: ${formattedStart} - ${formattedEnd}`;
}
return formattedEnd
? c('Email body for invitation (date part)').t`When: ${formattedStart} - ${formattedEnd}`
: c('Email body for invitation (date part)').t`When: ${formattedStart}`;
};
const getEmailBodyTexts = (vevent: VcalVeventComponent, dateFormatOptions?: Options) => {
const { summary, location, description } = vevent;
const eventTitle = getDisplayTitle(summary?.value);
const eventLocation = location?.value;
const eventDescription = description?.value;
const whenText = getWhenText(vevent, dateFormatOptions);
const locationText = eventLocation ? c('Email body for invitation (location part)').t`Where: ${eventLocation}` : '';
const descriptionText = eventDescription
? c('Email body for description (description part)').t`Description: ${eventDescription}`
: '';
const locationAndDescriptionText =
locationText && descriptionText
? `${locationText}
${descriptionText}`
: `${locationText || descriptionText}`;
const eventDetailsText = locationAndDescriptionText
? `${whenText}
${locationAndDescriptionText}`
: `${whenText}`;
return { eventTitle, eventDetailsText };
};
export const generateEmailBody = ({
method,
vevent,
isCreateEvent,
partstat,
emailAddress,
options,
}: {
method: ICAL_METHOD;
vevent: VcalVeventComponent;
isCreateEvent?: boolean;
emailAddress?: string;
partstat?: ICAL_ATTENDEE_STATUS;
options?: Options;
}) => {
const { eventTitle, eventDetailsText } = getEmailBodyTexts(vevent, options);
if (method === ICAL_METHOD.REQUEST) {
if (isCreateEvent) {
return c('Email body for invitation').t`You are invited to ${eventTitle}
${eventDetailsText}`;
}
return c('Email body for invitation').t`${eventTitle} has been updated.
${eventDetailsText}`;
}
if (method === ICAL_METHOD.CANCEL) {
return c('Email body for invitation').t`${eventTitle} has been canceled.`;
}
if (method === ICAL_METHOD.REPLY) {
if (!partstat || !emailAddress) {
throw new Error('Missing parameters for reply body');
}
if (partstat === ICAL_ATTENDEE_STATUS.ACCEPTED) {
return c('Email body for response to invitation')
.t`${emailAddress} has accepted your invitation to ${eventTitle}`;
}
if (partstat === ICAL_ATTENDEE_STATUS.TENTATIVE) {
return c('Email body for response to invitation')
.t`${emailAddress} has tentatively accepted your invitation to ${eventTitle}`;
}
if (partstat === ICAL_ATTENDEE_STATUS.DECLINED) {
return c('Email body for response to invitation')
.t`${emailAddress} has declined your invitation to ${eventTitle}`;
}
throw new Error('Unanswered partstat');
}
throw new Error('Unexpected method');
};
export const getIcsMessageWithPreferences = (globalSign: number) => ({
MIMEType: MIME_TYPES.PLAINTEXT,
Flags: globalSign ? MESSAGE_FLAGS.FLAG_SIGN : undefined,
});
export const getHasUpdatedInviteData = ({
newVevent,
oldVevent,
hasModifiedDateTimes,
}: {
newVevent: VcalVeventComponent;
oldVevent?: VcalVeventComponent;
hasModifiedDateTimes?: boolean;
}) => {
if (!oldVevent) {
return false;
}
const hasUpdatedDateTimes =
hasModifiedDateTimes !== undefined ? hasModifiedDateTimes : getHasModifiedDateTimes(newVevent, oldVevent);
const keys: VcalComponentKeys[] = ['summary', 'description', 'location'];
const hasUpdatedTitleDescriptionOrLocation = keys.some(
(key) =>
getSupportedStringValue(newVevent[key] as VcalStringProperty) !==
getSupportedStringValue(oldVevent[key] as VcalStringProperty)
);
const hasUpdatedRrule = !getIsRruleEqual(newVevent.rrule, oldVevent.rrule);
return hasUpdatedDateTimes || hasUpdatedTitleDescriptionOrLocation || hasUpdatedRrule;
};
export const getUpdatedInviteVevent = (
newVevent: VcalVeventComponent,
oldVevent: VcalVeventComponent,
method?: ICAL_METHOD
) => {
if (method === ICAL_METHOD.REQUEST && getSequence(newVevent) > getSequence(oldVevent)) {
if (!newVevent.attendee?.length) {
return { ...newVevent };
}
const withResetPartstatAttendees = newVevent.attendee.map((attendee) => ({
...attendee,
parameters: {
...attendee.parameters,
partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION,
},
}));
return { ...newVevent, attendee: withResetPartstatAttendees };
}
return { ...newVevent };
};
export const getResetPartstatActions = (
singleEdits: CalendarEvent[],
token: string,
partstat: ICAL_ATTENDEE_STATUS
) => {
const updateTime = getCurrentUnixTimestamp();
const updatePartstatActions = singleEdits
.map((event) => {
if (getIsEventCancelled(event)) {
// no need to reset the partsat as it should have been done already
return;
}
const selfAttendee = event.Attendees.find(({ Token }) => Token === token);
if (!selfAttendee) {
return;
}
const oldPartstat = toIcsPartstat(selfAttendee.Status);
if ([ICAL_ATTENDEE_STATUS.NEEDS_ACTION, partstat].includes(oldPartstat)) {
// no need to reset the partstat as it's already reset or it coincides with the new partstat
return;
}
return {
attendeeID: selfAttendee.ID,
eventID: event.ID,
calendarID: event.CalendarID,
updateTime,
partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION,
};
})
.filter(isTruthy);
const updatePersonalPartActions = updatePartstatActions
.map(({ eventID, calendarID }) => ({ eventID, calendarID }))
.filter(isTruthy);
return { updatePartstatActions, updatePersonalPartActions };
};
export const getHasNonCancelledSingleEdits = (singleEdits: CalendarEvent[]) => {
return singleEdits.some((event) => !getIsEventCancelled(event));
};
export const getMustResetPartstat = (singleEdits: CalendarEvent[], token?: string, partstat?: ICAL_ATTENDEE_STATUS) => {
if (!token || !partstat) {
return false;
}
return singleEdits.some((event) => {
if (getIsEventCancelled(event)) {
return false;
}
const selfAttendee = event.Attendees.find(({ Token }) => Token === token);
if (!selfAttendee) {
return false;
}
const oldPartstat = toIcsPartstat(selfAttendee.Status);
if ([ICAL_ATTENDEE_STATUS.NEEDS_ACTION, partstat].includes(oldPartstat)) {
return false;
}
return true;
});
};
| 8,390 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/recurrence/getFrequencyString.ts | import { c, msgid } from 'ttag';
import mod from '@proton/utils/mod';
import unique from '@proton/utils/unique';
import { format } from '../../date-fns-utc';
import { WeekStartsOn } from '../../date-fns-utc/interface';
import { toUTCDate } from '../../date/timezone';
import {
VcalDateOrDateTimeProperty,
VcalRruleProperty,
VcalRrulePropertyValue,
} from '../../interfaces/calendar/VcalModel';
import { END_TYPE, FREQUENCY, MONTHLY_TYPE } from '../constants';
import { getPropertyTzid } from '../vcalHelper';
import { getIsRruleCustom, getIsRruleSimple, getPositiveSetpos } from './rrule';
import { getEndType, getMonthType, getUntilDate, getWeeklyDays } from './rruleProperties';
interface RruleEnd {
type: END_TYPE;
count?: number;
until?: Date;
}
interface GetTimezonedFrequencyStringOptions {
currentTzid: string;
locale: Locale;
weekStartsOn: WeekStartsOn;
}
// NOTE: due to the different grammar of different languages, to allow for a proper translation,
// we need to expand all possible cases so there will be quite a bit of duplicated code
export const getOnDayString = (date: Date, monthlyType: MONTHLY_TYPE) => {
const dayOfMonth = date.getUTCDate();
const day = date.getUTCDay();
if (monthlyType === MONTHLY_TYPE.ON_NTH_DAY) {
const setPos = getPositiveSetpos(date);
if (setPos === 1) {
if (day === 0) {
return c('Monthly recurring event, repeats on').t`on the first Sunday`;
}
if (day === 1) {
return c('Monthly recurring event, repeats on').t`on the first Monday`;
}
if (day === 2) {
return c('Monthly recurring event, repeats on').t`on the first Tuesday`;
}
if (day === 3) {
return c('Monthly recurring event, repeats on').t`on the first Wednesday`;
}
if (day === 4) {
return c('Monthly recurring event, repeats on').t`on the first Thursday`;
}
if (day === 5) {
return c('Monthly recurring event, repeats on').t`on the first Friday`;
}
if (day === 6) {
return c('Monthly recurring event, repeats on').t`on the first Saturday`;
}
}
if (setPos === 2) {
if (day === 0) {
return c('Monthly recurring event, repeats on').t`on the second Sunday`;
}
if (day === 1) {
return c('Monthly recurring event, repeats on').t`on the second Monday`;
}
if (day === 2) {
return c('Monthly recurring event, repeats on').t`on the second Tuesday`;
}
if (day === 3) {
return c('Monthly recurring event, repeats on').t`on the second Wednesday`;
}
if (day === 4) {
return c('Monthly recurring event, repeats on').t`on the second Thursday`;
}
if (day === 5) {
return c('Monthly recurring event, repeats on').t`on the second Friday`;
}
if (day === 6) {
return c('Monthly recurring event, repeats on').t`on the second Saturday`;
}
}
if (setPos === 3) {
if (day === 0) {
return c('Monthly recurring event, repeats on').t`on the third Sunday`;
}
if (day === 1) {
return c('Monthly recurring event, repeats on').t`on the third Monday`;
}
if (day === 2) {
return c('Monthly recurring event, repeats on').t`on the third Tuesday`;
}
if (day === 3) {
return c('Monthly recurring event, repeats on').t`on the third Wednesday`;
}
if (day === 4) {
return c('Monthly recurring event, repeats on').t`on the third Thursday`;
}
if (day === 5) {
return c('Monthly recurring event, repeats on').t`on the third Friday`;
}
if (day === 6) {
return c('Monthly recurring event, repeats on').t`on the third Saturday`;
}
}
if (setPos === 4) {
if (day === 0) {
return c('Monthly recurring event, repeats on').t`on the fourth Sunday`;
}
if (day === 1) {
return c('Monthly recurring event, repeats on').t`on the fourth Monday`;
}
if (day === 2) {
return c('Monthly recurring event, repeats on').t`on the fourth Tuesday`;
}
if (day === 3) {
return c('Monthly recurring event, repeats on').t`on the fourth Wednesday`;
}
if (day === 4) {
return c('Monthly recurring event, repeats on').t`on the fourth Thursday`;
}
if (day === 5) {
return c('Monthly recurring event, repeats on').t`on the fourth Friday`;
}
if (day === 6) {
return c('Monthly recurring event, repeats on').t`on the fourth Saturday`;
}
}
}
if (monthlyType === MONTHLY_TYPE.ON_MINUS_NTH_DAY) {
if (day === 0) {
return c('Monthly recurring event, repeats on').t`on the last Sunday`;
}
if (day === 1) {
return c('Monthly recurring event, repeats on').t`on the last Monday`;
}
if (day === 2) {
return c('Monthly recurring event, repeats on').t`on the last Tuesday`;
}
if (day === 3) {
return c('Monthly recurring event, repeats on').t`on the last Wednesday`;
}
if (day === 4) {
return c('Monthly recurring event, repeats on').t`on the last Thursday`;
}
if (day === 5) {
return c('Monthly recurring event, repeats on').t`on the last Friday`;
}
if (day === 6) {
return c('Monthly recurring event, repeats on').t`on the last Saturday`;
}
}
return c('Monthly recurring event, repeats on').t`on day ${dayOfMonth}`;
};
const getTimesString = (count: number) => {
return c('Daily recurring event, frequency').ngettext(msgid`${count} time`, `${count} times`, count);
};
const getUntilString = (dateString: string) => {
return c('Daily recurring event, frequency').t`until ${dateString}`;
};
const getCustomDailyString = (
rruleValue: VcalRrulePropertyValue,
{ type: endType, count = 1, until }: RruleEnd,
locale: Locale
) => {
const { interval = 1 } = rruleValue;
if (endType === END_TYPE.NEVER) {
if (interval === 1) {
return c('Daily recurring event, frequency').t`Daily`;
}
// translator: When interval = 1 we do not use this string; we use 'daily' instead. Treat the case of interval = 1 as dummy
return c('Daily recurring event, frequency').ngettext(
msgid`Every ${interval} day`,
`Every ${interval} days`,
interval
);
}
if (endType === END_TYPE.AFTER_N_TIMES) {
const timesString = getTimesString(count);
if (interval === 1) {
return c('Daily recurring event, frequency').t`Daily, ${timesString}`;
}
// translator: When interval = 1 we do not use this string; we use 'daily' instead. Treat the case of interval = 1 as dummy
return c('Daily recurring event, frequency').ngettext(
msgid`Every ${interval} day, ${timesString}`,
`Every ${interval} days, ${timesString}`,
interval
);
}
if (endType === END_TYPE.UNTIL && until) {
const dateString = format(until, 'PP', { locale });
const untilString = getUntilString(dateString);
if (interval === 1) {
return c('Daily recurring event, frequency').t`Daily, ${untilString}`;
}
// translator: When interval = 1 we do not use this string; we use 'daily' instead. Treat the case of interval = 1 as dummy
return c('Daily recurring event, frequency').ngettext(
msgid`Every ${interval} day, ${untilString}`,
`Every ${interval} days, ${untilString}`,
interval
);
}
};
const getWeekdayString = (weekday: number) => {
if (weekday === 0) {
return c('Weekly recurring event, repeats on (multiple days), frequency').t`Sunday`;
}
if (weekday === 1) {
return c('Weekly recurring event, repeats on (multiple days), frequency').t`Monday`;
}
if (weekday === 2) {
return c('Weekly recurring event, repeats on (multiple days), frequency').t`Tuesday`;
}
if (weekday === 3) {
return c('Weekly recurring event, repeats on (multiple days), frequency').t`Wednesday`;
}
if (weekday === 4) {
return c('Weekly recurring event, repeats on (multiple days), frequency').t`Thursday`;
}
if (weekday === 5) {
return c('Weekly recurring event, repeats on (multiple days), frequency').t`Friday`;
}
if (weekday === 6) {
return c('Weekly recurring event, repeats on (multiple days), frequency').t`Saturday`;
}
throw new Error('Unknown weekday');
};
const getCustomWeeklyString = (
{ interval = 1, byday }: VcalRrulePropertyValue,
{ type: endType, count = 1, until }: RruleEnd,
weekStartsOn: WeekStartsOn,
startDate: Date,
locale: Locale
) => {
const days = getWeeklyDays(byday);
const safeDays = unique([...days, startDate.getUTCDay()]);
// sort weekly days depending on the day the week starts
const sortedWeekDays = safeDays.slice().sort((a: number, b: number) => {
// shift days. Get a positive modulus
const A = mod(a - weekStartsOn, +7);
const B = mod(b - weekStartsOn, 7);
return A - B;
});
const multipleDaysString = sortedWeekDays.map(getWeekdayString).join(', ');
if (endType === END_TYPE.NEVER) {
if (days.length === 7) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on all days`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on all days`,
`Every ${interval} weeks on all days`,
interval
);
}
if (days.length === 1) {
const startDate = days[0];
if (startDate === 0) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Sunday`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Sunday`,
`Every ${interval} weeks on Sunday`,
interval
);
}
if (startDate === 1) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Monday`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Monday`,
`Every ${interval} weeks on Monday`,
interval
);
}
if (startDate === 2) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Tuesday`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Tuesday`,
`Every ${interval} weeks on Tuesday`,
interval
);
}
if (startDate === 3) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Wednesday`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Wednesday`,
`Every ${interval} weeks on Wednesday`,
interval
);
}
if (startDate === 4) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Thursday`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Thursday`,
`Every ${interval} weeks on Thursday`,
interval
);
}
if (startDate === 5) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Friday`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Friday`,
`Every ${interval} weeks on Friday`,
interval
);
}
if (startDate === 6) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Saturday`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Saturday`,
`Every ${interval} weeks on Saturday`,
interval
);
}
}
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on ${multipleDaysString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on ${multipleDaysString}`,
`Every ${interval} weeks on ${multipleDaysString}`,
interval
);
}
if (endType === END_TYPE.AFTER_N_TIMES) {
const timesString = getTimesString(count);
if (days.length === 7) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on all days, ${timesString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on all days, ${timesString}`,
`Every ${interval} weeks on all days, ${timesString}`,
interval
);
}
if (days.length === 1) {
const startDate = days[0];
if (startDate === 0) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Sunday, ${timesString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Sunday, ${timesString}`,
`Every ${interval} weeks on Sunday, ${timesString}`,
interval
);
}
if (startDate === 1) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Monday, ${timesString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Monday, ${timesString}`,
`Every ${interval} weeks on Monday, ${timesString}`,
interval
);
}
if (startDate === 2) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Tuesday, ${timesString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Tuesday, ${timesString}`,
`Every ${interval} weeks on Tuesday, ${timesString}`,
interval
);
}
if (startDate === 3) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Wednesday, ${timesString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Wednesday, ${timesString}`,
`Every ${interval} weeks on Wednesday, ${timesString}`,
interval
);
}
if (startDate === 4) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Thursday, ${timesString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Thursday, ${timesString}`,
`Every ${interval} weeks on Thursday, ${timesString}`,
interval
);
}
if (startDate === 5) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Friday, ${timesString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Friday, ${timesString}`,
`Every ${interval} weeks on Friday, ${timesString}`,
interval
);
}
if (startDate === 6) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Saturday, ${timesString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Saturday, ${timesString}`,
`Every ${interval} weeks on Saturday, ${timesString}`,
interval
);
}
}
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on ${multipleDaysString}, ${timesString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on ${multipleDaysString}, ${timesString}`,
`Every ${interval} weeks on ${multipleDaysString}, ${timesString}`,
interval
);
}
if (endType === END_TYPE.UNTIL && until) {
const dateString = format(until, 'PP', { locale });
const untilString = getUntilString(dateString);
if (days.length === 7) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on all days, ${untilString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on all days, ${untilString}`,
`Every ${interval} weeks on all days, ${untilString}`,
interval
);
}
if (days.length === 1) {
const startDate = days[0];
if (startDate === 0) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Sunday, ${untilString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Sunday, ${untilString}`,
`Every ${interval} weeks on Sunday, ${untilString}`,
interval
);
}
if (startDate === 1) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Monday, ${untilString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Monday, ${untilString}`,
`Every ${interval} weeks on Monday, ${untilString}`,
interval
);
}
if (startDate === 2) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Tuesday, ${untilString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Tuesday, ${untilString}`,
`Every ${interval} weeks on Tuesday, ${untilString}`,
interval
);
}
if (startDate === 3) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Wednesday, ${untilString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Wednesday, ${untilString}`,
`Every ${interval} weeks on Wednesday, ${untilString}`,
interval
);
}
if (startDate === 4) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Thursday, ${untilString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Thursday, ${untilString}`,
`Every ${interval} weeks on Thursday, ${untilString}`,
interval
);
}
if (startDate === 5) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Friday, ${untilString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Friday, ${untilString}`,
`Every ${interval} weeks on Friday, ${untilString}`,
interval
);
}
if (startDate === 6) {
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Saturday, ${untilString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on Saturday, ${untilString}`,
`Every ${interval} weeks on Saturday, ${untilString}`,
interval
);
}
}
if (interval === 1) {
return c('Weekly recurring event, frequency').t`Weekly on ${multipleDaysString}, ${untilString}`;
}
// translator: When interval = 1 we do not use this string; we use 'weekly' instead. Treat the case of interval = 1 as dummy
return c('Weekly recurring event, frequency').ngettext(
msgid`Every ${interval} week on ${multipleDaysString}, ${untilString}`,
`Every ${interval} weeks on ${multipleDaysString}, ${untilString}`,
interval
);
}
};
const getCustomMonthlyString = (
rruleValue: VcalRrulePropertyValue,
{ type: endType, count = 1, until }: RruleEnd,
monthlyType: MONTHLY_TYPE,
date: Date,
locale: Locale
) => {
const { interval = 1 } = rruleValue;
const onDayString = date ? getOnDayString(date, monthlyType) : '';
if (endType === END_TYPE.NEVER) {
if (interval === 1) {
return c('Monthly recurring event, frequency').t`Monthly ${onDayString}`;
}
// translator: When interval = 1 we do not use this string; we use 'monthly' instead. Treat the case of interval = 1 as dummy
return c('Monthly recurring event, frequency').ngettext(
msgid`Every ${interval} month ${onDayString}`,
`Every ${interval} months ${onDayString}`,
interval
);
}
if (endType === END_TYPE.AFTER_N_TIMES) {
const timesString = getTimesString(count);
if (interval === 1) {
return c('Monthly recurring event, frequency').t`Monthly ${onDayString}, ${timesString}`;
}
// translator: When interval = 1 we do not use this string; we use 'monthly' instead. Treat the case of interval = 1 as dummy
return c('Monthly recurring event, frequency').ngettext(
msgid`Every ${interval} month ${onDayString}, ${timesString}`,
`Every ${interval} months ${onDayString}, ${timesString}`,
interval
);
}
if (endType === END_TYPE.UNTIL && until) {
const dateString = format(until, 'PP', { locale });
const untilString = getUntilString(dateString);
if (interval === 1) {
return c('Monthly recurring event, frequency').t`Monthly ${onDayString}, ${untilString}`;
}
// translator: When interval = 1 we do not use this string; we use 'monthly' instead. Treat the case of interval = 1 as dummy
return c('Monthly recurring event, frequency').ngettext(
msgid`Every ${interval} month ${onDayString}, ${untilString}`,
`Every ${interval} months ${onDayString}, ${untilString}`,
interval
);
}
};
const getCustomYearlyString = (
{ interval = 1 }: VcalRrulePropertyValue,
{ type: endType, count = 1, until }: RruleEnd,
locale: Locale
) => {
if (endType === END_TYPE.NEVER) {
if (interval === 1) {
return c('Yearly recurring event, frequency').t`Yearly`;
}
// translator: When interval = 1 we do not use this string; we use 'yearly' instead. Treat the case of interval = 1 as dummy
return c('Yearly recurring event, frequency').ngettext(
msgid`Every ${interval} year`,
`Every ${interval} years`,
interval
);
}
if (endType === END_TYPE.AFTER_N_TIMES) {
const timesString = getTimesString(count);
if (interval === 1) {
return c('Yearly recurring event, frequency').t`Yearly, ${timesString}`;
}
// translator: When interval = 1 we do not use this string; we use 'yearly' instead. Treat the case of interval = 1 as dummy
return c('Yearly recurring event, frequency').ngettext(
msgid`Every ${interval} year, ${timesString}`,
`Every ${interval} years, ${timesString}`,
interval
);
}
if (endType === END_TYPE.UNTIL && until) {
const dateString = format(until, 'PP', { locale });
const untilString = getUntilString(dateString);
if (interval === 1) {
return c('Yearly recurring event, frequency').t`Yearly, ${untilString}`;
}
// translator: When interval = 1 we do not use this string; we use 'yearly' instead. Treat the case of interval = 1 as dummy
return c('Yearly recurring event, frequency').ngettext(
msgid`Every ${interval} year, ${untilString}`,
`Every ${interval} years, ${untilString}`,
interval
);
}
};
export const getFrequencyString = (
rruleValue: VcalRrulePropertyValue,
dtstart: VcalDateOrDateTimeProperty,
{ weekStartsOn, locale }: Pick<GetTimezonedFrequencyStringOptions, 'weekStartsOn' | 'locale'>
) => {
const { freq, count, until } = rruleValue;
const isSimple = getIsRruleSimple(rruleValue);
const isCustom = getIsRruleCustom(rruleValue);
const startFakeUtcDate = toUTCDate(dtstart.value);
const startDay = startFakeUtcDate.getUTCDay();
const end = {
type: getEndType(count, until),
count,
until: getUntilDate(until, getPropertyTzid(dtstart)),
};
if (!isSimple) {
if (!isCustom) {
if (freq === FREQUENCY.DAILY) {
return c('Info').t`Custom daily`;
}
if (freq === FREQUENCY.WEEKLY) {
return c('Info').t`Custom weekly`;
}
if (freq === FREQUENCY.MONTHLY) {
return c('Info').t`Custom monthly`;
}
if (freq === FREQUENCY.YEARLY) {
return c('Info').t`Custom yearly`;
}
return c('Info').t`Custom`;
}
if (freq === FREQUENCY.DAILY) {
return getCustomDailyString(rruleValue, end, locale);
}
if (freq === FREQUENCY.WEEKLY) {
return getCustomWeeklyString(rruleValue, end, weekStartsOn, startFakeUtcDate, locale);
}
if (freq === FREQUENCY.MONTHLY) {
const { byday, bysetpos } = rruleValue;
const monthType = getMonthType(byday, bysetpos);
return getCustomMonthlyString(rruleValue, end, monthType, startFakeUtcDate, locale);
}
if (freq === FREQUENCY.YEARLY) {
return getCustomYearlyString(rruleValue, end, locale);
}
}
if (freq === FREQUENCY.DAILY) {
return c('Info').t`Daily`;
}
if (freq === FREQUENCY.WEEKLY) {
if (startDay === 0) {
return c('Weekly recurring event, frequency').t`Weekly on Sunday`;
}
if (startDay === 1) {
return c('Weekly recurring event, frequency').t`Weekly on Monday`;
}
if (startDay === 2) {
return c('Weekly recurring event, frequency').t`Weekly on Tuesday`;
}
if (startDay === 3) {
return c('Weekly recurring event, frequency').t`Weekly on Wednesday`;
}
if (startDay === 4) {
return c('Weekly recurring event, frequency').t`Weekly on Thursday`;
}
if (startDay === 5) {
return c('Weekly recurring event, frequency').t`Weekly on Friday`;
}
if (startDay === 6) {
return c('Weekly recurring event, frequency').t`Weekly on Saturday`;
}
}
if (freq === FREQUENCY.MONTHLY) {
const { byday, bysetpos } = rruleValue;
const monthType = getMonthType(byday, bysetpos);
const onDayString = getOnDayString(startFakeUtcDate, monthType);
return c('Info').t`Monthly ${onDayString}`;
}
if (freq === FREQUENCY.YEARLY) {
return c('Info').t`Yearly`;
}
return '';
};
export const getTimezonedFrequencyString = (
rrule: VcalRruleProperty | undefined,
dtstart: VcalDateOrDateTimeProperty,
options: GetTimezonedFrequencyStringOptions
) => {
if (!rrule) {
return '';
}
const { value: rruleValue } = rrule;
const startTzid = getPropertyTzid(dtstart);
const { currentTzid } = options;
if (!startTzid || startTzid === currentTzid) {
return getFrequencyString(rruleValue, dtstart, options);
}
const isTimezoneStringNeeded = (() => {
const { freq, count, until, byday } = rruleValue;
const isCustom = getIsRruleCustom(rruleValue);
const endType = getEndType(count, until);
if (!freq) {
return false;
}
if ([FREQUENCY.DAILY, FREQUENCY.YEARLY].includes(freq as FREQUENCY)) {
return isCustom && endType === END_TYPE.UNTIL;
}
if (freq === FREQUENCY.WEEKLY) {
const days = getWeeklyDays(byday);
const hasCustomUntil = isCustom && endType === END_TYPE.UNTIL;
const hasDays = days.length !== 7;
return hasCustomUntil || hasDays;
}
if (freq === FREQUENCY.MONTHLY) {
return true;
}
return false;
})();
const timezoneString = isTimezoneStringNeeded ? ` (${startTzid})` : '';
return getFrequencyString(rruleValue, dtstart, options) + timezoneString;
};
| 8,391 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/recurrence/getRecurrenceIdValueFromTimestamp.ts | import { convertTimestampToTimezone } from '../../date/timezone';
import { toExdate } from '../exdate';
const getRecurrenceIdValueFromTimestamp = (unixTimestamp: number, isAllDay: boolean, startTimezone: string) => {
const localStartDateTime = convertTimestampToTimezone(unixTimestamp, startTimezone);
return toExdate(localStartDateTime, isAllDay, startTimezone);
};
export default getRecurrenceIdValueFromTimestamp;
| 8,392 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/recurrence/recurring.ts | /* eslint-disable no-param-reassign */
import { addDays, addMilliseconds, differenceInCalendarDays, max } from '../../date-fns-utc';
import { convertUTCDateTimeToZone, convertZonedDateTimeToUTC, fromUTCDate, toUTCDate } from '../../date/timezone';
import {
VcalDateOrDateTimeProperty,
VcalDateOrDateTimeValue,
VcalRruleProperty,
VcalVeventComponent,
} from '../../interfaces/calendar/VcalModel';
import { createExdateMap } from '../exdate';
import { getInternalDateTimeValue, internalValueToIcalValue } from '../vcal';
import { getDtendProperty, propertyToUTCDate } from '../vcalConverter';
import { getPropertyTzid } from '../vcalHelper';
import { getIsAllDay } from '../veventHelper';
interface CacheInner {
dtstart: VcalDateOrDateTimeValue;
utcStart: Date;
isAllDay: boolean;
eventDuration: number;
modifiedRrule: VcalRruleProperty;
exdateMap: { [key: number]: boolean };
}
export interface RecurringResult {
localStart: Date;
localEnd: Date;
utcStart: Date;
utcEnd: Date;
occurrenceNumber: number;
}
export interface OccurrenceIterationCache {
start: CacheInner;
iteration: {
iterator: any;
result: RecurringResult[];
interval: number[];
};
}
type RequiredVcalVeventComponent = Pick<VcalVeventComponent, 'dtstart' | 'rrule' | 'exdate'>;
const YEAR_IN_MS = Date.UTC(1971, 0, 1);
const isInInterval = (a1: number, a2: number, b1: number, b2: number) => a1 <= b2 && a2 >= b1;
// Special case for when attempting to use occurrences when an rrule does not exist.
// Fake an rrule so that the iteration goes through at least once
const DEFAULT_RRULE = {
value: {
freq: 'DAILY',
count: 1,
},
};
interface FillOccurrencesBetween {
interval: number[];
iterator: any;
eventDuration: number;
originalDtstart: VcalDateOrDateTimeProperty;
originalDtend: VcalDateOrDateTimeProperty;
isAllDay: boolean;
exdateMap: { [key: number]: boolean };
}
const fillOccurrencesBetween = ({
interval: [start, end],
iterator,
eventDuration,
originalDtstart,
originalDtend,
isAllDay,
exdateMap,
}: FillOccurrencesBetween) => {
const result = [];
let next;
const startTzid = getPropertyTzid(originalDtstart);
const endTzid = getPropertyTzid(originalDtend);
// eslint-disable-next-line no-cond-assign
while ((next = iterator.next())) {
const localStart = toUTCDate(getInternalDateTimeValue(next));
if (exdateMap[+localStart]) {
continue;
}
let localEnd;
let utcStart;
let utcEnd;
if (isAllDay) {
localEnd = addDays(localStart, eventDuration);
utcStart = localStart;
utcEnd = localEnd;
} else if (!startTzid || !endTzid) {
const endInStartTimezone = addMilliseconds(localStart, eventDuration);
localEnd = endInStartTimezone;
utcStart = localStart;
utcEnd = endInStartTimezone;
} else {
const endInStartTimezone = addMilliseconds(localStart, eventDuration);
const endInUTC = convertZonedDateTimeToUTC(fromUTCDate(endInStartTimezone), startTzid);
localEnd = toUTCDate(convertUTCDateTimeToZone(endInUTC, endTzid));
utcStart = toUTCDate(convertZonedDateTimeToUTC(fromUTCDate(localStart), startTzid));
utcEnd = toUTCDate(endInUTC);
}
if (+utcStart > end) {
break;
}
if (isInInterval(+utcStart, +utcEnd, start, end)) {
result.push({
localStart,
localEnd,
utcStart,
utcEnd,
occurrenceNumber: iterator.occurrence_number as number,
});
}
}
return result;
};
/**
* Convert the until property of an rrule to be in the timezone of the start date
*/
const getModifiedUntilRrule = (internalRrule: VcalRruleProperty, startTzid: string | undefined): VcalRruleProperty => {
if (!internalRrule || !internalRrule.value || !internalRrule.value.until || !startTzid) {
return internalRrule;
}
const utcUntil = toUTCDate(internalRrule.value.until);
const localUntil = convertUTCDateTimeToZone(fromUTCDate(utcUntil), startTzid);
return {
...internalRrule,
value: {
...internalRrule.value,
until: {
...localUntil,
isUTC: true,
},
},
};
};
const getOccurrenceSetup = (component: RequiredVcalVeventComponent) => {
const { dtstart: internalDtstart, rrule: internalRrule, exdate: internalExdate } = component;
const internalDtEnd = getDtendProperty(component);
const isAllDay = getIsAllDay(component);
const dtstartType = isAllDay ? 'date' : 'date-time';
// Pretend the (local) date is in UTC time to keep the absolute times.
const dtstart = internalValueToIcalValue(dtstartType, {
...internalDtstart.value,
isUTC: true,
}) as VcalDateOrDateTimeValue;
// Since the local date is pretended in UTC time, the until has to be converted into a fake local UTC time too
const safeRrule = getModifiedUntilRrule(internalRrule || DEFAULT_RRULE, getPropertyTzid(internalDtstart));
const utcStart = propertyToUTCDate(internalDtstart);
let eventDuration: number;
if (isAllDay) {
const rawEnd = propertyToUTCDate(internalDtEnd);
// Non-inclusive end...
const modifiedEnd = addDays(rawEnd, -1);
const utcEnd = max(utcStart, modifiedEnd);
eventDuration = differenceInCalendarDays(utcEnd, utcStart);
} else {
const utcStart = propertyToUTCDate(internalDtstart);
const utcEnd = propertyToUTCDate(internalDtEnd);
eventDuration = Math.max(+utcEnd - +utcStart, 0);
}
return {
dtstart,
utcStart,
isAllDay,
eventDuration,
modifiedRrule: safeRrule,
exdateMap: createExdateMap(internalExdate),
};
};
interface GetOccurrences {
component: RequiredVcalVeventComponent;
maxStart?: Date;
maxCount?: number;
cache?: Partial<OccurrenceIterationCache>;
}
export const getOccurrences = ({
component,
maxStart = new Date(9999, 0, 1),
maxCount = 1,
cache = {},
}: GetOccurrences): Pick<RecurringResult, 'localStart' | 'localEnd' | 'occurrenceNumber'>[] => {
// ICAL.js ignores COUNT=0, so we have to deal with it by hand
if (maxCount <= 0 || component?.rrule?.value.count === 0) {
return [];
}
if (!cache.start) {
cache.start = getOccurrenceSetup(component);
}
const { eventDuration, isAllDay, dtstart, modifiedRrule, exdateMap } = cache.start;
let iterator;
try {
const rrule = internalValueToIcalValue('recur', modifiedRrule.value);
iterator = rrule.iterator(dtstart);
} catch (e: any) {
console.error(e);
// Pretend it was ok
return [];
}
const result = [];
let next;
// eslint-disable-next-line no-cond-assign
while ((next = iterator.next())) {
const localStart = toUTCDate(getInternalDateTimeValue(next));
if (exdateMap[+localStart]) {
continue;
}
if (result.length >= maxCount || localStart >= maxStart) {
break;
}
const localEnd = isAllDay ? addDays(localStart, eventDuration) : addMilliseconds(localStart, eventDuration);
result.push({
localStart,
localEnd,
occurrenceNumber: iterator.occurrence_number,
});
}
return result;
};
export const getOccurrencesBetween = (
component: Pick<VcalVeventComponent, 'dtstart' | 'rrule' | 'exdate'>,
start: number,
end: number,
cache: Partial<OccurrenceIterationCache> = {}
): RecurringResult[] => {
// ICAL.js ignores COUNT=0, so we have to deal with it by hand
if (component?.rrule?.value.count === 0) {
return [];
}
if (!cache.start) {
cache.start = getOccurrenceSetup(component);
}
const originalDtstart = component.dtstart;
const originalDtend = getDtendProperty(component);
const { eventDuration, isAllDay, utcStart, dtstart, modifiedRrule, exdateMap } = cache.start;
// If it starts after the current end, ignore it
if (+utcStart > end) {
return [];
}
if (!cache.iteration || start < cache.iteration.interval[0] || end > cache.iteration.interval[1]) {
try {
const rrule = internalValueToIcalValue('recur', modifiedRrule.value);
const iterator = rrule.iterator(dtstart);
const interval = [start - YEAR_IN_MS, end + YEAR_IN_MS];
const result = fillOccurrencesBetween({
interval,
iterator,
eventDuration,
originalDtstart,
originalDtend,
isAllDay,
exdateMap,
});
cache.iteration = {
iterator,
result,
interval,
};
} catch (e: any) {
console.error(e);
// Pretend it was ok
return [];
}
}
return cache.iteration.result.filter(({ utcStart, utcEnd }) => isInInterval(+utcStart, +utcEnd, start, end));
};
| 8,393 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/recurrence/rrule.ts | import { getDaysInMonth } from '../../date-fns-utc';
import {
convertUTCDateTimeToZone,
convertZonedDateTimeToUTC,
fromUTCDate,
toLocalDate,
toUTCDate,
} from '../../date/timezone';
import { omit, pick } from '../../helpers/object';
import { RequireSome } from '../../interfaces';
import {
VcalDateOrDateTimeProperty,
VcalDateOrDateTimeValue,
VcalDaysKeys,
VcalRruleFreqValue,
VcalRruleProperty,
VcalRrulePropertyValue,
VcalVeventComponent,
} from '../../interfaces/calendar/VcalModel';
import {
FREQUENCY,
FREQUENCY_COUNT_MAX,
FREQUENCY_COUNT_MAX_INVITATION,
FREQUENCY_INTERVALS_MAX,
MAXIMUM_DATE,
MAXIMUM_DATE_UTC,
} from '../constants';
import { propertyToUTCDate } from '../vcalConverter';
import { getIsDateTimeValue, getIsPropertyAllDay, getPropertyTzid } from '../vcalHelper';
import { getOccurrences } from './recurring';
export const getIsStandardByday = (byday = ''): byday is VcalDaysKeys => {
return /^(SU|MO|TU|WE|TH|FR|SA)$/.test(byday);
};
export const getIsStandardBydayArray = (byday: (string | undefined)[]): byday is VcalDaysKeys[] => {
return !byday.some((day) => !getIsStandardByday(day));
};
export const getPositiveSetpos = (date: Date) => {
const dayOfMonth = date.getUTCDate();
const shiftedDayOfMonth = dayOfMonth - 1;
return Math.floor(shiftedDayOfMonth / 7) + 1;
};
export const getNegativeSetpos = (date: Date) => {
const dayOfMonth = date.getUTCDate();
const daysInMonth = getDaysInMonth(date);
// return -1 if it's the last occurrence in the month
return Math.ceil((dayOfMonth - daysInMonth) / 7) - 1;
};
export const getDayAndSetpos = (byday?: string, bysetpos?: number) => {
if (byday) {
const alternativeBydayMatch = /^([-+]?\d{1})(SU|MO|TU|WE|TH|FR|SA$)/.exec(byday);
if (alternativeBydayMatch) {
const [, pos, day] = alternativeBydayMatch;
return { day, setpos: +pos };
}
}
const result: { day?: string; setpos?: number } = {};
if (byday) {
result.day = byday;
}
if (bysetpos) {
result.setpos = bysetpos;
}
return result;
};
export const getRruleValue = (rrule?: VcalRruleProperty) => {
if (!rrule) {
return;
}
return { ...rrule.value };
};
const getSupportedFreq = (freq: VcalRruleFreqValue): freq is 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'YEARLY' => {
const supportedFreqs = ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'];
return freq ? supportedFreqs.includes(freq) : false;
};
export const getSupportedRruleProperties = (rrule: VcalRrulePropertyValue, isInvitation = false) => {
const { freq } = rrule;
if (isInvitation) {
return [
'freq',
'count',
'interval',
'until',
'wkst',
'bysetpos',
'bysecond',
'byminute',
'byhour',
'byday',
'byweekno',
'bymonthday',
'bymonth',
'byyearday',
];
}
if (freq === 'DAILY') {
return [
'freq',
'count',
'interval',
'until',
'wkst',
'byyearday', // supported but invalid
];
}
if (freq === 'WEEKLY') {
return [
'freq',
'count',
'interval',
'until',
'wkst',
'byday',
'byyearday', // supported but invalid
];
}
if (freq === 'MONTHLY') {
return [
'freq',
'count',
'interval',
'until',
'wkst',
'bymonthday',
'byday',
'bysetpos',
'byyearday', // supported but invalid
];
}
if (freq === 'YEARLY') {
return ['freq', 'count', 'interval', 'until', 'wkst', 'bymonthday', 'bymonth', 'byyearday'];
}
return ['freq', 'count', 'interval', 'until', 'wkst', 'bysetpos', 'byday', 'bymonthday', 'bymonth', 'byyearday'];
};
const ALLOWED_BYSETPOS = [-1, 1, 2, 3, 4];
export const getIsSupportedSetpos = (setpos: number) => {
return ALLOWED_BYSETPOS.includes(setpos);
};
const isLongArray = <T>(arg: T | T[] | undefined): arg is T[] => {
return Array.isArray(arg) && arg.length > 1;
};
const getHasUnsupportedProperties = (rruleProperty: VcalRrulePropertyValue, isInvitation = false) => {
const rruleProperties = Object.entries(rruleProperty)
.filter(([, value]) => value !== undefined)
.map(([field]) => field);
const supportedRruleProperties = getSupportedRruleProperties(rruleProperty, isInvitation);
return rruleProperties.some((property) => !supportedRruleProperties.includes(property));
};
/**
* Given an rrule, return true it's one of the non-custom rules that we support
*/
export const getIsRruleSimple = (rrule?: VcalRrulePropertyValue): boolean => {
if (!rrule) {
return false;
}
const { freq, count, interval, until, bysetpos, byday, bymonth, bymonthday, byyearday } = rrule;
if (!freq || getHasUnsupportedProperties(rrule)) {
return false;
}
const isBasicSimple = (!interval || interval === 1) && !count && !until;
if (freq === FREQUENCY.DAILY) {
return isBasicSimple;
}
if (freq === FREQUENCY.WEEKLY) {
if (isLongArray(byday)) {
return false;
}
return isBasicSimple;
}
if (freq === FREQUENCY.MONTHLY) {
if (byday || isLongArray(bymonthday) || bysetpos) {
return false;
}
return isBasicSimple;
}
if (freq === FREQUENCY.YEARLY) {
if (isLongArray(bymonthday) || isLongArray(bymonth) || byyearday) {
return false;
}
return isBasicSimple;
}
return false;
};
/**
* Given an rrule property, return true if it's one of our custom rules (the limits for COUNT and interval are not taken into account).
* If the event is not recurring or the rrule is not supported, return false.
*/
export const getIsRruleCustom = (rrule?: VcalRrulePropertyValue): boolean => {
if (!rrule) {
return false;
}
const { freq, count, interval, until, bysetpos, byday, bymonth, bymonthday, byyearday } = rrule;
if (!freq || getHasUnsupportedProperties(rrule)) {
return false;
}
const isBasicCustom = (interval && interval > 1) || (count && count >= 1) || !!until;
if (freq === FREQUENCY.DAILY) {
return isBasicCustom;
}
if (freq === FREQUENCY.WEEKLY) {
return isLongArray(byday) || isBasicCustom;
}
if (freq === FREQUENCY.MONTHLY) {
if (isLongArray(byday) || isLongArray(bymonthday) || isLongArray(bysetpos)) {
return false;
}
const { setpos } = getDayAndSetpos(byday, bysetpos);
return (setpos && !!byday) || isBasicCustom;
}
if (freq === FREQUENCY.YEARLY) {
if (isLongArray(bymonthday) || isLongArray(bymonth) || isLongArray(byyearday)) {
return false;
}
return isBasicCustom;
}
return false;
};
export const getIsRruleSupported = (rruleProperty?: VcalRrulePropertyValue, isInvitation = false) => {
if (!rruleProperty) {
return false;
}
const hasUnsupportedProperties = getHasUnsupportedProperties(rruleProperty, isInvitation);
if (hasUnsupportedProperties) {
return false;
}
const { freq, interval = 1, count, until, byday, bysetpos, bymonthday, bymonth, byyearday } = rruleProperty;
const supportedFreq = getSupportedFreq(freq);
if (!supportedFreq) {
return false;
}
if (interval > FREQUENCY_INTERVALS_MAX[freq]) {
return false;
}
if (count) {
if (count > (isInvitation ? FREQUENCY_COUNT_MAX_INVITATION : FREQUENCY_COUNT_MAX)) {
return false;
}
}
if (until) {
if ('isUTC' in until && until.isUTC) {
if (+toUTCDate(until) > +MAXIMUM_DATE_UTC) {
return false;
}
}
if (+toLocalDate(until) > +MAXIMUM_DATE) {
return false;
}
}
if (freq === 'DAILY') {
if (isInvitation) {
return !hasUnsupportedProperties;
}
return true;
}
if (freq === 'WEEKLY') {
if (isInvitation) {
return !hasUnsupportedProperties;
}
return true;
}
if (freq === 'MONTHLY') {
if (isInvitation) {
return !hasUnsupportedProperties;
}
if (isLongArray(byday) || isLongArray(bysetpos) || isLongArray(bymonthday)) {
return false;
}
// byday and bysetpos must both be absent or both present. If they are present, bymonthday should not be present
const { setpos, day } = getDayAndSetpos(byday, bysetpos);
if (!!day && !!setpos) {
return getIsStandardByday(day) && getIsSupportedSetpos(setpos) && !bymonthday;
}
if (+!!day ^ +!!setpos) {
return false;
}
return true;
}
if (freq === 'YEARLY') {
if (isInvitation) {
if (bymonthday && !bymonth) {
// These RRULEs are problematic as ICAL.js does not expand them properly.
// The API will reject them, so we want to block them as well
return false;
}
return !hasUnsupportedProperties;
}
if (isLongArray(bymonthday) || isLongArray(bymonth) || isLongArray(byyearday)) {
return false;
}
if (bymonthday && !bymonth) {
return false;
}
return true;
}
return false;
};
export const getSupportedUntil = ({
until,
dtstart,
guessTzid = 'UTC',
}: {
until: VcalDateOrDateTimeValue;
dtstart: VcalDateOrDateTimeProperty;
guessTzid?: string;
}) => {
const isAllDay = getIsPropertyAllDay(dtstart);
const tzid = getPropertyTzid(dtstart) || 'UTC';
const startDateUTC = propertyToUTCDate(dtstart);
const untilDateUTC = toUTCDate(until);
const startsAfterUntil = +startDateUTC > +untilDateUTC;
const adjustedUntil = startsAfterUntil ? fromUTCDate(startDateUTC) : until;
// According to the RFC, we should use UTC dates if and only if the event is not all-day.
if (isAllDay) {
// we should use a floating date in this case
if (getIsDateTimeValue(adjustedUntil)) {
// try to guess the right UNTIL
const untilGuess = convertUTCDateTimeToZone(adjustedUntil, guessTzid);
return {
year: untilGuess.year,
month: untilGuess.month,
day: untilGuess.day,
};
}
return {
year: adjustedUntil.year,
month: adjustedUntil.month,
day: adjustedUntil.day,
};
}
const zonedUntilDateTime = getIsDateTimeValue(adjustedUntil)
? pick(adjustedUntil, ['year', 'month', 'day', 'hours', 'minutes', 'seconds'])
: { ...pick(adjustedUntil, ['year', 'month', 'day']), hours: 0, minutes: 0, seconds: 0 };
const zonedUntil = convertUTCDateTimeToZone(zonedUntilDateTime, tzid);
// Pick end of day in the event start date timezone
const zonedEndOfDay = { ...zonedUntil, hours: 23, minutes: 59, seconds: 59 };
const utcEndOfDay = convertZonedDateTimeToUTC(zonedEndOfDay, tzid);
return { ...utcEndOfDay, isUTC: true };
};
export const getSupportedRrule = (
vevent: RequireSome<Partial<VcalVeventComponent>, 'dtstart'>,
isInvitation = false,
guessTzid?: string
): VcalRruleProperty | undefined => {
if (!vevent.rrule?.value) {
return;
}
const { dtstart, rrule } = vevent;
const { until } = rrule.value;
const supportedRrule = { ...rrule };
if (until) {
const supportedUntil = getSupportedUntil({
until,
dtstart,
guessTzid,
});
supportedRrule.value.until = supportedUntil;
}
if (!getIsRruleSupported(rrule.value, isInvitation)) {
return;
}
return supportedRrule;
};
export const getHasOccurrences = (vevent: RequireSome<Partial<VcalVeventComponent>, 'dtstart'>) =>
!!getOccurrences({ component: vevent, maxCount: 1 }).length;
export const getHasConsistentRrule = (vevent: RequireSome<Partial<VcalVeventComponent>, 'dtstart'>) => {
const { rrule } = vevent;
if (!rrule?.value) {
return true;
}
const { freq, until, count, byyearday } = rrule.value;
if (byyearday && freq !== 'YEARLY') {
// According to the RFC, the BYYEARDAY rule part MUST NOT be specified when the FREQ
// rule part is set to DAILY, WEEKLY, or MONTHLY
return false;
}
if (until && count !== undefined) {
return false;
}
// make sure DTSTART matches the pattern of the recurring series (we exclude EXDATE and COUNT/UNTIL here)
const rruleValueWithNoCountOrUntil = omit(rrule.value, ['count', 'until']);
const [first] = getOccurrences({
component: omit({ ...vevent, rrule: { value: rruleValueWithNoCountOrUntil } }, ['exdate']),
maxCount: 1,
});
if (!first) {
return false;
}
if (+first.localStart !== +toUTCDate(vevent.dtstart.value)) {
return false;
}
return true;
};
| 8,394 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/recurrence/rruleEqual.ts | import shallowEqual from '@proton/utils/shallowEqual';
import { isSameDay } from '../../date-fns-utc';
import { toUTCDate } from '../../date/timezone';
import isDeepEqual from '../../helpers/isDeepEqual';
import { omit } from '../../helpers/object';
import {
VcalDateOrDateTimeValue,
VcalDays,
VcalDaysKeys,
VcalRruleProperty,
VcalRrulePropertyValue,
} from '../../interfaces/calendar/VcalModel';
import { FREQUENCY } from '../constants';
import { dayToNumericDay } from '../vcalConverter';
import { getRruleValue } from './rrule';
import { withRruleWkst } from './rruleWkst';
const maybeArrayComparisonKeys = [
'byday',
'bymonthday',
'bymonth',
'bysecond',
'byminute',
'byhour',
'byyearday',
'byweekno',
] as const;
const isSingleValue = <T>(arg: T | T[] | undefined) => {
if (arg === undefined) {
return false;
}
return !Array.isArray(arg) || arg.length === 1;
};
/**
* Remove redundant properties for a given RRULE
*/
const getNormalizedRrule = (rrule: VcalRrulePropertyValue, wkstCalendar = VcalDays.MO) => {
const { freq, count, interval, byday, bymonth, bymonthday, wkst: wkstRrule } = rrule;
const wkst = wkstRrule ? dayToNumericDay(wkstRrule) : wkstCalendar;
const redundantProperties: (keyof VcalRrulePropertyValue)[] = [];
if (count && count === 1) {
redundantProperties.push('count');
}
if (interval && interval === 1) {
redundantProperties.push('interval');
}
if (freq === FREQUENCY.WEEKLY) {
if (isSingleValue(byday)) {
redundantProperties.push('byday');
}
}
if (freq === FREQUENCY.MONTHLY) {
if (isSingleValue(bymonthday)) {
redundantProperties.push('bymonthday');
}
}
if (freq === FREQUENCY.YEARLY) {
if (isSingleValue(byday) && isSingleValue(bymonth)) {
redundantProperties.push('byday', 'bymonth');
}
}
return withRruleWkst({ freq, ...omit(rrule, redundantProperties) }, wkst);
};
const isMaybeArrayEqual = (oldValue: any | any[], newValue: any | any[]) => {
if (Array.isArray(oldValue) && Array.isArray(newValue)) {
return shallowEqual(oldValue.slice().sort(), newValue.slice().sort());
}
return oldValue === newValue;
};
const isUntilEqual = (oldUntil?: VcalDateOrDateTimeValue, newUntil?: VcalDateOrDateTimeValue) => {
if (!oldUntil && !newUntil) {
return true;
}
// If changing an all-day event into a part-day event the until adds the time part, so ignore that here.
return oldUntil && newUntil && isSameDay(toUTCDate(oldUntil), toUTCDate(newUntil));
};
/**
* Determine if two recurring rules are equal up to re-writing.
*/
export const getIsRruleEqual = (oldRrule?: VcalRruleProperty, newRrule?: VcalRruleProperty, ignoreWkst = false) => {
const oldValue = getRruleValue(oldRrule);
const newValue = getRruleValue(newRrule);
if (ignoreWkst && oldValue && newValue) {
// To ignore WKST, we just set it to 'MO' in both RRULEs
oldValue.wkst = VcalDays[VcalDays.MO] as VcalDaysKeys;
newValue.wkst = VcalDays[VcalDays.MO] as VcalDaysKeys;
}
if (newValue && oldValue) {
// we "normalize" the rrules first (i.e. remove maybeArrayComparisonKeys in case they are redundant)
const normalizedOldValue = getNormalizedRrule(oldValue);
const normalizedNewValue = getNormalizedRrule(newValue);
// Compare array values separately because they can be possibly unsorted...
const oldWithoutMaybeArrays = omit(normalizedOldValue, [...maybeArrayComparisonKeys, 'until']);
const newWithoutMaybeArrays = omit(normalizedNewValue, [...maybeArrayComparisonKeys, 'until']);
if (!isDeepEqual(newWithoutMaybeArrays, oldWithoutMaybeArrays)) {
return false;
}
// Separate comparison for until to handle all-day -> to part-day
if (!isUntilEqual(oldValue.until, newValue.until)) {
return false;
}
return !maybeArrayComparisonKeys.some((key) => {
return !isMaybeArrayEqual(normalizedOldValue[key], normalizedNewValue[key]);
});
}
return isDeepEqual(oldRrule, newRrule);
};
| 8,395 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/recurrence/rruleProperties.ts | import unique from '@proton/utils/unique';
import { convertUTCDateTimeToZone, fromUTCDate } from '../../date/timezone';
import { VcalDateOrDateTimeValue, VcalDateTimeValue, VcalDays } from '../../interfaces/calendar/VcalModel';
import { END_TYPE, MONTHLY_TYPE } from '../constants';
import { dayToNumericDay, propertyToUTCDate } from '../vcalConverter';
import { getDayAndSetpos, getIsStandardBydayArray } from './rrule';
export const getEndType = (count?: number, until?: VcalDateOrDateTimeValue) => {
// count and until cannot occur at the same time (see https://tools.ietf.org/html/rfc5545#page-37)
if (count && count >= 1) {
return END_TYPE.AFTER_N_TIMES;
}
if (until) {
return END_TYPE.UNTIL;
}
return END_TYPE.NEVER;
};
export const getMonthType = (byday?: string | string[], bysetpos?: number | number[]) => {
if (typeof byday === 'string' && !Array.isArray(bysetpos)) {
const { setpos } = getDayAndSetpos(byday, bysetpos);
if (setpos) {
return setpos > 0 ? MONTHLY_TYPE.ON_NTH_DAY : MONTHLY_TYPE.ON_MINUS_NTH_DAY;
}
}
return MONTHLY_TYPE.ON_MONTH_DAY;
};
export const getUntilDate = (until?: VcalDateOrDateTimeValue, startTzid?: string) => {
if (!until) {
return undefined;
}
if (!(until as VcalDateTimeValue).isUTC || !startTzid) {
const { year, month, day } = until;
return new Date(Date.UTC(year, month - 1, day));
}
const utcDate = propertyToUTCDate({ value: until as VcalDateTimeValue });
const localDate = convertUTCDateTimeToZone(fromUTCDate(utcDate), startTzid);
return new Date(Date.UTC(localDate.year, localDate.month - 1, localDate.day));
};
export const getWeeklyDays = (byday?: string | string[]) => {
if (byday === undefined) {
return [];
}
const bydayArray = Array.isArray(byday) ? byday : [byday];
if (!getIsStandardBydayArray(bydayArray)) {
return [];
}
const bydayArraySafe = bydayArray.map(dayToNumericDay).filter((value): value is VcalDays => value !== undefined);
// Ensure the start date is included in the list
return unique(bydayArraySafe);
};
| 8,396 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/recurrence/rruleSubset.ts | import { convertZonedDateTimeToUTC, fromUTCDate, toUTCDate } from '../../date/timezone';
import { VcalVeventComponent } from '../../interfaces/calendar';
import { propertyToUTCDate } from '../vcalConverter';
import { getPropertyTzid } from '../vcalHelper';
import {getIsAllDay} from '../veventHelper';
import { RecurringResult, getOccurrences, getOccurrencesBetween } from './recurring';
import { getIsRruleEqual } from './rruleEqual';
export const getAreOccurrencesSubset = (
newOccurrences: (RecurringResult | Pick<RecurringResult, 'localStart'>)[],
oldVevent: VcalVeventComponent
) => {
const cache = {};
for (const { localStart } of newOccurrences) {
const isAllDay = getIsAllDay(oldVevent);
const startTzid = getPropertyTzid(oldVevent.dtstart);
let utcStart = localStart;
if (!isAllDay && startTzid) {
utcStart = toUTCDate(convertZonedDateTimeToUTC(fromUTCDate(localStart), startTzid));
}
const [oldOccurrence] = getOccurrencesBetween(oldVevent, +utcStart, +utcStart, cache);
if (!oldOccurrence) {
return false;
}
}
return true;
};
/**
* Return true if the set of occurrences of the new rrule is contained (equality counts) in the old rrule.
* Return false otherwise
* We restrict to rrules that can be created by us
*/
export const getIsRruleSubset = (newVevent: VcalVeventComponent, oldVevent: VcalVeventComponent) => {
const [{ rrule: newRrule, dtstart: newDtstart }, { rrule: oldRrule }] = [newVevent, oldVevent];
const isRruleEqual = getIsRruleEqual(newRrule, oldRrule);
if (!newRrule || !oldRrule || isRruleEqual) {
return isRruleEqual;
}
const { count: oldCount, until: oldUntil } = oldRrule.value;
const { count: newCount, until: newUntil } = newRrule.value;
if (!newCount && !newUntil && (oldCount || oldUntil)) {
return false;
}
/**
* Given the repeating nature of recurring rules, we're gonna play dirty here
* and simply check if the at max 10 first occurrences of the new recurring rule are generated by the old one.
* For the recurring rules we support this is more than enough, but it wouldn't be
* in a more general (and pathological) scenario.
* The alternative would be to write some code checking the frequency, interval,
* byday, etc properties and going case by case. That code would be cumbersome and ugly
*/
// either newUntil or newCount are not undefined, so we can check if all new occurrences are in the original set
// but for performance we use the same trick as above and check max 10
const maxCount = newCount ? Math.min(newCount, 10) : 10;
const newOccurrences = newUntil
? getOccurrencesBetween(newVevent, +propertyToUTCDate(newDtstart), +toUTCDate(newUntil)).slice(0, 10)
: getOccurrences({ component: newVevent, maxCount });
return getAreOccurrencesSubset(newOccurrences, oldVevent);
};
| 8,397 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/recurrence/rruleUntil.ts | import { VcalDateOrDateTimeProperty, VcalRruleProperty } from '../../interfaces/calendar/VcalModel';
import { getUntilProperty } from '../vcalConverter';
import { getIsPropertyAllDay, getPropertyTzid } from '../vcalHelper';
export const withRruleUntil = (rrule: VcalRruleProperty, dtstart: VcalDateOrDateTimeProperty): VcalRruleProperty => {
const until = rrule.value?.until;
if (!until) {
return rrule;
}
return {
...rrule,
value: {
...rrule.value,
until: getUntilProperty(until, getIsPropertyAllDay(dtstart), getPropertyTzid(dtstart)),
},
};
};
| 8,398 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar | petrpan-code/ProtonMail/WebClients/packages/shared/lib/calendar/recurrence/rruleWkst.ts | import { omit } from '../../helpers/object';
import { VcalDays, VcalRrulePropertyValue, VcalVeventComponent } from '../../interfaces/calendar/VcalModel';
import { FREQUENCY } from '../constants';
import { numericDayToDay } from '../vcalConverter';
/**
* WKST is significant when a WEEKLY "RRULE" has an interval greater than 1,
* and a BYDAY rule part is specified. This is also significant when
* in a YEARLY "RRULE" when a BYWEEKNO rule part is specified. The
* default value is MO. From rfc5545
*/
export const withRruleWkst = (rrule: VcalRrulePropertyValue, wkst = VcalDays.MO): VcalRrulePropertyValue => {
if (wkst !== VcalDays.MO) {
const isWeeklySignificant =
rrule.freq === FREQUENCY.WEEKLY && (rrule.interval ?? 0) >= 1 && rrule.byday !== undefined;
const isYearlySignificant = rrule.freq === FREQUENCY.YEARLY && rrule.byweekno !== undefined;
if (isWeeklySignificant || isYearlySignificant) {
return {
...rrule,
wkst: numericDayToDay(wkst),
};
}
}
if (!rrule.wkst) {
return rrule;
}
return omit(rrule, ['wkst']);
};
const withVeventRruleWkst = <T>(vevent: VcalVeventComponent & T, wkst?: VcalDays): VcalVeventComponent & T => {
if (!vevent.rrule) {
return vevent;
}
return {
...vevent,
rrule: { value: withRruleWkst(vevent.rrule.value, wkst) },
};
};
export default withVeventRruleWkst;
| 8,399 |
Subsets and Splits