1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use reqwest::{blocking::multipart, blocking::Client, blocking::Response, Result};
use std::env;
use std::io::prelude::*;

pub fn upload(filepath: &str) -> Result<Response> {
    let home_path = dirs::home_dir()
        .and_then(|a| Some(a.join(".streamable")))
        .unwrap();

    dotenv::from_path(home_path.as_path()).unwrap();

    let username = env::var("STREAMABLE_USERNAME").unwrap();
    let password = env::var("STREAMABLE_PASSWORD").unwrap();

    let endpoint = "https://api.streamable.com/upload";

    let form = multipart::Form::new()
        .file("file", std::path::Path::new(filepath))
        .unwrap_or_else(|e| panic!("Error: {}", e));

    let client = Client::new();
    let resp = client
        .post(endpoint)
        .basic_auth(username, Some(password))
        .multipart(form)
        .send()
        .unwrap_or_else(|e| panic!("Error: {}", e));

    // dbg!(&resp);

    Ok(resp)
}

pub fn get_username_password() -> (String, String) {
    println!("Please input Your username and password");
    let username = rpassword::read_password_from_tty(Some("Username: ")).unwrap();
    let password = rpassword::read_password_from_tty(Some("Password: ")).unwrap();
    (username, password)
}

pub fn setup() -> Result<()> {
    let env = get_username_password();

    let text = format!(
        "STREAMABLE_USERNAME={}\nSTREAMABLE_PASSWORD={}",
        env.0, env.1
    );

    let home_path = dirs::home_dir().unwrap();
    let config_path = home_path.join(".streamable");
    std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .open(config_path)
        .expect("can not create config file")
        .write_all(text.as_bytes())
        .unwrap();

    println!("saved your login params in {}", home_path.to_str().unwrap());
    Ok(())
}

#[cfg(test)]
mod tests {
    use crate::upload;

    #[test]
    fn streamable_upload() {
        let result = upload("./media/sample.mp4");
        dbg!(&result);

        match result {
            Ok(v) => println!("{:?}", v),
            Err(e) => panic!("Error: {}", e),
        }
    }
}