Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {addToHistory, loadHistory} from './lib/history.js'
import {detectPlatform, isProbablyUrl, type Platform} from './lib/platforms.js'
import {useMouseClick} from './lib/use-mouse-click.js'
import {nextThemeMode, ThemeProvider, type ThemeMode, useTheme} from './theme.js'
import {spotifyProbe} from './lib/spotify.js'
import {
buildChoices,
download,
Expand Down Expand Up @@ -178,16 +179,20 @@ function AppContent({
const startProbe = useCallback(async (targetUrl: string) => {
const controller = new AbortController()
abortRef.current = controller
setPlatform(detectPlatform(targetUrl))
const detectedPlatform = detectPlatform(targetUrl)
setPlatform(detectedPlatform)
setPhase({name: 'probing', status: 'warming up…'})
try {
const ytdlp =
ytdlpRef.current ||
(await ensureYtDlp(status => setPhase({name: 'probing', status}), controller.signal))
ytdlpRef.current = ytdlp
if (controller.signal.aborted) return
setPhase({name: 'probing', status: 'fetching video info…'})
const {info: videoInfo, infoJsonPath} = await probe(ytdlp, targetUrl, controller.signal)
const isSpotify = detectedPlatform.key === 'spotify'
setPhase({name: 'probing', status: isSpotify ? 'resolving Spotify track…' : 'fetching video info…'})
const {info: videoInfo, infoJsonPath} = isSpotify
? await spotifyProbe(ytdlp, targetUrl, controller.signal)
: await probe(ytdlp, targetUrl, controller.signal)
if (controller.signal.aborted) return
infoJsonRef.current = infoJsonPath
setInfo(videoInfo)
Expand Down Expand Up @@ -341,7 +346,7 @@ function AppContent({
<Logo />
<Gap />
<Text color={theme.primary}>{TAGLINE}</Text>
<Text color={theme.gray} dimColor={theme.dimSecondary}>youtube · x · instagram · threads · tiktok · +1800 more</Text>
<Text color={theme.gray} dimColor={theme.dimSecondary}>youtube · x · instagram · threads · tiktok · spotify · +1800 more</Text>
<Gap />

{phase.name === 'input' && (
Expand Down
1 change: 1 addition & 0 deletions src/lib/platforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const PLATFORMS: Array<{hosts: string[]; platform: Platform}> = [
{hosts: ['twitch.tv'], platform: {key: 'twitch', label: 'Twitch'}},
{hosts: ['reddit.com'], platform: {key: 'reddit', label: 'Reddit'}},
{hosts: ['facebook.com', 'fb.watch'], platform: {key: 'facebook', label: 'Facebook'}},
{hosts: ['open.spotify.com', 'spotify.link'], platform: {key: 'spotify', label: 'Spotify'}},
]

export function detectPlatform(url: string): Platform {
Expand Down
84 changes: 84 additions & 0 deletions src/lib/spotify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import {spawn} from 'node:child_process'
import os from 'node:os'
import path from 'node:path'
import fs from 'node:fs/promises'
import type {ProbeResult, VideoInfo} from './ytdlp.js'

const OEMBED_BASE = 'https://open.spotify.com/oembed'

type SpotifyOEmbed = {
title: string
thumbnail_url?: string
provider_name: string
}

export function extractSpotifyId(url: string): string | null {
try {
const u = new URL(url)
const match = u.pathname.match(/\/(track|album|playlist|artist)\/([A-Za-z0-9]{22})/)
return match ? match[2] : null
} catch {
return null
}
}

export async function fetchSpotifyTrackMeta(url: string): Promise<{
title: string
thumbnail?: string
searchQuery: string
}> {
const resp = await fetch(`${OEMBED_BASE}?url=${encodeURIComponent(url)}`)
if (!resp.ok) throw new Error(`Spotify oEmbed failed (${resp.status})`)
const data = (await resp.json()) as SpotifyOEmbed
const title = data.title
const thumbnail = data.thumbnail_url
// use title stripped of " - Remastered YYYY" suffixes for better search
const cleanTitle = title.replace(/\s*-\s*(Remaster|Remastered|Live|Deluxe|Edition|Version)\s*\d{0,4}$/i, '').trim()
const searchQuery = `${cleanTitle} audio`
return {title, thumbnail, searchQuery}
}

export async function spotifyProbe(
ytdlp: string,
url: string,
signal?: AbortSignal,
): Promise<ProbeResult> {
const {title, searchQuery} = await fetchSpotifyTrackMeta(url)

const stdout = await new Promise<string>((resolve, reject) => {
const child = spawn(
ytdlp,
['-J', '--no-playlist', '--no-warnings', '-f', 'ba/b', '--prefer-free-formats', `ytsearch1:${searchQuery}`],
{signal},
)
let out = ''
let stderr = ''
child.stdout.on('data', chunk => (out += chunk))
child.stderr.on('data', chunk => (stderr += chunk))
child.on('error', reject)
child.on('close', code => {
if (code !== 0) {
const err = stderr.trim().split('\n').filter(l => l.includes('ERROR:')).pop() ?? ''
reject(new Error(err.replace(/^ERROR:\s*/, '') || `No match found for "${title}" on YouTube`))
} else {
resolve(out)
}
})
})

let data: {entries?: unknown[]; _type?: string}
try {
data = JSON.parse(stdout)
} catch {
throw new Error('Could not parse yt-dlp search results.')
}

if (data._type === 'playlist' && data.entries && data.entries.length > 0) {
const entry = data.entries[0] as VideoInfo
const infoJsonPath = path.join(os.tmpdir(), `yoinks-info-${process.pid}-${Date.now()}.json`)
await fs.writeFile(infoJsonPath, JSON.stringify(entry))
return {info: entry, infoJsonPath}
}

throw new Error(`No YouTube result found for "${title}".`)
}