Compare commits

..

No commits in common. '176bde9d016137ca918dd2f9992707c8f1185429' and '80e0fce32a0f1971b89719abc330c3961a426833' have entirely different histories.

  1. 21
      src/bootstrap.rs
  2. 88
      src/ele.rs
  3. 127
      src/main.rs
  4. 18
      src/store.rs

@ -1,9 +1,8 @@
//! Application start-up code handling CLI args, logging, config file load etc
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
use failure::Fallible; use failure::Fallible;
use crate::Config; use serde::Deserialize;
use serde::Serialize;
const CONFIG_FILE: &str = "manabu.toml"; const CONFIG_FILE: &str = "manabu.toml";
@ -13,11 +12,20 @@ const SOFTWARE_NAME: &str = env!("CARGO_PKG_NAME");
/// 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; 6] = ["tokio_reactor", "hyper", "reqwest", "mio", "want", "elefren"]; const SPAMMY_LIBS: [&str; 6] = ["tokio_reactor", "hyper", "reqwest", "mio", "want", "elefren"];
const LOG_LEVELS: [&str; 5] = ["error", "warn", "info", "debug", "trace"]; #[derive(SmartDefault,Serialize,Deserialize,Debug)]
#[serde(default)]
pub struct Config {
#[default="info"]
logging: String,
pub instance: String,
#[default="manabu_store.json"]
pub store: String,
}
const LOG_LEVELS: [&str; 5] = ["error", "warn", "info", "debug", "trace"];
/// Load the shared config file /// Load the shared config file
pub fn load_config(file: &str) -> Fallible<Config> { fn load_config(file: &str) -> Fallible<Config> {
let mut file = File::open(file)?; let mut file = File::open(file)?;
let mut buf = String::new(); let mut buf = String::new();
@ -33,8 +41,7 @@ pub fn load_config(file: &str) -> Fallible<Config> {
Ok(config) Ok(config)
} }
/// Boot up the application. Initializes common stuff and returns the loaded config. pub(crate) fn init() -> Fallible<Config> {
pub fn handle_cli_args_and_load_config() -> Fallible<Config> {
let version = format!("{}, built from {}", env!("CARGO_PKG_VERSION"), env!("GIT_REV")); let version = format!("{}, built from {}", env!("CARGO_PKG_VERSION"), env!("GIT_REV"));
let argv = let argv =
clap::App::new(SOFTWARE_NAME) clap::App::new(SOFTWARE_NAME)

@ -1,88 +0,0 @@
//! Mastodon API types and functions building on elefren
use serde::Deserialize;
use serde::Serialize;
use crate::store::Store;
use crate::Config;
use elefren::{Registration, Mastodon};
use elefren::http_send::HttpSender;
use elefren::helpers::cli;
use elefren::scopes::Scopes;
use std::str::FromStr;
use failure::Fallible;
const KEY_OAUTH_REGISTRATION: &str = "oauth.registration";
const KEY_OAUTH_SESSION: &str = "oauth.session";
pub type EleRegistratered = elefren::registration::Registered<HttpSender>;
pub type EleSession = elefren::Mastodon<HttpSender>;
pub type EleStreamSocket = websocket::sync::Client<native_tls::TlsStream<std::net::TcpStream>>;
/// Wrapper for the long tuple with Registration state
#[derive(Serialize,Deserialize,Debug)]
pub struct ElefrenRegistration {
pub parts: (String, String, String, String, Scopes, bool),
}
/// Register "app" in the server software
pub 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(&format!("https://{}", config.instance))
.client_name("manabu")
.scopes(Scopes::from_str("read write").expect("err parse scopes"))
.build().expect("error register");
store.put(KEY_OAUTH_REGISTRATION, ElefrenRegistration { parts : registered.clone().into_parts() });
registered
}
}
}
/// Open mastodon API session (get access token)
pub fn open_session(store : &mut Store, registered: EleRegistratered) -> EleSession {
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
}
}
}
/// Open streaming api websocket
pub fn open_stream_websocket(session : &EleSession, stream_name : &str) -> Fallible<EleStreamSocket> {
let connector = native_tls::TlsConnector::new()?;
let hostname = &session.data.base[session.data.base.find("://").unwrap()+3..];
let url = format!("wss://{host}/api/v1/streaming/?stream={sname}&access_token={token}",
host=hostname,
sname=stream_name,
token=session.data.token);
debug!("WS url = {}", &url);
Ok(websocket::ClientBuilder::new(&url)
.expect("Error create ClientBuilder")
.connect_secure(Some(connector))?)
}

@ -6,85 +6,120 @@ extern crate failure;
extern crate smart_default; extern crate smart_default;
#[macro_use] #[macro_use]
extern crate serde; extern crate serde;
#[macro_use]
use elefren::{
helpers::cli,
prelude::*,
entities::prelude::*,
http_send::HttpSender,
};
use failure::Fallible;
use crate::bootstrap::Config;
use crate::store::Store;
use websocket::{OwnedMessage}; use native_tls::TlsConnector;
use std::thread; use std::io::{Read, Write};
use std::net::TcpStream;
use websocket::OwnedMessage;
mod bootstrap; mod bootstrap;
mod store; mod store;
mod ele;
use crate::bootstrap::handle_cli_args_and_load_config; type EleRegistratered = elefren::registration::Registered<HttpSender>;
use crate::store::Store; /// Wrapper for the long tuple with Registration state
use crate::ele::{EleSession, EleStreamSocket}; #[derive(Serialize,Deserialize,Debug)]
use std::time::Duration; struct ElefrenRegistration {
parts: (String, String, String, String, Scopes, bool),
#[derive(SmartDefault,Serialize,Deserialize,Debug)]
#[serde(default)]
pub struct Config {
/// Logging level to use (can be increased using -v flags)
#[default="info"]
pub logging: String,
/// Instance domain name, e.g. example.com
pub instance: String,
/// File to use for session storage
#[default="manabu_store.json"]
pub store: String,
} }
const KEY_OAUTH_REGISTRATION: &str = "elefren.registration";
const KEY_OAUTH_SESSION: &str = "elefren.session";
fn main() { fn main() {
let config : Config = handle_cli_args_and_load_config().expect("error init"); 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); store.set_autosave(true);
store.set_pretty_print(true);
let registered = ele::register(&mut store, &config); let registered = register(&mut store, &config);
let session = ele::open_session(&mut store, registered); let client = open_session(&mut store, registered);
debug!("Listening to events"); debug!("Listening to events");
let m_session = session.clone(); let connector = TlsConnector::new().unwrap();
let handle = thread::spawn(move || handle_stream(m_session));
let _ = handle.join();
}
fn handle_stream(session : EleSession) -> ! {
loop {
debug!("Trying to open websocket");
match ele::open_stream_websocket(&session, "user") { use websocket::ClientBuilder;
Ok(socket) => process_incoming_events(socket),
Err(e) => error!("Error opening socket: {}", e)
}
debug!("Delay before reconnecting..."); let url = format!("wss://{host}/api/v1/streaming/?stream=user&access_token={token}", host=config.instance, token=client.data.token);
thread::sleep(Duration::from_secs(10)); debug!("WS url = {}", &url);
} let mut client = ClientBuilder::new(&url)
} .expect("Error create ClientBuilder")
.connect_secure(Some(connector))
.expect("Error connect to wss");
fn process_incoming_events(mut socket : EleStreamSocket) { for m in client.incoming_messages() {
'listen: for m in socket.incoming_messages() {
match m { match m {
Ok(OwnedMessage::Text(text)) => { Ok(OwnedMessage::Text(text)) => {
debug!("Got msg: {}", text); debug!("Got msg: {}", text);
}, },
Ok(OwnedMessage::Close(_text)) => { Ok(OwnedMessage::Close(text)) => {
debug!("Close"); debug!("Close");
break 'listen; break;
}, },
Ok(any) => { Ok(any) => {
debug!("Unhandled msg: {:?}", any); debug!("Unhandled msg: {:?}", any);
} }
Err(e) => { Err(e) => {
error!("Error reading from socket: {}", e); error!("{}", e);
break 'listen; break;
}, },
} }
} }
info!("Exit.");
}
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(&format!("https://{}", 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
}
}
} }

@ -1,7 +1,3 @@
#![allow(unused)]
//! JSON store
use std::borrow::Cow; use std::borrow::Cow;
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
@ -22,7 +18,6 @@ use std::fmt::{self, Display, Formatter};
pub struct Store { pub struct Store {
path: Option<PathBuf>, path: Option<PathBuf>,
autosave: bool, autosave: bool,
prettysave: bool,
items: Map<String, serde_json::Value>, items: Map<String, serde_json::Value>,
} }
@ -31,7 +26,6 @@ impl Default for Store {
Self { Self {
path: None, path: None,
autosave: false, autosave: false,
prettysave: false,
items: Map::new() items: Map::new()
} }
} }
@ -88,7 +82,6 @@ impl Store {
let mut store = Store { let mut store = Store {
path: Some(path.as_ref().into()), path: Some(path.as_ref().into()),
autosave: false, autosave: false,
prettysave: false,
items: Map::new(), items: Map::new(),
}; };
@ -99,11 +92,6 @@ impl Store {
store store
} }
/// Set pretty print option to use when saved
pub fn set_pretty_print(&mut self, pretty : bool) {
self.prettysave = pretty;
}
/// Set auto-save option - save on each mutation. /// Set auto-save option - save on each mutation.
pub fn set_autosave(&mut self, autosave: bool) { pub fn set_autosave(&mut self, autosave: bool) {
self.autosave = autosave; self.autosave = autosave;
@ -154,11 +142,7 @@ impl Store {
/// Save the map to a custom file path. /// Save the map to a custom file path.
pub fn save_to<P: AsRef<Path>>(&self, path: P) -> Result<()> { pub fn save_to<P: AsRef<Path>>(&self, path: P) -> Result<()> {
let as_str = (if self.prettysave { let as_str = serde_json::to_string(&self.items).unwrap();
serde_json::to_string_pretty(&self.items)
} else {
serde_json::to_string(&self.items)
}).unwrap();
let mut file = File::create(path)?; let mut file = File::create(path)?;
file.write(as_str.as_bytes())?; file.write(as_str.as_bytes())?;

Loading…
Cancel
Save