mod.rs 14.7 KB
Newer Older
1 2
extern crate url;

3
use globals;
4
use std::sync::{Arc, Mutex, Condvar};
5 6 7 8 9 10 11 12 13
use std::thread;
use self::url::Url;
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc::channel;
use std::sync::mpsc::RecvError;

use error::Error;

use util::build_url;
14
use util::json_q;
15 16 17 18 19 20 21 22 23
use cache::CacheMap;

mod types;
mod register;
mod user;
mod room;
mod sync;
mod media;
mod directory;
24
mod stickers;
25 26 27 28 29 30 31

pub use self::types::BKResponse;
pub use self::types::BKCommand;

pub use self::types::Backend;
pub use self::types::BackendData;

32 33
pub use self::types::RoomType;

34 35 36 37 38 39 40

impl Backend {
    pub fn new(tx: Sender<BKResponse>) -> Backend {
        let data = BackendData {
            user_id: String::from("Guest"),
            access_token: String::from(""),
            server_url: String::from("https://matrix.org"),
41 42 43
            scalar_token: None,
            scalar_url: String::from("https://scalar.vector.im"),
            sticker_widget: None,
44 45 46 47 48 49 50 51 52
            since: String::from(""),
            rooms_since: String::from(""),
            join_to_room: String::from(""),
        };
        Backend {
            tx: tx,
            internal_tx: None,
            data: Arc::new(Mutex::new(data)),
            user_info_cache: CacheMap::new().timeout(60*60),
53
            limit_threads: Arc::new((Mutex::new(0u8), Condvar::new())),
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
        }
    }

    fn get_base_url(&self) -> Result<Url, Error> {
        let s = self.data.lock().unwrap().server_url.clone();
        let url = Url::parse(&s)?;
        Ok(url)
    }

    fn url(&self, path: &str, params: Vec<(&str, String)>) -> Result<Url, Error> {
        let base = self.get_base_url()?;
        let tk = self.data.lock().unwrap().access_token.clone();

        let mut params2 = params.to_vec();
        params2.push(("access_token", tk.clone()));

        client_url!(&base, path, params2)
    }

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    fn get_scalar_token(&self) -> Result<String, Error> {
        let s = self.data.lock().unwrap().scalar_url.clone();
        let uid = self.data.lock().unwrap().user_id.clone();

        let url = self.url(&format!("user/{}/openid/request_token", uid), vec![])?;
        let js = json_q("post", &url, &json!({}), globals::TIMEOUT)?;

        let vurl = Url::parse(&format!("{}/api/register", s))?;
        let js = json_q("post", &vurl, &js, globals::TIMEOUT)?;

        match js["scalar_token"].as_str() {
            Some(st) => {
                self.data.lock().unwrap().scalar_token = Some(st.to_string());
                Ok(st.to_string())
            }
            None => Err(Error::BackendError),
        }
    }

    fn vurl(&self, path: &str, params: Vec<(&str, String)>) -> Result<Url, Error> {
        let s = self.data.lock().unwrap().scalar_url.clone();
        let base = Url::parse(&s)?;
        let token = self.data.lock().unwrap().scalar_token.clone();
        let tk = match token {
            None => self.get_scalar_token()?,
            Some(t) => t.clone(),
        };

        let mut params2 = params.to_vec();
        params2.push(("scalar_token", tk));

        scalar_url!(&base, path, params2)
    }

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    pub fn run(mut self) -> Sender<BKCommand> {
        let (apptx, rx): (Sender<BKCommand>, Receiver<BKCommand>) = channel();

        self.internal_tx = Some(apptx.clone());
        thread::spawn(move || loop {
            let cmd = rx.recv();
            if !self.command_recv(cmd) {
                break;
            }
        });

        apptx
    }

    pub fn command_recv(&mut self, cmd: Result<BKCommand, RecvError>) -> bool {
        let tx = self.tx.clone();

        match cmd {
            // Register module

            Ok(BKCommand::Login(user, passwd, server)) => {
                let r = register::login(self, user, passwd, server);
                bkerror!(r, tx, BKResponse::LoginError);
            }
            Ok(BKCommand::Logout) => {
                let r = register::logout(self);
                bkerror!(r, tx, BKResponse::LogoutError);
            }
            Ok(BKCommand::Register(user, passwd, server)) => {
                let r = register::register(self, user, passwd, server);
                bkerror!(r, tx, BKResponse::LoginError);
            }
            Ok(BKCommand::Guest(server)) => {
                let r = register::guest(self, server);
                bkerror!(r, tx, BKResponse::GuestLoginError);
            }
143 144 145 146
            Ok(BKCommand::SetToken(token, uid, server)) => {
                let r = register::set_token(self, token, uid, server);
                bkerror!(r, tx, BKResponse::LoginError);
            }
147 148 149 150 151 152 153

            // User module

            Ok(BKCommand::GetUsername) => {
                let r = user::get_username(self);
                bkerror!(r, tx, BKResponse::UserNameError);
            }
154 155 156 157
            Ok(BKCommand::SetUserName(name)) => {
                let r = user::set_username(self, name);
                bkerror!(r, tx, BKResponse::SetUserNameError);
            }
158 159 160 161
            Ok(BKCommand::GetThreePID) => {
                let r = user::get_threepid(self);
                bkerror!(r, tx, BKResponse::GetThreePIDError);
            }
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
            Ok(BKCommand::GetTokenEmail(identity, email, client_secret)) => {
                let r = user::get_email_token(self, identity, email, client_secret);
                bkerror!(r, tx, BKResponse::GetTokenEmailError);
            }
            Ok(BKCommand::GetTokenPhone(identity, phone, client_secret)) => {
                let r = user::get_phone_token(self, identity, phone, client_secret);
                bkerror!(r, tx, BKResponse::GetTokenEmailError);
            }
            Ok(BKCommand::SubmitPhoneToken(identity, client_secret, sid, token)) => {
                let r = user::submit_phone_token(self, identity, client_secret, sid, token);
                bkerror!(r, tx, BKResponse::SubmitPhoneTokenError);
            }
            Ok(BKCommand::AddThreePID(identity, client_secret, sid)) => {
                let r = user::add_threepid(self, identity, client_secret, sid);
                bkerror!(r, tx, BKResponse::AddThreePIDError);
            }
            Ok(BKCommand::DeleteThreePID(medium, address)) => {
                let r = user::delete_three_pid(self, medium, address);
                bkerror!(r, tx, BKResponse::DeleteThreePIDError);
            }
182 183 184 185 186 187 188 189
            Ok(BKCommand::ChangePassword(username, old_password, new_password)) => {
                let r = user::change_password(self, username, old_password, new_password);
                bkerror!(r, tx, BKResponse::ChangePasswordError);
            }
            Ok(BKCommand::AccountDestruction(username, password, flag)) => {
                let r = user::account_destruction(self, username, password, flag);
                bkerror!(r, tx, BKResponse::AccountDestructionError);
            }
190 191 192 193
            Ok(BKCommand::GetAvatar) => {
                let r = user::get_avatar(self);
                bkerror!(r, tx, BKResponse::AvatarError);
            }
194 195 196 197
            Ok(BKCommand::SetUserAvatar(file)) => {
                let r = user::set_user_avatar(self, file);
                bkerror!(r, tx, BKResponse::SetUserAvatarError);
            }
198 199 200 201
            Ok(BKCommand::GetAvatarAsync(member, ctx)) => {
                let r = user::get_avatar_async(self, member, ctx);
                bkerror!(r, tx, BKResponse::CommandError);
            }
202 203 204 205
            Ok(BKCommand::GetUserInfoAsync(sender, ctx)) => {
                let r = user::get_user_info_async(self, &sender, ctx);
                bkerror!(r, tx, BKResponse::CommandError);
            }
206 207 208 209
            Ok(BKCommand::UserSearch(term)) => {
                let r = user::search(self, term);
                bkerror!(r, tx, BKResponse::CommandError);
            }
210 211 212 213 214 215 216 217 218 219 220 221 222 223

            // Sync module

            Ok(BKCommand::Sync) => {
                let r = sync::sync(self);
                bkerror!(r, tx, BKResponse::SyncError);
            }
            Ok(BKCommand::SyncForced) => {
                let r = sync::force_sync(self);
                bkerror!(r, tx, BKResponse::SyncError);
            }

            // Room module

224 225 226 227
            Ok(BKCommand::GetRoomMembers(room)) => {
                let r = room::get_room_members(self, room);
                bkerror!(r, tx, BKResponse::RoomMembersError);
            }
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
            Ok(BKCommand::GetRoomMessages(room)) => {
                let r = room::get_room_messages(self, room);
                bkerror!(r, tx, BKResponse::RoomMessagesError);
            }
            Ok(BKCommand::GetMessageContext(message)) => {
                let r = room::get_message_context(self, message);
                bkerror!(r, tx, BKResponse::RoomMessagesError);
            }
            Ok(BKCommand::SendMsg(msg)) => {
                let r = room::send_msg(self, msg);
                bkerror!(r, tx, BKResponse::SendMsgError);
            }
            Ok(BKCommand::SetRoom(room)) => {
                let r = room::set_room(self, room);
                bkerror!(r, tx, BKResponse::SetRoomError);
            }
            Ok(BKCommand::GetRoomAvatar(room)) => {
                let r = room::get_room_avatar(self, room);
                bkerror!(r, tx, BKResponse::GetRoomAvatarError);
            }
            Ok(BKCommand::JoinRoom(roomid)) => {
                let r = room::join_room(self, roomid);
                bkerror!(r, tx, BKResponse::JoinRoomError);
            }
            Ok(BKCommand::LeaveRoom(roomid)) => {
                let r = room::leave_room(self, roomid);
                bkerror!(r, tx, BKResponse::LeaveRoomError);
            }
            Ok(BKCommand::MarkAsRead(roomid, evid)) => {
                let r = room::mark_as_read(self, roomid, evid);
                bkerror!(r, tx, BKResponse::MarkAsReadError);
            }
            Ok(BKCommand::SetRoomName(roomid, name)) => {
                let r = room::set_room_name(self, roomid, name);
                bkerror!(r, tx, BKResponse::SetRoomNameError);
            }
            Ok(BKCommand::SetRoomTopic(roomid, topic)) => {
                let r = room::set_room_topic(self, roomid, topic);
                bkerror!(r, tx, BKResponse::SetRoomTopicError);
            }
            Ok(BKCommand::SetRoomAvatar(roomid, fname)) => {
                let r = room::set_room_avatar(self, roomid, fname);
                bkerror!(r, tx, BKResponse::SetRoomAvatarError);
            }
272 273
            Ok(BKCommand::AttachFile(msg)) => {
                let r = room::attach_file(self, msg);
274 275
                bkerror!(r, tx, BKResponse::AttachFileError);
            }
276 277 278 279 280
            Ok(BKCommand::NewRoom(name, privacy, internalid)) => {
                let r = room::new_room(self, name, privacy, internalid.clone());
                if let Err(e) = r {
                    tx.send(BKResponse::NewRoomError(e, internalid)).unwrap();
                }
281
            }
282 283 284 285 286 287
            Ok(BKCommand::DirectChat(user, internalid)) => {
                let r = room::direct_chat(self, user, internalid.clone());
                if let Err(e) = r {
                    tx.send(BKResponse::NewRoomError(e, internalid)).unwrap();
                }
            }
288 289 290 291
            Ok(BKCommand::AddToFav(roomid, tofav)) => {
                let r = room::add_to_fav(self, roomid, tofav);
                bkerror!(r, tx, BKResponse::AddToFavError);
            }
292 293 294 295
            Ok(BKCommand::Search(roomid, term)) => {
                let r = room::search(self, roomid, term);
                bkerror!(r, tx, BKResponse::SearchError);
            }
296 297 298 299 300 301 302 303
            Ok(BKCommand::AcceptInv(roomid)) => {
                let r = room::join_room(self, roomid);
                bkerror!(r, tx, BKResponse::AcceptInvError);
            }
            Ok(BKCommand::RejectInv(roomid)) => {
                let r = room::leave_room(self, roomid);
                bkerror!(r, tx, BKResponse::RejectInvError);
            }
304 305 306 307
            Ok(BKCommand::Invite(room, userid)) => {
                let r = room::invite(self, room, userid);
                bkerror!(r, tx, BKResponse::InviteError);
            }
308 309 310 311 312 313 314

            // Media module

            Ok(BKCommand::GetThumbAsync(media, ctx)) => {
                let r = media::get_thumb_async(self, media, ctx);
                bkerror!(r, tx, BKResponse::CommandError);
            }
315 316 317 318
            Ok(BKCommand::GetMediaAsync(media, ctx)) => {
                let r = media::get_media_async(self, media, ctx);
                bkerror!(r, tx, BKResponse::CommandError);
            }
319 320 321 322
            Ok(BKCommand::GetMediaListAsync(roomid, first_media_id, prev_batch, ctx)) => {
                let r = media::get_media_list_async(self, roomid, first_media_id, prev_batch, ctx);
                bkerror!(r, tx, BKResponse::CommandError);
            }
323 324 325 326
            Ok(BKCommand::GetMedia(media)) => {
                let r = media::get_media(self, media);
                bkerror!(r, tx, BKResponse::CommandError);
            }
327 328 329 330
            Ok(BKCommand::GetMediaUrl(media, ctx)) => {
                let r = media::get_media_url(self, media.to_string(), ctx);
                bkerror!(r, tx, BKResponse::CommandError);
            }
331 332 333 334
            Ok(BKCommand::GetFileAsync(url, ctx)) => {
                let r = media::get_file_async(url, ctx);
                bkerror!(r, tx, BKResponse::CommandError);
            }
335 336 337 338 339 340 341

            // Directory module

            Ok(BKCommand::DirectoryProtocols) => {
                let r = directory::protocols(self);
                bkerror!(r, tx, BKResponse::DirectoryError);
            }
342
            Ok(BKCommand::DirectorySearch(dhs, dq, dtp, more)) => {
343 344 345 346 347
                let hs = match dhs {
                    ref a if a.is_empty() => None,
                    b => Some(b),
                };

348 349 350 351 352
                let q = match dq {
                    ref a if a.is_empty() => None,
                    b => Some(b),
                };

353 354 355 356 357 358
                let tp = match dtp {
                    ref a if a.is_empty() => None,
                    b => Some(b),
                };

                let r = directory::room_search(self, hs, q, tp, more);
359 360 361
                bkerror!(r, tx, BKResponse::DirectoryError);
            }

362 363 364 365 366 367
            // Stickers module

            Ok(BKCommand::ListStickers) => {
                let r = stickers::list(self);
                bkerror!(r, tx, BKResponse::StickersError);
            }
368 369 370 371
            Ok(BKCommand::SendSticker(room, sticker)) => {
                let r = stickers::send(self, room, &sticker);
                bkerror!(r, tx, BKResponse::StickersError);
            }
372 373 374 375
            Ok(BKCommand::PurchaseSticker(group)) => {
                let r = stickers::purchase(self, &group);
                bkerror!(r, tx, BKResponse::StickersError);
            }
376

377 378
            // Internal commands
            Ok(BKCommand::ShutDown) => {
379
                tx.send(BKResponse::ShutDown).unwrap();
380 381 382 383 384 385 386 387 388 389
                return false;
            }
            Err(_) => {
                return false;
            }
        };

        true
    }
}