aboutsummaryrefslogtreecommitdiff
path: root/import/src/acoustid.rs
diff options
context:
space:
mode:
Diffstat (limited to 'import/src/acoustid.rs')
-rw-r--r--import/src/acoustid.rs101
1 files changed, 93 insertions, 8 deletions
diff --git a/import/src/acoustid.rs b/import/src/acoustid.rs
index b5a466a..8e8a603 100644
--- a/import/src/acoustid.rs
+++ b/import/src/acoustid.rs
@@ -6,16 +6,105 @@
use anyhow::Result;
use bincode::{Decode, Encode};
use jellybase::cache::async_cache_memory;
+use reqwest::{
+ header::{HeaderMap, HeaderName, HeaderValue},
+ Client, ClientBuilder,
+};
use serde::Deserialize;
-use std::{path::Path, process::Stdio, sync::Arc};
-use tokio::{io::AsyncReadExt, process::Command};
+use std::{path::Path, process::Stdio, sync::Arc, time::Duration};
+use tokio::{
+ io::AsyncReadExt,
+ process::Command,
+ sync::Semaphore,
+ time::{sleep_until, Instant},
+};
-#[derive(Debug, Encode, Decode, Deserialize)]
+pub(crate) struct AcoustID {
+ client: Client,
+ key: String,
+ rate_limit: Arc<Semaphore>,
+}
+
+#[derive(Debug, Hash, Clone, Encode, Decode, Deserialize)]
pub(crate) struct Fingerprint {
- duration: f32,
+ duration: u32,
fingerprint: String,
}
+#[derive(Deserialize, Encode, Decode)]
+pub(crate) struct AcoustIDLookupResultRecording {
+ id: String,
+}
+#[derive(Deserialize, Encode, Decode)]
+pub(crate) struct AcoustIDLookupResult {
+ id: String,
+ score: f32,
+ recordings: Vec<AcoustIDLookupResultRecording>,
+}
+#[derive(Deserialize, Encode, Decode)]
+pub(crate) struct AcoustIDLookupResponse {
+ status: String,
+ results: Vec<AcoustIDLookupResult>,
+}
+
+impl AcoustID {
+ pub fn new(api_key: &str) -> Self {
+ let client = ClientBuilder::new()
+ .default_headers(HeaderMap::from_iter([(
+ HeaderName::from_static("accept"),
+ HeaderValue::from_static("application/json"),
+ )]))
+ .build()
+ .unwrap();
+ Self {
+ client,
+ // send at most 3 req/s according to acoustid docs, each lock is therefore held for 1s
+ // this implementation also never sends more than 3 requests in-flight.
+ rate_limit: Arc::new(Semaphore::new(3)),
+ key: api_key.to_owned(),
+ }
+ }
+
+ pub async fn get_atid_mbid(&self, fp: Fingerprint) -> Result<Option<(String, String)>> {
+ let res = self.lookup(fp).await?;
+ for r in &res.results {
+ if let Some(k) = r.recordings.get(0) {
+ return Ok(Some((r.id.clone(), k.id.clone())));
+ }
+ }
+ Ok(None)
+ }
+
+ pub async fn lookup(&self, fp: Fingerprint) -> Result<Arc<AcoustIDLookupResponse>> {
+ async_cache_memory("api-acoustid", fp.clone(), || async move {
+ let _permit = self.rate_limit.clone().acquire_owned().await?;
+ let permit_drop_ts = Instant::now() + Duration::SECOND;
+
+ let duration = fp.duration;
+ let fingerprint = &fp.fingerprint;
+ let client = &self.key;
+ let meta = "recordingids";
+ let body = format!("format=json&client={client}&duration={duration}&fingerprint={fingerprint}&meta={meta}");
+
+ let resp = self
+ .client
+ .post(format!("https://api.acoustid.org/v2/lookup"))
+ .body(body)
+ .send()
+ .await?.error_for_status()?.json::<AcoustIDLookupResponse>().await?;
+
+
+ tokio::task::spawn(async move {
+ sleep_until(permit_drop_ts).await;
+ drop(_permit);
+ });
+
+ Ok(resp)
+ })
+ .await
+ }
+}
+
#[allow(unused)]
pub(crate) async fn acoustid_fingerprint(path: &Path) -> Result<Arc<Fingerprint>> {
async_cache_memory("fpcalc", path, || async move {
@@ -33,7 +122,3 @@ pub(crate) async fn acoustid_fingerprint(path: &Path) -> Result<Arc<Fingerprint>
})
.await
}
-
-// pub(crate) async fn acoustid_mbid(fingerprint: Fingerprint) -> Result<Arc<Option<String>>> {
-// async_cache_memory(&["api-acoustid", fingerprint], generate)
-// }