move sbot helper functions to utils

This commit is contained in:
glyph 2022-03-20 12:28:08 +02:00
parent 40c4f8aaf2
commit cd7c2bc230
2 changed files with 3 additions and 180 deletions

View File

@ -1,51 +1,8 @@
use std::error::Error;
use async_std::task;
use futures::stream::TryStreamExt;
use golgi::{messages::SsbMessageValue, Sbot};
use maud::{html, Markup, PreEscaped};
use peach_lib::sbot::{SbotConfig, SbotStatus};
use crate::{error::PeachWebError, templates};
// SBOT HELPER FUNCTIONS
pub async fn init_sbot_with_config(
sbot_config: &Option<SbotConfig>,
) -> Result<Sbot, PeachWebError> {
// initialise sbot connection with ip:port and shscap from config file
let sbot_client = match sbot_config {
// TODO: panics if we pass `Some(conf.shscap)` as second arg
Some(conf) => {
let ip_port = conf.lis.clone();
Sbot::init(Some(ip_port), None).await?
}
None => Sbot::init(None, None).await?,
};
Ok(sbot_client)
}
fn latest_sequence_number() -> Result<u64, Box<dyn Error>> {
// retrieve latest go-sbot configuration parameters
let sbot_config = SbotConfig::read().ok();
task::block_on(async {
let mut sbot_client = init_sbot_with_config(&sbot_config).await?;
// retrieve the local id
let id = sbot_client.whoami().await?;
let history_stream = sbot_client.create_history_stream(id).await?;
let mut msgs: Vec<SsbMessageValue> = history_stream.try_collect().await?;
// reverse the list of messages so we can easily reference the latest one
msgs.reverse();
// return the sequence number of the latest msg
Ok(msgs[0].sequence)
})
}
use crate::templates;
use crate::utils::sbot;
// HTML RENDERING FOR ELEMENTS
@ -90,7 +47,7 @@ fn run_on_startup_element(boot_state: &Option<String>) -> Markup {
fn database_element(state: &str) -> Markup {
// retrieve the sequence number of the latest message in the sbot database
let sequence_num = latest_sequence_number();
let sequence_num = sbot::latest_sequence_number();
if state == "active" && sequence_num.is_ok() {
let number = sequence_num.unwrap();

View File

@ -1,134 +0,0 @@
use log::info;
use crate::THEME;
// THEME FUNCTIONS
#[derive(Debug, Copy, Clone)]
pub enum Theme {
Light,
Dark,
}
pub fn get_theme() -> String {
let current_theme = THEME.read().unwrap();
match *current_theme {
Theme::Dark => "dark".to_string(),
_ => "light".to_string(),
}
}
pub fn set_theme(theme: Theme) {
info!("set ui theme to: {:?}", theme);
let mut writable_theme = THEME.write().unwrap();
*writable_theme = theme;
}
// get_cookie
// set_cookie
/*
pub mod monitor;
use std::io::prelude::*;
use std::{fs, fs::File, path::Path};
use dirs;
use golgi::blobs;
use log::info;
use peach_lib::sbot::SbotConfig;
use rocket::{
fs::TempFile,
response::{Redirect, Responder},
serde::Serialize,
};
use rocket_dyn_templates::Template;
use temporary::Directory;
use crate::{error::PeachWebError, THEME};
// FILEPATH FUNCTIONS
// return the path of the ssb-go directory
pub fn get_go_ssb_path() -> Result<String, PeachWebError> {
let go_ssb_path = match SbotConfig::read() {
Ok(conf) => conf.repo,
// return the default path if unable to read `config.toml`
Err(_) => {
// determine the home directory
let mut home_path = dirs::home_dir().ok_or_else(|| PeachWebError::HomeDir)?;
// add the go-ssb subdirectory
home_path.push(".ssb-go");
// convert the PathBuf to a String
home_path
.into_os_string()
.into_string()
.map_err(|_| PeachWebError::OsString)?
}
};
Ok(go_ssb_path)
}
// check whether a blob is in the blobstore
pub async fn blob_is_stored_locally(blob_path: &str) -> Result<bool, PeachWebError> {
let go_ssb_path = get_go_ssb_path()?;
let complete_path = format!("{}/blobs/sha256/{}", go_ssb_path, blob_path);
let blob_exists_locally = Path::new(&complete_path).exists();
Ok(blob_exists_locally)
}
// take the path to a file, add it to the blobstore and return the blob id
pub async fn write_blob_to_store(file: &mut TempFile<'_>) -> Result<String, PeachWebError> {
// create temporary directory and path
let temp_dir = Directory::new("blob")?;
// we performed a `file.name().is_some()` check before calling `write_blob_to_store`
// so it should be safe to do a simple unwrap here
let filename = file.name().expect("retrieving filename from uploaded file");
let temp_path = temp_dir.join(filename);
// write file to temporary path
file.persist_to(&temp_path).await?;
// open the file and read it into a buffer
let mut file = File::open(&temp_path)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
// hash the bytes representing the file
let (hex_hash, blob_id) = blobs::hash_blob(&buffer)?;
// define the blobstore path and blob filename
let (blob_dir, blob_filename) = hex_hash.split_at(2);
let go_ssb_path = get_go_ssb_path()?;
let blobstore_sub_dir = format!("{}/blobs/sha256/{}", go_ssb_path, blob_dir);
// create the blobstore sub-directory
fs::create_dir_all(&blobstore_sub_dir)?;
// copy the file to the blobstore
let blob_path = format!("{}/{}", blobstore_sub_dir, blob_filename);
fs::copy(temp_path, blob_path)?;
Ok(blob_id)
}
// HELPER FUNCTIONS
#[derive(Debug, Serialize)]
pub struct FlashContext {
pub flash_name: Option<String>,
pub flash_msg: Option<String>,
}
/// A helper enum which allows routes to either return a Template or a Redirect
/// from: https://github.com/SergioBenitez/Rocket/issues/253#issuecomment-532356066
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Responder)]
pub enum TemplateOrRedirect {
Template(Template),
Redirect(Redirect),
}
*/