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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
#![deny(
    rustdoc::broken_intra_doc_links,
    rustdoc::private_intra_doc_links,
    rustdoc::bare_urls
)]
#![warn(missing_docs, rustdoc::unescaped_backticks)]
//! [![docs.rs](https://img.shields.io/docsrs/libwebnovel-storage)](https://docs.rs/libwebnovel-storage)
//!
//! This is an implementation of a local repository of webnovels. It downloads
//! webnovels & places them in a coherent manner on the filesystem.
//!
//! ## What this does
//!
//! Basically, it provides data structures and method easing the work of implementing a program using [`libwebnovel`](https://crates.io/crates/libwebnovel).
//!
//! ## Example
//!
//! ```rust,no_run
//! use libwebnovel_storage::{LibraryError, LocalLibrary};
//! fn main() -> Result<(), LibraryError> {
//!     let library_path = ".config/my_library/config.toml";
//!     let mut library = LocalLibrary::load(library_path)?;
//!     // Add to watchlist & download
//!     library.add("https://www.royalroad.com/fiction/21220/mother-of-learning")?;
//!
//!     // update all novels
//!     let errors = library.update();
//!     // or, if you want to have more control over the update process
//!     // (for instance, printing a progress bar):
//!     for novel in library.novels_mut() {
//!         let novel_title = novel.title()?.clone();
//!         for (i, result) in novel.update_iter().enumerate() {
//!             if result.is_err() {
//!                 eprintln!(
//!                     "Encountered an error while updating novel {}: {}",
//!                     novel_title,
//!                     result.unwrap_err()
//!                 );
//!             }
//!             println!("novel {}: updated chapter {}", novel_title, i + 1);
//!         }
//!     }
//!
//!     Ok(())
//! }
//! ```
//!
//! # TODO
//!
//! - [x] a local filesystem representation for a novel library
//! - [x] bulk updates
//!   - [x] bulk updates with an iterator, to offer control over looping and get
//!     update information while they happen
//! - [ ] add epub generation
//!
//! ## Legal
//!
//! Without explicit refutation in the header of any file in this repository,
//! all files in this repository are considered under the terms of the AGPL-3
//! license (of which a copy can be found in the LICENSE file at the root of
//! this repository) and bearing the mention "Copyright (c) 2024 paulollivier &
//! contributors".
//!
//! Basically, please do not use this code without crediting its writer(s) or
//! for a commercial project.

use std::fmt::{Debug, Formatter};
use std::fs;
use std::fs::{create_dir_all, File};
use std::io::{Cursor, Read, Write};
use std::path::{Path, PathBuf};

use directories::BaseDirs;
use fs_extra::dir::{move_dir, CopyOptions};
use image::{ImageError, ImageFormat};
use libwebnovel::backends::BackendError;
use libwebnovel::{Backend, Backends, Chapter, ChapterParseError};
use log::{debug, error, info, trace, warn};
use serde::{Deserialize, Serialize};
use url::Url;

/// Represents an error that can happen during Library operations
#[derive(thiserror::Error, Debug)]
pub enum LibraryError {
    /// Wraps a [`std::io::Error`]
    #[error(transparent)]
    IoError(#[from] std::io::Error),
    /// Wraps a [`toml::de::Error`]
    #[error(transparent)]
    TomlDeserializationError(#[from] toml::de::Error),
    /// Wraps a [`toml::ser::Error`]
    #[error(transparent)]
    TomlSerializationError(#[from] toml::ser::Error),
    /// Wraps an [`url::ParseError`]
    #[error(transparent)]
    UrlParseError(#[from] url::ParseError),
    /// Wraps a [`ChapterParseError`]
    #[error(transparent)]
    ChapterParseError(#[from] ChapterParseError),
    /// Wraps a [`BackendError`]
    #[error(transparent)]
    BackendError(#[from] BackendError),
    /// Wraps a [`ImageError`]
    #[error(transparent)]
    ImageError(#[from] ImageError),
    /// Needed for accepting convert error with ?.
    #[error(transparent)]
    Infallible(#[from] std::convert::Infallible),
    /// Wraps an error from fs_extra
    #[error(transparent)]
    FsError(#[from] fs_extra::error::Error),
    /// Returned when attempting to delete a fiction
    #[error("No novel with URL \"{0}\"was found.")]
    NoSuchNovel(Url),
    /// A generic error encountered when parsing something
    #[error("{0}")]
    ParseError(String),
    /// Returned when trying to add a novel that is already watched
    #[error("Novel at url {0} is already in our watchlist")]
    NovelAlreadyPresent(Url),
}

/// A local disk storage.
/// ```rust
/// use tempfile::tempdir;
/// use libwebnovel_storage::LocalLibrary;
///
/// // Dummy path to a config file. If the path does not exist, a default configuration will be created
/// let config_path = "path/to/toml_config";
/// # let tempdir = tempdir().unwrap();
/// # let config_path = tempdir.path().join(env!("CARGO_PKG_NAME"));
///
/// let mut library = LocalLibrary::load(config_path).unwrap();
/// // Add & download a given URL
/// library
///     .add("https://www.royalroad.com/fiction/21220/mother-of-learning")
///     .unwrap();
/// let novel_urls_list = library.list();
/// assert_eq!(novel_urls_list.len(), 1);
/// assert_eq!(
///     &novel_urls_list[0].to_string(),
///     "https://www.royalroad.com/fiction/21220/mother-of-learning"
/// );
/// ```
#[derive(Serialize, Deserialize, Debug)]
pub struct LocalLibrary {
    #[serde(skip)]
    config_path: PathBuf,
    library_base_path: PathBuf,
    novels: Vec<Novel>,
}

impl Default for LocalLibrary {
    fn default() -> Self {
        let dirs = BaseDirs::new().unwrap();
        Self {
            config_path: dirs.config_dir().join(env!("CARGO_PKG_NAME")).to_path_buf(),
            library_base_path: dirs.data_dir().join(env!("CARGO_PKG_NAME")),
            novels: Vec::new(),
        }
    }
}

impl LocalLibrary {
    /// Attempts to create a new [`Self`] from a config file.
    /// ```rust
    /// use directories::BaseDirs;
    /// use libwebnovel_storage::LocalLibrary;
    ///
    /// let config_path = "path/to/config.toml";
    /// let library = LocalLibrary::load(config_path).unwrap(); // If the path doesn't exist, a
    ///                                                         // default configuration will be
    ///                                                         // loaded
    /// // Get the default data directory on this platform
    /// let basedirs = BaseDirs::new().unwrap();
    /// let data_dir = basedirs.data_dir().join(env!["CARGO_PKG_NAME"]);
    /// assert_eq!(library.base_path(), data_dir);
    /// ```
    pub fn load(config_path: impl Into<PathBuf>) -> Result<Self, LibraryError> {
        let config_path = config_path.into();
        if !config_path.exists() {
            info!("Could not find a configuration file, creating one with default values.");
            return Ok(Self {
                config_path,
                ..Default::default()
            });
        }
        let mut config_file = File::open(config_path)?;
        let mut config_str = String::new();
        config_file.read_to_string(&mut config_str)?;
        let config: Self = toml::from_str(&config_str)?;
        Ok(config)
    }

    /// Changes the library base data path, moving existing content if
    /// necessary.
    pub fn set_base_path(
        &mut self,
        base_path: impl Into<PathBuf> + AsRef<Path>,
    ) -> Result<(), LibraryError> {
        if self.library_base_path.is_dir() {
            // Then we need to move the content of the directory to the new one given in
            // parameter
            create_dir_all(&base_path)?;
            move_dir(
                &self.library_base_path,
                &base_path,
                &CopyOptions {
                    overwrite: true,
                    ..CopyOptions::default()
                },
            )?;
        }
        self.library_base_path = base_path.into();
        Ok(())
    }

    /// Saves the current config to disk.
    /// ```rust
    /// use std::path::Path;
    ///
    /// use libwebnovel_storage::LocalLibrary;
    ///
    /// let config_path_str = "/tmp/libwebnovel/config.toml";
    /// let config_path = Path::new(config_path_str);
    /// # use tempfile::tempdir;
    /// # let tempdir = tempdir().unwrap();
    /// # let config_path_str = tempdir.path().join(env!("CARGO_PKG_NAME")).join("config.toml");
    /// let library = LocalLibrary::load(config_path_str.clone()).unwrap();
    ///
    /// let config_path = Path::new(&config_path_str);
    /// assert!(!config_path.exists());
    /// library.persist().unwrap();
    /// # println!("config_path: {:?}", config_path.display());
    /// # println!("library: {:?}", library);
    /// assert!(config_path.exists());
    /// ```
    pub fn persist(&self) -> Result<(), LibraryError> {
        let toml = toml::to_string(self)?;
        fs::create_dir_all(self.config_path.parent().unwrap())?;
        let mut file = File::create(&self.config_path)?;
        file.write_all(toml.as_bytes())?;
        Ok(())
    }

    /// Returns the base path of the library storage
    pub fn base_path(&self) -> &Path {
        self.library_base_path.as_path()
    }

    /// Adds a new webnovel to watch. Won't call [`self.update()`].
    pub fn add(&mut self, url: &str) -> Result<String, LibraryError> {
        let url = url.parse::<Url>()?;
        if self.novels.iter().any(|n| n.url == url) {
            return Err(LibraryError::NovelAlreadyPresent(url));
        }
        let novel = Novel::new(url, self.base_path())?;
        let novel_title = novel.title()?;
        self.novels.push(novel);
        self.persist()?;
        Ok(novel_title)
    }

    /// Returns a list of webnovels currently watched
    pub fn list(&self) -> Vec<Url> {
        self.novels.iter().map(|novel| novel.url.clone()).collect()
    }

    /// Updates all watched novels. If at least one error has been encountered
    /// during update.
    pub fn update(&mut self) -> Result<(), Vec<LibraryError>> {
        let mut errors = Vec::new();
        for novel in self.novels.iter_mut() {
            match novel.update() {
                Ok(()) => {}
                Err(e) => {
                    errors.push(e);
                }
            }
        }
        if !errors.is_empty() {
            return Err(errors);
        }
        Ok(())
    }

    /// Removes a webnovel from the watchlist and deletes local content. If
    /// there are duplicates in the novels list, only the first found will be
    /// removed and deleted.
    pub fn remove(&mut self, url: &str) -> Result<(), LibraryError> {
        let url = Url::parse(url)?;
        self.novels.retain(|novel| {
            if novel.url == url {
                let path = novel.novel_path();
                if let Err(e) = fs::remove_dir_all(path) {
                    warn!("Failed to remove directory {}: {}", path.display(), e);
                }
                return false;
            }
            true
        });
        Ok(())
    }

    /// Returns a reference to the internal novels vector.
    pub fn novels(&self) -> &Vec<Novel> {
        &self.novels
    }

    /// Returns a mutable reference to the internal novels vector
    pub fn novels_mut(&mut self) -> &mut Vec<Novel> {
        &mut self.novels
    }
}

/// Represents a novel.
/// Stored on disk at the following path: <base_library_path>/<novel.title()>/
///
/// TODO: Detect remote novel title changes
#[derive(Serialize, Deserialize)]
#[serde(try_from = "NovelConfig", into = "NovelConfig")]
pub struct Novel {
    url: Url,
    path: PathBuf,
    backend: Backends,
    chapters: Vec<Chapter>,
}

impl Debug for Novel {
    #[allow(dead_code)]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        #[derive(Debug)]
        struct Novel<'a> {
            url: String,
            path: &'a PathBuf,
            backend: &'a Backends,
            chapters: &'a Vec<Chapter>,
        }
        let Self {
            url,
            path,
            backend,
            chapters,
        } = self;
        Debug::fmt(
            &Novel {
                url: url.to_string(),
                path,
                backend,
                chapters,
            },
            f,
        )
    }
}

impl Clone for Novel {
    fn clone(&self) -> Self {
        Self {
            url: self.url.clone(),
            path: self.path.clone(),
            backend: Backends::new(self.url.as_ref()).unwrap(),
            chapters: self.chapters.clone(),
        }
    }
}

/// An iterator over the update operation of a chapter. Used to be able to
/// monitor progress from your code.
///
/// ```rust
/// # use std::thread::sleep;
/// use std::time::Duration;
///
/// use libwebnovel_storage::{LibraryError, Novel};
/// use tempfile::tempdir;
/// use url::Url;
/// let path = "random/path";
/// # let dir = tempdir().unwrap();
/// # let path = dir.path();
/// let mut novel = Novel::new(
///     "https://www.royalroad.com/fiction/21220/mother-of-learning"
///         .parse::<Url>()
///         .unwrap(),
///     path,
/// )
/// .unwrap();
/// for (i, chapter_result) in novel.update_iter().enumerate() {
///     sleep(Duration::from_micros(500)); // throttleing requests
///     match chapter_result {
///         Ok(_) => {
///             println!(":) Chapter update succeded!")
///         }
///         Err(e) => {
///             println!(":'( chapter update failed: {e}")
///         }
///     }
/// }
/// assert_eq!(novel.get_local_chapter_count().unwrap(), 109);
/// ```
pub struct NovelChapterUpdateIter<'a> {
    novel: &'a mut Novel,
    missing_chapters: Vec<usize>,
    current_chapter_index: usize,
}
impl Debug for NovelChapterUpdateIter<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "NovelChapterUpdateIter {}/{}:\n  Chapter_Index={},\n  Novel={},\n  base_dir={}",
            self.current_chapter_index,
            self.missing_chapters.len(),
            if self.current_chapter_index >= self.missing_chapters.len() {
                "Out of bounds (may be normal if end of iter)".to_string()
            } else {
                self.missing_chapters[self.current_chapter_index].to_string()
            },
            self.novel.url,
            self.novel.path.display(),
        )
    }
}

impl<'a> Iterator for NovelChapterUpdateIter<'a> {
    type Item = Result<(), LibraryError>;

    fn next(&mut self) -> Option<Self::Item> {
        trace!("{:?}", self);
        if self.current_chapter_index >= self.missing_chapters.len() {
            return None;
        }
        let r = match self
            .novel
            .backend
            .get_chapter(self.missing_chapters[self.current_chapter_index])
        {
            Ok(v) => match Novel::persist_chapter(&self.novel.path, &v) {
                Ok(_) => {
                    self.novel.chapters.push(v);
                    Some(Ok(()))
                }
                Err(e) => Some(Err(e)),
            },
            Err(e) => Some(Err(LibraryError::from(e))),
        };
        self.current_chapter_index += 1;
        r
    }
}

impl Novel {
    /// Returns a new Novel from the given URL. Functionally equivalent to
    /// [`Novel::try_from(Url)`].
    pub fn new(url: impl Into<Url>, library_path: &Path) -> Result<Self, LibraryError> {
        let url = url.into();
        let mut novel = Self {
            url: url.clone(),
            path: Default::default(),
            backend: Backends::new(url.as_ref())?,
            chapters: vec![],
        };
        novel.path = library_path.join(novel.backend.immutable_identifier()?);
        Ok(novel)
    }

    /// Returns the url of the novel
    pub fn url(&self) -> &Url {
        &self.url
    }

    /// Returns the title of the novel
    pub fn title(&self) -> Result<String, LibraryError> {
        Ok(self.backend.title()?)
    }

    /// returns where all the chapters are stored. static alternative to
    /// [`self.chapter_storage_path()`].
    pub fn get_chapter_storage_path(novel_path: &Path) -> PathBuf {
        novel_path.join("chapters")
    }

    /// returns where the cover image is stored. static alternative to
    /// [`self.cover_storage_path`].
    pub fn get_cover_storage_path(novel_path: &Path) -> PathBuf {
        novel_path.join("cover.png")
    }

    /// Returns where all the chapters are stored. Alternative to the static
    /// [`Self::get_chapter_storage_path`].
    pub fn chapter_storage_path(&self) -> PathBuf {
        Self::get_chapter_storage_path(&self.path)
    }

    /// Returns where the cover image is stored. Alternative to the static
    /// [`Self::get_cover_storage_path`].
    pub fn cover_storage_path(&self) -> PathBuf {
        Self::get_cover_storage_path(&self.path)
    }

    fn persist_chapter(novel_path: &Path, chapter: &Chapter) -> Result<(), LibraryError> {
        let path = Self::get_chapter_storage_path(novel_path);
        if !path.exists() {
            create_dir_all(&path)?;
        }
        let chapter_file_name = match chapter.title() {
            None => {
                format!("{}.html", chapter.index())
            }
            Some(title) => {
                format!("{}-{}.html", chapter.index(), title)
            }
        };
        let chapter_path = path.join(chapter_file_name);
        let mut file = File::create(chapter_path)?;
        file.write_all(chapter.to_string().as_bytes())?;
        Ok(())
    }

    /// Downloads the cover file and places it in [`self.cover_image_path`],
    /// performing appropriate image format conversions if necessary.
    pub fn download_cover(&self) -> Result<(), LibraryError> {
        let cover_path = self.path.join("cover.png");
        if !cover_path.is_file() {
            if !self.path.exists() {
                create_dir_all(&self.path)?;
            } else if cover_path.is_dir() {
                warn!(
                    "{} is a directory! we will delete it in order to create the cover file",
                    cover_path.display()
                );
                // There's no sense it being a directory. let's delete this shit.
                fs::remove_dir_all(&cover_path)?;
            }
            let cover_data = self.backend.cover()?;
            let data = match image::guess_format(&cover_data) {
                Ok(format) => match format {
                    ImageFormat::Png => cover_data,
                    iformat => {
                        info!(
                            "Cover image is in {}. Converting to png.",
                            iformat.extensions_str()[0]
                        );
                        let cursor = Cursor::new(cover_data);
                        let img = image::load(cursor, iformat)?;
                        let mut buffer = Vec::new();
                        img.write_to(&mut Cursor::new(&mut buffer), ImageFormat::Png)?;
                        buffer
                    }
                },
                Err(e) => {
                    // Then, attempt to guess from the URL filename?
                    // for now, let's just return the data.
                    warn!("Error trying to guess image: {}", e);
                    cover_data
                }
            };
            let mut f = File::create(cover_path)?;
            f.write_all(&data)?;
        }
        Ok(())
    }

    /// Fetch remote chapters & saves them locally. Will attempt to fix
    /// duplicates, ordering, and detect collisions.
    pub fn update(&mut self) -> Result<(), LibraryError> {
        self.load_local_chapters()?;

        // TODO: check errors, not only print them. For instance, if the source is a
        //       http 429 or equivalent, it may be worthwhile to retry.
        let _errors = self
            .update_iter()
            .filter(Result::is_err)
            .map(|r| {
                let err = r.unwrap_err();
                warn!("{}", err);
                err
            })
            .collect::<Vec<_>>();
        self.consolidate_chapter_collection();
        // TODO: Check for remaining duplicates/index collisions
        // Write all chapters to disk
        for chapter in &self.chapters {
            Self::persist_chapter(&self.path, chapter)?;
        }
        Ok(())
    }

    /// Sorts, dedups and tries to fix chapter indexes in the current "live"
    /// chapter list.
    pub fn consolidate_chapter_collection(&mut self) {
        // …sort them…
        self.chapters.sort_by(self.backend.get_ordering_function());
        // … and remove duplicates. There should not be any.
        self.chapters.dedup();
        // update the indexes accordingly, as it may happen when some chapters have been
        // deleted from the source.
        for (i, chapter) in self.chapters.iter_mut().enumerate() {
            // enumerate is 0-indexed so we must add 1 :p
            let chapter_index = i + 1;
            if *chapter.index() != chapter_index {
                warn!("There could be a conflict in chapter {}: index was expected to be {} but was {}. Setting chapter index to expectation",
                    chapter.title().clone().unwrap_or("<title_not_found>".to_string()),
                    chapter_index,
                    chapter.index()
                );
                chapter.set_index(chapter_index);
            }
        }
    }

    /// Returns an iterator that will fetch the chapters, returning a Result for
    /// each operation. See [`NovelChapterUpdateIter::next`] for more info.
    /// Will not attempt to handle duplicates & other stuff.
    ///
    /// # Panics
    ///
    /// Panics when:
    /// - [`self.get_missing_chapters_indexes`] panics
    pub fn update_iter(&mut self) -> NovelChapterUpdateIter {
        let missing_chapters = self.get_missing_chapters_indexes().unwrap();
        debug!("Missing chapters: {:?}", missing_chapters);

        NovelChapterUpdateIter {
            novel: self,
            missing_chapters,
            current_chapter_index: 0,
        }
    }

    /// Returns chapter indexes that are present in the source but not locally.
    pub fn get_missing_chapters_indexes(&self) -> Result<Vec<usize>, LibraryError> {
        // Get the local chapters
        let local_chapters_tuples: Vec<(usize, String)> = self
            .get_local_chapters()?
            .iter()
            .map(|c| c.try_into().unwrap())
            .collect();
        debug!("local chapters: {:?}", local_chapters_tuples);
        // then get the list of chapters from the backend
        let available_chapters = self.backend.get_chapter_list()?;
        debug!("available chapters: {:?}", available_chapters);
        // Extract a list of all chapters present on the source but not locally
        Ok(available_chapters
            .iter()
            .filter(|c| {
                for lc in &local_chapters_tuples {
                    if c.0 == lc.0 {
                        // That means we have an index match, let's check the
                        // title match.
                        if c.1 == lc.1 {
                            // they are the same, no need to download this one.
                            return false;
                        }
                        // if we are here, it means we have the same index but
                        // the title differs. Tomfoolery is afoot.
                        warn!("distant chapter {:?} and local chapter {:?} have the same index but different titles! I won't download them.", c, lc);
                        return false;
                    }
                }
                // if they don't have the same index, consider them missing
                debug!("Will download chapter {}: {}", c.0, c.1);
                true
            })
            .map(|c| c.0)
            .collect::<Vec<_>>())
    }

    /// Returns the count of locally-saved chapters
    pub fn get_local_chapter_count(&self) -> Result<usize, LibraryError> {
        let path = self.chapter_storage_path();
        if !path.exists() {
            return Ok(0);
        }
        // count the number of chapters in self.novel_dir()
        Ok(fs::read_dir(path)?.count())
    }

    /// returns the total count of remote chapters
    pub fn get_remote_chapter_count(&self) -> Result<usize, LibraryError> {
        Ok(self.backend.get_chapter_count()?)
    }

    /// Loads local chapters and saves them in `self.chapters`. Overrides any
    /// currently loaded chapters.
    pub fn load_local_chapters(&mut self) -> Result<(), LibraryError> {
        self.chapters = self.get_local_chapters()?;
        Ok(())
    }

    /// Returns a vector of all local [`Chapter`].
    pub fn get_local_chapters(&self) -> Result<Vec<Chapter>, LibraryError> {
        if !self.path.exists() {
            return Ok(Vec::new());
        }
        let mut chapters: Vec<Chapter> = Vec::new();
        let chapter_files = fs::read_dir(&self.path)?;
        for chapter_file in chapter_files {
            let chapter_file = chapter_file?;
            let chapter_path = chapter_file.path();
            let mut file = File::open(&chapter_path)?;
            let mut content = String::new();
            file.read_to_string(&mut content)?;
            let chapter = content.parse()?;
            chapters.push(chapter);
        }
        Ok(chapters)
    }

    /// Returns the root path of where this novel stores its files.
    pub fn novel_path(&self) -> &Path {
        &self.path
    }
}

impl TryFrom<Url> for Novel {
    type Error = LibraryError;

    /// WARNING: returns an uninitialized Novel.path!
    fn try_from(value: Url) -> Result<Self, Self::Error> {
        let novel = Self {
            url: value.clone(),
            path: Default::default(),
            backend: Backends::new(value.as_str())?,
            chapters: vec![],
        };
        Ok(novel)
    }
}

impl TryFrom<NovelConfig> for Novel {
    type Error = LibraryError;

    fn try_from(value: NovelConfig) -> Result<Self, Self::Error> {
        Self::try_from(value.url)
    }
}

/// A type not destined to be used directly, but rather by serde.
#[derive(Serialize, Deserialize, Clone, Debug)]
struct NovelConfig {
    url: Url,
    path: PathBuf,
}

impl From<Novel> for NovelConfig {
    fn from(value: Novel) -> Self {
        Self {
            url: value.url,
            path: value.path,
        }
    }
}