add /api/files endpoint, refactor retrieve_file()

feat/vaults
Tomáš Mládek 2021-04-23 23:28:58 +02:00
parent c2705d328d
commit 7420fd45d8
3 changed files with 35 additions and 16 deletions

View File

@ -210,6 +210,20 @@ pub fn insert_file<C: Connection<Backend = Sqlite>>(
.execute(connection)?)
}
pub fn retrieve_file<C: Connection<Backend = Sqlite>>(
connection: &C,
obj_hash: Hash,
) -> Result<Vec<models::File>> {
use crate::schema::files::dsl::*;
let matches = files
.filter(valid.eq(true))
.filter(hash.eq(obj_hash.0))
.load::<models::File>(connection)?;
Ok(matches)
}
pub fn retrieve_all_files<C: Connection<Backend = Sqlite>>(
connection: &C,
) -> Result<Vec<models::File>> {
@ -232,20 +246,6 @@ pub fn get_latest_files<C: Connection<Backend = Sqlite>>(
Ok(matches)
}
pub fn retrieve_file<C: Connection<Backend = Sqlite>>(
connection: &C,
obj_hash: Hash,
) -> Result<Option<String>> {
use crate::schema::files::dsl::*;
let matches = files
.filter(valid.eq(true))
.filter(hash.eq(obj_hash.0))
.load::<models::File>(connection)?;
Ok(matches.get(0).map(|f| f.path.clone()))
}
pub fn file_set_valid<C: Connection<Backend = Sqlite>>(
connection: &C,
file_id: i32,

View File

@ -97,6 +97,7 @@ fn main() -> Result<()> {
.service(routes::delete_object)
.service(routes::api_refresh)
.service(routes::list_hier)
.service(routes::get_file)
.service(routes::latest_files)
.service(routes::get_jobs)
.service(

View File

@ -36,8 +36,8 @@ pub async fn get_raw(state: web::Data<State>, hash: web::Path<String>) -> Result
debug!("{:?}", response);
match response {
Ok(result) => match result {
Some(path) => Ok(NamedFile::open(state.directory.join(path))?),
Ok(result) => match result.get(0) {
Some(file) => Ok(NamedFile::open(state.directory.join(&file.path))?),
None => Err(error::ErrorNotFound("NOT FOUND")),
},
Err(e) => Err(error::ErrorInternalServerError(e)),
@ -177,6 +177,24 @@ pub async fn api_refresh(state: web::Data<State>) -> Result<HttpResponse, Error>
Ok(HttpResponse::Ok().finish())
}
#[get("/api/files/{hash}")]
pub async fn get_file(
state: web::Data<State>,
hash: web::Path<String>,
) -> Result<HttpResponse, Error> {
let address = Address::decode(&decode(hash.into_inner()).map_err(ErrorInternalServerError)?)
.map_err(ErrorInternalServerError)?;
if let Address::Hash(hash) = address {
let connection = state.db_pool.get().map_err(ErrorInternalServerError)?;
let response = retrieve_file(&connection, hash).map_err(ErrorInternalServerError)?;
Ok(HttpResponse::Ok().json(response))
} else {
Err(ErrorBadRequest("Address does not refer to a file."))
}
}
#[get("/api/files/latest")]
pub async fn latest_files(state: web::Data<State>) -> Result<HttpResponse, Error> {
let connection = state.db_pool.get().map_err(ErrorInternalServerError)?;