import { set } from "https://esm.town/v/std/set?v=11";
import { spacexLemmyDb } from "https://esm.town/v/pdebie/spacexLemmyDb";
import { fetchRss } from "https://esm.town/v/pdebie/fetchRss";
export async function syncCommentToLemmy(
instance: string,
redditUrl: string,
postId: number,
auth: string,
matcher?: (author: string, content: string) => boolean,
) {
function hashCode(str) {
let hash = 0;
for (let i = 0, len = str.length; i < len; i++) {
let chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0;
}
return hash;
}
const { LemmyHttp } = await import("npm:lemmy-js-client@0.18.1");
let client = new LemmyHttp(`https://${instance}`, {
fetchFunction: fetch,
});
let comments = (await fetchRss(redditUrl)).filter((i) =>
new Date(i.isoDate) >= new Date(Date.now() - 1000 * 60 * 60 * 24)
)
.filter((i) => matcher ? matcher(i.author, i.contentSnippet) : true);
const ret = [];
for (const comment of comments) {
const linkParts = comment.link.split("/");
const commentId = linkParts[linkParts.length - 2];
console.log("Found comment with id " + commentId);
const contentHash = hashCode(comment.contentSnippet);
const syncedContent =
`New comment from ${comment.author} [on Reddit](${comment.link}):\n\n ` +
comment.contentSnippet.replace(/\n/g, "\n\n") + `\n\n(This gets synced)`;
const existingStatus =
spacexLemmyDb.commentMap[commentId];
if (!existingStatus) {
spacexLemmyDb.commentMap[commentId] = {
lemmyId: undefined,
};
const ret = await client.createComment({
post_id: postId,
content: syncedContent,
auth,
});
spacexLemmyDb.commentMap[commentId] = {
lemmyId: ret.comment_view.comment.id,
contentHash,
};
}
else {
if (!existingStatus.lemmyId) {
console.log(
`Skipping comment ${commentId} because the previous run failed`,
);
continue;
}
if (existingStatus.contentHash !== contentHash) {
await client.editComment({
comment_id: existingStatus.lemmyId,
content: syncedContent,
auth,
});
existingStatus.contentHash = contentHash;
}
}
ret.push(commentId);
}
await set("spacexLemmyDb", spacexLemmyDb);
return comments;
}