lesspub 1.0.2

CLI tool for downloading Sequences from LessWrong and exporting them as EPUB format ebooks
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
use chrono::{DateTime, SubsecRound, Utc};
use indicatif::ProgressBar;
use lol_html::element;
use lol_html::{RewriteStrSettings, rewrite_str};
use rapidhash::RapidHashMap as HashMap;
use rapidhash::RapidHashSet as HashSet;
use std::error::Error;
use std::fs;
use std::path::Path;

use const_format::formatcp;

use anyhow::anyhow;
use bytes::Buf;
use epub_builder::{EpubBuilder, EpubContent, ReferenceType, ZipLibrary};
use rand::{Rng, SeedableRng};
use reqwest::Client;
use slug::slugify;
use uuid::Uuid;

use crate::html::sequence_title_page;
use crate::{
    cache::get_crosspost,
    cli::CacheOptions,
    html::{cover_page, title_page, wrap_body},
    image::{cover_image, intern_image},
};
use lesspub_schema::{Collection, Post, Sequence};

const LW_IMG_PREFIX: &str = "https://res.cloudinary.com/lesswrong-2-0/image/upload/c_fill,ar_0.625,g_auto:subject:thirds_0,q_auto:best/";
const SEQUENCE_IMG_PREFIX: &str = formatcp!("{LW_IMG_PREFIX}v1/");
const DEFAULT_SEQUENCE_IMG: &str = "sequences/vnyzzznenju0hzdv6pqb.jpg";
const DEFAULT_POST_IMG_URL: &str = formatcp!(
    "{LW_IMG_PREFIX}ohabryka_Topographic_aquarelle_book_cover_by_Thomas_W._Schaller_f9c9dbbe-4880-4f12-8ebb-b8f0b900abc1_m4k6dy_734413"
);
const COVER_PATH: &str = "cover.png";
const SEQUENCE_URL_PREFIX: &str = "https://www.lesswrong.com/sequences/";
const LW_POST_URL_PREFIX: &str = "https://www.lesswrong.com/posts/";

#[derive(Debug, Clone)]
pub struct EpubInfo {
    pub created: Option<DateTime<Utc>>,
    pub updated: Option<DateTime<Utc>>,
    pub entries: usize,
}
pub fn get_saved_epub_data(
    title: &str,
    output_dir: &Path,
) -> Result<Option<EpubInfo>, Box<dyn Error>> {
    let filename = format!("{}.epub", slugify(title));
    let path = output_dir.join(filename);
    if !path.exists() || !path.is_file() {
        Ok(None)
    } else if let Ok(epub) = epub::doc::EpubDoc::new(path) {
        Ok(Some(EpubInfo {
            created: epub
                .mdata("date")
                .and_then(|meta| Some(DateTime::parse_from_rfc3339(&meta).ok()?.to_utc())),
            updated: epub
                .mdata("dcterms:modified")
                .and_then(|meta| Some(DateTime::parse_from_rfc3339(&meta).ok()?.to_utc())),
            entries: epub
                .toc
                .len()
                .max(epub.toc.into_iter().flat_map(|p| p.children).count()),
        }))
    } else {
        Ok(None)
    }
}

pub enum EpubStatus {
    UpToDate,
    OutOfDate,
    Nonexistent,
}
pub fn parse_saved_post_epub_data(
    data: Result<Option<EpubInfo>, Box<dyn Error>>,
    post: &Post,
) -> EpubStatus {
    match data {
        Ok(Some(epub_info)) => {
            if epub_info.updated.is_some_and(|updated| {
                post.modifiedAt
                    .is_some_and(|modified_at| updated < modified_at.trunc_subsecs(0))
            }) {
                EpubStatus::OutOfDate
            } else {
                EpubStatus::UpToDate
            }
        }
        _ => EpubStatus::Nonexistent,
    }
}
pub fn parse_saved_sequence_epub_data(
    data: Result<Option<EpubInfo>, Box<dyn Error>>,
    sequence: &Sequence,
) -> EpubStatus {
    match data {
        Ok(Some(epub_info)) => {
            if epub_info.entries < sequence.postsCount.unwrap_or_default() as usize
                || epub_info.updated.is_some_and(|updated| {
                    updated < sequence.lastUpdated.unwrap_or_default().trunc_subsecs(0)
                })
            {
                EpubStatus::OutOfDate
            } else {
                EpubStatus::UpToDate
            }
        }
        _ => EpubStatus::Nonexistent,
    }
}

pub async fn build_sequence_epub(
    client: &Client,
    sequence: Sequence,
    sequence_id: &str,
    cache_options: &CacheOptions,
    progress: ProgressBar,
) -> Result<EpubBuilder<ZipLibrary>, Box<dyn Error>> {
    let mut builder = EpubBuilder::new(ZipLibrary::new()?)?;
    builder.epub_version(epub_builder::EpubVersion::V30);
    let mut level = 0;

    let author = if let Some(user) = sequence.user {
        if let Some(display_name) = user.displayName {
            builder.metadata("author", &display_name)?;
            display_name
        } else if let Some(username) = user.username {
            builder.metadata("author", &username)?;
            username
        } else {
            "unknown".to_string()
        }
    } else {
        "unknown".to_string()
    };

    if let Some(title) = sequence.title.clone() {
        builder.metadata("title", title)?;
    }

    if let Some(created_at) = sequence.createdAt {
        builder.set_publication_date(created_at);
    }
    if let Some(updated_at) = sequence.lastUpdated {
        builder.set_modified_date(updated_at);
    }

    builder.set_uuid(Uuid::from_u128(
        rapidhash::RapidRng::seed_from_u64(rapidhash::rapidhash(sequence_id.as_bytes())).random(),
    ));

    progress.set_message(format!("{sequence_id}: Generating cover image"));
    let image_id = sequence.bannerImageId.unwrap_or(
        sequence
            .gridImageId
            .unwrap_or(DEFAULT_SEQUENCE_IMG.to_string()),
    );

    let authors = &[author];
    let cover_image = match cover_image(
        &sequence.title.clone().unwrap_or("".to_string()),
        authors,
        client,
        &format!("{SEQUENCE_IMG_PREFIX}{image_id}"),
        cache_options,
        true,
    )
    .await
    {
        Ok(img) => img,
        Err(e) => {
            log::error!(
                "error generating cover image for sequence {sequence_id}, using fallback: {e:?}"
            );
            cover_image(
                &sequence.title.clone().unwrap_or("".to_string()),
                authors,
                client,
                &format!("{SEQUENCE_IMG_PREFIX}{DEFAULT_SEQUENCE_IMG}"),
                cache_options,
                false,
            )
            .await?
        }
    };
    builder.add_cover_image(COVER_PATH, cover_image.bytes.reader(), cover_image.mime)?;

    let description = sequence
        .contents
        .and_then(|contents| contents.html)
        .and_then(|html| {
            rewrite_str(
                &html,
                RewriteStrSettings {
                    element_content_handlers: vec![
                        element!("html", |el| {
                            el.remove_and_keep_content();
                            Ok(())
                        }),
                        element!("head", |el| {
                            el.remove();
                            Ok(())
                        }),
                        element!("body", |el| {
                            el.remove_and_keep_content();
                            Ok(())
                        }),
                    ],
                    ..RewriteStrSettings::new()
                },
            )
            .ok()
        });

    builder.add_content(
        EpubContent::new("cover.xhtml", cover_page(COVER_PATH).as_bytes())
            .reftype(ReferenceType::Cover),
    )?;

    let url = format!("{SEQUENCE_URL_PREFIX}{sequence_id}");
    builder.add_content(
        EpubContent::new(
            "title.xhtml",
            sequence_title_page(
                &sequence
                    .title
                    .clone()
                    .unwrap_or(format!("untitled_{sequence_id}")),
                &url,
                description,
            )
            .as_bytes(),
        )
        .reftype(ReferenceType::TitlePage),
    )?;

    if let Some(chapters) = sequence.chapters {
        for (index, chapter_option) in chapters.into_iter().enumerate() {
            progress.set_message(format!("{sequence_id}: Parsing chapter {index}"));

            if let Some(chapter) = chapter_option {
                let chapter_id = chapter._id.unwrap();
                progress.set_message(format!(
                    "{sequence_id}: Parsing chapter {index}: {chapter_id}"
                ));

                if let Some(title) = chapter.title.clone() {
                    progress.set_message(format!(
                        "{sequence_id}: Parsing chapter {index} ({chapter_id}): {title}"
                    ));

                    builder.add_content(
                        EpubContent::new(
                            format!("{chapter_id}_title.xhtml"),
                            title_page(&title).as_bytes(),
                        )
                        .title(title)
                        .reftype(ReferenceType::TitlePage)
                        .level(level),
                    )?;
                    level += 1;
                }

                if let Some(posts) = chapter.posts {
                    for (post_index, post_option) in posts.into_iter().enumerate() {
                        progress.set_message(format!(
                            "{sequence_id}: Parsing chapter {index} post {post_index}"
                        ));
                        if let Some(post) = post_option {
                            let post_id = post._id.clone().unwrap_or_default();
                            progress.set_message(format!(
                                "{sequence_id}: Parsing chapter {index} post {post_index}: {post_id}"
                            ));
                            if let Some(title) = &post.title {
                                progress.set_message(format!(
                                    "{sequence_id}: Parsing chapter {index} post {post_index} ({post_id}): {title}"
                                ));
                            }
                            if let Err(e) = async {
                                let mut post = post;

                                let id = post._id.ok_or(anyhow!("No post ID found"))?;

                                if let Some(fm_crosspost) = post.fmCrosspost {
                                    if fm_crosspost.isCrosspost
                                        && fm_crosspost
                                            .hostedHere
                                            .is_some_and(|hosted_here| !hosted_here)
                                    {
                                        if let Some(foreign_post_id) = fm_crosspost.foreignPostId {
                                            progress.set_message(format!(
                                                "Fetching remote post {foreign_post_id}"
                                            ));
                                            post = get_crosspost(
                                                client,
                                                &foreign_post_id,
                                                cache_options,
                                            )
                                            .await?;
                                        }
                                    }
                                }

                                let post_title = post.title.unwrap_or(id.clone());
                                let mut html_body =
                                    post.htmlBody.ok_or(anyhow!("No html body found"))?;

                                let mut urls = HashSet::default();
                                edit_image_urls(&html_body, |url| {
                                    urls.insert(url.clone());
                                    url
                                });
                                let mut images: HashMap<String, String> = HashMap::default();
                                for url in urls {
                                    match intern_image(&mut builder, client, &url, cache_options)
                                        .await
                                    {
                                        Ok(new_path) => {
                                            images.insert(url, new_path);
                                        }
                                        Err(e) => {
                                            log::warn!(
                                                "Notice: Failed to intern image for post {id}: {e}"
                                            );
                                            images.insert(url.clone(), url);
                                        }
                                    }
                                }
                                html_body = edit_image_urls(&html_body, |url| images[&url].clone());

                                let url = format!("{LW_POST_URL_PREFIX}{id}");

                                builder.add_content(
                                    EpubContent::new(
                                        format!("{id}_content.xhtml"),
                                        wrap_body(html_body, &post_title, &url).as_bytes(),
                                    )
                                    .title(post_title)
                                    .reftype(ReferenceType::Text)
                                    .level(level),
                                )?;

                                Ok::<(), Box<dyn Error>>(())
                            }
                            .await
                            {
                                log::error!(
                                    "Error appending post {post_id} to sequence {sequence_id}: {e:?}"
                                );
                            }
                        }
                    }
                }

                if chapter.title.is_some() {
                    level -= 1;
                }
            }
        }
    }

    Ok(builder)
}

pub fn save_sequence_epub(
    builder: EpubBuilder<ZipLibrary>,
    sequence: Sequence,
    sequence_id: &str,
    output_dir: &Path,
    collection_subfolder: bool,
) -> Result<(), Box<dyn Error>> {
    let mut file: Vec<u8> = vec![];
    builder.generate(&mut file)?;

    let title = sequence.title.unwrap_or(format!("untitled_{sequence_id}"));
    let slug = slugify(title);

    let out_dir = if collection_subfolder {
        let folder = slugify(
            sequence
                .canonicalCollection
                .unwrap_or(Collection {
                    _id: Some(String::new()),
                    slug: Some("library".to_string()),
                    title: Some("Library".to_string()),
                    gridImageId: None,
                })
                .slug
                .unwrap_or("unknown".to_string()),
        );
        output_dir.join(folder)
    } else {
        output_dir.to_path_buf()
    };

    fs::create_dir_all(&out_dir)?;
    fs::write(out_dir.join(format!("{slug}.epub")), file)?;

    Ok(())
}

pub async fn build_and_save_sequence_epub(
    client: &Client,
    sequence: Sequence,
    sequence_id: &str,
    cache_options: &CacheOptions,
    output_dir: &Path,
    collection_subfolder: bool,
    progress: ProgressBar,
) -> Result<(), Box<dyn Error>> {
    let title = sequence
        .clone()
        .title
        .unwrap_or(format!("untitled_{sequence_id}"));
    let out_dir = if collection_subfolder {
        let folder = slugify(
            sequence
                .clone()
                .canonicalCollection
                .unwrap_or(Collection {
                    _id: Some(String::new()),
                    slug: Some("library".to_string()),
                    title: Some("Library".to_string()),
                    gridImageId: None,
                })
                .slug
                .unwrap_or("unknown".to_string()),
        );
        output_dir.join(folder)
    } else {
        output_dir.to_path_buf()
    };

    match parse_saved_sequence_epub_data(get_saved_epub_data(&title, &out_dir), &sequence) {
        EpubStatus::Nonexistent => {
            log::debug!("Downloading new sequence {sequence_id}: {title}");
            let builder = build_sequence_epub(
                client,
                sequence.clone(),
                sequence_id,
                cache_options,
                progress,
            )
            .await?;
            save_sequence_epub(
                builder,
                sequence,
                sequence_id,
                output_dir,
                collection_subfolder,
            )?;
        }
        EpubStatus::OutOfDate => {
            log::debug!("Ignoring cache for {sequence_id}: Generated copy is out-of-date.");
            let builder = build_sequence_epub(
                client,
                sequence.clone(),
                sequence_id,
                &CacheOptions {
                    ignore_cache: true,
                    cache_dir: cache_options.cache_dir.clone(),
                },
                progress,
            )
            .await?;
            save_sequence_epub(
                builder,
                sequence,
                sequence_id,
                output_dir,
                collection_subfolder,
            )?;
        }
        EpubStatus::UpToDate => {
            log::debug!(
                "Skipping epub generation for {sequence_id}: Generated copy is up-to-date."
            );
        }
    };
    Ok(())
}

pub async fn build_post_epub(
    client: &Client,
    post: Post,
    post_id: &str,
    cache_options: &CacheOptions,
    progress: ProgressBar,
) -> Result<EpubBuilder<ZipLibrary>, Box<dyn Error>> {
    let mut builder = EpubBuilder::new(ZipLibrary::new()?)?;
    builder.epub_version(epub_builder::EpubVersion::V30);

    let author = if let Some(user) = post.user {
        if let Some(display_name) = user.displayName {
            builder.metadata("author", &display_name)?;
            display_name
        } else if let Some(username) = user.username {
            builder.metadata("author", &username)?;
            username
        } else {
            "unknown".to_string()
        }
    } else {
        "unknown".to_string()
    };

    let post_title = post.title.clone().unwrap_or(String::from("unknown"));

    builder.metadata("title", &post_title)?;

    if let Some(created_at) = post.createdAt {
        builder.set_publication_date(created_at);
    }
    if let Some(updated_at) = post.modifiedAt {
        builder.set_modified_date(updated_at);
    }

    builder.set_uuid(Uuid::from_u128(
        rapidhash::RapidRng::seed_from_u64(rapidhash::rapidhash(post_id.as_bytes())).random(),
    ));

    progress.set_message(format!("{post_id}: Generating cover image"));
    let mut image_url = post.socialPreviewImageAutoUrl.unwrap_or(
        post.sequence
            .map(|sequence| {
                sequence
                    .bannerImageId
                    .map(|banner_image_id| format!("{SEQUENCE_IMG_PREFIX}{banner_image_id}"))
                    .unwrap_or(
                        sequence
                            .gridImageId
                            .map(|grid_image_id| format!("{SEQUENCE_IMG_PREFIX}{grid_image_id}"))
                            .unwrap_or(DEFAULT_POST_IMG_URL.to_string()),
                    )
            })
            .unwrap_or(DEFAULT_POST_IMG_URL.to_string()),
    );
    if image_url == String::new() {
        image_url = DEFAULT_POST_IMG_URL.to_string();
    }

    let authors = &[author];
    let cover_image = match cover_image(
        &post.title.clone().unwrap_or("".to_string()),
        authors,
        client,
        &image_url,
        cache_options,
        true,
    )
    .await
    {
        Ok(img) => img,
        Err(e) => {
            log::error!("error generating cover image for post {post_id}, using fallback: {e:?}");
            cover_image(
                &post.title.clone().unwrap_or("".to_string()),
                authors,
                client,
                DEFAULT_POST_IMG_URL,
                cache_options,
                false,
            )
            .await?
        }
    };
    builder.add_cover_image(COVER_PATH, cover_image.bytes.reader(), cover_image.mime)?;

    builder.add_content(
        EpubContent::new("cover.xhtml", cover_page(COVER_PATH).as_bytes())
            .reftype(ReferenceType::Cover),
    )?;

    let mut html_body = post.htmlBody.ok_or(anyhow!("No html body found"))?;

    let mut urls = HashSet::default();
    edit_image_urls(&html_body, |url| {
        urls.insert(url.clone());
        url
    });
    let mut images: HashMap<String, String> = HashMap::default();
    for url in urls {
        match intern_image(&mut builder, client, &url, cache_options).await {
            Ok(new_path) => {
                images.insert(url, new_path);
            }
            Err(e) => {
                log::warn!("Notice: Failed to intern image for post {post_id}: {e}");
                images.insert(url.clone(), url);
            }
        }
    }
    html_body = edit_image_urls(&html_body, |url| images[&url].clone());

    let url = format!("{LW_POST_URL_PREFIX}{post_id}");

    builder.add_content(
        EpubContent::new(
            "content.xhtml",
            wrap_body(html_body, &post_title, &url).as_bytes(),
        )
        .title(post_title)
        .reftype(ReferenceType::Text),
    )?;

    Ok(builder)
}

pub fn save_post_epub(
    builder: EpubBuilder<ZipLibrary>,
    post: Post,
    post_id: &str,
    output_dir: &Path,
) -> Result<(), Box<dyn Error>> {
    let mut file: Vec<u8> = vec![];
    builder.generate(&mut file)?;

    let title = post.title.unwrap_or(format!("untitled_{post_id}"));
    let slug = slugify(title);
    fs::create_dir_all(output_dir)?;
    fs::write(output_dir.join(format!("{slug}.epub")), file)?;

    Ok(())
}

pub async fn build_and_save_post_epub(
    client: &Client,
    post: Post,
    post_id: &str,
    cache_options: &CacheOptions,
    output_dir: &Path,
    progress: ProgressBar,
) -> Result<(), Box<dyn Error>> {
    let title = post.title.clone().unwrap_or(format!("untitled_{post_id}"));
    match parse_saved_post_epub_data(get_saved_epub_data(&title, output_dir), &post) {
        EpubStatus::Nonexistent => {
            log::debug!("Downloading new post {post_id}: {title}");
            let builder =
                build_post_epub(client, post.clone(), post_id, cache_options, progress).await?;
            save_post_epub(builder, post, post_id, output_dir)?;
        }
        EpubStatus::OutOfDate => {
            log::debug!("Ignoring cache for {post_id}: Generated copy is out-of-date.");
            let builder = build_post_epub(
                client,
                post.clone(),
                post_id,
                &CacheOptions {
                    ignore_cache: true,
                    cache_dir: cache_options.cache_dir.clone(),
                },
                progress,
            )
            .await?;
            save_post_epub(builder, post, post_id, output_dir)?;
        }
        EpubStatus::UpToDate => {
            log::debug!("Skipping epub generation for {post_id}: Generated copy is up-to-date.");
        }
    };
    Ok(())
}

/// Blatantly stolen from GlowPub
/// (Because otherwise, I had to add that entire project to the dependencies for this one function)
pub fn edit_image_urls(content: &str, mut f: impl FnMut(String) -> String) -> String {
    rewrite_str(
        content,
        RewriteStrSettings {
            element_content_handlers: vec![element!("img", |el| {
                if let Some(url) = el.get_attribute("src") {
                    let new_url = f(url);
                    el.set_attribute("src", &new_url).unwrap();
                }
                Ok(())
            })],
            ..RewriteStrSettings::default()
        },
    )
    .unwrap()
}