diff --git a/docs/mirror.md b/docs/mirror.md index 7387ebe9..9dac0c32 100644 --- a/docs/mirror.md +++ b/docs/mirror.md @@ -33,10 +33,21 @@ the new owner has confirmed it on that server's page. Settings, then Roles, and drags Sylo's role to the very top (Sylo cannot move its own role), and you look again. (Without this, a mirrored role with Manage Roles could end up above the mirrored Administrator role.) 3. To be the owner of the Discord server, and the owner of the Fluxer server to agree (or to own both). + The Fluxer server shows up in the picker only if you are its owner. ## The steps -1. **Ask.** The Discord server's owner opens the Mirror page and enters the id of the Fluxer server. +1. **Ask.** The Discord server's owner opens the Mirror page and **picks the Fluxer server from a list**. The + list holds the Fluxer servers where Sylo is a member and where you are the owner, going by the Fluxer login + you connected under Account. Each entry shows the server's name, icon and member count, and a note when Sylo's + role there lacks the Administrator permission or is not the top role (the same checks the preview makes; they + do not stop you from picking, the preview does). A server that is already part of a mirror is shown but cannot + be picked. Picking one fills in the request. If you own the Fluxer server too, both sides agree at once (next + step). + - **No Fluxer login connected?** The page says "Connect Fluxer under Account to pick your Fluxer servers" and + links to Account. + - **The Fluxer server belongs to someone else?** Choose **Enter an id instead** and paste the server's id + (copy it on Fluxer with Developer Mode on). Its owner then agrees with the code, as below. 2. **Agree.** Nothing is created until the owner of the Fluxer server has agreed: - If you own both servers with your own account (you signed in with Discord and also connected Fluxer under Account), both sides agree at once. @@ -186,6 +197,12 @@ Looking at the page, the preview and the report needs View access. Everything th server's owner (see the top), on the server the action is made on. Every action looks only at the mirror the server is part of, so a code or an id of another server reaches nothing. +The list of Fluxer servers on the Ask step (`GET /api/v2/guilds//mirror/fluxer-servers`) is asked for only by +the owner of the Discord server, is rate limited, and names only Fluxer servers that the caller's own Fluxer login +lists and that Fluxer reports the caller as the owner of. A server somebody else owns is never named, even to its +Administrators. On an instance with sign-in switched off there is no account to compare, so every Fluxer server Sylo +is in is listed, as with the other access checks. + ## For the app A Sylo that has the mirror lists `mirror` in the `features` of `GET /api/mobile/info`. See the diff --git a/docs/modules/bridge.md b/docs/modules/bridge.md index f49d3e65..971499e1 100644 --- a/docs/modules/bridge.md +++ b/docs/modules/bridge.md @@ -10,6 +10,12 @@ Sylo is) and that is a member of both servers. **Dashboard:** `/v2/guilds//m/bridge` - the linked channels, a form to ask for a link, a form to use a code, what this server shares, and pause, resume and unlink. +**Setting up a whole Fluxer server?** Linking channels one by one is for single conversations. To copy a +Discord server's channels, roles and emoji to a Fluxer server and bridge every channel at once, use +[Mirror to Fluxer](../mirror.md). The Bridge page of a Discord server points to it with a short note and a +link; the note is shown only to the server's owner and only when Sylo is connected to both platforms. It is not +shown on a Fluxer server: the mirror's target is chosen from the Discord side. + ## Who can use it: the server owner **Only the owner of a server can use the bridge** (the Discord server owner, the Fluxer server owner), on diff --git a/src/web/lib/routeAccess.js b/src/web/lib/routeAccess.js index df75b7c8..3d0c9ae7 100644 --- a/src/web/lib/routeAccess.js +++ b/src/web/lib/routeAccess.js @@ -329,6 +329,8 @@ export const ROUTE_ACCESS = Object.freeze({ 'GET /guilds/:guildId/mirror': 'view', 'GET /guilds/:guildId/mirror/preview': 'view', 'GET /guilds/:guildId/mirror/report': 'view', + // The picker of the Fluxer servers the person owns is part of asking: Edit, and the server owner (checked in the route). + 'GET /guilds/:guildId/mirror/fluxer-servers': 'edit', 'POST /guilds/:guildId/mirror/request': 'edit', 'POST /guilds/:guildId/mirror/accept': 'edit', 'POST /guilds/:guildId/mirror/options': 'edit', diff --git a/src/web/routes/v2Mirror.js b/src/web/routes/v2Mirror.js index defe7b93..5e691c01 100644 --- a/src/web/routes/v2Mirror.js +++ b/src/web/routes/v2Mirror.js @@ -17,6 +17,7 @@ import { PAIR_STATUS, pairsOfGuild, updatePair } from '../../db/mirror.js'; import { recordAudit } from '../../db/audit.js'; import { accessRouter } from '../middleware/access.js'; import { adminGuildIds, currentUser, userIdForGuild } from '../middleware/auth.js'; +import { identityFor } from '../lib/accountAuth.js'; import { isGuildOwner } from '../lib/guildOwner.js'; import { platformActionKey, rateLimit } from '../middleware/rateLimit.js'; import { asyncHandler } from '../lib/asyncHandler.js'; @@ -25,6 +26,7 @@ import { mirror } from '../../mirror/index.js'; import { ConsentError, acceptMirror, requestMirror } from '../../mirror/consent.js'; import { MirrorError } from '../../mirror/errors.js'; import { DEFAULT_OPTIONS, FLUXER_LIMITS, normaliseOptions } from '../../mirror/spec.js'; +import { createFluxerTarget } from '../../mirror/target.js'; import { invalidateHealth } from '../../lib/healthCache.js'; const router = accessRouter('/guilds/:guildId', { mergeParams: true }); @@ -54,6 +56,13 @@ const startLimit = rateLimit({ message: 'The copy was started several times just now. Wait a few minutes.', keyFn: (req) => `mirror-start|${platformActionKey(req)}`, }); +// The list of the person's Fluxer servers reads each one's roles; it is asked for when the page opens. +const listLimit = rateLimit({ + windowMs: 60_000, + max: 12, + message: 'The list of Fluxer servers was asked for too often. Wait a minute.', + keyFn: (req) => `mirror-servers|${platformActionKey(req)}`, +}); const controlLimit = rateLimit({ windowMs: 60_000, max: 20, @@ -118,13 +127,6 @@ function pairView(pair, side) { async function stateOf(req) { const platform = platformOfGuild(req.guild); const found = await pairOf(req); - const candidates = - platform === 'discord' && isGuildOwner(req, req.guild.id) - ? [...adminGuildIds(req)] - .filter((k) => splitPlatformGuildId(k)?.platform === 'fluxer') - .filter((k) => isGuildOwner(req, k)) - .map((k) => ({ id: k, name: guildByKey(k)?.name ?? k })) - : []; return { platform, canMirror: platform === 'discord', @@ -133,7 +135,6 @@ async function stateOf(req) { isOwner: isGuildOwner(req, req.guild.id), pair: found ? pairView(found.pair, found.side) : null, progress: found ? await mirror.progress(found.pair) : null, - candidates, defaults: DEFAULT_OPTIONS, limits: { emoji: FLUXER_LIMITS.emoji, stickers: FLUXER_LIMITS.stickers }, }; @@ -147,6 +148,77 @@ router.get( }) ); +/** How many of a person's Fluxer servers the list names at most. */ +const MAX_FLUXER_CHOICES = 100; + +/** + * What the picker says about one Fluxer server, checked as the preview checks it (src/mirror/engine.js): Sylo's role + * needs Administrator there (or the four permissions the copy uses) and has to be the highest role. These are + * notes, not blockers: the preview is where they stop a copy. + */ +async function choiceOf(key, guild) { + const notes = []; + try { + const target = createFluxerTarget(guild); + if (target.missingPermissions().length) { + notes.push({ + code: 'target-permissions', + message: "Sylo's role needs the Administrator permission on this server.", + }); + } + const above = target.rolesAboveSylo([]); + if (above === null) { + notes.push({ code: 'role-hierarchy', message: "Sylo's own role on this server could not be read." }); + } else if (above.length > 0) { + notes.push({ + code: 'role-hierarchy', + message: `Sylo's role is not the highest on this server (${above.length} ${above.length === 1 ? 'role ranks' : 'roles rank'} above or level with it). Drag it to the top under Server Settings, then Roles.`, + }); + } + } catch { + notes.push({ code: 'unreadable', message: 'Sylo could not read the roles on this server just now.' }); + } + const busy = (await pairsOfGuild(key)).length > 0; + const members = Number(guild.memberCount ?? guild.members?.cache?.size ?? 0); + return { + id: key, + name: String(guild.name ?? key), + icon: guild.iconURL?.({ size: 64 }) ?? null, + memberCount: Number.isFinite(members) && members > 0 ? members : null, + inUse: busy, + notes, + }; +} + +// The Fluxer servers to pick the mirror's target from: those Sylo is a member of and the signed-in person owns +// according to their own connected Fluxer login (the owner id Fluxer reports, never a list the browser sends). A +// server they do not own is never named. Only the owner of this Discord server may ask, as for the request itself. +router.get( + '/mirror/fluxer-servers', + listLimit, + asyncHandler(async (req, res) => { + res.set('Cache-Control', 'no-store'); + if (platformOfGuild(req.guild) !== 'discord') { + return fail(res, 'Only a Discord server can be mirrored. Ask for the mirror on the Discord server.'); + } + if (!needOwner(req, res, 'pick a Fluxer server for a mirror')) return; + // Open mode has no logins, so there is no identity to look for (and every server counts as the caller's). + const connected = !config.authEnabled || Boolean(identityFor(req.account, 'fluxer')); + const servers = []; + if (config.fluxerEnabled && connected) { + const keys = [...adminGuildIds(req)] + .filter((k) => splitPlatformGuildId(k)?.platform === 'fluxer') + .filter((k) => isGuildOwner(req, k)); + for (const key of keys.slice(0, MAX_FLUXER_CHOICES)) { + const guild = guildByKey(key); + if (guild) servers.push(await choiceOf(key, guild)); + } + servers.sort((a, b) => a.name.localeCompare(b.name)); + } + res.json({ fluxerConnected: config.fluxerEnabled, connected, servers }); + }) +); + /** A raw Fluxer id, or "fluxer:", as a key. Null when it is neither. */ function fluxerKeyOf(raw) { const text = String(raw ?? '').trim(); diff --git a/test/v2.accessLevels.test.js b/test/v2.accessLevels.test.js index 25d0f348..c74b0599 100644 --- a/test/v2.accessLevels.test.js +++ b/test/v2.accessLevels.test.js @@ -187,6 +187,7 @@ const GETS_ABOVE_VIEW = { 'GET /guilds/:guildId/applications/submissions/:id': 'inbox', 'GET /guilds/:guildId/applications/export': 'inbox', 'GET /guilds/:guildId/export': 'edit', + 'GET /guilds/:guildId/mirror/fluxer-servers': 'edit', }; test('every /api/v2 route declares its access level, and every declaration has a route', () => { diff --git a/test/v2Mirror.test.js b/test/v2Mirror.test.js index 32bc6bb4..eefa50ef 100644 --- a/test/v2Mirror.test.js +++ b/test/v2Mirror.test.js @@ -79,7 +79,7 @@ test('the owner of the Discord server asks; the owner of the Fluxer server agree [empty.platform, empty.canMirror, empty.pair, empty.isOwner], ['discord', true, null, true] ); - assert.equal(empty.candidates.length, 0, 'this person owns no Fluxer server'); + assert.ok(!('candidates' in empty), 'the Fluxer servers come from their own route'); const res = await anna.post(`/guilds/${D_GUILD}/mirror/request`, { targetGuildId: F_GUILD }); assert.equal(res.status, 200); @@ -216,9 +216,9 @@ test('the same person who owns both servers agrees on both sides at once', async await reset(); const both = await person({ discord: true, fluxer: true }); owners({ discord: both.ids.discord, fluxer: both.ids.fluxer }); - const state = await (await both.get(`/guilds/${D_GUILD}/mirror`)).json(); + const list = await (await both.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).json(); assert.deepEqual( - state.candidates.map((c) => c.id), + list.servers.map((c) => c.id), [F_KEY], 'the Fluxer servers this person owns are offered' ); @@ -244,8 +244,8 @@ test('an owner of one server who is only an Administrator of the other is not en await reset(); const mixed = await person({ discord: true, fluxer: true }); owners({ discord: mixed.ids.discord, fluxer: 'someone-else' }); // owns Discord, is not the Fluxer owner - const state = await (await mixed.get(`/guilds/${D_GUILD}/mirror`)).json(); - assert.deepEqual(state.candidates, [], 'a Fluxer server they do not own is not offered'); + const list = await (await mixed.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).json(); + assert.deepEqual(list.servers, [], 'a Fluxer server they do not own is not offered'); const res = await mixed.post(`/guilds/${D_GUILD}/mirror/request`, { targetGuildId: F_KEY, options: { mirrorDeletes: true }, @@ -418,3 +418,166 @@ test('signed out and without a CSRF token, nothing works', async () => { assert.ok([401, 403].includes(noToken.status)); assert.equal((await anna.get(`/guilds/${D_GUILD}/mirror`)).status, 200); }); + +// ---- the picker of the Fluxer servers ------------------------------------------------------------------ + +const F_OTHER_OWNER = '900000000000000204'; // Fluxer says it is theirs (OAuth), the gateway says it is somebody else's +const F_NOT_LISTED = '900000000000000205'; // the gateway says they own it, their login does not list it +const SYLO_ROLE = '900000000000000301'; + +/** Add servers to the fake Fluxer bot, run `fn`, and take them away again. */ +async function withFluxerGuilds(extra, fn) { + const cache = runtime.clients.fluxer.guilds.cache; + for (const g of extra) cache.set(g.id, g); + try { + return await fn(); + } finally { + for (const g of extra) cache.delete(g.id); + } +} +const copyOfF = (id, name, ownerId) => ({ ...fGuild, id, name, ownerId }); + +/** Sylo's own member on a fake Fluxer server: its permissions and where its role stands among `roles`. */ +function syloIs(guild, { administrator = true, roles = [] } = {}) { + guild.members = { + ...guild.members, + me: { + permissions: { has: () => administrator }, + roles: { highest: { id: SYLO_ROLE, position: 5 } }, + }, + }; + guild.roles = { cache: new Map(roles.map((r) => [r.id, r])) }; +} + +test('the picker lists the Fluxer servers the person owns and Sylo is in, with a note for what Sylo lacks there', async () => { + await reset(); + const both = await person({ discord: true, fluxer: true }); + owners({ discord: both.ids.discord, fluxer: both.ids.fluxer }); + const saved = { members: fGuild.members, roles: fGuild.roles, memberCount: fGuild.memberCount }; + try { + // Sylo is not the top role, and lacks Administrator. + syloIs(fGuild, { + administrator: false, + roles: [ + { id: SYLO_ROLE, name: 'Sylo', position: 5 }, + { id: '900000000000000302', name: 'Admins', position: 9 }, + ], + }); + fGuild.memberCount = 42; + const res = await both.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`); + assert.equal(res.status, 200); + assert.equal(res.headers.get('cache-control'), 'no-store'); + const body = await res.json(); + assert.equal(body.connected, true); + assert.equal(body.servers.length, 1); + const [one] = body.servers; + assert.deepEqual( + [one.id, one.name, one.memberCount, one.inUse, one.icon], + [F_KEY, 'F-main', 42, false, null] + ); + assert.deepEqual(one.notes.map((n) => n.code).sort(), ['role-hierarchy', 'target-permissions']); + + // Sylo is the top role with Administrator: no notes. + syloIs(fGuild, { roles: [{ id: SYLO_ROLE, name: 'Sylo', position: 5 }] }); + const clean = (await (await both.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).json()).servers[0]; + assert.deepEqual(clean.notes, []); + + // A server that is already part of a mirror says so. + await both.post(`/guilds/${D_GUILD}/mirror/request`, { targetGuildId: F_KEY }); + const taken = (await (await both.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).json()).servers[0]; + assert.equal(taken.inUse, true); + } finally { + Object.assign(fGuild, saved); + await reset(); + } +}); + +test('the picker never names a Fluxer server the person does not own', async () => { + await reset(); + const other = copyOfF(F_OTHER_OWNER, 'Secret-other-server', 'somebody-else'); + const unlisted = copyOfF(F_NOT_LISTED, 'Secret-unlisted-server', 'placeholder'); + await withFluxerGuilds([other, unlisted], async () => { + setProfiles(); + profiles.fluxer.guilds = [ + { id: F_GUILD, owner: true }, + { id: F_OTHER_OWNER, owner: true }, + ]; + const b = own(); + await signIn(b, 'discord'); + await signIn(b, 'fluxer', { connect: true }); + const get = (path) => b.get(`/api/v2${path}`, { headers: { accept: 'application/json' } }); + dGuild.ownerId = profiles.discord.id; + fGuild.ownerId = 'somebody-else'; + other.ownerId = 'somebody-else'; + unlisted.ownerId = profiles.fluxer.id; + + const text = await (await get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).text(); + const body = JSON.parse(text); + assert.deepEqual(body.servers, [], 'no server they own: an empty list'); + for (const secret of [ + 'F-main', + 'Secret-other-server', + 'Secret-unlisted-server', + F_GUILD, + F_OTHER_OWNER, + F_NOT_LISTED, + ]) { + assert.ok(!text.includes(secret), `${secret} is not in the answer`); + } + + // Now they own the first one only: the other two stay out. + fGuild.ownerId = profiles.fluxer.id; + const mine = await (await get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).json(); + assert.deepEqual( + mine.servers.map((x) => x.id), + [F_KEY] + ); + }); +}); + +test('the picker says when no Fluxer login is connected, and only the owner of the Discord server may ask', async () => { + await reset(); + const discordOnly = await person({ discord: true }); + owners({ discord: discordOnly.ids.discord, fluxer: discordOnly.ids.fluxer }); + const none = await (await discordOnly.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).json(); + assert.deepEqual([none.connected, none.servers], [false, []]); + + const admin = await person({ discord: true, fluxer: true, admin: true }); + owners({ discord: 'somebody-else', fluxer: admin.ids.fluxer }); + const refused = await admin.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`); + assert.equal(refused.status, 403); + const refusedBody = await refused.json(); + assert.equal(refusedBody.code, 'owner-only'); + assert.ok(!JSON.stringify(refusedBody).includes('F-main')); + + const onFluxer = await person({ discord: true, fluxer: true }); + owners({ discord: onFluxer.ids.discord, fluxer: onFluxer.ids.fluxer }); + assert.equal((await onFluxer.get(`/guilds/${F_KEY}/mirror/fluxer-servers`)).status, 400); + + const out = own(); + assert.ok( + [401, 403].includes( + ( + await out.get(`/api/v2/guilds/${D_GUILD}/mirror/fluxer-servers`, { + headers: { accept: 'application/json' }, + }) + ).status + ), + 'signed out' + ); +}); + +test('the picker is rate limited and classified in the access table', async () => { + await reset(); + const { ROUTE_ACCESS } = await import('../src/web/lib/routeAccess.js'); + assert.equal(ROUTE_ACCESS['GET /guilds/:guildId/mirror/fluxer-servers'], 'edit'); + const both = await person({ discord: true, fluxer: true }); + owners({ discord: both.ids.discord, fluxer: both.ids.fluxer }); + let last = 0; + for (let i = 0; i < 14; i++) last = (await both.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).status; + assert.equal(last, 429); + // Another person has a budget of their own. + const next = await person({ discord: true, fluxer: true }); + owners({ discord: next.ids.discord, fluxer: next.ids.fluxer }); + assert.equal((await next.get(`/guilds/${D_GUILD}/mirror/fluxer-servers`)).status, 200); +}); diff --git a/web-v2/src/__tests__/Bridge.test.jsx b/web-v2/src/__tests__/Bridge.test.jsx index f9f1e907..f89ea69f 100644 --- a/web-v2/src/__tests__/Bridge.test.jsx +++ b/web-v2/src/__tests__/Bridge.test.jsx @@ -70,6 +70,27 @@ describe('Bridge page', () => { expect(api.getBridge).toHaveBeenCalledWith(GUILD); }); + it('points the owner of a Discord server to Mirror to Fluxer, and shows it to nobody else', async () => { + renderAtGuild(, GUILD); + expect(await screen.findByText(/Setting up a whole Fluxer server\?/)).toBeTruthy(); + expect( + screen.getByText(/copy channels, roles and emoji and\s+bridge every channel at once/) + ).toBeTruthy(); + const link = screen.getByRole('link', { name: 'Mirror to Fluxer' }); + expect(link.getAttribute('href')).toBe(`/guilds/${GUILD}/mirror`); + }); + + it('hides the Mirror hint from people who are not the owner, on a Fluxer server, and without both platforms', async () => { + for (const over of [{ owner: false }, { platform: 'fluxer' }, { bothPlatforms: false }]) { + api.getBridge.mockResolvedValue(overview(over)); + const { unmount } = renderAtGuild(, GUILD); + await screen.findByRole('heading', { name: 'Bridge' }); + expect(screen.queryByText(/Setting up a whole Fluxer server/)).toBeNull(); + expect(screen.queryByRole('link', { name: 'Mirror to Fluxer' })).toBeNull(); + unmount(); + } + }); + it('names the other platform, and explains that nothing pings and bots are off', async () => { renderAtGuild(, GUILD); await screen.findByRole('heading', { name: 'Bridge' }); diff --git a/web-v2/src/__tests__/Mirror.test.jsx b/web-v2/src/__tests__/Mirror.test.jsx index b10d9236..9201fb16 100644 --- a/web-v2/src/__tests__/Mirror.test.jsx +++ b/web-v2/src/__tests__/Mirror.test.jsx @@ -6,6 +6,7 @@ import { renderAtGuild } from './routerHarness.jsx'; vi.mock('../api.js', () => ({ ApiError: class ApiError extends Error {}, getMirror: vi.fn(), + getMirrorFluxerServers: vi.fn(), allowMirrorDeletes: vi.fn(), getMirrorPreview: vi.fn(), getMirrorReport: vi.fn(), @@ -62,7 +63,6 @@ const state = (over = {}) => ({ fluxerConnected: true, pair: null, progress: null, - candidates: [{ id: FLUXER, name: 'Fluxer copy' }], defaults: OPTIONS, limits: { emoji: 50, stickers: 50 }, ...over, @@ -78,23 +78,37 @@ const progress = (over = {}) => ({ waitingChanges: 0, ...over, }); -const fluxerState = (p) => state({ platform: 'fluxer', canMirror: false, candidates: [], pair: p }); +const fluxerState = (p) => state({ platform: 'fluxer', canMirror: false, pair: p }); + +const choice = (over = {}) => ({ + id: FLUXER, + name: 'Fluxer copy', + icon: null, + memberCount: 12, + inUse: false, + notes: [], + ...over, +}); +const choices = (servers, over = {}) => ({ fluxerConnected: true, connected: true, servers, ...over }); beforeEach(() => { vi.resetAllMocks(); confirmDialog.mockResolvedValue(true); + api.getMirrorFluxerServers.mockResolvedValue(choices([])); }); describe('Mirror: the Discord server', () => { it('asks for a mirror with the id of the Fluxer server, and shows the one-time code that comes back', async () => { api.getMirror.mockResolvedValue(state()); + api.getMirrorFluxerServers.mockResolvedValue(choices([choice()])); api.requestMirror.mockResolvedValue({ ...state({ pair: pair({ status: 'pending', otherName: null, codeExpiresAt: Date.now() + 3_000_000 }) }), code: 'K7QW-H2NP', }); renderAtGuild(, GUILD); const button = await screen.findByRole('button', { name: 'Ask for the mirror' }); - const input = screen.getByLabelText('Fluxer server'); + fireEvent.click(await screen.findByRole('button', { name: 'Enter an id instead' })); + const input = screen.getByLabelText('Fluxer server id'); fireEvent.change(input, { target: { value: 'nonsense' } }); expect(button.disabled).toBe(true); fireEvent.change(input, { target: { value: FLUXER } }); @@ -229,6 +243,91 @@ describe('Mirror: the Discord server', () => { }); }); +describe('Mirror: picking the Fluxer server', () => { + it('lists the Fluxer servers the person owns with name, members and notes, and picking one fills the request', async () => { + api.getMirror.mockResolvedValue(state()); + api.getMirrorFluxerServers.mockResolvedValue( + choices([ + choice({ + notes: [ + { + code: 'target-permissions', + message: "Sylo's role needs the Administrator permission on this server.", + }, + { + code: 'role-hierarchy', + message: "Sylo's role is not the highest on this server (1 role ranks above or level with it).", + }, + ], + }), + choice({ + id: 'fluxer:323456789012345678', + name: 'Second', + memberCount: 1204, + icon: 'https://cdn.test/i.png', + }), + choice({ id: 'fluxer:423456789012345678', name: 'Busy', memberCount: null, inUse: true }), + ]) + ); + api.requestMirror.mockResolvedValue(state({ pair: pair({ status: 'pending', otherName: null }) })); + renderAtGuild(, GUILD); + const button = await screen.findByRole('button', { name: 'Ask for the mirror' }); + expect(api.getMirrorFluxerServers).toHaveBeenCalledWith(GUILD); + expect(await screen.findByText('Fluxer copy')).toBeTruthy(); + expect(screen.getByText('12 members')).toBeTruthy(); + expect(screen.getByText('1,204 members')).toBeTruthy(); + expect(screen.getByText(/needs the Administrator permission/)).toBeTruthy(); + expect(screen.getByText(/not the highest on this server/)).toBeTruthy(); + expect(screen.getByText(/already part of a mirror/)).toBeTruthy(); + expect(screen.getByLabelText(/Busy/).disabled).toBe(true); + expect(screen.queryByLabelText('Fluxer server id')).toBeNull(); + // Nothing is picked for the person. + expect(button.disabled).toBe(true); + fireEvent.click(screen.getByLabelText(/Fluxer copy/)); + expect(button.disabled).toBe(false); + fireEvent.click(button); + await waitFor(() => expect(api.requestMirror).toHaveBeenCalledWith(GUILD, FLUXER)); + }); + + it('keeps the manual id field behind "Enter an id instead", and back', async () => { + api.getMirror.mockResolvedValue(state()); + api.getMirrorFluxerServers.mockResolvedValue(choices([choice()])); + renderAtGuild(, GUILD); + fireEvent.click(await screen.findByLabelText(/Fluxer copy/)); + fireEvent.click(screen.getByRole('button', { name: 'Enter an id instead' })); + const input = screen.getByLabelText('Fluxer server id'); + expect(input.value).toBe(''); + expect(screen.getByRole('button', { name: 'Ask for the mirror' }).disabled).toBe(true); + expect(screen.getByText(/If you do not own that Fluxer server/)).toBeTruthy(); + fireEvent.click(screen.getByRole('button', { name: 'Pick from my Fluxer servers instead' })); + expect(screen.queryByLabelText('Fluxer server id')).toBeNull(); + expect(screen.getByLabelText(/Fluxer copy/)).toBeTruthy(); + }); + + it('says to connect Fluxer under Account when the person has no Fluxer login', async () => { + api.getMirror.mockResolvedValue(state()); + api.getMirrorFluxerServers.mockResolvedValue(choices([], { connected: false })); + renderAtGuild(, GUILD); + const link = await screen.findByRole('link', { name: 'Connect Fluxer under Account' }); + expect(link.getAttribute('href')).toBe('/account'); + expect(screen.getByText(/to pick your Fluxer servers/)).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Enter an id instead' })).toBeTruthy(); + }); + + it('says so when no Fluxer server is found, and falls back to the id field when the list fails', async () => { + api.getMirror.mockResolvedValue(state()); + const { unmount } = renderAtGuild(, GUILD); + expect( + await screen.findByText(/No Fluxer server was found where Sylo is a member and you are the owner/) + ).toBeTruthy(); + unmount(); + api.getMirrorFluxerServers.mockRejectedValue(new Error('boom')); + renderAtGuild(, GUILD); + expect(await screen.findByLabelText('Fluxer server id')).toBeTruthy(); + expect(screen.getByText(/could not be listed/)).toBeTruthy(); + }); +}); + describe('Mirror: the Fluxer server', () => { it('explains how to start when there is no mirror', async () => { api.getMirror.mockResolvedValue(fluxerState(null)); @@ -265,11 +364,12 @@ describe('Mirror: the Fluxer server', () => { describe('Mirror: only the owner, and the pauses', () => { it('lets people without ownership look, but not change anything', async () => { - api.getMirror.mockResolvedValue(state({ isOwner: false, candidates: [] })); + api.getMirror.mockResolvedValue(state({ isOwner: false })); renderAtGuild(, GUILD); expect(await screen.findByText(/Only the server owner can do this/)).toBeTruthy(); expect(screen.getByRole('button', { name: 'Ask for the mirror' }).matches(':disabled')).toBe(true); - expect(screen.getByLabelText('Fluxer server').matches(':disabled')).toBe(true); + expect(screen.getByLabelText('Fluxer server id').matches(':disabled')).toBe(true); + expect(api.getMirrorFluxerServers).not.toHaveBeenCalled(); }); it('shows the status and the stop button as locked for a non-owner on a running mirror', async () => { diff --git a/web-v2/src/api.js b/web-v2/src/api.js index bf6a2736..f394f596 100644 --- a/web-v2/src/api.js +++ b/web-v2/src/api.js @@ -499,6 +499,9 @@ export const applySetup = (guildId, body) => postJson(`/api/v2/guilds/${gid(guil export const getMirror = (guildId) => apiFetch(`/api/v2/guilds/${gid(guildId)}/mirror`); export const getMirrorPreview = (guildId) => apiFetch(`/api/v2/guilds/${gid(guildId)}/mirror/preview`); export const getMirrorReport = (guildId) => apiFetch(`/api/v2/guilds/${gid(guildId)}/mirror/report`); +// The Fluxer servers the signed-in person owns and Sylo is in: the choices for the mirror's target. +export const getMirrorFluxerServers = (guildId) => + apiFetch(`/api/v2/guilds/${gid(guildId)}/mirror/fluxer-servers`); export const requestMirror = (guildId, targetGuildId, options) => postJson(`/api/v2/guilds/${gid(guildId)}/mirror/request`, { targetGuildId, diff --git a/web-v2/src/mirrorModel.js b/web-v2/src/mirrorModel.js index 873f1998..1caa4e4f 100644 --- a/web-v2/src/mirrorModel.js +++ b/web-v2/src/mirrorModel.js @@ -137,3 +137,9 @@ export function codeLeft(expiresAt, now = Date.now()) { /** The id the person typed or picked as the Fluxer server: a raw id or "fluxer:" is accepted. */ export const validTargetId = (text) => /^(fluxer:)?\d{17,20}$/.test(String(text ?? '').trim()); + +/** "1 member", "1,204 members", or a plain note when Fluxer did not say. */ +export const memberCountText = (n) => + Number.isFinite(n) && n > 0 + ? `${n.toLocaleString('en-US')} ${n === 1 ? 'member' : 'members'}` + : 'Members not known'; diff --git a/web-v2/src/moduleForms/Bridge.jsx b/web-v2/src/moduleForms/Bridge.jsx index 6e87bc89..3f7fcf02 100644 --- a/web-v2/src/moduleForms/Bridge.jsx +++ b/web-v2/src/moduleForms/Bridge.jsx @@ -1,5 +1,5 @@ import { useState } from 'react'; -import { useParams } from 'react-router-dom'; +import { Link, useParams } from 'react-router-dom'; import { acceptBridgeLink, bridgeLinkAction, @@ -12,6 +12,7 @@ import { notify } from '../notify.js'; import { useApiData } from '../useApiData.js'; import LoadError from '../components/LoadError.jsx'; import HowItWorks from '../components/HowItWorks.jsx'; +import Callout from '../components/Callout.jsx'; import CopyButton from '../components/CopyButton.jsx'; import EmptyList from '../components/EmptyList.jsx'; import RowActions from '../components/RowActions.jsx'; @@ -185,6 +186,13 @@ export default function Bridge() { write as they always do, and Sylo shows each message on the other side with the author's name and picture.

+ {data.platform === 'discord' && data.bothPlatforms && owner ? ( + + Setting up a whole Fluxer server? Use{' '} + Mirror to Fluxer to copy channels, roles and emoji and + bridge every channel at once. + + ) : null}

Both servers agree. One asks for a link and gets a code that works for 15 minutes; the owner of the diff --git a/web-v2/src/pages/Mirror.jsx b/web-v2/src/pages/Mirror.jsx index 6048eaf9..d3b87c3a 100644 --- a/web-v2/src/pages/Mirror.jsx +++ b/web-v2/src/pages/Mirror.jsx @@ -1,9 +1,10 @@ import { createContext, useCallback, useContext, useEffect, useState } from 'react'; -import { useParams } from 'react-router-dom'; +import { Link, useParams } from 'react-router-dom'; import { acceptMirror, allowMirrorDeletes, getMirror, + getMirrorFluxerServers, getMirrorPreview, getMirrorReport, mirrorAction, @@ -21,6 +22,7 @@ import Switch from '../components/Switch.jsx'; import Time from '../components/Time.jsx'; import CopyButton from '../components/CopyButton.jsx'; import { confirmDialog } from '../components/ConfirmDialog.jsx'; +import { initial } from '../util.js'; import { OPTION_HINTS, OPTION_ROWS, @@ -30,6 +32,7 @@ import { deleteSummary, groupNotes, isBusy, + memberCountText, progressText, statusOf, stepOf, @@ -278,7 +281,7 @@ function SourceView({ guildId, state, onState, code }) { of the Fluxer server, can set up and run a mirror.

- {!pair ? : null} + {!pair ? : null} {pair?.status === 'pending' ? ( ) : null} @@ -290,8 +293,151 @@ function SourceView({ guildId, state, onState, code }) { ); } +/** One Fluxer server in the picker: icon, name, members, and what Sylo still needs there. */ +function ServerChoice({ server, selected, onPick }) { + const id = `mirror-pick-${server.id}`; + return ( +
  • + onPick(server.id)} + /> + + {server.inUse ? ( +

    This server is already part of a mirror.

    + ) : null} + {server.notes.map((n) => ( +

    + {n.message} +

    + ))} +
  • + ); +} + +/** + * Which Fluxer server to mirror to: a list of the ones the signed-in person owns on Fluxer and Sylo is in, or, behind + * "Enter an id instead", an id typed in (for a Fluxer server somebody else owns: its owner then agrees with a code). + */ +function ServerPicker({ guildId, state, target, setTarget }) { + const canList = state.isOwner !== false && state.fluxerConnected; + const [manual, setManual] = useState(false); + // 'loading' | 'ready' | 'failed' + const [list, setList] = useState({ status: canList ? 'loading' : 'failed', data: null }); + + useEffect(() => { + if (!canList) return undefined; + let live = true; + getMirrorFluxerServers(guildId) + .then((data) => live && setList({ status: 'ready', data })) + .catch(() => live && setList({ status: 'failed', data: null })); + return () => { + live = false; + }; + }, [guildId, canList]); + + const servers = list.data?.servers ?? []; + const connected = list.data?.connected !== false; + const showManual = manual || !canList || list.status === 'failed'; + + if (showManual) { + return ( + <> + {list.status === 'failed' && canList ? ( +

    Your Fluxer servers could not be listed just now.

    + ) : null} + + setTarget(e.target.value)} + placeholder="Server id" + autoComplete="off" + spellCheck={false} + /> + + {manual && canList && list.status === 'ready' ? ( +

    + If you do not own that Fluxer server, its owner agrees with a code you give them.{' '} + +

    + ) : null} + + ); + } + + return ( +
    +

    + Pick the Fluxer server +

    + {list.status === 'loading' ?

    Looking for your Fluxer servers…

    : null} + {list.status === 'ready' && !connected ? ( + + Connect Fluxer under Account to pick your Fluxer servers. + + ) : null} + {list.status === 'ready' && connected && servers.length === 0 ? ( +

    + No Fluxer server was found where Sylo is a member and you are the owner. Invite Sylo to your server + first, or enter an id instead. +

    + ) : null} + {servers.length ? ( +
      + {servers.map((server) => ( + + ))} +
    + ) : null} + {list.status === 'ready' ? ( +

    + +

    + ) : null} +
    + ); +} + function AskStep({ guildId, state, onState }) { - const [target, setTarget] = useState(state.candidates[0]?.id ?? ''); + const [target, setTarget] = useState(''); const { working, act } = useAct(onState); const valid = validTargetId(target); @@ -308,35 +454,12 @@ function AskStep({ guildId, state, onState }) { ) : null}
    1. On Fluxer, create an empty server for the mirror.
    2. -
    3. Invite Sylo to it and give Sylo's role the Administrator permission.
    4. -
    5. Enter the id of that Fluxer server below.
    6. +
    7. Invite Sylo to it and give Sylo's role the Administrator permission, at the top of the roles.
    8. +
    9. Pick that Fluxer server below.
    - - setTarget(e.target.value)} - placeholder="Server id" - autoComplete="off" - spellCheck={false} - /> - - - {state.candidates.map((c) => ( - - ))} - +