Refactor callback functions

Signed-off-by: trivernis <trivernis@protonmail.com>
pull/4/head
trivernis 3 years ago
parent 1769a54d53
commit 4cebfc7eb2

@ -11,6 +11,7 @@ use std::path::PathBuf;
use tokio::fs::OpenOptions; use tokio::fs::OpenOptions;
use tokio::io::BufReader; use tokio::io::BufReader;
#[derive(Clone)]
pub struct Repo { pub struct Repo {
db: DatabaseConnection, db: DatabaseConnection,
main_storage: Option<Storage>, main_storage: Option<Storage>,

@ -1,8 +1,9 @@
use crate::repo::Repo; use crate::repo::Repo;
use std::sync::Arc;
use typemap_rev::TypeMapKey; use typemap_rev::TypeMapKey;
pub struct RepoKey; pub struct RepoKey;
impl TypeMapKey for RepoKey { impl TypeMapKey for RepoKey {
type Value = Repo; type Value = Arc<Repo>;
} }

@ -3,6 +3,7 @@ use mediarepo_core::rmp_ipc::prelude::*;
mod namespaces; mod namespaces;
pub mod types; pub mod types;
mod utils;
pub fn get_builder(address: &str) -> IPCBuilder { pub fn get_builder(address: &str) -> IPCBuilder {
namespaces::build_namespaces(IPCBuilder::new().address(address)).on("info", callback!(info)) namespaces::build_namespaces(IPCBuilder::new().address(address)).on("info", callback!(info))

@ -2,11 +2,11 @@ use crate::types::requests::{
AddFileRequest, FileIdentifier, GetFileThumbnailsRequest, ReadFileRequest, AddFileRequest, FileIdentifier, GetFileThumbnailsRequest, ReadFileRequest,
}; };
use crate::types::responses::{FileResponse, ThumbnailResponse}; use crate::types::responses::{FileResponse, ThumbnailResponse};
use crate::utils::get_repo_from_context;
use mediarepo_core::error::{RepoError, RepoResult}; use mediarepo_core::error::{RepoError, RepoResult};
use mediarepo_core::rmp_ipc::prelude::*; use mediarepo_core::rmp_ipc::prelude::*;
use mediarepo_model::file::File; use mediarepo_model::file::File;
use mediarepo_model::repo::Repo; use mediarepo_model::repo::Repo;
use mediarepo_model::type_keys::RepoKey;
use std::path::PathBuf; use std::path::PathBuf;
use tokio::io::AsyncReadExt; use tokio::io::AsyncReadExt;
@ -32,8 +32,7 @@ impl FilesNamespace {
/// Returns a list of all files /// Returns a list of all files
async fn all_files(ctx: &Context, event: Event) -> IPCResult<()> { async fn all_files(ctx: &Context, event: Event) -> IPCResult<()> {
let files = { let files = {
let data = ctx.data.read().await; let repo = get_repo_from_context(ctx).await;
let repo = data.get::<RepoKey>().unwrap();
repo.files().await? repo.files().await?
}; };
let responses: Vec<FileResponse> = files.into_iter().map(FileResponse::from).collect(); let responses: Vec<FileResponse> = files.into_iter().map(FileResponse::from).collect();
@ -48,11 +47,9 @@ impl FilesNamespace {
async fn add_file(ctx: &Context, event: Event) -> IPCResult<()> { async fn add_file(ctx: &Context, event: Event) -> IPCResult<()> {
let request = event.data::<AddFileRequest>()?; let request = event.data::<AddFileRequest>()?;
let path = PathBuf::from(request.path); let path = PathBuf::from(request.path);
let file = { let repo = get_repo_from_context(ctx).await;
let data = ctx.data.read().await; let file = repo.add_file_by_path(path).await?;
let repo = data.get::<RepoKey>().unwrap();
repo.add_file_by_path(path).await?
};
ctx.emitter ctx.emitter
.emit_response_to( .emit_response_to(
event.id(), event.id(),
@ -68,16 +65,13 @@ impl FilesNamespace {
/// Reads the binary contents of a file /// Reads the binary contents of a file
async fn read_file(ctx: &Context, event: Event) -> IPCResult<()> { async fn read_file(ctx: &Context, event: Event) -> IPCResult<()> {
let request = event.data::<ReadFileRequest>()?; let request = event.data::<ReadFileRequest>()?;
let mut reader = {
let data = ctx.data.read().await; let repo = get_repo_from_context(ctx).await;
let repo = data.get::<RepoKey>().unwrap(); let file = file_by_identifier(request, &repo).await?;
let file = file_by_identifier(request, repo) let mut reader = file.get_reader().await?;
.await?
.ok_or_else(|| RepoError::from("File not found"));
file?.get_reader().await?
};
let mut buf = Vec::new(); let mut buf = Vec::new();
reader.read_to_end(&mut buf).await?; reader.read_to_end(&mut buf).await?;
ctx.emitter ctx.emitter
.emit_response_to(event.id(), Self::name(), "read_file", buf) .emit_response_to(event.id(), Self::name(), "read_file", buf)
.await?; .await?;
@ -88,12 +82,10 @@ impl FilesNamespace {
/// Returns a list of available thumbnails of a file /// Returns a list of available thumbnails of a file
async fn thumbnails(ctx: &Context, event: Event) -> IPCResult<()> { async fn thumbnails(ctx: &Context, event: Event) -> IPCResult<()> {
let request = event.data::<GetFileThumbnailsRequest>()?; let request = event.data::<GetFileThumbnailsRequest>()?;
let data = ctx.data.read().await; let repo = get_repo_from_context(ctx).await;
let repo = data.get::<RepoKey>().unwrap(); let file = file_by_identifier(request, &repo).await?;
let file = file_by_identifier(request, repo)
.await?
.ok_or_else(|| RepoError::from("File not found"))?;
let thumbnails = file.thumbnails().await?; let thumbnails = file.thumbnails().await?;
let thumb_responses: Vec<ThumbnailResponse> = thumbnails let thumb_responses: Vec<ThumbnailResponse> = thumbnails
.into_iter() .into_iter()
.map(ThumbnailResponse::from) .map(ThumbnailResponse::from)
@ -108,15 +100,12 @@ impl FilesNamespace {
/// Reads a thumbnail for the given thumbnail hash /// Reads a thumbnail for the given thumbnail hash
async fn read_thumbnail(ctx: &Context, event: Event) -> IPCResult<()> { async fn read_thumbnail(ctx: &Context, event: Event) -> IPCResult<()> {
let hash = event.data::<String>()?; let hash = event.data::<String>()?;
let mut reader = { let repo = get_repo_from_context(ctx).await;
let data = ctx.data.read().await;
let repo = data.get::<RepoKey>().unwrap();
let thumbnail = repo let thumbnail = repo
.thumbnail_by_hash(&hash) .thumbnail_by_hash(&hash)
.await? .await?
.ok_or_else(|| RepoError::from("Thumbnail not found"))?; .ok_or_else(|| RepoError::from("Thumbnail not found"))?;
thumbnail.get_reader().await? let mut reader = thumbnail.get_reader().await?;
};
let mut buf = Vec::new(); let mut buf = Vec::new();
reader.read_to_end(&mut buf).await?; reader.read_to_end(&mut buf).await?;
ctx.emitter ctx.emitter
@ -127,9 +116,10 @@ impl FilesNamespace {
} }
} }
async fn file_by_identifier(identifier: FileIdentifier, repo: &Repo) -> RepoResult<Option<File>> { async fn file_by_identifier(identifier: FileIdentifier, repo: &Repo) -> RepoResult<File> {
match identifier { let file = match identifier {
FileIdentifier::ID(id) => repo.file_by_id(id).await, FileIdentifier::ID(id) => repo.file_by_id(id).await,
FileIdentifier::Hash(hash) => repo.file_by_hash(hash).await, FileIdentifier::Hash(hash) => repo.file_by_hash(hash).await,
} }?;
file.ok_or_else(|| RepoError::from("Thumbnail not found"))
} }

@ -0,0 +1,10 @@
use mediarepo_core::rmp_ipc::ipc::context::Context;
use mediarepo_model::repo::Repo;
use mediarepo_model::type_keys::RepoKey;
use std::sync::Arc;
pub async fn get_repo_from_context(ctx: &Context) -> Arc<Repo> {
let data = ctx.data.read().await;
let repo = data.get::<RepoKey>().unwrap();
Arc::clone(repo)
}

@ -11,6 +11,7 @@ use mediarepo_model::repo::Repo;
use mediarepo_model::type_keys::RepoKey; use mediarepo_model::type_keys::RepoKey;
use mediarepo_socket::get_builder; use mediarepo_socket::get_builder;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc;
use structopt::StructOpt; use structopt::StructOpt;
use tokio::fs; use tokio::fs;
use tokio::runtime; use tokio::runtime;
@ -105,7 +106,7 @@ async fn start_server(opt: Opt) -> RepoResult<()> {
get_builder(&settings.listen_address) get_builder(&settings.listen_address)
.insert::<SettingsKey>(settings) .insert::<SettingsKey>(settings)
.insert::<RepoKey>(repo) .insert::<RepoKey>(Arc::new(repo))
.build_server() .build_server()
.await?; .await?;

Loading…
Cancel
Save