~james/core

core/web/src/lib/api/graph.ts -rw-r--r-- 9.5 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import type { Did, ResourceUri } from "@atcute/lexicons/syntax";
import type { OAuthUserAgent } from "@atcute/oauth-browser-client";
import { ClientResponseError, type BobbinContext } from "#lib/api/client.ts";
import { jsonGet } from "#lib/api/_request.ts";
import { httpStatusFor } from "#lib/api/load.ts";
import { nsidOf, recordKeyOf } from "#lib/api/syntax.ts";
import { rkeyFromUri } from "#lib/api/uri.ts";
import { createRecord, deleteRecord, putRecord, type WrittenRecord } from "#lib/api/write.ts";
import type { VouchRecord } from "#lib/api/records.ts";
import type * as OrgTangledFeedGetStar from "#lib/api/lexicons/types/org/tangled/feed/getStar.ts";
import type * as OrgTangledGraphFollow from "#lib/api/lexicons/types/org/tangled/graph/follow.ts";
import type * as OrgTangledGraphGetFollow from "#lib/api/lexicons/types/org/tangled/graph/getFollow.ts";
import type * as OrgTangledGraphListNetworkVouches from "#lib/api/lexicons/types/org/tangled/graph/listNetworkVouches.ts";

export type FollowRecord = OrgTangledGraphFollow.Main;
export type { VouchRecord };

const FOLLOW_COLLECTION = nsidOf("org.tangled.graph.follow");
const STAR_COLLECTION = nsidOf("org.tangled.feed.star");
const VOUCH_COLLECTION = nsidOf("org.tangled.graph.vouch");
const SUBSCRIPTION_COLLECTION = nsidOf("org.tangled.feed.subscription");

export const getFollowRkey = async (
	ctx: BobbinContext,
	actor: string,
	subject: string
): Promise<string | null> => {
	try {
		const { uri } = await jsonGet<OrgTangledGraphGetFollow.$output>(
			ctx,
			"org.tangled.graph.getFollow",
			{
				actor: actor as Did,
				subject: subject as Did
			} satisfies OrgTangledGraphGetFollow.$params
		);
		return rkeyFromUri(uri);
	} catch (cause) {
		if (cause instanceof ClientResponseError && httpStatusFor(cause) === 404) return null;
		throw cause;
	}
};

export const getStarRkey = async (
	ctx: BobbinContext,
	actor: string,
	subject: string
): Promise<string | null> => {
	try {
		const { uri } = await jsonGet<OrgTangledFeedGetStar.$output>(
			ctx,
			"org.tangled.feed.getStar",
			{
				actor: actor as Did,
				subject
			} satisfies OrgTangledFeedGetStar.$params
		);
		return rkeyFromUri(uri);
	} catch (cause) {
		if (cause instanceof ClientResponseError && httpStatusFor(cause) === 404) return null;
		throw cause;
	}
};

export const createFollow = async (
	agent: OAuthUserAgent,
	subject: string
): Promise<WrittenRecord & { rkey: string }> => {
	// keyed by the subject did
	const written = await putRecord(agent, FOLLOW_COLLECTION, recordKeyOf(subject), {
		$type: "org.tangled.graph.follow",
		createdAt: new Date().toISOString()
	});
	return { ...written, rkey: rkeyFromUri(written.uri) };
};

export const deleteFollow = async (
	agent: OAuthUserAgent,
	rkey: string
): Promise<{ uri: ResourceUri }> => {
	const uri = `at://${agent.sub}/${FOLLOW_COLLECTION}/${rkey}` as ResourceUri;
	await deleteRecord(agent, FOLLOW_COLLECTION, recordKeyOf(rkey));
	return { uri };
};

export type StarSubject =
	| { kind: "repo"; did: string; ownerHandle: string; name: string }
	| { kind: "string"; uri: string; cid?: string };

export const createStar = async (
	agent: OAuthUserAgent,
	subject: StarSubject
): Promise<WrittenRecord & { rkey: string }> => {
	let record;
	if (subject.kind === "repo") {
		record = { $type: "org.tangled.feed.star#repo" as const, identity: subject.did as Did };
	} else {
		if (!subject.cid) throw new Error("Cannot star a record without its cid");
		record = {
			$type: "org.tangled.feed.star#record" as const,
			record: { uri: subject.uri as ResourceUri, cid: subject.cid }
		};
	}
	const written = await createRecord(agent, STAR_COLLECTION, {
		$type: "org.tangled.feed.star",
		subject: record,
		createdAt: new Date().toISOString()
	});
	return { ...written, rkey: rkeyFromUri(written.uri) };
};

export const deleteStar = async (
	agent: OAuthUserAgent,
	rkey: string
): Promise<{ uri: ResourceUri }> => {
	const uri = `at://${agent.sub}/${STAR_COLLECTION}/${rkey}` as ResourceUri;
	await deleteRecord(agent, STAR_COLLECTION, recordKeyOf(rkey));
	return { uri };
};

export const createSubscription = async (
	agent: OAuthUserAgent,
	repoDid: string
): Promise<WrittenRecord & { rkey: string }> => {
	const written = await createRecord(agent, SUBSCRIPTION_COLLECTION, {
		$type: SUBSCRIPTION_COLLECTION,
		subject: {
			$type: "org.tangled.feed.subscription#repo",
			did: repoDid as Did
		},
		createdAt: new Date().toISOString()
	});
	return { ...written, rkey: rkeyFromUri(written.uri) };
};

export const deleteSubscription = async (
	agent: OAuthUserAgent,
	rkey: string
): Promise<{ uri: ResourceUri }> => {
	const uri = `at://${agent.sub}/${SUBSCRIPTION_COLLECTION}/${rkey}` as ResourceUri;
	await deleteRecord(agent, SUBSCRIPTION_COLLECTION, recordKeyOf(rkey));
	return { uri };
};

// bobbin sends a mute back as a record too, same rkey with ignore set
export interface EntitySubscription {
	rkey: string;
	ignore: boolean;
}

// no record means deliberi still notifies, so a mute is ignore: true, not a delete
const writeEntitySubscription = async (
	agent: OAuthUserAgent,
	entityUri: string,
	ignore: boolean,
	existingRkey?: string
): Promise<string> => {
	const record = {
		$type: SUBSCRIPTION_COLLECTION,
		subject: {
			$type: "org.tangled.feed.subscription#record" as const,
			uri: entityUri
		},
		...(ignore ? { ignore } : {}),
		createdAt: new Date().toISOString()
	};
	if (existingRkey) {
		await putRecord(agent, SUBSCRIPTION_COLLECTION, recordKeyOf(existingRkey), record);
		return existingRkey;
	}
	const { uri } = await createRecord(agent, SUBSCRIPTION_COLLECTION, record);
	return rkeyFromUri(uri);
};

export const createEntitySubscription = (agent: OAuthUserAgent, entityUri: string) =>
	writeEntitySubscription(agent, entityUri, false);

export const getEntitySubscription = async (
	ctx: BobbinContext,
	actor: string,
	subject: string
): Promise<EntitySubscription | null> => {
	try {
		const { uri, ignore } = await jsonGet<{ uri: string; ignore?: boolean }>(
			ctx,
			"org.tangled.feed.subscription.getForActor",
			{ actor: actor as Did, subject }
		);
		return { rkey: rkeyFromUri(uri), ignore: ignore === true };
	} catch (cause) {
		if (cause instanceof ClientResponseError && httpStatusFor(cause) === 404) return null;
		throw cause;
	}
};

export const getSubscriptionRkey = async (
	ctx: BobbinContext,
	actor: string,
	subject: string
): Promise<string | null> => (await getEntitySubscription(ctx, actor, subject))?.rkey ?? null;

// a stale button would stack a second record, so reread the rkey first
export const setEntitySubscribed = async (
	agent: OAuthUserAgent,
	ctx: BobbinContext,
	actor: string,
	entityUri: string,
	subscribed: boolean
): Promise<string> => {
	const existing = await getEntitySubscription(ctx, actor, entityUri);
	return writeEntitySubscription(agent, entityUri, !subscribed, existing?.rkey);
};

export const ENTITY_SUBSCRIBED = "entity-subscribed";

// the page's subscribe button can't see a comment subscribing, so it gets this event
const announceSubscribed = (entityUri: string, rkey: string) => {
	if (typeof window === "undefined") return;
	window.dispatchEvent(new CustomEvent(ENTITY_SUBSCRIBED, { detail: { entityUri, rkey } }));
};

export const ensureEntitySubscription = async (
	agent: OAuthUserAgent,
	ctx: BobbinContext,
	actor: string,
	entityUri: string
): Promise<string> => {
	const existing = await getEntitySubscription(ctx, actor, entityUri);
	if (existing && !existing.ignore) return existing.rkey;
	const rkey = await writeEntitySubscription(agent, entityUri, false, existing?.rkey);
	announceSubscribed(entityUri, rkey);
	return rkey;
};

export type VouchKind = "vouch" | "denounce";

export interface VouchInput {
	kind: VouchKind;
	reason?: string;
	evidences?: string[];
}

export const putVouch = async (
	agent: OAuthUserAgent,
	subject: string,
	input: VouchInput
): Promise<WrittenRecord> => {
	return putRecord(agent, VOUCH_COLLECTION, recordKeyOf(subject), {
		$type: "org.tangled.graph.vouch",
		kind: input.kind,
		...(input.reason ? { reason: input.reason } : {}),
		...(input.evidences?.length ? { evidences: input.evidences } : {}),
		createdAt: new Date().toISOString()
	});
};

export const deleteVouch = async (
	agent: OAuthUserAgent,
	subject: string
): Promise<{ uri: ResourceUri }> => {
	const uri = `at://${agent.sub}/${VOUCH_COLLECTION}/${subject}` as ResourceUri;
	await deleteRecord(agent, VOUCH_COLLECTION, recordKeyOf(subject));
	return { uri };
};
export type NetworkVouchItem = Omit<OrgTangledGraphListNetworkVouches.ListItem, "value"> & {
	value: VouchRecord;
};

export interface NetworkVouchesByActor {
	items: Record<string, NetworkVouchItem[]>;
	cursor?: string;
}

export const listNetworkVouches = async (
	ctx: BobbinContext,
	actors: readonly string[],
	options: { limit?: number; cursor?: string } = {}
): Promise<NetworkVouchesByActor> => {
	const unique = [...new Set(actors)];
	if (options.cursor && unique.length !== 1) {
		throw new Error("A vouch cursor requires exactly one actor");
	}
	const groups = Object.fromEntries(unique.map((actor) => [actor, [] as NetworkVouchItem[]]));
	const pages = await Promise.all(
		Array.from({ length: Math.ceil(unique.length / 50) }, (_, index) =>
			jsonGet<OrgTangledGraphListNetworkVouches.$output>(
				ctx,
				"org.tangled.graph.listNetworkVouches",
				{
					actors: unique.slice(index * 50, (index + 1) * 50) as Did[],
					limit: options.limit,
					cursor: options.cursor
				} satisfies OrgTangledGraphListNetworkVouches.$params
			)
		)
	);
	for (const page of pages) {
		for (const item of page.items) groups[item.actor]?.push(item as NetworkVouchItem);
	}
	return { items: groups, cursor: pages[0]?.cursor };
};