cbz 1.0.2

Provide `cbz`, `cbt`, `cb7` reader and writers
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
use std::{
    fs::File,
    io::{BufWriter, Cursor, Seek, Write},
    num::NonZeroUsize,
    path::Path,
};

use image::ImageFormat;
use sevenz_rust2::{ArchiveEntry, ArchiveWriter};

#[cfg(feature = "comicinfo")]
use crate::comicinfo::{
    COMIC_INFO_XML, ComicInfoBuilder, ComicInfoBuilderError,
    comic_page_info::{ComicPageInfoBuilder, ComicPageInfoBuilderError},
};

use crate::write::ComicBookWriter;

#[derive(Debug, thiserror::Error)]
#[error(transparent)]
#[non_exhaustive]
pub enum Cb7WriterError {
    Image(#[from] image::ImageError),
    Io(#[from] std::io::Error),
    #[error("the inner 7z inner writer was dropped early")]
    S7WriterInnerDroppedEarly,
    S7(#[from] sevenz_rust2::Error),
    #[cfg(feature = "comicinfo")]
    #[cfg_attr(docsrs, doc(feature = "comicinfo"))]
    SerdeXml(#[from] serde_xml_rs::Error),
    #[cfg(feature = "comicinfo")]
    #[cfg_attr(docsrs, doc(feature = "comicinfo"))]
    ComicInfoBuilder(#[from] ComicInfoBuilderError),
    #[cfg(feature = "comicinfo")]
    #[cfg_attr(docsrs, doc(feature = "comicinfo"))]
    ComicPageInfoBuilder(#[from] ComicPageInfoBuilderError),
    IntCast(#[from] std::num::TryFromIntError),
    #[error("cannot transform a `Path` into a `&str`")]
    PathToStr,
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Cb7WriterImageFormat {
    #[default]
    Png,
    Jpeg,
    // TODO Avif
    // TODO Webp
}

impl From<Cb7WriterImageFormat> for image::ImageFormat {
    fn from(value: Cb7WriterImageFormat) -> Self {
        match value {
            Cb7WriterImageFormat::Jpeg => Self::Jpeg,
            Cb7WriterImageFormat::Png => Self::Png,
        }
    }
}

/// A generic cb7 writer
///
/// Please look up to [`ComicBookWriter`] if you want more information on how to add pages.
///
/// Mostly a wrapper around [`sevenz_rust2::ArchiveWriter`]
///
#[derive(derive_more::Debug)]
pub struct Cb7Writer<W>
where
    W: Write + Seek,
{
    s7_inner: Option<ArchiveWriter<W>>,
    count: usize,
    suffix: Option<String>,
    width: usize,
    images_format: Cb7WriterImageFormat,
    #[cfg(feature = "comicinfo")]
    comicinfo_builder: Option<ComicInfoBuilder>,
    #[cfg(feature = "comicinfo")]
    auto_double_page: bool,
}

impl<W> Cb7Writer<W>
where
    W: Write + Seek,
{
    /// Make a new CbzWriter from a writer.
    pub fn new(writer: W) -> Result<Self, sevenz_rust2::Error> {
        Ok(Self::from_archive_writer(ArchiveWriter::new(writer)?))
    }
    /// Create a `Cb7Writer` from an [`ArchiveWriter`]
    pub fn from_archive_writer(writer: ArchiveWriter<W>) -> Self {
        Self {
            s7_inner: Some(writer),
            count: 1,
            suffix: None,
            width: 4,
            images_format: Default::default(),
            #[cfg(feature = "comicinfo")]
            comicinfo_builder: None,
            #[cfg(feature = "comicinfo")]
            auto_double_page: true,
        }
    }
    /// Add a suffix to the page name.
    ///
    /// Please call this before adding any images to archive or your image archive "nomenclature" will break/.
    pub fn suffix(mut self, suffix: String) -> Self {
        self.suffix = Some(suffix);
        self
    }
    /// Remove suffixes.
    ///
    /// Please call this before adding any images to archive or your image archive "nomenclature" will break/.
    pub fn no_suffix(mut self) -> Self {
        let _ = self.suffix.take();
        self
    }
    /// Set the number width for the page name
    /// *aka the number length*.
    ///
    /// Default: __4__
    pub fn width(mut self, width: NonZeroUsize) -> Self {
        self.width = width.into();
        self
    }
    fn s7_inner_(&mut self) -> Result<&mut ArchiveWriter<W>, Cb7WriterError> {
        self.s7_inner
            .as_mut()
            .ok_or(Cb7WriterError::S7WriterInnerDroppedEarly)
    }
    /// Automatically set [`ComicPageInfo::double_page`] value on [`<Pages/>`](ComicInfo::pages).
    ///
    /// If this is enabled (which it is), every pages where its [`width`](image::DynamicImage::width) is bigger than its [`height`](image::DynamicImage::height) are set to `true`.
    #[cfg(feature = "comicinfo")]
    #[cfg_attr(docsrs, doc(feature = "comicinfo"))]
    pub fn auto_double_page(mut self, auto_double_page: bool) -> Self {
        self.auto_double_page = auto_double_page;
        self
    }
    /// Finish the actual 7z archive.
    ///
    /// Normally, the writer should auto finish on drop, but i recommend using this instead.
    ///
    /// It just call [`sevenz_rust2::ArchiveWriter::finish`].
    pub fn finish(mut self) -> Result<W, Cb7WriterError> {
        #[cfg(feature = "comicinfo")]
        {
            self.write_comicinfo()?;
        }
        let write = self
            .s7_inner
            .take()
            .ok_or(Cb7WriterError::S7WriterInnerDroppedEarly)?
            .finish()?;
        Ok(write)
    }
    #[cfg(feature = "comicinfo")]
    fn write_comicinfo(&mut self) -> Result<(), Cb7WriterError> {
        if let Some(comicinfo) = self.comicinfo_builder.take() {
            let mut buf = tempfile::spooled_tempfile(1024);
            serde_xml_rs::to_writer(&mut buf, &comicinfo.build()?)?;
            buf.rewind()?;
            self.add_file(COMIC_INFO_XML, buf)?;
        } else {
            #[cfg(feature = "log")]
            {
                log::warn!("no comic info found... moving on");
            }
        }
        Ok(())
    }
    /// Set a comicbook builder for this writer.
    ///
    /// It is worth noting that the `ComicInfo.xml` file coming out of this builder will be written
    ///
    #[cfg(feature = "comicinfo")]
    #[cfg_attr(docsrs, doc(feature = "comicinfo"))]
    pub fn set_comicinfo_builder(mut self, builder: ComicInfoBuilder) -> Self {
        self.comicinfo_builder = Some(builder);
        self
    }
    /// [Take](Option::take) the internal [comicinfo builder](ComicInfoBuilder)
    #[cfg(feature = "comicinfo")]
    #[cfg_attr(docsrs, doc(feature = "comicinfo"))]
    pub fn take_comicinfo_builder(&mut self) -> Option<ComicInfoBuilder> {
        self.comicinfo_builder.take()
    }
    /// Remove the internal [comicinfo builder](ComicInfoBuilder)
    ///
    /// If you want to take the builder, use [`Self::take_comicinfo_builder`];
    #[cfg(feature = "comicinfo")]
    #[cfg_attr(docsrs, doc(feature = "comicinfo"))]
    pub fn unset_comicinfo_builder(mut self) -> Self {
        let _ = self.take_comicinfo_builder();
        self
    }
    /// Get the current comicinfo builder
    #[cfg(feature = "comicinfo")]
    #[cfg_attr(docsrs, doc(feature = "comicinfo"))]
    pub fn get_comicinfo_builder(&mut self) -> Option<&ComicInfoBuilder> {
        self.comicinfo_builder.as_ref()
    }
    #[cfg(feature = "comicinfo")]
    fn get_current_page_info_builder(&self) -> ComicPageInfoBuilder {
        let mut builder = ComicPageInfoBuilder::default();
        builder.image(self.count);
        builder
    }
    fn inner_add_image(&mut self, add_page: AddPage) -> Result<(), Cb7WriterError> {
        let (mut img_buf, filename): (Cursor<Vec<u8>>, String) = {
            let width = self.width;
            let mut buf = Cursor::new(Vec::<u8>::new());
            let name = if matches!(add_page._format, Some(ImageFormat::Gif)) {
                add_page.image.write_to(&mut buf, ImageFormat::Gif)?;
                format!(
                    "{}{:0>width$}.gif",
                    self.suffix.as_deref().unwrap_or(""),
                    self.count
                )
            } else {
                add_page
                    .image
                    .write_to(&mut buf, self.images_format.into())?;
                format!(
                    "{}{:0>width$}.{}",
                    self.suffix.as_deref().unwrap_or(""),
                    self.count,
                    match self.images_format {
                        Cb7WriterImageFormat::Jpeg => "jpg",
                        Cb7WriterImageFormat::Png => "png",
                    }
                )
            };
            (buf, name)
        };
        img_buf.rewind()?;
        {
            let entry = ArchiveEntry::new_file(&filename);
            self.s7_inner_()?.push_archive_entry(entry, Some(img_buf))?;
        }

        #[cfg(feature = "comicinfo")]
        {
            if self.comicinfo_builder.is_some() {
                let mut page_builder = self.get_current_page_info_builder();
                page_builder
                    .image(self.count)
                    .image_height(NonZeroUsize::new(add_page.image.height().try_into()?))
                    .image_width(NonZeroUsize::new(add_page.image.width().try_into()?));
                if self.auto_double_page {
                    page_builder.double_page(add_page.image.width() > add_page.image.height());
                }
                if let Some(bookmark) = add_page._bookmark {
                    page_builder.bookmark(bookmark);
                }
                if !add_page._page_type.is_empty() {
                    page_builder.type_(add_page._page_type);
                }
                if let Some(builder) = self.comicinfo_builder.as_mut() {
                    builder.add_page(page_builder.build()?);
                }
            }
        }

        self.count += 1;
        Ok(())
    }
}

impl Cb7Writer<BufWriter<File>> {
    /// Create a file cb7 from a file.
    pub fn create<P: AsRef<Path>>(path: P) -> Result<Self, sevenz_rust2::Error> {
        Self::new(BufWriter::new(File::create(path)?))
    }
}

impl<W> Drop for Cb7Writer<W>
where
    W: Write + Seek,
{
    fn drop(&mut self) {
        #[cfg(feature = "comicinfo")]
        {
            let _a = self.write_comicinfo();
            #[cfg(feature = "log")]
            {
                let _ = _a.inspect_err(|err| {
                    log::error!("cannot write the `ComicInfo.xml` on drop : [{}]", err);
                });
            }
        }
        if let Some(inner) = self.s7_inner.take() {
            let _res = inner.finish();
            #[cfg(feature = "log")]
            {
                let _ = _res.inspect_err(|err| {
                    log::error!("cannot finish 7z writer [{}]", err);
                });
            }
        }
    }
}

struct AddPage {
    image: image::DynamicImage,
    _format: Option<image::ImageFormat>,
    #[cfg(feature = "comicinfo")]
    _page_type: Vec<crate::comicinfo::comic_page_type::ComicPageType>,
    #[cfg(feature = "comicinfo")]
    _bookmark: Option<String>,
}

impl<W> ComicBookWriter for Cb7Writer<W>
where
    W: Write + Seek,
{
    type Error = Cb7WriterError;
    fn add_page(
        &mut self,
        image: image::DynamicImage,
        format: Option<image::ImageFormat>,
    ) -> Result<(), Self::Error> {
        self.inner_add_image(AddPage {
            image,
            _format: format,
            #[cfg(feature = "comicinfo")]
            _page_type: Vec::new(),
            #[cfg(feature = "comicinfo")]
            _bookmark: None,
        })
    }
    #[cfg(feature = "comicinfo")]
    #[cfg_attr(docsrs, doc(feature = "comicinfo"))]
    fn add_page_with_metadata(
        &mut self,
        image: image::DynamicImage,
        _format: Option<image::ImageFormat>,
        _page_type: Vec<crate::comicinfo::comic_page_type::ComicPageType>,
        _bookmark: Option<String>,
    ) -> Result<(), Self::Error> {
        self.inner_add_image(AddPage {
            image,
            _format,
            #[cfg(feature = "comicinfo")]
            _page_type,
            #[cfg(feature = "comicinfo")]
            _bookmark,
        })
    }
    fn add_file<P, R>(&mut self, path: P, file: R) -> Result<(), Self::Error>
    where
        P: AsRef<std::path::Path>,
        R: std::io::Read,
    {
        let header =
            ArchiveEntry::new_file(path.as_ref().to_str().ok_or(Cb7WriterError::PathToStr)?);
        self.s7_inner_()?.push_archive_entry(header, Some(file))?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::{
        fs::read_dir,
        io::{self, BufReader, BufWriter, Seek, Write},
        num::NonZero,
        path::Path,
    };

    use crate::{
        read::{ComicBookReader, cb7::Cb7Reader},
        write::ComicBookWriter,
    };

    #[test]
    fn test_write() -> anyhow::Result<()> {
        let to_import = read_dir("test-data/images/no-order")?.collect::<io::Result<Vec<_>>>()?;

        let mut file_to_use = tempfile::tempfile()?;

        {
            let mut writer = Cb7Writer::new(BufWriter::new(&mut file_to_use))?
                .width(NonZero::new(4).ok_or(anyhow::anyhow!("Unreachable"))?);
            for img in &to_import {
                writer.add_page(
                    image::open(img.path())?,
                    image::ImageFormat::from_path(img.path()).ok(),
                )?;
            }
            writer.finish()?.flush()?;
        }

        file_to_use.rewind()?;

        {
            let reader = Cb7Reader::new(BufReader::new(&mut file_to_use))?;
            let images = reader.pages();
            assert_eq!(images.len(), to_import.len());
            for (index, image) in images.into_iter().enumerate() {
                assert_eq!(
                    format!("{:0>4}", index + 1).as_str(),
                    Path::new(&image)
                        .file_prefix()
                        .and_then(|d| d.to_str())
                        .ok_or(anyhow::anyhow!("No filename"))?
                );
            }
        }

        Ok(())
    }
    #[cfg(feature = "comicinfo")]
    #[test]
    fn test_with_comic_info() -> anyhow::Result<()> {
        let to_import = read_dir("test-data/images/no-order")?.collect::<io::Result<Vec<_>>>()?;

        let mut file_to_use = tempfile::tempfile()?;

        let writed_comic_info = {
            use fake::{Fake, faker};

            use crate::comicinfo::ComicInfoBuilder;

            let mut writer = Cb7Writer::new(BufWriter::new(&mut file_to_use))?
                .set_comicinfo_builder({
                    let mut builer = ComicInfoBuilder::default();
                    builer
                        .title(faker::name::ja_jp::Title().fake())
                        .summary(faker::lorem::en::Paragraph(1..3).fake())
                        .series(faker::name::ja_jp::NameWithTitle().fake())
                        .writer(faker::name::ja_jp::Name().fake())
                        .colorist(faker::name::ja_jp::Name().fake())
                        .translator(faker::name::en::Name().fake())
                        .language_iso("en".into());
                    builer
                })
                .width(NonZero::new(4).ok_or(anyhow::anyhow!("Unreachable"))?);
            for img in &to_import {
                writer.add_page(
                    image::open(img.path())?,
                    image::ImageFormat::from_path(img.path()).ok(),
                )?;
            }
            let comic_info = writer.get_comicinfo_builder().cloned().unwrap().build()?;
            writer.finish()?.flush()?;
            comic_info
        };

        file_to_use.rewind()?;

        {
            use crate::read::comicinfo::GetComicInfo;

            let mut reader = Cb7Reader::new(BufReader::new(&mut file_to_use))?;
            let images = reader.pages();
            assert_eq!(images.len(), to_import.len());
            for (index, image) in images.into_iter().enumerate() {
                assert_eq!(
                    format!("{:0>4}", index + 1).as_str(),
                    Path::new(&image)
                        .file_prefix()
                        .and_then(|d| d.to_str())
                        .ok_or(anyhow::anyhow!("No filename"))?
                );
            }
            assert_eq!(reader.get_comic_info()?, writed_comic_info);
        }

        Ok(())
    }
}