You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mod.rs 20KB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. use std::collections::HashMap;
  2. use std::path::PathBuf;
  3. use std::sync::{Arc, Mutex, RwLock};
  4. use tera::{from_value, to_value, Error, Function as TeraFn, Result, Value};
  5. use config::Config;
  6. use image;
  7. use image::GenericImageView;
  8. use library::{Library, Taxonomy};
  9. use utils::site::resolve_internal_link;
  10. use imageproc;
  11. #[macro_use]
  12. mod macros;
  13. mod load_data;
  14. pub use self::load_data::LoadData;
  15. #[derive(Debug)]
  16. pub struct Trans {
  17. config: Config,
  18. }
  19. impl Trans {
  20. pub fn new(config: Config) -> Self {
  21. Self { config }
  22. }
  23. }
  24. impl TeraFn for Trans {
  25. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  26. let key = required_arg!(String, args.get("key"), "`trans` requires a `key` argument.");
  27. let lang = optional_arg!(String, args.get("lang"), "`trans`: `lang` must be a string.")
  28. .unwrap_or_else(|| self.config.default_language.clone());
  29. let term = self
  30. .config
  31. .get_translation(lang, key)
  32. .map_err(|e| Error::chain("Failed to retreive term translation", e))?;
  33. Ok(to_value(term).unwrap())
  34. }
  35. }
  36. #[derive(Debug)]
  37. pub struct GetUrl {
  38. config: Config,
  39. permalinks: HashMap<String, String>,
  40. }
  41. impl GetUrl {
  42. pub fn new(config: Config, permalinks: HashMap<String, String>) -> Self {
  43. Self { config, permalinks }
  44. }
  45. }
  46. impl TeraFn for GetUrl {
  47. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  48. let cachebust =
  49. args.get("cachebust").map_or(false, |c| from_value::<bool>(c.clone()).unwrap_or(false));
  50. let trailing_slash = args
  51. .get("trailing_slash")
  52. .map_or(false, |c| from_value::<bool>(c.clone()).unwrap_or(false));
  53. let path = required_arg!(
  54. String,
  55. args.get("path"),
  56. "`get_url` requires a `path` argument with a string value"
  57. );
  58. if path.starts_with("@/") {
  59. match resolve_internal_link(&path, &self.permalinks) {
  60. Ok(resolved) => Ok(to_value(resolved.permalink).unwrap()),
  61. Err(_) => {
  62. Err(format!("Could not resolve URL for link `{}` not found.", path).into())
  63. }
  64. }
  65. } else {
  66. // anything else
  67. let mut permalink = self.config.make_permalink(&path);
  68. if !trailing_slash && permalink.ends_with('/') {
  69. permalink.pop(); // Removes the slash
  70. }
  71. if cachebust {
  72. permalink = format!("{}?t={}", permalink, self.config.build_timestamp.unwrap());
  73. }
  74. Ok(to_value(permalink).unwrap())
  75. }
  76. }
  77. }
  78. #[derive(Debug)]
  79. pub struct ResizeImage {
  80. imageproc: Arc<Mutex<imageproc::Processor>>,
  81. }
  82. impl ResizeImage {
  83. pub fn new(imageproc: Arc<Mutex<imageproc::Processor>>) -> Self {
  84. Self { imageproc }
  85. }
  86. }
  87. static DEFAULT_OP: &str = "fill";
  88. static DEFAULT_FMT: &str = "auto";
  89. const DEFAULT_Q: u8 = 75;
  90. impl TeraFn for ResizeImage {
  91. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  92. let path = required_arg!(
  93. String,
  94. args.get("path"),
  95. "`resize_image` requires a `path` argument with a string value"
  96. );
  97. let width = optional_arg!(
  98. u32,
  99. args.get("width"),
  100. "`resize_image`: `width` must be a non-negative integer"
  101. );
  102. let height = optional_arg!(
  103. u32,
  104. args.get("height"),
  105. "`resize_image`: `height` must be a non-negative integer"
  106. );
  107. let op = optional_arg!(String, args.get("op"), "`resize_image`: `op` must be a string")
  108. .unwrap_or_else(|| DEFAULT_OP.to_string());
  109. let format =
  110. optional_arg!(String, args.get("format"), "`resize_image`: `format` must be a string")
  111. .unwrap_or_else(|| DEFAULT_FMT.to_string());
  112. let quality =
  113. optional_arg!(u8, args.get("quality"), "`resize_image`: `quality` must be a number")
  114. .unwrap_or(DEFAULT_Q);
  115. if quality == 0 || quality > 100 {
  116. return Err("`resize_image`: `quality` must be in range 1-100".to_string().into());
  117. }
  118. let mut imageproc = self.imageproc.lock().unwrap();
  119. if !imageproc.source_exists(&path) {
  120. return Err(format!("`resize_image`: Cannot find path: {}", path).into());
  121. }
  122. let imageop = imageproc::ImageOp::from_args(path, &op, width, height, &format, quality)
  123. .map_err(|e| format!("`resize_image`: {}", e))?;
  124. let url = imageproc.insert(imageop);
  125. to_value(url).map_err(|err| err.into())
  126. }
  127. }
  128. #[derive(Debug)]
  129. pub struct GetImageMeta {
  130. content_path: PathBuf,
  131. }
  132. impl GetImageMeta {
  133. pub fn new(content_path: PathBuf) -> Self {
  134. Self { content_path }
  135. }
  136. }
  137. impl TeraFn for GetImageMeta {
  138. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  139. let path = required_arg!(
  140. String,
  141. args.get("path"),
  142. "`get_image_meta` requires a `path` argument with a string value"
  143. );
  144. let src_path = self.content_path.join(&path);
  145. if !src_path.exists() {
  146. return Err(format!("`get_image_meta`: Cannot find path: {}", path).into());
  147. }
  148. let img = image::open(&src_path)
  149. .map_err(|e| Error::chain(format!("Failed to process image: {}", path), e))?;
  150. let mut map = tera::Map::new();
  151. map.insert(String::from("height"), Value::Number(tera::Number::from(img.height())));
  152. map.insert(String::from("width"), Value::Number(tera::Number::from(img.width())));
  153. Ok(Value::Object(map))
  154. }
  155. }
  156. #[derive(Debug)]
  157. pub struct GetTaxonomyUrl {
  158. taxonomies: HashMap<String, HashMap<String, String>>,
  159. default_lang: String,
  160. }
  161. impl GetTaxonomyUrl {
  162. pub fn new(default_lang: &str, all_taxonomies: &[Taxonomy]) -> Self {
  163. let mut taxonomies = HashMap::new();
  164. for taxo in all_taxonomies {
  165. let mut items = HashMap::new();
  166. for item in &taxo.items {
  167. items.insert(item.name.clone(), item.permalink.clone());
  168. }
  169. taxonomies.insert(format!("{}-{}", taxo.kind.name, taxo.kind.lang), items);
  170. }
  171. Self { taxonomies, default_lang: default_lang.to_string() }
  172. }
  173. }
  174. impl TeraFn for GetTaxonomyUrl {
  175. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  176. let kind = required_arg!(
  177. String,
  178. args.get("kind"),
  179. "`get_taxonomy_url` requires a `kind` argument with a string value"
  180. );
  181. let name = required_arg!(
  182. String,
  183. args.get("name"),
  184. "`get_taxonomy_url` requires a `name` argument with a string value"
  185. );
  186. let lang =
  187. optional_arg!(String, args.get("lang"), "`get_taxonomy`: `lang` must be a string")
  188. .unwrap_or_else(|| self.default_lang.clone());
  189. let container = match self.taxonomies.get(&format!("{}-{}", kind, lang)) {
  190. Some(c) => c,
  191. None => {
  192. return Err(format!(
  193. "`get_taxonomy_url` received an unknown taxonomy as kind: {}",
  194. kind
  195. )
  196. .into());
  197. }
  198. };
  199. if let Some(permalink) = container.get(&name) {
  200. return Ok(to_value(permalink).unwrap());
  201. }
  202. Err(format!("`get_taxonomy_url`: couldn't find `{}` in `{}` taxonomy", name, kind).into())
  203. }
  204. }
  205. #[derive(Debug)]
  206. pub struct GetPage {
  207. base_path: PathBuf,
  208. library: Arc<RwLock<Library>>,
  209. }
  210. impl GetPage {
  211. pub fn new(base_path: PathBuf, library: Arc<RwLock<Library>>) -> Self {
  212. Self { base_path: base_path.join("content"), library }
  213. }
  214. }
  215. impl TeraFn for GetPage {
  216. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  217. let path = required_arg!(
  218. String,
  219. args.get("path"),
  220. "`get_page` requires a `path` argument with a string value"
  221. );
  222. let full_path = self.base_path.join(&path);
  223. let library = self.library.read().unwrap();
  224. match library.get_page(&full_path) {
  225. Some(p) => Ok(to_value(p.to_serialized(&library)).unwrap()),
  226. None => Err(format!("Page `{}` not found.", path).into()),
  227. }
  228. }
  229. }
  230. #[derive(Debug)]
  231. pub struct GetSection {
  232. base_path: PathBuf,
  233. library: Arc<RwLock<Library>>,
  234. }
  235. impl GetSection {
  236. pub fn new(base_path: PathBuf, library: Arc<RwLock<Library>>) -> Self {
  237. Self { base_path: base_path.join("content"), library }
  238. }
  239. }
  240. impl TeraFn for GetSection {
  241. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  242. let path = required_arg!(
  243. String,
  244. args.get("path"),
  245. "`get_section` requires a `path` argument with a string value"
  246. );
  247. let metadata_only = args
  248. .get("metadata_only")
  249. .map_or(false, |c| from_value::<bool>(c.clone()).unwrap_or(false));
  250. let full_path = self.base_path.join(&path);
  251. let library = self.library.read().unwrap();
  252. match library.get_section(&full_path) {
  253. Some(s) => {
  254. if metadata_only {
  255. Ok(to_value(s.to_serialized_basic(&library)).unwrap())
  256. } else {
  257. Ok(to_value(s.to_serialized(&library)).unwrap())
  258. }
  259. }
  260. None => Err(format!("Section `{}` not found.", path).into()),
  261. }
  262. }
  263. }
  264. #[derive(Debug)]
  265. pub struct GetTaxonomy {
  266. library: Arc<RwLock<Library>>,
  267. taxonomies: HashMap<String, Taxonomy>,
  268. default_lang: String,
  269. }
  270. impl GetTaxonomy {
  271. pub fn new(
  272. default_lang: &str,
  273. all_taxonomies: Vec<Taxonomy>,
  274. library: Arc<RwLock<Library>>,
  275. ) -> Self {
  276. let mut taxonomies = HashMap::new();
  277. for taxo in all_taxonomies {
  278. taxonomies.insert(format!("{}-{}", taxo.kind.name, taxo.kind.lang), taxo);
  279. }
  280. Self { taxonomies, library, default_lang: default_lang.to_string() }
  281. }
  282. }
  283. impl TeraFn for GetTaxonomy {
  284. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  285. let kind = required_arg!(
  286. String,
  287. args.get("kind"),
  288. "`get_taxonomy` requires a `kind` argument with a string value"
  289. );
  290. let lang =
  291. optional_arg!(String, args.get("lang"), "`get_taxonomy`: `lang` must be a string")
  292. .unwrap_or_else(|| self.default_lang.clone());
  293. match self.taxonomies.get(&format!("{}-{}", kind, lang)) {
  294. Some(t) => Ok(to_value(t.to_serialized(&self.library.read().unwrap())).unwrap()),
  295. None => {
  296. Err(format!("`get_taxonomy` received an unknown taxonomy as kind: {}", kind).into())
  297. }
  298. }
  299. }
  300. }
  301. #[cfg(test)]
  302. mod tests {
  303. use super::{GetTaxonomy, GetTaxonomyUrl, GetUrl, Trans};
  304. use std::collections::HashMap;
  305. use std::sync::{Arc, RwLock};
  306. use tera::{to_value, Function, Value};
  307. use config::{Config, Taxonomy as TaxonomyConfig};
  308. use library::{Library, Taxonomy, TaxonomyItem};
  309. #[test]
  310. fn can_add_cachebust_to_url() {
  311. let config = Config::default();
  312. let static_fn = GetUrl::new(config, HashMap::new());
  313. let mut args = HashMap::new();
  314. args.insert("path".to_string(), to_value("app.css").unwrap());
  315. args.insert("cachebust".to_string(), to_value(true).unwrap());
  316. assert_eq!(static_fn.call(&args).unwrap(), "http://a-website.com/app.css?t=1");
  317. }
  318. #[test]
  319. fn can_add_trailing_slashes() {
  320. let config = Config::default();
  321. let static_fn = GetUrl::new(config, HashMap::new());
  322. let mut args = HashMap::new();
  323. args.insert("path".to_string(), to_value("app.css").unwrap());
  324. args.insert("trailing_slash".to_string(), to_value(true).unwrap());
  325. assert_eq!(static_fn.call(&args).unwrap(), "http://a-website.com/app.css/");
  326. }
  327. #[test]
  328. fn can_add_slashes_and_cachebust() {
  329. let config = Config::default();
  330. let static_fn = GetUrl::new(config, HashMap::new());
  331. let mut args = HashMap::new();
  332. args.insert("path".to_string(), to_value("app.css").unwrap());
  333. args.insert("trailing_slash".to_string(), to_value(true).unwrap());
  334. args.insert("cachebust".to_string(), to_value(true).unwrap());
  335. assert_eq!(static_fn.call(&args).unwrap(), "http://a-website.com/app.css/?t=1");
  336. }
  337. #[test]
  338. fn can_link_to_some_static_file() {
  339. let config = Config::default();
  340. let static_fn = GetUrl::new(config, HashMap::new());
  341. let mut args = HashMap::new();
  342. args.insert("path".to_string(), to_value("app.css").unwrap());
  343. assert_eq!(static_fn.call(&args).unwrap(), "http://a-website.com/app.css");
  344. }
  345. #[test]
  346. fn can_get_taxonomy() {
  347. let mut config = Config::default();
  348. config.slugify_paths = true;
  349. let taxo_config = TaxonomyConfig {
  350. name: "tags".to_string(),
  351. lang: config.default_language.clone(),
  352. ..TaxonomyConfig::default()
  353. };
  354. let taxo_config_fr = TaxonomyConfig {
  355. name: "tags".to_string(),
  356. lang: "fr".to_string(),
  357. ..TaxonomyConfig::default()
  358. };
  359. let library = Arc::new(RwLock::new(Library::new(0, 0, false)));
  360. let tag = TaxonomyItem::new(
  361. "Programming",
  362. &taxo_config,
  363. &config,
  364. vec![],
  365. &library.read().unwrap(),
  366. );
  367. let tag_fr = TaxonomyItem::new(
  368. "Programmation",
  369. &taxo_config_fr,
  370. &config,
  371. vec![],
  372. &library.read().unwrap(),
  373. );
  374. let tags = Taxonomy { kind: taxo_config, items: vec![tag] };
  375. let tags_fr = Taxonomy { kind: taxo_config_fr, items: vec![tag_fr] };
  376. let taxonomies = vec![tags.clone(), tags_fr.clone()];
  377. let static_fn =
  378. GetTaxonomy::new(&config.default_language, taxonomies.clone(), library.clone());
  379. // can find it correctly
  380. let mut args = HashMap::new();
  381. args.insert("kind".to_string(), to_value("tags").unwrap());
  382. let res = static_fn.call(&args).unwrap();
  383. let res_obj = res.as_object().unwrap();
  384. assert_eq!(res_obj["kind"], to_value(tags.kind).unwrap());
  385. assert_eq!(res_obj["items"].clone().as_array().unwrap().len(), 1);
  386. assert_eq!(
  387. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["name"],
  388. Value::String("Programming".to_string())
  389. );
  390. assert_eq!(
  391. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["slug"],
  392. Value::String("programming".to_string())
  393. );
  394. assert_eq!(
  395. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()
  396. ["permalink"],
  397. Value::String("http://a-website.com/tags/programming/".to_string())
  398. );
  399. assert_eq!(
  400. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["pages"],
  401. Value::Array(vec![])
  402. );
  403. // Works with other languages as well
  404. let mut args = HashMap::new();
  405. args.insert("kind".to_string(), to_value("tags").unwrap());
  406. args.insert("lang".to_string(), to_value("fr").unwrap());
  407. let res = static_fn.call(&args).unwrap();
  408. let res_obj = res.as_object().unwrap();
  409. assert_eq!(res_obj["kind"], to_value(tags_fr.kind).unwrap());
  410. assert_eq!(res_obj["items"].clone().as_array().unwrap().len(), 1);
  411. assert_eq!(
  412. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["name"],
  413. Value::String("Programmation".to_string())
  414. );
  415. // and errors if it can't find it
  416. let mut args = HashMap::new();
  417. args.insert("kind".to_string(), to_value("something-else").unwrap());
  418. assert!(static_fn.call(&args).is_err());
  419. }
  420. #[test]
  421. fn can_get_taxonomy_url() {
  422. let mut config = Config::default();
  423. config.slugify_paths = true;
  424. let taxo_config = TaxonomyConfig {
  425. name: "tags".to_string(),
  426. lang: config.default_language.clone(),
  427. ..TaxonomyConfig::default()
  428. };
  429. let taxo_config_fr = TaxonomyConfig {
  430. name: "tags".to_string(),
  431. lang: "fr".to_string(),
  432. ..TaxonomyConfig::default()
  433. };
  434. let library = Library::new(0, 0, false);
  435. let tag = TaxonomyItem::new("Programming", &taxo_config, &config, vec![], &library);
  436. let tag_fr = TaxonomyItem::new("Programmation", &taxo_config_fr, &config, vec![], &library);
  437. let tags = Taxonomy { kind: taxo_config, items: vec![tag] };
  438. let tags_fr = Taxonomy { kind: taxo_config_fr, items: vec![tag_fr] };
  439. let taxonomies = vec![tags.clone(), tags_fr.clone()];
  440. let static_fn = GetTaxonomyUrl::new(&config.default_language, &taxonomies);
  441. // can find it correctly
  442. let mut args = HashMap::new();
  443. args.insert("kind".to_string(), to_value("tags").unwrap());
  444. args.insert("name".to_string(), to_value("Programming").unwrap());
  445. assert_eq!(
  446. static_fn.call(&args).unwrap(),
  447. to_value("http://a-website.com/tags/programming/").unwrap()
  448. );
  449. // works with other languages
  450. let mut args = HashMap::new();
  451. args.insert("kind".to_string(), to_value("tags").unwrap());
  452. args.insert("name".to_string(), to_value("Programmation").unwrap());
  453. args.insert("lang".to_string(), to_value("fr").unwrap());
  454. assert_eq!(
  455. static_fn.call(&args).unwrap(),
  456. to_value("http://a-website.com/fr/tags/programmation/").unwrap()
  457. );
  458. // and errors if it can't find it
  459. let mut args = HashMap::new();
  460. args.insert("kind".to_string(), to_value("tags").unwrap());
  461. args.insert("name".to_string(), to_value("random").unwrap());
  462. assert!(static_fn.call(&args).is_err());
  463. }
  464. const TRANS_CONFIG: &str = r#"
  465. base_url = "https://remplace-par-ton-url.fr"
  466. default_language = "fr"
  467. [translations]
  468. [translations.fr]
  469. title = "Un titre"
  470. [translations.en]
  471. title = "A title"
  472. "#;
  473. #[test]
  474. fn can_translate_a_string() {
  475. let config = Config::parse(TRANS_CONFIG).unwrap();
  476. let static_fn = Trans::new(config);
  477. let mut args = HashMap::new();
  478. args.insert("key".to_string(), to_value("title").unwrap());
  479. assert_eq!(static_fn.call(&args).unwrap(), "Un titre");
  480. args.insert("lang".to_string(), to_value("en").unwrap());
  481. assert_eq!(static_fn.call(&args).unwrap(), "A title");
  482. args.insert("lang".to_string(), to_value("fr").unwrap());
  483. assert_eq!(static_fn.call(&args).unwrap(), "Un titre");
  484. }
  485. #[test]
  486. fn error_on_absent_translation_lang() {
  487. let mut args = HashMap::new();
  488. args.insert("lang".to_string(), to_value("absent").unwrap());
  489. args.insert("key".to_string(), to_value("title").unwrap());
  490. let config = Config::parse(TRANS_CONFIG).unwrap();
  491. let error = Trans::new(config).call(&args).unwrap_err();
  492. assert_eq!("Failed to retreive term translation", format!("{}", error));
  493. }
  494. #[test]
  495. fn error_on_absent_translation_key() {
  496. let mut args = HashMap::new();
  497. args.insert("lang".to_string(), to_value("en").unwrap());
  498. args.insert("key".to_string(), to_value("absent").unwrap());
  499. let config = Config::parse(TRANS_CONFIG).unwrap();
  500. let error = Trans::new(config).call(&args).unwrap_err();
  501. assert_eq!("Failed to retreive term translation", format!("{}", error));
  502. }
  503. }