Skip to content

Commit

Permalink
Work in progress: Attach file
Browse files Browse the repository at this point in the history
  • Loading branch information
danigm committed Oct 1, 2017
1 parent 0548bf7 commit 233727f
Show file tree
Hide file tree
Showing 5 changed files with 111 additions and 3 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ chrono = "0.4.0"
gdk-pixbuf = "0.2.0"
gio = "0.2.0"
glib = "0.3.1"
mime = "0.3.4"
pango = "0.2.0"
regex = "0.2.2"
reqwest = "0.7.3"
Expand All @@ -16,6 +17,7 @@ serde = "1.0.15"
serde_derive = "1.0.15"
serde_json = "1.0.3"
time = "0.1.38"
tree_magic = "0.2.0"
url = "1.5.1"
xdg = "2.1.0"

Expand Down
1 change: 0 additions & 1 deletion TODO
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
Fixs:
* Add mentions tab with a search of the username
* Ignore launched threads when changing room...
* Sort rooms by last message or fav?

Expand Down
38 changes: 38 additions & 0 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,32 @@ impl AppOp {
self.backend.send(BKCommand::SendMsg(m)).unwrap();
}

pub fn attach_file(&mut self) {
let window: gtk::ApplicationWindow = self.gtk_builder
.get_object("main_window")
.expect("Can't find main_window in ui file.");
let dialog = gtk::FileChooserDialog::new(None,
Some(&window),
gtk::FileChooserAction::Open);

let btn = dialog.add_button("Select", 1);
btn.get_style_context().unwrap().add_class("suggested-action");

let backend = self.backend.clone();
let room = self.active_room.clone();
dialog.connect_response(move |dialog, resp| {
if resp == 1 {
if let Some(fname) = dialog.get_filename() {
let f = strn!(fname.to_str().unwrap_or(""));
backend.send(BKCommand::AttachFile(room.clone(), f)).unwrap();
}
}
dialog.destroy();
});

dialog.show();
}

pub fn hide_members(&self) {
self.gtk_builder
.get_object::<gtk::Stack>("sidebar_stack")
Expand Down Expand Up @@ -1078,6 +1104,7 @@ impl App {
self.connect_msg_scroll();

self.connect_send();
self.connect_attach();

self.connect_directory();
self.connect_room_config();
Expand Down Expand Up @@ -1215,6 +1242,17 @@ impl App {
});
}

fn connect_attach(&self) {
let attach_button: gtk::ToolButton = self.gtk_builder
.get_object("attach_button")
.expect("Couldn't find attach_button in ui file.");

let op = self.op.clone();
attach_button.connect_clicked(move |_| {
op.lock().unwrap().attach_file();
});
}

fn connect_user_button(&self) {
// Set up user popover
let user_button: gtk::Button = self.gtk_builder
Expand Down
64 changes: 64 additions & 0 deletions src/backend.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
extern crate url;
extern crate serde_json;
extern crate tree_magic;
extern crate chrono;

use self::chrono::prelude::*;

use self::serde_json::Value as JsonValue;

use std::path::Path;
use std::sync::{Arc, Mutex};
use std::thread;
use self::url::Url;
Expand Down Expand Up @@ -65,6 +69,7 @@ pub enum BKCommand {
SetRoomName(String, String),
SetRoomTopic(String, String),
SetRoomAvatar(String, String),
AttachFile(String, String),
}

#[derive(Debug)]
Expand Down Expand Up @@ -93,6 +98,7 @@ pub enum BKResponse {
RoomName(String, String),
RoomTopic(String, String),
Media(String),
AttachedFile(String),

//errors
UserNameError(Error),
Expand All @@ -116,6 +122,7 @@ pub enum BKResponse {
SetRoomAvatarError(Error),
GetRoomAvatarError(Error),
MediaError(Error),
AttachFileError(Error),
}


Expand Down Expand Up @@ -257,6 +264,10 @@ impl Backend {
let r = self.set_room_avatar(roomid, fname);
bkerror!(r, tx, BKResponse::SetRoomAvatarError);
}
Ok(BKCommand::AttachFile(roomid, fname)) => {
let r = self.attach_file(roomid, fname);
bkerror!(r, tx, BKResponse::AttachFileError);
}
Ok(BKCommand::ShutDown) => {
return false;
}
Expand Down Expand Up @@ -906,6 +917,59 @@ impl Backend {
},
);

Ok(())
}

pub fn attach_file(&self, roomid: String, path: String) -> Result<(), Error> {
let baseu = self.get_base_url()?;
let tk = self.data.lock().unwrap().access_token.clone();
let params = vec![("access_token", tk.clone())];
let mediaurl = media_url!(&baseu, "upload", params)?;

let mut file = File::open(&path)?;
let mut contents: Vec<u8> = vec![];
file.read_to_end(&mut contents)?;

let p: &Path = Path::new(&path);
let mime = tree_magic::from_filepath(p);
let now = Local::now();
let userid = self.data.lock().unwrap().user_id.clone();

let mtype = match mime.as_ref() {
"image/gif" => "m.image",
"image/png" => "m.image",
"image/jpeg" => "m.image",
"image/jpg" => "m.image",
_ => "m.file"
};

let m = Message {
sender: userid,
mtype: strn!(mtype),
body: strn!(path.split("/").last().unwrap_or(&path)),
room: roomid.clone(),
date: now,
thumb: String::from(""),
url: String::from(""),
id: String::from(""),
};

let tx = self.tx.clone();
thread::spawn(
move || {
match put_media(mediaurl.as_str(), contents) {
Err(err) => {
tx.send(BKResponse::AttachFileError(err)).unwrap();
}
Ok(js) => {
let uri = js["content_uri"].as_str().unwrap_or("");
// TODO: don't send this to the client, send it internally to chain with
// send_msg
tx.send(BKResponse::AttachedFile(strn!(uri))).unwrap();
}
};
},
);

Ok(())
}
Expand Down
9 changes: 7 additions & 2 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ extern crate serde_json;
extern crate chrono;
extern crate time;
extern crate cairo;
extern crate mime;
extern crate tree_magic;

use self::regex::Regex;

Expand All @@ -31,6 +33,7 @@ use types::Room;
use types::Event;

use self::reqwest::header::ContentType;
use self::mime::Mime;


// from https://stackoverflow.com/a/43992218/1592377
Expand Down Expand Up @@ -265,11 +268,13 @@ pub fn get_media(url: &str) -> Result<Vec<u8>, Error> {
}

pub fn put_media(url: &str, file: Vec<u8>) -> Result<JsonValue, Error> {

let client = reqwest::Client::new()?;
let mut conn = client.post(url)?;
let mime: Mime = (&tree_magic::from_u8(&file)).parse().unwrap();

conn.body(file);
conn.header(ContentType::png());

conn.header(ContentType(mime));

let mut res = conn.send()?;

Expand Down

0 comments on commit 233727f

Please sign in to comment.