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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
|
<!--
SPDX-FileCopyrightText: hazelnoot and other Sharkey contributors
SPDX-License-Identifier: AGPL-3.0-only
-->
<template>
<div v-if="isRefreshing">
<MkLoading :class="$style.loading"></MkLoading>
</div>
<template v-else>
<MkUrlPreview
v-for="preview of urlPreviews"
:key="preview.url"
:url="preview.url"
:previewHint="preview"
:noteHint="preview.note"
:attributionHint="preview.attributionUser"
:detail="detail"
:compact="compact"
:showAsQuote="showAsQuote"
:showActions="showActions"
:skipNoteIds="skipNoteIds"
></MkUrlPreview>
</template>
</template>
<script setup lang="ts">
import * as Misskey from 'misskey-js';
import * as mfm from 'mfm-js';
import { computed, ref, watch } from 'vue';
import { versatileLang } from '@@/js/intl-const';
import promiseLimit from 'promise-limit';
import type { SummalyResult } from '@/components/MkUrlPreview.vue';
import { extractPreviewUrls } from '@/utility/extract-preview-urls';
import { extractUrlFromMfm } from '@/utility/extract-url-from-mfm';
import { $i } from '@/i';
import { misskeyApi } from '@/utility/misskey-api';
import MkUrlPreview from '@/components/MkUrlPreview.vue';
import { getNoteUrls } from '@/utility/getNoteUrls';
type Summary = SummalyResult & {
note?: Misskey.entities.Note | null;
attributionUser?: Misskey.entities.User | null;
};
type Limiter<T> = ReturnType<typeof promiseLimit<T>>;
const props = withDefaults(defineProps<{
sourceUrls?: string[];
sourceNodes?: mfm.MfmNode[];
sourceText?: string;
sourceNote?: Misskey.entities.Note;
detail?: boolean;
compact?: boolean;
showAsQuote?: boolean;
showActions?: boolean;
skipNoteIds?: string[];
}>(), {
sourceUrls: undefined,
sourceText: undefined,
sourceNodes: undefined,
sourceNote: undefined,
detail: undefined,
compact: undefined,
showAsQuote: undefined,
showActions: undefined,
skipNoteIds: () => [],
});
const urlPreviews = ref<Summary[]>([]);
const urls = computed<string[]>(() => {
if (props.sourceUrls) {
return props.sourceUrls;
}
// sourceNodes > sourceText > sourceNote
const source =
props.sourceNodes ??
(props.sourceText ? mfm.parse(props.sourceText) : null) ??
(props.sourceNote?.text ? mfm.parse(props.sourceNote.text) : null);
if (source) {
if (props.sourceNote) {
return extractPreviewUrls(props.sourceNote, source);
} else {
return extractUrlFromMfm(source);
}
}
return [];
});
// todo un-ref these
const isRefreshing = ref<Promise<void> | false>(false);
const cachedNotes = ref(new Map<string, Misskey.entities.Note | null>());
const cachedPreviews = ref(new Map<string, Summary | null>());
const cachedUsers = new Map<string, Misskey.entities.User | null>();
/**
* Refreshes the group.
* Calls are automatically de-duplicated.
*/
function refresh(): Promise<void> {
if (isRefreshing.value) return isRefreshing.value;
const promise = doRefresh();
promise.finally(() => isRefreshing.value = false);
isRefreshing.value = promise;
return promise;
}
/**
* Refreshes the group.
* Don't call this directly - use refresh() instead!
*/
async function doRefresh(): Promise<void> {
let previews = await fetchPreviews();
// Remove duplicates
previews = deduplicatePreviews(previews);
// Remove any with hidden notes
previews = previews.filter(preview => !preview.note || !props.skipNoteIds.includes(preview.note.id));
urlPreviews.value = previews;
}
async function fetchPreviews(): Promise<Summary[]> {
const userLimiter = promiseLimit<Misskey.entities.User | null>(4);
const noteLimiter = promiseLimit<Misskey.entities.Note | null>(2);
const summaryLimiter = promiseLimit<Summary | null>(5);
const summaries = await Promise.all(urls.value.map(url =>
summaryLimiter(async () => {
return await fetchPreview(url);
}).then(async (summary) => {
if (summary) {
await Promise.all([
attachNote(summary, noteLimiter),
attachAttribution(summary, userLimiter),
]);
}
return summary;
})));
return summaries.filter((preview): preview is Summary => preview != null);
}
async function fetchPreview(url: string): Promise<Summary | null> {
const cached = cachedPreviews.value.get(url);
if (cached) {
return cached;
}
const headers = $i ? { Authorization: `Bearer ${$i.token}` } : undefined;
const params = new URLSearchParams({ url, lang: versatileLang });
const res = await window.fetch(`/url?${params.toString()}`, { headers }).catch(() => null);
if (res?.ok) {
// Success - got the summary
const summary: Summary = await res.json();
cachedPreviews.value.set(url, summary);
if (summary.url !== url) {
cachedPreviews.value.set(summary.url, summary);
}
return summary;
}
// Failed, blocked, or not found
cachedPreviews.value.set(url, null);
return null;
}
async function attachNote(summary: Summary, noteLimiter: Limiter<Misskey.entities.Note | null>): Promise<void> {
if (props.showAsQuote && summary.activityPub && summary.haveNoteLocally) {
// Have to pull this out to make TS happy
const noteUri = summary.activityPub;
summary.note = await noteLimiter(async () => {
return await fetchNote(noteUri);
});
}
}
async function fetchNote(noteUri: string): Promise<Misskey.entities.Note | null> {
const cached = cachedNotes.value.get(noteUri);
if (cached) {
return cached;
}
const response = await misskeyApi('ap/show', { uri: noteUri }).catch(() => null);
if (response && response.type === 'Note') {
const note = response['object'];
// Success - got the note
cachedNotes.value.set(noteUri, note);
if (note.uri && note.uri !== noteUri) {
cachedNotes.value.set(note.uri, note);
}
return note;
}
// Failed, blocked, or not found
cachedNotes.value.set(noteUri, null);
return null;
}
async function attachAttribution(summary: Summary, userLimiter: Limiter<Misskey.entities.User | null>): Promise<void> {
if (summary.linkAttribution) {
// Have to pull this out to make TS happy
const userId = summary.linkAttribution.userId;
summary.attributionUser = await userLimiter(async () => {
return await fetchUser(userId);
});
}
}
async function fetchUser(userId: string): Promise<Misskey.entities.User | null> {
const cached = cachedUsers.get(userId);
if (cached) {
return cached;
}
const user = await misskeyApi('users/show', { userId }).catch(() => null);
cachedUsers.set(userId, user);
return user;
}
function deduplicatePreviews(previews: Summary[]): Summary[] {
// eslint-disable-next-line no-param-reassign
previews = previews
// Remove any previews with duplicate URL
.filter((preview, index) => !previews.some((p, i) => {
// Skip the current preview (don't count self as duplicate).
if (p === preview) return false;
// Skip differing URLs (not duplicate).
if (p.url !== preview.url) return false;
// Skip if we have AP and the other doesn't
if (preview.activityPub && !p.activityPub) return false;
// Skip if we have a note and the other doesn't
if (preview.note && !p.note) return false;
// Skip later previews (keep the earliest instance)...
// ...but only if we have AP or the later one doesn't...
// ...and only if we have note or the later one doesn't.
if (i > index && (preview.activityPub || !p.activityPub) && (preview.note || !p.note)) return false;
// If we get here, then "preview" is a duplicate of "p" and should be skipped.
return true;
}));
// eslint-disable-next-line no-param-reassign
previews = previews
// Remove any previews with duplicate AP
.filter((preview, index) => !previews.some((p, i) => {
// Skip the current preview (don't count self as duplicate).
if (p === preview) return false;
// Skip if we don't have AP
if (!preview.activityPub) return false;
// Skip if other does not have AP
if (!p.activityPub) return false;
// Skip differing URLs (not duplicate).
if (p.activityPub !== preview.activityPub) return false;
// Skip later previews (keep the earliest instance)
if (i > index) return false;
// If we get here, then "preview" is a duplicate of "p" and should be skipped.
return true;
}));
// eslint-disable-next-line no-param-reassign
previews = previews
// Remove any previews with duplicate note
.filter((preview, index) => !previews.some((p, i) => {
// Skip the current preview (don't count self as duplicate).
if (p === preview) return false;
// Skip if we don't have a note
if (!preview.note) return false;
// Skip if other does not have a note
if (!p.note) return false;
// Skip differing notes (not duplicate).
if (p.note.id !== preview.note.id) return false;
// Skip later previews (keep the earliest instance)
if (i > index) return false;
// If we get here, then "preview" is a duplicate of "p" and should be skipped.
return true;
}));
// eslint-disable-next-line no-param-reassign
previews = previews
// Remove any previews where the note duplicates url
.filter((preview, index) => !previews.some((p, i) => {
// Skip the current preview (don't count self as duplicate).
if (p === preview) return false;
// Skip if we have a note
if (preview.note) return false;
// Skip if other does not have a note
if (!p.note) return false;
// Skip later previews (keep the earliest instance)
if (i > index) return false;
const noteUrls = getNoteUrls(p.note);
// Remove if other duplicates our AP URL
if (preview.activityPub && noteUrls.includes(preview.activityPub)) return true;
// Remove if other duplicates our main URL
return noteUrls.includes(preview.url);
}));
return previews;
}
// Kick everything off, and watch for changes.
watch(
[urls, () => props.showAsQuote, () => props.skipNoteIds],
() => refresh(),
{ immediate: true },
);
</script>
<style module lang="scss">
.loading {
box-shadow: 0 0 0 1px var(--MI_THEME-divider);
border-radius: var(--MI-radius-sm);
}
</style>
|