Skip to content

Commit

Permalink
0.2.0: Join futures instead of running it separately
Browse files Browse the repository at this point in the history
  • Loading branch information
DoumanAsh committed Oct 30, 2017
1 parent a8296ed commit a48e275
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 27 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "fie"
version = "0.1.0"
version = "0.2.0"
authors = ["Douman <[email protected]>"]
repository = "https://github.com/DoumanAsh/fie"
description = "Small and cute twitter app."
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,18 @@ Use [example](fie.toml) as reference.
## Usage

```
fie 0.1.0
fie 0.2.0
Douman <[email protected]>
Small and cute twitter app.
USAGE:
fie.exe [SUBCOMMAND]
fie.exe [FLAGS] [SUBCOMMAND]
FLAGS:
--gab Use gab.ai. By default all social medias are used unless flag is specified.
-h, --help Prints help information
--twitter Use Twitter. By default all social medias are used unless flag is specified.
-V, --version Prints version information
SUBCOMMANDS:
Expand Down
25 changes: 18 additions & 7 deletions src/api/gab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ mod hyper {
pub use ::hyper::client::{HttpConnector, FutureResponse};
pub use ::hyper_tls::{HttpsConnector};
}

use ::futures::future;
use ::hyper::mime;

use ::serde_json;
Expand All @@ -14,7 +14,10 @@ use ::tokio_core::reactor::{

use super::common;
use ::config;
use ::utils::Image;
use ::utils::{
empty_future_job,
Image
};

const POST_URL: &'static str = "https://gab.ai/posts";
const IMAGES_URL: &'static str = "https://gab.ai/api/media-attachments/images";
Expand Down Expand Up @@ -137,12 +140,20 @@ impl Client {
self.hyper.request(req)
}

pub fn handle_post(response: hyper::Response) -> Result<(), String> {
if response.status() != hyper::StatusCode::Ok {
return Err(format!("Failed to post. Status: {}", response.status()));
pub fn handle_post(result: Result<hyper::Response, String>) -> future::FutureResult<(), ()> {
println!(">>>Gab:");
match result {
Ok(response) => {
if response.status() != hyper::StatusCode::Ok {
println!("Failed to post. Status: {}", response.status());
}
else {
println!("OK");
}
}
Err(error) => println!("{}", error)
}

println!("OK");
Ok(())
empty_future_job()
}
}
17 changes: 13 additions & 4 deletions src/api/twitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,18 @@ use ::egg_mode::{
tweet,
media
};

use ::futures::future;
use ::tokio_core::reactor::{
Handle
};

use super::common;
use ::config;

use ::utils::Image;
use ::utils::{
empty_future_job,
Image
};

///Twitter client.
pub struct Client {
Expand Down Expand Up @@ -58,7 +61,13 @@ impl Client {
tweet::DraftTweet::new(&message).media_ids(images).send(&self.token, &self.handle)
}

pub fn handle_post(response: Response<tweet::Tweet>) -> Result<(), String> {
Ok(println!("OK(id={})", response.response.id))
pub fn handle_post(result: Result<Response<tweet::Tweet>, String>) -> future::FutureResult<(), ()> {
println!(">>>Twitter:");
match result {
Ok(rsp) => println!("OK(id={})", rsp.response.id),
Err(error) => println!("{}", error)
}

empty_future_job()
}
}
33 changes: 21 additions & 12 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,36 +33,45 @@ fn run() -> Result<i32, String> {

match args.command {
cli::Commands::Post(message, tags, None) => {
//TODO: Find a better way to schedule futures.
//Boxing requires allocations and dynamic dispatch after all.
//But using Handle::spawn() has restrictions on lifetimes which needs to be worked out
//somehow
let mut jobs: Vec<Box<Future<Item=(), Error=()>>> = vec![];
if args.flags.gab {
println!(">>>Gab:");
tokio_core.run(gab.post(&message, &tags).map_err(error_formatter!("Cannot post.")).and_then(api::gab::Client::handle_post))?;
let gab_post = gab.post(&message, &tags).map_err(error_formatter!("Cannot post.")).then(api::gab::Client::handle_post);
jobs.push(Box::new(gab_post))
}
if args.flags.twitter {
println!(">>>Twitter:");
tokio_core.run(twitter.post(&message, &tags).map_err(error_formatter!("Cannot tweet.")).and_then(api::twitter::Client::handle_post))?;
let tweet = twitter.post(&message, &tags).map_err(error_formatter!("Cannot tweet.")).then(api::twitter::Client::handle_post);
jobs.push(Box::new(tweet))
}

tokio_core.run(futures::future::join_all(jobs)).unwrap();
},
cli::Commands::Post(message, tags, Some(image)) => {
let mut jobs: Vec<Box<Future<Item=(), Error=()>>> = vec![];
let image = utils::open_image(image).map_err(error_formatter!("Cannot open image!"))?;
if args.flags.gab {
println!(">>>Gab:");
let gab_post = gab.upload_image(&image).map_err(error_formatter!("Cannot upload image."))
.and_then(handle_bad_hyper_response!("Cannot upload image."))
.and_then(|response| response.body().concat2().map_err(error_formatter!("Cannot read image upload's response")))
.and_then(move |body| serde_json::from_slice(&body).map_err(error_formatter!("Cannot parse image upload's response")))
.and_then(|body| serde_json::from_slice(&body).map_err(error_formatter!("Cannot parse image upload's response")))
.and_then(|response: api::gab::payload::UploadResponse| gab.post_w_images(&message, &tags, &[response.id]).map_err(error_formatter!("Cannot post.")))
.and_then(api::gab::Client::handle_post);
tokio_core.run(gab_post)?;
.then(api::gab::Client::handle_post);
jobs.push(Box::new(gab_post))
}
if args.flags.twitter {
println!(">>>Twitter:");
let tweet = twitter.upload_image(&image).map_err(error_formatter!("Cannot upload image."))
.and_then(|rsp| twitter.post_w_images(&message, &tags, &[rsp.response.id]).map_err(error_formatter!("Cannot tweet.")))
.and_then(api::twitter::Client::handle_post);
tokio_core.run(tweet)?;
.then(api::twitter::Client::handle_post);
jobs.push(Box::new(tweet))
}

tokio_core.run(futures::future::join_all(jobs)).unwrap();
}
}
};


Ok(0)
}
Expand Down
6 changes: 5 additions & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use self::io::{
BufReader,
Read
};

use ::futures::future;
use ::mime_guess::{
Mime,
guess_mime_type
Expand Down Expand Up @@ -64,3 +64,7 @@ pub fn get_config() -> PathBuf {

result
}

pub fn empty_future_job() -> future::FutureResult<(), ()> {
future::ok(())
}

0 comments on commit a48e275

Please sign in to comment.