|
| 1 | +use std::fs; |
| 2 | +use std::path::Path; |
| 3 | + |
| 4 | +use argh::FromArgs; |
| 5 | +use futures::future::try_join_all; |
| 6 | +use regex::Regex; |
| 7 | +use select::document::Document; |
| 8 | +use select::node::Node; |
| 9 | +use select::predicate::{Class, Name}; |
| 10 | +use serde::ser::SerializeTuple; |
| 11 | +use serde::{Serialize, Serializer}; |
| 12 | +use tokio::runtime::Runtime; |
| 13 | + |
| 14 | +use crate::minify::Minifier; |
| 15 | +use crate::tasks::Task; |
| 16 | + |
| 17 | +const BOOKS_INDEX_PATH: &str = "../lib/index/books.js"; |
| 18 | +const COMMANDS: &str = include_str!("../../../lib/index/commands.js"); |
| 19 | + |
| 20 | +/// Books task |
| 21 | +#[derive(FromArgs)] |
| 22 | +#[argh(subcommand, name = "books")] |
| 23 | +pub struct BooksTask { |
| 24 | + /// destination path |
| 25 | + #[argh(option, short = 'd', default = "BOOKS_INDEX_PATH.to_string()")] |
| 26 | + dest_path: String, |
| 27 | +} |
| 28 | + |
| 29 | +#[derive(Debug)] |
| 30 | +struct Page { |
| 31 | + title: String, |
| 32 | + path: String, |
| 33 | + parent_titles: Option<Vec<String>>, |
| 34 | +} |
| 35 | + |
| 36 | +#[derive(Serialize, Debug, Default)] |
| 37 | +struct Book<'a> { |
| 38 | + name: &'a str, |
| 39 | + url: &'a str, |
| 40 | + #[serde(skip_deserializing)] |
| 41 | + pages: Vec<Page>, |
| 42 | +} |
| 43 | + |
| 44 | +impl<'a> Book<'a> { |
| 45 | + fn is_empty(&self) -> bool { |
| 46 | + self.name.is_empty() || self.url.is_empty() |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +impl Page { |
| 51 | + #[inline] |
| 52 | + fn parse(node: &Node) -> Option<Page> { |
| 53 | + if let Some(a) = node.first_child().filter(|n| n.is(Name("a"))) { |
| 54 | + let title = a.text(); |
| 55 | + let path = a |
| 56 | + .attr("href") |
| 57 | + .unwrap() |
| 58 | + .trim_end_matches(".html") |
| 59 | + .to_string(); |
| 60 | + |
| 61 | + Some(Page { |
| 62 | + title, |
| 63 | + path, |
| 64 | + parent_titles: None, |
| 65 | + }) |
| 66 | + } else { |
| 67 | + None |
| 68 | + } |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +impl Serialize for Page { |
| 73 | + #[inline] |
| 74 | + fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> |
| 75 | + where |
| 76 | + S: Serializer, |
| 77 | + { |
| 78 | + let mut ser = serializer.serialize_tuple(3)?; |
| 79 | + ser.serialize_element(&self.title)?; |
| 80 | + ser.serialize_element(&self.path)?; |
| 81 | + ser.serialize_element(&self.parent_titles)?; |
| 82 | + ser.end() |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +#[inline] |
| 87 | +fn parse_node(node: &Node, parent_titles: Option<Vec<String>>) -> Vec<Page> { |
| 88 | + let mut pages = vec![]; |
| 89 | + for child in node.children() { |
| 90 | + if child.is(Class("expanded")) || child.first_child().filter(|n| n.is(Name("a"))).is_some() |
| 91 | + { |
| 92 | + if let Some(mut page) = Page::parse(&child) { |
| 93 | + page.parent_titles = parent_titles.clone(); |
| 94 | + pages.push(page); |
| 95 | + } |
| 96 | + } else { |
| 97 | + let mut new_parent_titles = parent_titles.clone().unwrap_or_default(); |
| 98 | + if let Some(page) = child.prev().and_then(|n| Page::parse(&n)) { |
| 99 | + new_parent_titles.push(page.title); |
| 100 | + if let Some(section) = child.find(Class("section")).next() { |
| 101 | + pages.extend(parse_node(§ion, Some(new_parent_titles))) |
| 102 | + } |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + pages |
| 107 | +} |
| 108 | + |
| 109 | +async fn fetch_book(mut book: Book<'_>) -> crate::Result<Book<'_>> { |
| 110 | + let html = reqwest::get(book.url).await?.text().await?; |
| 111 | + let doc = Document::from(html.as_str()); |
| 112 | + if let Some(node) = doc.find(Class("chapter")).next() { |
| 113 | + book.pages = parse_node(&node, None); |
| 114 | + Ok(book) |
| 115 | + } else { |
| 116 | + println!("Parse failed, book `{}` is ignored.", book.name); |
| 117 | + Ok(Book::default()) |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +impl Task for BooksTask { |
| 122 | + fn execute(&self) -> crate::Result<()> { |
| 123 | + let rt = Runtime::new()?; |
| 124 | + rt.block_on(self.run())?; |
| 125 | + Ok(()) |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +impl BooksTask { |
| 130 | + async fn run(&self) -> crate::Result<()> { |
| 131 | + let re = Regex::new(r#"^\["(.*)",\s?"(.*)"\]"#).unwrap(); |
| 132 | + let mut books = vec![]; |
| 133 | + let mut started = false; |
| 134 | + for line in COMMANDS.lines() { |
| 135 | + if line.trim().starts_with("\"book\"") { |
| 136 | + started = true; |
| 137 | + } else if line.trim().starts_with("\"book/zh\"") { |
| 138 | + break; |
| 139 | + } |
| 140 | + |
| 141 | + if started { |
| 142 | + if let Some(capture) = re.captures(line.trim()) { |
| 143 | + let book = Book { |
| 144 | + name: capture.get(1).unwrap().as_str(), |
| 145 | + url: capture.get(2).unwrap().as_str(), |
| 146 | + pages: Vec::default(), |
| 147 | + }; |
| 148 | + books.push(book); |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | + println!("{:?}", books); |
| 153 | + let futures: Vec<_> = books.into_iter().map(fetch_book).collect(); |
| 154 | + match try_join_all(futures).await { |
| 155 | + Ok(result) => { |
| 156 | + let books: Vec<_> = result.into_iter().filter(|book| !book.is_empty()).collect(); |
| 157 | + let contents = format!( |
| 158 | + "var N=null;const booksIndex={};export default booksIndex;", |
| 159 | + serde_json::to_string(&books)? |
| 160 | + ); |
| 161 | + let path = Path::new(&self.dest_path); |
| 162 | + fs::write(path, Minifier::minify_js(&contents)).unwrap(); |
| 163 | + } |
| 164 | + Err(error) => { |
| 165 | + println!("{:?}", error); |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + Ok(()) |
| 170 | + } |
| 171 | +} |
0 commit comments