lavende-core 0.1.4

Core in-process Discord voice connection and playback engine
Documentation
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
pub mod manager {
    use super::{track::AudiomackTrack, utils::build_auth_header};
    use crate::{
        protocol::tracks::{LoadResult, PlaylistData, PlaylistInfo, Track, TrackInfo},
        sources::{SourcePlugin, playable_track::BoxedTrack},
    };
    use async_trait::async_trait;
    use rand::{Rng, distributions::Alphanumeric, thread_rng};
    use regex::Regex;
    use serde_json::Value;
    use std::{
        collections::BTreeMap,
        sync::{Arc, OnceLock},
    };
    use tracing::{error, warn};
    const API_BASE: &str = "https://api.audiomack.com/v1";
    static SONG_REGEX: OnceLock<Regex> = OnceLock::new();
    static ALBUM_REGEX: OnceLock<Regex> = OnceLock::new();
    static PLAYLIST_REGEX: OnceLock<Regex> = OnceLock::new();
    static ARTIST_REGEX: OnceLock<Regex> = OnceLock::new();
    static LIKES_REGEX: OnceLock<Regex> = OnceLock::new();
    pub struct AudiomackSource {
        client: Arc<reqwest::Client>,
        search_limit: usize,
    }
    impl AudiomackSource {
        pub fn new(
            config: Option<crate::config::AudiomackConfig>,
            client: Arc<reqwest::Client>,
        ) -> Result<Self, String> {
            let search_limit = config.map(|c| c.search_limit).unwrap_or(20);
            Ok(Self {
                client,
                search_limit,
            })
        }
        fn generate_nonce(&self) -> String {
            thread_rng()
                .sample_iter(&Alphanumeric)
                .take(32)
                .map(char::from)
                .collect()
        }
        async fn make_request(
            &self,
            method: reqwest::Method,
            endpoint: &str,
            query_params: Option<BTreeMap<String, String>>,
        ) -> Option<Value> {
            let url = format!("{API_BASE}{endpoint}");
            tracing::debug!("Audiomack request: {method} {url} params: {query_params:?}");
            let mut request_builder = self.base_request(self.client.request(method.clone(), &url));
            let nonce = self.generate_nonce();
            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs()
                .to_string();
            let auth_header = build_auth_header(
                method.as_str(),
                &url,
                query_params.as_ref().unwrap_or(&BTreeMap::new()),
                &nonce,
                &timestamp,
            );
            request_builder = request_builder.header("Authorization", auth_header);
            if let Some(qp) = query_params {
                request_builder = request_builder.query(&qp);
            }
            let resp = match request_builder.send().await {
                Ok(r) => r,
                Err(e) => {
                    error!("Audiomack request failed: {e}");
                    return None;
                }
            };
            let status = resp.status();
            let text = match resp.text().await {
                Ok(t) => t,
                Err(e) => {
                    error!("Failed to read Audiomack response text: {e}");
                    return None;
                }
            };
            if !status.is_success() {
                warn!("Audiomack API error status: {status} for endpoint: {endpoint}");
                return None;
            }
            match serde_json::from_str(&text) {
                Ok(v) => Some(v),
                Err(e) => {
                    error!("Failed to parse Audiomack JSON: {e} body: {text}");
                    None
                }
            }
        }
        fn base_request(&self, builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
            builder
            .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36")
            .header("Accept", "application/json")
            .header("Accept-Language", "en-US,en;q=0.9")
            .header("Origin", "https://audiomack.com")
            .header("Referer", "https://audiomack.com/")
            .header("Sec-Fetch-Site", "same-site")
            .header("Sec-Fetch-Mode", "cors")
            .header("Sec-Fetch-Dest", "empty")
            .header("Priority", "u=1, i")
            .header("DNT", "1")
            .header("sec-ch-ua-platform", "\"Windows\"")
        }
        fn parse_track(&self, json: &Value) -> Option<Track> {
            let id_val = json.get("id").or_else(|| json.get("song_id"));
            let id = match id_val {
                Some(Value::String(s)) => s.clone(),
                Some(Value::Number(n)) => n.to_string(),
                _ => {
                    tracing::debug!("Audiomack track missing id: {json:?}");
                    return None;
                }
            };
            let title = json.get("title")?.as_str()?.to_owned();
            let author = json.get("artist")?.as_str()?.to_owned();
            let duration_sec = json
                .get("duration")
                .and_then(|v| {
                    v.as_u64()
                        .or_else(|| v.as_i64().map(|i| i as u64))
                        .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
                })
                .unwrap_or_default();
            let uploader_slug = json
                .pointer("/uploader/url_slug")
                .and_then(|v| v.as_str())
                .or_else(|| json.get("uploader_url_slug").and_then(|v| v.as_str()))
                .unwrap_or("unknown");
            let url_slug = json.get("url_slug")?.as_str()?;
            let uri = Some(format!(
                "https://audiomack.com/{uploader_slug}/song/{url_slug}"
            ));
            let artwork_url = json
                .get("image")
                .and_then(|v| v.as_str())
                .filter(|s| !s.is_empty())
                .map(|s| s.to_owned());
            let isrc = json
                .get("isrc")
                .and_then(|v| v.as_str())
                .filter(|s| !s.is_empty())
                .map(|s| s.to_owned());
            Some(Track::new(TrackInfo {
                identifier: id,
                is_seekable: true,
                author,
                length: duration_sec * 1000,
                is_stream: false,
                position: 0,
                title,
                uri,
                artwork_url,
                isrc,
                source_name: "audiomack".to_owned(),
            }))
        }
        async fn search(&self, query: &str) -> LoadResult {
            let mut params = BTreeMap::new();
            params.insert("q".to_owned(), query.to_owned());
            params.insert("limit".to_owned(), self.search_limit.to_string());
            params.insert("show".to_owned(), "songs".to_owned());
            params.insert("sort".to_owned(), "popular".to_owned());
            let json = match self
                .make_request(reqwest::Method::GET, "/search", Some(params))
                .await
            {
                Some(j) => j,
                None => return LoadResult::Empty {},
            };
            let results = match json.get("results").and_then(|v| v.as_array()) {
                Some(r) => r,
                None => return LoadResult::Empty {},
            };
            let tracks: Vec<_> = results
                .iter()
                .filter_map(|item| self.parse_track(item))
                .collect();
            if tracks.is_empty() {
                LoadResult::Empty {}
            } else {
                LoadResult::Search(tracks)
            }
        }
        async fn get_song(&self, artist: &str, slug: &str) -> LoadResult {
            let endpoint = format!("/music/song/{artist}/{slug}");
            let json = match self
                .make_request(reqwest::Method::GET, &endpoint, None)
                .await
            {
                Some(j) => j,
                None => return LoadResult::Empty {},
            };
            if let Some(track) = json.get("results").and_then(|v| self.parse_track(v)) {
                LoadResult::Track(track)
            } else {
                LoadResult::Empty {}
            }
        }
        async fn get_playlist_items(&self, type_: &str, artist: &str, slug: &str) -> LoadResult {
            let endpoint = if type_ == "playlist" {
                format!("/playlist/{artist}/{slug}")
            } else {
                format!("/music/album/{artist}/{slug}")
            };
            let json = match self
                .make_request(reqwest::Method::GET, &endpoint, None)
                .await
            {
                Some(j) => j,
                None => return LoadResult::Empty {},
            };
            let results = match json.get("results") {
                Some(r) => r,
                None => return LoadResult::Empty {},
            };
            let name = results
                .get("title")
                .and_then(|v| v.as_str())
                .unwrap_or("Unknown")
                .to_owned();
            let tracks: Vec<_> = results
                .get("tracks")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|item| self.parse_track(item))
                        .collect()
                })
                .unwrap_or_default();
            if tracks.is_empty() {
                return LoadResult::Empty {};
            }
            let url = results
                .get("url")
                .and_then(|v| v.as_str())
                .map(|s| format!("https://audiomack.com{s}"))
                .unwrap_or_else(|| format!("https://audiomack.com/{artist}/{type_}/{slug}"));
            LoadResult::Playlist(PlaylistData {
                info: PlaylistInfo {
                    name,
                    selected_track: -1,
                },
                plugin_info: serde_json::json!({
                    "type": type_,
                    "url": url,
                    "artworkUrl": results.get("image").and_then(|v| v.as_str()),
                    "author": results.get("artist").and_then(|v| v.as_str()),
                    "totalTracks": tracks.len()
                }),
                tracks,
            })
        }
        async fn get_artist(&self, artist_slug: &str) -> LoadResult {
            let json = match self
                .make_request(
                    reqwest::Method::GET,
                    &format!("/artist/{artist_slug}"),
                    None,
                )
                .await
            {
                Some(j) => j,
                None => return LoadResult::Empty {},
            };
            let results = match json.get("results") {
                Some(r) => r,
                None => return LoadResult::Empty {},
            };
            let artist_id = results
                .get("id")
                .and_then(|v| {
                    v.as_str()
                        .map(|s| s.to_owned())
                        .or_else(|| v.as_i64().map(|i| i.to_string()))
                })
                .unwrap_or_default();
            if artist_id.is_empty() {
                return LoadResult::Empty {};
            }
            let name = results
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("Artist")
                .to_owned();
            let mut params = BTreeMap::new();
            params.insert("artist_id".to_owned(), artist_id);
            params.insert("limit".to_owned(), "100".to_owned());
            params.insert("sort".to_owned(), "rank".to_owned());
            params.insert("type".to_owned(), "songs".to_owned());
            let tracks_json = match self
                .make_request(reqwest::Method::GET, "/search_artist_content", Some(params))
                .await
            {
                Some(j) => j,
                None => return LoadResult::Empty {},
            };
            let tracks: Vec<_> = tracks_json
                .get("results")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|item| self.parse_track(item))
                        .collect()
                })
                .unwrap_or_default();
            if tracks.is_empty() {
                return LoadResult::Empty {};
            }
            let url = results
                .get("url")
                .and_then(|v| v.as_str())
                .map(|s| format!("https://audiomack.com{s}"))
                .unwrap_or_else(|| format!("https://audiomack.com/{artist_slug}"));
            LoadResult::Playlist(PlaylistData {
                info: PlaylistInfo {
                    name: format!("{name}'s Top Tracks"),
                    selected_track: -1,
                },
                plugin_info: serde_json::json!({
                    "type": "artist",
                    "url": url,
                    "artworkUrl": results.get("image").and_then(|v| v.as_str()),
                    "author": name,
                    "totalTracks": tracks.len()
                }),
                tracks,
            })
        }
        async fn get_artist_likes(&self, artist_slug: &str) -> LoadResult {
            let json = match self
                .make_request(
                    reqwest::Method::GET,
                    &format!("/artist/{artist_slug}"),
                    None,
                )
                .await
            {
                Some(j) => j,
                None => return LoadResult::Empty {},
            };
            let results = match json.get("results") {
                Some(r) => r,
                None => return LoadResult::Empty {},
            };
            let name = results
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("Artist")
                .to_owned();
            let likes_json = match self
                .make_request(
                    reqwest::Method::GET,
                    &format!("/artist/{artist_slug}/favorites"),
                    None,
                )
                .await
            {
                Some(j) => j,
                None => return LoadResult::Empty {},
            };
            let tracks: Vec<_> = likes_json
                .get("results")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|item| self.parse_track(item))
                        .collect()
                })
                .unwrap_or_default();
            if tracks.is_empty() {
                return LoadResult::Empty {};
            }
            LoadResult::Playlist(PlaylistData {
                info: PlaylistInfo {
                    name: format!("{name}'s Liked Tracks"),
                    selected_track: -1,
                },
                plugin_info: serde_json::json!({}),
                tracks,
            })
        }
    }
    #[async_trait]
    impl SourcePlugin for AudiomackSource {
        fn name(&self) -> &str {
            "audiomack"
        }
        fn can_handle(&self, identifier: &str) -> bool {
            self.search_prefixes()
            .iter()
            .any(|p| identifier.starts_with(p))
            || SONG_REGEX
                .get_or_init(|| Regex::new(r"https?://(?:www\.)?audiomack\.com/(?P<artist>[^/]+)/song/(?P<slug>[^/?#]+)").unwrap())
                .is_match(identifier)
            || ALBUM_REGEX
                .get_or_init(|| Regex::new(r"https?://(?:www\.)?audiomack\.com/(?P<artist>[^/]+)/album/(?P<slug>[^/?#]+)").unwrap())
                .is_match(identifier)
            || PLAYLIST_REGEX
                .get_or_init(|| Regex::new(r"https?://(?:www\.)?audiomack\.com/(?P<artist>[^/]+)/playlist/(?P<slug>[^/?#]+)").unwrap())
                .is_match(identifier)
            || ARTIST_REGEX
                .get_or_init(|| Regex::new(r"https?://(?:www\.)?audiomack\.com/(?P<artist>[^/?#]+)(?:/songs)?/?$").unwrap())
                .is_match(identifier)
            || LIKES_REGEX
                .get_or_init(|| Regex::new(r"https?://(?:www\.)?audiomack\.com/(?P<artist>[^/]+)/likes").unwrap())
                .is_match(identifier)
        }
        fn search_prefixes(&self) -> Vec<&str> {
            vec!["amksearch:"]
        }
        async fn load(
            &self,
            identifier: &str,
            _routeplanner: Option<Arc<dyn crate::routeplanner::RoutePlanner>>,
        ) -> LoadResult {
            if let Some(prefix) = self
                .search_prefixes()
                .into_iter()
                .find(|p| identifier.starts_with(p))
            {
                let query = identifier.strip_prefix(prefix).unwrap();
                return self.search(query).await;
            }
            if let Some(caps) = SONG_REGEX.get().and_then(|r| r.captures(identifier)) {
                let artist = caps.name("artist").map(|m| m.as_str()).unwrap_or("");
                let slug = caps.name("slug").map(|m| m.as_str()).unwrap_or("");
                return self.get_song(artist, slug).await;
            }
            if let Some(caps) = ALBUM_REGEX.get().and_then(|r| r.captures(identifier)) {
                let artist = caps.name("artist").map(|m| m.as_str()).unwrap_or("");
                let slug = caps.name("slug").map(|m| m.as_str()).unwrap_or("");
                return self.get_playlist_items("album", artist, slug).await;
            }
            if let Some(caps) = PLAYLIST_REGEX.get().and_then(|r| r.captures(identifier)) {
                let artist = caps.name("artist").map(|m| m.as_str()).unwrap_or("");
                let slug = caps.name("slug").map(|m| m.as_str()).unwrap_or("");
                return self.get_playlist_items("playlist", artist, slug).await;
            }
            if let Some(caps) = LIKES_REGEX.get().and_then(|r| r.captures(identifier)) {
                let artist = caps.name("artist").map(|m| m.as_str()).unwrap_or("");
                return self.get_artist_likes(artist).await;
            }
            if let Some(caps) = ARTIST_REGEX.get().and_then(|r| r.captures(identifier)) {
                let artist = caps.name("artist").map(|m| m.as_str()).unwrap_or("");
                return self.get_artist(artist).await;
            }
            LoadResult::Empty {}
        }
        async fn get_track(
            &self,
            identifier: &str,
            routeplanner: Option<Arc<dyn crate::routeplanner::RoutePlanner>>,
        ) -> Option<BoxedTrack> {
            let mut track_id = identifier.to_owned();
            if SONG_REGEX
                .get()
                .map(|r| r.is_match(identifier))
                .unwrap_or(false)
            {
                if let LoadResult::Track(track) = self.load(identifier, None).await {
                    track_id = track.info.identifier;
                } else {
                    return None;
                }
            }
            let local_addr = routeplanner.and_then(|rp| rp.get_address());
            let stream_url = super::track::fetch_stream_url(&self.client, &track_id).await;
            if stream_url.is_none() {
                warn!(
                    "Audiomack: no stream URL for track {}, falling back to mirrors",
                    track_id
                );
                return None;
            }
            Some(Arc::new(AudiomackTrack {
                stream_url: stream_url.unwrap(),
                local_addr,
            }))
        }
        fn get_proxy_config(&self) -> Option<crate::config::HttpProxyConfig> {
            None
        }
    }
}
pub mod track {
    use crate::sources::{
        audiomack::utils::build_auth_header,
        http::HttpTrack,
        playable_track::{PlayableTrack, ResolvedTrack},
    };
    use async_trait::async_trait;
    use rand::{Rng, distributions::Alphanumeric, thread_rng};
    use std::{collections::BTreeMap, net::IpAddr, sync::Arc};
    use tracing::debug;
    pub struct AudiomackTrack {
        pub stream_url: String,
        pub local_addr: Option<IpAddr>,
    }
    #[async_trait]
    impl PlayableTrack for AudiomackTrack {
        async fn resolve(&self) -> Result<ResolvedTrack, String> {
            let url = self.stream_url.clone();
            debug!("Reddit playback URL: {url}");
            HttpTrack {
                url,
                local_addr: self.local_addr,
                proxy: None,
            }
            .resolve()
            .await
        }
    }
    pub async fn fetch_stream_url(
        client: &Arc<reqwest::Client>,
        identifier: &str,
    ) -> Option<String> {
        let nonce = generate_nonce();
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
            .to_string();
        let post_url = format!("https://api.audiomack.com/v1/music/{identifier}/play");
        let mut body = BTreeMap::new();
        body.insert("environment".to_owned(), "desktop-web".to_owned());
        body.insert("session".to_owned(), "backend-session".to_owned());
        body.insert("hq".to_owned(), "true".to_owned());
        let auth_post = build_auth_header("POST", &post_url, &body, &nonce, &timestamp);
        if let Ok(resp) = client
            .post(&post_url)
            .header("Authorization", auth_post)
            .form(&body)
            .send()
            .await
            && let Some(url) = parse_response(resp).await
        {
            return Some(url);
        }
        let get_url = format!("https://api.audiomack.com/v1/music/play/{identifier}");
        let mut query = BTreeMap::new();
        query.insert("environment".to_owned(), "desktop-web".to_owned());
        query.insert("hq".to_owned(), "true".to_owned());
        let auth_get = build_auth_header("GET", &get_url, &query, &nonce, &timestamp);
        if let Ok(resp) = client
            .get(&get_url)
            .header("Authorization", auth_get)
            .query(&query)
            .send()
            .await
            && let Some(url) = parse_response(resp).await
        {
            return Some(url);
        }
        None
    }
    async fn parse_response(resp: reqwest::Response) -> Option<String> {
        if !resp.status().is_success() {
            return None;
        }
        let text = resp.text().await.ok()?;
        let is_stream = |url: &str| {
            url.contains("music.audiomack.com")
                || url.ends_with(".m4a")
                || url.ends_with(".mp3")
                || url.contains(".m4a?")
                || url.contains(".mp3?")
        };
        if text.starts_with("http") && is_stream(&text) {
            return Some(text);
        }
        let json: serde_json::Value = serde_json::from_str(&text).ok()?;
        if let Some(s) = json.as_str()
            && is_stream(s)
        {
            return Some(s.to_owned());
        }
        let results = json.get("results").unwrap_or(&json);
        let potential_url = results
            .get("signedUrl")
            .or_else(|| results.get("signed_url"))
            .or_else(|| results.get("streamUrl"))
            .or_else(|| results.get("stream_url"))
            .or_else(|| results.get("url"))
            .and_then(|v| v.as_str());
        if let Some(url) = potential_url
            && is_stream(url)
        {
            return Some(url.to_owned());
        }
        None
    }
    fn generate_nonce() -> String {
        thread_rng()
            .sample_iter(&Alphanumeric)
            .take(32)
            .map(char::from)
            .collect()
    }
}
pub mod utils {
    use base64::{Engine as _, engine::general_purpose::STANDARD};
    use hmac::{Hmac, Mac};
    use sha1::Sha1;
    use std::collections::BTreeMap;
    const CONSUMER_KEY: &str = "audiomack-web";
    const CONSUMER_SECRET: &str = "bd8a07e9f23fbe9d808646b730f89b8e";
    type HmacSha1 = Hmac<Sha1>;
    pub fn percent_encode(s: &str) -> String {
        let mut out = String::with_capacity(s.len());
        for b in s.as_bytes() {
            match b {
                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                    out.push(*b as char)
                }
                _ => out.push_str(&format!("%{:02X}", b)),
            }
        }
        out
    }
    pub fn build_auth_header(
        method: &str,
        url: &str,
        params: &BTreeMap<String, String>,
        nonce: &str,
        timestamp: &str,
    ) -> String {
        let mut oauth_params = BTreeMap::new();
        oauth_params.insert("oauth_consumer_key".to_owned(), CONSUMER_KEY.to_owned());
        oauth_params.insert("oauth_nonce".to_owned(), nonce.to_owned());
        oauth_params.insert("oauth_signature_method".to_owned(), "HMAC-SHA1".to_owned());
        oauth_params.insert("oauth_timestamp".to_owned(), timestamp.to_owned());
        oauth_params.insert("oauth_version".to_owned(), "1.0".to_owned());
        let mut all_params = oauth_params.clone();
        for (k, v) in params {
            all_params.insert(percent_encode(k), percent_encode(v));
        }
        let param_string = all_params
            .iter()
            .map(|(k, v)| format!("{k}={v}"))
            .collect::<Vec<_>>()
            .join("&");
        let base_string = format!(
            "{}&{}&{}",
            percent_encode(&method.to_uppercase()),
            percent_encode(url),
            percent_encode(&param_string)
        );
        let signing_key = format!("{}&", percent_encode(CONSUMER_SECRET));
        let mut mac =
            HmacSha1::new_from_slice(signing_key.as_bytes()).expect("HMAC can take any key size");
        mac.update(base_string.as_bytes());
        let signature = STANDARD.encode(mac.finalize().into_bytes());
        oauth_params.insert("oauth_signature".to_owned(), signature);
        let header_parts: Vec<_> = oauth_params
            .iter()
            .map(|(k, v)| format!("{}=\"{}\"", percent_encode(k), percent_encode(v)))
            .collect();
        format!("OAuth {}", header_parts.join(", "))
    }
}
pub use manager::AudiomackSource;