Toude

linker

May 22nd, 2020
356
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #![feature(proc_macro_hygiene, decl_macro)]
  2.  
  3. #[macro_use]
  4. extern crate rocket;
  5.  
  6. use rocket::http::Status;
  7. use rocket_contrib::json::Json;
  8. use serde_json::Value;
  9. use std::fs;
  10. use std::path::Path;
  11.  
  12. const BASE_PATH: &str = "../../python/discord/botanist/src/";
  13. const SERVER_PATH: &str = "../../python/discord/botanist/src/servers/";
  14.  
  15. /// Returns the IDs of guilds handled by the bot.
  16. fn get_guilds() -> Vec<String> {
  17.     Path::new(SERVER_PATH)
  18.         .read_dir()
  19.         .expect("SERVER_PATH does not exist!")
  20.         .map(|file| {
  21.             file.expect("Could not read files in SERVER_PATH")
  22.                 .file_name()
  23.                 .into_string()
  24.                 .unwrap() //the value written by python here is always UTF-8 valid
  25.                 .split(".")
  26.                 .next()
  27.                 .unwrap() //there will always at least be one value in this collection, even if for some reason the filename did not contain a `.`
  28.                 .to_string()
  29.         })
  30.         .collect()
  31. }
  32.  
  33. /// Returns an array sttrings of guild IDs. Each ID represents a guild handled by the bot.
  34. #[get("/servers")]
  35. fn server_all() -> Json<Value> {
  36.     Json(Value::Array(
  37.         get_guilds()
  38.             .iter()
  39.             .map(|id| Value::String(id.to_string()))
  40.             .collect(),
  41.     ))
  42. }
  43.  
  44. /// Returns a JSON bool denoting the existence of a config for this guild
  45. #[get("/server/<gid>")]
  46. fn server_one(gid: String) -> Json<bool> {
  47.     let mut file = String::from(gid);
  48.     file.push_str(".json");
  49.     Json(Path::new(SERVER_PATH).join(file).exists())
  50. }
  51.  
  52. /// Returns the JSON config file for the specified guild
  53. #[get("/config/<gid>")]
  54. fn server_conf(gid: String) -> Option<Json<Value>> {
  55.     let mut path = String::from(SERVER_PATH);
  56.     path.push_str(&gid);
  57.     path.push_str(".json");
  58.     let contents = fs::read_to_string(path).ok()?;
  59.     Some(Json(serde_json::from_str(&contents).ok()?))
  60. }
  61.  
  62. /// returns a JSON array of available languages for the bot
  63. #[get("/langs")]
  64. fn available_langs() -> Json<Value> {
  65.     let path = Path::new(BASE_PATH).join("settings.py");
  66.     let contents = fs::read_to_string(path).expect("settings.py is missing!");
  67.  
  68.     let langs_line: Vec<_> = contents
  69.         .lines()
  70.         .filter(|line| line.starts_with("ALLOWED_LANGS"))
  71.         .collect();
  72.     assert_eq!(langs_line.len(), 1); //langs shouldn't be degined more than once
  73.     Json(
  74.         serde_json::from_str(langs_line[0].rsplit("=").next().unwrap())
  75.             .expect("Could not decode python list to json array!"),
  76.     )
  77. }
  78.  
  79. /// Reloads the langs, currently not needed. Only here for backward-compatibility
  80. #[get("/reload")]
  81. fn reload_langs() -> Json<bool> {
  82.     Json(true)
  83. }
  84.  
  85. /// attempts to update the config file for guild with id <gid>
  86. /// retuns different status codes depending on the results:
  87. ///     200 if successful
  88. ///     404 if <gid> is invalid
  89. ///     304 if updating failed for some internal reason
  90. #[put("/update/<gid>", format = "json", data = "<conf>")]
  91. fn overwrite_conf(gid: String, conf: Json<serde_json::Value>) -> Status {
  92.     let mut name = String::from(gid);
  93.     name.push_str(".json");
  94.     let path = Path::new(SERVER_PATH);
  95.     if !get_guilds().contains(&name) {
  96.         return Status::NotFound;
  97.     } else {
  98.         match fs::write(path, conf.to_string()) {
  99.             Ok(_) => Status::Ok,
  100.             Err(_) => Status::NotModified,
  101.         }
  102.     }
  103. }
  104.  
  105. fn main() {
  106.     rocket::ignite()
  107.         .mount(
  108.             "/",
  109.             routes![
  110.                 server_one,
  111.                 server_all,
  112.                 server_conf,
  113.                 available_langs,
  114.                 overwrite_conf
  115.             ],
  116.         )
  117.         .launch();
  118. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×