refactor: context item retrieval logic

This commit is contained in:
Julian Lam
2024-06-28 16:28:48 -04:00
parent cc0bbcb7bf
commit 20aee8e9ae
2 changed files with 51 additions and 22 deletions

View File

@@ -35,31 +35,14 @@ Contexts.getItems = async (uid, id, root = true) => {
return [];
}
if (type.startsWith('Ordered')) {
if (type.startsWith('Ordered') && orderedItems) {
items = orderedItems;
}
if (items) {
items = (await Promise.all(items.map(async (item) => {
const { type, id } = await activitypub.helpers.resolveLocalId(item);
const pid = type === 'post' && id ? id : item;
const postData = await posts.getPostData(pid);
if (postData) {
// Already cached
return postData;
}
// No local copy, fetch from source
try {
const object = await activitypub.get('uid', uid, pid);
winston.verbose(`[activitypub/context] Retrieved ${pid}`);
return await activitypub.mocks.post(object);
} catch (e) {
// Unresolvable, either temporariliy or permanent, ignore for now.
winston.verbose(`[activitypub/context] Cannot retrieve ${id}`);
return null;
}
}))).filter(Boolean);
items = await Promise.all(items
.map(async item => (activitypub.helpers.isUri(item) ? parseString(uid, item) : parseItem(uid, item))));
items = items.filter(Boolean);
winston.verbose(`[activitypub/context] Found ${items.length} items.`);
}
@@ -79,3 +62,49 @@ Contexts.getItems = async (uid, id, root = true) => {
return chain;
};
async function parseString(uid, item) {
const { type, id } = await activitypub.helpers.resolveLocalId(item);
const pid = type === 'post' && id ? id : item;
const postData = await posts.getPostData(pid);
if (postData) {
// Already cached
return postData;
}
// No local copy, fetch from source
try {
const object = await activitypub.get('uid', uid, pid);
winston.verbose(`[activitypub/context] Retrieved ${pid}`);
return parseItem(uid, object);
} catch (e) {
// Unresolvable, either temporarily or permanent, ignore for now.
winston.verbose(`[activitypub/context] Cannot retrieve ${id}`);
return null;
}
}
async function parseItem(uid, item) {
const { type, id } = await activitypub.helpers.resolveLocalId(item.id);
const pid = type === 'post' && id ? id : item.id;
const postData = await posts.getPostData(pid);
if (postData) {
// Already cached
return postData;
}
// Handle activity wrapper
if (item.type === 'Create') {
item = item.object;
if (activitypub.helpers.isUri(item)) {
return parseString(uid, item);
}
} else if (!activitypub._constants.acceptedPostTypes.includes(item.type)) {
// Not a note, silently skip.
return null;
}
winston.verbose(`[activitypub/context] Parsing ${pid}`);
return await activitypub.mocks.post(item);
}

View File

@@ -125,7 +125,7 @@ Mocks.post = async (objects) => {
// tid, --> purposely omitted
name,
content,
sourceContent: source.mediaType === 'text/markdown' ? source.content : undefined,
sourceContent: source && source.mediaType === 'text/markdown' ? source.content : undefined,
timestamp,
toPid,