use rocket::State; use rocket_contrib::json::Json; use serde_json::Value; use db::DbConn; use db::models::*; use api::{JsonResult, EmptyResult, JsonUpcase, WebSocketUsers, UpdateType}; use auth::Headers; use rocket::Route; pub fn routes() -> Vec { routes![ get_folders, get_folder, post_folders, post_folder, put_folder, delete_folder_post, delete_folder, ] } #[get("/folders")] fn get_folders(headers: Headers, conn: DbConn) -> JsonResult { let folders = Folder::find_by_user(&headers.user.uuid, &conn); let folders_json: Vec = folders.iter().map(|c| c.to_json()).collect(); Ok(Json(json!({ "Data": folders_json, "Object": "list", "ContinuationToken": null, }))) } #[get("/folders/")] fn get_folder(uuid: String, headers: Headers, conn: DbConn) -> JsonResult { let folder = match Folder::find_by_uuid(&uuid, &conn) { Some(folder) => folder, _ => err!("Invalid folder") }; if folder.user_uuid != headers.user.uuid { err!("Folder belongs to another user") } Ok(Json(folder.to_json())) } #[derive(Deserialize)] #[allow(non_snake_case)] pub struct FolderData { pub Name: String } #[post("/folders", data = "")] fn post_folders(data: JsonUpcase, headers: Headers, conn: DbConn, ws: State) -> JsonResult { let data: FolderData = data.into_inner().data; let mut folder = Folder::new(headers.user.uuid.clone(), data.Name); if folder.save(&conn).is_err() { err!("Failed to save folder") } ws.send_folder_update(UpdateType::SyncFolderCreate, &folder); Ok(Json(folder.to_json())) } #[post("/folders/", data = "")] fn post_folder(uuid: String, data: JsonUpcase, headers: Headers, conn: DbConn, ws: State) -> JsonResult { put_folder(uuid, data, headers, conn, ws) } #[put("/folders/", data = "")] fn put_folder(uuid: String, data: JsonUpcase, headers: Headers, conn: DbConn, ws: State) -> JsonResult { let data: FolderData = data.into_inner().data; let mut folder = match Folder::find_by_uuid(&uuid, &conn) { Some(folder) => folder, _ => err!("Invalid folder") }; if folder.user_uuid != headers.user.uuid { err!("Folder belongs to another user") } folder.name = data.Name; if folder.save(&conn).is_err() { err!("Failed to save folder") } ws.send_folder_update(UpdateType::SyncFolderUpdate, &folder); Ok(Json(folder.to_json())) } #[post("/folders//delete")] fn delete_folder_post(uuid: String, headers: Headers, conn: DbConn, ws: State) -> EmptyResult { delete_folder(uuid, headers, conn, ws) } #[delete("/folders/")] fn delete_folder(uuid: String, headers: Headers, conn: DbConn, ws: State) -> EmptyResult { let folder = match Folder::find_by_uuid(&uuid, &conn) { Some(folder) => folder, _ => err!("Invalid folder") }; if folder.user_uuid != headers.user.uuid { err!("Folder belongs to another user") } // Delete the actual folder entry match folder.delete(&conn) { Ok(()) => { ws.send_folder_update(UpdateType::SyncFolderDelete, &folder); Ok(()) } Err(_) => err!("Failed deleting folder") } }