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
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 transform;
pub mod unzip;
pub mod update;
pub mod zip;

use std::{collections::HashMap, path::Path, process, sync::Arc};

use clap::ValueEnum;
use fluent_templates::Loader;
use novel_api::Client;
use strum::AsRefStr;
use tokio::signal;
use tracing::warn;
use url::Url;

use crate::{LANG_ID, LOCALES};

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

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

#[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)
    }
}

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).unwrap()
}