bazzar/db-seed/src/photos.rs

153 lines
3.8 KiB
Rust
Raw Normal View History

2022-05-08 09:47:05 +02:00
use actix::{Actor, Addr};
use config::SharedAppConfig;
use database_manager::{query_db, Database};
use fs_manager::query_fs;
use tokio::io::AsyncReadExt;
use crate::{Result, SharedState};
async fn create_photo(
db: Addr<Database>,
seed: SharedState,
fs: Addr<fs_manager::FsManager>,
file: &'static str,
) -> crate::Result<()> {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let read = async move {
let mut file =
tokio::fs::File::open(std::path::Path::new("./assets/examples/images").join(file))
.await
.unwrap();
while let Ok(b) = file.read_u8().await {
tx.send(b).unwrap();
}
};
let write = async {
let fs_manager::WriteResult {
unique_name: _,
local_path,
} = query_fs!(
fs,
fs_manager::WriteFile {
file_name: file.to_string(),
stream: rx,
},
panic
);
let photo: model::Photo = query_db!(
db,
database_manager::CreatePhoto {
local_path,
file_name: model::FileName::new(file)
},
crate::Error::WritePhoto(file.into())
);
seed.lock().unwrap().photos.push(photo);
Ok(())
};
let (_, res) = tokio::join!(read, write);
log::debug!("Photo {:?} done", file);
res
}
pub(crate) async fn create_photos(
db: Addr<Database>,
seed: SharedState,
config: SharedAppConfig,
) -> Result<()> {
log::debug!("Creating photos");
let photos: Vec<model::Photo> = query_db!(db, database_manager::AllPhotos, default vec![]);
if photos.len() >= 10 {
seed.lock().unwrap().photos = photos;
return Ok(());
}
let fs = fs_manager::FsManager::build(config.clone())
.await
.unwrap()
.start();
let results = tokio::join!(
create_photo(
db.clone(),
seed.clone(),
fs.clone(),
"pexels-alex-azabache-3907507.webp"
),
create_photo(
db.clone(),
seed.clone(),
fs.clone(),
"pexels-binoid-cbd-3612182.webp"
),
create_photo(
db.clone(),
seed.clone(),
fs.clone(),
"pexels-caio-1279107.webp"
),
create_photo(
db.clone(),
seed.clone(),
fs.clone(),
"pexels-eprism-studio-335257.webp"
),
create_photo(
db.clone(),
seed.clone(),
fs.clone(),
"pexels-gabriel-freytez-341523.webp"
),
create_photo(
db.clone(),
seed.clone(),
fs.clone(),
"pexels-jess-bailey-designs-913135.webp"
),
create_photo(
db.clone(),
seed.clone(),
fs.clone(),
"pexels-luis-quintero-1738641.webp"
),
create_photo(
db.clone(),
seed.clone(),
fs.clone(),
"pexels-math-90946.webp"
),
create_photo(
db.clone(),
seed.clone(),
fs.clone(),
"pexels-mike-380954.webp"
),
create_photo(
db.clone(),
seed.clone(),
fs.clone(),
"pexels-pixabay-279906.webp"
),
create_photo(
db.clone(),
seed.clone(),
fs.clone(),
"pexels-Venus-HD-Make-up-and-perfume-2587370.webp"
)
);
results.0.unwrap();
results.1.unwrap();
results.2.unwrap();
results.3.unwrap();
results.4.unwrap();
results.5.unwrap();
results.6.unwrap();
results.7.unwrap();
results.8.unwrap();
results.9.unwrap();
results.10.unwrap();
Ok(())
}