Files
dawnline/web/src/admin/invite.ts
T
Aemeath 2f2aaf6c34
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
Dawnline 0.11.0
- Russian translation. The admin pages, the LuCI menu and the router's
  messages (errors, Health checks, update steps, the service log) come in
  Russian with the new luci-i18n-dawnline-ru package, released beside the
  app. LuCI shows it when its language is Russian, or "auto" with a Russian
  browser
- The translation installs with install.sh when LuCI is in Russian (or with
  --lang ru), follows every Dawnline update and rollback, and can be added
  or removed in Components → Dawnline → Translation
- The portal speaks the visitor's language: it opens in the system's
  language and switches between English and Russian in place, from the
  language pill beside its QR code. It carries its own translation and needs
  no package
- Set-up steps quote the apps' own menus word for word, in Russian too:
  AmneziaVPN is "+ → Insert → Continue" (it has no "Add server"), and the
  Mac and Windows menus of WireGuard and AmneziaWG have their real names
- Questions in the portal (Reconnect, Remove) read from the left edge and
  close with Cancel, without ×
- Numbers, sizes and dates follow the page's language. A server that can't
  start says why in one sentence; event details and service log lines read
  as whole sentences
- README in Russian (README_ru.md). rules/i18n.md: how strings are written
  and translated; CI checks the catalogs (npm run i18n:check)
2026-10-20 19:33:52 +03:00

179 lines
7.6 KiB
TypeScript

// Invite card: a picture with the person's QR code, link and three steps,
// made in the browser to share (Telegram, AirDrop) or print.
import type { Person } from '../shared/types';
import { E } from './e';
import { api } from './api';
import { button } from './ui/button';
import { closeModal, modal } from './ui/modal';
import { copyText, downloadFile } from './ui/files';
import { attempt, notify } from './ui/toast';
import { icon } from '../shared/icons';
import { qrSvg } from '../shared/qr';
import { fill, fmt } from '../shared/i18n';
const W = 1080,
H = 1512;
/** One margin for everything: header, greeting and the QR tile share both edges. */
const M = 96;
const SANS = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
const MONO = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!);
function cardSvg(p: Pick<Person, 'name'>, server: string, link: string): string {
const url = new URL(link);
const word = url.pathname.slice(1);
const hi = fmt(_('Hi, %s'), p.name);
// Long names shrink to stay on one line (roughly 0.58 em per character).
const nameSize = Math.min(92, Math.floor((W - 2 * M) / (0.58 * hi.length)));
const tile = W - 2 * M,
top = 392,
pad = 40;
const qr = qrSvg(link, 2).replace('<svg ', `<svg x="${M + pad}" y="${top + pad}" width="${tile - 2 * pad}" height="${tile - 2 * pad}" `);
const text = (x: number, y: number, size: number, fill: string, body: string, extra = '') =>
`<text x="${x}" y="${y}" font-size="${size}" fill="${fill}" font-family="${SANS}" ${extra}>${body}</text>`;
return (
`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">` +
`<rect width="${W}" height="${H}" rx="72" fill="#0b0b0b"/>` +
// Mark and server name
`<g transform="translate(${M} ${M})"><rect width="60" height="60" rx="15" fill="#fff"/>` +
`<g transform="scale(.9375)"><path d="M14 38a18 18 0 0 1 36 0z" fill="#0b0b0b"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#0b0b0b" opacity=".5"/></g></g>` +
text(M + 82, M + 42, 36, '#a3a3a3', esc(server)) +
// Greeting
text(M, 276, nameSize, '#ffffff', esc(hi), 'font-weight="600"') +
text(M, 340, 40, '#8a8a8a', esc(fmt(_('Scan to connect to %s'), server))) +
// Big QR on a white tile, edge to edge with the text above
`<rect x="${M}" y="${top}" width="${tile}" height="${tile}" rx="52" fill="#ffffff"/>` +
qr +
// The link: three words, then the host
`<text x="${W / 2}" y="${top + tile + 100}" font-size="58" fill="#ffffff" font-family="${MONO}" text-anchor="middle">${esc(word)}</text>` +
text(W / 2, top + tile + 156, 34, '#737373', esc(url.host), 'text-anchor="middle"') +
`</svg>`
);
}
async function toPng(svg: string): Promise<Blob> {
const img = new Image();
img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
await img.decode();
const canvas = document.createElement('canvas');
canvas.width = W;
canvas.height = H;
canvas.getContext('2d')!.drawImage(img, 0, 0, W, H);
return new Promise((resolve, reject) =>
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(_('Could not draw the card')))), 'image/png'),
);
}
/** Who to invite; without `link` the card asks the router for the person's links (they are not in the status). */
type Invitee = Pick<Person, 'id' | 'name'> & { link?: string | null; links?: string[] };
/** The personal link and its other addresses (person_links); null while the portal is off. */
export async function personLinks(id: string): Promise<{ link: string; links: string[] } | null> {
const r = await attempt(() => api.personLinks(id));
if (!r) return null;
if (!r.link) {
notify(_('The personal portal is off. Turn it on in Settings.'), 'warning');
return null;
}
return { link: r.link, links: r.links ?? [] };
}
/** Copy a person's personal link. */
export async function copyPersonLink(id: string) {
const r = await personLinks(id);
if (r) await copyText(r.link, _('Personal link copied'));
}
/**
* The card with Copy link and Share / Download. Also the "is ready" step
* after adding someone.
*/
export async function inviteCard(p: Invitee, server: string, opts: { title?: string; lead?: string } = {}) {
let link = p.link;
let links = p.links;
if (link === undefined) {
const r = await personLinks(p.id);
if (!r) return;
link = r.link;
links = r.links;
}
if (!link) {
notify(_('The personal portal is off. Turn it on in Settings.'), 'warning');
return;
}
const href = link;
const png = await attempt(() => toPng(cardSvg(p, server, href)));
if (!png) return;
const file = new File([png], `${p.id}-invite.png`, { type: 'image/png' });
const url = URL.createObjectURL(png);
const nav = navigator as Navigator & { canShare?: (d: unknown) => boolean };
// Three tiers: the card as a file, the link through the share sheet (older
// Android, Firefox on phones), else a download of the card.
const canShareFile = !!nav.canShare?.({ files: [file] });
const canShareLink = !canShareFile && typeof nav.share === 'function' && (nav.canShare?.({ url: href }) ?? true);
const close = () => {
URL.revokeObjectURL(url);
closeModal();
};
const shareIt = async (data: ShareData) => {
try {
await nav.share(data);
} catch {
/* cancelled */
}
};
const share = canShareFile
? button([icon('link'), ' ', _('Share card')], () => shareIt({ files: [file], title: fmt(_('Invite %s'), p.name) }), 'positive')
: canShareLink
? button(
[icon('link'), ' ', _('Share link')],
() => shareIt({ url: href, title: fmt(_('Invite %s'), p.name), text: _('Your personal VPN link') }),
'positive',
)
: button([icon('download'), ' ', _('Download card')], () => downloadFile(file.name, png), 'positive');
modal(
opts.title ?? fmt(_('Invite %s'), p.name),
E('div', { class: 'dl-invite' }, [
E('img', { src: url, alt: fmt(_('Invite card for %s'), p.name) }),
E('div', { class: 'dl-invite-side' }, [
E(
'p',
{ class: 'dl-muted' },
opts.lead ?? fmt(_('Send %s the card or the link. They open it, add their devices and connect - no account needed.'), p.name),
),
E(
'button',
{ type: 'button', class: 'dl-invite-link', title: _('Copy link'), click: () => copyText(href, _('Personal link copied')) },
[E('span', {}, href.replace(/^https:\/\//, '')), icon('copy')],
),
...(links ?? [])
.filter((l) => l !== href)
.map((l) =>
E(
'button',
{ type: 'button', class: 'dl-invite-link alt', title: _('Copy this link'), click: () => copyText(l, _('Link copied')) },
[
E('span', {}, l.replace(/^https?:\/\//, '')),
E('span', { class: `dl-pill ${l.startsWith('http:') ? 'warn' : ''}` }, l.startsWith('http:') ? 'HTTP' : _('Also')),
icon('copy'),
],
),
),
E('ol', { class: 'dl-invite-steps' }, [
E('li', {}, fill(_('Install %s on the device'), E('b', {}, 'AmneziaVPN'))),
E('li', {}, _('Open the link or scan the code')),
E('li', {}, _('Add the device and connect')),
]),
E('div', { class: 'dl-invite-actions' }, [
share,
button([icon('copy'), ' ', _('Copy link')], () => copyText(href, _('Personal link copied'))),
]),
]),
]),
[E('button', { class: 'cbi-button cbi-button-neutral', click: close }, _('Done'))],
'wide',
);
}