util.rs 27.3 KB
Newer Older
1
extern crate glib;
2 3 4 5 6 7 8
extern crate url;
extern crate reqwest;
extern crate regex;
extern crate serde_json;
extern crate chrono;
extern crate time;
extern crate cairo;
Daniel García Moreno's avatar
Daniel García Moreno committed
9 10
extern crate gdk;
extern crate gdk_pixbuf;
11 12
extern crate mime;
extern crate tree_magic;
13 14 15
extern crate unicode_segmentation;

use self::unicode_segmentation::UnicodeSegmentation;
16

Daniel García Moreno's avatar
Daniel García Moreno committed
17
use self::gdk_pixbuf::Pixbuf;
18
use self::gdk_pixbuf::PixbufExt;
Daniel García Moreno's avatar
Daniel García Moreno committed
19 20
use self::gdk::ContextExt;

21 22 23 24 25 26
use self::regex::Regex;

use self::serde_json::Value as JsonValue;

use self::url::Url;
use std::io::Read;
27
use std::path::Path;
28
use std::path::PathBuf;
29 30

use std::fs::File;
31
use std::fs::create_dir_all;
32 33
use std::io::prelude::*;

34
use std::collections::HashSet;
35 36 37 38 39
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use self::chrono::prelude::*;
use self::time::Duration;
40
use std::time::Duration as StdDuration;
41 42 43

use error::Error;
use types::Message;
44
use types::Room;
45
use types::Event;
46
use types::Member;
47

48
use self::reqwest::header::ContentType;
49
use self::mime::Mime;
50

51 52
use globals;

53

54
#[allow(dead_code)]
55 56 57 58 59 60 61 62 63 64 65 66
pub enum AvatarMode {
    Rect,
    Circle,
}


#[macro_export]
macro_rules! identicon {
    ($userid: expr, $name: expr) => { draw_identicon($userid, $name, AvatarMode::Circle) }
}


67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
// from https://stackoverflow.com/a/43992218/1592377
#[macro_export]
macro_rules! clone {
    (@param _) => ( _ );
    (@param $x:ident) => ( $x );
    ($($n:ident),+ => move || $body:expr) => (
        {
            $( let $n = $n.clone(); )+
            move || $body
        }
    );
    ($($n:ident),+ => move |$($p:tt),+| $body:expr) => (
        {
            $( let $n = $n.clone(); )+
            move |$(clone!(@param $p),)+| $body
        }
    );
}
85

86 87 88 89 90 91 92
#[macro_export]
macro_rules! strn {
    ($p: expr) => (
        String::from($p)
    );
}

93 94 95 96 97 98 99 100 101 102 103 104 105 106
#[macro_export]
macro_rules! client_url {
    ($b: expr, $path: expr, $params: expr) => (
        build_url($b, &format!("/_matrix/client/r0/{}", $path), $params)
    )
}

#[macro_export]
macro_rules! media_url {
    ($b: expr, $path: expr, $params: expr) => (
        build_url($b, &format!("/_matrix/media/r0/{}", $path), $params)
    )
}

107 108 109 110 111 112 113 114 115 116
#[macro_export]
macro_rules! derror {
    ($from: path, $to: path) => {
        impl From<$from> for Error {
            fn from(_: $from) -> Error {
                $to
            }
        }
    };
}
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 143 144 145 146 147 148 149 150

#[macro_export]
macro_rules! bkerror {
    ($result: ident, $tx: ident, $type: expr) => {
        if let Err(e) = $result {
            $tx.send($type(e)).unwrap();
        }
    }
}

#[macro_export]
macro_rules! get {
    ($url: expr, $attrs: expr, $okcb: expr, $errcb: expr) => {
        query!("get", $url, $attrs, $okcb, $errcb)
    };
    ($url: expr, $okcb: expr, $errcb: expr) => {
        query!("get", $url, $okcb, $errcb)
    };
}

#[macro_export]
macro_rules! post {
    ($url: expr, $attrs: expr, $okcb: expr, $errcb: expr) => {
        query!("post", $url, $attrs, $okcb, $errcb)
    };
    ($url: expr, $okcb: expr, $errcb: expr) => {
        query!("post", $url, $okcb, $errcb)
    };
}

#[macro_export]
macro_rules! query {
    ($method: expr, $url: expr, $attrs: expr, $okcb: expr, $errcb: expr) => {
        thread::spawn(move || {
151
            let js = json_q($method, $url, $attrs, globals::TIMEOUT);
152 153 154 155 156 157 158 159 160 161 162 163

            match js {
                Ok(r) => {
                    $okcb(r)
                },
                Err(err) => {
                    $errcb(err)
                }
            }
        });
    };
    ($method: expr, $url: expr, $okcb: expr, $errcb: expr) => {
164
        let attrs = json!(null);
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
        query!($method, $url, &attrs, $okcb, $errcb)
    };
}

#[allow(unused_macros)]
#[macro_export]
macro_rules! media {
    ($base: expr, $url: expr, $dest: expr) => {
        dw_media($base, $url, false, $dest, 0, 0)
    };
    ($base: expr, $url: expr) => {
        dw_media($base, $url, false, None, 0, 0)
    };
}

#[macro_export]
macro_rules! thumb {
    ($base: expr, $url: expr) => {
        dw_media($base, $url, true, None, 64, 64)
    };
    ($base: expr, $url: expr, $size: expr) => {
        dw_media($base, $url, true, None, $size, $size)
    };
    ($base: expr, $url: expr, $w: expr, $h: expr) => {
        dw_media($base, $url, true, None, $w, $h)
    };
}

193 194 195 196 197 198 199 200 201 202 203
pub fn evc(events: &JsonValue, t: &str, field: &str) -> String {
    if let Some(arr) = events.as_array() {
        return match arr.iter().find(|x| x["type"] == t) {
            Some(js) => String::from(js["content"][field].as_str().unwrap_or("")),
            None => String::new(),
        };
    }

    String::new()
}

204
pub fn get_rooms_from_json(r: &JsonValue, userid: &str, baseu: &Url) -> Result<Vec<Room>, Error> {
205 206 207
    let rooms = &r["rooms"];

    let join = rooms["join"].as_object().ok_or(Error::BackendError)?;
208
    let leave = rooms["leave"].as_object().ok_or(Error::BackendError)?;
209
    let invite = rooms["invite"].as_object().ok_or(Error::BackendError)?;
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    let global_account = &r["account_data"]["events"].as_array();

    // getting the list of direct rooms
    let mut direct: HashSet<String> = HashSet::new();
    match global_account.unwrap_or(&vec![]).iter().find(|x| x["type"] == "m.direct") {
        Some(js) => {
            if let Some(content) = js["content"].as_object() {
                for i in content.keys() {
                    for room in content[i].as_array().unwrap_or(&vec![]) {
                        if let Some(roomid) = room.as_str() {
                            direct.insert(roomid.to_string());
                        }
                    }
                }
            }
        },
        None => {}
    };
228

229
    let mut rooms: Vec<Room> = vec![];
230 231
    for k in join.keys() {
        let room = join.get(k).ok_or(Error::BackendError)?;
232
        let stevents = &room["state"]["events"];
233
        let timeline = &room["timeline"];
234
        let dataevs = &room["account_data"]["events"];
235
        let name = calculate_room_name(stevents, userid)?;
236
        let mut r = Room::new(k.clone(), Some(name));
237

238 239 240
        r.avatar = Some(evc(stevents, "m.room.avatar", "url"));
        r.alias = Some(evc(stevents, "m.room.canonical_alias", "alias"));
        r.topic = Some(evc(stevents, "m.room.topic", "topic"));
241
        r.direct = direct.contains(k);
242
        r.notifications = room["unread_notifications"]["notification_count"]
243 244
            .as_i64()
            .unwrap_or(0) as i32;
245 246 247
        r.highlight = room["unread_notifications"]["highlight_count"]
            .as_i64()
            .unwrap_or(0) as i32;
248

249 250
        for ev in dataevs.as_array() {
            for tag in ev.iter().filter(|x| x["type"] == "m.tag") {
251
                if let Some(_) = tag["content"]["tags"]["m.favourite"].as_object() {
252 253 254 255 256
                    r.fav = true;
                }
            }
        }

257 258 259 260
        for ev in timeline["events"].as_array()
            .unwrap_or(&vec![]).iter()
            .filter(|x| x["type"] == "m.room.message") {

261 262 263 264
            let msg = parse_room_message(baseu, k.clone(), ev);
            r.messages.push(msg);
        }

265 266 267 268 269 270 271 272 273 274 275
        let mevents = stevents.as_array().unwrap()
            .iter()
            .filter(|x| x["type"] == "m.room.member");

        for ev in mevents {
            let member = parse_room_member(ev);
            if let Some(m) = member {
                r.members.insert(m.uid.clone(), m.clone());
            }
        }

276
        rooms.push(r);
277 278
    }

279
    // left rooms
280 281 282 283 284 285
    for k in leave.keys() {
        let mut r = Room::new(k.clone(), None);
        r.left = true;
        rooms.push(r);
    }

286 287 288 289 290 291 292 293 294 295 296
    // invitations
    for k in invite.keys() {
        let room = invite.get(k).ok_or(Error::BackendError)?;
        let stevents = &room["invite_state"]["events"];
        let name = calculate_room_name(stevents, userid)?;
        let mut r = Room::new(k.clone(), Some(name));
        r.inv = true;

        r.avatar = Some(evc(stevents, "m.room.avatar", "url"));
        r.alias = Some(evc(stevents, "m.room.canonical_alias", "alias"));
        r.topic = Some(evc(stevents, "m.room.topic", "topic"));
297
        r.direct = direct.contains(k);
298

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
        if let Some(arr) = stevents.as_array() {
            if let Some(ev) = arr.iter()
                                 .find(|x| x["membership"] == "invite" && x["state_key"] == userid) {
                if let Ok((alias, avatar)) = get_user_avatar(baseu, ev["sender"].as_str().unwrap_or_default()) {
                    r.inv_sender = Some(
                        Member {
                            alias: Some(alias),
                            avatar: Some(avatar),
                            uid: strn!(userid),
                        }
                    );
                }
            }
        }

314 315 316
        rooms.push(r);
    }

317
    Ok(rooms)
318 319
}

320 321 322 323 324
pub fn get_rooms_timeline_from_json(baseu: &Url,
                                    r: &JsonValue,
                                    tk: String,
                                    prev_batch: String)
                                    -> Result<Vec<Message>, Error> {
325 326 327 328 329 330
    let rooms = &r["rooms"];
    let join = rooms["join"].as_object().ok_or(Error::BackendError)?;

    let mut msgs: Vec<Message> = vec![];
    for k in join.keys() {
        let room = join.get(k).ok_or(Error::BackendError)?;
331 332 333 334 335 336 337 338 339 340 341 342 343 344

        if let (Some(true), Some(pb)) = (room["timeline"]["limited"].as_bool(),
                                         room["timeline"]["prev_batch"].as_str()) {
            let pbs = pb.to_string();
            let fill_the_gap = fill_room_gap(baseu,
                                             tk.clone(),
                                             k.clone(),
                                             prev_batch.clone(),
                                             pbs.clone())?;
            for m in fill_the_gap {
                msgs.push(m);
            }
        }

345 346
        let timeline = room["timeline"]["events"].as_array();
        if timeline.is_none() {
347
            continue;
348 349
        }

350 351 352
        let events = timeline.unwrap()
            .iter()
            .filter(|x| x["type"] == "m.room.message");
353 354 355 356 357 358 359 360 361 362

        for ev in events {
            let msg = parse_room_message(baseu, k.clone(), ev);
            msgs.push(msg);
        }
    }

    Ok(msgs)
}

363
pub fn get_rooms_notifies_from_json(r: &JsonValue) -> Result<Vec<(String, i32, i32)>, Error> {
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    let rooms = &r["rooms"];
    let join = rooms["join"].as_object().ok_or(Error::BackendError)?;

    let mut out: Vec<(String, i32, i32)> = vec![];
    for k in join.keys() {
        let room = join.get(k).ok_or(Error::BackendError)?;
        let n = room["unread_notifications"]["notification_count"]
            .as_i64()
            .unwrap_or(0) as i32;
        let h = room["unread_notifications"]["highlight_count"]
            .as_i64()
            .unwrap_or(0) as i32;

        out.push((k.clone(), n, h));
    }

    Ok(out)
}

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
pub fn parse_sync_events(r: &JsonValue) -> Result<Vec<Event>, Error> {
    let rooms = &r["rooms"];
    let join = rooms["join"].as_object().ok_or(Error::BackendError)?;

    let mut evs: Vec<Event> = vec![];
    for k in join.keys() {
        let room = join.get(k).ok_or(Error::BackendError)?;
        let timeline = room["timeline"]["events"].as_array();
        if timeline.is_none() {
            return Ok(evs);
        }

        let events = timeline.unwrap()
            .iter()
            .filter(|x| x["type"] != "m.room.message");

        for ev in events {
400
            //println!("ev: {:#?}", ev);
401 402 403 404 405 406 407 408 409 410 411 412 413
            evs.push(Event {
                room: k.clone(),
                sender: strn!(ev["sender"].as_str().unwrap_or("")),
                content: ev["content"].clone(),
                stype: strn!(ev["type"].as_str().unwrap_or("")),
                id: strn!(ev["id"].as_str().unwrap_or("")),
            });
        }
    }

    Ok(evs)
}

414
pub fn get_media(url: &str) -> Result<Vec<u8>, Error> {
415 416
    let client = reqwest::Client::new();
    let mut conn = client.get(url);
417 418 419 420 421 422 423 424
    let mut res = conn.send()?;

    let mut buffer = Vec::new();
    res.read_to_end(&mut buffer)?;

    Ok(buffer)
}

425
pub fn put_media(url: &str, file: Vec<u8>) -> Result<JsonValue, Error> {
426 427
    let client = reqwest::Client::new();
    let mut conn = client.post(url);
428 429
    let mime: Mime = (&tree_magic::from_u8(&file)).parse().unwrap();

430
    conn.body(file);
431 432

    conn.header(ContentType(mime));
433 434 435 436 437 438 439 440 441

    let mut res = conn.send()?;

    match res.json() {
        Ok(js) => Ok(js),
        Err(_) => Err(Error::BackendError),
    }
}

442 443 444 445 446 447 448
pub fn dw_media(base: &Url,
                url: &str,
                thumb: bool,
                dest: Option<&str>,
                w: i32,
                h: i32)
                -> Result<String, Error> {
449 450 451 452 453
    let re = Regex::new(r"mxc://(?P<server>[^/]+)/(?P<media>.+)")?;
    let caps = re.captures(url).ok_or(Error::BackendError)?;
    let server = String::from(&caps["server"]);
    let media = String::from(&caps["media"]);

454 455
    let mut params: Vec<(&str, String)> = vec![];
    let path: String;
456 457

    if thumb {
458 459 460 461
        params.push(("width", format!("{}", w)));
        params.push(("height", format!("{}", h)));
        params.push(("method", strn!("scale")));
        path = format!("thumbnail/{}/{}", server, media);
462
    } else {
463
        path = format!("download/{}/{}", server, media);
464 465
    }

466
    let url = media_url!(base, &path, params)?;
467

468
    let fname = match dest {
469
        None => { cache_path(&media)?  }
470
        Some(d) => String::from(d),
471 472
    };

473 474 475
    let pathname = fname.clone();
    let p = Path::new(&pathname);
    if p.is_file() {
476 477 478 479 480
        if dest.is_none() {
            return Ok(fname);
        }

        let moddate = p.metadata()?.modified()?;
481 482
        // one minute cached
        if moddate.elapsed()?.as_secs() < 60 {
483 484
            return Ok(fname);
        }
485 486
    }

487 488 489 490 491 492 493 494 495 496 497 498 499
    let mut file = File::create(&fname)?;
    let buffer = get_media(url.as_str())?;
    file.write_all(&buffer)?;

    Ok(fname)
}

pub fn age_to_datetime(age: i64) -> DateTime<Local> {
    let now = Local::now();
    let diff = Duration::seconds(age / 1000);
    now - diff
}

500
pub fn json_q(method: &str, url: &Url, attrs: &JsonValue, timeout: u64) -> Result<JsonValue, Error> {
501
    let mut clientb = reqwest::ClientBuilder::new();
502 503 504 505
    let client = match timeout {
        0 => clientb.build()?,
        n => clientb.timeout(StdDuration::from_secs(n)).build()?
    };
506 507

    let mut conn = match method {
508 509 510 511
        "post" => client.post(url.as_str()),
        "put" => client.put(url.as_str()),
        "delete" => client.delete(url.as_str()),
        _ => client.get(url.as_str()),
512 513
    };

514 515 516 517 518
    if !attrs.is_null() {
        conn.json(attrs);
    }

    let mut res = conn.send()?;
519 520 521 522 523

    //let mut content = String::new();
    //res.read_to_string(&mut content);
    //cb(content);

524 525 526 527 528 529 530
    if !res.status().is_success() {
        return match res.json() {
            Ok(js) => Err(Error::MatrixError(js)),
            Err(err) => Err(Error::ReqwestError(err))
        }
    }

531 532 533 534 535 536 537 538 539 540 541 542
    let json: Result<JsonValue, reqwest::Error> = res.json();
    match json {
        Ok(js) => {
            let js2 = js.clone();
            if let Some(error) = js.as_object() {
                if error.contains_key("errcode") {
                    println!("ERROR: {:#?}", js2);
                    return Err(Error::MatrixError(js2));
                }
            }
            Ok(js)
        }
543 544 545 546
        Err(_) => Err(Error::BackendError),
    }
}

547
pub fn get_user_avatar(baseu: &Url, userid: &str) -> Result<(String, String), Error> {
548
    let url = client_url!(baseu, &format!("profile/{}", userid), vec![])?;
549
    let attrs = json!(null);
550

551
    match json_q("get", &url, &attrs, globals::TIMEOUT) {
552
        Ok(js) => {
553
            let name = String::from(js["displayname"].as_str().unwrap_or("@"));
554
            match js["avatar_url"].as_str() {
555 556 557
                Some(url) => {
                    let dest = cache_path(userid)?;
                    let img = dw_media(baseu, &url, true, Some(&dest), 64, 64)?;
558
                    Ok((name.clone(), img))
559
                },
560
                None => Ok((name.clone(), identicon!(userid, name)?)),
561 562
            }
        }
563
        Err(_) => Ok((String::from(userid), identicon!(userid, String::from(&userid[1..2]))?)),
564 565 566 567
    }
}

pub fn get_room_st(base: &Url, tk: &str, roomid: &str) -> Result<JsonValue, Error> {
568
    let url = client_url!(base, &format!("rooms/{}/state", roomid), vec![("access_token", strn!(tk))])?;
569

570
    let attrs = json!(null);
571
    let st = json_q("get", &url, &attrs, globals::TIMEOUT)?;
572 573 574 575 576 577 578 579 580
    Ok(st)
}

pub fn get_room_avatar(base: &Url, tk: &str, userid: &str, roomid: &str) -> Result<String, Error> {
    let st = get_room_st(base, tk, roomid)?;
    let events = st.as_array().ok_or(Error::BackendError)?;

    // we look for members that aren't me
    let filter = |x: &&JsonValue| {
581
        (x["type"] == "m.room.member" && x["content"]["membership"] == "join" &&
582 583 584 585 586 587 588
         x["sender"] != userid)
    };
    let members = events.iter().filter(&filter);
    let mut members2 = events.iter().filter(&filter);

    let m1 = match members2.nth(0) {
        Some(m) => m["content"]["avatar_url"].as_str().unwrap_or(""),
589
        None => "",
590 591 592
    };

    let mut fname = match members.count() {
593
        1 => thumb!(&base, m1).unwrap_or_default(),
594
        _ => String::new(),
595 596 597 598
    };

    if fname.is_empty() {
        let roomname = calculate_room_name(&st, userid)?;
599
        fname = identicon!(roomid, roomname)?;
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
    }

    Ok(fname)
}

struct Color {
    r: i32,
    g: i32,
    b: i32,
}

pub fn calculate_hash<T: Hash>(t: &T) -> u64 {
    let mut s = DefaultHasher::new();
    t.hash(&mut s);
    s.finish()
}

617
pub fn draw_identicon(fname: &str, name: String, mode: AvatarMode) -> Result<String, Error> {
618 619 620 621 622 623 624 625 626 627 628
    let colors = vec![
        Color { r: 69,  g: 189, b: 243, },
        Color { r: 224, g: 143, b: 112, },
        Color { r: 77,  g: 182, b: 172, },
        Color { r: 149, g: 117, b: 205, },
        Color { r: 176, g: 133, b: 94,  },
        Color { r: 240, g: 98,  b: 146, },
        Color { r: 163, g: 211, b: 108, },
        Color { r: 121, g: 134, b: 203, },
        Color { r: 241, g: 185, b: 29,  },
    ];
629

630
    let fname = cache_path(fname)?;
631 632 633 634 635

    let image = cairo::ImageSurface::create(cairo::Format::ARgb32, 40, 40)?;
    let g = cairo::Context::new(&image);

    let c = &colors[calculate_hash(&fname) as usize % colors.len() as usize];
636
    g.set_source_rgba(c.r as f64 / 256., c.g as f64 / 256., c.b as f64 / 256., 1.);
637 638 639 640 641 642 643 644

    match mode {
        AvatarMode::Rect => g.rectangle(0., 0., 40., 40.),
        AvatarMode::Circle => {
            g.arc(20.0, 20.0, 20.0, 0.0, 2.0 * 3.14159);
            g.fill();
        }
    };
645 646 647 648

    g.set_font_size(24.);
    g.set_source_rgb(1.0, 1.0, 1.0);

649 650 651 652 653 654 655 656
    let name = name.to_uppercase();
    let graphs = UnicodeSegmentation::graphemes(name.as_str(), true).collect::<Vec<&str>>();

    let first = match graphs.get(0) {
        Some(f) if *f == "#" && graphs.len() > 1 => graphs.get(1).unwrap().to_string(),
        Some(f) if *f == "@" && graphs.len() > 1 => graphs.get(1).unwrap().to_string(),
        Some(n) => n.to_string(),
        None => String::from("X"),
657 658 659
    };

    let te = g.text_extents(&first);
660 661
    g.move_to(20.0 - te.x_bearing - te.width / 2.0,
              20.0 + te.height / 2.0);
662 663 664 665 666 667 668 669 670 671 672 673 674
    g.show_text(&first);

    let mut buffer = File::create(&fname)?;
    image.write_to_png(&mut buffer)?;

    Ok(fname)
}

pub fn calculate_room_name(roomst: &JsonValue, userid: &str) -> Result<String, Error> {

    // looking for "m.room.name" event
    let events = roomst.as_array().ok_or(Error::BackendError)?;
    if let Some(name) = events.iter().find(|x| x["type"] == "m.room.name") {
675
        if let Some(name) = name["content"]["name"].as_str() {
676 677 678
            if !name.to_string().is_empty() {
                return Ok(name.to_string());
            }
679
        }
680
    }
681

682 683
    // looking for "m.room.canonical_alias" event
    if let Some(name) = events.iter().find(|x| x["type"] == "m.room.canonical_alias") {
684 685 686
        if let Some(name) = name["content"]["alias"].as_str() {
            return Ok(name.to_string());
        }
687 688 689 690
    }

    // we look for members that aren't me
    let filter = |x: &&JsonValue| {
691 692 693 694 695 696
        (x["type"] == "m.room.member" &&
         (
          (x["content"]["membership"] == "join" && x["sender"] != userid) ||
          (x["content"]["membership"] == "invite" && x["state_key"] != userid)
         )
        )
697 698 699 700 701
    };
    let members = events.iter().filter(&filter);
    let mut members2 = events.iter().filter(&filter);

    let m1 = match members2.nth(0) {
702 703 704 705
        Some(m) => {
            let sender = m["sender"].as_str().unwrap_or("NONAMED");
            m["content"]["displayname"].as_str().unwrap_or(sender)
        },
706
        None => "",
707 708
    };
    let m2 = match members2.nth(1) {
709 710 711 712
        Some(m) => {
            let sender = m["sender"].as_str().unwrap_or("NONAMED");
            m["content"]["displayname"].as_str().unwrap_or(sender)
        },
713
        None => "",
714 715 716 717 718 719
    };

    let name = match members.count() {
        0 => String::from("EMPTY ROOM"),
        1 => String::from(m1),
        2 => format!("{} and {}", m1, m2),
720
        _ => format!("{} and Others", m1),
721 722 723 724 725 726 727
    };

    Ok(name)
}

pub fn parse_room_message(baseu: &Url, roomid: String, msg: &JsonValue) -> Message {
    let sender = msg["sender"].as_str().unwrap_or("");
728 729 730 731 732
    let mut age = msg["age"].as_i64().unwrap_or(0);
    if age == 0 {
        age = msg["unsigned"]["age"].as_i64().unwrap_or(0);
    }

733
    let id = msg["event_id"].as_str().unwrap_or("");
734 735 736 737 738 739 740 741 742

    let c = &msg["content"];
    let mtype = c["msgtype"].as_str().unwrap_or("");
    let body = c["body"].as_str().unwrap_or("");

    let mut url = String::new();
    let mut thumb = String::new();

    match mtype {
743
        "m.image" | "m.file" | "m.video" | "m.audio" => {
744
            url = String::from(c["url"].as_str().unwrap_or(""));
745 746 747 748 749
            let mut t = String::from(c["info"]["thumbnail_url"].as_str().unwrap_or(""));
            if t.is_empty() && !url.is_empty() {
                t = url.clone();
            }
            thumb = media!(baseu, &t).unwrap_or(String::from(""));
750 751
        }
        _ => {}
752 753 754 755 756 757 758 759
    };

    Message {
        sender: String::from(sender),
        mtype: String::from(mtype),
        body: String::from(body),
        date: age_to_datetime(age),
        room: roomid.clone(),
760 761 762
        url: Some(url),
        thumb: Some(thumb),
        id: Some(String::from(id)),
763 764
    }
}
765

766 767 768 769 770
/// Recursive function that tries to get at least @get Messages for the room.
///
/// The @limit is the first "limit" param in the GET request.
/// The @end param is used as "from" param in the GET request, so we'll get
/// messages before that.
771 772 773 774 775 776 777
pub fn get_initial_room_messages(baseu: &Url,
                                 tk: String,
                                 roomid: String,
                                 get: usize,
                                 limit: i32,
                                 end: Option<String>)
                                 -> Result<(Vec<Message>, String, String), Error> {
778

779 780 781 782
    let mut ms: Vec<Message> = vec![];
    let mut nstart;
    let mut nend;

783 784
    let mut params = vec![
        ("dir", strn!("b")),
785
        ("limit", format!("{}", limit)),
786 787 788
        ("access_token", tk.clone()),
    ];

789
    match end {
790
        Some(ref e) => { params.push(("from", e.clone())) }
791
        None => {}
792 793
    };

794
    let path = format!("rooms/{}/messages", roomid);
795
    let url = client_url!(baseu, &path, params)?;
796

797
    let r = json_q("get", &url, &json!(null), globals::TIMEOUT)?;
798 799
    nend = String::from(r["end"].as_str().unwrap_or(""));
    nstart = String::from(r["start"].as_str().unwrap_or(""));
800

801 802 803 804
    let array = r["chunk"].as_array();
    if array.is_none() || array.unwrap().len() == 0 {
        return Ok((ms, nstart, nend));
    }
805

806 807 808 809
    for msg in array.unwrap().iter().rev() {
        if msg["type"].as_str().unwrap_or("") != "m.room.message" {
            continue;
        }
810

811 812 813
        let m = parse_room_message(&baseu, roomid.clone(), msg);
        ms.push(m);
    }
814

815
    if ms.len() < get {
816
        let (more, s, e) =
817
            get_initial_room_messages(baseu, tk, roomid, get, limit * 2, Some(nend))?;
818 819 820 821
        nstart = s;
        nend = e;
        for m in more.iter().rev() {
            ms.insert(0, m.clone());
822 823
        }
    }
824

825
    Ok((ms, nstart, nend))
826
}
827

828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
/// Recursive function that tries to get all messages in a room from a batch id to a batch id,
/// following the response pagination
pub fn fill_room_gap(baseu: &Url,
                     tk: String,
                     roomid: String,
                     from: String,
                     to: String)
                     -> Result<Vec<Message>, Error> {

    let mut ms: Vec<Message> = vec![];
    let nend;

    let mut params = vec![
        ("dir", strn!("f")),
        ("limit", format!("{}", globals::PAGE_LIMIT)),
        ("access_token", tk.clone()),
    ];

    params.push(("from", from.clone()));
    params.push(("to", to.clone()));

    let path = format!("rooms/{}/messages", roomid);
    let url = client_url!(baseu, &path, params)?;

    let r = json_q("get", &url, &json!(null), globals::TIMEOUT)?;
    nend = String::from(r["end"].as_str().unwrap_or(""));

    let array = r["chunk"].as_array();
    if array.is_none() || array.unwrap().len() == 0 {
        return Ok(ms);
    }

    for msg in array.unwrap().iter() {
        if msg["type"].as_str().unwrap_or("") != "m.room.message" {
            continue;
        }

        let m = parse_room_message(&baseu, roomid.clone(), msg);
        ms.push(m);
    }

    // loading more until no more messages
    let more = fill_room_gap(baseu, tk, roomid, nend, to)?;
    for m in more.iter() {
        ms.insert(0, m.clone());
    }

    Ok(ms)
}

878
pub fn build_url(base: &Url, path: &str, params: Vec<(&str, String)>) -> Result<Url, Error> {
879
    let mut url = base.join(path)?;
880 881 882 883 884 885 886 887 888 889 890

    {
        let mut query = url.query_pairs_mut();
        query.clear();
        for (k, v) in params {
            query.append_pair(k, &v);
        }
    }

    Ok(url)
}
Daniel García Moreno's avatar
Daniel García Moreno committed
891

892
pub fn circle_image(fname: String) -> Result<String, Error> {
893 894
    use std::f64::consts::PI;

895 896
    let pb = Pixbuf::new_from_file_at_scale(&fname, 40, -1, true)?;
    let image = cairo::ImageSurface::create(cairo::Format::ARgb32, 40, 40)?;
897
    let g = cairo::Context::new(&image);
898
    g.set_antialias(cairo::Antialias::Best);
899 900
    let hpos: f64 = (40.0 - (pb.get_height()) as f64) / 2.0;
    g.set_source_pixbuf(&pb, 0.0, hpos);
901

902
    g.arc(20.0, 20.0, 20.0, 0.0, 2.0 * PI);
903 904 905 906 907 908 909 910 911
    g.clip();

    g.paint();

    let mut buffer = File::create(&fname)?;
    image.write_to_png(&mut buffer)?;

    Ok(fname)
}
912 913

pub fn cache_path(name: &str) -> Result<String, Error> {
914 915 916 917 918 919
    let mut path = match glib::get_user_cache_dir() {
        Some(path) => path,
        None => PathBuf::from("/tmp"),
    };

    path.push("fractal");
920 921 922 923 924

    if !path.exists() {
        create_dir_all(&path)?;
    }

925
    path.push(name);
926

927
    Ok(path.into_os_string().into_string()?)
928
}
929 930 931 932 933 934 935 936

pub fn get_user_avatar_img(baseu: &Url, userid: String, alias: String, avatar: String) -> Result<String, Error> {
    if avatar.is_empty() {
        return identicon!(&userid, alias);
    }

    let dest = cache_path(&userid)?;
    let img = dw_media(baseu, &avatar, true, Some(&dest), 64, 64)?;
937
    Ok(img)
938 939 940 941 942 943 944
}

pub fn parse_room_member(msg: &JsonValue) -> Option<Member> {
    let sender = msg["sender"].as_str().unwrap_or("");

    let c = &msg["content"];

945 946 947 948 949
    let membership = c["membership"].as_str();
    if membership.is_none() || membership.unwrap() != "join" {
        return None;
    }

950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
    let displayname = match c["displayname"].as_str() {
        None => None,
        Some(s) => Some(strn!(s))
    };
    let avatar_url = match c["avatar_url"].as_str() {
        None => None,
        Some(s) => Some(strn!(s))
    };

    Some(Member {
        uid: strn!(sender),
        alias: displayname,
        avatar: avatar_url,
    })
}