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
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
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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
193
194
195
use std::{
    sync::Arc,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use anyhow::{bail, Result};
#[cfg(feature = "is_sync")]
use reqwest::blocking::Client;
use reqwest::cookie::Jar;
#[cfg(not(feature = "is_sync"))]
use reqwest::Client;
use serde::{Deserialize, Serialize};
use tracing::info;
use url::Url;

const BASE_URL: &str = "https://spclient.wg.spotify.com";
const COOKIE_DOMAIN: &str = ".spotify.com";
const COOKIE_NAME: &str = "sp_dc";
const TOKEN_URL: &str = "https://open.spotify.com/get_access_token";
const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36";
/* ^ This could be fetched from a list at runtime but I don't suspect this will need to be changed ^ */

lazy_static::lazy_static! {
    static ref COOKIE_URL: Url = format!("https://open{COOKIE_DOMAIN}").parse().unwrap();
}

#[cfg(feature = "browser")]
#[derive(Debug)]
pub enum Browser {
    All,
    Brave,
    Chrome,
    Chromium,
    Edge,
    Firefox,
    InternetExplorer,
    LibreWolf,
    Opera,
    OperaGX,
    #[cfg(target_os = "macos")]
    Safari,
    Vivaldi,
}

#[derive(Debug, Default)]
pub struct SpotifyLyrics {
    auth:   Authorization,
    client: Client,
}

impl SpotifyLyrics {
    /// Manually supply your own cookie
    pub fn from_cookie(cookie: &str) -> Result<Self> {
        let jar = Arc::new(Jar::default());
        jar.add_cookie_str(cookie, &COOKIE_URL);

        let client = Client::builder()
            .cookie_store(true)
            .cookie_provider(jar)
            .user_agent(USER_AGENT)
            .build()?;

        Ok(Self {
            client,
            ..Default::default()
        })
    }

    /// Try to get the cookie from the users web browser
    #[cfg(feature = "browser")]
    pub fn from_browser(browser: Browser) -> Result<Self> {
        use rookie::common::enums::CookieToString;

        let get_cookies = match browser {
            Browser::All => rookie::load,
            Browser::Brave => rookie::brave,
            Browser::Chrome => rookie::chrome,
            Browser::Chromium => rookie::chromium,
            Browser::Edge => rookie::edge,
            Browser::Firefox => rookie::firefox,
            Browser::InternetExplorer => rookie::internet_explorer,
            Browser::LibreWolf => rookie::libre_wolf,
            Browser::Opera => rookie::opera,
            Browser::OperaGX => rookie::opera_gx,
            #[cfg(target_os = "macos")]
            Browser::Safari => rookie::safari,
            Browser::Vivaldi => rookie::vivaldi,
        };

        let domains = Some(vec![COOKIE_DOMAIN]);
        let cookies = get_cookies(domains)?;
        let cookie = cookies
            .into_iter()
            .filter(|cookie| cookie.name == COOKIE_NAME)
            .collect::<Vec<_>>()
            .to_string();

        Self::from_cookie(&cookie)
    }

    #[maybe_async::maybe_async]
    pub async fn refresh_authorization(&mut self) -> Result<()> {
        let response = self.client.get(TOKEN_URL).send().await?;
        self.auth = response.json().await?;

        Ok(())
    }

    #[maybe_async::maybe_async]
    pub async fn get_authorization(&mut self) -> Result<Authorization> {
        let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?;
        let expiration = Duration::from_millis(self.auth.expiration_timestamp_ms);
        if current_time > expiration {
            info!("Refreshing authorization");
            self.refresh_authorization().await?;
        };

        Ok(self.auth.clone())
    }

    #[maybe_async::maybe_async]
    pub async fn get_color_lyrics(&mut self, track_id: &str) -> Result<ColorLyrics> {
        let url = format!("{BASE_URL}/color-lyrics/v2/track/{track_id}?format=json");
        let authorization = self.get_authorization().await?;
        let access_token = format!("Bearer {}", authorization.access_token);
        let response = self
            .client
            .get(url)
            .header("Authorization", access_token)
            .header("App-Platform", "WebPlayer")
            .send()
            .await?;

        let status = response.status();
        if !status.is_success() {
            bail!("Couldn't get color lyrics: {status}")
        };

        Ok(response.json().await?)
    }
}

/* Please feel free to create an issue or pull request to expand as needed */

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Authorization {
    pub client_id: String,
    pub access_token: String,
    #[serde(rename = "accessTokenExpirationTimestampMs")]
    pub expiration_timestamp_ms: u64,
    pub is_anonymous: bool,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ColorLyrics {
    pub lyrics: Lyrics,
    pub colors: Colors,
    pub has_vocal_removal: bool,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Lyrics {
    pub sync_type: String,
    pub lines: Vec<Line>,
    pub provider: String,
    pub provider_lyrics_id: String,
    pub provider_display_name: String,
    pub sync_lyrics_uri: String,
    pub is_dense_typeface: bool,
    // pub alternatives: Vec<Value>,
    pub language: String,
    pub is_rtl_language: bool,
    pub fullscreen_action: String,
    pub show_upsell: bool,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Line {
    pub start_time_ms: String,
    pub words:         String,
    // pub syllables: Vec<Value>,
    pub end_time_ms:   String,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Colors {
    pub background:     i64,
    pub text:           i64,
    pub highlight_text: i64,
}