eggbug 0.2.0

Bot library for cohost.org
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
use crate::{Ask, Asker, Attachment, Error, Session};
pub(crate) use de::PostPage;
use derive_more::{Display, From, FromStr, Into};
use reqwest::Method;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;

/// A post ID.
#[allow(clippy::module_name_repetitions)]
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    Deserialize,
    Display,
    Eq,
    From,
    FromStr,
    Hash,
    Into,
    Ord,
    PartialEq,
    PartialOrd,
    Serialize,
)]
#[serde(transparent)]
pub struct PostId(pub u64);

/// Describes a post's contents.
///
/// When you send a post with [`Session::create_post`] or [`Session::edit_post`], the `Post` must
/// be mutable. This is because the [`attachments`][`Post::attachments`] field will be modified
/// with the ID and URL of the uploaded attachment.
#[derive(Debug, Default)]
#[must_use]
pub struct Post {
    /// Marks the post as [18+ content](https://help.antisoftware.club/support/solutions/articles/62000225024-what-does-adult-content-mean-).
    pub adult_content: bool,
    /// Post headline, which is displayed above attachments and markdown.
    pub headline: String,
    /// The ask to which this post is responding, if any.
    pub ask: Option<Ask>,
    /// List of attachments, displayed between the headline and markdown.
    pub attachments: Vec<Attachment>,
    /// Markdown content for the post, displayed after the headline and attachments.
    pub markdown: String,
    /// List of tags.
    pub tags: Vec<String>,
    /// List of content warnings.
    pub content_warnings: Vec<String>,
    /// Marks the post as a draft, preventing it from being seen by other users without the draft
    /// link.
    pub draft: bool,
    /// Metadata returned by cohost from posts retrieved from the API.
    ///
    /// This field is ignored when creating or editing a post.
    pub metadata: Option<PostMetadata>,
}

/// Metadata returned by the cohost API for posts retrieved from post pages.
#[derive(Debug)]
#[non_exhaustive]
#[allow(clippy::struct_excessive_bools, clippy::module_name_repetitions)]
pub struct PostMetadata {
    /// All identifiers regarding where this post can be found.
    pub locations: PostLocations,
    /// True if the client has permission to share this post.
    pub can_share: bool,
    /// True if adding new comments is disabled on this post.
    pub comments_locked: bool,
    /// True if any contributor to the post is muted by the current account.
    pub has_any_contributor_muted: bool,
    /// True if cohost plus features were available to the poster.
    pub has_cohost_plus: bool,
    /// True if the current account has liked this post.
    pub liked: bool,
    /// The number of comments on this post.
    pub num_comments: u64,
    /// The number of comments on other posts in this post's branch of the
    /// share tree.
    pub num_shared_comments: u64,
    /// True if this post is pinned to its author's profile.
    pub pinned: bool,
    /// The handle of the project that posted this post.
    pub posting_project_id: String,
    /// The time at which the post was published.
    pub publication_date: chrono::DateTime<chrono::Utc>,
    /// A list of the handles of all the projects involved in this post.
    pub related_projects: Vec<String>,
    /// A list of all the posts in this post's branch of the share tree.
    pub share_tree: Vec<Post>,
}

/// All identifying information about where to find a post, from its ID to how to edit it.
#[derive(Debug, Hash, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[allow(clippy::module_name_repetitions)]
pub struct PostLocations {
    /// The unique numerical ID of the post.
    pub id: PostId,
    /// The filename of the post, excluding the protocol, domain, and project.
    /// Acts as a unique ID with a semi-readable slug.
    pub filename: String,
    /// The complete URL at which this post can be viewed.
    pub url: String,
    /// The location at which this post can be edited.
    pub edit_url: String,
}

impl Post {
    /// Returns true if the post has no content (no headline, attachments, or markdown content).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.attachments.is_empty() && self.headline.is_empty() && self.markdown.is_empty()
    }

    pub(crate) async fn send(
        &mut self,
        session: &Session,
        method: Method,
        path: &str,
        project: &str,
        shared_post: Option<PostId>,
    ) -> Result<PostId, Error> {
        if self.is_empty() && shared_post.is_none() {
            return Err(Error::EmptyPost);
        }
        if self.attachments.iter().any(Attachment::is_failed) {
            return Err(Error::FailedAttachment);
        }

        let need_upload = self.attachments.iter().any(Attachment::is_new);

        let de::PostResponse { post_id } = session
            .client
            .request(method, path)
            .json(&self.as_api(need_upload, shared_post))
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?;
        tracing::info!(%post_id);

        if need_upload {
            futures::future::try_join_all(
                self.attachments
                    .iter_mut()
                    .map(|attachment| attachment.upload(&session.client, project, post_id)),
            )
            .await?;

            session
                .client
                .put(&format!("project/{}/posts/{}", project, post_id))
                .json(&self.as_api(false, shared_post))
                .send()
                .await?
                .error_for_status()?;
        }

        Ok(post_id)
    }

    #[tracing::instrument]
    fn as_api(&self, force_draft: bool, shared_post: Option<PostId>) -> ser::Post<'_> {
        let mut blocks = self
            .attachments
            .iter()
            .map(|attachment| ser::Block::Attachment {
                attachment: ser::Attachment {
                    alt_text: attachment.alt_text.as_deref(),
                    attachment_id: attachment.id().unwrap_or_default(),
                },
            })
            .collect::<Vec<_>>();
        if !self.markdown.is_empty() {
            for block in self.markdown.split("\n\n") {
                blocks.push(ser::Block::Markdown {
                    markdown: ser::Markdown { content: block },
                });
            }
        }

        #[allow(clippy::bool_to_int_with_if)]
        let post_state = if force_draft || self.draft { 0 } else { 1 };

        let post = ser::Post {
            adult_content: self.adult_content,
            blocks,
            cws: &self.content_warnings,
            headline: &self.headline,
            post_state,
            share_of_post_id: shared_post,
            tags: &self.tags,
        };
        tracing::debug!(?post);
        post
    }
}

impl From<de::Post> for Post {
    fn from(api: de::Post) -> Self {
        let locations = PostLocations {
            id: api.post_id,
            filename: api.filename,
            url: api.single_post_page_url,
            edit_url: api.post_edit_url,
        };
        let metadata = PostMetadata {
            locations,
            can_share: api.can_share,
            comments_locked: api.comments_locked,
            has_any_contributor_muted: api.has_any_contributor_muted,
            has_cohost_plus: api.has_cohost_plus,
            liked: api.is_liked,
            num_comments: api.num_comments,
            num_shared_comments: api.num_shared_comments,
            pinned: api.pinned,
            related_projects: {
                let mut related_projects: Vec<String> = api
                    .related_projects
                    .into_iter()
                    .map(|project| project.handle)
                    .collect();
                if related_projects.is_empty() {
                    related_projects.push(api.posting_project.handle.clone());
                };
                related_projects
            },
            posting_project_id: api.posting_project.handle,
            publication_date: api.published_at,
            share_tree: api.share_tree.into_iter().map(Post::from).collect(),
        };

        let mut attachments: Vec<Attachment> = Vec::new();
        let mut ask: Option<Ask> = None;
        for block in api.blocks {
            match block {
                de::Block::Attachment { attachment } => {
                    attachments.push(crate::attachment::Attachment::from(attachment));
                }
                // Note: there should only be one ask per post!
                de::Block::Ask { ask: v } => ask = Some(crate::ask::Ask::from(v)),
                de::Block::Markdown { .. } => {}
            }
        }

        Self {
            metadata: Some(metadata),
            ask,
            adult_content: api.effective_adult_content,
            headline: api.headline,
            markdown: api.plain_text_body,
            tags: api.tags,
            content_warnings: api.cws,
            draft: api.state == 0,
            attachments,
        }
    }
}

impl From<de::Attachment> for Attachment {
    fn from(api: de::Attachment) -> Self {
        Self {
            kind: crate::attachment::Inner::Uploaded(crate::attachment::Finished {
                attachment_id: api.attachment_id,
                url: api.file_url,
            }),
            alt_text: api.alt_text,
        }
    }
}

impl From<de::Ask> for Ask {
    fn from(api: de::Ask) -> Self {
        Self {
            ask_id: api.ask_id,
            asker: api.asking_project.map(crate::ask::Asker::from),
            content: api.content,
            sent_at: api.sent_at,
        }
    }
}

impl From<de::AskingProject> for Asker {
    fn from(api: de::AskingProject) -> Self {
        Self {
            display_name: api.display_name.unwrap_or_else(|| api.handle.clone()),
            handle: api.handle,
        }
    }
}

impl From<PostPage> for Vec<Post> {
    fn from(page: PostPage) -> Self {
        page.items.into_iter().map(Post::from).collect()
    }
}

mod ser {
    use super::PostId;
    use crate::attachment::AttachmentId;
    use serde::Serialize;
    use std::fmt::{self, Debug};

    #[derive(Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct Post<'a> {
        pub adult_content: bool,
        pub blocks: Vec<Block<'a>>,
        pub cws: &'a [String],
        pub headline: &'a str,
        pub post_state: u64,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub share_of_post_id: Option<PostId>,
        pub tags: &'a [String],
    }

    impl Debug for Post<'_> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}", serde_json::to_value(self).map_err(|_| fmt::Error)?)
        }
    }

    #[derive(Serialize)]
    #[serde(tag = "type", rename_all = "camelCase")]
    pub enum Block<'a> {
        Attachment { attachment: Attachment<'a> },
        Markdown { markdown: Markdown<'a> },
    }

    #[derive(Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct Attachment<'a> {
        #[serde(skip_serializing_if = "Option::is_none")]
        pub alt_text: Option<&'a str>,
        pub attachment_id: AttachmentId,
    }

    #[derive(Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct Markdown<'a> {
        pub content: &'a str,
    }
}

mod de {
    use super::PostId;
    use crate::{AskId, AttachmentId};
    use serde::Deserialize;

    #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct PostPage {
        pub(super) n_items: u64,
        pub(super) n_pages: u64,
        pub(super) items: Vec<Post>,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
    #[serde(rename_all = "camelCase")]
    #[allow(clippy::struct_excessive_bools)]
    pub struct Post {
        pub blocks: Vec<Block>,
        //pub can_publish: bool,
        pub can_share: bool,
        pub comments_locked: bool,
        //pub contributor_block_incoming_or_outgoing: bool,
        pub cws: Vec<String>,
        pub effective_adult_content: bool,
        pub filename: String,
        pub has_any_contributor_muted: bool,
        pub has_cohost_plus: bool,
        pub headline: String,
        //pub is_editor: bool,
        pub is_liked: bool,
        pub num_comments: u64,
        pub num_shared_comments: u64,
        pub pinned: bool,
        pub plain_text_body: String,
        pub post_edit_url: String,
        pub post_id: PostId,
        pub posting_project: PostingProject,
        pub published_at: chrono::DateTime<chrono::Utc>,
        pub related_projects: Vec<PostingProject>,
        pub share_tree: Vec<Post>,
        pub single_post_page_url: String,
        pub state: u64,
        pub tags: Vec<String>,
        //pub transparent_share_of_post_id: Option<PostId>,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct PostingProject {
        pub handle: String,
        //pub display_name: Option<String>,
        //pub dek: Option<String>,
        //pub description: Option<String>,
        //#[serde(rename = "avatarURL")]
        //pub avatar_url: String,
        //#[serde(rename = "avatarPreviewURL")]
        //pub avatar_preview_url: String,
        //pub project_id: ProjectId,
        //pub privacy: String,
        //pub pronouns: Option<String>,
        //pub url: Option<String>,
        //pub avatar_shape: String,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct AskingProject {
        pub handle: String,
        pub display_name: Option<String>,
        //pub dek: Option<String>,
        //pub description: Option<String>,
        //#[serde(rename = "avatarURL")]
        //pub avatar_url: String,
        //#[serde(rename = "avatarPreviewURL")]
        //pub avatar_preview_url: String,
        //pub project_id: ProjectId,
        //pub privacy: String,
        //pub avatar_shape: String,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
    #[serde(tag = "type", rename_all = "camelCase")]
    pub enum Block {
        Attachment { attachment: Attachment },
        Markdown { markdown: Markdown },
        Ask { ask: Ask },
    }

    #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct Attachment {
        #[serde(default)]
        pub alt_text: Option<String>,
        pub attachment_id: AttachmentId,
        #[serde(rename = "fileURL")]
        pub file_url: String,
        #[serde(rename = "previewURL")]
        pub preview_url: String,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct Markdown {
        pub content: String,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct Ask {
        #[serde(rename = "askId")]
        pub ask_id: AskId,
        pub anon: bool,
        #[serde(rename = "askingProject")]
        pub asking_project: Option<AskingProject>,
        pub content: String,
        #[serde(rename = "sentAt")]
        pub sent_at: chrono::DateTime<chrono::Utc>,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct PostResponse {
        pub post_id: PostId,
    }
}

#[test]
fn test_parse_project_post_page() -> Result<(), Box<dyn std::error::Error>> {
    let post_page: de::PostPage =
        serde_json::from_str(include_str!("../samples/example.project.posts.json"))?;
    assert_eq!(post_page.n_items, 3);
    assert_eq!(
        usize::try_from(post_page.n_items).unwrap(),
        post_page.items.len()
    );
    let post = post_page
        .items
        .iter()
        .find(|post| post.post_id.0 == 185_838)
        .expect("Couldn't find post by ID 185838 as expected; did you change the sample?");
    assert_eq!(post.headline, "This is a test post.");
    assert_eq!(post.filename, "185838-this-is-a-test-post");
    assert_eq!(post.state, 1);
    //assert!(post.transparent_share_of_post_id.is_none());
    assert_eq!(post.num_comments, 0);
    assert_eq!(post.num_shared_comments, 0);
    assert_eq!(post.tags.len(), 3);
    assert_eq!(post.cws.len(), 0);
    assert_eq!(post.related_projects.len(), 0);

    let post = post_page
        .items
        .iter()
        .find(|post| post.post_id.0 == 185_916)
        .expect("Couldn't find post by ID 185916 as expected; did you change the sample?");

    assert_eq!(post.related_projects.len(), 2);
    assert_eq!(post.share_tree.len(), 1);
    Ok(())
}

#[test]
fn test_parse_project_post_page_with_ask() -> Result<(), Box<dyn std::error::Error>> {
    let post_page: de::PostPage =
        serde_json::from_str(include_str!("../samples/with-ask.project.posts.json"))?;

    let post = post_page
        .items
        .iter()
        .find(|post| post.post_id.0 == 1_811_182)
        .expect("Couldn't find post by ID 1811182 as expected; did you change the sample?");

    assert_eq!(post.blocks.len(), 3);
    let ask = match post.blocks.first() {
        Some(de::Block::Ask { ask }) => ask,
        _ => panic!("no ask block in ask test post"),
    };
    assert_eq!(ask.ask_id, crate::ask::AskId("871936863978390842".into()));
    assert!(!ask.anon);
    assert!(ask.asking_project.is_some());
    assert_eq!(ask.content.len(), 84);
    Ok(())
}

#[test]
fn test_convert_post() -> Result<(), Box<dyn std::error::Error>> {
    let post_page: de::PostPage =
        serde_json::from_str(include_str!("../samples/example.project.posts.json"))?;
    let post = post_page
        .items
        .iter()
        .find(|post| post.post_id.0 == 185_838)
        .expect("Couldn't find post by ID 185838 as expected; did you change the sample?");
    let converted_post = Post::from(post.clone());
    let converted_post_metadata = converted_post
        .metadata
        .expect("No metadata for converted post!");
    assert_eq!(post.post_id, converted_post_metadata.locations.id);
    assert!(!converted_post.attachments.is_empty());
    assert_eq!(
        converted_post_metadata.publication_date.timestamp(),
        1_667_531_869
    );

    Ok(())
}

#[test]
fn test_convert_project_post_with_ask() -> Result<(), Box<dyn std::error::Error>> {
    let post_page: de::PostPage =
        serde_json::from_str(include_str!("../samples/with-ask.project.posts.json"))?;

    let post = post_page
        .items
        .iter()
        .find(|post| post.post_id.0 == 1_811_182)
        .expect("Couldn't find post by ID 1811182 as expected; did you change the sample?");

    let converted_post = Post::from(post.clone());
    let ask = converted_post.ask.expect("no ask in ask example post!");
    assert_eq!(ask.id(), "871936863978390842");
    assert_eq!(ask.content.len(), 84);
    let asker = ask.asker.expect("no asker in ask example post!");
    assert_eq!(asker.handle, "asunchaser".to_string());
    Ok(())
}