1import { env } from '$env/dynamic/private';
2import { Bot, type Post } from '@skyware/bot';
3import { get, writable } from 'svelte/store';
4
5const bskyClient = writable<null | Bot>(null);
6
7export const getBskyClient = async () => {
8 let client = get(bskyClient);
9 if (client === null) {
10 client = await loginToBsky();
11 bskyClient.set(client);
12 }
13 return client;
14};
15
16const loginToBsky = async () => {
17 const password = env.BSKY_PASSWORD ?? null;
18 if (password === null) {
19 throw new Error('no password provided');
20 }
21 const bot = new Bot({ service: 'https://gaze.systems' });
22 await bot.login({ identifier: 'guestbook.gaze.systems', password });
23 return bot;
24};
25
26export const getUserPosts = async (
27 did: string,
28 count: number = 10,
29 cursor: string | null = null
30) => {
31 const client = await getBskyClient();
32 let feedCursor: string | null | undefined = cursor;
33 const posts: Post[] = [];
34 // fetch requested amount of posts
35 while (posts.length < count - 1 && (typeof feedCursor === 'string' || feedCursor === null)) {
36 const feedData = await client.getUserPosts(did, {
37 limit: count,
38 filter: 'posts_no_replies',
39 cursor: feedCursor === null ? undefined : feedCursor
40 });
41 posts.push(...feedData.posts.filter((post) => post.author.did === did));
42 feedCursor = feedData.cursor;
43 }
44 return { posts, cursor: feedCursor === null ? undefined : feedCursor };
45};
46
47const lastPosts = writable<Post[]>([]);
48
49export const updateLastPosts = async () => {
50 try {
51 const { posts } = await getUserPosts('did:plc:dfl62fgb7wtjj3fcbb72naae', 10);
52 lastPosts.set(posts);
53 } catch (err) {
54 console.log(`can't update last posts ${err}`);
55 }
56};
57
58export const getLastPosts = () => {
59 return get(lastPosts);
60};