~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
main
214 lines · 7.7 KB Raw History
import type * as resolveHandle from '#lib/lexicons/com/atproto/identity/resolveHandle.ts';
import type * as getActorInvites from '#lib/lexicons/org/atgrp/internal/getActorInvites.ts';
import type * as getGroup from '#lib/lexicons/org/atgrp/internal/getGroup.ts';
import type * as listConnectedApps from '#lib/lexicons/org/atgrp/internal/listConnectedApps.ts';
import type * as listInvites from '#lib/lexicons/org/atgrp/internal/listInvites.ts';
import type * as listMembers from '#lib/lexicons/org/atgrp/internal/listMembers.ts';
import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { act, xrpc } from '#lib/data.ts';
import { asGroup, membersOf } from '#lib/asGroup.ts';
import { changes, switchedOffActions } from '#lib/server/settings.ts';
import { m } from '#lib/paraglide/messages.js';

type Handle = `${string}.${string}`;

/** Someone's inbox, where groups write their invites to them. */
const inboxOf = (did: string) => `at:space/${did}/org.atgrp.inbox/self`;

/** The group the page's address names, by its handle: its DID. */
async function groupOf(event: { fetch: typeof fetch; params: { handle?: string } }) {
  const handle = (event.params.handle ?? '') as Handle;
  const answer = await xrpc<typeof resolveHandle.main>(
    event,
    'com.atproto.identity.resolveHandle',
    { handle }
  );
  return answer.did;
}

/** How many members a page shows at first, and how many more each time it shows more. */
const STEP = 5;

/**
 * A group, by its handle, as the person looking may see it: to a member
 * who may read them, its members, `shown` of them (five more each time)
 * whose handle holds `q`; its invites waiting, for one who may invite;
 * the AI apps a member connected; whether its settings have anything
 * for them; and to one not in it, whether it has invited them.
 */
export const load: PageServerLoad = async (event) => {
  const group = await groupOf(event);
  const view = await xrpc<typeof getGroup.main>(event, 'org.atgrp.internal.getGroup', {
    group
  });
  const viewer = view.group.viewer;
  const q = event.url.searchParams.get('q')?.trim() ?? '';
  const more = Math.floor(Number(event.url.searchParams.get('shown')) / STEP) * STEP;
  const shown = Math.min(100, Math.max(STEP, more || STEP));
  const page =
    view.group.memberCount === undefined
      ? null
      : await xrpc<typeof listMembers.main>(event, 'org.atgrp.internal.listMembers', {
          group,
          limit: shown,
          ...(q ? { q } : {})
        });
  const invites = viewer?.actions?.includes('invite')
    ? (await xrpc<typeof listInvites.main>(event, 'org.atgrp.internal.listInvites', { group }))
        .invites
    : null;
  // The AI apps a member connected here, and where they connect one.
  const apps = viewer?.member
    ? (
        await xrpc<typeof listConnectedApps.main>(event, 'org.atgrp.internal.listConnectedApps', {
          group
        })
      ).apps
    : null;
  const invited =
    viewer && !viewer.member && !view.group.deactivated
      ? (
          await xrpc<typeof getActorInvites.main>(event, 'org.atgrp.internal.getActorInvites', {
            group
          })
        ).invites.length > 0
      : false;
  const { configures, issues } = changes(view);
  return {
    ...view,
    settings: configures || issues,
    members: page?.members ?? null,
    more: !!page?.cursor,
    q,
    shown,
    invites,
    apps,
    invited,
    mcp: `${event.url.origin}/mcp`
  };
};

/** The group a form on its page is about, and the DID a form names. */
async function asked(event: {
  fetch: typeof fetch;
  params: { handle?: string };
  request: Request;
}) {
  const form = await event.request.formData();
  return { group: await groupOf(event), who: String(form.get('did') ?? ''), form };
}

const MEMBERSHIP = 'org.atgrp.membership';

/**
 * Writes `who`'s membership of `group`, holding `roles`, as the group:
 * admitting one who asked, or changing a member's roles.
 */
async function membership(
  event: { fetch: typeof fetch },
  group: string,
  who: string,
  roles: string[],
  action: 'create' | 'update'
) {
  const record = { $type: MEMBERSHIP, roles, createdAt: new Date().toISOString() };
  const nsid =
    action === 'create' ? 'com.atproto.space.createRecord' : 'com.atproto.space.putRecord';
  return asGroup(event, group, membersOf(group), nsid, {
    collection: MEMBERSHIP,
    rkey: who,
    record
  });
}

/** What a person does on a group's page: each drawn again after. */
export const actions: Actions = {
  ...switchedOffActions,
  join: async (event) => {
    const { group, form } = await asked(event);
    // Their note to whoever looks at the request, if they wrote one.
    const message = String(form.get('message') ?? '').trim();
    const failed = await act(event, 'org.atgrp.requestJoin', {
      group,
      ...(message ? { message } : {})
    });
    return failed ?? { joined: true };
  },
  decline: async (event) => {
    const { group } = await asked(event);
    return act(event, 'org.atgrp.internal.declineInvite', { group });
  },
  cancel: async (event) => {
    const { group } = await asked(event);
    return act(event, 'org.atgrp.cancelJoinRequest', { group });
  },
  leave: async (event) => {
    const { group } = await asked(event);
    return act(event, 'org.atgrp.leaveGroup', { group });
  },
  admit: async (event) => {
    const { group, who } = await asked(event);
    // With the roles every new member gets, and member, which everyone holds.
    const { roles } = await xrpc<typeof getGroup.main>(event, 'org.atgrp.internal.getGroup', {
      group: group as `did:${string}:${string}`
    });
    const given = (roles ?? []).filter((r) => r.default).map((r) => r.key);
    return membership(event, group, who, [...new Set(['member', ...given])], 'create');
  },
  deny: async (event) => {
    const { group, who } = await asked(event);
    return act(event, 'org.atgrp.denyJoinRequest', { group, member: who });
  },
  roles: async (event) => {
    const { group, who, form } = await asked(event);
    return membership(event, group, who, form.getAll('role').map(String), 'update');
  },
  eject: async (event) => {
    const { group, who } = await asked(event);
    return asGroup(event, group, membersOf(group), 'com.atproto.space.deleteRecord', {
      collection: MEMBERSHIP,
      rkey: who
    });
  },
  invite: async (event) => {
    const { group, form } = await asked(event);
    const handle = String(form.get('handle') ?? '')
      .trim()
      .replace(/^@/, '')
      .toLowerCase() as Handle;
    const found = await event.fetch(
      `/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`
    );
    if (!found.ok) return fail(400, { failed: m.route_group_invite_not_found({ handle }) });
    const { did } = await found.json();
    // Written as the group, in their own inbox, with the note if there is one.
    const message = String(form.get('message') ?? '').trim();
    const record = {
      $type: 'org.atgrp.invite',
      ...(message ? { message } : {}),
      createdAt: new Date().toISOString()
    };
    return asGroup(event, group, inboxOf(did), 'com.atproto.space.createRecord', {
      collection: 'org.atgrp.invite',
      record
    });
  },
  disconnect: async (event) => {
    const { group, form } = await asked(event);
    return act(event, 'org.atgrp.internal.revokeConnectedApp', {
      group,
      clientId: String(form.get('clientId'))
    });
  },
  uninvite: async (event) => {
    const { group, form } = await asked(event);
    // Cancelled by deleting it, as the group, from their inbox.
    const uri = String(form.get('uri') ?? '');
    const [inbox, rkey] = [uri.split(`/${group}/`)[0], uri.split('/').pop()];
    return asGroup(event, group, inbox, 'com.atproto.space.deleteRecord', {
      collection: 'org.atgrp.invite',
      rkey
    });
  }
};