eureka_manager_cli/commands/
transfer.rs

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
use std::{fs::File, io::BufReader, path::PathBuf, str::FromStr};

use actix::Actor;
use clap::Args;
use eureka_mmanager::{
    download::chapter::task::DownloadMode,
    prelude::{
        ChapterDataPullAsyncTrait, ChapterImagePushEntry, CoverDataPullAsyncTrait, DirsOptions,
        DirsOptionsCore, GetManagerStateData, MangaDataPullAsyncTrait, PushActorAddr,
    },
};
use log::info;
use mangadex_api_types_rust::RelationshipType;
use tokio_stream::StreamExt;
use uuid::Uuid;

use crate::DirsOptionsArgs;

use super::AsyncRun;

#[derive(Debug, Args)]
pub struct TransferCommand {
    /// directory targets for data to transfer in
    #[command(flatten)]
    pub transfer_dirs: DirsOptionsArgs,
    #[command(flatten)]
    pub mangas: TransferMangaArgs,
    #[command(flatten)]
    pub covers: TransferCoverArgs,
    #[command(flatten)]
    pub chapters: TransferChapterArgs,
    #[arg(long)]
    pub verify: bool,
}

#[derive(Debug, Args)]
pub struct TransferMangaArgs {
    #[arg(long)]
    pub manga: Vec<Uuid>,
    #[arg(long)]
    pub manga_ids_text_file: Vec<PathBuf>,
}

impl TransferMangaArgs {
    pub fn get_ids(&self) -> Vec<Uuid> {
        let mut ids = self.manga.clone();
        self.manga_ids_text_file
            .iter()
            .map(|e| (e, File::open(e)))
            .flat_map(|(path, res)| match res {
                Ok(file) => Some(id_list_txt_reader::IdListTxtReader::new(BufReader::new(
                    file,
                ))),
                Err(err) => {
                    log::error!("Cannot open the {} file: {}", path.to_string_lossy(), err);
                    None
                }
            })
            .flat_map(|file| file.flat_map(|s| Uuid::from_str(&s)))
            .for_each(|id| {
                ids.push(id);
            });
        ids.dedup();
        ids
    }
}

#[derive(Debug, Args)]
pub struct TransferCoverArgs {
    #[arg(long)]
    pub cover: Vec<Uuid>,
    #[arg(long)]
    pub cover_ids_text_file: Vec<PathBuf>,
}

impl TransferCoverArgs {
    pub fn get_ids(&self) -> Vec<Uuid> {
        let mut ids = self.cover.clone();
        self.cover_ids_text_file
            .iter()
            .map(|e| (e, File::open(e)))
            .flat_map(|(path, res)| match res {
                Ok(file) => Some(id_list_txt_reader::IdListTxtReader::new(BufReader::new(
                    file,
                ))),
                Err(err) => {
                    log::error!("Cannot open the {} file: {}", path.to_string_lossy(), err);
                    None
                }
            })
            .flat_map(|file| file.flat_map(|s| Uuid::from_str(&s)))
            .for_each(|id| {
                ids.push(id);
            });
        ids.dedup();
        ids
    }
}

#[derive(Debug, Args)]
pub struct TransferChapterArgs {
    #[arg(long)]
    pub chapter: Vec<Uuid>,
    #[arg(long)]
    pub chapter_ids_text_file: Vec<PathBuf>,
}

impl TransferChapterArgs {
    pub fn get_ids(&self) -> Vec<Uuid> {
        let mut ids = self.chapter.clone();
        self.chapter_ids_text_file
            .iter()
            .map(|e| (e, File::open(e)))
            .flat_map(|(path, res)| match res {
                Ok(file) => Some(id_list_txt_reader::IdListTxtReader::new(BufReader::new(
                    file,
                ))),
                Err(err) => {
                    log::error!("Cannot open the {} file: {}", path.to_string_lossy(), err);
                    None
                }
            })
            .flat_map(|file| file.flat_map(|s| Uuid::from_str(&s)))
            .for_each(|id| {
                ids.push(id);
            });
        ids.dedup();
        ids
    }
}

impl AsyncRun for TransferCommand {
    async fn run(
        &self,
        manager: actix::Addr<eureka_mmanager::DownloadManager>,
    ) -> anyhow::Result<()> {
        let mut chapters = self.chapters.get_ids();
        let mut mangas = self.mangas.get_ids();
        let mut covers = self.covers.get_ids();

        let target_opts = {
            let opts: DirsOptionsCore = self.transfer_dirs.clone().into();
            let opts: DirsOptions = opts.into();
            opts.start()
        };

        let current_opts = manager.get_dir_options().await?;
        chapters.dedup();
        let mut chapter_stream = current_opts
            .get_chapters_by_ids(chapters.into_iter())
            .await?;
        // Chapter push
        while let Some(chapter) = StreamExt::next(&mut chapter_stream).await {
            let id = chapter.id;
            let images = current_opts.get_chapter_images(id).await?;
            let images = {
                let mut entries: Vec<ChapterImagePushEntry<BufReader<File>>> = Vec::new();
                for data_entry_filename in images.data.iter() {
                    let entry = ChapterImagePushEntry::new(
                        chapter.id,
                        data_entry_filename.clone(),
                        BufReader::new(
                            current_opts
                                .get_chapter_image(chapter.id, data_entry_filename.clone())
                                .await?,
                        ),
                    )
                    .mode(DownloadMode::Normal);
                    entries.push(entry);
                }
                for data_saver_entry_filename in images.data_saver.iter() {
                    let entry = ChapterImagePushEntry::new(
                        chapter.id,
                        data_saver_entry_filename.clone(),
                        BufReader::new(
                            current_opts
                                .get_chapter_image_data_saver(
                                    chapter.id,
                                    data_saver_entry_filename.clone(),
                                )
                                .await?,
                        ),
                    )
                    .mode(DownloadMode::DataSaver);
                    entries.push(entry);
                }
                entries
            };
            info!("Transfering {} chapter...", id);
            let manga = chapter
                .find_first_relationships(RelationshipType::Manga)
                .cloned();

            if self.verify {
                target_opts.verify_and_push(chapter).await?;
                target_opts.verify_and_push(images).await?;
            } else {
                target_opts.push(chapter).await?;
                target_opts.push(images).await?;
            }

            info!("Transfered {} chapter!", id);
            if let Some(manga) = manga {
                if mangas.contains(&manga.id) {
                    mangas.push(manga.id);
                }
            }
        }

        mangas.dedup();
        let mut mangas_stream = current_opts
            .get_manga_list_by_ids(mangas.into_iter())
            .await?;
        while let Some(manga) = StreamExt::next(&mut mangas_stream).await {
            let id = manga.id;
            if let Some(cover) = manga
                .find_first_relationships(RelationshipType::CoverArt)
                .cloned()
            {
                covers.push(cover.id);
            }
            info!("Transfering {} title...", id);
            if self.verify {
                target_opts.verify_and_push(manga).await?;
            } else {
                target_opts.push(manga).await?;
            }
            info!("Transfered {} title!", id);
        }

        covers.dedup();
        let mut cover_stream = current_opts.get_covers_by_ids(covers.into_iter()).await?;
        while let Some(cover) = StreamExt::next(&mut cover_stream).await {
            let id = cover.id;
            info!("Transfering {} cover...", id);
            let image = current_opts.get_cover_image(cover.id).await?;
            if self.verify {
                target_opts
                    .verify_and_push((cover, BufReader::new(image)))
                    .await?;
            } else {
                target_opts.push((cover, BufReader::new(image))).await?;
            }
            info!("Transfered {} cover!", id);
        }
        Ok(())
    }
}