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
Merge pull request #7 from fvaha/ios-app
Ernani2690ac799982
diff --cc server/src/directAudio.tsindex 7acc8c0,0000000..e421295mode 100644,000000..100644--- a/server/src/directAudio.ts+++ b/server/src/directAudio.ts@@@ -1,71 -1,0 +1,74 @@@+import type { Lang } from "./i18n.js";+import { text, withClient } from "./search.js";++/**+ * A track's audio asked straight from YouTube's API, without yt-dlp. The Android app plays it this way, and the+ * server falls back to it when yt-dlp fails (YouTube's bot check on some connections, an outdated yt-dlp).+ *+ * YouTube only serves the first megabyte of a stream to most clients unless the request carries a proof-of-origin+ * token. A few clients don't need one; VISIONOS (the Apple Vision Pro app) is the one yt-dlp itself relies on, and+ * its URLs need no deciphering either. When YouTube changes that, the list of clients can be updated remotely+ * (mobile/streaming.json in the repository) without shipping a new version.+ */++export const DEFAULT_CLIENTS = ["VISIONOS"];+const REMOTE_CONFIG = "https://raw.githubusercontent.com/Ernani1234/musike/main/mobile/streaming.json";++export interface DirectAudio {+ url: string;+ mime: string;+ title: string;+ duration: number;+ /** When the URL stops working (ms). */+ expiresAt: number;+}++export const validClients = (v: unknown): string[] | null =>+ Array.isArray(v) && v.length > 0 && v.every((c) => typeof c === "string" && /^[A-Z_]{2,30}$/.test(c)) ? (v as string[]) : null;+- /** The client list published in the repository, or null when it can't be read. */- export async function fetchRemoteClients(): Promise<string[] | null> {++/**++ * The client list published in the repository, or null when it can't be read. `clients` is the list for the server++ * and Android; a platform can have its own (`ios`).++ */++export async function fetchRemoteClients(key: "clients" | "ios" = "clients"): Promise<string[] | null> {+ try {+ const res = await fetch(REMOTE_CONFIG, { signal: AbortSignal.timeout(6000) });- return validClients(((await res.json()) as { clients?: unknown }).clients);++ return validClients(((await res.json()) as Record<string, unknown>)[key]);+ } catch {+ return null; // offline or no config: keep what we have+ }+}++/** Tries each client in turn. Throws with YouTube's reason (or an empty message) when none of them has audio. */+export async function directAudio(id: string, clients: string[], lang?: Lang): Promise<DirectAudio> {+ let reason = "";+ for (const client of clients) {+ try {+ const info: any = await withClient((yt) => yt.getBasicInfo(id, { client: client as never }), lang);+ const status = info.playability_status;+ if (status?.status && status.status !== "OK") {+ reason = text(status.reason) || reason;+ continue;+ }+ const formats: any[] = [...(info.streaming_data?.adaptive_formats ?? []), ...(info.streaming_data?.formats ?? [])].filter(+ (f) => f.has_audio && !f.has_video && typeof f.url === "string",+ );+ // AAC (m4a) first: it plays everywhere. Highest bitrate within the same kind.+ const best = formats.sort(+ (a, b) => Number(b.mime_type?.startsWith("audio/mp4")) - Number(a.mime_type?.startsWith("audio/mp4")) || (b.bitrate ?? 0) - (a.bitrate ?? 0),+ )[0];+ if (!best) continue;+ const expire = Number(new URL(best.url).searchParams.get("expire")) * 1000;+ return {+ url: best.url,+ mime: best.mime_type?.startsWith("audio/webm") ? "audio/webm" : "audio/mp4",+ title: info.basic_info?.title ?? "",+ duration: info.basic_info?.duration ?? 0,+ expiresAt: expire || Date.now() + 3 * 3600_000,+ };+ } catch (e) {+ reason = (e as Error).message || reason;+ }+ }+ throw new Error(reason);+}diff --cc web/src/native/streams.tsindex a573b84,9d4a43f..e7a5485--- a/web/src/native/streams.ts+++ b/web/src/native/streams.ts@@@ -1,47 -1,124 +1,81 @@@+ import { Capacitor } from "@capacitor/core";+import { DEFAULT_CLIENTS, directAudio, fetchRemoteClients, validClients, type DirectAudio } from "../../../server/src/directAudio";import { msg, tr } from "../../../server/src/i18n";-import { config } from "./shims/config";-import { nativeResolverAvailable, resolveNatively } from "./ytplayer";--import { text, withClient } from "../../../server/src/search";import { getLang } from "../i18n";import { ApiError } from "../lib/apiTypes";++import { config } from "./shims/config";++import { nativeResolverAvailable, resolveNatively } from "./ytplayer";/**- * Resolves a track's audio on the phone, the job yt-dlp does on the server: straight from YouTube's API- * (server/src/directAudio.ts). The list of clients to ask can be updated remotely; the last one received is kept.- * Resolves a track's audio on the phone, the job yt-dlp does on the server.- *- * YouTube only serves the first megabyte of a stream to most clients unless the request carries a proof-of-origin- * token. A few clients don't need one; VISIONOS (the Apple Vision Pro app) is the one yt-dlp itself relies on, and- * its URLs need no deciphering either. When YouTube changes that, the list of clients to try can be updated- * remotely (mobile/streaming.json in the repository) without shipping a new app.++ * Resolves a track's audio on the phone, the job yt-dlp does on the server. On iOS the app's native side asks first++ * (ios/App/App/MusikeYouTube.swift); otherwise, and as iOS's fallback, the audio comes straight from YouTube's API++ * (server/src/directAudio.ts). Each platform's list of clients can be updated remotely (mobile/streaming.json); the++ * last one received is kept.*/-// iOS asks YouTube from Safari's side of the world: its "IOS" client hands out plain URLs, while VISIONOS now hits-// "Sign in to confirm you're not a bot" there. Android keeps the client yt-dlp itself uses.-const DEFAULT_CLIENTS = Capacitor.getPlatform() === "ios" ? ["IOS", "VISIONOS"] : ["VISIONOS"];-const REMOTE_CONFIG = "https://raw.githubusercontent.com/Ernani1234/musike/main/mobile/streaming.json";--const CLIENTS_KEY = "musike:stream-clients";--interface Resolved {- url: string;- mime: string;- size: number;- title: string;- duration: number;- expiresAt: number;-}--const cache = new Map<string, Resolved>();-const inflight = new Map<string, Promise<Resolved>>();++const ios = Capacitor.getPlatform() === "ios";++// On iOS VISIONOS is bot-checked from the web view while the IOS client still answers; Android uses the client++// yt-dlp itself relies on.++const PLATFORM_CLIENTS = ios ? ["IOS", "VISIONOS"] : DEFAULT_CLIENTS;++const REMOTE_KEY = ios ? "ios" : "clients";++const CLIENTS_KEY = ios ? "musike:stream-clients-ios" : "musike:stream-clients";-const validClients = (v: unknown): string[] | null =>- Array.isArray(v) && v.length > 0 && v.every((c) => typeof c === "string" && /^[A-Z_]{2,30}$/.test(c)) ? (v as string[]) : null;+const cache = new Map<string, DirectAudio>();+const inflight = new Map<string, Promise<DirectAudio>>();function storedClients(): string[] {try {- return validClients(JSON.parse(localStorage.getItem(CLIENTS_KEY) ?? "null")) ?? DEFAULT_CLIENTS;- const stored = validClients(JSON.parse(localStorage.getItem(CLIENTS_KEY) ?? "null")) ?? [];- // This platform's own clients come first: a list saved by an older build (or another platform) must not hide them.- return [...new Set([...DEFAULT_CLIENTS, ...stored])];++ return validClients(JSON.parse(localStorage.getItem(CLIENTS_KEY) ?? "null")) ?? PLATFORM_CLIENTS;} catch {-- return DEFAULT_CLIENTS;++ return PLATFORM_CLIENTS;}}let clients = storedClients();-/** Picks up a newer client list in the background; the stored one (or the default) is used meanwhile. */-async function refreshClients() {+// Pick up a newer client list in the background; the stored one (or the default) is used meanwhile.- void fetchRemoteClients().then((remote) => {++void fetchRemoteClients(REMOTE_KEY).then((remote) => {+ if (!remote) return;+ clients = remote;try {- const res = await fetch(REMOTE_CONFIG, { signal: AbortSignal.timeout(6000) });- const remote = validClients(((await res.json()) as { clients?: unknown }).clients);- if (!remote) return;- const merged = [...new Set([...DEFAULT_CLIENTS, ...remote])];- clients = merged;- localStorage.setItem(CLIENTS_KEY, JSON.stringify(merged));+ localStorage.setItem(CLIENTS_KEY, JSON.stringify(remote));} catch {- // offline or no config yet: keep what we have+ /* storage unavailable: keep it for this session */}-}-void refreshClients();+});-async function resolve(id: string): Promise<Resolved> {- if (nativeResolverAvailable()) {- try {- const r = await resolveNatively(id, getLang() === "pt-BR" ? "pt-BR" : "en", config.location);- if (!r.error && r.url) {- const expire = Number(new URL(r.url).searchParams.get("expire")) * 1000;- const resolved: Resolved = {- url: r.url,- mime: r.mime || "audio/mp4",- size: 0,- title: r.title,- duration: r.duration,- expiresAt: expire || Date.now() + 3 * 3600_000,- };- cache.set(id, resolved);- return resolved;- }- } catch (e) {- // fall through to the in-app clients below- }++/** iOS: the native resolver, or null to fall back to the in-app clients. */++async function resolveOnIos(id: string): Promise<DirectAudio | null> {++ if (!nativeResolverAvailable()) return null;++ try {++ const r = await resolveNatively(id, getLang() === "pt-BR" ? "pt-BR" : "en", config.location);++ if (r.error || !r.url) return null;++ const expire = Number(new URL(r.url).searchParams.get("expire")) * 1000;++ return {++ url: r.url,++ mime: r.mime || "audio/mp4",++ title: r.title,++ duration: r.duration,++ expiresAt: expire || Date.now() + 3 * 3600_000,++ };++ } catch {++ return null;+ }++}+- let reason = "";- for (const client of clients) {- try {- const info: any = await withClient((yt) => yt.getBasicInfo(id, { client: client as never }), getLang());- const status = info.playability_status;- if (status?.status && status.status !== "OK") {- reason = text(status.reason) || reason;- continue;- }- const formats: any[] = [...(info.streaming_data?.adaptive_formats ?? []), ...(info.streaming_data?.formats ?? [])].filter(- (f) => f.has_audio && !f.has_video && typeof f.url === "string",- );- // AAC (m4a) first: every Android WebView plays it. Highest bitrate within the same kind.- const best = formats.sort(- (a, b) => Number(b.mime_type?.startsWith("audio/mp4")) - Number(a.mime_type?.startsWith("audio/mp4")) || (b.bitrate ?? 0) - (a.bitrate ?? 0),- )[0];- if (!best) continue;- const expire = Number(new URL(best.url).searchParams.get("expire")) * 1000;- const resolved: Resolved = {- url: best.url,- mime: String(best.mime_type ?? "audio/mp4"),- size: Number(best.content_length ?? 0),- title: info.basic_info?.title ?? "",- duration: info.basic_info?.duration ?? 0,- expiresAt: expire || Date.now() + 3 * 3600_000,- };- cache.set(id, resolved);- return resolved;- } catch (e) {- reason = (e as Error).message || reason;- }+async function resolve(id: string): Promise<DirectAudio> {++ const native = await resolveOnIos(id);++ if (native) {++ cache.set(id, native);++ return native;++ }+ try {+ const resolved = await directAudio(id, clients, getLang());+ cache.set(id, resolved);+ return resolved;+ } catch (e) {+ throw new ApiError(404, (e as Error).message || tr(getLang(), msg("noAudio")));}- throw new ApiError(404, reason || tr(getLang(), msg("noAudio")));}/** A track's stream, from cache while its URL is still good for a minute or more. */