Search online for the right artist photo, bio and logo, or use your own

This commit is contained in:
Christian
2026-11-19 01:09:27 -05:00
parent bfaa53ddc3
commit f081ca4a45
5 changed files with 175 additions and 1 deletions
+81
View File
@@ -102,6 +102,83 @@ async fn wikidata_file(http: &reqwest::Client, qid: &str, prop: &str) -> Option<
get_bytes(http, &format!("https://commons.wikimedia.org/wiki/Special:FilePath/{}?width=800", path_enc(file))).await
}
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PhotoChoice {
pub name: String,
pub fans: u64,
pub thumb: String,
pub full: String,
}
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PageChoice {
pub key: String,
pub title: String,
pub description: String,
pub music: bool,
}
pub async fn choices(http: &reqwest::Client, query: &str) -> (Vec<PhotoChoice>, Vec<PageChoice>) {
let q = enc(query);
let photos = async {
let Some(v) = get_json(http, &format!("https://api.deezer.com/search/artist?q={q}&limit=12")).await else { return Vec::new() };
v["data"]
.as_array()
.map(|list| {
list.iter()
.filter_map(|a| {
let full = a["picture_xl"].as_str().filter(|u| !u.contains("/artist//"))?;
Some(PhotoChoice { name: a["name"].as_str()?.to_string(), fans: a["nb_fan"].as_u64().unwrap_or(0), thumb: a["picture_medium"].as_str().unwrap_or(full).to_string(), full: full.to_string() })
})
.collect()
})
.unwrap_or_default()
};
let pages = async {
let Some(v) = get_json(http, &format!("https://en.wikipedia.org/w/rest.php/v1/search/page?q={q}&limit=8")).await else { return Vec::new() };
v["pages"]
.as_array()
.map(|list| {
list.iter()
.filter_map(|p| {
let description = p["description"].as_str().unwrap_or_default().to_string();
Some(PageChoice { key: p["key"].as_str()?.to_string(), title: p["title"].as_str()?.to_string(), music: is_music_description(&description), description })
})
.collect()
})
.unwrap_or_default()
};
tokio::join!(photos, pages)
}
pub fn allowed_photo(url: &str) -> bool {
url::Url::parse(url).is_ok_and(|u| u.scheme() == "https" && u.host_str().is_some_and(|h| h.ends_with(".dzcdn.net")))
}
pub async fn chosen(http: &reqwest::Client, photo: Option<&str>, page: Option<&str>) -> Found {
let mut found = Found::default();
if let Some(url) = photo.filter(|u| allowed_photo(u)) {
found.photo = get_bytes(http, url).await;
}
if let Some(key) = page.filter(|k| !k.is_empty() && k.len() < 300 && !k.contains('/')) {
if let Some(s) = get_json(http, &format!("https://en.wikipedia.org/api/rest_v1/page/summary/{}", path_enc(key))).await {
if s["type"].as_str() == Some("standard") {
found.bio = s["extract"].as_str().map(|t| t.trim().to_string());
found.bio_source = s["content_urls"]["desktop"]["page"].as_str().map(String::from);
if let Some(q) = s["wikibase_item"].as_str() {
found.logo = wikidata_file(http, q, "P154").await;
if found.photo.is_none() && photo.is_none() {
found.photo = wikidata_file(http, q, "P18").await;
}
}
}
}
}
found
}
pub async fn find(http: &reqwest::Client, name: &str, want_photo: bool, want_bio: bool, want_logo: bool) -> Result<Found> {
let mut found = Found::default();
let photo = async {
@@ -153,6 +230,10 @@ mod tests {
assert_eq!(norm("Kühvt!"), "kühvt");
assert_eq!(path_enc("Daft Punk logo.svg"), "Daft_Punk_logo.svg");
assert_eq!(path_enc("Beyoncé"), "Beyonc%C3%A9");
assert!(allowed_photo("https://cdn-images.dzcdn.net/images/artist/abc/1000x1000.jpg"));
assert!(!allowed_photo("http://cdn-images.dzcdn.net/x.jpg"));
assert!(!allowed_photo("https://evil.example/dzcdn.net.jpg"));
assert!(!allowed_photo("file:///C:/Windows/win.ini"));
}
#[tokio::test]
+22
View File
@@ -707,3 +707,25 @@ pub async fn import_file(app: AppHandle, state: State<'_, AppState>, request: ta
changed(&app);
Ok(track)
}
#[tauri::command]
pub async fn artist_choices(state: State<'_, AppState>, query: String) -> CmdResult<serde_json::Value> {
let q = query.trim();
if q.is_empty() {
return Ok(serde_json::json!({ "photos": [], "pages": [] }));
}
let (photos, pages) = crate::artistinfo::choices(&state.http, q).await;
Ok(serde_json::json!({ "photos": photos, "pages": pages }))
}
#[tauri::command]
pub async fn artist_apply(state: State<'_, AppState>, name: String, photo: Option<String>, page: Option<String>) -> CmdResult<crate::library::ArtistMeta> {
if photo.as_deref().is_some_and(|u| !crate::artistinfo::allowed_photo(u)) {
return Err("That photo isn't from a source Atmosphere trusts.".into());
}
let found = crate::artistinfo::chosen(&state.http, photo.as_deref(), page.as_deref()).await;
if found.photo.is_none() && found.bio.is_none() && found.logo.is_none() {
return Err("Couldn't get anything from that choice. Try another one.".into());
}
Ok(state.library.apply_artist_info(&name, found, true))
}
+2
View File
@@ -552,6 +552,8 @@ fn main() {
libcmd::import_file,
libcmd::artist_fetch,
libcmd::artist_media,
libcmd::artist_choices,
libcmd::artist_apply,
libcmd::playlist_cover,
libcmd::playlist_relocate,
libcmd::playlist_unlink
+53 -1
View File
@@ -654,6 +654,50 @@ function queueLibraryArtists() {
queueArtistInfo(pending.map((a) => a.name));
}
async function searchArtistOnline(ar) {
let pick = { photo: null, page: null };
const input = h("input", { class: "text wide", type: "search", value: ar.name, "aria-label": "Search for this artist", spellcheck: "false" });
const photos = h("div", { class: "pick-photos" });
const pages = h("div", { class: "pick-pages" });
const status = h("p", { class: "muted small" }, "Searching…");
const fans = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M fans` : n >= 1e3 ? `${Math.round(n / 1e3)}K fans` : `${n} fans`);
const run = async () => {
status.textContent = "Searching…";
pick = { photo: null, page: null };
const r = await invoke("artist_choices", { query: input.value }).catch((e) => (status.textContent = errText(e), null));
if (!r) return;
photos.replaceChildren(...r.photos.map((p) => {
const el = h("button", { class: "pick-photo", type: "button", title: `${p.name} · ${fans(p.fans)}`, onclick: () => { pick.photo = pick.photo === p.full ? null : p.full; $$(".pick-photo", photos).forEach((x) => x.classList.toggle("on", x === el && !!pick.photo)); } },
h("img", { src: p.thumb, alt: "", referrerpolicy: "no-referrer", loading: "lazy" }), h("span", {}, p.name), h("small", {}, fans(p.fans)));
return el;
}));
pages.replaceChildren(...r.pages.map((p) => {
const el = h("button", { class: `pick-page ${p.music ? "" : "dim"}`, type: "button", onclick: () => { pick.page = pick.page === p.key ? null : p.key; $$(".pick-page", pages).forEach((x) => x.classList.toggle("on", x === el && !!pick.page)); } },
h("strong", {}, p.title), h("span", {}, p.description || "No description"));
return el;
}));
status.textContent = r.photos.length || r.pages.length ? "Pick a photo, a Wikipedia page for the bio and logo, or both." : "Nothing found. Try a different spelling.";
};
input.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); run(); } });
const body = h("div", { class: "stack" },
h("div", { class: "row" }, input, h("button", { class: "btn", type: "button", onclick: run }, icon("search"), "Search")),
status,
h("strong", { class: "pick-head" }, "Photos from Deezer"), photos,
h("strong", { class: "pick-head" }, "Wikipedia page (bio and logo)"), pages);
run();
const ok = await modal(`Find ${ar.name} online`, body, [{ label: "Cancel", value: false }, { label: "Use these", value: true, primary: true }]);
if (!ok || (!pick.photo && !pick.page)) return null;
try {
const meta = await invoke("artist_apply", { name: ar.name, photo: pick.photo, page: pick.page });
setArtistMeta(ar.name, meta);
toast("Artist updated", "ok");
return meta;
} catch (e) {
toast(errText(e), "err");
return null;
}
}
async function editArtist(ar) {
let meta = ar.meta || {};
const bio = h("textarea", { class: "text area", rows: "6", placeholder: "A few lines about this artist…" }, meta.bio || "");
@@ -681,6 +725,14 @@ async function editArtist(ar) {
if (errText(e) !== "cancelled") toast(errText(e), "err");
}
};
const search = h("button", { class: "btn small", type: "button", onclick: async () => {
const m = await searchArtistOnline(ar);
if (m) {
meta = m;
bio.value = m.bio || "";
draw();
}
} }, icon("search"), "Search online…");
const refresh = h("button", { class: "btn small ghost", type: "button", onclick: async (e) => {
const b = e.currentTarget;
b.disabled = true;
@@ -707,7 +759,7 @@ async function editArtist(ar) {
h("div", { class: "stack" }, h("strong", {}, "Logo"), logo,
h("div", { class: "row" }, h("button", { class: "btn small", type: "button", onclick: act("logo", true) }, "Choose logo…"), h("button", { class: "btn small ghost", type: "button", onclick: act("logo", false) }, "Remove"))),
h("label", { class: "field" }, h("span", {}, "About"), bio),
h("div", { class: "row between" }, h("p", { class: "muted small" }, "Photos come from Deezer and bios and logos from Wikipedia, when found. Anything you change here stays."), refresh));
h("div", { class: "row between" }, h("p", { class: "muted small" }, "Photos come from Deezer and bios and logos from Wikipedia. Not the right artist? Search online and pick, or use your own images. Anything you change here stays."), h("div", { class: "row" }, search, refresh)));
const ok = await modal(`Edit ${ar.name}`, body, [{ label: "Cancel", value: false }, { label: "Save", value: true, primary: true }]);
if (ok && bio.value !== (meta.bio || "")) {
try {
+17
View File
@@ -1148,3 +1148,20 @@ body.mini-mode > *:not(#mini):not(.toasts):not(.modal-wrap):not(script) { displa
.drop-hint .i svg { width: 40px; height: 40px; color: var(--accent); }
.drop-hint strong { font: 650 18px/1.3 var(--font-display); }
.drop-hint span { color: var(--text-2); font-size: 13px; }
/* choosing artist info online */
.modal:has(.pick-photos) { max-width: 720px; }
.pick-head { font-size: 12.5px; color: var(--text-2); margin-top: var(--s2); }
.pick-photos { display: grid; grid-template-columns: repeat(auto-fill, minmax(104px, 1fr)); gap: var(--s2); max-height: 260px; overflow-y: auto; }
.pick-photo { display: grid; gap: 4px; padding: 6px; border-radius: 10px; border: 2px solid transparent; text-align: center; min-width: 0; }
.pick-photo:hover { background: var(--hover); }
.pick-photo.on { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, transparent); }
.pick-photo img { width: 100%; aspect-ratio: 1; object-fit: cover; border-radius: 50%; background: var(--surface-2, var(--surface)); }
.pick-photo span { font-size: 12px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pick-photo small { font-size: 11px; color: var(--text-3); }
.pick-pages { display: grid; gap: 4px; max-height: 220px; overflow-y: auto; }
.pick-page { display: grid; gap: 2px; text-align: left; padding: 8px 10px; border-radius: 10px; border: 2px solid transparent; }
.pick-page:hover { background: var(--hover); }
.pick-page.on { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, transparent); }
.pick-page.dim { opacity: 0.6; }
.pick-page span { font-size: 12px; color: var(--text-2); }