Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

8/custom search #10

Merged
merged 2 commits into from
Apr 3, 2023
Merged
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
Binary file modified assets/screenshot2.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "sdh-gamethememusic",
"version": "1.1.0",
"version": "1.2.0",
"description": "Play theme songs on your game pages",
"scripts": {
"build": "shx rm -rf dist && rollup -c",
Expand Down
72 changes: 32 additions & 40 deletions src/actions/audio.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ServerAPI } from 'decky-frontend-lib'
import YouTubeVideo from '../../types/YouTube'

type YouTubeInitialData = {
contents: {
Expand All @@ -11,6 +12,9 @@ type YouTubeInitialData = {
videoRenderer: {
title: { runs: { text: string }[] }
videoId: string
thumbnail: {
thumbnails: { url: string }[]
}
}
}[]
}
Expand All @@ -23,13 +27,16 @@ type YouTubeInitialData = {

export async function getYouTubeSearchResults(
serverAPI: ServerAPI,
appName: string
): Promise<{ appName: string; title: string; id: string }[] | undefined> {
appName: string,
customSearch?: boolean
): Promise<YouTubeVideo[] | undefined> {
const searchTerm = `${encodeURIComponent(appName)}${
customSearch ? '' : '%20Theme%20Music'
}`
const req = {
method: 'GET',
url: `https://www.youtube.com/results?search_query=${encodeURIComponent(
appName
)}%20Theme%20Music`
url: `https://www.youtube.com/results?search_query=${searchTerm}&sp=EgIQAQ%253D%253D`,
timeout: 8000
}
const res = await serverAPI.callServerMethod<
{ method: string; url: string },
Expand All @@ -41,9 +48,7 @@ export async function getYouTubeSearchResults(

if (match) {
const ytInitialData: YouTubeInitialData = JSON.parse(match[1])
const results:
| { appName: string; title: string; id: string }[]
| undefined =
const results: YouTubeVideo[] | undefined =
ytInitialData?.contents?.twoColumnSearchResultsRenderer?.primaryContents?.sectionListRenderer?.contents
?.find(
(obj) =>
Expand All @@ -59,11 +64,14 @@ export async function getYouTubeSearchResults(
?.itemSectionRenderer?.contents?.filter((obj) =>
Object.prototype.hasOwnProperty.call(obj, 'videoRenderer')
)
.map((res) => ({
appName,
title: res?.videoRenderer?.title?.runs?.[0]?.text,
id: res?.videoRenderer?.videoId
}))
.map((res) => {
return {
appName,
title: res?.videoRenderer?.title?.runs?.[0]?.text,
id: res?.videoRenderer?.videoId,
thumbnail: res?.videoRenderer?.thumbnail?.thumbnails?.[0]?.url
}
})
.filter((res: { title: string; id: string }) => res.id?.length)
return results
} else {
Expand All @@ -75,15 +83,8 @@ export async function getYouTubeSearchResults(

export async function getAudioUrlFromVideoId(
serverAPI: ServerAPI,
video: {
appName: string
title: string
id: string
}
): Promise<
| { appName: string; title: string; videoId: string; audioUrl: string }
| undefined
> {
video: { title: string; id: string }
): Promise<string | undefined> {
const req = {
method: 'GET',
url: `https://www.youtube.com/watch?v=${encodeURIComponent(video.id)}`
Expand All @@ -101,7 +102,7 @@ export async function getAudioUrlFromVideoId(
}

const configJson = JSON.parse(configJsonMatch[1])
const streamMap = configJson.streamingData.adaptiveFormats.filter(
const streamMap = configJson?.streamingData?.adaptiveFormats?.filter(
(f: { mimeType: string }) => f.mimeType.startsWith('audio/')
)[0]
if (!streamMap?.url) return undefined
Expand All @@ -112,34 +113,25 @@ export async function getAudioUrlFromVideoId(
.find((s: string) => s.startsWith('s='))
.substr(2)
: undefined
return {
appName: video.appName,
title: video.title,
videoId: video.id,
audioUrl: `${streamMap.url}&${
signature ? `sig=${signature}` : 'ratebypass=yes'
}`
}
return `${streamMap.url}&${
signature ? `sig=${signature}` : 'ratebypass=yes'
}`
}
return undefined
}

export async function getAudio(
serverAPI: ServerAPI,
appName: string
): Promise<
| { appName: string; title: string; videoId: string; audioUrl: string }
| undefined
> {
): Promise<{ videoId: string; audioUrl: string } | undefined> {
const videos = await getYouTubeSearchResults(serverAPI, appName)
if (videos?.length) {
let audio:
| { appName: string; title: string; videoId: string; audioUrl: string }
| undefined
let audio: { videoId: string; audioUrl: string } | undefined
let i
for (i = 0; i < videos.length; i++) {
audio = await getAudioUrlFromVideoId(serverAPI, videos[i])
if (audio?.audioUrl?.length) {
const audioUrl = await getAudioUrlFromVideoId(serverAPI, videos[i])
if (audioUrl?.length) {
audio = { audioUrl, videoId: videos[i].id }
break
}
}
Expand Down
15 changes: 4 additions & 11 deletions src/cache/musicCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,11 @@ localforage.config({
})

type GameThemeMusicCache = {
appName: string
title: string
videoId: string
disabled?: boolean
videoId: string | undefined
}

export async function updateCache(appId: number, newData: GameThemeMusicCache) {
const oldCache = await localforage.getItem<GameThemeMusicCache>(
appId.toString()
)
const newCache: GameThemeMusicCache = { ...oldCache, ...newData }
await localforage.setItem(appId.toString(), newCache)
const newCache = await localforage.setItem(appId.toString(), newData)
return newCache
}

Expand All @@ -33,6 +26,6 @@ export function clearCache(appId?: number) {
export async function getCache(
appId: number
): Promise<GameThemeMusicCache | null> {
const data = await localforage.getItem<GameThemeMusicCache>(appId.toString())
return data
const cache = await localforage.getItem<GameThemeMusicCache>(appId.toString())
return cache
}
146 changes: 99 additions & 47 deletions src/components/changeTheme/audioPlayer.tsx
Original file line number Diff line number Diff line change
@@ -1,39 +1,44 @@
import {
DialogButton,
Focusable,
PanelSection,
PanelSectionRow
} from 'decky-frontend-lib'
import React, { useEffect, useRef } from 'react'
import { DialogButton, Focusable, ServerAPI } from 'decky-frontend-lib'
import React, { useEffect, useRef, useState } from 'react'
import useTranslations from '../../hooks/useTranslations'
import { getAudioUrlFromVideoId } from '../../actions/audio'
import YouTubeVideo from '../../../types/YouTube'

export default function AudioPlayer({
audio,
volume,
handlePlay,
selected,
selectNewAudio
selectNewAudio,
serverAPI,
video,
volume
}: {
audio: {
appName: string
title: string
videoId: string
audioUrl: string
isPlaying: boolean
}
serverAPI: ServerAPI
video: YouTubeVideo & { isPlaying: boolean }
volume: number
handlePlay: (startPlaying: boolean) => void
selected: boolean
selectNewAudio: (audio: {
appName: string
title: string
videoId: string
videoId: string | undefined
audioUrl: string
disabled: false
}) => void
}) {
const t = useTranslations()
const audioRef = useRef<HTMLAudioElement>(null)
const [loading, setLoading] = useState(true)
const [audioUrl, setAudio] = useState<string | undefined>()

useEffect(() => {
async function getData() {
setLoading(true)
const res = await getAudioUrlFromVideoId(serverAPI, video)
setAudio(res)
setLoading(false)
}
if (video.id.length) {
getData()
}
}, [video.id])

useEffect(() => {
if (audioRef.current) {
Expand All @@ -43,50 +48,97 @@ export default function AudioPlayer({

useEffect(() => {
if (audioRef.current) {
audio.isPlaying ? audioRef.current.play() : audioRef.current.pause()
video.isPlaying ? audioRef.current.play() : audioRef.current.pause()
}
}, [audio.isPlaying])
}, [video.isPlaying])

function togglePlay() {
if (audioRef?.current) {
audioRef.current.currentTime = 0
handlePlay(!audio.isPlaying)
handlePlay(!video.isPlaying)
}
}

function selectAudio() {
selectNewAudio({
appName: audio.appName,
title: audio.title,
videoId: audio.videoId,
audioUrl: audio.audioUrl,
disabled: false
})
if (audioUrl?.length && video.id.length)
selectNewAudio({
title: video.title,
videoId: video.id,
audioUrl: audioUrl
})
}
if (!loading && !audioUrl) return <></>
return (
<PanelSection title={audio.title}>
<div>
<Focusable
style={{
background: selected
? 'var(--main-light-blue-background)'
: 'var(--main-editor-bg-color)',
borderRadius: '6px',
display: 'grid',
gridTemplateRows: '129px max-content max-content',
overflow: 'hidden',
padding: '10px',
width: '230px'
}}
>
<img
src={video.thumbnail}
alt={video.title}
style={{
overflow: 'hidden',
width: '230px',
height: '129px',
borderRadius: '6px'
}}
/>
<p
style={{
color: selected
? 'var(--main-editor-bg-color)'
: 'var(--main-editor-text-color)',
overflow: 'hidden',
textOverflow: 'ellipsis',
width: '230px',
height: '68px'
}}
>
{video.title}
</p>

<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '6px',
width: '230px'
}}
>
<DialogButton
onClick={togglePlay}
disabled={loading}
focusable={!loading}
>
{video.isPlaying ? t('stop') : t('play')}
</DialogButton>
<DialogButton
disabled={selected || loading}
focusable={!selected && !loading}
onClick={selectAudio}
>
{selected ? t('selected') : t('select')}
</DialogButton>
</div>
</Focusable>
<audio
ref={audioRef}
src={audio.audioUrl}
src={audioUrl}
autoPlay={false}
controlsList="nodownload"
onPlay={() => audioRef.current?.play()}
onPause={() => audioRef.current?.pause()}
></audio>
<PanelSectionRow>
<Focusable style={{ display: 'flex', gap: '6px' }}>
<DialogButton onClick={togglePlay}>
{audio.isPlaying ? t('stop') : t('play')}
</DialogButton>
<DialogButton
disabled={selected}
focusable={!selected}
onClick={selectAudio}
>
{selected ? t('selected') : t('select')}
</DialogButton>
</Focusable>
</PanelSectionRow>
</PanelSection>
</div>
)
}
Loading