Open-source music player for YouTube Music's catalog, with genres, full albums and playlists. Windows, macOS, Linux, Android, iPhone and Docker. No account needed.
TypeScript
fix(android): search failing on some phones (1.5.1)
Ernani41706772a4c1
diff --git a/desktop/package.json b/desktop/package.jsonindex cdc629f..9499be8 100644--- a/desktop/package.json+++ b/desktop/package.json@@ -1,7 +1,7 @@{"name": "musike-desktop","productName": "Musike",- "version": "1.5.0",+ "version": "1.5.1","description": "Your music, uninterrupted.","author": "Musike","homepage": "https://github.com/Ernani1234/musike",diff --git a/mobile/ios/App/App.xcodeproj/project.pbxproj b/mobile/ios/App/App.xcodeproj/project.pbxprojindex 9952cab..85e8b8f 100644--- a/mobile/ios/App/App.xcodeproj/project.pbxproj+++ b/mobile/ios/App/App.xcodeproj/project.pbxproj@@ -316,14 +316,14 @@buildSettings = {ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 10500;+ CURRENT_PROJECT_VERSION = 10501;INFOPLIST_FILE = App/Info.plist;IPHONEOS_DEPLOYMENT_TARGET = 15.0;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",);- MARKETING_VERSION = 1.5.0;+ MARKETING_VERSION = 1.5.1;OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";PRODUCT_BUNDLE_IDENTIFIER = app.musike.ios;PRODUCT_NAME = "$(TARGET_NAME)";@@ -338,14 +338,14 @@buildSettings = {ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 10500;+ CURRENT_PROJECT_VERSION = 10501;INFOPLIST_FILE = App/Info.plist;IPHONEOS_DEPLOYMENT_TARGET = 15.0;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",);- MARKETING_VERSION = 1.5.0;+ MARKETING_VERSION = 1.5.1;PRODUCT_BUNDLE_IDENTIFIER = app.musike.ios;PRODUCT_NAME = "$(TARGET_NAME)";SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";diff --git a/mobile/package.json b/mobile/package.jsonindex 428bf5d..fd04498 100644--- a/mobile/package.json+++ b/mobile/package.json@@ -1,7 +1,7 @@{"name": "@musike/mobile","private": true,- "version": "1.5.0",+ "version": "1.5.1","description": "Musike for Android: the web app with the server's work done on the phone (Capacitor).","type": "module","scripts": {diff --git a/package.json b/package.jsonindex 0f92fc3..b0b6ec0 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "musike","private": true,- "version": "1.5.0",+ "version": "1.5.1","type": "module","scripts": {"dev": "pnpm --parallel --filter ./server --filter ./web dev",diff --git a/server/package.json b/server/package.jsonindex 50fa36a..456fdb1 100644--- a/server/package.json+++ b/server/package.json@@ -1,7 +1,7 @@{"name": "@musike/server","private": true,- "version": "1.5.0",+ "version": "1.5.1","type": "module","scripts": {"dev": "tsx watch --clear-screen=false src/index.ts",diff --git a/server/src/i18n.ts b/server/src/i18n.tsindex ea301a9..5d4277a 100644--- a/server/src/i18n.ts+++ b/server/src/i18n.ts@@ -9,6 +9,7 @@ type Params = Record<string, string | number>;const en = {invalidVideoId: "Invalid video ID.",emptyQuery: "Type something to search.",+ searchFailed: "Search is unavailable right now ({detail}). Try again in a moment.",missingTitle: "Give the song's title.",notBackup: "This file isn't a Musike backup.",newerBackup: "This backup was made by a newer Musike. Update the app to import it.",@@ -59,6 +60,7 @@ export type MsgKey = keyof typeof en;const pt: Record<MsgKey, string> = {invalidVideoId: "ID de vídeo inválido.",emptyQuery: "Digite algo para buscar.",+ searchFailed: "A busca está indisponível agora ({detail}). Tente de novo em instantes.",missingTitle: "Informe o título da música.",notBackup: "Este arquivo não é um backup do Musike.",newerBackup: "Backup de uma versão mais nova do Musike. Atualize o app para importar.",diff --git a/server/src/search.ts b/server/src/search.tsindex 09c3628..8c56e94 100644--- a/server/src/search.ts+++ b/server/src/search.ts@@ -1,8 +1,8 @@import { Innertube } from "youtubei.js";import { config } from "./config.js";-import { youtubeLang, type Lang } from "./i18n.js";+import { msg, youtubeLang, type Lang } from "./i18n.js";import type { Track } from "./types.js";-import { VIDEO_ID } from "./types.js";+import { HttpError, VIDEO_ID } from "./types.js";import { ytdlpSearch } from "./ytdlp.js";// One session per language: YouTube Music words its own texts (genre names, artist bios) in the session's language.@@ -69,16 +69,60 @@ export function toTrack(item: any, kind: Track["kind"]): Track | null {};}+/** Tracks from every shelf of a search response, not just the first (a "did you mean" block can come first). */+function tracksFrom(result: { contents?: unknown }, kind: Track["kind"]): Track[] {+ const seen = new Set<string>();+ const tracks: Track[] = [];+ const sections = Array.isArray(result.contents) ? (result.contents as { contents?: unknown }[]) : [];+ for (const section of sections) {+ for (const item of Array.isArray(section?.contents) ? section.contents : []) {+ const track = toTrack(item, kind);+ if (track && !seen.has(track.id)) {+ seen.add(track.id);+ tracks.push(track);+ }+ }+ }+ return tracks;+}++/** Short enough for an error message: "HTTP 403" rather than the whole request URL. */+function reason(e: unknown): string {+ const message = (e as Error)?.message || String(e);+ const status = /status code (\d{3})/.exec(message)?.[1];+ return status ? `HTTP ${status}` : message.slice(0, 80);+}++/**+ * YouTube Music first; then plain YouTube search (another endpoint, videos only), which also covers the Android app,+ * where there is no yt-dlp; then yt-dlp on a computer.+ */export async function search(query: string, type: "song" | "video", lang?: Lang): Promise<Track[]> {+ const failures: string[] = [];try {- const result = await withClient((yt) => yt.music.search(query, { type }), lang);- const shelf = result.contents?.[0] as { contents?: unknown[] } | undefined;- const tracks = (shelf?.contents ?? []).map((i) => toTrack(i, type)).filter((t): t is Track => !!t);+ const tracks = tracksFrom(await withClient((yt) => yt.music.search(query, { type }), lang), type);if (tracks.length) return tracks;- } catch {- // fall through to yt-dlp search+ failures.push("YouTube Music: no results");+ } catch (e) {+ failures.push(`YouTube Music: ${reason(e)}`);+ }+ try {+ const result = await withClient((yt) => yt.search(query, { type: "video" }), lang);+ const tracks = (result.videos ?? []).map((v) => toTrack(v, "video")).filter((t): t is Track => !!t);+ if (tracks.length) return tracks;+ failures.push("YouTube: no results");+ } catch (e) {+ failures.push(`YouTube: ${reason(e)}`);+ }+ let entries: Awaited<ReturnType<typeof ytdlpSearch>>;+ try {+ entries = await ytdlpSearch(query);+ } catch (err) {+ // yt-dlp's own problem (missing, outdated) is what to fix on a computer. On a phone there is no yt-dlp, so say+ // what YouTube answered: that's what a bug report needs.+ if (err instanceof HttpError) throw err;+ throw new HttpError(503, msg("searchFailed", { detail: failures.join("; ") }));}- const entries = await ytdlpSearch(query);return entries.filter((e) => VIDEO_ID.test(e.id)).map((e) => ({@@ -146,9 +190,7 @@ export async function findVideoFor(id: string, title: string, artist: string, du}async function videoSearch(query: string): Promise<Track[]> {- const result = await withClient((yt) => yt.music.search(query, { type: "video" }));- const shelf = result.contents?.[0] as { contents?: unknown[] } | undefined;- return (shelf?.contents ?? []).map((i) => toTrack(i, "video")).filter((t): t is Track => !!t);+ return tracksFrom(await withClient((yt) => yt.music.search(query, { type: "video" })), "video");}function pickClip(candidates: Track[], title: string, artist: string, duration: number): Track | null {diff --git a/web/package.json b/web/package.jsonindex 022edee..ec21598 100644--- a/web/package.json+++ b/web/package.json@@ -1,7 +1,7 @@{"name": "@musike/web","private": true,- "version": "1.5.0",+ "version": "1.5.1","type": "module","scripts": {"dev": "vite --host",diff --git a/web/src/native/http.ts b/web/src/native/http.tsindex 6387c94..d0b7bf2 100644--- a/web/src/native/http.ts+++ b/web/src/native/http.ts@@ -33,6 +33,20 @@ const capacitorTransport: Transport = async (req) => {return { status: res.status, headers: res.headers ?? {}, body };};+// A current desktop Chrome, for the few requests that carry no session to borrow one from.+const DESKTOP_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";++/** The browser the request's own body says it comes from (youtubei.js puts it in context.client.userAgent). */+function claimedUserAgent(body: string | undefined): string | undefined {+ if (!body?.startsWith("{")) return undefined;+ try {+ const ua = (JSON.parse(body) as { context?: { client?: { userAgent?: unknown } } }).context?.client?.userAgent;+ return typeof ua === "string" && ua ? ua : undefined;+ } catch {+ return undefined;+ }+}+export function makeFetch(transport: Transport): typeof fetch {return async (input, init) => {const request = input instanceof Request ? input : null;@@ -44,6 +58,12 @@ export function makeFetch(transport: Transport): typeof fetch {});const raw = init?.body ?? undefined;const body = raw == null ? undefined : typeof raw === "string" ? raw : await new Response(raw).text();+ // youtubei.js leaves out User-Agent and Origin in a web view, where the browser would add them. These requests+ // skip the browser, so Android would send Java's own "Dalvik/2.1.0 …" with no Origin, while the body claims to be+ // desktop Chrome: a mismatch YouTube's bot checks catch on some networks (search failed there, suggestions didn't).+ // Send what the server sends instead.+ headers["user-agent"] ??= claimedUserAgent(body) ?? DESKTOP_UA;+ if (!headers.origin && new URL(url).pathname.startsWith("/youtubei/")) headers.origin = new URL(url).origin;const res = await transport({ url, method: init?.method ?? request?.method ?? "GET", headers, body });// Statuses without a body (204, 304) can't be given one.const bodyless = res.status === 204 || res.status === 304 || (res.status >= 100 && res.status < 200);