bisky 0.3.0

Bluesky API library
Documentation
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::atproto::{Client, RecordStream, StreamError};
use crate::errors::BiskyError;
use crate::lexicon::app::bsky::actor::{ProfileView, ProfileViewDetailed};
use crate::lexicon::app::bsky::feed::{
    GetLikesLike, GetLikesOutput, GetPostThreadOutput, Post, ThreadViewPostEnum,
};
use crate::lexicon::app::bsky::graph::{GetFollowersOutput, GetFollowsOutput};
use crate::lexicon::app::bsky::notification::{
    ListNotificationsOutput, Notification, NotificationCount, NotificationRecord, UpdateSeen,
};
use crate::lexicon::com::atproto::repo::{BlobOutput, CreateRecordOutput, Record};
use chrono::{DateTime, Utc};
use serde::de::DeserializeOwned;
use std::collections::VecDeque;
use std::time::Duration;

pub struct Bluesky {
    client: Client,
}

impl Bluesky {
    pub fn new(client: Client) -> Self {
        Self { client }
    }

    pub fn user(&mut self, username: &str) -> Result<BlueskyUser, BiskyError> {
        let Some(_session) = &self.client.session else{
            return Err(BiskyError::MissingSession);
        };
        Ok(BlueskyUser {
            client: self,
            username: username.to_string(),
        })
    }

    pub fn me(&mut self) -> Result<BlueskyMe, BiskyError> {
        let Some(session) = &self.client.session else{
            return Err(BiskyError::MissingSession);
        };
        Ok(BlueskyMe {
            username: session.did.to_string(),
            client: self,
        })
    }

    /// Get the user's notification count. Can take a date to mark them as seen
    pub async fn bsky_get_notification_count(
        &mut self,
        seen_at: Option<&str>,
    ) -> Result<NotificationCount, BiskyError> {
        let mut query = Vec::new();

        if let Some(seen_at) = seen_at {
            query.push(("seen_at", seen_at));
        }
        let res = self
            .client
            .xrpc_get::<NotificationCount>("app.bsky.notification.getUnreadCount", Some(&query))
            .await?;
        Ok(res)
    }

    pub async fn bsky_list_notifications<D: DeserializeOwned + std::fmt::Debug>(
        &mut self,
        mut limit: usize,
        seen_at: Option<&str>,
        cursor: Option<&str>,
    ) -> Result<(Vec<Notification<D>>, Option<String>), BiskyError> {
        let mut notifications = Vec::new();
        let mut response_cursor = None;

        while limit > 0 {
            let query_limit = std::cmp::min(limit, 100).to_string();
            let mut query = Vec::from([("limit", query_limit.as_ref())]);

            if let Some(cursor) = cursor {
                query.push(("cursor", cursor));
            }
            if let Some(seen_at) = seen_at {
                query.push(("seenAt", seen_at));
            }

            let mut response = self
                .client
                .xrpc_get::<ListNotificationsOutput<D>>(
                    "app.bsky.notification.listNotifications",
                    Some(&query),
                )
                .await?;

            if response.notifications.is_empty() {
                // caller requested more records than are available
                break;
            }

            limit -= response.notifications.len();

            response_cursor = response.cursor.take();
            notifications.append(&mut response.notifications);
        }

        Ok((notifications, response_cursor))
    }

    pub async fn bsky_update_seen(&mut self, seen_at: DateTime<Utc>) -> Result<(), BiskyError> {
        self.client
            .xrpc_post_no_response("app.bsky.notification.updateSeen", &UpdateSeen { seen_at })
            .await
    }

    pub async fn bsky_stream_notifications<'a, D: DeserializeOwned + std::fmt::Debug>(
        &'a mut self,
        seen_at: Option<&'a str>,
    ) -> Result<NotificationStream<'a, D>, StreamError> {
        let (_, cursor) = self
            .bsky_list_notifications::<D>(usize::MAX, seen_at, None)
            .await?;

        if let Some(cursor) = cursor {
            Ok(NotificationStream {
                client: self,
                queue: VecDeque::new(),
                cursor,
                limit: usize::MAX,
                seen_at,
            })
        } else {
            Err(StreamError::NoCursor)
        }
    }
    ///app.bsky.feed.getLikes
    pub async fn bsky_get_likes(
        &mut self,
        uri: &str,
        mut limit: usize,
        cursor: Option<&str>,
    ) -> Result<(Vec<GetLikesLike>, Option<String>), BiskyError> {
        let mut likes = Vec::new();
        let mut response_cursor = None;

        while limit > 0 {
            let query_limit = std::cmp::min(limit, 100).to_string();
            let mut query = Vec::from([("uri", uri), ("limit", query_limit.as_str())]);

            if let Some(cursor) = cursor {
                query.push(("cursor", cursor));
            }

            let mut response = self
                .client
                .xrpc_get::<GetLikesOutput>("app.bsky.feed.getLikes", Some(&query))
                .await?;

            if response.likes.is_empty() {
                // caller requested more records than are available
                break;
            }

            limit -= response.likes.len();

            response_cursor = response.cursor.take();
            likes.append(&mut response.likes);
        }

        Ok((likes, response_cursor))
    }

    ///app.bsky.graph.getFollows
    pub async fn bsky_get_follows(
        &mut self,
        actor: &str,
        mut limit: usize,
        cursor: Option<&str>,
    ) -> Result<(Vec<ProfileView>, Option<String>), BiskyError> {
        let mut follows = Vec::new();
        let mut response_cursor = None;

        while limit > 0 {
            let query_limit = std::cmp::min(limit, 100).to_string();
            let mut query = Vec::from([("actor", actor), ("limit", &query_limit)]);

            if let Some(cursor) = cursor {
                query.push(("cursor", cursor));
            }

            let mut response = self
                .client
                .xrpc_get::<GetFollowsOutput>("app.bsky.graph.getFollows", Some(&query))
                .await?;

            if response.follows.is_empty() {
                // caller requested more records than are available
                break;
            }

            limit -= response.follows.len();

            response_cursor = response.cursor.take();
            follows.append(&mut response.follows);
        }

        Ok((follows, response_cursor))
    }

    ///app.bsky.graph.getFollowers
    pub async fn bsky_get_followers(
        &mut self,
        actor: &str,
        mut limit: usize,
        cursor: Option<&str>,
    ) -> Result<(Vec<ProfileView>, Option<String>), BiskyError> {
        let mut followers = Vec::new();
        let mut response_cursor = None;

        while limit > 0 {
            let query_limit = std::cmp::min(limit, 100).to_string();
            let mut query = Vec::from([("actor", actor), ("limit", &query_limit)]);

            if let Some(cursor) = cursor.as_ref() {
                query.push(("cursor", cursor));
            }

            let mut response = self
                .client
                .xrpc_get::<GetFollowersOutput>("app.bsky.graph.getFollowers", Some(&query))
                .await?;

            if response.followers.is_empty() {
                // caller requested more records than are available
                break;
            }

            limit -= response.followers.len();

            response_cursor = response.cursor.take();
            followers.append(&mut response.followers);
        }

        Ok((followers, response_cursor))
    }

    ///app.bsky.feed.getPostThread
    pub async fn bsky_get_post_thread(
        &mut self,
        uri: &str,
    ) -> Result<ThreadViewPostEnum, BiskyError> {
        let query = Vec::from([("uri", uri)]);

        let response = self
            .client
            .xrpc_get::<GetPostThreadOutput>("app.bsky.feed.getPostThread", Some(&query))
            .await?;

        Ok(response.thread)
    }
}

pub struct BlueskyMe<'a> {
    client: &'a mut Bluesky,
    username: String,
}

impl<'a> BlueskyMe<'a> {
    /// Post a new Post to your skyline
    pub async fn post(&mut self, post: Post) -> Result<CreateRecordOutput, BiskyError> {
        self.client
            .client
            .repo_create_record(&self.username, "app.bsky.feed.post", &post)
            .await
    }
    /// Get the notifications for the user
    ///app.bsky.notification.listNotifications#
    pub async fn get_notification_count(
        &mut self,
        seen_at: Option<&str>,
    ) -> Result<NotificationCount, BiskyError> {
        self.client.bsky_get_notification_count(seen_at).await
    }
    /// Get the notifications for the user
    ///app.bsky.notification.listNotifications#
    pub async fn list_notifications(
        &mut self,
        limit: usize,
    ) -> Result<Vec<Notification<NotificationRecord>>, BiskyError> {
        self.client
            .bsky_list_notifications(limit, None, None)
            .await
            .map(|l| l.0)
    }

    pub async fn stream_notifications(
        &mut self,
    ) -> Result<NotificationStream<Notification<NotificationRecord>>, StreamError> {
        self.client.bsky_stream_notifications(None).await
    }
    /// Tell Bsky when the notifications were seen, marking them as old
    pub async fn update_seen(&mut self) -> Result<(), BiskyError> {
        self.client.bsky_update_seen(Utc::now()).await
    }

    /// Upload a Blob(Image) for use in a Bsky Post later
    pub async fn upload_blob(
        &mut self,
        blob: &[u8],
        mime_type: &str,
    ) -> Result<BlobOutput, BiskyError> {
        self.client.client.repo_upload_blob(blob, mime_type).await
    }

    pub async fn get_post_thread(&mut self, uri: &str) -> Result<ThreadViewPostEnum, BiskyError> {
        self.client.bsky_get_post_thread(uri).await
    }
}
pub struct BlueskyUser<'a> {
    client: &'a mut Bluesky,
    username: String,
}

impl BlueskyUser<'_> {
    pub async fn get_profile(&mut self) -> Result<ProfileViewDetailed, BiskyError> {
        self.client
            .client
            .xrpc_get(
                "app.bsky.actor.getProfile",
                Some(&[("actor", &self.username)]),
            )
            .await
    }
    pub async fn get_likes(
        &mut self,
        uri: &str,
        limit: usize,
        cursor: Option<&str>,
    ) -> Result<Vec<GetLikesLike>, BiskyError> {
        self.client
            .bsky_get_likes(uri, limit, cursor)
            .await
            .map(|l| l.0)
    }
    pub async fn get_follows(
        &mut self,
        limit: usize,
        cursor: Option<&str>,
    ) -> Result<Vec<ProfileView>, BiskyError> {
        self.client
            .bsky_get_follows(&self.username, limit, cursor)
            .await
            .map(|l| l.0)
    }
    pub async fn get_followers(
        &mut self,
        limit: usize,
        cursor: Option<&str>,
    ) -> Result<Vec<ProfileView>, BiskyError> {
        self.client
            .bsky_get_followers(&self.username, limit, cursor)
            .await
            .map(|l| l.0)
    }

    pub async fn list_posts(&mut self) -> Result<Vec<Record<Post>>, BiskyError> {
        self.client
            .client
            .repo_list_records(
                &self.username,
                "app.bsky.feed.post",
                usize::MAX,
                false,
                None,
            )
            .await
            .map(|l| l.0)
    }

    pub async fn stream_posts(&mut self) -> Result<RecordStream<Post>, StreamError> {
        self.client
            .client
            .repo_stream_records(&self.username, "app.bsky.feed.post")
            .await
    }
}

pub struct NotificationStream<'a, D: DeserializeOwned> {
    client: &'a mut Bluesky,
    limit: usize,
    seen_at: Option<&'a str>,
    queue: VecDeque<Notification<D>>,
    cursor: String,
}

impl<'a, D: DeserializeOwned + std::fmt::Debug> NotificationStream<'a, D> {
    pub async fn next(&mut self) -> Result<Notification<D>, StreamError> {
        if let Some(notification) = self.queue.pop_front() {
            Ok(notification)
        } else {
            loop {
                let (notifications, cursor) = self
                    .client
                    .bsky_list_notifications(self.limit, self.seen_at, Some(self.cursor.as_ref()))
                    .await?;

                let mut notifications = VecDeque::from(notifications);
                if let Some(first_notification) = notifications.pop_front() {
                    if let Some(cursor) = cursor {
                        self.cursor = cursor;
                    } else {
                        return Err(StreamError::NoCursor);
                    }

                    self.queue.append(&mut notifications);
                    return Ok(first_notification);
                } else {
                    tokio::time::sleep(Duration::from_secs(15)).await;
                }
            }
        }
    }
}