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
pub mod bookshelf;
pub mod build;
pub mod check;
pub mod completions;
pub mod download;
pub mod info;
pub mod read;
pub mod real_cugan;
pub mod search;
pub mod sign;
pub mod template;
pub mod transform;
pub mod unzip;
pub mod update;
pub mod zip;

use std::{
    cmp,
    collections::HashMap,
    env,
    fs::{self, File},
    io,
    path::Path,
    process,
    sync::Arc,
};

use ::zip::ZipArchive;
use clap::ValueEnum;
use color_eyre::eyre::Result;
use fluent_templates::Loader;
use novel_api::Client;
use ratatui::{
    buffer::Buffer,
    layout::{Rect, Size},
    text::Text,
    widgets::{block::Title, Block, Paragraph, StatefulWidget, Widget, Wrap},
};
use strum::AsRefStr;
use tokio::signal;
use tracing::warn;
use tui_scrollview::{ScrollView, ScrollViewState};
use url::Url;

use crate::{utils, LANG_ID, LOCALES};

const DEFAULT_PROXY: &str = "http://127.0.0.1:8080";

const DEFAULT_PROXY_SURGE: &str = "http://127.0.0.1:6152";

#[must_use]
#[derive(Clone, PartialEq, ValueEnum, AsRefStr)]
pub enum Source {
    #[strum(serialize = "sfacg")]
    Sfacg,
    #[strum(serialize = "ciweimao")]
    Ciweimao,
    #[strum(serialize = "ciyuanji")]
    Ciyuanji,
}

#[must_use]
#[derive(Clone, PartialEq, ValueEnum, AsRefStr)]
pub enum Format {
    Pandoc,
    Mdbook,
}

#[must_use]
#[derive(Clone, PartialEq, ValueEnum, AsRefStr)]
pub enum Convert {
    S2T,
    T2S,
    JP2T2S,
    CUSTOM,
}

#[inline]
#[must_use]
fn default_cert_path() -> String {
    novel_api::home_dir_path()
        .unwrap()
        .join(".mitmproxy")
        .join("mitmproxy-ca-cert.pem")
        .display()
        .to_string()
}

fn set_options<T, E>(client: &mut T, proxy: &Option<Url>, no_proxy: &bool, cert: &Option<E>)
where
    T: Client,
    E: AsRef<Path>,
{
    if let Some(proxy) = proxy {
        client.proxy(proxy.clone());
    }

    if *no_proxy {
        client.no_proxy();
    }

    if let Some(cert) = cert {
        client.cert(cert.as_ref().to_path_buf())
    }
}

fn handle_ctrl_c<T>(client: &Arc<T>)
where
    T: Client + Send + Sync + 'static,
{
    let client = Arc::clone(client);

    tokio::spawn(async move {
        signal::ctrl_c().await.unwrap();

        warn!("Download terminated, login data will be saved");

        client.shutdown().await.unwrap();
        process::exit(128 + libc::SIGINT);
    });
}

fn cert_help_msg() -> String {
    let args = {
        let mut map = HashMap::new();
        map.insert(String::from("cert_path"), default_cert_path().into());
        map
    };

    LOCALES.lookup_with_args(&LANG_ID, "cert", &args)
}

#[derive(Default, PartialEq)]
enum Mode {
    #[default]
    Running,
    Quit,
}

pub struct ScrollableParagraph<'a> {
    title: Option<Title<'a>>,
    text: Text<'a>,
}

impl<'a> ScrollableParagraph<'a> {
    pub fn new<T>(text: T) -> Self
    where
        T: Into<Text<'a>>,
    {
        ScrollableParagraph {
            title: None,
            text: text.into(),
        }
    }

    pub fn title<T>(self, title: T) -> Self
    where
        T: Into<Title<'a>>,
    {
        ScrollableParagraph {
            title: Some(title.into()),
            ..self
        }
    }
}

impl<'a> StatefulWidget for ScrollableParagraph<'a> {
    type State = ScrollViewState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        let mut block = Block::bordered();
        if self.title.is_some() {
            block = block.title(self.title.as_ref().unwrap().clone());
        }

        let paragraph = Paragraph::new(self.text.clone()).wrap(Wrap { trim: false });
        let mut scroll_view = ScrollView::new(Size::new(area.width - 1, area.height));
        let mut block_area = block.inner(scroll_view.buf().area);

        let scroll_height = cmp::max(
            paragraph.line_count(block_area.width) as u16
                + (scroll_view.buf().area.height - block_area.height),
            area.height,
        );

        let scroll_width = if area.height >= scroll_height {
            // 不需要滚动条
            area.width
        } else {
            area.width - 1
        };

        scroll_view = ScrollView::new(Size::new(scroll_width, scroll_height));

        let scroll_view_buf = scroll_view.buf_mut();
        block_area = block.inner(scroll_view_buf.area);

        Widget::render(block, scroll_view_buf.area, scroll_view_buf);
        Widget::render(paragraph, block_area, scroll_view_buf);
        StatefulWidget::render(scroll_view, area, buf, state);
    }
}

fn unzip<T>(path: T) -> Result<()>
where
    T: AsRef<Path>,
{
    let path = path.as_ref();

    let output_dir = env::current_dir()?.join(path.file_stem().unwrap());
    if output_dir.try_exists()? {
        warn!("The epub output directory already exists and will be deleted");
        utils::remove_file_or_dir(&output_dir)?;
    }

    let file = File::open(path)?;
    let mut archive = ZipArchive::new(file)?;

    for i in 0..archive.len() {
        let mut file = archive.by_index(i)?;
        let outpath = match file.enclosed_name() {
            Some(path) => path.to_owned(),
            None => continue,
        };
        let outpath = output_dir.join(outpath);

        if (*file.name()).ends_with('/') {
            fs::create_dir_all(&outpath)?;
        } else {
            if let Some(p) = outpath.parent() {
                if !p.try_exists()? {
                    fs::create_dir_all(p)?;
                }
            }
            let mut outfile = fs::File::create(&outpath)?;
            io::copy(&mut file, &mut outfile)?;
        }

        #[cfg(unix)]
        {
            use std::{fs::Permissions, os::unix::fs::PermissionsExt};

            if let Some(mode) = file.unix_mode() {
                fs::set_permissions(&outpath, Permissions::from_mode(mode))?;
            }
        }
    }

    Ok(())
}