activitypress/src/collection.ts

81 lines
2.3 KiB
TypeScript

import { CONTEXT } from "./activity.js";
import { Actor } from "./activitypub_types.js";
import db from "./db.js";
import { z } from "zod";
export const zCollection = z.object({
id: z.number().min(0),
collection_types_id: z.number().min(0),
articles_id: z.optional(z.number().min(0)),
users_id: z.optional(z.number().min(0)),
value: z.string().min(1)
});
export type CollectionEntry = z.infer<typeof zCollection>;
export const orderedCollection = (id: string, orderedItems: (string | Record<string, any>)[], paged = false) => {
const collection: Record<string, any> = {
type: "OrderedCollection",
"@context": CONTEXT,
id,
totalItems: orderedItems.length
};
if (paged) {
collection.first = {
id: `${id}?page=1`,
next: `${id}?page=2`,
orderedItems,
partOf: id,
totalItems: orderedItems.length,
type: "OrderedCollectionPage"
};
}
else {
collection.orderedItems = orderedItems;
}
return collection;
};
export const orderedCollectionPage = (collectionId: string, orderedItems: (string | Record<string, any>)[], page: number, pageLength: number, totalItems: number) => {
const collection: Record<string, any> = {
id: `${collectionId}?page=${page}`,
type: "OrderedCollectionPage",
"@context": CONTEXT,
partOf: collectionId,
totalItems,
orderedItems
};
const hasNext = totalItems > (((page - 1) * pageLength) + orderedItems.length);
if (hasNext) collection.next = `${collectionId}?page=${page + 1}`;
return collection;
};
export const addLikeOrShare = async (articleId: number, person: Actor, likeOrShare: 1|2) => {
await db("remote_users")
.insert({
actor: person.id,
nickname: person.preferredUsername,
name: person.name,
inbox: person.inbox,
shared_inbox: person.endpoints?.sharedInbox
})
.onConflict().ignore();
;
await db("collections")
.insert({
collection_types_id: likeOrShare,
articles_id: articleId,
value: person.id,
created_at: new Date()
})
.onConflict().ignore()
;
console.log("Follower added");
};