cleaning, persistence

master
Ondřej Hruška 5 years ago
parent 987e4aead2
commit d97f460bd8
Signed by: MightyPork
GPG Key ID: 2C5FD5035250423D
  1. 4
      Cargo.lock
  2. 3
      Cargo.toml
  3. 2
      src/bootstrap.rs
  4. 85
      src/main.rs
  5. 44
      src/store.rs

4
Cargo.lock generated

@ -280,7 +280,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]] [[package]]
name = "elefren" name = "elefren"
version = "0.20.1" version = "0.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [ dependencies = [
"chrono 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", "chrono 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)",
"doc-comment 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "doc-comment 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
@ -627,7 +626,7 @@ name = "manabu"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)",
"elefren 0.20.1 (registry+https://github.com/rust-lang/crates.io-index)", "elefren 0.20.1",
"env_logger 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
@ -1779,7 +1778,6 @@ dependencies = [
"checksum doc-comment 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "923dea538cea0aa3025e8685b20d6ee21ef99c4f77e954a30febbaac5ec73a97" "checksum doc-comment 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "923dea538cea0aa3025e8685b20d6ee21ef99c4f77e954a30febbaac5ec73a97"
"checksum dtoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "ea57b42383d091c85abcc2706240b94ab2a8fa1fc81c10ff23c4de06e2a90b5e" "checksum dtoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "ea57b42383d091c85abcc2706240b94ab2a8fa1fc81c10ff23c4de06e2a90b5e"
"checksum either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" "checksum either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3"
"checksum elefren 0.20.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dfca8d8d0147086081224e22183a37a7b98e3230b945a717f1b5a0eed5fb07af"
"checksum encoding_rs 0.8.20 (registry+https://github.com/rust-lang/crates.io-index)" = "87240518927716f79692c2ed85bfe6e98196d18c6401ec75355760233a7e12e9" "checksum encoding_rs 0.8.20 (registry+https://github.com/rust-lang/crates.io-index)" = "87240518927716f79692c2ed85bfe6e98196d18c6401ec75355760233a7e12e9"
"checksum env_logger 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "39ecdb7dd54465526f0a56d666e3b2dd5f3a218665a030b6e4ad9e70fa95d8fa" "checksum env_logger 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "39ecdb7dd54465526f0a56d666e3b2dd5f3a218665a030b6e4ad9e70fa95d8fa"
"checksum error-chain 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3ab49e9dcb602294bc42f9a7dfc9bc6e936fca4418ea300dbfb84fe16de0b7d9" "checksum error-chain 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3ab49e9dcb602294bc42f9a7dfc9bc6e936fca4418ea300dbfb84fe16de0b7d9"

@ -9,7 +9,8 @@ build = "build.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
elefren = "0.20.1" #elefren = "0.20.1"
elefren = { path = "../elefren-fork" }
log = "0.4.8" log = "0.4.8"
env_logger = "0.7.0" env_logger = "0.7.0"
serde = "1.0.101" serde = "1.0.101"

@ -10,7 +10,7 @@ const SOFTWARE_NAME: &str = env!("CARGO_PKG_NAME");
/// 3rd-party libraries that produce log spam - we set these to a fixed higher level /// 3rd-party libraries that produce log spam - we set these to a fixed higher level
/// to allow using e.g. TRACE without drowing our custom messages /// to allow using e.g. TRACE without drowing our custom messages
const SPAMMY_LIBS: [&str; 5] = ["tokio_reactor", "hyper", "reqwest", "mio", "want"]; const SPAMMY_LIBS: [&str; 6] = ["tokio_reactor", "hyper", "reqwest", "mio", "want", "elefren"];
#[derive(SmartDefault,Serialize,Deserialize,Debug)] #[derive(SmartDefault,Serialize,Deserialize,Debug)]
#[serde(default)] #[serde(default)]

@ -7,7 +7,11 @@ extern crate smart_default;
#[macro_use] #[macro_use]
extern crate serde; extern crate serde;
#[macro_use] #[macro_use]
use elefren::{helpers::cli, prelude::*}; use elefren::{
helpers::cli,
prelude::*,
http_send::HttpSender,
};
use failure::Fallible; use failure::Fallible;
use crate::bootstrap::Config; use crate::bootstrap::Config;
@ -16,32 +20,28 @@ use crate::store::Store;
mod bootstrap; mod bootstrap;
mod store; mod store;
type EleRegistratered = elefren::registration::Registered<HttpSender>;
/// Wrapper for the long tuple with Registration state
#[derive(Serialize,Deserialize,Debug)]
struct ElefrenRegistration {
parts: (String, String, String, String, Scopes, bool),
}
const KEY_OAUTH_REGISTRATION: &str = "elefren.registration";
const KEY_OAUTH_SESSION: &str = "elefren.session";
fn main() { fn main() {
let config : Config = bootstrap::init().expect("error init config"); let config : Config = bootstrap::init().expect("error init config");
debug!("Loaded config: {:#?}", config); debug!("Loaded config: {:#?}", config);
let mut store = Store::from_file(&config.store); let mut store = Store::from_file(&config.store);
store.set_autosave(true);
debug!("Store: {:?}", store); let registered = register(&mut store, &config);
//store.put("foo", vec![1,2,3,4]);
let mut v : Vec<u32> = store.get("foo").unwrap();
v.push(v.last().unwrap()+1);
store.put("foo", v);
store.save();
/*
let registration = Registration::new(config.instance) let mastodon = open_session(&mut store, registered);
.client_name("elefren_test")
.build().expect("error register");
let mastodon = cli::authenticate(registration).expect("error auth");
println!( println!(
"{:?}", "{:?}",
@ -49,7 +49,50 @@ fn main() {
.get_home_timeline().expect("error get TL") .get_home_timeline().expect("error get TL")
.items_iter() .items_iter()
.take(100) .take(100)
.collect::<Vec<_>>() .map(|item| {
format!("{}: {}", item.account.acct, item.content)
})
.collect::<Vec<String>>()
); );
*/ }
fn register(store : &mut Store, config : &Config) -> EleRegistratered {
match store.get::<ElefrenRegistration>(KEY_OAUTH_REGISTRATION) {
Some(reg) => {
info!("Loaded registration from store");
EleRegistratered::from_parts(
// this sucks
&reg.parts.0, &reg.parts.1, &reg.parts.2, &reg.parts.3, reg.parts.4, reg.parts.5
)
}
None => {
info!("Creating a new registration");
let registered = Registration::new(&config.instance)
.client_name("manabu")
.build().expect("error register");
store.put(KEY_OAUTH_REGISTRATION, ElefrenRegistration { parts : registered.clone().into_parts() });
registered
}
}
}
fn open_session(store : &mut Store, registered: EleRegistratered) -> Mastodon<HttpSender> {
match store.get::<elefren::Data>(KEY_OAUTH_SESSION) {
Some(data) => {
info!("Reusing saved authorization.");
let cli = Mastodon::from(data);
// TODO check if the session is live, somehow
cli
}
None => {
info!("Creating new authorization.");
let cli = cli::authenticate(registered).expect("error auth");
store.put(KEY_OAUTH_SESSION, cli.data.clone());
cli
}
}
} }

@ -164,7 +164,10 @@ impl Store {
.map(ToOwned::to_owned) .map(ToOwned::to_owned)
.map(serde_json::from_value) .map(serde_json::from_value)
.transpose() .transpose()
.unwrap_or(None) .unwrap_or_else(|e| {
error!("Error deserializing: {}", e);
None
})
} }
/// Get an item, or a default value. /// Get an item, or a default value.
@ -184,6 +187,27 @@ impl Store {
self.get(key).unwrap_or_else(f) self.get(key).unwrap_or_else(f)
} }
/// Assign an item to a string key.
/// If the key was previously occupied, the old value is returned.
pub fn replace<ID, T>(&mut self, key: ID, value: T) -> Option<T>
where ID: Into<String>, T: Serialize + DeserializeOwned
{
let rv = self.items
.insert(key.into(), serde_json::to_value(value).unwrap())
.map(serde_json::from_value)
.transpose()
.unwrap_or_else(|e| {
error!("Error deserializing: {}", e);
None
});
if self.autosave {
let _ = self.save();
}
rv
}
/// Get an item using a string key, removing it from the store. /// Get an item using a string key, removing it from the store.
/// If no item was stored with this key, then None is returned. /// If no item was stored with this key, then None is returned.
pub fn take<T: DeserializeOwned>(&mut self, key: &str) -> Option<T> pub fn take<T: DeserializeOwned>(&mut self, key: &str) -> Option<T>
@ -224,23 +248,5 @@ impl Store {
let _ = self.save(); let _ = self.save();
} }
} }
/// Assign an item to a string key.
/// If the key was previously occupied, the old value is returned.
pub fn replace<ID, T>(&mut self, key: ID, value: T) -> Option<T>
where ID: Into<String>, T: Serialize + DeserializeOwned
{
let rv = self.items
.insert(key.into(), serde_json::to_value(value).unwrap())
.map(serde_json::from_value)
.transpose()
.unwrap_or(None);
if self.autosave {
let _ = self.save();
}
rv
}
} }

Loading…
Cancel
Save