aboutsummaryrefslogtreecommitdiff
path: root/client/src/lib.rs
blob: a4d0b0172074fe22c6779e96d0d59c779d7f6f8e (plain)
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
use reqwest::Client;
use serde_json::json;
use std::time::Duration;

pub struct Instance {
    pub host: String,
    pub tls: bool,
}
pub struct Session(pub String);

impl Instance {
    pub fn base(&self) -> String {
        format!(
            "{}://{}",
            if self.tls { "https" } else { "http" },
            self.host
        )
    }
}
impl Session {
    pub fn session_param(&self) -> String {
        format!("session={}", self.0)
    }
}

pub fn stream(
    instance: &Instance,
    session: &Session,
    id: &str,
    tracks: &[usize],
    webm: bool,
) -> String {
    format!(
        "{}/n/{}/stream?tracks={}&webm={}&{}",
        instance.base(),
        id,
        tracks
            .iter()
            .map(|v| format!("{v}"))
            .collect::<Vec<_>>()
            .join(","),
        if webm { "1" } else { "0" },
        session.session_param()
    )
}

pub async fn login(
    instance: &Instance,
    username: String,
    password: String,
    expire: Duration,
) -> anyhow::Result<Session> {
    let p = serde_json::to_string(&json!({
        "expire": expire.as_secs(),
        "password": password,
        "username": username,
    }))
    .unwrap();

    let r = Client::builder()
        .build()?
        .post(format!("{}/api/account/login", instance.base()))
        .body(p)
        .send()
        .await?
        .json()
        .await?;

    Ok(Session(r))
}