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.

442 lines
15KB

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