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/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/sessions/interface.ts
|
export interface Session {
ExpirationTime: number;
UnlockExpirationTime: number;
ClientID: string;
LocalizedClientName: string;
CreateTime: number;
Scope: number;
ParentUID: null;
RefreshCounter: number;
Flags: number;
AccessExpirationTime: number;
UID: string;
Algo: number;
UserID: number;
OwnerUserID: number | null;
MemberID: string;
Revocable: 1 | 0;
}
| 6,900
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/smtp/SMTPSubmissionSection.tsx
|
import { useEffect, useState } from 'react';
import { format, fromUnixTime } from 'date-fns';
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { Button } from '@proton/atoms/Button';
import {
Loader,
Prompt,
SettingsParagraph,
SettingsSection,
SettingsSectionWide,
Table,
TableBody,
TableHeader,
TableRow,
UpgradeBanner,
useActiveBreakpoint,
useAddresses,
useApi,
useModalState,
useNotifications,
useOrganization,
useUser,
} from '@proton/components';
import { useLoading } from '@proton/hooks';
import { deleteToken, getTokens, isTokenEligible } from '@proton/shared/lib/api/smtptokens';
import {
ADDRESS_TYPE,
APP_UPSELL_REF_PATH,
BRAND_NAME,
MAIL_APP_NAME,
MAIL_UPSELL_PATHS,
PLANS,
PLAN_NAMES,
UPSELL_COMPONENT,
} from '@proton/shared/lib/constants';
import { hasSMTPSubmission } from '@proton/shared/lib/helpers/organization';
import { getUpsellRef } from '@proton/shared/lib/helpers/upsell';
import { getKnowledgeBaseUrl, getSupportContactURL } from '@proton/shared/lib/helpers/url';
import { dateLocale } from '@proton/shared/lib/i18n';
import { Audience } from '@proton/shared/lib/interfaces';
import { isOrganizationB2B } from '@proton/shared/lib/organization/helper';
import clsx from '@proton/utils/clsx';
import isTruthy from '@proton/utils/isTruthy';
import SMTPTokenModal from './SMTPTokenModal';
interface SmtpTokens {
SmtpTokenID: string;
AddressID: string;
Name: string;
CreateTime: number;
LastUsedTime: number | null;
}
const SMTPSubmissionSection = () => {
const api = useApi();
const [user] = useUser();
const [addresses = []] = useAddresses();
const addressMap = new Map(addresses.map((address) => [address.ID, address.Email]));
const hasCustomAddress = addresses.some(({ Type }) => Type === ADDRESS_TYPE.TYPE_CUSTOM_DOMAIN);
const [organization, loadingOrganization] = useOrganization();
const isB2BOrganization = isOrganizationB2B(organization);
const [tokenIDToRemove, setTokenIDToRemove] = useState('');
const [loadingTokens, withLoadingTokens] = useLoading();
const [loadingTokenEligible, withloadingTokenEligible] = useLoading();
const [tokenEligible, setTokenEligible] = useState<boolean>(false);
const [loading, withLoading] = useLoading();
const { createNotification } = useNotifications();
const [confirmModalProps, setConfirmModalOpen, renderConfirmModal] = useModalState();
const [generateTokenModalProps, setGenerateTokenModalOpen, renderGenerateTokenModal] = useModalState();
const [tokens, setTokens] = useState<SmtpTokens[]>([]);
const { isDesktop } = useActiveBreakpoint();
const showDetails = isDesktop;
const submissionTokenAvailable = hasSMTPSubmission(organization);
const tokenNameToRemove = tokens.find(({ SmtpTokenID }) => SmtpTokenID === tokenIDToRemove)?.Name || '';
const hasTokens = tokens.length > 0;
const headers = [
c('Header for table').t`Token name`,
c('Header for table').t`Email address`,
showDetails && c('Header for table').t`Created`,
showDetails && c('Header for table').t`Last used`,
c('Header for table').t`Actions`,
].filter(isTruthy);
const headersLength = headers.length;
const openGenerateTokenModal = () => {
if (!hasCustomAddress) {
createNotification({
type: 'error',
text: c('Error')
.t`You need to have a custom domain address in order to generate an SMTP submission token.`,
});
return;
}
setGenerateTokenModalOpen(true);
};
const confirmRemoveToken = (tokenID: string) => {
setTokenIDToRemove(tokenID);
setConfirmModalOpen(true);
};
const removeToken = async () => {
await api(deleteToken(tokenIDToRemove));
setTokens(tokens.filter(({ SmtpTokenID }) => SmtpTokenID !== tokenIDToRemove));
setTokenIDToRemove('');
setConfirmModalOpen(false);
createNotification({ text: c('Success').t`SMTP token deleted` });
};
const getSmtpTokenEligible = async () => {
let isEligible = submissionTokenAvailable ?? false; // if null then false
// if not eligible and b2b then check
if (!isEligible && isB2BOrganization) {
isEligible = (await api({ ...isTokenEligible(), silence: true })).IsEligible;
}
setTokenEligible(isEligible);
};
const fetchTokens = async () => {
const { SmtpTokens } = await api(getTokens());
setTokens(SmtpTokens);
};
useEffect(() => {
if (!tokenEligible) {
void withloadingTokenEligible(getSmtpTokenEligible());
return;
}
void withLoadingTokens(fetchTokens());
}, [submissionTokenAvailable, tokenEligible]);
if (loadingOrganization || loadingTokenEligible) {
return (
<SettingsSection>
<Loader />
</SettingsSection>
);
}
const mailProPlanName = PLAN_NAMES[PLANS.MAIL_PRO];
const familyPlanName = PLAN_NAMES[PLANS.FAMILY];
const upsellRef = getUpsellRef({
app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH,
component: UPSELL_COMPONENT.BANNER,
feature: MAIL_UPSELL_PATHS.SMTP_SUBMISSION,
isSettings: true,
});
if (!tokenEligible) {
const params = {
topic: 'email delivery and spam',
username: user.Email,
};
const createTicket = (
<Href key="ticket" href={getSupportContactURL(params)}>{c('Link').t`create a ticket`}</Href>
);
if (isB2BOrganization) {
return (
<SettingsSection>
<SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/smtp-submission')}>
{
// translator: full sentence will be: SMTP submission allows 3rd-party services or devices to send email through <Proton Mail> for your custom domain addresses. To request access, please <create a ticket> describing your use cases, what custom domains you would like to use, and expected hourly and daily email volumes.
c('Info')
.jt`SMTP submission allows 3rd-party services or devices to send email through ${MAIL_APP_NAME} for your custom domain addresses. To request access, please ${createTicket} describing your use cases, what custom domains you would like to use, and expected hourly and daily email volumes.`
}
</SettingsParagraph>
</SettingsSection>
);
}
return (
<SettingsSection>
<SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/smtp-submission')}>
{c('Info')
.jt`SMTP submission allows 3rd-party services or devices to send email through ${MAIL_APP_NAME} for your custom domain addresses. This feature is only available to ${BRAND_NAME} for business users with custom domains.`}
</SettingsParagraph>
<UpgradeBanner audience={Audience.B2B} upsellPath={upsellRef}>
{c('new_plans: upgrade')
.t`Included with ${BRAND_NAME} for Business, ${familyPlanName} and ${mailProPlanName}.`}
</UpgradeBanner>
</SettingsSection>
);
}
return (
<SettingsSectionWide>
<SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/smtp-submission')}>
{
// translator: full sentence will be: SMTP submission allows 3rd-party services or devices to send email through <Proton Mail> for your custom domain addresses. To use this feature, start by generating a new token.
c('Info')
.t`SMTP submission allows 3rd-party services or devices to send email through ${MAIL_APP_NAME} for your custom domain addresses. To use this feature, start by generating a new token.`
}
</SettingsParagraph>
<div className="mb-4">
<Button
data-testid="smtp-submission:generate-token"
disabled={loadingTokens}
onClick={openGenerateTokenModal}
>{c('Action').t`Generate token`}</Button>
</div>
<Table className={clsx(!loadingTokens && hasTokens && 'simple-table--has-actions')}>
<TableHeader cells={headers} />
<TableBody colSpan={headersLength} loading={loadingTokens}>
{tokens.map((token) => {
const email = addressMap.get(token.AddressID) || '';
return (
<TableRow
key={token.SmtpTokenID}
cells={[
<span title={token.Name} className="text-ellipsis max-w-full inline-block">
{token.Name}
</span>,
<span title={email} className="text-ellipsis max-w-full inline-block">
{email}
</span>,
showDetails &&
format(fromUnixTime(token.CreateTime), 'PPp', { locale: dateLocale }),
showDetails &&
(token.LastUsedTime
? format(fromUnixTime(token.LastUsedTime), 'PPp', { locale: dateLocale })
: '-'),
<Button
size="small"
disabled={loadingTokens}
onClick={() => confirmRemoveToken(token.SmtpTokenID)}
>{c('Action').t`Delete`}</Button>,
].filter(isTruthy)}
/>
);
})}
{!loadingTokens && !hasTokens && (
<tr>
<td colSpan={headersLength} className="text-center">
<i>{c('TableRow').t`No SMTP tokens found`}</i>
</td>
</tr>
)}
</TableBody>
</Table>
{renderConfirmModal ? (
<Prompt
title={c('Title').t`Delete ${tokenNameToRemove}?`}
buttons={[
<Button
color="danger"
data-testid="smtp-submission:confirm-deletion"
loading={loading}
onClick={() => withLoading(removeToken())}
>{c('Action').t`Delete`}</Button>,
<Button autoFocus onClick={() => setConfirmModalOpen(false)}>{c('Action').t`Cancel`}</Button>,
]}
{...confirmModalProps}
>
<p>{c('Warning')
.t`The device or service using this token will no longer be able to send email through ${MAIL_APP_NAME}.`}</p>
</Prompt>
) : null}
{renderGenerateTokenModal ? (
<SMTPTokenModal
addresses={addresses}
onCreate={() => withLoadingTokens(fetchTokens())}
{...generateTokenModalProps}
/>
) : null}
</SettingsSectionWide>
);
};
export default SMTPSubmissionSection;
| 6,901
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/smtp/SMTPTokenModal.scss
|
@import '~@proton/styles/scss/lib';
.smtp-token {
&-copy {
padding: em(7); // same as input height
inset-block-start: 1px;
}
}
| 6,902
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/smtp/SMTPTokenModal.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { Button, Href } from '@proton/atoms';
import {
Copy,
Form,
InputFieldTwo,
ModalProps,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
Option,
PrimaryButton,
SelectTwo,
useApi,
useFormErrors,
useNotifications,
} from '@proton/components';
import { useLoading } from '@proton/hooks';
import { createToken } from '@proton/shared/lib/api/smtptokens';
import { ADDRESS_TYPE } from '@proton/shared/lib/constants';
import { maxLengthValidator, requiredValidator } from '@proton/shared/lib/helpers/formValidators';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import { Address } from '@proton/shared/lib/interfaces';
import noop from '@proton/utils/noop';
import './SMTPTokenModal.scss';
const Steps = {
TokenForm: 0,
TokenValue: 1,
};
const SMTP_SERVER = 'smtp.protonmail.ch';
const SMTP_PORT = '587';
interface Props extends ModalProps {
addresses: Address[];
onCreate: () => void; // fetch new tokens
}
const SMTPTokenModal = ({ addresses, onCreate, ...rest }: Props) => {
const { onClose } = rest;
const { validator, onFormSubmit } = useFormErrors();
const [step, setStep] = useState(Steps.TokenForm);
const [loading, withLoading] = useLoading();
const { createNotification } = useNotifications();
const [tokenName, setTokenName] = useState('');
const [token, setToken] = useState('');
// This modal can be open only if it has at least one custom address
const customAddresses = addresses.filter(({ Type }) => Type === ADDRESS_TYPE.TYPE_CUSTOM_DOMAIN);
const [addressID, setAddressID] = useState(customAddresses[0].ID);
const api = useApi();
const title = step === Steps.TokenForm ? c('Title').t`Generate SMTP token` : c('Title').t`Your SMTP token`;
const emailAddress = addresses.find(({ ID }) => ID === addressID)?.Email || '';
const handleClose = loading ? noop : onClose;
const handleSubmit = async () => {
if (step === Steps.TokenForm) {
if (loading || !onFormSubmit()) {
return;
}
const { SmtpTokenCode } = await api(createToken(addressID, tokenName));
setToken(SmtpTokenCode);
setStep(Steps.TokenValue);
onCreate();
}
};
const handleCopyEmail = () => {
createNotification({ type: 'success', text: c('Success').t`Email address copied to clipboard` });
};
const handleCopyToken = () => {
createNotification({ type: 'success', text: c('Success').t`Token copied to clipboard` });
};
const handleCopyServer = () => {
createNotification({ type: 'success', text: c('Success').t`Server copied to clipboard` });
};
const handleCopyPort = () => {
createNotification({ type: 'success', text: c('Success').t`Port copied to clipboard` });
};
const content = () => {
if (step === Steps.TokenForm) {
return (
<>
<p>{c('Info')
.t`Give the token a descriptive name, such as the service you plan to use it with, and select one of your active custom domain addresses. Only this address will be able to send emails with this token.`}</p>
<InputFieldTwo
label={c('Label').t`Token name`}
id="token-name"
autoFocus
maxLength={100}
error={validator([requiredValidator(tokenName), maxLengthValidator(tokenName, 100)])}
placeholder={c('Placeholder').t`Printer`}
value={tokenName}
onValue={(value: string) => setTokenName(value)}
disabled={loading}
required
/>
<InputFieldTwo
as={SelectTwo}
id="token-address"
label={c('Label').t`Email address`}
value={addressID}
onValue={(value: unknown) => setAddressID(value as string)}
disabled={loading}
>
{customAddresses.map(({ ID, Email }) => (
<Option key={ID} value={ID} title={Email} />
))}
</InputFieldTwo>
</>
);
}
return (
<>
<p>
{c('Info')
.t`Use the selected email address as the SMTP username in the external service, and the generated token as the SMTP password.`}
<br />
<Href href={getKnowledgeBaseUrl('/smtp-submission')}>{c('Link').t`Learn more`}</Href>
</p>
<div className="flex flex-align-items-center flex-nowrap mb-4">
<InputFieldTwo
id="smtp-username"
label={c('Label').t`SMTP username`}
readOnly
value={emailAddress}
inputClassName="bg-weak"
/>
<Copy
color="norm"
shape="solid"
value={emailAddress}
className="smtp-token-copy relative flex-item-noshrink ml-2"
onCopy={handleCopyEmail}
/>
</div>
<div className="flex flex-align-items-center flex-nowrap mb-4">
<InputFieldTwo
id="smtp-token"
label={c('Label').t`SMTP token`}
readOnly
value={token}
inputClassName="bg-weak"
/>
<Copy
color="norm"
shape="solid"
value={token}
className="smtp-token-copy relative flex-item-noshrink ml-2"
onCopy={handleCopyToken}
/>
</div>
<p className="color-danger">{c('Info')
.t`This token won’t be available after you close this window, and you should not share it with anyone.`}</p>
<div className="flex flex-align-items-center flex-nowrap mb-4">
<InputFieldTwo
id="server"
label={c('Label').t`SMTP server`}
readOnly
value={SMTP_SERVER}
inputClassName="bg-weak"
/>
<Copy
color="norm"
shape="solid"
value={SMTP_SERVER}
className="smtp-token-copy relative flex-item-noshrink ml-2"
onCopy={handleCopyServer}
/>
</div>
<div className="flex flex-align-items-center flex-nowrap mb-4">
<InputFieldTwo
id="port"
label={c('Label').t`SMTP port`}
readOnly
value={SMTP_PORT}
inputClassName="bg-weak"
/>
<Copy
color="norm"
shape="solid"
value={SMTP_PORT}
className="smtp-token-copy relative flex-item-noshrink ml-2"
onCopy={handleCopyPort}
/>
</div>
<p>{c('Info').t`Enable TLS or SSL on the external service if it is supported.`}</p>
</>
);
};
const footer = () => {
if (step === Steps.TokenForm) {
return (
<>
<Button onClick={handleClose}>{c('Action').t`Cancel`}</Button>
<PrimaryButton type="submit" loading={loading}>
{c('Action').t`Generate`}
</PrimaryButton>
</>
);
}
return (
<>
<Button shape="outline" color="norm" className="ml-auto" onClick={handleClose}>{c('Action')
.t`Close`}</Button>
</>
);
};
return (
<ModalTwo as={Form} onSubmit={() => withLoading(handleSubmit())} onClose={handleClose} {...rest}>
<ModalTwoHeader closeButtonProps={{ disabled: loading }} title={title} />
<ModalTwoContent>{content()}</ModalTwoContent>
<ModalTwoFooter>{footer()}</ModalTwoFooter>
</ModalTwo>
);
};
export default SMTPTokenModal;
| 6,903
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/smtp/index.ts
|
export { default as SMTPSubmissionSection } from './SMTPSubmissionSection';
| 6,904
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/support/AttachScreenshot.tsx
|
import { ChangeEvent, Dispatch, SetStateAction } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { MAX_SIZE_SCREENSHOT } from '@proton/shared/lib/constants';
import { resize, toBlob } from '@proton/shared/lib/helpers/image';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import removeItem from '@proton/utils/removeIndex';
import { FileInput, Icon, Info, Table, TableBody, TableCell, TableRow } from '../../components';
import { useNotifications } from '../../hooks';
export interface Screenshot {
name: string;
blob: Blob;
}
interface Props {
id: string;
screenshots: Screenshot[];
setScreenshots: Dispatch<SetStateAction<Screenshot[]>>;
uploading: boolean;
setUploading: Dispatch<SetStateAction<boolean>>;
disabled?: boolean;
}
const AttachScreenshot = ({ id, screenshots, setScreenshots, uploading, setUploading, disabled }: Props) => {
const { createNotification } = useNotifications();
const handleChange = async ({ target }: ChangeEvent<HTMLInputElement>) => {
setUploading(true);
try {
const targetImages = target.files ? [...target.files].filter(({ type }) => /^image\//i.test(type)) : [];
if (!targetImages.length) {
return createNotification({
type: 'error',
text: c('Error notification in the bug report modal when the user upload file')
.t`No image selected`,
});
}
const uploadedScreenshots = await Promise.all(
targetImages.map((img) =>
resize(img, MAX_SIZE_SCREENSHOT).then((base64str) => ({
name: img.name,
blob: toBlob(base64str),
}))
)
);
setScreenshots(uploadedScreenshots);
} finally {
setUploading(false);
}
};
const removeUploadedScreenShot = (screenshot: Screenshot) => {
const index = screenshots.indexOf(screenshot);
if (index === -1) {
return;
}
setScreenshots((items) => removeItem(items, index));
};
return (
<>
<label className="text-semibold block" htmlFor={id}>
<span className="mr-2 align-middle">{c('Label').t`Attach screenshot(s)`}</span>
<Info url={getKnowledgeBaseUrl('/screenshot-reporting-bugs')} />
</label>
<div>
<FileInput
multiple
accept="image/bmp, image/apng, image/png, image/jpeg, image/gif, image/tiff, image/webp"
id={id}
onChange={handleChange}
disabled={uploading || disabled}
loading={uploading}
color="norm"
shape="underline"
>
{c('Action').t`Attach screenshot(s)`}
</FileInput>
</div>
{screenshots.length > 0 && (
<Table hasActions>
<TableBody>
{screenshots.map((screenshot) => {
return (
<TableRow key={screenshot.name}>
<TableCell>
<div key={1} className="text-ellipsis" title={screenshot.name}>
{screenshot.name}
</div>
</TableCell>
<TableCell className="w-custom" style={{ '--w-custom': '4em' }}>
<Button
icon
color="weak"
shape="outline"
onClick={() => removeUploadedScreenShot(screenshot)}
>
<Icon name="trash" alt={c('Label').t`Delete`} />
</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
)}
</>
);
};
export default AttachScreenshot;
| 6,905
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/support/AuthenticatedBugModal.tsx
|
import { useAddresses, useUser, useUserSettings } from '../../hooks';
import BugModal, { Props } from './BugModal';
const AuthenticatedBugModal = (props: Omit<Props, 'username' | 'email'>) => {
const [{ Name = '', Email }] = useUser();
const [userSettings] = useUserSettings();
const [addresses = []] = useAddresses();
const email = Email || addresses[0]?.Email || userSettings?.Email?.Value;
return <BugModal username={Name} email={email} {...props} />;
};
export default AuthenticatedBugModal;
| 6,906
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/support/BugModal.tsx
|
import { useEffect, useMemo, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { c } from 'ttag';
import { Button, Href } from '@proton/atoms';
import { reportBug } from '@proton/shared/lib/api/reports';
import { APPS, BRAND_NAME, CLIENT_TYPES } from '@proton/shared/lib/constants';
import { requiredValidator } from '@proton/shared/lib/helpers/formValidators';
import { omit } from '@proton/shared/lib/helpers/object';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import noop from '@proton/utils/noop';
import {
Collapsible,
CollapsibleContent,
CollapsibleHeader,
CollapsibleHeaderIconButton,
DropdownSizeUnit,
Form,
Icon,
InputFieldTwo,
ModalTwo as Modal,
ModalTwoContent as ModalContent,
ModalTwoFooter as ModalFooter,
ModalTwoHeader as ModalHeader,
ModalProps,
Option,
SelectTwo,
TextAreaTwo,
useFormErrors,
} from '../../components';
import { getClientName, getReportInfo } from '../../helpers/report';
import { useApi, useConfig, useNotifications } from '../../hooks';
import AttachScreenshot, { Screenshot } from './AttachScreenshot';
export type BugModalMode = 'chat-no-agents';
type OptionLabelItem = { type: 'label'; value: string };
type OptionOptionItem = { type: 'option'; title: string; value: string; clientType?: CLIENT_TYPES };
type OptionItem = OptionOptionItem | OptionLabelItem;
interface Model extends ReturnType<typeof getReportInfo> {
Category: OptionOptionItem | undefined;
Description: string;
Email: string;
Username: string;
}
export interface Props {
username?: string;
email?: string;
mode?: BugModalMode;
onClose: ModalProps['onClose'];
onExit: ModalProps['onExit'];
open: ModalProps['open'];
}
const getMailOptions = (): OptionItem[] => {
return [
{ type: 'label', value: c('Group').t`Account` },
{ type: 'option', value: 'Sign in problem', title: c('Bug category').t`Sign in problem` },
{ type: 'option', value: 'Sign up problem', title: c('Bug category').t`Sign up problem` },
{ type: 'option', value: 'Payments problem', title: c('Bug category').t`Payments problem` },
{ type: 'option', value: 'Custom domain problem', title: c('Bug category').t`Custom domain problem` },
{ type: 'label', value: c('Group').t`Apps` },
{ type: 'option', value: 'Bridge problem', title: c('Bug category').t`Bridge problem` },
{ type: 'option', value: 'Import / export problem', title: c('Bug category').t`Import / export problem` },
{ type: 'label', value: c('Group').t`Network` },
{ type: 'option', value: 'Connection problem', title: c('Bug category').t`Connection problem` },
{ type: 'option', value: 'Slow speed problem', title: c('Bug category').t`Slow speed problem` },
{ type: 'label', value: c('Group').t`Services` },
{ type: 'option', value: 'Calendar problem', title: c('Bug category').t`Calendar problem` },
{ type: 'option', value: 'Contacts problem', title: c('Bug category').t`Contacts problem` },
{ type: 'option', value: 'Drive problem', title: c('Bug category').t`Drive problem` },
{ type: 'option', value: 'Mail problem', title: c('Bug category').t`Mail problem` },
{ type: 'option', value: 'VPN problem', title: c('Bug category').t`VPN problem`, clientType: CLIENT_TYPES.VPN },
{ type: 'option', value: 'Pass problem', title: c('Bug category').t`Pass problem` },
{ type: 'label', value: c('Group').t`Other category` },
{ type: 'option', value: 'Feature request', title: c('Bug category').t`Feature request` },
{ type: 'option', value: 'Other', title: c('Bug category').t`Other` },
];
};
const getVPNOptions = (): OptionItem[] => {
return [
{ type: 'option', value: 'Login problem', title: c('Bug category').t`Sign in problem` },
{ type: 'option', value: 'Signup problem', title: c('Bug category').t`Signup problem` },
{ type: 'option', value: 'Payments problem', title: c('Bug category').t`Payments problem` },
{ type: 'option', value: 'Installation problem', title: c('Bug category').t`Installation problem` },
{ type: 'option', value: 'Update problem', title: c('Bug category').t`Update problem` },
{ type: 'option', value: 'Application problem', title: c('Bug category').t`Application problem` },
{ type: 'option', value: 'Connection problem', title: c('Bug category').t`Connection problem` },
{ type: 'option', value: 'Speed problem', title: c('Bug category').t`Speed problem` },
{ type: 'option', value: 'Manual setup problem', title: c('Bug category').t`Manual setup problem` },
{ type: 'option', value: 'Website access problem', title: c('Bug category').t`Website access problem` },
{ type: 'option', value: 'Streaming problem', title: c('Bug category').t`Streaming problem` },
{ type: 'option', value: 'Feature request', title: c('Bug category').t`Feature request` },
];
};
const BugModal = ({ username: Username = '', email, mode, open, onClose, onExit }: Props) => {
const api = useApi();
const location = useLocation();
const [loading, setLoading] = useState(false);
const handleClose = loading ? noop : onClose;
const { APP_VERSION, CLIENT_TYPE, APP_NAME } = useConfig();
const isVpn = APP_NAME === APPS.PROTONVPN_SETTINGS;
const isDrive = APP_NAME === APPS.PROTONDRIVE;
const clearCacheLink = isVpn
? 'https://protonvpn.com/support/clear-browser-cache-cookies/'
: getKnowledgeBaseUrl('/how-to-clean-cache-and-cookies');
const Client = getClientName(APP_NAME);
const showCategory = !isDrive;
const { createNotification } = useNotifications();
const options = useMemo(() => {
return isVpn ? getVPNOptions() : getMailOptions();
}, []);
const categoryOptions = options.map((option) => {
const { type, value } = option;
if (type === 'label') {
return (
<label className="text-semibold px-2 py-1 block" key={value}>
{value}
</label>
);
}
const { title } = option;
return <Option title={title} value={option} key={value} />;
});
const [model, setModel] = useState<Model>(() => {
return {
...getReportInfo(),
Category: undefined,
Description: '',
Email: email || '',
Username: Username || '',
};
});
const [screenshots, setScreenshots] = useState<Screenshot[]>([]);
const [uploadingScreenshots, setUploadingScreenshots] = useState(false);
const link = <Href key="linkClearCache" href={clearCacheLink}>{c('Link').t`clearing your browser cache`}</Href>;
const { validator, onFormSubmit } = useFormErrors();
const setModelDiff = (model: Partial<Model>) => {
setModel((oldModel) => ({ ...oldModel, ...model }));
};
const handleChange = <K extends keyof Model>(key: K) => {
return (value: Model[K]) => setModelDiff({ [key]: value });
};
const categoryTitle = model.Category?.title || '';
const clientType = model.Category?.clientType || CLIENT_TYPE;
const handleSubmit = async () => {
if (!onFormSubmit()) {
return;
}
setLoading(true);
const getParameters = () => {
const screenshotBlobs = screenshots.reduce((acc: { [key: string]: Blob }, { name, blob }) => {
acc[name] = blob;
return acc;
}, {});
const Title = [!isVpn && '[V5]', `[${Client}] Bug [${location.pathname}]`, categoryTitle]
.filter(Boolean)
.join(' ');
return {
...screenshotBlobs,
...omit(model, ['OSArtificial', 'Category']),
Trigger: mode || '',
Client,
ClientVersion: APP_VERSION,
ClientType: clientType,
Title,
};
};
try {
await api(reportBug(getParameters(), 'form'));
onClose?.();
createNotification({ text: c('Success').t`Bug reported` });
} catch (error) {
setLoading(false);
}
};
useEffect(() => {
if (!model.Email && email) {
setModel({ ...model, Email: email });
}
}, [email]);
const OSAndOSVersionFields = (
<>
<InputFieldTwo
id="OS"
label={c('Label').t`Operating system`}
value={model.OS}
onValue={handleChange('OS')}
disabled={loading}
/>
<InputFieldTwo
id="OSVersion"
label={c('Label').t`Operating system version`}
value={model.OSVersion}
onValue={handleChange('OSVersion')}
disabled={loading}
/>
</>
);
const modeAlert = (() => {
if (mode === 'chat-no-agents') {
return (
<p>
{c('Warning')
.t`Unfortunately, we’re not online at the moment. Please complete the form below to describe your issue, and we will look into it and be in touch when we’re back online.`}
</p>
);
}
return (
<>
<p>
{c('Info').jt`Refreshing the page or ${link} will automatically resolve most issues.`}
<br />
<br />
{c('Warning')
.t`Reports are not end-to-end encrypted, please do not send any sensitive information.`}
</p>
</>
);
})();
// Retrieves the selected option by title to ensure referential equality for Select's value
const selectedValue = options.find(
(option) => (option.type === 'option' && option.title === model.Category?.title) || ''
);
return (
<Modal as={Form} open={open} onClose={handleClose} onExit={onExit} onSubmit={handleSubmit}>
<ModalHeader title={c('Title').t`Report a problem`} />
<ModalContent>
{modeAlert}
{Username ? null : (
<InputFieldTwo
autoFocus
id="Username"
label={c('Label').t`${BRAND_NAME} username`}
value={model.Username}
onValue={handleChange('Username')}
disabled={loading}
/>
)}
<InputFieldTwo
id="Email"
label={c('Label').t`Email address`}
placeholder={c('Placeholder').t`A way to contact you`}
value={model.Email}
onValue={handleChange('Email')}
error={validator([requiredValidator(model.Email)])}
disabled={loading}
/>
{showCategory && (
<InputFieldTwo
as={SelectTwo<OptionItem>}
label={c('Label').t`Category`}
placeholder={c('Placeholder').t`Select`}
id="Title"
value={selectedValue}
onValue={(option: OptionItem) => {
if (option.type === 'option') {
setModelDiff({ Category: option });
}
}}
error={validator([requiredValidator(categoryTitle)])}
disabled={loading}
size={{
width: DropdownSizeUnit.Anchor,
maxWidth: DropdownSizeUnit.Viewport,
maxHeight: '16em',
}}
>
{categoryOptions}
</InputFieldTwo>
)}
<InputFieldTwo
as={TextAreaTwo}
id="Description"
label={c('Label').t`What happened?`}
placeholder={c('Placeholder').t`Please describe the problem and include any error messages`}
value={model.Description}
onValue={handleChange('Description')}
error={validator([requiredValidator(model.Description)])}
rows={5}
disabled={loading}
/>
<AttachScreenshot
id="Attachments"
screenshots={screenshots}
setScreenshots={setScreenshots}
uploading={uploadingScreenshots}
setUploading={setUploadingScreenshots}
disabled={loading}
/>
{model.OSArtificial && OSAndOSVersionFields}
<Collapsible className="mt-4">
<CollapsibleHeader
disableFullWidth
suffix={
<CollapsibleHeaderIconButton size="small">
<Icon name="chevron-down" />
</CollapsibleHeaderIconButton>
}
>
<label className="text-semibold">{c('Label').t`System information`}</label>
</CollapsibleHeader>
<CollapsibleContent className="mt-4">
{!model.OSArtificial && OSAndOSVersionFields}
<InputFieldTwo
id="Browser"
label={c('Label').t`Browser`}
value={model.Browser}
onValue={handleChange('Browser')}
disabled={loading}
/>
<InputFieldTwo
id="BrowserVersion"
label={c('Label').t`Browser version`}
value={model.BrowserVersion}
onValue={handleChange('BrowserVersion')}
disabled={loading}
/>
</CollapsibleContent>
</Collapsible>
</ModalContent>
<ModalFooter>
<Button onClick={handleClose} disabled={loading}>
{c('Action').t`Cancel`}
</Button>
<Button loading={loading} disabled={uploadingScreenshots} type="submit" color="norm">
{c('Action').t`Submit`}
</Button>
</ModalFooter>
</Modal>
);
};
export default BugModal;
| 6,907
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/support/FreeUserLiveChatModal.tsx
|
import { c } from 'ttag';
import { Button, ButtonLike } from '@proton/atoms';
import { PLANS, PLAN_NAMES } from '@proton/shared/lib/constants';
import {
Icon,
ModalTwo as Modal,
ModalTwoContent as ModalContent,
ModalTwoHeader as ModalHeader,
ModalProps,
SettingsLink,
useModalState,
} from '../../components';
import { AuthenticatedBugModal } from '../support';
export interface Props {
onClose: ModalProps['onClose'];
onExit: ModalProps['onExit'];
open: ModalProps['open'];
}
const FreeUserLiveChatModal = ({ open, onExit, onClose }: Props) => {
const handleClose = onClose;
const [bugReportModal, setBugReportModal, render] = useModalState();
const handleBugReportClick = () => {
setBugReportModal(true);
};
const onCloseChildModal = () => {
bugReportModal.onClose();
handleClose?.();
};
const planName = PLAN_NAMES[PLANS.VPN];
return (
<>
{render && <AuthenticatedBugModal {...bugReportModal} onClose={onCloseChildModal} />}
<Modal open={open} onExit={onExit} onClose={handleClose} size="small">
<ModalHeader />
<ModalContent className="flex flex-column flex-align-items-center mb-8">
<div className="flex flex-row flex-justify-center flex-align-items-center p-4 rounded-full bg-weak">
<Icon name="speech-bubble" size={20} className="color-primary" />
</div>
<h3 className="text-3xl color-primary text-center mt-4 mb-1">
{c('Live Chat Modal').t`Live chat is available with ${planName}`}
</h3>
<p className="text-center text-lg color-weak">
{c('Live Chat Modal')
.t`Upgrade to unlock chat support and other premium features, or use our free support form to report your issue.`}
</p>
<ButtonLike
as={SettingsLink}
className="text-bold mt-8"
size="small"
pill
color="norm"
path={`/dashboard?plan=${PLANS.VPN}&cycle=1`}
onClick={handleClose}
>
{c('Live Chat Modal').t`Upgrade subscription`}
</ButtonLike>
<Button
shape="ghost"
pill
size="small"
className="color-primary mt-4 text-bold"
onClick={handleBugReportClick}
>{c('Live Chat Modal').t`Open support form`}</Button>
</ModalContent>
</Modal>
</>
);
};
export default FreeUserLiveChatModal;
| 6,908
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/support/index.ts
|
export { default as BugModal } from './BugModal';
export { default as AuthenticatedBugModal } from './AuthenticatedBugModal';
export { default as FreeUserLiveChatModal } from './FreeUserLiveChatModal';
| 6,909
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/ThemeCard.scss
|
@import '~@proton/styles/scss/lib';
.theme-card-button {
&.rounded {
--custom-border-radius: #{rem(8)};
}
&.rounded-sm {
--custom-border-radius: #{rem(4)};
}
&#{&} {
position: relative;
background-color: transparent; // Force transparent background even when active
border-radius: var(
--custom-border-radius
); // fix border radius to prevent border radius change when switching themes
box-shadow: 0 0 0 0 var(--button-default-border-color);
}
svg {
border-radius: calc(var(--custom-border-radius) - 1px);
}
&-medium-wide,
&-large {
svg {
border-end-start-radius: 0;
border-end-end-radius: 0;
}
}
&::after {
content: '';
position: absolute;
inset: -1px;
z-index: 1;
border: 1px solid var(--button-default-border-color);
pointer-events: none;
transition: 0.15s easing(ease-out-quad);
border-radius: inherit;
}
&.is-active {
box-shadow: 0 0 0 1px var(--button-active-border-color);
&::after {
border: 1px solid var(--button-active-border-color);
}
}
}
| 6,910
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/ThemeCard.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import clsx from '@proton/utils/clsx';
import ThemeSvg, { ThemeSvgColors, ThemeSvgSize } from './ThemeSvg';
import './ThemeCard.scss';
interface Props {
label: string;
id: string;
size?: ThemeSvgSize;
colors: ThemeSvgColors;
selected?: boolean;
onChange?: () => void;
disabled?: boolean;
as?: React.ElementType;
className?: string;
borderRadius?: 'sm' | 'md';
'data-testid'?: string;
}
const ThemeCard = ({
label,
id,
size,
colors,
selected,
onChange,
disabled,
borderRadius = 'md',
as: Component = Button,
className,
'data-testid': dataTestId,
}: Props) => {
return (
<Component
name="themeCard"
shape="outline"
color={selected ? 'norm' : 'weak'}
id={id}
className={clsx(
'theme-card-button p-0 flex flex-nowrap flex-column gap-1 flex-align-items-center',
selected && 'is-active no-pointer-events text-bold',
Component === Button && 'w-full interactive-pseudo',
borderRadius === 'sm' && 'rounded-sm',
borderRadius === 'md' && 'rounded',
`theme-card-button-${size}`,
className
)}
aria-pressed={Component === Button ? selected : undefined}
onClick={onChange}
disabled={disabled}
type={Component === Button ? 'button' : undefined}
aria-label={c('Action').t`Use ${label} theme`}
title={c('Action').t`Use ${label} theme`}
data-testid={dataTestId}
>
<ThemeSvg className={clsx('block theme-card-image on-rtl-mirror')} size={size} colors={colors} />
<span
className={clsx(
size === 'small' && 'sr-only',
size === 'medium' && 'sr-only',
size === 'medium-wide' && 'text-sm'
)}
>
{label}
</span>
</Component>
);
};
export default ThemeCard;
| 6,911
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/ThemeCards.tsx
|
import { ThemeTypes } from '@proton/shared/lib/themes/themes';
import clsx from '@proton/utils/clsx';
import ThemeCard from './ThemeCard';
import { ThemeSvgColors, ThemeSvgSize } from './ThemeSvg';
export interface Theme {
label: string;
identifier: ThemeTypes;
thumbColors: ThemeSvgColors;
}
interface Props {
themeIdentifier: ThemeTypes;
onChange: (themeType: ThemeTypes) => void;
className?: string;
disabled?: boolean;
list: Theme[];
size?: ThemeSvgSize;
}
const ThemeCards = ({ themeIdentifier, onChange, disabled, className, list, size = 'medium-wide' }: Props) => {
const { minGridTemplateColumnSize, gridGap } = (() => {
if (size === 'small') {
return {
minGridTemplateColumnSize: 4,
gridGap: 2,
};
}
if (size === 'medium-wide') {
return {
minGridTemplateColumnSize: 6,
gridGap: 4,
};
}
if (size === 'medium') {
return {
minGridTemplateColumnSize: 4,
gridGap: 4,
};
}
// size === 'large'
return {
minGridTemplateColumnSize: 8.25,
gridGap: 4,
};
})();
return (
<ul
className={clsx('unstyled m-0 grid-auto-fill', `gap-${gridGap}`, className)}
style={{ '--min-grid-template-column-size': `${minGridTemplateColumnSize}rem` }}
>
{list.map(({ identifier, label, thumbColors }) => {
const id = `id_${identifier}`;
return (
<li key={label}>
<ThemeCard
label={label}
id={id}
size={size}
colors={thumbColors}
selected={themeIdentifier === identifier}
onChange={() => onChange(identifier)}
disabled={disabled}
data-testid={`theme-card:theme-${label}`}
/>
</li>
);
})}
</ul>
);
};
export default ThemeCards;
| 6,912
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/ThemeInjector.tsx
|
import { useEffect, useLayoutEffect, useMemo } from 'react';
import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig';
import { updateTheme } from '@proton/shared/lib/api/settings';
import { postMessageToIframe, getIsDrawerApp } from '@proton/shared/lib/drawer/helpers';
import { DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces';
import { rootFontSize } from '@proton/shared/lib/helpers/dom';
import { ThemeSetting, getDefaultThemeSetting } from '@proton/shared/lib/themes/themes';
import debounce from '@proton/utils/debounce';
import noop from '@proton/utils/noop';
import { useApi, useDrawer, useUserSettings } from '../../hooks';
import { useTheme } from './ThemeProvider';
const ThemeInjector = () => {
const [userSettings] = useUserSettings();
const { addListener, settings, setThemeSetting } = useTheme();
const api = useApi();
const silentApi = getSilentApi(api);
const { iframeSrcMap } = useDrawer();
const legacyThemeType = userSettings.ThemeType;
const legacyThemeSettings = useMemo(() => getDefaultThemeSetting(legacyThemeType), [legacyThemeType]);
const themeSetting = userSettings.Theme && 'Mode' in userSettings.Theme ? userSettings.Theme : legacyThemeSettings;
useLayoutEffect(() => {
setThemeSetting(themeSetting);
}, [themeSetting]);
useLayoutEffect(() => {
// If apps are opened in drawer, update their theme too
if (iframeSrcMap) {
Object.keys(iframeSrcMap).map((app) => {
if (getIsDrawerApp(app)) {
postMessageToIframe({ type: DRAWER_EVENTS.UPDATE_THEME, payload: { themeSetting: settings } }, app);
}
});
}
}, [settings]);
useEffect(() => {
rootFontSize(true);
}, [settings.FontSize]);
useEffect(() => {
const cb = debounce((settings: ThemeSetting) => {
silentApi(updateTheme(settings)).catch(noop);
}, 500);
const removeListener = addListener(cb);
return () => {
removeListener();
};
}, []);
return null;
};
export default ThemeInjector;
| 6,913
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/ThemeProvider.tsx
|
import { ReactNode, createContext, useCallback, useContext, useEffect, useLayoutEffect, useState } from 'react';
import { clearBit, hasBit, setBit } from '@proton/shared/lib/helpers/bitset';
import { getCookie, setCookie } from '@proton/shared/lib/helpers/cookies';
import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual';
import createListeners from '@proton/shared/lib/helpers/listeners';
import { getSecondLevelDomain } from '@proton/shared/lib/helpers/url';
import {
ColorScheme,
MotionModeSetting,
PROTON_DEFAULT_THEME,
PROTON_THEMES_MAP,
ThemeFeatureSetting,
ThemeFontFaceSetting,
ThemeFontFaceSettingMap,
ThemeFontSizeSetting,
ThemeFontSizeSettingMap,
ThemeModeSetting,
ThemeSetting,
ThemeTypes,
getDarkThemes,
getDefaultThemeSetting,
getParsedThemeSetting,
getProminentHeaderThemes,
getThemeType,
serializeThemeSetting,
} from '@proton/shared/lib/themes/themes';
import noop from '@proton/utils/noop';
import { classNames, styles } from './properties';
interface ThemeInformation {
theme: ThemeTypes;
dark: boolean;
prominentHeader: boolean;
default: boolean;
style: string;
label: string;
colorScheme: ColorScheme;
motionMode: MotionModeSetting;
features: {
scrollbars: boolean;
animations: boolean;
};
}
interface ThemeContextInterface {
setTheme: (theme: ThemeTypes, mode?: ThemeModeSetting) => void;
setThemeSetting: (theme?: ThemeSetting) => void;
setAutoTheme: (enabled: boolean) => void;
setFontSize: (fontSize: ThemeFontSizeSetting) => void;
setFontFace: (fontFace: ThemeFontFaceSetting) => void;
setFeature: (featureBit: ThemeFeatureSetting, toggle: boolean) => void;
settings: ThemeSetting;
information: ThemeInformation;
addListener: (cb: (data: ThemeSetting) => void) => () => void;
}
export const ThemeContext = createContext<ThemeContextInterface>({
setTheme: noop,
setThemeSetting: noop,
setAutoTheme: noop,
setFontSize: noop,
setFontFace: noop,
setFeature: noop,
settings: {
LightTheme: PROTON_DEFAULT_THEME,
DarkTheme: PROTON_DEFAULT_THEME,
Mode: ThemeModeSetting.Light,
FontSize: ThemeFontSizeSetting.DEFAULT,
FontFace: ThemeFontFaceSetting.DEFAULT,
Features: ThemeFeatureSetting.DEFAULT,
},
information: {
theme: PROTON_DEFAULT_THEME,
dark: false,
prominentHeader: false,
default: false,
style: '',
label: '',
colorScheme: ColorScheme.Light,
motionMode: MotionModeSetting.No_preference,
features: {
scrollbars: false,
animations: false,
},
},
addListener: () => noop,
});
interface Props {
children: ReactNode;
initial?: ThemeTypes;
}
export const useTheme = () => {
return useContext(ThemeContext);
};
export const getThemeStyle = (themeType: ThemeTypes = PROTON_DEFAULT_THEME) => {
return PROTON_THEMES_MAP[themeType]?.theme || PROTON_THEMES_MAP[PROTON_DEFAULT_THEME].theme;
};
const THEME_COOKIE_NAME = 'Theme';
const storedTheme = getCookie(THEME_COOKIE_NAME);
export const THEME_ID = 'theme-root';
const matchMediaScheme = window.matchMedia('(prefers-color-scheme: dark)');
const matchMediaMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
const syncClassNameToEl = (el: HTMLElement | null, name: string, toggle: boolean) => {
if (!el) {
return;
}
if (toggle) {
el.classList.add(name);
} else {
el.classList.remove(name);
}
};
const syncStyleToEl = (el: HTMLElement | null, property: string, value: string | undefined) => {
if (!el) {
return;
}
el.style.removeProperty(property);
if (value === undefined) {
return;
}
el.style.setProperty(property, value);
};
const getColorScheme = (matches: boolean): ColorScheme => {
return matches ? ColorScheme.Dark : ColorScheme.Light;
};
const getMotionMode = (matches: boolean): MotionModeSetting => {
return matches ? MotionModeSetting.Reduce : MotionModeSetting.No_preference;
};
const listeners = createListeners<[ThemeSetting]>();
const darkThemes = getDarkThemes();
const prominentHeaderThemes = getProminentHeaderThemes();
const ThemeProvider = ({ children }: Props) => {
const [themeSetting, setThemeSettingDefault] = useState(() => {
return getParsedThemeSetting(storedTheme);
});
const setThemeSetting = useCallback((theme: ThemeSetting = getDefaultThemeSetting()) => {
setThemeSettingDefault((oldTheme: ThemeSetting) => {
if (isDeepEqual(theme, oldTheme)) {
return oldTheme;
}
return theme;
});
}, []);
const [colorScheme, setColorScheme] = useState<ColorScheme>(() => {
return getColorScheme(matchMediaScheme.matches);
});
const [motionMode, setMotionMode] = useState<MotionModeSetting>(() => {
return getMotionMode(matchMediaMotion.matches);
});
useLayoutEffect(() => {
setColorScheme(getColorScheme(matchMediaScheme.matches));
const listener = (e: MediaQueryListEvent) => {
setColorScheme(getColorScheme(e.matches));
};
// Safari <14 does not support addEventListener on match media queries
matchMediaScheme.addEventListener?.('change', listener);
return () => {
matchMediaScheme.removeEventListener?.('change', listener);
};
}, []);
useLayoutEffect(() => {
setMotionMode(getMotionMode(matchMediaMotion.matches));
const listener = (e: MediaQueryListEvent) => {
setMotionMode(getMotionMode(e.matches));
};
// Safari <14 does not support addEventListener on match media queries
matchMediaMotion.addEventListener?.('change', listener);
return () => {
matchMediaMotion.removeEventListener?.('change', listener);
};
}, []);
const syncThemeSettingValue = (theme: ThemeSetting) => {
listeners.notify(theme);
setThemeSetting(theme);
};
const setTheme = (themeType: ThemeTypes, mode?: ThemeModeSetting) => {
if (mode) {
syncThemeSettingValue({
...themeSetting,
Mode: ThemeModeSetting.Auto,
[mode === ThemeModeSetting.Dark ? 'DarkTheme' : 'LightTheme']: themeType,
});
return;
}
if (darkThemes.includes(themeType)) {
syncThemeSettingValue({ ...themeSetting, Mode: ThemeModeSetting.Dark, DarkTheme: themeType });
} else {
syncThemeSettingValue({ ...themeSetting, Mode: ThemeModeSetting.Light, LightTheme: themeType });
}
};
const setAutoTheme = (enabled: boolean) => {
if (enabled) {
syncThemeSettingValue({ ...themeSetting, Mode: ThemeModeSetting.Auto });
} else {
syncThemeSettingValue({
...themeSetting,
Mode: colorScheme === ColorScheme.Light ? ThemeModeSetting.Light : ThemeModeSetting.Dark,
});
}
};
const setFontSize = (fontSize: ThemeFontSizeSetting) => {
syncThemeSettingValue({ ...themeSetting, FontSize: fontSize });
};
const setFontFace = (fontFace: ThemeFontFaceSetting) => {
syncThemeSettingValue({ ...themeSetting, FontFace: fontFace });
};
const setFeature = (featureBit: ThemeFeatureSetting, toggle: boolean) => {
syncThemeSettingValue({
...themeSetting,
Features: toggle ? setBit(themeSetting.Features, featureBit) : clearBit(themeSetting.Features, featureBit),
});
};
const theme = getThemeType(themeSetting, colorScheme);
const style = getThemeStyle(theme);
const information: ThemeInformation = {
theme,
dark: darkThemes.includes(theme),
prominentHeader: prominentHeaderThemes.includes(theme),
default: PROTON_DEFAULT_THEME === theme,
style,
label: PROTON_THEMES_MAP[theme]?.label || '',
colorScheme,
motionMode,
features: {
scrollbars: hasBit(themeSetting.Features, ThemeFeatureSetting.SCROLLBARS_OFF),
animations: hasBit(themeSetting.Features, ThemeFeatureSetting.ANIMATIONS_OFF),
},
};
useLayoutEffect(() => {
const htmlEl = document.querySelector('html');
const defaultValue = ThemeFontSizeSettingMap[ThemeFontSizeSetting.DEFAULT].value;
const actualValue = ThemeFontSizeSettingMap[themeSetting.FontSize]?.value;
const value = !actualValue || defaultValue === actualValue ? undefined : `${actualValue}`;
syncStyleToEl(htmlEl, styles.fontSize, value);
}, [themeSetting.FontSize]);
useLayoutEffect(() => {
const htmlEl = document.querySelector('html');
const defaultValue = ThemeFontFaceSettingMap[ThemeFontFaceSetting.DEFAULT].value;
const actualValue = ThemeFontFaceSettingMap[themeSetting.FontFace]?.value;
const value = !actualValue || defaultValue === actualValue ? undefined : `${actualValue}`;
syncStyleToEl(htmlEl, styles.fontFamily, value);
}, [themeSetting.FontFace]);
useLayoutEffect(() => {
const htmlEl = document.querySelector('html');
syncClassNameToEl(htmlEl, classNames.scrollbars, information.features.scrollbars);
syncClassNameToEl(htmlEl, classNames.animations, information.features.animations);
}, [information.features.animations, information.features.scrollbars]);
useEffect(() => {
const syncToMeta = () => {
const themeMeta = document.querySelector("meta[name='theme-color']");
const uiProminentElement = document.querySelector('.ui-prominent');
const themeColor = uiProminentElement
? window.getComputedStyle(uiProminentElement).getPropertyValue('--background-norm').trim()
: '';
if (themeMeta && themeColor) {
themeMeta.setAttribute('content', themeColor);
}
};
syncToMeta();
}, [theme]);
useEffect(() => {
return () => {
listeners.clear();
};
}, []);
useEffect(() => {
const syncToCookie = () => {
const cookieValue = serializeThemeSetting(themeSetting);
// Note: We might set `undefined` which will clear the cookie
setCookie({
cookieName: THEME_COOKIE_NAME,
cookieValue,
cookieDomain: getSecondLevelDomain(window.location.hostname),
path: '/',
expirationDate: 'max',
});
};
syncToCookie();
}, [themeSetting]);
return (
<ThemeContext.Provider
value={{
settings: themeSetting,
setTheme,
setThemeSetting,
setAutoTheme,
setFontSize,
setFontFace,
setFeature,
information,
addListener: listeners.subscribe,
}}
>
<style id={THEME_ID}>{style}</style>
{children}
</ThemeContext.Provider>
);
};
export default ThemeProvider;
| 6,914
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/ThemeSvg.tsx
|
export type ThemeSvgSize = 'small' | 'medium-wide' | 'medium' | 'large';
export type ThemeSvgColors = { prominent: string; standard: string; primary: string; weak: string };
interface Props {
size?: ThemeSvgSize;
colors: ThemeSvgColors;
className?: string;
}
const ThemeSvg = ({ size = 'medium-wide', colors, className }: Props) => {
const dimensions = {
small: { width: 50, height: 32 },
'medium-wide': { width: 106, height: 44 },
medium: { width: 106, height: 66 },
large: { width: 122, height: 78 },
}[size];
return (
<svg
xmlns="http://www.w3.org/2000/svg"
className={className}
fill="none"
viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}
>
<path fill={colors.standard} d={`M0 0h${dimensions.width}v${dimensions.height}H0z`} />
<path fill={colors.prominent} d={`M0 0h36v${dimensions.height}H0z`} />
<rect width="20" height="4" x="8" y="8" fill={colors.primary} rx="2" ry="2" />
<g fill={colors.weak}>
<rect width="12" height="2" x="8" y="16" rx="1" ry="1" />
<rect width="16" height="2" x="8" y="20" rx="1" ry="1" opacity="0.75" />
<rect width="12" height="2" x="8" y="24" rx="1" ry="1" opacity="0.5" />
</g>
</svg>
);
};
export default ThemeSvg;
| 6,915
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/ThemeSyncModeCard.tsx
|
import { c } from 'ttag';
import { PROTON_THEMES_MAP, ThemeTypes } from '@proton/shared/lib/themes/themes';
import clsx from '@proton/utils/clsx';
import { Icon, Info, ThemeCards } from '../..';
import { Theme } from './ThemeCards';
import { ThemeSvgSize } from './ThemeSvg';
interface Props {
mode: 'light' | 'dark';
size?: ThemeSvgSize;
minSize?: string;
className?: string;
listClassName?: string;
themeIdentifier: ThemeTypes;
list: Theme[];
onChange: (themeType: ThemeTypes) => void;
active: boolean;
}
const ThemeSyncModeCard = ({
mode,
size = 'medium',
className,
listClassName,
themeIdentifier,
list,
onChange,
active,
}: Props) => {
return (
<div className={clsx('flex-item-fluid border rounded-lg p-4', className)}>
<div className={clsx(size !== 'small' && 'flex flex-justify-space-between flex-nowrap gap-2', 'mb-4')}>
<div className="flex flex-align-items-center flex-nowrap gap-2">
<Icon name={mode === 'light' ? 'sun' : 'moon'} className="flex-item-noshrink" />
<span className={clsx(active && 'text-semibold')}>
{mode === 'light' ? c('Title').t`Day theme` : c('Title').t`Night theme`}
{active && ` ${c('Title').t`(active)`}`}
</span>
<Info
title={
mode === 'light'
? c('Tooltip')
.t`The selected theme will be active when your system is set to "light mode"`
: c('Tooltip')
.t`The selected theme will be active when your system is set to "dark mode"`
}
/>
</div>
<div className={clsx(active && 'text-semibold', size === 'small' && 'ml-6')}>
{PROTON_THEMES_MAP[themeIdentifier].label}
</div>
</div>
<ThemeCards
size={size}
className={listClassName}
list={list}
themeIdentifier={themeIdentifier}
onChange={onChange}
/>
</div>
);
};
export default ThemeSyncModeCard;
| 6,916
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/ThemeSyncModeDropdown.tsx
|
import { c } from 'ttag';
import { ButtonLike } from '@proton/atoms/Button';
import { PROTON_THEMES_MAP, ThemeTypes } from '@proton/shared/lib/themes/themes';
import clsx from '@proton/utils/clsx';
import { DropdownMenu, DropdownMenuButton, DropdownSizeUnit, Icon, SimpleDropdown, ThemeCard } from '../..';
import { Theme } from './ThemeCards';
interface Props {
mode: 'light' | 'dark';
minSize?: string;
className?: string;
themeIdentifier: ThemeTypes;
list: Theme[];
onChange: (themeType: ThemeTypes) => void;
active: boolean;
}
const ThemeSyncModeDropdown = ({ mode, className, themeIdentifier, list, onChange }: Props) => {
const dropdownButtonContent = (
<>
<span className="w-custom" style={{ '--w-custom': '2.75rem' }}>
<ThemeCard
label={PROTON_THEMES_MAP[themeIdentifier].label}
id={`id_${PROTON_THEMES_MAP[themeIdentifier].identifier}`}
size="small"
colors={PROTON_THEMES_MAP[themeIdentifier].thumbColors}
as="div"
className="rounded-sm"
/>
</span>
<span className="flex-item-fluid">{PROTON_THEMES_MAP[themeIdentifier].label}</span>
</>
);
return (
<div className={clsx('', className)}>
<div className={clsx('flex flex-justify-space-between flex-nowrap gap-2 mb-2')}>
<div className="flex flex-align-items-center flex-nowrap gap-2 text-sm">
<Icon name={mode === 'light' ? 'sun' : 'moon'} className={clsx('color-weak flex-item-noshrink')} />
<span className="color-weak">
{mode === 'light' ? c('Title').t`Day theme` : c('Title').t`Night theme`}
</span>
</div>
</div>
<SimpleDropdown
as={ButtonLike}
shape="outline"
color="weak"
type="button"
originalPlacement="bottom"
dropdownClassName="quickSettingsThemeDropdown"
content={dropdownButtonContent}
contentProps={{
size: { width: DropdownSizeUnit.Anchor, height: DropdownSizeUnit.Dynamic, maxHeight: '10rem' },
}}
className={clsx('w-full flex flex-nowrap flex-justify-space-between p-2 gap-3 text-left', className)}
>
<DropdownMenu>
{list.map(({ identifier, label, thumbColors }) => {
const id = `id_${identifier}`;
return (
<DropdownMenuButton
key={label}
isSelected={themeIdentifier === identifier}
className={clsx('flex flex-nowrap flex-align-items-center gap-3')}
onClick={() => onChange(identifier)}
>
<span className="w-custom" style={{ '--w-custom': '2.75rem' }}>
<ThemeCard
label={label}
id={id}
size="small"
colors={thumbColors}
selected={themeIdentifier === identifier}
onChange={() => {}}
as="div"
className={clsx(
'rounded-sm border',
themeIdentifier === identifier ? 'border-primary' : 'border-weak'
)}
data-testid={`theme-card:theme-${label}`}
/>
</span>
<span className="">{label}</span>
</DropdownMenuButton>
);
})}
</DropdownMenu>
</SimpleDropdown>
</div>
);
};
export default ThemeSyncModeDropdown;
| 6,917
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/ThemesModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { ColorScheme, ThemeModeSetting, getThemes } from '@proton/shared/lib/themes/themes';
import { Info, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Toggle } from '../../components';
import ThemeCards from './ThemeCards';
import { useTheme } from './ThemeProvider';
import ThemeSyncModeCard from './ThemeSyncModeCard';
const ThemesModal = (props: ModalProps) => {
const { information, settings, setTheme, setAutoTheme } = useTheme();
const themes = getThemes();
return (
<ModalTwo size="large" {...props}>
<ModalTwoHeader title={c('Title').t`Select a theme`} />
<ModalTwoContent>
<p className="mb-4">{c('Info').t`Customize the look and feel of ${BRAND_NAME} applications.`}</p>
<div className="inline-flex flex-align-item-center mb-4">
<label htmlFor="themeSyncToggle" className="text-semibold">
<span className="mr-2">{c('Label').t`Synchronize with system`}</span>
<Info
title={c('Tooltip')
.t`Automatically switch between your preferred themes for day and night in sync with your system’s day and night modes`}
/>
</label>
<Toggle
id="themeSyncToggle"
className="ml-6"
checked={settings.Mode === ThemeModeSetting.Auto}
onChange={(e) => setAutoTheme(e.target.checked)}
/>
</div>
{settings.Mode === ThemeModeSetting.Auto ? (
<div className="flex flex-nowrap gap-4 on-mobile-flex-column">
<ThemeSyncModeCard
mode="light"
size="small"
list={themes}
themeIdentifier={settings.LightTheme}
onChange={(themeType) => {
setTheme(themeType, ThemeModeSetting.Light);
}}
active={information.colorScheme === ColorScheme.Light}
/>
<ThemeSyncModeCard
mode="dark"
size="small"
list={themes}
themeIdentifier={settings.DarkTheme}
onChange={(themeType) => {
setTheme(themeType, ThemeModeSetting.Dark);
}}
active={information.colorScheme === ColorScheme.Dark}
/>
</div>
) : (
<ThemeCards
list={themes}
themeIdentifier={information.theme}
onChange={(themeType) => {
setTheme(themeType);
}}
/>
)}
</ModalTwoContent>
<ModalTwoFooter>
<Button color="norm" className="ml-auto" onClick={props.onClose}>{c('Action').t`OK`}</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default ThemesModal;
| 6,918
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/ThemesSection.tsx
|
import { c } from 'ttag';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { ColorScheme, ThemeModeSetting, getThemes } from '@proton/shared/lib/themes/themes';
import { Info, Toggle, useNotifications } from '../..';
import {
SettingsLayout,
SettingsLayoutLeft,
SettingsLayoutRight,
SettingsParagraph,
SettingsSectionWide,
} from '../account';
import ThemeCards from './ThemeCards';
import { useTheme } from './ThemeProvider';
import ThemeSyncModeCard from './ThemeSyncModeCard';
const ThemesSection = () => {
const { information, settings, setTheme, setAutoTheme } = useTheme();
const { createNotification } = useNotifications();
const notifyPreferenceSaved = () => createNotification({ text: c('Success').t`Preference saved` });
const themes = getThemes();
return (
<>
<SettingsSectionWide>
<SettingsParagraph>{c('Info')
.t`Customize the look and feel of ${BRAND_NAME} applications.`}</SettingsParagraph>
</SettingsSectionWide>
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="themeSyncToggle" className="text-semibold align-top">
<span className="mr-2">{c('Label').t`Synchronize with system`}</span>
<Info
title={c('Tooltip')
.t`Automatically switch between your preferred themes for day and night in sync with your system’s day and night modes`}
/>
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight className="flex pt-1">
<Toggle
id="themeSyncToggle"
checked={settings.Mode === ThemeModeSetting.Auto}
onChange={(e) => {
setAutoTheme(e.target.checked);
notifyPreferenceSaved();
}}
/>
</SettingsLayoutRight>
</SettingsLayout>
{settings.Mode === ThemeModeSetting.Auto ? (
<SettingsSectionWide className="flex mt-6 flex-nowrap gap-4 on-mobile-flex-column">
<ThemeSyncModeCard
mode="light"
list={themes}
themeIdentifier={settings.LightTheme}
onChange={(themeType) => {
setTheme(themeType, ThemeModeSetting.Light);
notifyPreferenceSaved();
}}
active={information.colorScheme === ColorScheme.Light}
/>
<ThemeSyncModeCard
mode="dark"
list={themes}
themeIdentifier={settings.DarkTheme}
onChange={(themeType) => {
setTheme(themeType, ThemeModeSetting.Dark);
notifyPreferenceSaved();
}}
active={information.colorScheme === ColorScheme.Dark}
/>
</SettingsSectionWide>
) : (
<SettingsSectionWide className="mt-6">
<ThemeCards
size="large"
list={themes}
themeIdentifier={information.theme}
onChange={(themeType) => {
setTheme(themeType);
notifyPreferenceSaved();
}}
/>
</SettingsSectionWide>
)}
</>
);
};
export default ThemesSection;
| 6,919
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/index.ts
|
export { default as ThemeProvider } from './ThemeProvider';
export { default as ThemesSection } from './ThemesSection';
export { default as ThemeSvg } from './ThemeSvg';
export { default as ThemeCard } from './ThemeCard';
export { default as ThemeCards } from './ThemeCards';
export { default as useThemeQueryParameter } from './useThemeQueryParameter';
export { default as useSyncIframeStyles } from './useSyncIframeStyles';
export { useTheme } from './ThemeProvider';
| 6,920
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/properties.ts
|
export const styles = {
fontSize: '--setting-font-size',
fontFamily: '--setting-font-family',
} as const;
export const classNames = {
scrollbars: 'feature-scrollbars-off',
animations: 'feature-animations-off',
} as const;
| 6,921
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/useSyncIframeStyles.ts
|
import { useEffect } from 'react';
import { classNames, styles } from './properties';
const useSyncIframeStyles = (
targetEl: HTMLElement | null | undefined,
sourceEl: HTMLElement | null | undefined = document.documentElement
) => {
useEffect(() => {
if (!targetEl || !sourceEl) {
return;
}
const sync = (list: DOMTokenList, style: CSSStyleDeclaration) => {
Object.values(classNames).forEach((className) => {
if (list.contains(className)) {
targetEl.classList.add(className);
} else {
targetEl.classList.remove(className);
}
});
Object.values(styles).forEach((attribute) => {
const value = style.getPropertyValue(attribute);
if (value) {
targetEl.style.setProperty(attribute, value);
} else {
targetEl.style.removeProperty(attribute);
}
});
};
const observer = new MutationObserver((e) => {
if (e.some(({ attributeName }) => attributeName === 'class' || attributeName === 'style')) {
sync(sourceEl.classList, sourceEl.style);
}
});
sync(sourceEl.classList, sourceEl.style);
observer.observe(sourceEl, { attributes: true });
return () => {
observer.disconnect();
};
}, [targetEl, sourceEl]);
};
export default useSyncIframeStyles;
| 6,922
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/themes/useThemeQueryParameter.ts
|
import { useLayoutEffect } from 'react';
import { PROTON_DEFAULT_THEME, ThemeTypes } from '@proton/shared/lib/themes/themes';
import { useTheme } from './ThemeProvider';
/**
* Sets the current theme to use based on a `theme`
* query parameter .
*
* If no parameter is provide, or isn't a value in
* ThemeTypes, then it uses the default theme.
*/
const useThemeQueryParameter = () => {
const theme = useTheme();
const parsedTheme = (() => {
const queryParams = new URLSearchParams(location.search);
const themeQueryParam = queryParams.get('theme');
if (!themeQueryParam) {
return PROTON_DEFAULT_THEME;
}
const themeAsNumber = Number(themeQueryParam) as ThemeTypes;
if (!Object.values(ThemeTypes).includes(themeAsNumber)) {
return PROTON_DEFAULT_THEME;
}
return themeAsNumber;
})();
useLayoutEffect(() => {
theme.setTheme(parsedTheme);
}, [parsedTheme]);
return parsedTheme;
};
export default useThemeQueryParameter;
| 6,923
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/BadAppVersionBanner.tsx
|
import { c } from 'ttag';
import { APPS_CONFIGURATION } from '@proton/shared/lib/constants';
import { InlineLinkButton } from '../../components';
import { useConfig } from '../../hooks';
import useApiStatus from '../../hooks/useApiStatus';
import TopBanner from './TopBanner';
const BadAppVersionBanner = () => {
const { APP_NAME } = useConfig();
const { appVersionBad } = useApiStatus();
if (!appVersionBad) {
return null;
}
const appName = APPS_CONFIGURATION[APP_NAME].name;
const reload = () => window.location.reload();
const reloadButton = (
<InlineLinkButton key="reload-button" className="color-inherit" onClick={reload}>{c('Action')
.t`Refresh the page`}</InlineLinkButton>
);
return (
<TopBanner className="bg-danger">
{c('Message display when a new app version is available')
.jt`A new version of ${appName} is available. ${reloadButton}.`}
</TopBanner>
);
};
export default BadAppVersionBanner;
| 6,924
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/DelinquentTopBanner.tsx
|
import { c } from 'ttag';
import { getInvoicesPathname } from '@proton/shared/lib/apps/helper';
import { UNPAID_STATE } from '@proton/shared/lib/constants';
import { SettingsLink } from '../../components';
import { useUser } from '../../hooks';
import TopBanner from './TopBanner';
const DelinquentTopBanner = () => {
const [user] = useUser();
if (!user.Delinquent) {
return null;
}
const payInvoiceLink = (
<SettingsLink key="pay-invoices" className="color-inherit" path={getInvoicesPathname()}>{c('Link')
.t`Pay invoice`}</SettingsLink>
);
if (user.canPay) {
if (user.Delinquent === UNPAID_STATE.DELINQUENT) {
return (
<TopBanner className="bg-danger" data-testid="unpaid-state">
{c('Info')
.jt`Your account has at least one overdue invoice. Your account is restricted. Continued non-payment will block your emails and sharing links. ${payInvoiceLink}`}
</TopBanner>
);
}
if (user.Delinquent === UNPAID_STATE.NO_RECEIVE) {
return (
<TopBanner className="bg-danger" data-testid="pay-invoice-alert">
{c('Info')
.jt`Your account has at least one overdue invoice. Your account is restricted, and all services are now blocked until payment. ${payInvoiceLink}`}
</TopBanner>
);
}
return (
<TopBanner className="bg-danger" data-testid="restricted-state">
{c('Info')
.jt`Your account has at least one overdue invoice. Your access will soon get restricted. ${payInvoiceLink}`}
</TopBanner>
);
}
if (user.isMember) {
return (
<TopBanner className="bg-danger">
{c('Info').t`Account access restricted due to unpaid invoices. Please contact your administrator.`}
</TopBanner>
);
}
return null;
};
export default DelinquentTopBanner;
| 6,925
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/DesktopNotificationTopBanner.tsx
|
import { useLayoutEffect, useRef, useState } from 'react';
import { c } from 'ttag';
import { getAppName } from '@proton/shared/lib/apps/helper';
import { APPS, APP_NAMES } from '@proton/shared/lib/constants';
import { isMobile } from '@proton/shared/lib/helpers/browser';
import { Status, getStatus, request } from '@proton/shared/lib/helpers/desktopNotification';
import { UserSettings } from '@proton/shared/lib/interfaces';
import { useConfig, useLocalState, useUserSettings } from '../../hooks';
import TopBanner from './TopBanner';
const DesktopNotificationTopBanner = () => {
const [status, setStatus] = useState<Status>(getStatus());
const [dontAsk, setDontAsk] = useLocalState(false, 'dont-ask-desktop-notification');
const { APP_NAME } = useConfig();
const onMobile = useRef(isMobile());
const [userSettings] = useUserSettings();
const initialUserSettings = useRef<UserSettings>();
const { AppWelcome = {} } = initialUserSettings.current || {};
const { Calendar = [], Mail = [] } = AppWelcome;
// We don't want to display this banner to a new user on the first use, we are waiting for a refresh to do it
const hasSeenAppBefore =
APP_NAME === APPS.PROTONMAIL ? !!Mail.length : APP_NAME === APPS.PROTONCALENDAR ? !!Calendar.length : false;
const canShowBanner = !!initialUserSettings && hasSeenAppBefore;
useLayoutEffect(() => {
if (!initialUserSettings.current && userSettings) {
initialUserSettings.current = userSettings;
}
}, [userSettings]);
if (onMobile.current) {
// NOTE: we could support mobile notification but this require to run a service worker
return null;
}
const appName = getAppName(APP_NAME);
if (!([APPS.PROTONMAIL, APPS.PROTONCALENDAR] as APP_NAMES[]).includes(APP_NAME)) {
return null;
}
if (dontAsk) {
return null;
}
if ([Status.GRANTED, Status.DENIED].includes(status)) {
return null;
}
if (!canShowBanner) {
return null;
}
const handleEnable = () => {
request(
() => setStatus(getStatus()),
() => setStatus(getStatus())
);
};
const enableDesktopNotifications = (
<button
key="enable-desktop-notifications"
className="link align-baseline text-left"
type="button"
onClick={handleEnable}
>
{c('Action').t`enable desktop notifications`}
</button>
);
return (
<TopBanner onClose={() => setDontAsk(true)} className="bg-info">{c('Info')
.jt`${appName} needs your permission to ${enableDesktopNotifications}.`}</TopBanner>
);
};
export default DesktopNotificationTopBanner;
| 6,926
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/OnlineTopBanner.tsx
|
import { useEffect, useRef, useState } from 'react';
import { c } from 'ttag';
import { ping } from '@proton/shared/lib/api/tests';
import { isElectronApp } from '@proton/shared/lib/helpers/desktop';
import clsx from '@proton/utils/clsx';
import noop from '@proton/utils/noop';
import { useDebounceInput } from '../../components';
import { useOnline } from '../../hooks';
import useApi from '../../hooks/useApi';
import useApiStatus from '../../hooks/useApiStatus';
import TopBanner from './TopBanner';
import UnreachableTopBanner from './UnreachableTopBanner';
const OFFLINE_TIMEOUT = 5000;
const OnlineTopBanner = () => {
const { apiUnreachable, offline } = useApiStatus();
const onlineStatus = useOnline();
const safeOnlineStatusValue = onlineStatus && !offline;
const safeOnlineStatus = useDebounceInput(safeOnlineStatusValue, safeOnlineStatusValue ? 0 : OFFLINE_TIMEOUT);
const api = useApi();
const isElectron = isElectronApp();
const oldRef = useRef(safeOnlineStatus);
const [backOnline, setBackOnline] = useState(false);
useEffect(() => {
if (oldRef.current === safeOnlineStatus) {
return;
}
oldRef.current = safeOnlineStatus;
const handlePing = () => {
// Ping can only be used to resolve if the client can establish a connection to the API.
api(ping()).catch(noop);
};
if (!safeOnlineStatus) {
const handle = window.setInterval(() => {
handlePing();
}, 5000);
return () => window.clearInterval(handle);
}
setBackOnline(true);
const handle = window.setTimeout(() => {
setBackOnline(false);
// Ensure it's true
handlePing();
}, 2000);
return () => window.clearTimeout(handle);
}, [safeOnlineStatus]);
if (safeOnlineStatus && backOnline) {
return <TopBanner className="bg-success">{c('Info').t`Internet connection restored.`}</TopBanner>;
}
if (safeOnlineStatus) {
// If the device is known to be online, and the API is unreachable
if (apiUnreachable) {
return <UnreachableTopBanner errorMessage={apiUnreachable} />;
}
return null;
}
// If the device is known to be offline, the API unreachable is not displayed.
return (
<TopBanner className={clsx(isElectron ? 'bg-info' : 'bg-danger')}>{c('Info')
.t`Internet connection lost. Please check your device's connectivity.`}</TopBanner>
);
};
export default OnlineTopBanner;
| 6,927
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/PendingInvitationTopBanner.tsx
|
import { useEffect } from 'react';
import { c } from 'ttag';
import { useModalState, useSettingsLink } from '@proton/components/components';
import usePendingUserInvitations from '@proton/components/hooks/usePendingUserInvitations';
import useUid from '@proton/components/hooks/useUid';
import { APPS, APP_NAMES, BRAND_NAME } from '@proton/shared/lib/constants';
import { UserInvitationModel } from '@proton/shared/lib/models';
import { useCache, useConfig, useOrganization } from '../../hooks';
import PendingInvitationModal from '../payments/subscription/PendingInvitationModal';
import TopBanner from './TopBanner';
const PendingInvitationTopBanner = () => {
const cache = useCache();
const protonConfig = useConfig();
const [invites = []] = usePendingUserInvitations();
const [organization] = useOrganization();
const goToSettings = useSettingsLink();
const [modalProps, setModal, render] = useModalState();
const uid = useUid('pending-invitation-top-banner');
const inviteLengths = invites.length;
useEffect(() => {
// Force refresh the invitations when the organization changes since this could cause errors in the invitations
if (cache.get(UserInvitationModel.key) && organization) {
cache.delete(UserInvitationModel.key);
}
}, [organization]);
const allowedApps: APP_NAMES[] = [APPS.PROTONACCOUNT, APPS.PROTONCALENDAR, APPS.PROTONMAIL, APPS.PROTONDRIVE];
if (!allowedApps.includes(protonConfig.APP_NAME)) {
return null;
}
if (inviteLengths === 0) {
return null;
}
const handleTopBannerClick = () => {
if (inviteLengths === 1) {
setModal(true);
return;
}
goToSettings('/dashboard', APPS.PROTONACCOUNT);
};
const viewInviteButton = (
<button
key="view-invitation"
className="link align-baseline text-left"
type="button"
onClick={handleTopBannerClick}
>
{inviteLengths === 1
? c('familyOffer_2023:Action').t`View the invitation`
: c('familyOffer_2023:Action').t`View the invitations`}
</button>
);
const bannerOrganization =
inviteLengths === 1 ? invites[0].OrganizationName : c('familyOffer_2023:Family plan').t`${BRAND_NAME} groups`;
return (
<>
{/* translator: The text will display "You have been invited to join" then either the org name if one invite or "Family plan" if multiple invites. Finally, a button will open the modal of one invite or redirect to the dashboard if several, the buttons say "View the invitation" with invitations if multiple invites */}
<TopBanner className="bg-info">{c('familyOffer_2023:Family plan')
.jt`You have been invited to join ${bannerOrganization}. ${viewInviteButton}`}</TopBanner>
{render && <PendingInvitationModal invite={invites[0]} {...modalProps} key={uid} />}
</>
);
};
export default PendingInvitationTopBanner;
| 6,928
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/PublicTopBanners.tsx
|
import { ReactNode } from 'react';
import BadAppVersionBanner from './BadAppVersionBanner';
import OnlineTopBanner from './OnlineTopBanner';
import TorWarningBanner from './TorWarningBanner';
interface Props {
children?: ReactNode;
}
const PublicTopBanners = ({ children }: Props) => {
return (
<>
<TorWarningBanner />
<OnlineTopBanner />
<BadAppVersionBanner />
{children}
</>
);
};
export default PublicTopBanners;
| 6,929
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/ReferralTopBanner.tsx
|
import { format, fromUnixTime } from 'date-fns';
import { c } from 'ttag';
import { APPS, MAIL_APP_NAME, OPEN_OFFER_MODAL_EVENT } from '@proton/shared/lib/constants';
import { isTrial, isTrialExpired, willTrialExpire } from '@proton/shared/lib/helpers/subscription';
import { dateLocale } from '@proton/shared/lib/i18n';
import { InlineLinkButton } from '../../components';
import { useConfig, useSubscription } from '../../hooks';
import TopBanner from './TopBanner';
const ReferralTopBanner = () => {
const [subscription, loadingSubscription] = useSubscription();
const protonConfig = useConfig();
const isVpn = protonConfig.APP_NAME === APPS.PROTONVPN_SETTINGS;
const trial = isTrial(subscription);
const { PeriodEnd = 0 } = subscription || {};
const willExpire = willTrialExpire(subscription);
const isExpired = isTrialExpired(subscription);
const textAction = c('Button').t`Continue using ${MAIL_APP_NAME}.`;
const handleClick = () => document.dispatchEvent(new CustomEvent(OPEN_OFFER_MODAL_EVENT));
const action = (
<InlineLinkButton key="continue" className="color-inherit" onClick={handleClick}>
{textAction}
</InlineLinkButton>
);
const textDate = format(fromUnixTime(PeriodEnd), 'PPP', { locale: dateLocale });
if (loadingSubscription || !trial || isVpn) {
return null;
}
// 1 week before the trial ends
if (willExpire) {
const message = c('Warning').jt`Your free trial ends on ${textDate}. ${action}`;
return <TopBanner className="bg-warning">{message}</TopBanner>;
}
// Trial has ended
if (isExpired) {
const message = c('Message')
.jt`Your free trial has ended. Access to your account will soon be disabled. ${action}`;
return <TopBanner className="bg-danger">{message}</TopBanner>;
}
// In trial
return null;
};
export default ReferralTopBanner;
| 6,930
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/SessionRecoveryBanners.tsx
|
import { c, msgid } from 'ttag';
import { APPS } from '@proton/shared/lib/constants';
import { InlineLinkButton, SettingsLink, useModalState } from '../../components';
import {
useConfig,
useIsSessionRecoveryInitiatedByCurrentSession,
useSessionRecoveryGracePeriodHoursRemaining,
useSessionRecoveryInsecureTimeRemaining,
useShouldNotifyPasswordResetAvailable,
useShouldNotifySessionRecoveryCancelled,
useShouldNotifySessionRecoveryInProgress,
useUser,
} from '../../hooks';
import { SessionRecoveryInProgressModal } from '../account';
import PasswordResetAvailableAccountModal from '../account/sessionRecovery/PasswordResetAvailableAccountModal';
import { useSessionRecoveryLocalStorage } from '../account/sessionRecovery/SessionRecoveryLocalStorageManager';
import TopBanner from './TopBanner';
const SessionRecoveryInProgressBanner = () => {
const hoursRemaining = useSessionRecoveryGracePeriodHoursRemaining();
const [user] = useUser();
const [
sessionRecoveryInProgressModal,
setSessionRecoveryInProgressModalOpen,
renderSessionRecoveryInProgressModal,
] = useModalState();
if (hoursRemaining === null) {
return null;
}
const readMore = (
<InlineLinkButton key="read-more" onClick={() => setSessionRecoveryInProgressModalOpen(true)}>
{c('session_recovery:in_progress:action').t`Learn more`}
</InlineLinkButton>
);
return (
<>
{renderSessionRecoveryInProgressModal && (
<SessionRecoveryInProgressModal {...sessionRecoveryInProgressModal} />
)}
<TopBanner className="bg-warning">
{
// translator: Full sentence "Password reset requested (user@email.com). You can change your password in 72 hours."
c('session_recovery:in_progress:info').ngettext(
msgid`Password reset requested (${user.Email}). You can change your password in ${hoursRemaining} hour.`,
`Password reset requested (${user.Email}). You can change your password in ${hoursRemaining} hours.`,
hoursRemaining
)
}{' '}
{readMore}
</TopBanner>
</>
);
};
const PasswordResetAvailableBanner = () => {
const timeRemaining = useSessionRecoveryInsecureTimeRemaining();
const isSessionRecoveryInitiatedByCurrentSession = useIsSessionRecoveryInitiatedByCurrentSession();
const [user] = useUser();
const { APP_NAME } = useConfig();
const [
passwordResetAvailableAccountModal,
setPasswordResetAvailableAccountModalOpen,
renderPasswordResetAvailableAccountModal,
] = useModalState();
if (timeRemaining === null) {
return null;
}
const cta =
APP_NAME === APPS.PROTONACCOUNT ? (
<InlineLinkButton key="reset-password" onClick={() => setPasswordResetAvailableAccountModalOpen(true)}>
{isSessionRecoveryInitiatedByCurrentSession
? c('session_recovery:available:action').t`Reset password`
: c('Action').t`See how`}
</InlineLinkButton>
) : (
<SettingsLink
key="reset-password"
path="/account-password?action=session-recovery-password-reset-available"
>
{c('session_recovery:available:link').t`See how`}
</SettingsLink>
);
const message =
timeRemaining.inDays === 0
? // translator: Full sentence "Password reset request approved (user@email.com). You have N hours to reset your password."
c('session_recovery:available:info').ngettext(
msgid`Password reset request approved (${user.Email}). You have ${timeRemaining.inHours} hour to reset your password.`,
`Password reset request approved (${user.Email}). You have ${timeRemaining.inHours} hours to reset your password.`,
timeRemaining.inHours
)
: // translator: Full sentence "Password reset request approved (user@email.com). You have N days to reset your password."
c('session_recovery:available:info').ngettext(
msgid`Password reset request approved (${user.Email}). You have ${timeRemaining.inDays} day to reset your password.`,
`Password reset request approved (${user.Email}). You have ${timeRemaining.inDays} days to reset your password.`,
timeRemaining.inDays
);
return (
<>
{renderPasswordResetAvailableAccountModal && (
<PasswordResetAvailableAccountModal {...passwordResetAvailableAccountModal} />
)}
<TopBanner className="bg-success">
{message} {cta}
</TopBanner>
</>
);
};
const SessionRecoveryCancelledBanner = () => {
const [user] = useUser();
const { dismissSessionRecoveryCancelled } = useSessionRecoveryLocalStorage();
const changePasswordLink = (
<SettingsLink key="change-password-link" path="/account-password?action=change-password">
{
// translator: Full sentence "Password reset request cancelled (user@email.com). If you didn’t make this request, change your password now."
c('session_recovery:cancelled:link').t`change your password now`
}
</SettingsLink>
);
return (
<>
<TopBanner
className="bg-danger"
onClose={() => {
dismissSessionRecoveryCancelled();
}}
>
{
// translator: Full sentence "Password reset request cancelled (user@email.com). If you didn’t make this request, change your password now."
c('session_recovery:cancelled:info')
.jt`Password reset request cancelled (${user.Email}). If you didn’t make this request, ${changePasswordLink}.`
}
</TopBanner>
</>
);
};
const SessionRecoveryBanners = () => {
const shouldNotifyPasswordResetAvailable = useShouldNotifyPasswordResetAvailable();
const shouldNotifySessionRecoveryInProgress = useShouldNotifySessionRecoveryInProgress();
const shouldNotifySessionRecoveryCancelled = useShouldNotifySessionRecoveryCancelled();
return (
<>
{shouldNotifySessionRecoveryInProgress && <SessionRecoveryInProgressBanner />}
{shouldNotifyPasswordResetAvailable && <PasswordResetAvailableBanner />}
{shouldNotifySessionRecoveryCancelled && <SessionRecoveryCancelledBanner />}
</>
);
};
export default SessionRecoveryBanners;
| 6,931
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/StorageLimitTopBanner.tsx
|
import { useEffect, useState } from 'react';
import { c } from 'ttag';
import { APP_NAMES, SHARED_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants';
import { getItem, setItem } from '@proton/shared/lib/helpers/storage';
import { addUpsellPath, getUpsellRefFromApp } from '@proton/shared/lib/helpers/upsell';
import { SettingsLink } from '../../components';
import { useConfig, useUser } from '../../hooks';
import TopBanner from './TopBanner';
const IGNORE_STORAGE_LIMIT_KEY = 'ignore-storage-limit';
interface Props {
app?: APP_NAMES;
}
const StorageLimitTopBanner = ({ app }: Props) => {
const [user] = useUser();
const { APP_NAME } = useConfig();
const spacePercentage = (user.UsedSpace * 100) / user.MaxSpace;
const spaceDisplayed = Number.isNaN(spacePercentage) ? 0 : Math.floor(spacePercentage);
const [ignoreStorageLimit, setIgnoreStorageLimit] = useState(
getItem(`${IGNORE_STORAGE_LIMIT_KEY}${user.ID}`) === 'true'
);
const upsellRef = getUpsellRefFromApp({
app: APP_NAME,
feature: SHARED_UPSELL_PATHS.STORAGE_PERCENTAGE,
component: UPSELL_COMPONENT.MODAL,
fromApp: app,
});
useEffect(() => {
if (ignoreStorageLimit) {
setItem(`${IGNORE_STORAGE_LIMIT_KEY}${user.ID}`, 'true');
}
}, [ignoreStorageLimit]);
const upgradeLink = user.canPay ? (
<SettingsLink key="storage-link" className="color-inherit" path={addUpsellPath('/upgrade', upsellRef)}>
{c('Link').t`Upgrade account`}
</SettingsLink>
) : (
''
);
const freeUpMessage = user.canPay
? c('Info').t`Free up some space or add more storage space.`
: c('Info').t`Free up some space or contact your administrator.`;
if (spacePercentage >= 100) {
return (
<TopBanner className="bg-danger">{c('Info')
.jt`You reached 100% of your storage capacity. You cannot send or receive new emails. ${freeUpMessage} ${upgradeLink}`}</TopBanner>
);
}
if (!ignoreStorageLimit && spacePercentage >= 80 && spacePercentage < 100) {
return (
<TopBanner className="bg-warning" onClose={() => setIgnoreStorageLimit(true)}>{c('Info')
.jt`You reached ${spaceDisplayed}% of your storage capacity. ${freeUpMessage} ${upgradeLink}`}</TopBanner>
);
}
return null;
};
export default StorageLimitTopBanner;
| 6,932
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/SubUserTopBanner.tsx
|
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import { useUser } from '../../hooks';
import TopBanner from './TopBanner';
const SubUserTopBanner = () => {
const [user] = useUser();
if (!user.isSubUser) {
return null;
}
return (
<TopBanner className="bg-info">
{c('Info').t`You are currently signed in as ${user.Name} (${user.Email}).`}
{` `}
<Href href={getKnowledgeBaseUrl('/manage-public-users-organization')}>{c('Link').t`Learn more`}</Href>
</TopBanner>
);
};
export default SubUserTopBanner;
| 6,933
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/SubscriptionEndsBanner.tsx
|
import { c } from 'ttag';
import { APPS, APP_NAMES } from '@proton/shared/lib/constants';
import { SettingsLink, Time } from '../../components';
import { useConfig, useSubscription } from '../../hooks';
import { subscriptionExpires } from '../payments/subscription/helpers';
import TopBanner from './TopBanner';
const SubscriptionEndsBanner = () => {
const { APP_NAME } = useConfig();
const [subscription] = useSubscription();
const { subscriptionExpiresSoon, planName, expirationDate } = subscriptionExpires(subscription);
if (!([APPS.PROTONACCOUNT, APPS.PROTONVPN_SETTINGS] as APP_NAMES[]).includes(APP_NAME)) {
return null;
}
if (!subscriptionExpiresSoon || !subscription) {
return null;
}
const byDate = (
<Time format="PP" key="subscription-end">
{expirationDate}
</Time>
);
const reactivateLink = (
<SettingsLink
data-testid="reactivate-link"
key="reactivate-subscription"
className="color-inherit"
path="/dashboard#your-subscriptions"
>{c('Link').t`Reactivate now`}</SettingsLink>
);
return (
<TopBanner className="bg-danger">
{c('Info')
.jt`Subscription ending: Reactivate by ${byDate} to keep your ${planName} benefits. ${reactivateLink}`}
</TopBanner>
);
};
export default SubscriptionEndsBanner;
| 6,934
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/TimeOutOfSyncTopBanner.tsx
|
import { useEffect, useRef, useState } from 'react';
import { c } from 'ttag';
import { HOUR } from '@proton/shared/lib/constants';
import { captureMessage } from '@proton/shared/lib/helpers/sentry';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import LearnMore from '../../components/link/LearnMore';
import useApiServerTime from '../../hooks/useApiServerTime';
import TopBanner from './TopBanner';
const isOutOfSync = (serverTime: Date) => {
const timeDifference = Math.abs(serverTime.getTime() - Date.now());
// We should allow at least a 14-hour time difference,
// because of potential internal clock issues when using dual-boot with Windows and a different OS
return timeDifference > 24 * HOUR;
};
const TimeOutOfSyncTopBanner = () => {
const [ignore, setIgnore] = useState(false);
const serverTime = useApiServerTime();
// We warn the user if the server time is too far off from local time.
// We do not want the server to set arbitrary times (either past or future), to avoid signature replay issues and more.
const showWarning = !ignore && serverTime && isOutOfSync(serverTime);
// Log warning to have an idea of how many clients might be affected
const onceRef = useRef(false);
useEffect(() => {
if (!showWarning || onceRef.current) {
return;
}
onceRef.current = true;
captureMessage('Client time difference larger than 24 hours', {
level: 'info',
extra: {
serverTime: serverTime?.toString(),
localTime: new Date().toString(),
},
});
}, [showWarning]);
if (!showWarning) {
return null;
}
const learnMore = <LearnMore url={getKnowledgeBaseUrl('/device-time-warning')} />;
return (
<TopBanner onClose={() => setIgnore(true)} className="bg-warning">
{c('Warning').jt`The date and time settings on your device are out of sync. ${learnMore}`}
</TopBanner>
);
};
export default TimeOutOfSyncTopBanner;
| 6,935
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/TopBanner.tsx
|
import { ReactNode } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { isElectronOnMac } from '@proton/shared/lib/helpers/desktop';
import clsx from '@proton/utils/clsx';
import Icon from '../../components/icon/Icon';
interface Props {
children: ReactNode;
className?: string;
onClose?: () => void;
'data-testid'?: string;
}
const TopBanner = ({ children, className, onClose, ...rest }: Props) => {
const isElectronOnMacComputers = isElectronOnMac();
return (
<div
role="alert"
className={clsx([
'flex flex-item-noshrink flex-nowrap text-center relative text-bold no-print',
className,
isElectronOnMacComputers && 'pt-4',
])}
{...rest}
>
<div className="flex-item-fluid p-2">{children}</div>
{onClose ? (
<Button
icon
shape="ghost"
className="flex-item-noshrink rounded-none"
onClick={onClose}
title={c('Action').t`Close this banner`}
>
<Icon name="cross" alt={c('Action').t`Close this banner`} />
</Button>
) : null}
</div>
);
};
export default TopBanner;
| 6,936
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/TopBanners.tsx
|
import { ReactNode } from 'react';
import { APP_NAMES } from '@proton/shared/lib/constants';
import BadAppVersionBanner from './BadAppVersionBanner';
import DelinquentTopBanner from './DelinquentTopBanner';
import DesktopNotificationTopBanner from './DesktopNotificationTopBanner';
import OnlineTopBanner from './OnlineTopBanner';
import PendingInvitationTopBanner from './PendingInvitationTopBanner';
import ReferralTopBanner from './ReferralTopBanner';
import SessionRecoveryBanners from './SessionRecoveryBanners';
import StorageLimitTopBanner from './StorageLimitTopBanner';
import SubUserTopBanner from './SubUserTopBanner';
import SubscriptionEndsBanner from './SubscriptionEndsBanner';
import TimeOutOfSyncTopBanner from './TimeOutOfSyncTopBanner';
interface Props {
app?: APP_NAMES;
children?: ReactNode;
}
const TopBanners = ({ children, app }: Props) => {
return (
<>
<DelinquentTopBanner />
<OnlineTopBanner />
<TimeOutOfSyncTopBanner />
<StorageLimitTopBanner app={app} />
<BadAppVersionBanner />
<SubUserTopBanner />
<DesktopNotificationTopBanner />
<ReferralTopBanner />
<PendingInvitationTopBanner />
<SubscriptionEndsBanner />
<SessionRecoveryBanners />
{children}
</>
);
};
export default TopBanners;
| 6,937
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/TorWarningBanner.tsx
|
import { useEffect, useState } from 'react';
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { isMaybeTorLessThan11 } from '@proton/shared/lib/helpers/browser';
import TopBanner from './TopBanner';
const TorWarningBanner = () => {
const [show, setShow] = useState(false);
useEffect(() => {
try {
setShow(isMaybeTorLessThan11());
} catch (e) {
// Ignore
}
}, []);
if (!show) {
return null;
}
const stableRelease = (
<Href key="link" href="https://www.torproject.org/download/">{c('Tor out of date').t`stable release`}</Href>
);
return (
<TopBanner className="bg-danger">
{
// translator: followed by a link "stable release"
c('Tor out of date')
.jt`This version of Tor Browser is not supported. Please update to the latest ${stableRelease}`
}
</TopBanner>
);
};
export default TorWarningBanner;
| 6,938
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/UnreachableTopBanner.tsx
|
import { c } from 'ttag';
import { Href } from '@proton/atoms/Href';
import { PROTON_WEBSITES } from '@proton/shared/lib/constants';
import TopBanner from './TopBanner';
interface Props {
errorMessage: string;
}
const UnreachableTopBanner = ({ errorMessage }: Props) => {
// translator: At the end of a longer sentence "Servers are unreachable. Please try again in a few minutes. You can also check our status page"
const statusPageLink = (
<Href href={PROTON_WEBSITES.PROTON_STATUS_PAGE} target="_blank">{c('Error').t`status page`}</Href>
);
// translator: full sentence "Servers are unreachable. Please try again in a few minutes. You can also check our status page"
const errorMessageWithStatusPage = c('Error').jt`${errorMessage}. You can also check our ${statusPageLink}`;
return <TopBanner className="bg-danger">{errorMessageWithStatusPage}</TopBanner>;
};
export default UnreachableTopBanner;
| 6,939
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/topBanners/index.ts
|
export { default as DelinquentTopBanner } from './DelinquentTopBanner';
export { default as BadAppVersionBanner } from './BadAppVersionBanner';
export { default as OnlineTopBanner } from './OnlineTopBanner';
export { default as PublicTopBanners } from './PublicTopBanners';
export { default as StorageLimitTopBanner } from './StorageLimitTopBanner';
export { default as SubUserTopBanner } from './SubUserTopBanner';
export { default as TimeOutOfSyncTopBanner } from './TimeOutOfSyncTopBanner';
export { default as TopBanners } from './TopBanners';
export { default as TopBanner } from './TopBanner';
| 6,940
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/unleash/UnleashContext.ts
|
/**
* Feature flag list from Unleash
* Format should be FeatureFlagName = 'FeatureFlagName'
*/
enum MailFeatureFlag {
AttachmentThumbnails = 'AttachmentThumbnails',
WebMailPageSizeSetting = 'WebMailPageSizeSetting',
EmailForwarding = 'EmailForwarding',
SnoozeFeature = 'SnoozeFeature',
}
enum CommonFeatureFlag {
DisableElectronMail = 'DisableElectronMail',
SignedInAccountRecovery = 'SignedInAccountRecovery',
}
enum AccountFlag {
MaintenanceImporter = 'MaintenanceImporter',
BF2023IsExpired = 'BF2023IsExpired',
BF2023OfferCheck = 'BF2023OfferCheck',
SentinelPassPlus = 'SentinelPassPlus',
}
enum DriveFeatureFlag {
DrivePhotos = 'DrivePhotos',
DrivePhotosUploadDisabled = 'DrivePhotosUploadDisabled',
}
export type FeatureFlag = `${MailFeatureFlag}` | `${AccountFlag}` | `${DriveFeatureFlag}` | `${CommonFeatureFlag}`;
| 6,941
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/unleash/UnleashFlagProvider.tsx
|
import { ReactNode } from 'react';
import FlagProvider from '@protontech/proxy-client-react';
import { IConfig } from 'unleash-proxy-client';
import { Api } from '@proton/shared/lib/interfaces';
import useApi from '../../hooks/useApi';
// Just something dummy to have a valid domain because the library does new URL
const prefix = 'https://proton.me/';
const url = new URL(prefix);
const customFetch =
(api: Api): typeof window.fetch =>
(url, config) => {
if (typeof url === 'string') {
return api({
url: `feature/v2/frontend${url.replace(prefix, '')}`,
headers: config?.headers,
silence: true,
output: 'raw',
});
}
throw new Error('not supported');
};
interface Props {
children: ReactNode;
}
const UnleashFlagProvider = ({ children }: Props) => {
const api = useApi();
const unleashConfig: IConfig = {
url,
clientKey: '-', // set by the server
appName: '-', // set by the server
refreshInterval: 600, // refreshInterval in seconds, 10 mins
disableMetrics: true,
fetch: customFetch(api),
};
return <FlagProvider config={unleashConfig}>{children}</FlagProvider>;
};
export default UnleashFlagProvider;
| 6,942
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/unleash/index.ts
|
export * from './UnleashContext';
export { default as UnleashFlagProvider } from './UnleashFlagProvider';
export { default as useFlagsReady } from './useFlagsReady';
export { default as useFlag } from './useFlag';
| 6,943
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/unleash/useFlag.ts
|
import { useFlag as useUnleashFlag } from '@protontech/proxy-client-react';
import { FeatureFlag } from './UnleashContext';
const useFlag: (name: FeatureFlag) => boolean = useUnleashFlag;
export default useFlag;
| 6,944
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/unleash/useFlagsReady.ts
|
import { useEffect } from 'react';
import { useUnleashClient } from '@protontech/proxy-client-react';
import { createPromise } from '@proton/shared/lib/helpers/promise';
type SimpleFunc = () => void;
const readyCallbackSet: Set<SimpleFunc> = new Set();
const errorCallbackSet: Set<SimpleFunc> = new Set();
// Memoize initial states to keep value consistency between hook instances
let readyInitialState = false;
let readyPromise = createPromise<void>();
/**
* useFlagsReady
*
* @description
* This hooks is a custom override of `useFlagsStatus` function from unleash React SDK.
* Unleash React client `useFlagsStatus` hook: https://github.com/Unleash/proxy-client-react/blob/main/src/useFlagsStatus.ts
* Unleash React client context Provider: https://github.com/Unleash/proxy-client-react/blob/main/src/FlagProvider.tsx
*
* It returns `flagsReady` and `flagsError` based on the `ready` and `error` Unleash JS client event emitter.
* JS client: https://github.com/Unleash/unleash-proxy-client-js/blob/main/src/index.ts#L61
*
* Error event has an issue in the react client so in the meantime this stands as our own hotfix
* https://github.com/Unleash/proxy-client-react/pull/127
*
* @returns {boolean}
*/
const useFlagsReady = () => {
const client = useUnleashClient();
useEffect(() => {
const readyListener = () => {
readyCallbackSet.forEach((callback) => callback());
};
const readyCallback: SimpleFunc = () => {
if (readyInitialState === false) {
readyPromise.resolve();
readyInitialState = true;
}
};
const errorListener = () => {
errorCallbackSet.forEach((callback) => callback());
};
if (readyCallbackSet.size === 0) {
client.on('ready', readyListener);
client.on('error', errorListener);
}
readyCallbackSet.add(readyCallback);
errorCallbackSet.add(readyCallback);
return () => {
readyCallbackSet.delete(readyCallback);
errorCallbackSet.delete(readyCallback);
if (readyCallbackSet.size === 0) {
client.off('ready', readyListener);
client.off('error', errorListener);
}
};
}, []);
return readyPromise.promise;
};
export default useFlagsReady;
| 6,945
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/verification/EmbeddedVerification.tsx
|
import { useEffect, useMemo, useRef, useState } from 'react';
import { APPS } from '@proton/shared/lib/constants';
import { getAppUrlFromApiUrl, getAppUrlRelativeToOrigin, stringifySearchParams } from '@proton/shared/lib/helpers/url';
import { localeCode } from '@proton/shared/lib/i18n';
import { HumanVerificationMethodType } from '@proton/shared/lib/interfaces';
import { useConfig, useNotifications } from '../../hooks';
interface EmbeddedVerificationProps {
token: string;
methods: HumanVerificationMethodType[];
defaultCountry?: string;
defaultEmail?: string;
defaultPhone?: string;
onSuccess: (token: string, tokenType: HumanVerificationMethodType) => void;
}
const EmbeddedVerification = ({
token,
methods,
onSuccess,
defaultCountry,
defaultEmail,
defaultPhone,
}: EmbeddedVerificationProps) => {
const iframeRef = useRef<HTMLIFrameElement>(null);
const [iframeHeight, setIframeHeight] = useState<number | undefined>();
const { API_URL } = useConfig();
const { createNotification } = useNotifications();
const embedUrl = useMemo(() => {
if (window.location.origin.includes('localhost')) {
return getAppUrlFromApiUrl(API_URL, APPS.PROTONVERIFICATION);
}
return getAppUrlRelativeToOrigin(window.location.origin, APPS.PROTONVERIFICATION);
}, []);
useEffect(() => {
const handleMessage = (e: MessageEvent) => {
const { origin, data, source } = e;
const contentWindow = iframeRef.current?.contentWindow;
if (!contentWindow || origin !== embedUrl.origin || !data || source !== contentWindow) {
return;
}
const { type, payload } = JSON.parse(e.data);
switch (type) {
case 'RESIZE': {
const { height } = payload;
setIframeHeight(height);
break;
}
case 'NOTIFICATION': {
createNotification(payload);
break;
}
case 'HUMAN_VERIFICATION_SUCCESS': {
const { token, type } = payload;
onSuccess(token, type);
break;
}
default:
}
};
window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
}, [onSuccess]);
const params = {
methods,
token,
defaultCountry: defaultCountry || undefined,
defaultEmail: defaultEmail || undefined,
defaultPhone: defaultPhone || undefined,
locale: localeCode,
};
const src = `${embedUrl.toString()}?${stringifySearchParams(params)}`;
return (
<iframe
style={{ height: `${iframeHeight}px`, width: '100%' }}
src={src}
ref={iframeRef}
title="verification-iframe"
sandbox="allow-scripts allow-same-origin allow-popups"
/>
);
};
export default EmbeddedVerification;
| 6,946
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/verification/index.ts
|
export { default as EmbeddedVerification } from './EmbeddedVerification';
| 6,947
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/Certificate.ts
|
export interface Certificate {
id: string;
name?: string | null | undefined;
serialNumber?: string;
privateKey?: string;
publicKey: string;
publicKeyFingerprint: string;
expirationTime: number;
config?: string;
features?: Record<string, string | number | boolean | null>;
}
| 6,948
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/Logical.ts
|
import { Server } from './Server';
export interface Logical {
ID: string;
City?: string | null;
DisplayTier: number;
Domain: string;
EntryCountry: string;
ExitCountry: string;
HostCountry: string;
Features: number; // bitmap
Location: { Lat: number; Long: number };
Name: string;
Region?: string | null;
ServerIDs?: number[];
UserIDs?: (string | number)[];
Servers?: Server[];
Tier: number;
Visible: boolean | number;
Score: number;
Load?: number;
}
| 6,949
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/OpenVPNCredentialsSection.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { useLoading } from '@proton/hooks';
import { resetVPNSettings } from '@proton/shared/lib/api/vpn';
import { VPN_APP_NAME } from '@proton/shared/lib/constants';
import { Copy, Icon, LearnMore, PrimaryButton } from '../../components';
import { useApi, useNotifications, useUserVPN } from '../../hooks';
import { SettingsParagraph, SettingsSectionWide } from '../account';
import SettingsLayout from '../account/SettingsLayout';
import SettingsLayoutLeft from '../account/SettingsLayoutLeft';
import SettingsLayoutRight from '../account/SettingsLayoutRight';
interface Props {
app?: string;
}
const OpenVPNCredentialsSection = (props: Props) => {
const [updating, withUpdating] = useLoading();
const { result = {}, fetch: fetchUserVPN } = useUserVPN();
const { VPN = {} } = result as any;
const { Name = '', Password = '' } = VPN;
const [show, setShow] = useState(false);
const api = useApi();
const { createNotification } = useNotifications();
const { app } = props;
const handleResetCredentials = async () => {
await api(resetVPNSettings());
await fetchUserVPN();
createNotification({ text: c('Notification').t`OpenVPN / IKEv2 credentials regenerated` });
};
const learnMore = <LearnMore key="learn-more" url="https://protonvpn.com/support/vpn-login/" />;
return (
<SettingsSectionWide>
{app ? (
<>
<SettingsParagraph>
{c('Info')
.t`You can use the following credentials to connect to a ${VPN_APP_NAME} server using a third-party, open source VPN app, like Tunnelblick for macOS or OpenVPN for GNU/Linux.`}
</SettingsParagraph>
<SettingsParagraph>
{c('Info').t`Learn how to sign in to ${VPN_APP_NAME} with third-party VPN applications.`}
</SettingsParagraph>
<SettingsParagraph>
{c('Info').t`We advise you to use official ${VPN_APP_NAME} applications when possible.`}
</SettingsParagraph>
<SettingsParagraph>
{c('Info')
.jt`These credentials cannot be used to sign in to our official ${VPN_APP_NAME} apps. ${learnMore}`}
</SettingsParagraph>
</>
) : (
<>
<SettingsParagraph>
{c('Info')
.t`Use the following credentials when connecting to ${VPN_APP_NAME} servers without application. Example use cases include: Tunnelblick on macOS, OpenVPN on GNU/Linux.`}
</SettingsParagraph>
<SettingsParagraph>
{c('Info')
.jt`These credentials cannot be used to sign in to our official ${VPN_APP_NAME} apps. ${learnMore}`}
</SettingsParagraph>
</>
)}
<SettingsLayout>
<SettingsLayoutLeft>
<span className="label pt-0">{c('Label').t`OpenVPN / IKEv2 username`}</span>
</SettingsLayoutLeft>
<SettingsLayoutRight className="flex flex-align-items-center">
<div className="text-ellipsis max-w-full mr-0 md:mr-4">
<code title={Name}>{Name}</code>
</div>
<div className="flex flex-item-noshrink mt-2 md:mt-0">
<Copy value={Name} />
</div>
</SettingsLayoutRight>
</SettingsLayout>
<SettingsLayout>
<SettingsLayoutLeft>
<span className="label pt-0">{c('Label').t`OpenVPN / IKEv2 password`}</span>
</SettingsLayoutLeft>
<SettingsLayoutRight className="flex flex-align-items-center">
<div className="text-ellipsis max-w-full mr-0 md:mr-4">
<code>{show ? Password : '••••••••••••••••'}</code>
</div>
<div className="flex flex-item-noshrink mt-2 md:mt-0">
<Copy className="mr-4" value={Password} />
<Button
icon
onClick={() => setShow(!show)}
title={show ? c('Action').t`Hide` : c('Action').t`Show`}
>
<Icon name={show ? 'eye-slash' : 'eye'} />
</Button>
</div>
</SettingsLayoutRight>
</SettingsLayout>
<PrimaryButton
disabled={!Name || !Password}
loading={updating}
onClick={() => withUpdating(handleResetCredentials())}
>{c('Action').t`Reset credentials`}</PrimaryButton>
</SettingsSectionWide>
);
};
export default OpenVPNCredentialsSection;
| 6,950
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/Server.ts
|
export interface Server {
ID?: string | number;
Domain: string;
EntryIP: string;
ExitIP: string;
Label?: string | null;
MaxSpeed: number;
Generation: number;
Enabled: boolean | number;
ServicesDownPublicReason?: string | null;
ServicesDownDetailedReason?: string | null;
EndOfLife?: number | null;
X25519PublicKey?: string | null;
LoadUpdateTime?: number | null;
Bytes?: number | null;
Load?: number | null;
ServicesDown?: number | null;
}
| 6,951
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/flag.ts
|
const flags = require.context('@proton/styles/assets/img/flags', true, /.svg$/);
const flagsMap = flags.keys().reduce((acc, key) => {
acc[key] = () => flags(key);
return acc;
}, {} as Record<string, () => string>);
export const getFlagSvg = (abbreviation: string) => flagsMap[`./${abbreviation}.svg`]?.();
| 6,952
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/index.ts
|
export { default as GatewaysSection } from './gateways/GatewaysSection';
export { default as OpenVPNConfigurationSection } from './OpenVPNConfigurationSection/OpenVPNConfigurationSection';
export { default as ProtonVPNClientsSection } from './ProtonVPNClientsSection/ProtonVPNClientsSection';
export { default as OpenVPNCredentialsSection } from './OpenVPNCredentialsSection';
export { default as ProtonVPNResourcesSection } from './ProtonVPNResourcesSection/ProtonVPNResourcesSection';
export { default as ProtonVPNCredentialsSection } from './ProtonVPNCredentialsSection/ProtonVPNCredentialsSection';
export { default as WireGuardConfigurationSection } from './WireGuardConfigurationSection/WireGuardConfigurationSection';
export * from './flag';
| 6,953
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/OpenVPNConfigurationSection/CityNumber.tsx
|
import { c, msgid } from 'ttag';
import { VPNServer } from '@proton/shared/lib/interfaces/VPNServer';
import uniqueBy from '@proton/utils/uniqueBy';
interface Props {
group: VPNServer[];
}
const CityNumber = ({ group }: Props) => {
const number = uniqueBy(group, ({ City }) => City).length;
return (
<div className="inline-flex-vcenter">
{c('Info').ngettext(msgid`${number} city`, `${number} cities`, number)}
</div>
);
};
export default CityNumber;
| 6,954
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/OpenVPNConfigurationSection/ConfigsTable.js
|
import { memo } from 'react';
import PropTypes from 'prop-types';
import { c } from 'ttag';
import { ButtonLike } from '@proton/atoms';
import { Button } from '@proton/atoms';
import { getVPNServerConfig } from '@proton/shared/lib/api/vpn';
import { PLANS } from '@proton/shared/lib/constants';
import { textToClipboard } from '@proton/shared/lib/helpers/browser';
import downloadFile from '@proton/shared/lib/helpers/downloadFile';
import clsx from '@proton/utils/clsx';
import isTruthy from '@proton/utils/isTruthy';
import {
DropdownActions,
Icon,
SettingsLink,
Table,
TableBody,
TableCell,
TableRow,
Tooltip,
} from '../../../components';
import { useApi, useNotifications, useUser } from '../../../hooks';
import Country from './Country';
import LoadIndicator from './LoadIndicator';
import { isP2PEnabled, isTorEnabled } from './utils';
export const CATEGORY = {
SECURE_CORE: 'SecureCore',
COUNTRY: 'Country',
SERVER: 'Server',
FREE: 'Free',
};
const PlusBadge = () => (
<span className="ml-2">
<Tooltip title="Plus">
<div className="text-center rounded">P</div>
</Tooltip>
</span>
);
const ServerDown = () => (
<span className="ml-2">
<Tooltip title={c('Info').t`Server is currently down`}>
<div className="flex inline-flex-vcenter">
<Icon className="color-danger" size={20} name="exclamation-circle" />
</div>
</Tooltip>
</span>
);
export const P2PIcon = () => (
<span className="mx-2">
<Tooltip title={c('Info').t`P2P`}>
<Icon name="arrow-right-arrow-left" size={18} className="rounded bg-strong p-1" />
</Tooltip>
</span>
);
export const TorIcon = () => (
<span className="mx-2">
<Tooltip title={c('Info').t`Tor`}>
<Icon name="brand-tor" size={18} className="rounded bg-strong p-1" />
</Tooltip>
</span>
);
// TODO: Add icons instead of text for p2p and tor when they are ready
const ConfigsTable = ({ loading, servers = [], platform, protocol, category, onSelect, selecting }) => {
const api = useApi();
const { createNotification } = useNotifications();
const [{ hasPaidVpn }] = useUser();
const handleClickDownload =
({ ID, ExitCountry, Domain }) =>
async () => {
const buffer = await api(
getVPNServerConfig({
LogicalID: category === CATEGORY.COUNTRY ? undefined : ID,
Platform: platform,
Protocol: protocol,
Country: ExitCountry,
})
);
const blob = new Blob([buffer], { type: 'application/x-openvpn-profile' });
const [country, ...rest] = Domain.split('.');
const domain = category === CATEGORY.COUNTRY ? [country.substring(0, 2), ...rest].join('.') : Domain;
downloadFile(blob, `${domain}.${protocol}.ovpn`);
};
return (
<Table hasActions>
<thead>
<tr>
<TableCell
className={clsx(['w-auto', category === CATEGORY.SERVER ? 'md:w-1/4' : 'md:w-1/3'])}
type="header"
>
{[CATEGORY.SERVER, CATEGORY.FREE].includes(category)
? c('TableHeader').t`Name`
: c('TableHeader').t`Country`}
</TableCell>
{category === CATEGORY.SERVER ? (
<TableCell className="w-auto md:w-1/4" type="header">{c('TableHeader').t`City`}</TableCell>
) : null}
<TableCell
className={clsx(['w-auto', category === CATEGORY.SERVER ? 'md:w-1/4' : 'md:w-1/3'])}
type="header"
>{c('TableHeader').t`Status`}</TableCell>
<TableCell
className={clsx(['w-auto', category === CATEGORY.SERVER ? 'md:w-1/4' : 'md:w-1/3'])}
type="header"
>{c('TableHeader').t`Action`}</TableCell>
</tr>
</thead>
<TableBody loading={loading} colSpan={4}>
{servers.map((server) => (
<TableRow
key={server.ID}
cells={[
[CATEGORY.SERVER, CATEGORY.FREE].includes(category) ? (
server.Name
) : (
<Country key="country" server={server} />
),
category === CATEGORY.SERVER ? (
<div className="inline-flex-vcenter" key="city">
{server.City}
</div>
) : null,
<div className="inline-flex-vcenter" key="status">
<LoadIndicator server={server} />
{server.Tier === 2 && <PlusBadge />}
{server.Servers.every(({ Status }) => !Status) && <ServerDown />}
{isP2PEnabled(server.Features) && <P2PIcon />}
{isTorEnabled(server.Features) && <TorIcon />}
</div>,
server.isUpgradeRequired ? (
<Tooltip
key="download"
title={
server.Tier === 2
? c('Info').t`Plus or Visionary subscription required`
: c('Info').t`Basic, Plus or Visionary subscription required`
}
>
<ButtonLike
as={SettingsLink}
color="norm"
size="small"
path={hasPaidVpn ? `/dashboard?plan=${PLANS.VPN}` : '/upgrade'}
>{c('Action').t`Upgrade`}</ButtonLike>
</Tooltip>
) : onSelect ? (
<Button size="small" onClick={() => onSelect(server)} loading={selecting}>{c('Action')
.t`Create`}</Button>
) : (
<DropdownActions
key="dropdown"
size="small"
list={[
{
text: c('Action').t`Download`,
onClick: handleClickDownload(server),
},
category !== CATEGORY.SECURE_CORE && {
text: (
<div className="flex flex-nowrap flex-align-items-center flex-justify-space-between">
<span className="mr-2">{server.Domain}</span>
<Icon name="squares" title={c('Action').t`Copy`} />
</div>
),
onClick(event) {
textToClipboard(server.Domain, event.currentTarget);
createNotification({
text: c('Success').t`${server.Domain} copied to your clipboard`,
});
},
},
].filter(isTruthy)}
/>
),
].filter(isTruthy)}
/>
))}
</TableBody>
</Table>
);
};
ConfigsTable.propTypes = {
onSelect: PropTypes.func,
selecting: PropTypes.bool,
category: PropTypes.oneOf([CATEGORY.SECURE_CORE, CATEGORY.COUNTRY, CATEGORY.SERVER, CATEGORY.FREE]),
platform: PropTypes.string,
protocol: PropTypes.string,
loading: PropTypes.bool,
servers: PropTypes.arrayOf(
PropTypes.shape({
ID: PropTypes.string,
Country: PropTypes.string,
EntryCountry: PropTypes.string,
ExitCountry: PropTypes.string,
Domain: PropTypes.string,
Features: PropTypes.number,
Load: PropTypes.number,
Tier: PropTypes.number,
})
),
};
export default memo(ConfigsTable);
| 6,955
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/OpenVPNConfigurationSection/Country.js
|
import PropTypes from 'prop-types';
import { c } from 'ttag';
import { useUserSettings } from '@proton/components/hooks';
import { correctAbbr, getLocalizedCountryByAbbr } from '../../../helpers/countries';
import { getFlagSvg } from '../flag';
const Country = ({ server: { EntryCountry, ExitCountry } }) => {
const [userSettings] = useUserSettings();
const isRouted = EntryCountry && EntryCountry !== ExitCountry;
const correctEntryCountry = correctAbbr(EntryCountry);
const correctExitCountry = correctAbbr(ExitCountry);
const entryCountryName = getLocalizedCountryByAbbr(correctEntryCountry, userSettings.Locale || navigator.languages);
const exitCountryName = getLocalizedCountryByAbbr(correctExitCountry, userSettings.Locale || navigator.languages);
return (
<div className="inline-flex-vcenter">
<img width={20} className="mr-2 border" src={getFlagSvg(correctExitCountry)} alt={exitCountryName} />
<p className="mx-1">{exitCountryName}</p>
{isRouted && <span className="color-weak">{c('CountryInfo').t`(via ${entryCountryName})`}</span>}
</div>
);
};
Country.propTypes = {
server: PropTypes.shape({
EntryCountry: PropTypes.string,
ExitCountry: PropTypes.string,
}),
};
export default Country;
| 6,956
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/OpenVPNConfigurationSection/LoadIndicator.js
|
import PropTypes from 'prop-types';
import { c } from 'ttag';
import { CircularProgress, Tooltip } from '../../../components';
const LoadIndicator = ({ server: { Load = 0 } }) => {
// 1-49% load is GREEN color #5db039
// 50-89% load is YELLOW color #eac819
// 90-100% load is RED color #ec5858
const className = Load < 50 ? '' : Load < 90 ? 'circle-bar--medium' : 'circle-bar--full';
return (
<span className="min-w-custom hidden md:inline" style={{ '--min-w-custom': '5em' }}>
<Tooltip title={c('Info').t`Server load`}>
<div className="flex inline-flex-vcenter">
<CircularProgress progress={Load} size={22} className={className}>
<g className="circle-chart-info">
<rect x="17" y="14" width="1.55" height="9.1" className="circle-chart-percent" />
<rect x="17" y="11" width="1.55" height="1.53" className="circle-chart-percent" />
</g>
</CircularProgress>
<div className="ml-2">{Load}%</div>
</div>
</Tooltip>
</span>
);
};
LoadIndicator.propTypes = {
server: PropTypes.shape({
Load: PropTypes.number,
}),
};
export default LoadIndicator;
| 6,957
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/OpenVPNConfigurationSection/OpenVPNConfigurationSection.js
|
import { useEffect, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import { c, msgid } from 'ttag';
import { Button, ButtonLike, Href } from '@proton/atoms';
import { SettingsSectionWide } from '@proton/components/containers';
import { getVPNServerConfig } from '@proton/shared/lib/api/vpn';
import { PLANS, SORT_DIRECTION, VPN_APP_NAME, VPN_CONNECTIONS, VPN_HOSTNAME } from '@proton/shared/lib/constants';
import downloadFile from '@proton/shared/lib/helpers/downloadFile';
import groupWith from '@proton/utils/groupWith';
import { Block, Icon, Info, Radio, RadioGroup, SettingsLink, Tooltip } from '../../../components';
import { correctAbbr, getLocalizedCountryByAbbr } from '../../../helpers/countries';
import {
useApiWithoutResult,
usePlans,
useSortedList,
useUser,
useUserSettings,
useUserVPN,
useVPNLogicals,
} from '../../../hooks';
import { SettingsParagraph } from '../../account';
import ConfigsTable, { CATEGORY } from './ConfigsTable';
import ServerConfigs from './ServerConfigs';
import { isSecureCoreEnabled, isTorEnabled } from './utils';
const PLATFORM = {
MACOS: 'macOS',
LINUX: 'Linux',
WINDOWS: 'Windows',
ANDROID: 'Android',
IOS: 'iOS',
ROUTER: 'Router',
};
const PROTOCOL = {
TCP: 'tcp',
UDP: 'udp',
};
const OpenVPNConfigurationSection = ({ onSelect, selecting, listOnly = false, excludedCategories = [] }) => {
const [platform, setPlatform] = useState(PLATFORM.ANDROID);
const [protocol, setProtocol] = useState(PROTOCOL.UDP);
const { request } = useApiWithoutResult(getVPNServerConfig);
const [plans, loadingPlans] = usePlans();
const { loading, result = {}, fetch: fetchLogicals } = useVPNLogicals();
const { result: vpnResult, loading: vpnLoading, fetch: fetchUserVPN } = useUserVPN();
const [{ hasPaidVpn }] = useUser();
const [userSettings] = useUserSettings();
const userVPN = vpnResult?.VPN || {};
const isBasicVPN = userVPN?.PlanName === PLANS.VPNBASIC;
const maxTier = userVPN?.MaxTier || 0;
const [category, setCategory] = useState(CATEGORY.FREE);
const excludeCategoryMap = excludedCategories.reduce((map, excludedCategory) => {
map[excludedCategory] = true;
return map;
}, {});
if (maxTier) {
excludeCategoryMap[CATEGORY.FREE] = true;
}
const selectedCategory = maxTier && category === CATEGORY.FREE ? CATEGORY.SERVER : category;
const downloadAllConfigs = async () => {
const freeSelected = selectedCategory === CATEGORY.FREE;
const buffer = await request({
Category: freeSelected ? CATEGORY.SERVER : selectedCategory,
Platform: platform,
Protocol: protocol,
Tier: freeSelected ? 0 : maxTier,
});
const blob = new Blob([buffer], { type: 'application/zip' });
downloadFile(blob, 'ProtonVPN_server_configs.zip');
};
const servers = useMemo(
() =>
(result.LogicalServers || []).map((server) => ({
...server,
Country: getLocalizedCountryByAbbr(
correctAbbr(server.ExitCountry),
userSettings.Locale || navigator.languages
),
})),
[result.LogicalServers]
);
const { sortedList: allServers } = useSortedList(servers, { key: 'Country', direction: SORT_DIRECTION.ASC });
const isUpgradeRequiredForSecureCore = !Object.keys(userVPN).length || !hasPaidVpn || isBasicVPN;
const isUpgradeRequiredForCountries = !Object.keys(userVPN).length || !hasPaidVpn;
const isUpgradeRequiredForDownloadAll =
!Object.keys(userVPN).length ||
(!hasPaidVpn && ![CATEGORY.SERVER, CATEGORY.FREE].includes(selectedCategory)) ||
(isBasicVPN && selectedCategory === CATEGORY.SECURE_CORE);
const secureCoreServers = useMemo(() => {
return allServers
.filter(({ Features }) => isSecureCoreEnabled(Features))
.map((server) => {
return {
...server,
isUpgradeRequired: isUpgradeRequiredForSecureCore,
};
});
}, [allServers, isUpgradeRequiredForSecureCore]);
const countryServers = groupWith(
(a, b) => a.ExitCountry === b.ExitCountry,
allServers.filter(
({ Tier, Features }) => Tier === 2 && !isSecureCoreEnabled(Features) && !isTorEnabled(Features)
)
).map((groups) => {
const [first] = groups;
const activeServers = groups.filter(({ Status }) => Status === 1);
const load = activeServers.reduce((acc, { Load }) => acc + Load, 0) / activeServers.length;
return {
...first,
isUpgradeRequired: isUpgradeRequiredForCountries,
Load: Number.isNaN(load) ? 0 : Math.round(load),
Domain: `${first.EntryCountry.toLowerCase()}.protonvpn.net`, // Forging domain
Servers: groups.reduce((acc, { Servers = [] }) => {
acc.push(...Servers);
return acc;
}, []),
};
});
const freeServers = useMemo(() => {
return allServers.filter(({ Tier }) => Tier === 0).map((server) => ({ ...server, open: true }));
}, [allServers]);
useEffect(() => {
if (!hasPaidVpn || userVPN.PlanName === 'trial') {
setCategory(CATEGORY.FREE);
}
}, [vpnLoading]);
useEffect(() => {
fetchUserVPN(30_000);
}, [hasPaidVpn]);
useEffect(() => {
fetchLogicals(30_000);
}, []);
const vpnPlan = plans?.find(({ Name }) => Name === PLANS.VPN);
const plusVpnConnections = vpnPlan?.MaxVPN || VPN_CONNECTIONS;
const vpnPlus = vpnPlan?.Title;
return (
<SettingsSectionWide>
{!vpnLoading && (
<>
{!listOnly && (
<>
<SettingsParagraph>
{c('Info')
.t`These configuration files let you choose which ${VPN_APP_NAME} server you connect to when using a third-party VPN app or setting up a VPN connection on a router.
`}
</SettingsParagraph>
<h3 className="mt-8 mb-2">{c('Title').t`1. Select platform`}</h3>
<div className="flex on-mobile-flex-column">
{[
{
value: PLATFORM.ANDROID,
link: 'https://protonvpn.com/support/android-vpn-setup/',
label: c('Option').t`Android`,
},
{
value: PLATFORM.IOS,
link: 'https://protonvpn.com/support/ios-vpn-setup/',
label: c('Option').t`iOS`,
},
{
value: PLATFORM.WINDOWS,
link: 'https://protonvpn.com/support/openvpn-windows-setup/',
label: c('Option').t`Windows`,
},
{
value: PLATFORM.MACOS,
link: 'https://protonvpn.com/support/mac-vpn-setup/',
label: c('Option').t`macOS`,
},
{
value: PLATFORM.LINUX,
link: 'https://protonvpn.com/support/linux-vpn-setup/',
label: c('Option').t`GNU/Linux`,
},
{
value: PLATFORM.ROUTER,
link: 'https://protonvpn.com/support/installing-protonvpn-on-a-router/',
label: c('Option').t`Router`,
},
].map(({ value, label, link }) => {
return (
<div key={value} className="mr-8 mb-4">
<Radio
onChange={() => setPlatform(value)}
checked={platform === value}
name="platform"
className="flex inline-flex-vcenter mb-2"
>
{label}
</Radio>
<Href
href={link}
className="text-sm m-0 block ml-custom"
style={{ '--ml-custom': '1.75rem' }}
>{c('Link').t`View guide`}</Href>
</div>
);
})}
</div>
<h3 className="mt-8 mb-2">{c('Title').t`2. Select protocol`}</h3>
<div className="flex on-mobile-flex-column mb-2">
<RadioGroup
name="protocol"
value={protocol}
onChange={setProtocol}
options={[
{ value: PROTOCOL.UDP, label: c('Option').t`UDP` },
{ value: PROTOCOL.TCP, label: c('Option').t`TCP` },
]}
/>
</div>
<div className="mb-4">
<Href href="https://protonvpn.com/support/udp-tcp/" className="text-sm m-0">{c('Link')
.t`What is the difference between UDP and TCP protocols?`}</Href>
</div>
<h3 className="mt-8 mb-2">{c('Title').t`3. Select config file and download`}</h3>
</>
)}
<div className="flex on-mobile-flex-column mb-6">
<RadioGroup
name={'category' + (listOnly ? '-list' : '')}
value={selectedCategory}
onChange={setCategory}
options={[
{ value: CATEGORY.COUNTRY, label: c('Option').t`Country configs` },
{ value: CATEGORY.SERVER, label: c('Option').t`Standard server configs` },
{ value: CATEGORY.FREE, label: c('Option').t`Free server configs` },
{ value: CATEGORY.SECURE_CORE, label: c('Option').t`Secure Core configs` },
].filter((option) => !excludeCategoryMap[option.value])}
/>
</div>
</>
)}
<Block>
{selectedCategory === CATEGORY.SECURE_CORE && (
<>
<SettingsParagraph learnMoreUrl="https://protonvpn.com/support/secure-core-vpn">
{c('Info')
.t`Install a Secure Core configuration file to benefit from an additional protection against VPN endpoint compromise.`}
</SettingsParagraph>
{isUpgradeRequiredForSecureCore && (
<SettingsParagraph>
<span className="block">{
// translator: ${vpnPlus} is "VPN Plus" (taken from plan title)
c('Info').t`${vpnPlus} required for Secure Core feature.`
}</span>
<SettingsLink path="/upgrade">{c('Link').t`Learn more`}</SettingsLink>
</SettingsParagraph>
)}
<ConfigsTable
category={CATEGORY.SECURE_CORE}
platform={platform}
protocol={protocol}
loading={loading}
servers={secureCoreServers}
onSelect={onSelect}
selecting={selecting}
/>
</>
)}
{selectedCategory === CATEGORY.COUNTRY && (
<>
{!listOnly && (
<SettingsParagraph>
{c('Info')
.t`Install a Country configuration file to connect to a random server in the country of your choice.`}
</SettingsParagraph>
)}
{isUpgradeRequiredForCountries && (
<SettingsParagraph learnMoreUrl={`https://${VPN_HOSTNAME}/dashboard`}>{
// translator: ${vpnPlus} is "VPN Plus" (taken from plan title)
// translator: This notice appears when a free user go to "OpenVPN configuration files" section and select "Country configs'
c('Info').t`${vpnPlus} required for Country level connection.`
}</SettingsParagraph>
)}
<ConfigsTable
category={CATEGORY.COUNTRY}
platform={platform}
protocol={protocol}
loading={loading}
servers={countryServers}
onSelect={onSelect}
selecting={selecting}
/>
</>
)}
{selectedCategory === CATEGORY.SERVER && (
<>
{!listOnly && (
<SettingsParagraph>{c('Info')
.t`Install a Server configuration file to connect to a specific server in the country of your choice.`}</SettingsParagraph>
)}
<ServerConfigs
category={selectedCategory}
platform={platform}
protocol={protocol}
loading={loading}
servers={allServers}
select={onSelect}
selecting={selecting}
/>
</>
)}
{selectedCategory === CATEGORY.FREE && (
<>
{!listOnly && (
<SettingsParagraph>
{c('Info')
.t`Install a Free server configuration file to connect to a specific server in one of the three free locations.`}
</SettingsParagraph>
)}
<ServerConfigs
category={selectedCategory}
platform={platform}
protocol={protocol}
loading={loading}
servers={freeServers}
select={onSelect}
selecting={selecting}
/>
</>
)}
{!listOnly && (
<>
<div className="mb-8">
{isUpgradeRequiredForDownloadAll ? (
<Tooltip title={c('Info').t`Plan upgrade required`}>
<Button loading={vpnLoading} disabled>{c('Action')
.t`Download all configurations`}</Button>
</Tooltip>
) : (
<Button loading={vpnLoading} onClick={() => downloadAllConfigs()}>{c('Action')
.t`Download all configurations`}</Button>
)}
</div>
{!loadingPlans && (userVPN.PlanName === 'trial' || !hasPaidVpn) && vpnPlus && (
<div className="border p-7 text-center">
<h3 className="color-primary mt-0 mb-4">{
// translator: ${vpnPlus} is "VPN Plus" (taken from plan title)
c('Title').t`Get ${vpnPlus} to access all servers`
}</h3>
<ul className="unstyled inline-flex mt-0 mb-8 on-mobile-flex-column">
<li className="flex flex-nowrap flex-align-items-center mr-4">
<Icon name="checkmark" className="color-success mr-2" />
<span className="text-bold">{c('Feature').t`Access to all countries`}</span>
</li>
<li className="flex flex-nowrap flex-align-items-center mr-4">
<Icon name="checkmark" className="color-success mr-2" />
<span className="text-bold">{c('Feature').t`Secure Core servers`}</span>
</li>
<li className="flex flex-nowrap flex-align-items-center mr-4">
<Icon name="checkmark" className="color-success mr-2" />
<span className="text-bold">{c('Feature').t`Fastest VPN servers`}</span>
</li>
<li className="flex flex-nowrap flex-align-items-center mr-4">
<Icon name="checkmark" className="color-success mr-2" />
<span className="text-bold">{c('Feature').t`Torrenting support (P2P)`}</span>
</li>
<li className="flex flex-nowrap flex-align-items-center mr-4">
<Icon name="checkmark" className="color-success mr-2" />
<span className="text-bold">
{c('Feature').ngettext(
msgid`Connection for up to ${plusVpnConnections} device`,
`Connection for up to ${plusVpnConnections} devices`,
plusVpnConnections
)}
</span>
</li>
<li className="flex flex-nowrap flex-align-items-center ">
<Icon name="checkmark" className="color-success mr-2" />
<span className="text-bold mr-2">{c('Feature')
.t`Secure streaming support`}</span>
<Info
url="https://protonvpn.com/support/streaming-guide/"
title={c('VPN info')
.t`Netflix, Amazon Prime Video, BBC iPlayer, ESPN+, Disney+, HBO Now, and more.`}
/>
</li>
</ul>
<div>
<ButtonLike as={SettingsLink} color="norm" path={`/dashboard?plan=${PLANS.VPN}`}>
{
// translator: ${vpnPlus} is "VPN Plus" (taken from plan title)
c('Action').t`Get ${vpnPlus}`
}
</ButtonLike>
</div>
</div>
)}
</>
)}
</Block>
</SettingsSectionWide>
);
};
OpenVPNConfigurationSection.propTypes = {
onSelect: PropTypes.func,
selecting: PropTypes.bool,
listOnly: PropTypes.bool,
excludedCategories: PropTypes.arrayOf(
PropTypes.oneOf([CATEGORY.SECURE_CORE, CATEGORY.COUNTRY, CATEGORY.SERVER, CATEGORY.FREE])
),
};
export default OpenVPNConfigurationSection;
| 6,958
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/OpenVPNConfigurationSection/ServerConfigs.js
|
import { useCallback, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import { PLANS } from '@proton/shared/lib/constants';
import clsx from '@proton/utils/clsx';
import compare from '@proton/utils/compare';
import groupWith from '@proton/utils/groupWith';
import { Details, Summary } from '../../../components';
import { useUser, useUserVPN } from '../../../hooks';
import CityNumber from './CityNumber';
import ConfigsTable, { CATEGORY, P2PIcon, TorIcon } from './ConfigsTable';
import Country from './Country';
import ServerNumber from './ServerNumber';
import { isP2PEnabled, isSecureCoreEnabled, isTorEnabled } from './utils';
const getServerNum = (server) => Number(server.Name.replace('-TOR', '').split('#')[1]);
const getServerRegion = (server) => server.Name.split('#')[0];
const serverRegionAsc = (a, b) => compare(getServerRegion(a), getServerRegion(b));
const serverNumAsc = (a, b) => compare(getServerNum(a), getServerNum(b));
const serverNameAsc = (a, b) => serverRegionAsc(a, b) || serverNumAsc(a, b);
const ServerConfigs = ({ servers, category, select, selecting, ...rest }) => {
const [{ hasPaidVpn }] = useUser();
const { result, fetch: fetchUserVPN } = useUserVPN();
const userVPN = result?.VPN || {};
const isBasicVPN = userVPN && userVPN.PlanName === PLANS.VPNBASIC;
const isUpgradeRequired = useCallback(
(server) => {
return !userVPN || (!hasPaidVpn && server.Tier > 0) || (isBasicVPN && server.Tier === 2);
},
[userVPN, hasPaidVpn, isBasicVPN]
);
useEffect(() => {
fetchUserVPN(30_000);
}, [hasPaidVpn]);
// Free servers at the top, then sorted by Name#ID
const sortedGroups = useMemo(() => {
const groupedServers = groupWith(
(a, b) => a.Country === b.Country,
servers.filter(({ Features = 0 }) => !isSecureCoreEnabled(Features))
);
return groupedServers.map((group) => {
const freeServers = group.filter(({ Name }) => Name.includes('FREE')).sort(serverNameAsc);
const otherServers = group.filter(({ Name }) => !Name.includes('FREE')).sort(serverNameAsc);
return [...freeServers, ...otherServers].map((server) => {
return {
...server,
isUpgradeRequired: isUpgradeRequired(server),
};
});
});
}, [servers, isUpgradeRequired]);
return (
<div className="mb-6">
{sortedGroups.map((group) => {
const server = group[0];
return (
<Details key={server.Country || 'XX'} open={server.open}>
<Summary>
<div className="ml-2 flex flex-nowrap flex-align-items-center">
<div className={clsx([category === CATEGORY.SERVER ? 'w-1/3' : ''])}>
<Country server={server} />
</div>
{category === CATEGORY.SERVER && (
<>
<div className="w-1/3">
<ServerNumber group={group} />
</div>
<div className="w-1/3 flex flex-justify-space-between">
<CityNumber group={group} />
<div className={clsx(['flex'])}>
{group.some(({ Features }) => isP2PEnabled(Features)) ? (
<P2PIcon />
) : null}
{group.some(({ Features }) => isTorEnabled(Features)) ? (
<TorIcon />
) : null}
</div>
</div>
</>
)}
</div>
</Summary>
<div className="p-4">
<ConfigsTable
{...rest}
category={category}
servers={group}
onSelect={select}
selecting={selecting}
/>
</div>
</Details>
);
})}
</div>
);
};
ServerConfigs.propTypes = {
servers: PropTypes.arrayOf(
PropTypes.shape({
ID: PropTypes.string,
Country: PropTypes.string,
EntryCountry: PropTypes.string,
ExitCountry: PropTypes.string,
Domain: PropTypes.string,
Features: PropTypes.number,
Load: PropTypes.number,
Tier: PropTypes.number,
})
),
category: PropTypes.oneOf([CATEGORY.SECURE_CORE, CATEGORY.COUNTRY, CATEGORY.SERVER, CATEGORY.FREE]),
select: PropTypes.func,
isSelected: PropTypes.func,
};
export default ServerConfigs;
| 6,959
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/OpenVPNConfigurationSection/ServerNumber.tsx
|
import { c, msgid } from 'ttag';
import { VPNServer } from '@proton/shared/lib/interfaces/VPNServer';
interface Props {
group: VPNServer[];
}
const ServerNumber = ({ group }: Props) => {
const number = group.reduce((acc, { Servers }) => acc + Servers.length, 0);
return (
<div className="inline-flex-vcenter">
{c('Info').ngettext(msgid`${number} server`, `${number} servers`, number)}
</div>
);
};
export default ServerNumber;
| 6,960
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/OpenVPNConfigurationSection/utils.js
|
import { SERVER_FEATURES } from '@proton/shared/lib/constants';
export const isFeatureOn =
(feature) =>
(features = 0) =>
!!(features & feature);
export const isSecureCoreEnabled = isFeatureOn(SERVER_FEATURES.SECURE_CORE);
export const isP2PEnabled = isFeatureOn(SERVER_FEATURES.P2P);
export const isTorEnabled = isFeatureOn(SERVER_FEATURES.TOR);
| 6,961
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/ProtonVPNClientsSection/ProtonVPNClientsSection.tsx
|
import { useHistory, useLocation } from 'react-router-dom';
import { c } from 'ttag';
import { Button, ButtonLike, Href } from '@proton/atoms';
import { VPN_APP_NAME } from '@proton/shared/lib/constants';
import onboardingVPNWelcome from '@proton/styles/assets/img/onboarding/vpn-welcome.svg';
import { Copy, DownloadClientCard, DropdownMenuLink, ModalProps, ModalTwo, ModalTwoContent } from '../../../components';
import { useWelcomeFlags } from '../../../hooks';
import { SettingsParagraph, SettingsSectionWide } from '../../account';
import { OnboardingContent } from '../../onboarding';
interface DownloadModalProps extends ModalProps {
downloadUrl: string;
}
const DownloadModal = ({ downloadUrl, ...rest }: DownloadModalProps) => {
return (
<ModalTwo {...rest} size="small">
<ModalTwoContent className="m-8 text-center">
<OnboardingContent
img={<img src={onboardingVPNWelcome} alt={c('Onboarding').t`Welcome to ${VPN_APP_NAME}`} />}
title={c('Title').t`Download ${VPN_APP_NAME}`}
description={c('Info').t`The securest way to browse, stream, and be online.`}
/>
<ButtonLike
as={Href}
color="norm"
size="large"
target="_blank"
href={downloadUrl}
fullWidth
onClick={() => {
rest.onClose?.();
}}
className="mb-2"
>{c('Action').t`Download`}</ButtonLike>
<Button color="norm" size="large" fullWidth shape="ghost" onClick={rest.onClose}>
{c('Action').t`Close`}
</Button>
</ModalTwoContent>
</ModalTwo>
);
};
const ProtonVPNClientsSection = () => {
const history = useHistory();
const location = useLocation();
const [, setDone] = useWelcomeFlags();
const androidLinks = [
{
href: 'https://protonvpn.com/download/ProtonVPN.apk',
children: 'APK',
},
{
href: 'https://github.com/ProtonVPN/android-app/releases',
children: 'GitHub',
},
{
href: 'https://f-droid.org/en/packages/ch.protonvpn.android/',
children: 'F-Droid',
},
].map(({ href, children }) => {
return (
<div className="flex flex-align-items-center no-scroll" key={children}>
<DropdownMenuLink className="flex-item-fluid" href={href}>
{children}
</DropdownMenuLink>
<Copy shape="ghost" value={href} className="flex-item-noshrink mr-2" />
</div>
);
});
return (
<SettingsSectionWide>
<DownloadModal
downloadUrl="https://protonvpn.com/download"
open={location.search.includes('prompt')}
onClose={() => {
history.replace({ ...location, search: '' });
setDone();
}}
/>
<SettingsParagraph>
{c('Info')
.t`To secure your internet connection, download and install the ${VPN_APP_NAME} application for your device and connect to a server.`}
</SettingsParagraph>
<div className="flex gap-4 on-mobile-flex-column">
<DownloadClientCard
title={c('VPNClient').t`Android`}
icon="brand-android"
link="https://play.google.com/store/apps/details?id=ch.protonvpn.android&utm_campaign=ww-all-2a-vpn-int_webapp-g_eng-apps_links_dashboard&utm_source=account.protonvpn.com&utm_medium=link&utm_content=dashboard&utm_term=android"
items={androidLinks}
/>
<DownloadClientCard
title={c('VPNClient').t`iOS`}
icon="brand-apple"
link="https://apps.apple.com/app/apple-store/id1437005085?pt=106513916&ct=protonvpn.com-dashboard&mt=8"
/>
<DownloadClientCard
title={c('VPNClient').t`Windows`}
icon="brand-windows"
link="https://protonvpn.com/download-windows/"
/>
<DownloadClientCard
title={c('VPNClient').t`macOS`}
icon="brand-mac"
link="https://protonvpn.com/download-macos/"
/>
<DownloadClientCard
title={c('VPNClient').t`GNU/Linux`}
icon="brand-linux"
link="https://protonvpn.com/download-linux/"
/>
<DownloadClientCard
title={c('VPNClient').t`Chromebook`}
icon="brand-chrome"
link="https://play.google.com/store/apps/details?id=ch.protonvpn.android&utm_campaign=ww-all-2a-vpn-int_webapp-g_eng-apps_links_dashboard&utm_source=account.protonvpn.com&utm_medium=link&utm_content=dashboard&utm_term=chromebook"
items={androidLinks}
/>
<DownloadClientCard
title={c('VPNClient').t`Android TV`}
icon="tv"
link="https://play.google.com/store/apps/details?id=ch.protonvpn.android&utm_campaign=ww-all-2a-vpn-int_webapp-g_eng-apps_links_dashboard&utm_source=account.protonvpn.com&utm_medium=link&utm_content=dashboard&utm_term=androidtv"
items={androidLinks}
/>
</div>
</SettingsSectionWide>
);
};
export default ProtonVPNClientsSection;
| 6,962
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/ProtonVPNCredentialsSection/ProtonVPNCredentialsSection.js
|
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { BRAND_NAME, MAIL_APP_NAME, VPN_APP_NAME } from '@proton/shared/lib/constants';
import { Alert, Field, Label, Row } from '../../../components';
import { useUser } from '../../../hooks';
const ProtonVPNCredentialsSection = () => {
const [user] = useUser();
const username = user.isMember ? user.Email : user.Name;
const downloadLink = (
<Href key="link" className="mr-2" href="https://protonvpn.com/download">{c('Link')
.t`${VPN_APP_NAME} native clients`}</Href>
);
return (
<>
<Alert className="mb-4">{c('Info')
.jt`Use the following credentials to log into the ${downloadLink}.`}</Alert>
<Row>
<Label>{c('Label').t`${BRAND_NAME} username`}</Label>
<Field className="mt-2">
<strong>{username}</strong>
</Field>
</Row>
<Row>
<Label>{c('Label').t`Password`}</Label>
<Field className="mt-2">
<strong>{c('Info').t`Same as ${MAIL_APP_NAME} login password`}</strong>
</Field>
</Row>
</>
);
};
export default ProtonVPNCredentialsSection;
| 6,963
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/ProtonVPNResourcesSection/ProtonVPNResourcesSection.js
|
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { VPN_APP_NAME } from '@proton/shared/lib/constants';
import { Field, Label, Row } from '../../../components';
const ProtonVPNResourcesSection = () => {
return (
<>
<Row>
<Label>{c('Label').t`Download ${VPN_APP_NAME}`}</Label>
<Field>
<Href href="https://protonvpn.com/download">{c('Link').t`Download page`}</Href>
</Field>
</Row>
<Row>
<Label>{c('Label').t`${VPN_APP_NAME} homepage`}</Label>
<Field>
<Href href="https://protonvpn.com/">{c('Link').t`Homepage`}</Href>
</Field>
</Row>
<Row>
<Label>{c('Label').t`Get support for ${VPN_APP_NAME}`}</Label>
<Field>
<Href href="https://protonvpn.com/support">{c('Link').t`Support page`}</Href>
</Field>
</Row>
</>
);
};
export default ProtonVPNResourcesSection;
| 6,964
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/WireGuardConfigurationSection/Certificate.ts
|
import { KeyMode } from './KeyPair';
export type CertificateMode = 'session' | 'persistent';
export interface CertificateGenerationParams {
ClientPublicKey: string;
ClientPublicKeyMode?: KeyMode | null | undefined;
DeviceName?: string | null | undefined;
Duration?: string | null | undefined;
ExpirationTime?: number | null | undefined;
Mode?: CertificateMode | null | undefined;
Features?: Record<string, string | number | boolean | null> | string[];
Renew?: boolean;
}
export interface CertificateDeletionParams {
SerialNumber?: string;
ClientPublicKey?: string;
ClientPublicKeyMode?: string;
ClientPublicKeyFingerprint?: string;
DeviceName?: string;
}
export interface CertificateDTO {
SerialNumber: string;
ClientKeyFingerprint: string;
ClientKey: string;
Certificate: string;
ExpirationTime: number;
RefreshTime: number;
Mode: CertificateMode;
ServerPublicKeyMode: KeyMode;
ServerPublicKey: string;
DeviceName?: string;
Features?: Record<string, string | number | boolean | null>;
}
| 6,965
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/WireGuardConfigurationSection/KeyPair.ts
|
export interface KeyPair {
PrivateKey: string;
PublicKey: string;
}
export type KeyMode = 'EC' | 'RSA';
| 6,966
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/WireGuardConfigurationSection/WireGuardConfigurationSection.test.ts
|
const fs = require('fs');
const path = require('path');
/**
* This is a test to ensure the bigint polyfill patch is applied. It is intended to catch a scenario where the
* ed25519 library may get updated and we won't get notified through the yarn install.
*/
describe('ed25519 library', () => {
it('should polyfill bigint', () => {
const file = fs.readFileSync(path.resolve(`${require.resolve('@noble/ed25519')}/../esm/index.js`)).toString();
expect(
file.includes(`const BigInt = typeof window.BigInt !== 'undefined' ? window.BigInt : (() => 0);`)
).toBeTruthy();
});
});
| 6,967
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/WireGuardConfigurationSection/WireGuardConfigurationSection.tsx
|
import { ChangeEvent, FormEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import { Point, utils } from '@noble/ed25519';
import { c } from 'ttag';
import { Button, CircleLoader, Href } from '@proton/atoms';
import downloadFile from '@proton/shared/lib/helpers/downloadFile';
import { base64StringToUint8Array, uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import { readableTime } from '@proton/shared/lib/helpers/time';
import {
Alert,
ConfirmModal,
Details,
ErrorButton,
Icon,
Info,
InputFieldTwo,
Option,
Radio,
Row,
SelectTwo,
Summary,
TextArea,
Toggle,
} from '../../../components';
import { useModalTwo } from '../../../components/modalTwo/useModalTwo';
import { getObjectKeys } from '../../../helpers';
import { getLocalizedCountryByAbbr } from '../../../helpers/countries';
import {
useApi,
useApiResult,
useModals,
useNotifications,
useUser,
useUserSettings,
useUserVPN,
useVPNLogicals,
} from '../../../hooks';
import { SettingsParagraph, SettingsSectionWide } from '../../account';
import { Certificate } from '../Certificate';
import { Logical } from '../Logical';
import { CATEGORY } from '../OpenVPNConfigurationSection/ConfigsTable';
import OpenVPNConfigurationSection from '../OpenVPNConfigurationSection/OpenVPNConfigurationSection';
import { getFlagSvg } from '../flag';
import { CertificateDTO, CertificateDeletionParams, CertificateGenerationParams } from './Certificate';
import { KeyPair } from './KeyPair';
import WireGuardCreationModal, { WireGuardCreationModalProps } from './WireGuardCreationModal';
import { deleteCertificates, generateCertificate, getKey, queryVPNClientConfig } from './api';
import { CURVE } from './curve';
import {
FeatureFlagsConfig,
FeatureOption,
FeatureSelection,
FeaturesConfig,
FeaturesValues,
clientConfigKeys,
formatFeatureShortName,
formatFeatureValue,
getKeyOfCheck,
initialFeaturesConfig,
isFeatureSelection,
} from './feature';
import { normalize } from './normalize';
import useCertificates from './useCertificates';
enum PLATFORM {
MACOS = 'macOS',
LINUX = 'Linux',
WINDOWS = 'Windows',
ANDROID = 'Android',
IOS = 'iOS',
ROUTER = 'Router',
}
interface Peer {
name: string;
publicKey: string;
ip: string;
label: string;
}
interface ExtraCertificateFeatures {
peerName: Peer['name'];
peerPublicKey: Peer['publicKey'];
peerIp: Peer['ip'];
label: Peer['label'];
platform: PLATFORM;
}
const isExtraFeatureKey = getKeyOfCheck<ExtraCertificateFeatures>(['peerIp', 'peerName', 'peerPublicKey', 'platform']);
// From https://github.com/paulmillr/noble-ed25519/blob/d87d6e953304c9d4dbfb275e8e67a0c975d3262b/index.js
const bytesToNumberLE = (uint8a: Uint8Array) => {
let value = BigInt(0);
for (let i = 0; i < uint8a.length; i++) {
value += BigInt(uint8a[i]) << (BigInt(8) * BigInt(i));
}
return value;
};
const unarmor = (key: string): string => `\n${key}\n`.replace(/\n---.+\n/g, '').replace(/\s/g, '');
const randomPrivateKey = () => {
if (!CURVE) {
throw new Error('BigInt not supported');
}
let i = 1024;
while (i--) {
const b32 = crypto.getRandomValues(new Uint8Array(32));
const num = bytesToNumberLE(b32);
if (num > BigInt(1) && num < CURVE.n) {
return b32;
}
}
throw new Error('Valid private key was not found in 1024 iterations. PRNG is broken');
};
const getPublicKey = async (privateKey: Uint8Array): Promise<Uint8Array> => {
const key = await Point.fromPrivateKey(privateKey);
return key.toRawBytes();
};
const getFeatureLink = (feature: FeatureOption<any>) =>
feature.url ? (
<>
{' '}
<Href className="text-no-bold" href={feature.url}>{c('Info').t`Learn more`}</Href>
</>
) : (
''
);
const getConfigTemplate = (
interfacePrivateKey: string,
name: string | undefined,
features: Partial<FeaturesValues & ExtraCertificateFeatures> | undefined,
peer: Peer
) => `[Interface]${name ? `\n# Key for ${name}` : ''}${getObjectKeys(features)
.map((key) =>
isExtraFeatureKey(key) ? '' : `\n# ${formatFeatureShortName(key)} = ${formatFeatureValue(features, key)}`
)
.join('')}
PrivateKey = ${interfacePrivateKey}
Address = 10.2.0.2/32
DNS = 10.2.0.1
[Peer]
# ${features?.peerName || peer.name}
PublicKey = ${features?.peerPublicKey || peer.publicKey}
AllowedIPs = ${features?.platform === PLATFORM.WINDOWS ? '0.0.0.0/1, 128.0.0.0/1' : '0.0.0.0/0'}
Endpoint = ${features?.peerIp || peer.ip}:51820`;
const privateKeyPlaceholder = '*****';
const getCertificateModel = (
certificateDto: CertificateDTO & { id?: string },
peer: Peer,
privateKey?: string,
id?: string
): Certificate => {
if (!id && !certificateDto.id) {
certificateDto.id = `c${Date.now()}-${Math.random()}`;
}
const name = certificateDto?.DeviceName;
const features = certificateDto?.Features;
return {
id: `${id || certificateDto.id}`,
name,
features,
serialNumber: certificateDto.SerialNumber,
privateKey: privateKey || privateKeyPlaceholder,
publicKey: certificateDto.ClientKey,
publicKeyFingerprint: certificateDto.ClientKeyFingerprint,
expirationTime: certificateDto.ExpirationTime,
config: getConfigTemplate(privateKey || privateKeyPlaceholder, name, features, peer),
};
};
const paginationSize = 50;
const formatServerName = (bestServerName: string, locale: string | readonly string[]) => {
const countryCode = bestServerName.split(/#/g)[0];
const flag = getFlagSvg(countryCode);
return (
<>
{flag && (
<img
width={20}
className="mx-2 border"
src={flag}
alt={getLocalizedCountryByAbbr(countryCode, locale)}
/>
)}
<strong className="align-middle">{bestServerName}</strong>
</>
);
};
const getX25519PrivateKey = async (privateKey: string): Promise<string> => {
const sha512 = (await utils.sha512(base64StringToUint8Array(privateKey))).slice(0, 32);
sha512[0] &= 0xf8;
sha512[31] &= 0x7f;
sha512[31] |= 0x40;
return uint8ArrayToBase64String(sha512);
};
const WireGuardConfigurationSection = () => {
const [platform, setPlatform] = useState(PLATFORM.ANDROID);
const [featuresConfig, setFeaturesConfig] = useState<FeaturesConfig>(initialFeaturesConfig);
const api = useApi();
const [peer, setPeer] = useState<Peer>({
name: '',
publicKey: '',
ip: '',
label: '',
});
const certificateCacheRef = useRef<Record<string, Certificate>>({});
const certificateCache = certificateCacheRef.current;
const [logical, setLogical] = useState<Logical | undefined>();
const [creationModal, handleShowCreationModal] = useModalTwo<WireGuardCreationModalProps, void>(
WireGuardCreationModal,
false
);
const [creating, setCreating] = useState<boolean>(false);
const [removing, setRemoving] = useState<Record<string, boolean>>({});
const [removedCertificates, setRemovedCertificates] = useState<string[]>([]);
const [currentCertificate, setCurrentCertificate] = useState<string | undefined>();
const [certificates, setCertificates] = useState<Certificate[]>([]);
const [{ hasPaidVpn }] = useUser();
const [userSettings] = useUserSettings();
const { result, loading: vpnLoading, fetch: fetchUserVPN } = useUserVPN();
const userVPN = result?.VPN;
const nameInputRef = useRef<HTMLInputElement>(null);
const { createModal } = useModals();
const { createNotification } = useNotifications();
const { result: clientConfig = { FeatureFlags: {} as FeatureFlagsConfig } } = useApiResult<
{ FeatureFlags: FeatureFlagsConfig },
typeof queryVPNClientConfig
>(queryVPNClientConfig, []);
const {
loading: logicalsLoading,
result: logicalsResult = { LogicalServers: [] },
fetch: fetchLogicals,
} = useVPNLogicals();
const [limit, setLimit] = useState(paginationSize);
const { loading: certificatesLoading, result: certificatesResult, moreToLoad } = useCertificates(limit);
const logicalInfoLoading = logicalsLoading || vpnLoading;
const maxTier = userVPN?.MaxTier || 0;
const logicals = useMemo(
() =>
((!logicalInfoLoading && logicalsResult.LogicalServers) || [])
.map((logical) => ({
...logical,
Servers: (logical.Servers || []).filter((server) => server.X25519PublicKey),
}))
.filter((logical) => logical.Servers.length),
[logicalInfoLoading, logicalsResult.LogicalServers]
);
const bestLogicals = logicals
.filter((server) => server.Tier <= maxTier && (server.Features & 3) === 0)
.sort((a, b) => a.Score - b.Score);
const bestLogical = bestLogicals[0];
const bestServerName = bestLogical?.Name;
const formattedBestServerName = bestServerName
? formatServerName(bestServerName, userSettings.Locale || navigator.languages)
: '';
const getCertificates = (): Certificate[] => {
certificatesResult.forEach((certificateDto) => {
if (
removedCertificates.indexOf(certificateDto.ClientKeyFingerprint) !== -1 ||
certificateDto.ExpirationTime <
(certificateCache[certificateDto.ClientKeyFingerprint]?.expirationTime || 0)
) {
return;
}
certificateCache[certificateDto.ClientKeyFingerprint] = getCertificateModel(certificateDto, peer);
});
certificates.forEach((certificate) => {
if (
removedCertificates.indexOf(certificate.publicKeyFingerprint) !== -1 ||
certificate.expirationTime < (certificateCache[certificate.publicKeyFingerprint]?.expirationTime || 0)
) {
return;
}
certificateCache[certificate.publicKeyFingerprint] = certificate;
});
return Object.values(certificateCache);
};
const setFeature = <K extends keyof FeaturesConfig>(key: K, value: FeaturesConfig[K]['value']) => {
setFeaturesConfig({
...featuresConfig,
[key]: {
...featuresConfig[key],
value,
},
});
};
const getKeyPair = async (): Promise<{ privateKey: string; publicKey: string }> => {
try {
const privateKey = randomPrivateKey();
return {
privateKey: uint8ArrayToBase64String(privateKey),
publicKey: uint8ArrayToBase64String(await getPublicKey(privateKey)),
};
} catch (e) {
console.warn(e);
console.info(
'Fallback to server-side generated key. Upgrade to a modern browser, to generate right from your device.'
);
const { PrivateKey, PublicKey } = await api<KeyPair>(getKey());
return { privateKey: unarmor(PrivateKey), publicKey: unarmor(PublicKey) };
}
};
const getToggleCallback = (certificate: Certificate) => (event: ChangeEvent<HTMLDetailsElement>) => {
if (!event?.target?.hasAttribute('open')) {
return;
}
if (certificate.id === currentCertificate) {
return;
}
setCurrentCertificate(certificate.id);
};
const queryCertificate = (
publicKey: string,
deviceName?: string | null | undefined,
features?: Record<string, string | number | boolean | null> | undefined,
options: Partial<CertificateGenerationParams> = {}
): Promise<CertificateDTO> =>
api<CertificateDTO>(
generateCertificate({
ClientPublicKey: publicKey,
Mode: 'persistent',
DeviceName: deviceName,
Features: features,
...options,
})
);
const getFeatureKeys = () =>
getObjectKeys(featuresConfig).filter(
(key) => maxTier >= (featuresConfig[key].tier || 0) && clientConfig?.FeatureFlags?.[clientConfigKeys[key]]
);
const getFeatureValues = useCallback(
(addedPeer?: Peer) => {
const peerFeatures = addedPeer || peer;
const label = peerFeatures?.label;
return Object.assign(
label ? { Bouncing: label } : {},
Object.fromEntries(
getFeatureKeys().map((key) => [
key,
((featuresConfig[key].transform || ((v: any) => v)) as <T>(value: T) => T)(
featuresConfig[key].value
),
])
),
peerFeatures
? {
peerName: peerFeatures.name,
peerIp: peerFeatures.ip,
peerPublicKey: peerFeatures.publicKey,
platform,
}
: {}
);
},
[featuresConfig, peer, platform]
);
const getDownloadCallback = (certificate: Certificate) => () => {
if (creating) {
return;
}
const serverName = `${certificate?.features?.peerName || peer.name}`.substring(0, 20);
downloadFile(
new Blob([certificate.config || '']),
normalize((certificate.name || 'wg') + '-' + serverName) + '.conf'
);
};
const add = async (addedPeer?: Peer, silent = false) => {
if (creating) {
return;
}
setCreating(true);
try {
const serverName = addedPeer?.name;
if (!silent && serverName) {
handleShowCreationModal({
open: true,
serverName: serverName,
text: undefined,
config: undefined,
onClose() {
silent = true;
handleShowCreationModal({ open: false });
},
});
}
try {
const { privateKey, publicKey } = await getKeyPair();
const x25519PrivateKey = await getX25519PrivateKey(privateKey);
const deviceName = nameInputRef?.current?.value || '';
const certificate = await queryCertificate(publicKey, deviceName, getFeatureValues(addedPeer));
if (!certificate.DeviceName) {
certificate.DeviceName = deviceName;
}
const newCertificate = getCertificateModel(certificate, peer, x25519PrivateKey);
const id = newCertificate.id;
let name = newCertificate.name || newCertificate.publicKeyFingerprint || newCertificate.publicKey;
if (name.length > 46) {
name = name.substring(0, 21) + '…' + name.substring(name.length - 21);
}
if (!silent) {
const downloadCallback = getDownloadCallback(newCertificate);
handleShowCreationModal({
open: true,
serverName: serverName,
// translator: name a name given by the user to a config file
text: c('Success notification')
.t`Config "${name}" created, note that the private key is not stored and won't be shown again, you should copy or download this config.`,
config: newCertificate?.config || '',
onDownload() {
downloadCallback();
handleShowCreationModal({ open: false });
},
onClose() {
handleShowCreationModal({ open: false });
},
});
}
flushSync(() => {
setCurrentCertificate(id);
setCertificates([...(certificates || []), newCertificate]);
});
document.querySelector(`[data-certificate-id="${id}"]`)?.scrollIntoView();
if (nameInputRef?.current) {
nameInputRef.current.value = '';
}
} catch (e) {
if (!silent && serverName) {
handleShowCreationModal({ open: false });
}
throw e;
}
} finally {
setCreating(false);
}
};
const selectLogical = useCallback(
async (logical: Logical, silent = false, doAdd = false) => {
const servers = logical?.Servers || [];
const numberOfServers = servers.length;
const server = servers[Math.floor(Math.random() * numberOfServers)];
const serverName = logical?.Name;
let addPromise: Promise<void> | undefined = undefined;
if (server) {
const newPeer = {
name: serverName,
publicKey: `${server.X25519PublicKey}`,
ip: server.EntryIP,
label: server.Label || '',
};
if (doAdd) {
addPromise = add(newPeer, silent);
}
if (peer.ip !== server.EntryIP) {
setPeer(newPeer);
}
}
setLogical({ ...logical });
if (addPromise) {
await addPromise;
}
},
[peer, getFeatureValues, platform, creating]
);
if (!logicalInfoLoading && logicals.length && typeof logical === 'undefined') {
void selectLogical(bestLogical, true);
}
const createWithLogical = useCallback(
(logical: Logical, silent = false) => selectLogical(logical, silent, true),
[selectLogical]
);
const revokeCertificate = (name: string) => {
createNotification({
// translator: name is arbitrary name given by the user or a random key if not set
text: c('Success notification').t`Certificate ${name} revoked`,
});
};
const confirmRevocation = async (name: string) => {
return new Promise<void>((resolve, reject) => {
createModal(
<ConfirmModal
small={false}
title={c('Title').t`Revoke certificate`}
onConfirm={resolve}
confirm={<ErrorButton type="submit">{c('Action').t`Delete`}</ErrorButton>}
onClose={reject}
>
<Alert className="mb-4" type="info">
{
// translator: name is arbitrary name given by the user or a random key if not set
c('Info').t`Revoke certificate ${name}`
}
</Alert>
<Alert className="mb-4" type="error">
{c('Alter').t`This will disconnect all the routers and clients using this certificate.`}
</Alert>
</ConfirmModal>
);
});
};
const getDeleteFilter = (certificate: Certificate): CertificateDeletionParams => {
if (certificate.serialNumber) {
return { SerialNumber: certificate.serialNumber };
}
if (certificate.publicKeyFingerprint) {
return { ClientPublicKeyFingerprint: certificate.publicKeyFingerprint };
}
return { ClientPublicKey: certificate.publicKey };
};
const askForRevocation = (certificate: Certificate) => async () => {
const key = certificate.publicKeyFingerprint || certificate.publicKey || certificate.id;
setRemoving({
...removing,
[key]: true,
});
const end = () => {
const newValues = { ...removing };
delete newValues[key];
setRemoving(newValues);
};
try {
const name = certificate.name || certificate.publicKeyFingerprint || certificate.publicKey || '';
await confirmRevocation(name);
const { Count } = await api(deleteCertificates(getDeleteFilter(certificate)));
if (!Count) {
createNotification({
type: 'warning',
// translator: name is arbitrary name given by the user or a random key if not set
text: c('Error notification').t`Certificate ${name} not found or already revoked`,
});
end();
return;
}
delete certificateCache[certificate.publicKeyFingerprint];
setRemovedCertificates([...removedCertificates, certificate.publicKeyFingerprint]);
setCertificates(certificates.filter((c) => c.id !== certificate.id));
revokeCertificate(name);
} catch (e) {
// Abort revocation
} finally {
end();
}
};
const handleFormSubmit = (e: FormEvent) => {
e.preventDefault();
return createWithLogical(bestLogical);
};
const getExtendCallback = (certificate: Certificate) => async () => {
if (creating) {
return;
}
setCreating(true);
try {
const renewedCertificate = await queryCertificate(
certificate.publicKey,
certificate.name,
certificate.features || getFeatureValues(),
{ Renew: true }
);
if (!renewedCertificate.DeviceName) {
renewedCertificate.DeviceName = nameInputRef?.current?.value || '';
}
const newCertificate = getCertificateModel(renewedCertificate, peer, certificate.privateKey);
setCertificates([...(certificates || []), newCertificate]);
setCurrentCertificate(newCertificate.id);
const formattedExpirationDate = readableTime(newCertificate.expirationTime, {
format: 'PPp',
});
createNotification({
// translator: formattedExpirationDate is a date+time such as "Jan 31, 2023, 7:57 PM" with format appropriately localized to match current locale
text: c('Success notification').t`Certificate extended until ${formattedExpirationDate}`,
});
} finally {
setCreating(false);
}
};
useEffect(() => {
fetchUserVPN(30_000);
fetchLogicals(30_000);
}, [hasPaidVpn]);
return (
<SettingsSectionWide>
<SettingsParagraph>
{c('Info').t`These configurations are provided to work with WireGuard routers and official clients.`}
</SettingsParagraph>
{creationModal}
{logicalInfoLoading || certificatesLoading ? (
<div aria-busy="true" className="text-center mb-4">
<CircleLoader />
</div>
) : (
<>
{getCertificates().map((certificate) => {
const name = certificate.name || certificate.publicKeyFingerprint || certificate.publicKey;
const expirationDate = readableTime(certificate.expirationTime);
// translator: expirationDate is a date such as "Dec 11, 2022" (formatted according to current language)
const expirationString = c('Info').t`expires ${expirationDate}`;
const serverName = certificate?.features?.peerName || peer.name;
return (
<Details
data-certificate-id={certificate.id}
key={certificate.id}
open={certificate.id === currentCertificate}
onToggle={getToggleCallback(certificate)}
>
<Summary>
<Row className="flex-justify-space-between" collapseOnMobile={false}>
<div className="text-ellipsis">{name}</div>
<div className="flex-item-noshrink">
{expirationString}
{certificate.serialNumber ||
certificate.publicKeyFingerprint ||
certificate.publicKey ? (
removing[
certificate.publicKeyFingerprint ||
certificate.publicKey ||
certificate.id
] ? (
<CircleLoader />
) : (
<button
type="button"
className="label-stack-item-delete flex-item-noshrink"
onClick={askForRevocation(certificate)}
title={
// translator: name is arbitrary name given by the user or a random key if not set
c('Action').t`Revoke ${name}`
}
>
<Icon
name="cross"
size={12}
className="label-stack-item-delete-icon"
alt={c('Action').t`Revoke`}
/>
</button>
)
) : (
''
)}
</div>
</Row>
</Summary>
<div>
<Button loading={creating} onClick={getExtendCallback(certificate)}>{c('Action')
.t`Extend`}</Button>
{certificate?.config && (
<Button
className="ml-4"
loading={creating}
onClick={getDownloadCallback(certificate)}
>{c('Action').t`Download`}</Button>
)}
<label className="block my-2">
{c('Label').t`Config to connect to ${serverName}`}
<TextArea
className="block mt-2"
value={certificate?.config}
readOnly
rows={14}
/>
</label>
</div>
</Details>
);
})}
{moreToLoad && (
<div aria-busy="true" className="text-center mt-4">
<Button
type="button"
onClick={() => setLimit(limit + paginationSize)}
title={c('Action').t`Load more`}
>{c('Action').t`Load more`}</Button>
</div>
)}
<form onSubmit={handleFormSubmit} className="mt-8">
<h3 className="mt-8 mb-2">{c('Title').t`1. Give a name to the config to be generated`}</h3>
<InputFieldTwo
id="certificate-device-name"
ref={nameInputRef}
label={
<>
{c('Label').t`Device/certificate name`}
<Info
className="ml-1"
title={c('Info')
.t`A name to help you identify where you use it so you can easily revoke it or extend it later.`}
/>
</>
}
placeholder={c('Label').t`Choose a name for the generated certificate file`}
maxLength={100}
/>
<h3 className="mt-8 mb-2">{c('Title').t`2. Select platform`}</h3>
<div className="flex on-mobile-flex-column">
{[
{
value: PLATFORM.ANDROID,
label: c('Option').t`Android`,
},
{
value: PLATFORM.IOS,
label: c('Option').t`iOS`,
},
{
value: PLATFORM.WINDOWS,
label: c('Option').t`Windows`,
},
{
value: PLATFORM.MACOS,
label: c('Option').t`macOS`,
},
{
value: PLATFORM.LINUX,
label: c('Option').t`GNU/Linux`,
},
{
value: PLATFORM.ROUTER,
label: c('Option').t`Router`,
},
].map(({ value, label }) => {
return (
<div key={'wg-' + value} className="mr-8 mb-4">
<Radio
id={'wg-platform-' + value}
onChange={() => setPlatform(value)}
checked={platform === value}
name="platform"
className="flex inline-flex-vcenter mb-2"
>
{label}
</Radio>
</div>
);
})}
</div>
<h3 className="mt-8 mb-2">{c('Title').t`3. Select VPN options`}</h3>
{getFeatureKeys().map((key) => (
<div className="mb-4" key={'wg-feature-' + key}>
<label className="field-two-container w-full" htmlFor={'wg-feature-' + key}>
{isFeatureSelection(featuresConfig[key]) ? (
<>
<div className="flex field-two-label-container flex-justify-space-between flex-nowrap flex-align-items-end">
<span className="field-two-label">
{featuresConfig[key].name}
{getFeatureLink(featuresConfig[key])}
</span>
</div>
<SelectTwo
id={'wg-feature-' + key}
key={'wg-feature-' + key}
value={featuresConfig[key].value}
onValue={(value) => setFeature(key, value)}
>
{(featuresConfig[key] as FeatureSelection).values.map((option) => (
<Option
key={'wg-feature-' + key + '-' + option.value}
title={option.name}
value={option.value}
/>
))}
</SelectTwo>
</>
) : (
<>
<Toggle
key={'feature-' + key}
id={'feature-' + key}
checked={!!featuresConfig[key].value}
onChange={() => setFeature(key, !featuresConfig[key].value)}
/>
{featuresConfig[key].name}
{getFeatureLink(featuresConfig[key])}
</>
)}
</label>
</div>
))}
{logical && (
<>
<h3 className="mt-8 mb-2">{c('Title').t`4. Select a server to connect to`}</h3>
<div className="mb-8">
{bestServerName && (
<>
<p className="mt-0">
{c('Info')
.jt`Use the best server according to current load and position: ${formattedBestServerName}`}
</p>
<div className="mt-4">
<Button type="submit" color="norm" loading={creating}>{c('Action')
.t`Create`}</Button>
</div>
</>
)}
</div>
<p className="my-8">{c('Info').t`Or select a particular server:`}</p>
<OpenVPNConfigurationSection
onSelect={createWithLogical}
selecting={creating}
listOnly={true}
excludedCategories={[CATEGORY.COUNTRY]}
/>
</>
)}
</form>
</>
)}
</SettingsSectionWide>
);
};
export default WireGuardConfigurationSection;
| 6,968
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/WireGuardConfigurationSection/WireGuardCreationModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import {
Form,
Loader,
ModalProps,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
TextArea,
} from '../../../components';
export interface WireGuardCreationModalProps extends ModalProps {
text?: string;
serverName?: string;
config?: string;
onDownload?: () => void;
onClose?: () => void;
}
const WireGuardCreationModal = ({
open,
text,
serverName,
config,
onDownload,
onClose,
}: WireGuardCreationModalProps) => {
const close = () => {
onClose?.();
};
return (
<ModalTwo
as={Form}
open={open}
size="large"
className="contacts-modal"
onSubmit={() => {
onDownload?.();
}}
onClose={close}
>
<ModalTwoHeader title={serverName} />
<ModalTwoContent>
{config ? (
<div className="text-center">
<p>{text}</p>
<TextArea className="block mt-2" value={config} readOnly rows={14} />
</div>
) : (
<div className="text-center">
<p>{
// translator: serverName is code name for a logical server such as NL-FREE#1
c('Success notification').t`Creating config file for ${serverName}`
}</p>
<Loader />
</div>
)}
</ModalTwoContent>
<ModalTwoFooter>
<Button onClick={close}>{c('Action').t`Close`}</Button>
<Button color="norm" type="submit" loading={!config} disabled={!config}>
{c('Action').t`Download`}
</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default WireGuardCreationModal;
| 6,969
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/WireGuardConfigurationSection/api.ts
|
import { PaginationParams } from '@proton/shared/lib/api/interface';
import { CertificateDeletionParams, CertificateGenerationParams } from './Certificate';
export enum CertificateMode {
SESSION = 'session',
PERSISTENT = 'persistent',
}
export interface CertificateListParams extends PaginationParams {
Offset?: number;
Limit?: number;
Sort?: string;
Desc?: 0 | 1;
WithSessions?: 0 | 1;
Mode?: CertificateMode;
BeginID?: string;
}
export const queryVPNClientConfig = () => ({
url: 'vpn/v2/clientconfig',
method: 'get',
});
export const getKey = () => ({
url: 'vpn/v1/certificate/key/EC',
method: 'get',
});
export const generateCertificate = (data: CertificateGenerationParams) => ({
url: 'vpn/v1/certificate',
method: 'post',
data,
});
export const queryCertificates = (params?: CertificateListParams) => ({
url: 'vpn/v1/certificate/all',
method: 'get',
params,
});
export const deleteCertificates = (data: CertificateDeletionParams) => ({
url: 'vpn/v1/certificate',
method: 'delete',
data,
});
| 6,970
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/WireGuardConfigurationSection/curve.ts
|
// Thanks DJB https://ed25519.cr.yp.to
// https://tools.ietf.org/html/rfc8032, https://en.wikipedia.org/wiki/EdDSA
// Includes Ristretto https://ristretto.group
// Curve formula is −x² + y² = 1 − (121665/121666) * x² * y²
export const CURVE = (() => {
try {
return {
// Params: a, b
a: BigInt(-1),
// Equal to -121665/121666 over finite field.
// Negative number is P - number, and division is invert(number, P)
d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
// Finite field 𝔽p over which we'll do calculations
P: BigInt(2) ** BigInt(255) - BigInt(19),
// Subgroup order aka C
n: BigInt(2) ** BigInt(252) + BigInt('27742317777372353535851937790883648493'),
// Cofactor
h: BigInt(8),
// Base point (x, y) aka generator point
Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
};
} catch (e) {
return null;
}
})();
| 6,971
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/WireGuardConfigurationSection/feature.ts
|
import { c } from 'ttag';
export interface FeaturePair<T extends number | boolean = number | boolean> {
name: string;
shortName?: string;
value: T;
transform?: (value: T) => T;
unTransform?: (value: T) => T;
}
export interface FeatureOption<T extends number | boolean = number | boolean> extends FeaturePair<T> {
tier?: number;
url?: string;
}
export interface FeatureSelection<T extends number | boolean = number | boolean> extends FeatureOption<T> {
values: FeaturePair<T>[];
}
export interface FeatureFlagsConfig {
NetShield: boolean;
GuestHoles: boolean;
ServerRefresh: boolean;
StreamingServicesLogos: boolean;
PortForwarding: boolean;
ModerateNAT: boolean;
SafeMode: boolean;
PollNotificationAPI: boolean;
VpnAccelerator: boolean;
SmartReconnect: boolean;
}
export interface FeaturesConfig {
NetShieldLevel: FeatureSelection<number>;
RandomNAT: FeatureOption<boolean>;
PortForwarding: FeatureOption<boolean>;
SplitTCP: FeatureOption<boolean>;
SafeMode: FeatureOption<boolean>;
}
export interface FeaturesValues {
NetShieldLevel?: number;
// PortForwarding?: boolean;
SplitTCP?: boolean;
RandomNAT?: boolean;
SafeMode?: boolean;
}
export const isFeatureSelection = (value: FeatureOption<any>): value is FeatureSelection<any> => {
return 'values' in value;
};
export const initialFeaturesConfig: FeaturesConfig = {
NetShieldLevel: {
tier: 1,
url: 'https://protonvpn.com/support/netshield/',
name: c('Label').t`Level for NetShield blocker filtering`,
shortName: 'NetShield',
value: 1,
values: [
{
name: c('Label').t`No filter`,
value: 0,
},
{
name: c('Label').t`Block malware only`,
value: 1,
},
{
name: c('Label').t`Block malware, ads and trackers`,
value: 2,
},
],
},
RandomNAT: {
tier: 1,
name: c('Label').t`Moderate NAT`,
url: 'https://protonvpn.com/support/moderate-nat',
value: false,
transform: (value) => !value,
unTransform: (value) => !value,
},
PortForwarding: {
name: c('Label').t`NAT-PMP (Port Forwarding)`,
url: 'https://protonvpn.com/support/port-forwarding',
value: false,
},
SplitTCP: {
name: c('Label').t`VPN Accelerator`,
url: 'https://protonvpn.com/blog/vpn-accelerator/',
value: true,
},
SafeMode: {
tier: 1,
name: c('Label').t`Non-standard ports`,
url: 'https://protonvpn.com/support/non-standard-ports',
value: false,
transform: (value) => !value,
unTransform: (value) => !value,
},
};
export const clientConfigKeys = {
NetShieldLevel: 'NetShield',
RandomNAT: 'ModerateNAT',
PortForwarding: 'PortForwarding',
SplitTCP: 'VpnAccelerator',
SafeMode: 'SafeMode',
} as Record<keyof FeaturesConfig, keyof FeatureFlagsConfig>;
export const formatFeatureValue = <T extends Partial<FeaturesValues>, K extends keyof T>(
features: T | undefined,
key: K
): string | T[K] | undefined => {
const value = `${(
(initialFeaturesConfig?.[key as any as keyof FeaturesConfig]?.unTransform || ((v: any) => v)) as <T>(
value: T
) => T
)(features?.[key])}`;
return { true: 'on', false: 'off' }[value] || value;
};
export const getKeyOfCheck = <T>(keys: (keyof T)[]): (<K extends keyof T>(key: any) => key is K) =>
((key: any) => keys.indexOf(key) !== -1) as any;
export const formatFeatureShortName = (key: keyof FeaturesValues) =>
initialFeaturesConfig[key]?.shortName || initialFeaturesConfig[key]?.name || key;
| 6,972
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/WireGuardConfigurationSection/normalize.ts
|
export const normalize = (str: string) => {
const replacements: [string, RegExp][] = [
[
'A',
/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g,
],
['AA', /[\uA732]/g],
['AE', /[\u00C6\u01FC\u01E2]/g],
['AO', /[\uA734]/g],
['AU', /[\uA736]/g],
['AV', /[\uA738\uA73A]/g],
['AY', /[\uA73C]/g],
['B', /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g],
['C', /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g],
['D', /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g],
['DZ', /[\u01F1\u01C4]/g],
['Dz', /[\u01F2\u01C5]/g],
[
'E',
/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g,
],
['F', /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g],
['G', /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g],
['H', /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g],
[
'I',
/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g,
],
['J', /[\u004A\u24BF\uFF2A\u0134\u0248]/g],
['K', /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g],
[
'L',
/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g,
],
['LJ', /[\u01C7]/g],
['Lj', /[\u01C8]/g],
['M', /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g],
['N', /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g],
['NJ', /[\u01CA]/g],
['Nj', /[\u01CB]/g],
[
'O',
/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g,
],
['OI', /[\u01A2]/g],
['OO', /[\uA74E]/g],
['OU', /[\u0222]/g],
['P', /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g],
['Q', /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g],
[
'R',
/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g,
],
[
'S',
/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g,
],
['T', /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g],
['TZ', /[\uA728]/g],
[
'U',
/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g,
],
['V', /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g],
['VY', /[\uA760]/g],
['W', /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g],
['X', /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g],
['Y', /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g],
['Z', /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g],
[
'a',
/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g,
],
['aa', /[\uA733]/g],
['ae', /[\u00E6\u01FD\u01E3]/g],
['ao', /[\uA735]/g],
['au', /[\uA737]/g],
['av', /[\uA739\uA73B]/g],
['ay', /[\uA73D]/g],
['b', /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g],
['c', /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g],
['d', /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g],
['dz', /[\u01F3\u01C6]/g],
[
'e',
/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g,
],
['f', /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g],
['g', /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g],
['h', /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g],
['hv', /[\u0195]/g],
[
'i',
/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g,
],
['j', /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g],
['k', /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g],
[
'l',
/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g,
],
['lj', /[\u01C9]/g],
['m', /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g],
[
'n',
/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g,
],
['nj', /[\u01CC]/g],
[
'o',
/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g,
],
['oi', /[\u01A3]/g],
['ou', /[\u0223]/g],
['oo', /[\uA74F]/g],
['p', /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g],
['q', /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g],
[
'r',
/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g,
],
[
's',
/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g,
],
['t', /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g],
['tz', /[\uA729]/g],
[
'u',
/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g,
],
['v', /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g],
['vy', /[\uA761]/g],
['w', /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g],
['x', /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g],
['y', /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g],
['z', /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g],
['-', /[#]+/g],
['_', /[^A-Za-z0-9-]+/g],
];
replacements.forEach(([letters, regExp]) => {
str = str.replace(regExp, letters);
});
return str;
};
| 6,973
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/WireGuardConfigurationSection/useCertificates.ts
|
import { useEffect, useState } from 'react';
import { useApiResult } from '../../../hooks';
import { CertificateDTO } from './Certificate';
import { CertificateMode, queryCertificates } from './api';
type ReplaceReturnType<T extends (...a: any) => any, TNewReturn> = (...a: Parameters<T>) => TNewReturn;
interface ApiResult {
Certificates: CertificateDTO[];
Total?: number;
}
interface Result {
result: CertificateDTO[];
error: Error;
loading: boolean;
request: ReplaceReturnType<typeof queryCertificates, Promise<ApiResult>>;
moreToLoad: boolean;
}
const chunkSize = 51;
const seedCertificates = (
certificatesResult: CertificateDTO[],
certificateCache: Record<string, CertificateDTO>
): CertificateDTO[] => {
certificatesResult.forEach((certificateDto) => {
if (
certificateDto.Mode === 'persistent' &&
certificateDto.ExpirationTime >=
(certificateCache[certificateDto.ClientKeyFingerprint]?.ExpirationTime || 0)
) {
certificateCache[certificateDto.ClientKeyFingerprint] = certificateDto;
}
});
return Object.values(certificateCache);
};
const useCertificates = (limit: number = chunkSize): Result => {
const [certificateCache] = useState<Record<string, CertificateDTO>>({});
const [beginId, setBeginId] = useState<string | undefined>(undefined);
const [offset, setOffset] = useState(0);
const [currentState, setCurrentState] = useState('');
const [done, setDone] = useState(false);
const [responses, setResponses] = useState<ApiResult[]>([]);
const { loading, result, error, request } = useApiResult<ApiResult, typeof queryCertificates>(
() =>
queryCertificates({
Mode: CertificateMode.PERSISTENT,
Offset: offset,
Limit: chunkSize,
BeginID: beginId,
}),
[beginId, offset]
);
if (error) {
// Throw in render to allow the error boundary to catch it
throw error;
}
if (result && responses.indexOf(result) === -1) {
setResponses([...responses, result]);
}
useEffect(() => {
let certificates = Object.values(certificateCache);
const newState = limit + '|' + offset + '|' + beginId + '|' + responses.length;
if (currentState !== newState && !loading) {
if (!result || certificates.length >= limit) {
setCurrentState(newState);
} else if (result) {
const newCertificates = result.Certificates || [];
const finished = newCertificates.length === (result.Total || 0) || newCertificates.length < chunkSize;
if (finished) {
setDone(true);
setCurrentState(newState);
}
if (newCertificates.length) {
seedCertificates(newCertificates, certificateCache);
certificates = Object.values(certificateCache);
if (!finished) {
// is new API
if ('Total' in result) {
setBeginId(newCertificates[newCertificates.length - 1].SerialNumber);
} else {
setOffset(offset + newCertificates.length);
}
}
}
if (certificates.length >= limit) {
setCurrentState(newState);
}
}
}
}, [loading, limit]);
const certificates = Object.values(certificateCache);
return {
result: certificates.slice(0, limit),
error,
loading,
request,
moreToLoad: !loading && (!done || certificates.length > limit),
};
};
export default useCertificates;
| 6,974
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/ButtonNumberInput.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { Icon } from '@proton/components/components';
import clsx from '@proton/utils/clsx';
export const ButtonNumberInput = ({
value,
onChange,
id,
min = 0,
max = 999,
step = 1,
disabled = false,
}: {
step?: number;
id: string;
min?: number;
max?: number;
value: number;
disabled?: boolean;
onChange?: (newValue: number) => void;
}) => {
const [tmpValue, setTmpValue] = useState<number | undefined>(value);
const getIsValidValue = (newValue?: number) => {
return newValue !== undefined && newValue >= min && newValue <= max && newValue % step === 0;
};
const isDecDisabled = disabled || !getIsValidValue((tmpValue || 0) - step);
const isIncDisabled = disabled || !getIsValidValue((tmpValue || 0) + step);
const isValidTmpValue = getIsValidValue(tmpValue);
return (
<div className="border rounded flex-item-noshrink flex flex-nowrap">
<button
type="button"
title={c('Action').t`Decrease`}
className={clsx(['p-2 flex', isDecDisabled && 'color-disabled'])}
disabled={isDecDisabled}
onClick={() => {
if (!isValidTmpValue || tmpValue === undefined) {
return;
}
const newValue = tmpValue - step;
setTmpValue?.(newValue);
onChange?.(newValue);
}}
>
<Icon name="minus" alt={c('Action').t`Decrease`} className="m-auto" />
</button>
<label htmlFor={id} className="my-2 flex">
<input
autoComplete="off"
min={min}
max={max}
value={tmpValue}
id={id}
className="w-custom border-left border-right text-center"
style={{ '--w-custom': '6em' }}
onBlur={() => {
if (!isValidTmpValue) {
// Revert to the latest valid value upon blur
setTmpValue(value);
}
}}
onChange={({ target: { value: newValue } }) => {
if (newValue === '') {
setTmpValue?.(undefined);
return;
}
const newIntValue = parseInt(newValue, 10);
setTmpValue?.(newIntValue);
if (getIsValidValue(newIntValue)) {
onChange?.(newIntValue);
}
}}
/>
</label>
<button
type="button"
title={c('Action').t`Increase`}
className={clsx(['p-2 flex', isIncDisabled && 'color-disabled'])}
disabled={isIncDisabled}
onClick={() => {
if (!isValidTmpValue || tmpValue === undefined) {
return;
}
const newValue = tmpValue + step;
setTmpValue?.(newValue);
onChange?.(newValue);
}}
>
<Icon name="plus" alt={c('Action').t`Increase`} className="m-auto" />
</button>
</div>
);
};
| 6,975
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/Gateway.ts
|
import { GatewayLogical } from './GatewayLogical';
import { GatewayUser } from './GatewayUser';
export interface Gateway {
Name: string;
ExitCountry: string;
Logicals: GatewayLogical[];
Users: GatewayUser[];
}
| 6,976
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayAddServersModal.tsx
|
import { useMemo, useState } from 'react';
import { c, msgid } from 'ttag';
import { Button } from '@proton/atoms';
import { Form, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '@proton/components/components';
import { GatewayCountrySelection } from './GatewayCountrySelection';
import { GatewayDto } from './GatewayDto';
import { GatewayUser } from './GatewayUser';
import { getInitialModel } from './helpers';
import { useAddedQuantities } from './useAddedQuantities';
import { useSpecificCountryCount } from './useSpecificCountryCount';
interface Props {
countries: readonly string[];
deletedInCountries: Record<string, number>;
ownedCount: number;
usedCount: number;
users: readonly GatewayUser[];
language: string | readonly string[];
singleServer?: boolean;
showCancelButton?: boolean;
onSubmitDone: (quantities: Record<string, number>) => void;
onResolve: () => void;
onReject: () => void;
onUpsell: () => void;
}
const GatewayAddServersModal = ({
countries,
deletedInCountries,
ownedCount,
usedCount,
users,
language,
onSubmitDone,
onReject,
onResolve,
onUpsell,
singleServer = false,
showCancelButton = false,
...rest
}: Props) => {
const [model, setModel] = useState(getInitialModel(countries));
const remainingCount = useMemo(() => ownedCount - usedCount, [ownedCount, usedCount]);
const numberOfAddedServers = useAddedQuantities(model);
const totalCountExceeded = useMemo(
() => numberOfAddedServers > remainingCount,
[numberOfAddedServers, remainingCount]
);
const specificCountryCount = useSpecificCountryCount(model, remainingCount, deletedInCountries);
const needUpsell = useMemo(
() => totalCountExceeded || specificCountryCount > 0,
[totalCountExceeded, specificCountryCount]
);
const changeModel = <V extends GatewayDto[K], K extends keyof GatewayDto = keyof GatewayDto>(key: K, value: V) =>
setModel((model: GatewayDto) => ({ ...model, [key]: key === 'features' ? Number(value) : value }));
const handleSubmit = async () => {
onSubmitDone(model.quantities || {});
onResolve();
};
return (
<ModalTwo size="large" as={Form} onSubmit={handleSubmit} onClose={onReject} {...rest}>
<ModalTwoHeader title={c('Title').t`Add servers`} />
<ModalTwoContent>
<GatewayCountrySelection
singleServer={singleServer}
countries={countries}
ownedCount={ownedCount}
usedCount={usedCount}
addedCount={numberOfAddedServers}
needUpsell={needUpsell}
specificCountryCount={specificCountryCount}
language={language}
onUpsell={() => {
onReject();
onUpsell();
}}
model={model}
changeModel={changeModel}
/>
</ModalTwoContent>
<ModalTwoFooter>
{showCancelButton ? (
<Button color="weak" onClick={onReject}>
{c('Action').t`Cancel`}
</Button>
) : (
<div />
)}
{!needUpsell && numberOfAddedServers >= 1 ? (
<Button color="norm" type="submit">
{c('Feature').ngettext(
msgid`Add (${numberOfAddedServers})`,
`Add (${numberOfAddedServers})`,
numberOfAddedServers
)}
</Button>
) : (
<Button color="norm" type="submit" disabled>
{c('Feature').t`Add`}
</Button>
)}
</ModalTwoFooter>
</ModalTwo>
);
};
export default GatewayAddServersModal;
| 6,977
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayCountrySelection.tsx
|
import { c, msgid } from 'ttag';
import { Button } from '@proton/atoms';
import { Field, Icon, Label, Option, Row, SelectTwo } from '@proton/components/components';
import { SelectChangeEvent } from '@proton/components/components/selectTwo/select';
import { vpnEnterpriseContactUrl } from '@proton/components/containers/payments/subscription/helpers';
import { getLocalizedCountryByAbbr } from '@proton/components/helpers/countries';
import { MAX_IPS_ADDON } from '@proton/shared/lib/constants';
import { ButtonNumberInput } from './ButtonNumberInput';
import { GatewayDto } from './GatewayDto';
import { getCountryFlagAndName } from './getCountryFlagAndName';
interface Props {
singleServer: boolean;
countries: readonly string[];
ownedCount: number;
usedCount: number;
addedCount: number;
language: string | readonly string[];
onUpsell: () => void;
specificCountryCount: number;
loading?: boolean;
needUpsell: boolean;
model: GatewayDto;
changeModel: <V extends GatewayDto[K], K extends keyof GatewayDto = keyof GatewayDto>(key: K, value: V) => void;
}
export const GatewayCountrySelection = ({
singleServer,
countries,
ownedCount,
usedCount,
addedCount,
language,
onUpsell,
loading = false,
needUpsell,
specificCountryCount,
model,
changeModel,
}: Props) => {
const remainingCount = ownedCount - usedCount;
const availableCount = Math.max(0, remainingCount - addedCount);
const totalCountExceeded = addedCount > remainingCount;
const canBuyMore = ownedCount < MAX_IPS_ADDON;
const handleCountryChange = ({ value }: SelectChangeEvent<string>) => changeModel('country', value);
return singleServer ? (
<Row>
<Label htmlFor="domain">{c('Label').t`Country`}</Label>
<Field>
<SelectTwo value={model.country} onChange={handleCountryChange}>
{countries.map((country) => (
<Option
key={country}
value={country}
title={getLocalizedCountryByAbbr(country, language) || country}
>
{getCountryFlagAndName(language, country, undefined, {
key: country + '-country-option-image',
})}
</Option>
))}
</SelectTwo>
</Field>
</Row>
) : (
<>
<p className="mb-2">
{c('Info').ngettext(
msgid`You have ${availableCount} dedicated server available.`,
`You have ${availableCount} dedicated servers available.`,
availableCount
)}
</p>
{countries.map((country) => (
<div
key={'country-' + country}
className="flex-no-min-children flex-nowrap flex-align-items-center mb-4 on-mobile-flex-wrap"
>
<Label htmlFor={'country-number-' + country} className="flex-item-fluid">
{getCountryFlagAndName(language, country, undefined, {
key: country + '-country-label-image',
})}
</Label>
<ButtonNumberInput
id={'country-number-' + country}
value={model.quantities?.[country] || 0}
min={0}
max={99}
disabled={loading}
onChange={(newQuantity) => {
const quantities = {
...model.quantities,
[country]: newQuantity,
};
const mainCountry = Object.keys(quantities).reduce(
(previous, country) =>
(quantities[country] || 0) > (quantities[previous] || 0) ? country : previous,
'US'
);
if (mainCountry !== model.country) {
changeModel('country', mainCountry);
}
changeModel('quantities', quantities);
}}
step={1}
/>
</div>
))}
<Row>
{c('Info').t`Want servers in other countries?`}
<a href={vpnEnterpriseContactUrl} className="ml-1">{c('Link').t`Contact us`}</a>
</Row>
{needUpsell && (
<>
<Row className="rounded p-2 bg-info">
<div className="flex-item-noshrink">
<Icon name="info-circle" />
</div>
<div className="ml-2">
{totalCountExceeded ? (
c('Info')
.t`Number of dedicated servers you try to assign (${addedCount}) is more than what is still available in your plan (${remainingCount}) as you own ${ownedCount} and you already use ${usedCount}.`
) : (
<>
<div>{c('Info')
.t`Some of your available servers can only be used in specific countries due to recent removals`}</div>
<div className="mt-3">
{c('Info')
.t`You can immediately unlock the setup above by adding ${specificCountryCount} to the number of IP addresses in your plan or reach us for tailor-made solutions.`}
<a href={vpnEnterpriseContactUrl} className="ml-1">{c('Link').t`Contact us`}</a>
</div>
</>
)}
</div>
</Row>
<Row>
{canBuyMore && (
<Button
color="norm"
onClick={onUpsell}
title={c('Title').t`Customize the number of IP addresses in your plan`}
>
{c('Action').t`Get more servers`}
</Button>
)}
</Row>
</>
)}
<Row className="rounded p-2 bg-weak">
<div className="flex-item-noshrink">
<Icon name="info-circle" />
</div>
<div className="ml-2">
{c('Info').t`We recommend having multiple servers in different locations to provide redundancy.`}
</div>
</Row>
</>
);
};
export default GatewayCountrySelection;
| 6,978
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayDto.ts
|
export interface GatewayDto {
name?: string;
country: string;
quantities?: Record<string, number>;
features: number;
userIds: readonly string[];
}
| 6,979
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayIpModel.ts
|
export interface GatewayIpModel {
Name: string;
Country: string;
}
| 6,980
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayLogical.ts
|
import { GatewayServer } from './GatewayServer';
export interface GatewayLogical {
ID: string;
Name: string;
EntryCountry: string;
ExitCountry: string;
HostCountry: string | null;
Region: string | null;
City: string;
Features: number; // bitmap
Location: { Lat: number; Long: number };
Users: string[];
Servers: GatewayServer[];
Visible: boolean;
}
| 6,981
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayManageButton.tsx
|
import { c, msgid } from 'ttag';
import {
Dropdown,
DropdownButton,
DropdownMenu,
DropdownMenuButton,
Icon,
usePopperAnchor,
} from '@proton/components/components';
import { Gateway } from './Gateway';
import { GatewayLogical } from './GatewayLogical';
interface Props {
gateway: Gateway;
logical: GatewayLogical;
deleted: boolean;
deletingLogicals: readonly string[];
deletedLogicals: Record<string, boolean>;
renameGateway: (id: string, name: string) => () => any;
editGatewayServers: (gateway: Gateway, logical: GatewayLogical) => () => any;
editGatewayUsers: (gateway: Gateway, logical: GatewayLogical) => () => any;
deleteGateway: (gateway: Gateway) => () => any;
}
export const GatewayManageButton = ({
gateway,
logical,
renameGateway = () => () => {},
editGatewayServers = () => () => {},
editGatewayUsers = () => () => {},
deleteGateway = () => () => {},
deletingLogicals,
deletedLogicals,
deleted = false,
}: Props) => {
const deleteServerTitle = (() => {
const days = 7;
return c('Title').ngettext(
msgid`Delete the server (you will still be able to recover it for ${days} day)`,
`Delete the server (you will still be able to recover it for ${days} days)`,
days
);
})();
const loading = deletingLogicals.indexOf(logical.ID) !== -1;
const disabled = Boolean(deletedLogicals[logical.ID]);
const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>();
return (
<>
<DropdownButton
ref={anchorRef}
isOpen={isOpen}
onClick={toggle}
icon
title={c('Title').t`Open actions dropdown`}
size="small"
>
<Icon name="three-dots-vertical" />
</DropdownButton>
<Dropdown isOpen={isOpen} anchorRef={anchorRef} onClose={close} originalPlacement="bottom-end">
<DropdownMenu>
<DropdownMenuButton
className="text-left"
loading={loading}
disabled={disabled}
onClick={renameGateway(logical.ID, logical.Name.replace(/#\d+$/, '').replace(/-\d+$/, ''))}
title={c('Title').t`Rename the gateway`}
>
<Icon name="pen" className="mr-2" />
{c('Action').t`Edit name`}
</DropdownMenuButton>
<DropdownMenuButton
className="text-left"
loading={loading}
disabled={disabled}
onClick={editGatewayServers(gateway, logical)}
title={c('Title').t`Edit the list of servers of the gateway`}
>
<Icon name="servers" className="mr-2" />
{c('Action').t`Edit servers`}
</DropdownMenuButton>
<DropdownMenuButton
className="text-left"
loading={loading}
disabled={disabled}
onClick={editGatewayUsers(gateway, logical)}
title={c('Title').t`Edit who can access the gateway`}
>
<Icon name="users" className="mr-2" />
{c('Action').t`Edit users`}
</DropdownMenuButton>
{!deleted && (
<>
<div className="dropdown-item-hr" key="hr-more-options" />
<DropdownMenuButton
className="text-left color-danger"
loading={loading}
onClick={deleteGateway(gateway)}
title={deleteServerTitle}
>
<Icon name="trash" className="mr-2" />
{c('Action').t`Delete`}
</DropdownMenuButton>
</>
)}
</DropdownMenu>
</Dropdown>
</>
);
};
export default GatewayManageButton;
| 6,982
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayModal.tsx
|
import { useMemo, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import {
Form,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
useFormErrors,
} from '@proton/components/components';
import { GatewayCountrySelection } from './GatewayCountrySelection';
import { GatewayDto } from './GatewayDto';
import { GatewayModel } from './GatewayModel';
import { GatewayNameField } from './GatewayNameField';
import { GatewayUser } from './GatewayUser';
import { GatewayUserSelection } from './GatewayUserSelection';
import { getInitialModel } from './helpers';
import { useAddedQuantities } from './useAddedQuantities';
import { useSpecificCountryCount } from './useSpecificCountryCount';
interface Props {
countries: readonly string[];
deletedInCountries: Record<string, number>;
ownedCount: number;
usedCount: number;
users: readonly GatewayUser[];
language: string | readonly string[];
isEditing?: boolean;
singleServer?: boolean;
showCancelButton?: boolean;
onSubmitDone: (server: GatewayModel) => Promise<void>;
onResolve: () => void;
onReject: () => void;
onUpsell: () => void;
}
enum STEP {
NAME,
COUNTRIES,
MEMBERS,
}
const GatewayModal = ({
countries,
deletedInCountries,
ownedCount,
usedCount,
users,
language,
onSubmitDone,
onReject,
onResolve,
onUpsell,
isEditing = false,
singleServer = false,
showCancelButton = false,
...rest
}: Props) => {
const { validator, onFormSubmit } = useFormErrors();
const [step, setStep] = useState(STEP.NAME);
const [model, setModel] = useState(getInitialModel(countries));
const [loading, setLoading] = useState(false);
const remainingCount = useMemo(() => ownedCount - usedCount, [ownedCount, usedCount]);
const addedCount = useAddedQuantities(model);
const totalCountExceeded = useMemo(() => addedCount > remainingCount, [addedCount, remainingCount]);
const specificCountryCount = useSpecificCountryCount(model, remainingCount, deletedInCountries);
const needUpsell = useMemo(
() => totalCountExceeded || specificCountryCount > 0,
[totalCountExceeded, specificCountryCount]
);
const canContinue = useMemo(
() => step !== STEP.COUNTRIES || !(needUpsell || (!singleServer && addedCount < 1)),
[step, needUpsell, singleServer, addedCount]
);
const changeModel = <V extends GatewayDto[K], K extends keyof GatewayDto = keyof GatewayDto>(key: K, value: V) =>
setModel((model: GatewayDto) => ({ ...model, [key]: key === 'features' ? Number(value) : value }));
const stepBack = () => {
if (step === STEP.MEMBERS) {
setStep(countries.length > 1 ? STEP.COUNTRIES : STEP.NAME);
return;
}
if (step === STEP.COUNTRIES) {
setStep(STEP.NAME);
return;
}
onReject();
};
const handleSubmit = async () => {
if (!onFormSubmit()) {
return;
}
if (step === STEP.NAME) {
setStep(countries.length > 1 ? STEP.COUNTRIES : STEP.MEMBERS);
return;
}
if (step === STEP.COUNTRIES) {
setStep(STEP.MEMBERS);
return;
}
const quantities: Record<string, number> = {};
let total = 0;
Object.keys(model.quantities || {}).forEach((country) => {
const count = model.quantities?.[country] || 0;
if (count > 0) {
quantities[country] = count;
total += count;
}
});
const dtoBody: GatewayModel =
singleServer || total === 1
? {
Name: model.name,
Country: model.country,
Features: model.features,
UserIds: model.userIds,
}
: {
Name: model.name,
Features: model.features,
UserIds: model.userIds,
Quantities: quantities,
};
try {
setLoading(true);
await onSubmitDone(dtoBody);
onResolve();
} finally {
setLoading(false);
}
};
return (
<ModalTwo
size={step === STEP.MEMBERS ? 'xlarge' : 'large'}
as={Form}
onSubmit={handleSubmit}
onClose={onReject}
{...rest}
>
<ModalTwoHeader
title={(() => {
if (step === STEP.NAME) {
return isEditing ? c('Action').t`Edit Gateway` : c('Title').t`Create Gateway`;
}
if (step === STEP.COUNTRIES) {
return c('Title').t`Add servers`;
}
return c('Title').t`Add users`;
})()}
/>
<ModalTwoContent>
{step === STEP.NAME && (
<GatewayNameField model={model} changeModel={changeModel} validator={validator} />
)}
{step === STEP.COUNTRIES && (
<GatewayCountrySelection
singleServer={singleServer}
countries={countries}
ownedCount={ownedCount}
usedCount={usedCount}
addedCount={addedCount}
needUpsell={needUpsell}
specificCountryCount={specificCountryCount}
language={language}
onUpsell={() => {
onReject();
onUpsell();
}}
loading={loading}
model={model}
changeModel={changeModel}
/>
)}
{step === STEP.MEMBERS && (
<GatewayUserSelection loading={loading} users={users} model={model} changeModel={changeModel} />
)}
</ModalTwoContent>
<ModalTwoFooter>
{showCancelButton || step !== STEP.NAME ? (
<Button color="weak" onClick={stepBack}>
{step === STEP.NAME
? c('Action').t`Cancel`
: /* button to go back to previous step of gateway creation */ c('Action').t`Back`}
</Button>
) : (
<div />
)}
<Button color="norm" type="submit" loading={loading} disabled={!canContinue}>
{step === STEP.MEMBERS
? /* final step submit button of the creation, if not clean translation possible, it can also simply be "Create" */ c(
'Action'
).t`Done`
: /* button to continue to the next step of gateway creation */ c('Action').t`Continue`}
</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default GatewayModal;
| 6,983
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayModel.ts
|
export interface GatewayModel {
Name?: string;
Country?: string;
Features?: number;
UserIds?: readonly string[] | null;
Quantities?: Record<string, number>;
}
| 6,984
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayNameField.tsx
|
import { ChangeEvent } from 'react';
import { c } from 'ttag';
import { InputFieldTwo } from '@proton/components/components';
import { maxLengthValidator, minLengthValidator, requiredValidator } from '@proton/shared/lib/helpers/formValidators';
import { GatewayDto } from './GatewayDto';
type FormInput = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
type GatewayName = Pick<GatewayDto, 'name'>;
interface Props {
model: GatewayName;
changeModel: <V extends GatewayName[K], K extends keyof GatewayName = keyof GatewayName>(key: K, value: V) => void;
validator: (validations: string[]) => string;
}
export const GatewayNameField = ({ model, changeModel, validator }: Props) => {
const handleTextFieldChange =
<T extends keyof GatewayName>(key: T, transformer?: (value: GatewayName[T]) => GatewayName[T]) =>
({ target }: ChangeEvent<FormInput>) =>
changeModel(
key,
transformer ? transformer(target.value as GatewayName[T]) : (target.value as GatewayName[T])
);
const noSpaceMessage = c('Info').t`Must not contain spaces.`;
const formatMessage = c('Info').t`Must contain only letters, digits, and dashes (-).`;
const startWithLetterMessage = c('Info').t`Must start with a letter.`;
const gatewayNameNoSpaceValidator = (value: string) => (/\s/.test(value) ? noSpaceMessage : '');
const gatewayNameStartWithLetterValidator = (value: string) => (/^[A-Z]/.test(value) ? '' : startWithLetterMessage);
const gatewayNameValidator = (value: string) => (/^[A-Z][A-Z0-9-]+$/.test(value) ? '' : formatMessage);
const name = model.name || '';
return (
<>
<InputFieldTwo
autoFocus
label={c('Label').t`Gateway name`}
placeholder="MY-COMPANY-OFFICE"
value={name}
onChange={handleTextFieldChange('name', (v) => v?.toUpperCase())}
error={validator([
requiredValidator(name),
minLengthValidator(name, 3),
maxLengthValidator(name, 20),
gatewayNameStartWithLetterValidator(name),
gatewayNameNoSpaceValidator(name),
gatewayNameValidator(name),
])}
/>
<div>
<ul className="pl-4 mt-2 color-weak">
<li>{c('Info').t`Must be between 3 and 20 characters long.`}</li>
<li>{startWithLetterMessage}</li>
<li>{formatMessage}</li>
<li>{noSpaceMessage}</li>
</ul>
</div>
</>
);
};
export default GatewayNameField;
| 6,985
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayRenameModal.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import {
Form,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
useFormErrors,
} from '@proton/components/components';
import { GatewayDto } from './GatewayDto';
import { GatewayNameField } from './GatewayNameField';
interface Props {
currentName: string;
showCancelButton?: boolean;
onSubmitDone: (server: { Name: string }) => Promise<void>;
onResolve: () => void;
onReject: () => void;
}
const GatewayRenameModal = ({
currentName,
showCancelButton = false,
onSubmitDone,
onReject,
onResolve,
...rest
}: Props) => {
const { validator, onFormSubmit } = useFormErrors();
const [model, setModel] = useState({
name: '',
} as GatewayDto);
const [loading, setLoading] = useState(false);
const changeModel = <V extends GatewayDto[K], K extends keyof GatewayDto = keyof GatewayDto>(key: K, value: V) =>
setModel((model: GatewayDto) => ({ ...model, [key]: value }));
const handleSubmit = async () => {
if (!onFormSubmit()) {
return;
}
const dtoBody = {
Name: model.name || '',
};
try {
setLoading(true);
await onSubmitDone(dtoBody);
onResolve();
} finally {
setLoading(false);
}
};
return (
<ModalTwo size="large" {...rest} as={Form} onSubmit={handleSubmit} onClose={onReject}>
<ModalTwoHeader title={c('Title').t`Edit Gateway ${currentName}`} />
<ModalTwoContent>
<GatewayNameField model={model} changeModel={changeModel} validator={validator} />
</ModalTwoContent>
<ModalTwoFooter>
{showCancelButton ? (
<Button color="weak" onClick={onReject}>
{c('Action').t`Cancel`}
</Button>
) : (
<div />
)}
<Button color="norm" type="submit" loading={loading}>
{c('Action').t`Rename`}
</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default GatewayRenameModal;
| 6,986
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayRow.tsx
|
import { c, msgid } from 'ttag';
import { Copy, TableRow } from '@proton/components/components';
import { useNotifications } from '@proton/components/hooks';
import clsx from '@proton/utils/clsx';
import { Gateway } from './Gateway';
import { GatewayLogical } from './GatewayLogical';
import GatewayManageButton from './GatewayManageButton';
import { GatewayServer } from './GatewayServer';
import { GatewayUser } from './GatewayUser';
import { getCountryFlagAndName } from './getCountryFlagAndName';
import { getFormattedLoad, getMembers, getSuffix } from './helpers';
interface Props {
isAdmin: boolean;
showDeleted?: boolean;
showIPv4?: boolean;
showIPv6?: boolean;
showLoad?: boolean;
gateway: Gateway;
isDeleted: (logical: GatewayLogical) => boolean;
users: readonly GatewayUser[];
language: string | readonly string[];
provisioningDuration: string;
deletingLogicals: readonly string[];
deletedLogicals: Record<string, boolean>;
renameGateway: (id: string, name: string) => () => any;
editGatewayServers: (gateway: Gateway, logical: GatewayLogical) => () => any;
editGatewayUsers: (gateway: Gateway, logical: GatewayLogical) => () => any;
deleteGateway: (gateway: Gateway) => () => any;
}
export const GatewayRow = ({
isAdmin,
showDeleted,
showIPv4,
showIPv6,
showLoad,
gateway,
isDeleted,
users,
language,
provisioningDuration,
renameGateway,
editGatewayServers,
editGatewayUsers,
deleteGateway,
deletingLogicals,
deletedLogicals,
}: Props) => {
const { createNotification } = useNotifications();
let provisioningCounter = 0;
const allLogicals = gateway.Logicals || [];
const deleted = allLogicals.every(isDeleted);
if (deleted && !showDeleted) {
return <></>;
}
const logicals = allLogicals.filter((logical) => {
if (isDeleted(logical)) {
return false;
}
if (!logical.Servers?.length) {
provisioningCounter++;
return false;
}
return true;
});
const provisionedLogicals = [...logicals.filter((l) => l.Visible), ...logicals.filter((l) => !l.Visible)];
const hasPendingServers = provisioningCounter > 0;
const main = provisionedLogicals[0] || allLogicals[0];
const [statusClasses, statusText] = provisionedLogicals.length
? ['bg-success', /** translator: status of the gateway: people can connect to it */ c('Info').t`active`]
: [
'bg-weak color-weak',
/** translator: status of the gateway: people cannot connect to it */ c('Info').t`inactive`,
];
const getIpsCell = (servers: GatewayServer[]) =>
servers[0]
? [
...(showIPv4 ? [servers[0].ExitIPv4] : []),
...(showIPv6 ? [servers[0].ExitIPv6] : []),
...(showLoad ? [getFormattedLoad(servers)] : []),
].join(', ')
: c('Action').t`Your server will be provisioned in the next days`;
return (
<TableRow
className={deleted ? 'opacity-50' : undefined}
cells={[
gateway.Name,
<span className={clsx(['py-1 px-2 rounded text-uppercase', statusClasses])}>{statusText}</span>,
<div>
{provisionedLogicals.length < 1 && !hasPendingServers && '0'}
{provisionedLogicals.map((logical) => (
<div key={'logical-' + logical.ID}>
<span className="text-nowrap bg-weak py-1 px-2 rounded">
{getCountryFlagAndName(language, logical.ExitCountry, getSuffix(logical.Name), {
className: 'mb-1',
key: 'country-logical-' + logical.ID + '-' + logical.ExitCountry,
})}
<span className="color-weak"> • </span>
{getIpsCell(logical.Servers)}
<Copy
value={logical.Servers[0].ExitIPv4}
shape="ghost"
onCopy={() => {
createNotification({
text: c('Notification').t`IP Address copied to clipboard`,
});
}}
/>
</span>
</div>
))}
{hasPendingServers && (
<div className="color-weak">
{c('Info').ngettext(
msgid`${provisioningCounter} server is still being set up. This usually takes around ${provisioningDuration}.`,
`${provisioningCounter} servers are still being set up. This usually takes around ${provisioningDuration}.`,
provisioningCounter
)}
</div>
)}
</div>,
...(isAdmin
? [
getMembers(users, main),
<GatewayManageButton
gateway={gateway}
logical={main}
renameGateway={renameGateway}
editGatewayServers={editGatewayServers}
editGatewayUsers={editGatewayUsers}
deleteGateway={deleteGateway}
deletingLogicals={deletingLogicals}
deletedLogicals={deletedLogicals}
deleted={deleted}
/>,
]
: []),
]}
/>
);
};
export default GatewayRow;
| 6,987
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayServer.ts
|
export interface GatewayServer {
ID: string;
Domain: string;
Label: string;
Enabled: boolean;
EntryIPv4: string;
EntryIPv6: string | null;
ExitIPv4: string;
ExitIPv6: string | null;
Load: number;
}
| 6,988
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayServersModal.tsx
|
import React, { useState } from 'react';
import { c, msgid } from 'ttag';
import { Button } from '@proton/atoms';
import {
Cell,
Form,
Icon,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
Table,
TableBody,
TableCell,
TableRow,
useModalTwo,
} from '@proton/components/components';
import { MAX_IPS_ADDON } from '@proton/shared/lib/constants';
import range from '@proton/utils/range';
import { Gateway } from './Gateway';
import GatewayAddServersModal from './GatewayAddServersModal';
import { GatewayLogical } from './GatewayLogical';
import { GatewayUser } from './GatewayUser';
import { getCountryFlagAndName } from './getCountryFlagAndName';
import { getFormattedLoad, getSuffix, getTotalAdded } from './helpers';
interface Props {
gateway: Gateway;
language: string | readonly string[];
countries: readonly string[];
deletedInCountries: Record<string, number>;
users: readonly GatewayUser[];
ownedCount: number;
usedCount: number;
showDeleted?: boolean;
showIPv4?: boolean;
showIPv6?: boolean;
showLoad?: boolean;
showCancelButton?: boolean;
singleServer?: boolean;
isDeleted: (logical: GatewayLogical) => boolean;
onSubmitDone: (deletedLogicalIds: readonly string[], addedQuantities: Record<string, number>) => Promise<void>;
onResolve: () => void;
onReject: () => void;
onUpsell: () => void;
}
const GatewayServersModal = ({
gateway,
language,
countries,
deletedInCountries,
users,
ownedCount,
usedCount,
showDeleted = false,
showIPv4 = true,
showIPv6 = true,
showLoad = true,
showCancelButton = false,
singleServer = false,
isDeleted,
onSubmitDone,
onReject,
onResolve,
onUpsell,
...rest
}: Props) => {
const [addServersModal, showAddServersModal] = useModalTwo(GatewayAddServersModal);
const [deleted, setDeleted] = useState<Record<string, boolean>>({});
const [added, setAdded] = useState<Record<string, number>>({});
const [loading, setLoading] = useState(false);
const remainingCount = ownedCount - usedCount;
const previousServers = gateway.Logicals.filter((l) => !l.Servers?.length || l.Visible);
const previousNumberOfServers = previousServers.length;
const deletedServers = previousServers.filter((l) => deleted[l.ID]);
const deletedServerCount = deletedServers.length;
const addedServerCount = Object.entries(added).reduce((total, [, quantity]) => total + quantity, 0);
const availableAddedCount = remainingCount + deletedServerCount - addedServerCount;
const newNumberOfServers = previousNumberOfServers + addedServerCount - deletedServerCount;
const showIP = showIPv4 || showIPv6;
const decreaseQuantities = (quantities: Record<string, number>) => {
const newAdded = { ...added };
Object.entries(quantities).forEach(([country, quantity]) => {
const newQuantity = (newAdded[country] || 0) - quantity;
if (newQuantity) {
newAdded[country] = newQuantity;
return;
}
delete newAdded[country];
});
setAdded(newAdded);
};
const addQuantities = (quantities: Record<string, number>) => {
const entries = Object.entries(quantities);
if (!entries.length) {
return;
}
const newAdded = { ...added };
let deletedIds = Object.keys(deleted).filter((id) => deleted[id]);
entries.forEach(([country, quantity]) => {
const serversFromTrash = gateway.Logicals.filter((l) => l.ExitCountry === country && l.ID && deleted[l.ID])
.map((l) => l.ID)
.slice(0, quantity);
const recoverableQuantity = serversFromTrash.length;
if (recoverableQuantity) {
deletedIds = deletedIds.filter((id) => serversFromTrash.indexOf(id) === -1);
}
const addedQuantity = quantity - recoverableQuantity;
if (addedQuantity > 0) {
newAdded[country] = (newAdded[country] || 0) + addedQuantity;
}
});
const newDeleted: Record<string, true> = {};
deletedIds.forEach((id) => {
newDeleted[id] = true;
});
setAdded(newAdded);
setDeleted(newDeleted);
};
const addServers = () =>
showAddServersModal({
countries,
deletedInCountries,
ownedCount,
usedCount: usedCount - deletedServerCount + addedServerCount,
users,
language,
singleServer,
showCancelButton,
onSubmitDone: addQuantities,
onUpsell,
});
const handleDelete = (logical: GatewayLogical) => async () => {
if (added[logical.ExitCountry] > 0) {
decreaseQuantities({ [logical.ExitCountry]: 1 });
return;
}
setDeleted({
...deleted,
[logical.ID]: !deleted[logical.ID],
});
};
const handleSubmit = async () => {
const idsToDelete = Object.keys(deleted).filter((id) => deleted[id]);
if (getTotalAdded(added) < 1 && idsToDelete.length < 1) {
onReject();
return;
}
try {
setLoading(true);
await onSubmitDone(idsToDelete, added);
onResolve();
} finally {
setLoading(false);
}
};
return (
<>
<ModalTwo size="xlarge" {...rest} as={Form} onSubmit={handleSubmit} onClose={onReject}>
<ModalTwoHeader title={c('Title').t`Edit servers`} />
<ModalTwoContent>
<Table className="my-2">
<thead>
<tr>
<TableCell key="country" type="header">{c('Header').t`Country`}</TableCell>
<TableCell key="server" type="header" className="w-1/10">
{c('Header').t`Server`}
</TableCell>
<TableCell key="status" type="header" className="w-1/6">
{c('Header').t`Status`}
</TableCell>
{showIP && (
<TableCell key="ip" type="header" className="w-1/6">
{c('Header').t`IP address`}
</TableCell>
)}
{showLoad && (
<TableCell key="load" type="header" className="w-1/6">
{c('Header').t`Server load`}
</TableCell>
)}
<TableCell key="manage" type="header" className="w-1/10">
</TableCell>
</tr>
</thead>
<TableBody colSpan={4 + Number(showIP) + Number(showLoad)} loading={loading}>
{gateway.Logicals.filter((l) => l.Servers?.length && l.Visible).map((logical) => (
<TableRow
key={'logical-' + logical.ID}
className={deleted[logical.ID] ? 'opacity-50' : undefined}
cells={[
getCountryFlagAndName(language, logical.ExitCountry, undefined, {
className: 'mb-1',
key: `country-logical-${logical.ID}-${logical.ExitCountry}`,
}),
getSuffix(logical.Name),
<span className="py-1 px-2 rounded text-uppercase bg-success">{
/** translator: status of the server: people can connect to it */
c('Server-Info').t`active`
}</span>,
...(showIP
? [
<>
{[
showIPv4 && logical.Servers[0].ExitIPv4,
showIPv6 && logical.Servers[0].ExitIPv6,
]
.filter(Boolean)
.map((ip) => (
<div
key={'ip-' + ip}
className="text-ellipsis"
title={ip || undefined}
>
{ip}
</div>
))}
</>,
]
: []),
...(showLoad ? [getFormattedLoad(logical.Servers)] : []),
<Button icon size="small" key="delete" onClick={handleDelete(logical)}>
<Icon name="trash" />
</Button>,
]}
/>
))}
{showDeleted &&
gateway.Logicals.filter((l) => l.Servers?.length && !l.Visible).map((logical) => (
<TableRow
key={'logical-' + logical.ID}
className="opacity-50"
cells={[
getCountryFlagAndName(language, logical.ExitCountry, undefined, {
className: 'mb-1',
key: 'country-logical-' + logical.ID + '-' + logical.ExitCountry,
}),
getSuffix(logical.Name),
<span className="py-1 px-2 rounded text-uppercase bg-weak color-weak">{
/** translator: status of the server: people cannot connect to it */
c('Server-Info').t`inactive`
}</span>,
...(showIP
? [
<>
{[logical.Servers[0].ExitIPv4, logical.Servers[0].ExitIPv6]
.filter(Boolean)
.map((ip) => (
<div key={'ip-' + ip}>{ip}</div>
))}
</>,
]
: []),
...(showLoad ? [getFormattedLoad(logical.Servers)] : []),
'',
]}
/>
))}
{gateway.Logicals.filter((l) => !l.Servers?.length).map((logical) => (
<TableRow
key={'logical-' + logical.ID}
className={deleted[logical.ID] ? 'opacity-50' : undefined}
cells={[
getCountryFlagAndName(language, logical.ExitCountry, undefined, {
className: 'mb-1',
key: 'country-logical-' + logical.ID + '-' + logical.ExitCountry,
}),
getSuffix(logical.Name),
<span className="py-1 px-2 rounded text-uppercase bg-info">{
/** translator: status of the server: people cannot yet use it */
c('Server-Info').t`pending`
}</span>,
...(showIP ? ['-'] : []),
...(showLoad ? ['-'] : []),
<Button icon size="small" key="delete" onClick={handleDelete(logical)}>
<Icon name="trash" />
</Button>,
]}
/>
))}
{Object.keys(added).map((country) =>
range(0, added[country]).map((index) => (
<TableRow
key={'future-logical-' + country + '-' + index}
cells={[
getCountryFlagAndName(language, country, undefined, {
className: 'mb-1',
key: 'country-future-logical-' + country + '-' + index,
}),
'',
new Cell(
(
<span className="py-1 px-2 rounded text-uppercase bg-weak">{
/** translator: status of the server: will be created when user click "Save" */
c('Server-Info').t`to be created`
}</span>
),
1 + Number(showIP) + Number(showLoad)
),
<Button
icon
size="small"
key="delete"
onClick={() => {
decreaseQuantities({ [country]: 1 });
}}
>
<Icon name="trash" />
</Button>,
]}
/>
))
)}
</TableBody>
</Table>
{availableAddedCount >= 1 ? (
<Button shape="ghost" className="color-primary" onClick={addServers}>
<Icon name="plus-circle-filled" className="mr-2" />
{c('Info').ngettext(
msgid`Add server (${availableAddedCount} available)`,
`Add server (${availableAddedCount} available)`,
availableAddedCount
)}
</Button>
) : (
ownedCount < MAX_IPS_ADDON && (
<Button
shape="ghost"
className="color-primary"
onClick={() => {
onUpsell();
onReject();
}}
>
<Icon name="plus-circle-filled" className="mr-2" />
{c('Action').t`Get more servers`}
</Button>
)
)}
</ModalTwoContent>
<ModalTwoFooter>
{showCancelButton ? (
<Button color="weak" onClick={onReject}>
{c('Action').t`Cancel`}
</Button>
) : (
<div />
)}
<Button color={newNumberOfServers ? 'norm' : 'danger'} type="submit" loading={loading}>
{newNumberOfServers ? c('Action').t`Save` : c('Action').t`Delete Gateway`}
</Button>
</ModalTwoFooter>
</ModalTwo>
{addServersModal}
</>
);
};
export default GatewayServersModal;
| 6,989
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayUser.ts
|
import { USER_ROLES } from '@proton/shared/lib/constants';
export interface GatewayUser {
ID: string;
Email: string;
Name: string | null;
Role?: USER_ROLES;
Subscriber?: boolean;
}
| 6,990
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayUserSelection.tsx
|
import { c } from 'ttag';
import {
Checkbox,
Field,
Option,
Row,
SelectTwo,
SortingTableHeader,
Table,
TableBody,
TableRow,
} from '@proton/components/components';
import { SelectChangeEvent } from '@proton/components/components/selectTwo/select';
import { useSortedList } from '@proton/components/hooks';
import { SERVER_FEATURES, SORT_DIRECTION, USER_ROLES } from '@proton/shared/lib/constants';
import noop from '@proton/utils/noop';
import { GatewayDto } from './GatewayDto';
import { GatewayUser } from './GatewayUser';
interface Props {
loading: boolean;
users: readonly GatewayUser[];
model: Pick<GatewayDto, 'features' | 'userIds'>;
changeModel: <V extends GatewayDto[K], K extends keyof GatewayDto = keyof GatewayDto>(key: K, value: V) => void;
}
export const GatewayUserSelection = ({ loading, users, model, changeModel }: Props) => {
const { sortConfig, sortedList, toggleSort } = useSortedList(users as GatewayUser[], {
key: 'Email',
direction: SORT_DIRECTION.DESC,
});
const handleFeatureChange = ({ value }: SelectChangeEvent<string>) => changeModel('features', Number(value));
const getSelectToggle = (id: string) =>
loading
? noop
: () =>
changeModel(
'userIds',
model.userIds.indexOf(id) !== -1
? model.userIds.filter((selected) => selected !== id)
: [...model.userIds, id]
);
const selectAllToggle = loading
? noop
: () =>
changeModel(
'userIds',
users.every(({ ID }) => model.userIds.indexOf(ID) !== -1) ? [] : users.map(({ ID }) => ID)
);
return (
<>
<Row>
<Field>
<SelectTwo
value={`${model.features & SERVER_FEATURES.DOUBLE_RESTRICTION}`}
onChange={handleFeatureChange}
>
<Option value="0" title={c('Title').t`Every member of the organization can access`}>
{c('Option').t`The whole organization`}
</Option>
<Option
value={`${SERVER_FEATURES.DOUBLE_RESTRICTION}`}
title={c('Title').t`Custom selection of users`}
>
{c('Option').t`Select who can access...`}
</Option>
</SelectTwo>
</Field>
</Row>
{model.features & SERVER_FEATURES.DOUBLE_RESTRICTION ? (
<Table>
<SortingTableHeader
config={sortConfig}
onToggleSort={toggleSort as any}
cells={[
{
content: (
<Checkbox
className="p-1"
checked={users.every(({ ID }) => model.userIds.indexOf(ID) !== -1)}
onChange={selectAllToggle}
/>
),
className: 'w-custom',
style: { '--w-custom': '5%' },
},
{ key: 'Name', content: c('TableHeader').t`Name`, sorting: true },
{ key: 'Email', content: c('TableHeader').t`Email`, sorting: true },
{
key: 'Role',
content: c('TableHeader').t`Role`,
sorting: true,
className: 'w-1/10',
},
]}
/>
<TableBody loading={!users} colSpan={4}>
{sortedList.map(({ ID, Name, Email, Role, Subscriber }: GatewayUser) => (
<TableRow
key={`select-user--${ID}`}
cells={[
<Checkbox
className="p-1"
checked={model.userIds.indexOf(ID) !== -1}
onChange={getSelectToggle(ID)}
/>,
<div className="text-ellipsis">{Name}</div>,
<div className="text-ellipsis">{Email}</div>,
Role === USER_ROLES.ADMIN_ROLE
? Subscriber
? /* Current status of a user being admin of their organization */ c('Role')
.t`Primary admin`
: /* Current status of a user being admin of their organization */ c('Role')
.t`Admin`
: /* Current status of a user being simple member in their organization */ c(
'Role'
).t`User`,
]}
/>
))}
</TableBody>
</Table>
) : undefined}
</>
);
};
export default GatewayUserSelection;
| 6,991
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewayUsersModal.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Form, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '@proton/components/components';
import { GatewayDto } from './GatewayDto';
import { GatewayModel } from './GatewayModel';
import { GatewayUser } from './GatewayUser';
import { GatewayUserSelection } from './GatewayUserSelection';
interface Props {
model: GatewayDto;
users: readonly GatewayUser[];
showCancelButton?: boolean;
onSubmitDone: (gateway: Pick<GatewayModel, 'Features' | 'UserIds'>) => Promise<void>;
onResolve: () => void;
onReject: () => void;
}
const GatewayUsersModal = ({
model: initialModel,
users,
showCancelButton = false,
onSubmitDone,
onReject,
onResolve,
...rest
}: Props) => {
const [model, setModel] = useState({ ...initialModel });
const [loading, setLoading] = useState(false);
const changeModel = <V extends GatewayDto[K], K extends keyof GatewayDto = keyof GatewayDto>(key: K, value: V) =>
setModel((model: GatewayDto) => ({ ...model, [key]: value }));
const handleSubmit = async () => {
const dtoBody = {
Features: model.features,
UserIds: model.userIds,
};
try {
setLoading(true);
await onSubmitDone(dtoBody);
onResolve();
} finally {
setLoading(false);
}
};
return (
<ModalTwo size="xlarge" {...rest} as={Form} onSubmit={handleSubmit} onClose={onReject}>
<ModalTwoHeader title={c('Title').t`Edit users`} />
<ModalTwoContent>
<GatewayUserSelection loading={loading} users={users} model={model} changeModel={changeModel} />
</ModalTwoContent>
<ModalTwoFooter>
{showCancelButton ? (
<Button color="weak" onClick={onReject}>
{c('Action').t`Cancel`}
</Button>
) : (
<div />
)}
<Button color="norm" type="submit" loading={loading}>
{c('Action').t`Save`}
</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default GatewayUsersModal;
| 6,992
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/GatewaysSection.tsx
|
import React, { useMemo, useState } from 'react';
import { c, msgid } from 'ttag';
import { Button, Href } from '@proton/atoms';
import { EmptyViewContainer, SUBSCRIPTION_STEPS, useSubscriptionModal } from '@proton/components/containers';
import { getApiErrorMessage } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import { PLANS, SERVER_FEATURES, SORT_DIRECTION } from '@proton/shared/lib/constants';
import { getVPNDedicatedIPs, hasVpnBusiness } from '@proton/shared/lib/helpers/subscription';
import { Organization } from '@proton/shared/lib/interfaces';
import gatewaySvg from '@proton/styles/assets/img/illustrations/gateway.svg';
import gatewaysEmptyStateAdminsSvg from '@proton/styles/assets/img/illustrations/gateways-empty-state-admins.svg';
import gatewaysEmptyStateUsersSvg from '@proton/styles/assets/img/illustrations/gateways-empty-state-users.svg';
import { Loader, Row, Table, TableBody, TableCell, useModalTwo } from '../../../components';
import { useApi, useNotifications, useSortedList, useSubscription, useUser, useUserSettings } from '../../../hooks';
import { Gateway } from './Gateway';
import { GatewayLogical } from './GatewayLogical';
import GatewayModal from './GatewayModal';
import { GatewayModel } from './GatewayModel';
import GatewayRenameModal from './GatewayRenameModal';
import GatewayRow from './GatewayRow';
import GatewayServersModal from './GatewayServersModal';
import GatewayUsersModal from './GatewayUsersModal';
import { addIpInVPNGateway, createVPNGateway, deleteVPNGateway, renameVPNGateway, updateVPNGatewayUsers } from './api';
import { useGateways } from './useGateways';
interface Props {
organization?: Organization;
showCancelButton?: boolean;
}
const getFeaturesAndUserIds = (data: Partial<GatewayModel>): [number, readonly string[] | null] => {
const features = data.Features || 0;
return [features, features & SERVER_FEATURES.DOUBLE_RESTRICTION ? data.UserIds || [] : null];
};
const GatewaysSection = ({ organization, showCancelButton = true }: Props) => {
const api = useApi();
const [createModal, showCreateModal] = useModalTwo(GatewayModal);
const [renameModal, showRenameModal] = useModalTwo(GatewayRenameModal);
const [usersModal, showUsersModal] = useModalTwo(GatewayUsersModal);
const [serversModal, showServersModal] = useModalTwo(GatewayServersModal);
const [user] = useUser();
const { createNotification } = useNotifications();
const [userSettings] = useUserSettings();
const [subscription] = useSubscription();
const [deletedLogicals, setDeletedLogicals] = useState<Record<string, boolean>>({});
const [deletingLogicals, setDeletingLogicals] = useState<readonly string[]>([]);
const [createdGateways, setCreatedGateways] = useState<Gateway[]>([]);
const [updatedLogicals, setUpdatedLogicals] = useState<Record<string, GatewayLogical>>({});
const {
config: {
Table: { IPv4, IPv6, Load, Deleted },
ServerTable: serverTableConfig,
Provisioning: { TranslatedDuration: provisioningDuration },
},
users,
countries,
gateways,
refresh,
} = useGateways();
const refreshList = async () => {
setCreatedGateways([]);
setUpdatedLogicals({});
await refresh();
};
const allGateways = useMemo<readonly Gateway[]>(() => {
const ids: Record<string, true> = {};
return [...createdGateways, ...(gateways || [])]
.map((gateway) => ({
...gateway,
Logicals: gateway.Logicals.filter((l) => !deletedLogicals[l.ID]).map((l) => updatedLogicals[l.ID] || l),
}))
.filter((gateway) => {
if (ids[gateway.Name]) {
return false;
}
if (gateway.Logicals.length) {
ids[gateway.Name] = true;
return true;
}
return false;
});
}, [createdGateways, gateways, updatedLogicals, deletedLogicals]);
const { sortedList } = useSortedList(allGateways as Gateway[], { key: 'Name', direction: SORT_DIRECTION.ASC });
const [openSubscriptionModal] = useSubscriptionModal();
if (!organization || !user || !subscription || !gateways || !countries) {
return <Loader />;
}
const getCustomizeSubscriptionOpener = (source: 'dashboard' | 'upsells') => () =>
openSubscriptionModal({
metrics: {
source,
},
step: SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION,
plan: PLANS.VPN_BUSINESS,
});
const isAdmin = user.isAdmin && !user.isSubUser;
if (!hasVpnBusiness(subscription) && !(organization && organization.PlanName === PLANS.VPN_BUSINESS)) {
const boldDedicatedServers = (
<b key="bold-dedicated-servers">{
// translator: Full sentence "With a Business or Enterprise plan, you can purchase dedicated servers for your organization, and set up Gateways to control which users can access them"
c('Info').t`dedicated servers`
}</b>
);
const boldGateways = (
<b key="bold-gateways">{
// translator: Full sentence "With a Business or Enterprise plan, you can purchase dedicated servers for your organization, and set up Gateways to control which users can access them"
c('Info').t`Gateways`
}</b>
);
return (
<>
<Row className="rounded-lg" style={{ 'background-color': 'var(--interaction-norm-minor-1)' }}>
<div className="m-5 mt-6" style={{ minWidth: '38px' }}>
<img
key="gateway-upgrade-image"
className="h-auto"
src={gatewaySvg}
alt=""
width={96}
height={96}
/>
</div>
<div className="m-4">
<p className="mb-2">
<b>{c('Info').t`Enhance your network security`}</b>
</p>
<p className="mt-2">
{
// translator: Full sentence "With a Business or Enterprise plan, you can purchase dedicated servers for your organization, and set up Gateways to control which users can access them"
c('Info')
.jt`With a Business or Enterprise plan, you can purchase ${boldDedicatedServers} for your organization, and set up ${boldGateways} to control which users can access them.`
}{' '}
<Href
href="https://protonvpn.com/support/manage-vpn-servers-organization"
title={c('Info').t`Lean more about gateways`}
>{c('Link').t`Learn more`}</Href>
</p>
</div>
{isAdmin && (
<div className="m-4 mr-6 flex-item-noshrink flex-align-self-center">
<Button
color="norm"
onClick={getCustomizeSubscriptionOpener('upsells')}
title={c('Title').t`Setup dedicated servers by upgrading to Business`}
>
{c('Action').t`Upgrade to Business`}
</Button>
</div>
)}
</Row>
</>
);
}
const isDeleted = (logical: GatewayLogical): boolean => !logical.Visible && logical.Servers?.length > 0;
const ipAddresses = getVPNDedicatedIPs(subscription);
const deletedInCountries: Record<string, number> = {};
const ipCount = allGateways.reduce((total, gateway) => {
return (
total +
gateway.Logicals.reduce((sum, logical) => {
if (isDeleted(logical)) {
deletedInCountries[gateway.ExitCountry] = (deletedInCountries[gateway.ExitCountry] || 0) + 1;
return sum;
}
return sum + Math.max(1, logical.Servers?.length || 0);
}, 0)
);
}, 0);
const canAdd = ipAddresses > ipCount;
const language = userSettings.Locale || navigator.languages;
const createServersSequentially = async (
data: GatewayModel,
initialGateway?: Gateway,
key = 'gateway-creation',
getNotificationMessage?: (serverNumber: number, total: number) => string
): Promise<Gateway | undefined> => {
const quantities = data.Quantities;
if (!quantities) {
return;
}
const countries = Object.keys(quantities);
const total = countries.reduce((total, country) => total + (quantities[country] || 0), 0);
let gatewayHost: Gateway | undefined = initialGateway;
let serverNumber = 0;
for (let i = 0; i < countries.length; i++) {
const country = countries[i];
for (let j = 0; j < quantities[country]; j++) {
++serverNumber;
createNotification({
key,
text: getNotificationMessage
? getNotificationMessage(serverNumber, total)
: /*
translator: "Creating gateway servers" refers to the whole operation, so pluralization uses ${total}, not ${serverNumber}, "Creating gateway servers: 1 / 3" is plural in English because we are creating a gateway of 3 servers
translator: This message appears when starting to creating a gateway that will contain ${total} server in the end (total is always an integer and at least 2, so for any language with "One" form < 2, don't care much about singular)
*/ c('Info').ngettext(
msgid`Creating gateway server: ${serverNumber} / ${total}`,
`Creating gateway servers: ${serverNumber} / ${total}`,
total
),
type: 'info',
});
if (!gatewayHost) {
const [features, usersIds] = getFeaturesAndUserIds(data);
gatewayHost = (
await api<{ Gateway: Gateway }>(
createVPNGateway({
Name: data.Name,
Country: country,
Features: features,
UserIds: usersIds,
})
)
)?.Gateway;
continue;
}
try {
gatewayHost = (
await api<{ Gateway: Gateway }>(
addIpInVPNGateway({
Name: gatewayHost.Name,
Country: country,
})
)
)?.Gateway;
} catch (error) {
createNotification({
key,
text:
getApiErrorMessage(error as Error) ||
(error as Error)?.message ||
c('Error').t`Unknown error`,
type: 'warning',
});
return gatewayHost;
}
}
}
return gatewayHost;
};
const buildGateway = async (data: GatewayModel): Promise<Gateway | undefined> => {
if (data.Quantities) {
return createServersSequentially(data);
}
const [features, usersIds] = getFeaturesAndUserIds(data);
return (
await api<{ Gateway: Gateway }>(
createVPNGateway({
Name: data.Name,
Country: data.Country,
Features: features,
UserIds: usersIds,
})
)
)?.Gateway;
};
const addGateway = () =>
showCreateModal({
showCancelButton,
countries,
deletedInCountries,
ownedCount: ipAddresses,
usedCount: ipCount,
users,
language,
onSubmitDone: async (data: GatewayModel) => {
const gateway = await buildGateway(data);
if (!gateway) {
createNotification({
text: c('Error').t`Impossible to create the gateway`,
type: 'error',
});
return;
}
setCreatedGateways([...createdGateways, gateway]);
},
onUpsell: getCustomizeSubscriptionOpener('dashboard'),
});
const editGatewayServers = (gateway: Gateway) => () =>
showServersModal({
showCancelButton,
gateway,
countries,
deletedInCountries,
users,
ownedCount: ipAddresses,
usedCount: ipCount,
showDeleted: serverTableConfig.Deleted,
showIPv4: serverTableConfig.IPv4,
showIPv6: serverTableConfig.IPv6,
showLoad: serverTableConfig.Load,
isDeleted,
onSubmitDone: async (deletedLogicalIds: readonly string[], addedQuantities: Record<string, number>) => {
const deletedServerCount = deletedLogicalIds.length;
const addedServerCount = Object.entries(addedQuantities).reduce(
(total, [, quantity]) => total + quantity,
0
);
if (deletedServerCount && addedServerCount) {
createNotification({
key: 'gateway-servers-editions',
text: c('Info').ngettext(
msgid`Deleting ${deletedServerCount} gateway server`,
`Deleting ${deletedServerCount} gateway servers`,
deletedServerCount
),
type: 'info',
});
}
if (deletedServerCount) {
await api(deleteVPNGateway(deletedLogicalIds));
}
if (deletedServerCount && addedServerCount) {
createNotification({
key: 'gateway-servers-editions',
text: c('Info').ngettext(
msgid`Adding ${addedServerCount} gateway server`,
`Adding ${addedServerCount} gateway servers`,
addedServerCount
),
type: 'info',
});
}
if (addedServerCount) {
await createServersSequentially(
{
Name: gateway.Name,
Features: gateway.Logicals[0]?.Features,
UserIds: gateway.Logicals[0]?.Users,
Quantities: addedQuantities,
},
gateway,
'gateway-servers-editions',
(serverNumber: number, total: number) =>
/*
translator: "Creating gateway servers" refers to the whole operation, so pluralization uses ${total}, not ${serverNumber}, "Creating gateway servers: 1 / 3" is plural in English because we are creating a gateway of 3 servers
translator: This message appears when starting to creating a gateway that will contain ${total} server in the end (total is always an integer and at least 2, so for any language with "One" form < 2, don't care much about singular)
*/ c('Info').ngettext(
msgid`Adding gateway server: ${serverNumber} / ${total}`,
`Adding gateway servers: ${serverNumber} / ${total}`,
total
)
);
}
await refreshList();
},
onUpsell: getCustomizeSubscriptionOpener('dashboard'),
});
const editGatewayUsers = (gateway: Gateway, logical: GatewayLogical) => () =>
showUsersModal({
showCancelButton,
model: {
features: logical.Features,
userIds: logical.Users,
},
users,
onSubmitDone: async (data: GatewayModel) => {
const [features, usersIds] = getFeaturesAndUserIds(data);
const update = await api<{ Gateway: Gateway }>(updateVPNGatewayUsers(gateway.Name, features, usersIds));
if (!update?.Gateway) {
createNotification({
text: c('Error').t`Impossible to edit the gateway`,
type: 'error',
});
return;
}
await refreshList();
},
});
const renameGateway = (id: string, currentName: string) => async () => {
if (deletingLogicals.indexOf(id) !== -1) {
return;
}
await showRenameModal({
showCancelButton,
currentName,
onSubmitDone: async ({ Name: newName }: { Name: string }) => {
const gateway = await api<{ Gateway: Gateway }>(renameVPNGateway(currentName, newName));
if (!gateway?.Gateway) {
createNotification({
text: c('Error').t`Impossible to rename the gateway`,
type: 'error',
});
return;
}
await refreshList();
},
});
};
const deleteGateway = (gateway: Gateway) => async () => {
const ids = gateway.Logicals.map(({ ID }) => ID);
if (deletingLogicals.some((id) => ids.indexOf(id) !== -1)) {
return;
}
setDeletingLogicals([...deletingLogicals, ...ids]);
try {
const { Logicals: logicals } = await api<{ Logicals: GatewayLogical[] }>(deleteVPNGateway(ids));
const update = { ...updatedLogicals };
const kept: Record<string, boolean> = {};
logicals.forEach((logical) => {
kept[logical.ID] = true;
update[logical.ID] = logical;
});
setUpdatedLogicals(update);
if (ids.length !== Object.keys(kept).length) {
const removed: Record<string, boolean> = { ...deletedLogicals };
ids.forEach((id) => {
if (!kept[id]) {
removed[id] = true;
}
});
setDeletedLogicals(removed);
}
} finally {
setDeletingLogicals(deletingLogicals.filter((deletingId) => ids.indexOf(deletingId) === -1));
}
};
return (
<>
{isAdmin && (
<>
{createModal}
{renameModal}
{serversModal}
{usersModal}
<div className="mb-4 flex flex-align-items-center gap-2">
<span className="color-weak">
{c('Info').ngettext(
msgid`You are currently using ${ipCount} of your ${ipAddresses} available dedicated server.`,
`You are currently using ${ipCount} of your ${ipAddresses} available dedicated servers.`,
ipAddresses
)}
</span>
<Button
size="small"
color="norm"
shape={canAdd ? 'outline' : 'solid'}
onClick={getCustomizeSubscriptionOpener('dashboard')}
title={c('Title').t`Customize the number of IP addresses in your plan`}
>
{c('Action').t`Get more servers`}
</Button>
</div>
</>
)}
{sortedList.length ? (
<>
{isAdmin && (
<div className="mb-4">
<Button
color="norm"
disabled={!canAdd}
onClick={addGateway}
title={c('Title').t`Create a new Gateway`}
>
{c('Action').t`Create Gateway`}
</Button>
</div>
)}
<Table className="my-2">
<thead>
<tr>
<TableCell key="name" type="header">{c('Header').t`Name`}</TableCell>
<TableCell key="status" type="header" className="w-1/10">
{c('Header').t`Status`}
</TableCell>
<TableCell key="servers" type="header">{c('Header').t`Servers`}</TableCell>
{isAdmin && (
<>
<TableCell key="members" type="header">{c('Header').t`Members`}</TableCell>
<TableCell
key="manage"
type="header"
className="w-custom"
style={{ '--w-custom': '12rem' }}
>
</TableCell>
</>
)}
</tr>
</thead>
<TableBody colSpan={3 + (isAdmin ? 2 : 0)}>
{sortedList.map((gateway) => (
<GatewayRow
key={'gateway-' + gateway.Name}
isAdmin={isAdmin}
showDeleted={Deleted}
showIPv4={IPv4}
showIPv6={IPv6}
showLoad={Load}
gateway={gateway}
isDeleted={isDeleted}
users={users ?? []}
language={language}
provisioningDuration={provisioningDuration}
renameGateway={renameGateway}
editGatewayServers={editGatewayServers}
editGatewayUsers={editGatewayUsers}
deleteGateway={deleteGateway}
deletingLogicals={deletingLogicals}
deletedLogicals={deletedLogicals}
/>
))}
</TableBody>
</Table>
</>
) : (
<EmptyViewContainer
key="no-gateways-container"
imageProps={{
src: isAdmin ? gatewaysEmptyStateAdminsSvg : gatewaysEmptyStateUsersSvg,
title: c('Info').t`No gateways`,
key: 'no-gateways-image',
}}
>
<h3 className="text-bold">
{isAdmin ? c('Info').t`Create your first Gateway` : c('Info').t`No Gateways yet`}
</h3>
<p className="color-weak">
{isAdmin
? c('Info')
.t`Organize your dedicated servers into Gateways and decide which members can access them.`
: c('Info').t`Ask your organisation admin to setup Gateways.`}
</p>
{isAdmin && (
<div>
<Button
color="norm"
disabled={!canAdd}
onClick={addGateway}
title={c('Title').t`Create a new gateway`}
>
{c('Action').t`Create Gateway`}
</Button>
</div>
)}
</EmptyViewContainer>
)}
</>
);
};
export default GatewaysSection;
| 6,993
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/api.ts
|
import { GatewayIpModel } from '@proton/components/containers/vpn/gateways/GatewayIpModel';
import { GatewayModel } from './GatewayModel';
export const queryVPNGateways = () => ({
url: 'vpn/v1/business/gateways',
method: 'get',
});
export const createVPNGateway = (data: GatewayModel) => ({
url: 'vpn/v1/business/gateways',
method: 'post',
data,
});
export const addIpInVPNGateway = (data: GatewayIpModel) => ({
url: 'vpn/v1/business/gateways/ip',
method: 'post',
data,
});
export const deleteVPNGateway = (ids: readonly string[]) => ({
url: 'vpn/v1/business/gateways',
method: 'delete',
data: {
LogicalIds: ids,
},
});
export const renameVPNGateway = (currentName: string, newName: string) => ({
url: 'vpn/v1/business/gateways',
method: 'put',
data: {
CurrentName: currentName,
NewName: newName,
},
});
export const updateVPNGatewayUsers = (currentName: string, features: number, userIds?: readonly string[] | null) => ({
url: 'vpn/v1/business/gateways',
method: 'put',
data: {
CurrentName: currentName,
NewName: currentName,
Features: features,
UserIds: userIds ?? null,
},
});
| 6,994
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/getCountryFlagAndName.tsx
|
import { Attributes, ImgHTMLAttributes } from 'react';
import { getLocalizedCountryByAbbr } from '@proton/components/helpers/countries';
import clsx from '@proton/utils/clsx';
import { getFlagSvg } from '../flag';
export const getCountryFlagAndName = (
languageOrLanguages: string | readonly string[],
countryCode?: string,
label?: string,
rest: Attributes & ImgHTMLAttributes<HTMLImageElement> = {}
) => {
const upperCode = (countryCode || '').toUpperCase();
const flag = getFlagSvg(upperCode);
const name = getLocalizedCountryByAbbr(upperCode, languageOrLanguages);
const classes = rest.className;
delete rest.className;
return [
flag && <img width={20} className={clsx(['mx-2 border', classes])} src={flag} alt={name} {...rest} />,
label ?? name,
];
};
| 6,995
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/helpers.tsx
|
import { c } from 'ttag';
import { SERVER_FEATURES } from '@proton/shared/lib/constants';
import { GatewayDto } from './GatewayDto';
import { GatewayLogical } from './GatewayLogical';
import { GatewayServer } from './GatewayServer';
import { GatewayUser } from './GatewayUser';
export const getSuffix = (name: string | undefined) => name?.match(/#\d+$/)?.[0] || '';
const getAverageLoad = (servers: GatewayServer[]) =>
servers.reduce((load, server) => load + server.Load, 0) / servers.length;
const getColorForLoad = (load: number): string => {
if (load > 90) {
return 'danger';
}
if (load > 75) {
return 'warning';
}
return 'success';
};
export const getFormattedLoad = (servers: GatewayServer[]) => {
const load = Math.max(0, Math.min(100, Math.round(getAverageLoad(servers))));
return <span className={'color-' + getColorForLoad(load)}>{load}%</span>;
};
const getInitialQuantities = (countries: readonly string[]) => {
const quantities: Record<string, 1> = {};
// Add 2 by default in different countries (take 1 in each of the 2 first countries)
for (let i = 0; i < 2 && countries[i]; i++) {
quantities[countries[i] as string] = 1;
}
return quantities;
};
export const getTotalAdded = (quantities: Record<string, number> | null | undefined): number =>
Object.values(quantities || {}).reduce((total, quantity) => total + quantity, 0);
export const getInitialModel = (countries: readonly string[]): GatewayDto => ({
country: countries[0] || 'US',
name: '',
features: 0,
userIds: [],
quantities: getInitialQuantities(countries),
});
const getUsersList = (userIds: readonly string[], users: readonly GatewayUser[], key = '') =>
userIds.length
? userIds.map((id) => {
const user = users?.find((user) => user.ID === id);
return <div key={'logical-users-' + key + '-' + id}>{user?.Name || user?.Email}</div>;
})
: '0';
export const getMembers = (users: readonly GatewayUser[], logical: GatewayLogical) =>
logical.Features & SERVER_FEATURES.DOUBLE_RESTRICTION
? getUsersList(logical.Users, users, logical.ID)
: /* translator: The whole organization has access to the gateway */ c('Info').t`Whole organization`;
| 6,996
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/useAddedQuantities.ts
|
import { useMemo } from 'react';
import { getTotalAdded } from './helpers';
export const useAddedQuantities = (model: { quantities?: Record<string, number> }) =>
useMemo(() => getTotalAdded(model.quantities), [model]);
| 6,997
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/useGateways.ts
|
import { c, msgid } from 'ttag';
import { useApiResult } from '@proton/components/hooks';
import { Gateway } from './Gateway';
import { GatewayUser } from './GatewayUser';
import { queryVPNGateways } from './api';
interface TableConfig {
Name: boolean;
Status: boolean;
Country: boolean;
IPv4: boolean;
IPv6: boolean;
Load: boolean;
Deleted?: boolean;
}
interface GatewayConfig {
Table: TableConfig;
ServerTable: TableConfig;
Provisioning: {
TranslatedDuration: string;
};
}
export const useGateways = () => {
const {
loading,
result,
request: refresh,
} = useApiResult<
{
Config: GatewayConfig;
Countries: readonly string[];
Gateways: readonly Gateway[];
Users: readonly GatewayUser[];
},
typeof queryVPNGateways
>(queryVPNGateways, []);
const nbDay = 7;
return {
loading: !result || loading,
config: result?.Config || {
Table: {
Name: false,
Status: true,
Country: true,
IPv4: true,
IPv6: false,
Load: false,
},
ServerTable: {
Name: false,
Status: true,
Country: true,
IPv4: true,
IPv6: false,
Load: true,
},
Provisioning: {
TranslatedDuration: c('Label').ngettext(msgid`${nbDay} day`, `${nbDay} days`, nbDay),
},
},
countries: result?.Countries,
gateways: result?.Gateways,
users: result?.Users,
refresh,
};
};
export default useGateways;
| 6,998
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/vpn/gateways/useSpecificCountryCount.ts
|
import { useMemo } from 'react';
const getMaxForCountry = (country: string, remainingCount: number, deletedInCountries: Record<string, number>) =>
remainingCount -
Object.keys(deletedInCountries).reduce(
(count, otherCountry) => count + (country === otherCountry ? 0 : deletedInCountries[country]),
0
);
export const useSpecificCountryCount = (
model: { quantities?: Record<string, number> },
remainingCount: number,
deletedInCountries: Record<string, number>
) =>
useMemo(
() =>
Object.keys(model.quantities || {}).reduce(
(total, country) =>
total +
Math.max(
0,
(model.quantities?.[country] || 0) -
getMaxForCountry(country, remainingCount, deletedInCountries)
),
0
),
[model, remainingCount, deletedInCountries]
);
| 6,999
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.