Compare commits
63 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4127fd1181 | |||
| 6c99b96b12 | |||
| acbaf2ed1c | |||
| e7ed89056e | |||
| b5432e3e5f | |||
| 13664c3cec | |||
| 0b4a551744 | |||
| ed75c2fff7 | |||
| bd7d988741 | |||
| deac6081ca | |||
| e09ae15e32 | |||
| 33af131b77 | |||
| 3d6d4918bc | |||
| 35ad858d0d | |||
| af827a9a96 | |||
| 2cf9559b0b | |||
| 20336ea716 | |||
| 8b7b38276e | |||
| 8496922aaf | |||
| 5e3ad48a2d | |||
| 005ac8fde3 | |||
| 1f0b9de456 | |||
| 3388757185 | |||
| 8049d02457 | |||
| 1b55b7117c | |||
| 15f8a098b5 | |||
| 2d7d49b91c | |||
| df9c519439 | |||
| 2bf1c229c7 | |||
| b2e9e5c16c | |||
| 41c0002090 | |||
| c0252fc9b8 | |||
| 0c3506beb5 | |||
| ef9fc13aaa | |||
| 0b0637b9dc | |||
| e73e608b9f | |||
| ebed49237c | |||
| dc2b22eaa5 | |||
| 2bb612ee07 | |||
| dc855ab8a0 | |||
| f976bdc2b7 | |||
| 1cf3361e59 | |||
| ada441300a | |||
| 6134dea044 | |||
| 93d5925dfd | |||
| de6d0ccbf6 | |||
| cda29bcb95 | |||
| 3775a9801d | |||
| a9589e7686 | |||
| c52fa14e42 | |||
| 116d095ad5 | |||
| b280af484c | |||
| 5dce21c038 | |||
| d2c46631ef | |||
| 67032460ff | |||
| 0f3ffcf934 | |||
| c813949d48 | |||
| eb220386ce | |||
| 19eae4fd5a | |||
| e70469b1ec | |||
| 30b7ff57d3 | |||
| fd689aba04 | |||
| 8eaca82ce9 |
8
.github/workflows/release.yml
vendored
@@ -37,7 +37,7 @@ jobs:
|
|||||||
plat: darwin
|
plat: darwin
|
||||||
steps:
|
steps:
|
||||||
- name: Check out repo
|
- name: Check out repo
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v5
|
||||||
|
|
||||||
- name: Set up Bun
|
- name: Set up Bun
|
||||||
uses: oven-sh/setup-bun@v2
|
uses: oven-sh/setup-bun@v2
|
||||||
@@ -78,7 +78,7 @@ jobs:
|
|||||||
./podtui-*/podtui --version
|
./podtui-*/podtui --version
|
||||||
|
|
||||||
- name: Upload artifact
|
- name: Upload artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v6
|
||||||
with:
|
with:
|
||||||
name: podtui-${{ matrix.plat }}-${{ matrix.arch }}
|
name: podtui-${{ matrix.plat }}-${{ matrix.arch }}
|
||||||
path: dist/podtui-*.tar.gz
|
path: dist/podtui-*.tar.gz
|
||||||
@@ -89,12 +89,12 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Download all binaries
|
- name: Download all binaries
|
||||||
uses: actions/download-artifact@v4
|
uses: actions/download-artifact@v7
|
||||||
with:
|
with:
|
||||||
path: artifacts
|
path: artifacts
|
||||||
|
|
||||||
- name: Publish release
|
- name: Publish release
|
||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@v3
|
||||||
with:
|
with:
|
||||||
generate_release_notes: true
|
generate_release_notes: true
|
||||||
files: |
|
files: |
|
||||||
|
|||||||
1
.gitignore
vendored
@@ -34,3 +34,4 @@ report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
|||||||
.DS_Store
|
.DS_Store
|
||||||
.harness/
|
.harness/
|
||||||
.ralpi
|
.ralpi
|
||||||
|
notes.md
|
||||||
|
|||||||
14
README.md
@@ -161,6 +161,9 @@ All keys are remappable — edit `keybinds.jsonc` in your config directory
|
|||||||
| `.` | Toggle hidden |
|
| `.` | Toggle hidden |
|
||||||
| `r` | Refresh |
|
| `r` | Refresh |
|
||||||
| `x` | Unsubscribe the focused show (My Shows) |
|
| `x` | Unsubscribe the focused show (My Shows) |
|
||||||
|
| `d` | Download the focused episode (Feed / My Shows detail pane) |
|
||||||
|
| `D` | Delete the focused episode's download (if one exists) |
|
||||||
|
| `w` | Toggle the focused show in/out of the auto-download whitelist (My Shows, whitelist scope) |
|
||||||
|
|
||||||
**Audio**
|
**Audio**
|
||||||
|
|
||||||
@@ -185,7 +188,16 @@ default (`$XDG_CONFIG_HOME/podtui` if set).
|
|||||||
Legacy `feeds.json`, `sources.json`, and `app-state.json` are auto-migrated
|
Legacy `feeds.json`, `sources.json`, and `app-state.json` are auto-migrated
|
||||||
into `config.json` on first run.
|
into `config.json` on first run.
|
||||||
|
|
||||||
Env overrides: `PODTUI_AUDIO_BACKEND`, `XDG_CONFIG_HOME`.
|
**Auto-download** — in Settings → Preferences: `Auto Download` (master
|
||||||
|
toggle) downloads the `Auto Download Count` most recent episodes (default 2,
|
||||||
|
any positive integer — type it in the editor) of every show in the `Auto
|
||||||
|
Download Scope` (all / none / whitelist, default all). With the whitelist
|
||||||
|
scope, a search field appears under the setting to pick shows (Space toggles
|
||||||
|
a suggestion in/out), and `w` in My Shows adds/removes the focused show.
|
||||||
|
|
||||||
|
Env overrides: `PODTUI_AUDIO_BACKEND`, `XDG_CONFIG_HOME`, `PODTUI_NERD_FONTS`.
|
||||||
|
|
||||||
|
**Fonts** — PodTui prepends Nerd Font glyphs to non-episode/show list rows (tabs, Discover categories, Settings sections, the Feed and per-show "Fetch More" rows). Icons are hidden automatically when your terminal font is not Nerd Font capable (no tofu, no layout gaps); detection is heuristic (terminal type), so force it with `PODTUI_NERD_FONTS=1` or `=0` if it guesses wrong. A Nerd Font-patched font (e.g. JetBrainsMono Nerd Font) is recommended.
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
|
|||||||
|
After Width: | Height: | Size: 465 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 759 B |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 2.9 KiB |
|
After Width: | Height: | Size: 5.2 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 154 KiB |
|
After Width: | Height: | Size: 5.0 KiB |
|
After Width: | Height: | Size: 8.7 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 5.6 KiB |
|
After Width: | Height: | Size: 7.1 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 154 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 28 KiB |
@@ -0,0 +1 @@
|
|||||||
|
<svg width="400" xmlns="http://www.w3.org/2000/svg" height="125.714" id="screenshot-993fe4cb-279d-80e0-8008-769a7b1374b8" viewBox="0 0 400 125.714" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1"><g id="shape-993fe4cb-279d-80e0-8008-769a7b1374b8" rx="0" ry="0"><g id="shape-993fe4cb-279d-80e0-8008-769a7a62c77d"><g class="fills" id="fills-993fe4cb-279d-80e0-8008-769a7a62c77d"><rect rx="6.857142857142833" ry="6.857142857142833" x="0" y="56" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)" width="34.28571428571428" height="13.714285714285666" style="fill: rgb(136, 192, 208); fill-opacity: 1;"/></g></g><g id="shape-993fe4cb-279d-80e0-8008-769a7a89c956"><g class="fills" id="fills-993fe4cb-279d-80e0-8008-769a7a89c956"><rect rx="15" ry="15" x="45.71428571428572" y="45.714285714285666" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)" width="34.28571428571428" height="34.285714285714334" style="fill: rgb(136, 192, 208); fill-opacity: 1;"/></g></g><g id="shape-993fe4cb-279d-80e0-8008-769a7a9fe4f2"><g class="fills" id="fills-993fe4cb-279d-80e0-8008-769a7a9fe4f2"><rect rx="15" ry="15" x="91.42857142857144" y="33.14285714285711" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)" width="34.28571428571428" height="59.428571428571445" style="fill: rgb(136, 192, 208); fill-opacity: 1;"/></g></g><g id="shape-993fe4cb-279d-80e0-8008-769a7ab46172"><g class="fills" id="fills-993fe4cb-279d-80e0-8008-769a7ab46172"><rect rx="15" ry="15" x="137.1428571428571" y="18.285714285714306" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)" width="34.285714285714334" height="89.14285714285714" style="fill: rgb(136, 192, 208); fill-opacity: 1;"/></g></g><g id="shape-993fe4cb-279d-80e0-8008-769a7ac82b71"><g class="fills" id="fills-993fe4cb-279d-80e0-8008-769a7ac82b71"><rect rx="15" ry="15" x="182.85714285714283" y="0" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)" width="34.285714285714334" height="125.71428571428578" style="fill: rgb(136, 192, 208); fill-opacity: 1;"/></g></g><g id="shape-993fe4cb-279d-80e0-8008-769a7ad6c7b7"><g class="fills" id="fills-993fe4cb-279d-80e0-8008-769a7ad6c7b7"><rect rx="15" ry="15" x="228.57142857142856" y="18.285714285714306" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)" width="34.28571428571428" height="89.14285714285714" style="fill: rgb(136, 192, 208); fill-opacity: 1;"/></g></g><g id="shape-993fe4cb-279d-80e0-8008-769a7aea70cd"><g class="fills" id="fills-993fe4cb-279d-80e0-8008-769a7aea70cd"><rect rx="15" ry="15" x="274.28571428571433" y="33.14285714285711" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)" width="34.28571428571428" height="59.428571428571445" style="fill: rgb(136, 192, 208); fill-opacity: 1;"/></g></g><g id="shape-993fe4cb-279d-80e0-8008-769a7af77904"><g class="fills" id="fills-993fe4cb-279d-80e0-8008-769a7af77904"><rect rx="15" ry="15" x="320" y="45.714285714285666" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)" width="34.28571428571428" height="34.285714285714334" style="fill: rgb(59, 66, 82); fill-opacity: 1;"/></g></g><g id="shape-993fe4cb-279d-80e0-8008-769a7b04705e"><g class="fills" id="fills-993fe4cb-279d-80e0-8008-769a7b04705e"><rect rx="6.857142857142833" ry="6.857142857142833" x="365.7142857142858" y="56" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)" width="34.28571428571428" height="13.714285714285666" style="fill: rgb(59, 66, 82); fill-opacity: 1;"/></g></g></g></svg>
|
||||||
|
After Width: | Height: | Size: 3.6 KiB |
1
assets/App Icon/App Icon.icon/Assets/Terminal Cursor.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg width="80" xmlns="http://www.w3.org/2000/svg" height="256" id="screenshot-993fe4cb-279d-80e0-8008-76a1e45d35f1" viewBox="0 0 80 256" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1"><g id="shape-993fe4cb-279d-80e0-8008-76a1e45d35f1"><g class="fills" id="fills-993fe4cb-279d-80e0-8008-76a1e45d35f1"><rect rx="10" ry="10" x="0" y="0" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)" width="80" height="256" style="fill: rgb(136, 192, 208); fill-opacity: 1;"/></g></g></svg>
|
||||||
|
After Width: | Height: | Size: 526 B |
51
assets/App Icon/App Icon.icon/icon.json
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
{
|
||||||
|
"fill" : {
|
||||||
|
"solid" : "display-p3:0.18481,0.20325,0.24683,1.00000"
|
||||||
|
},
|
||||||
|
"groups" : [
|
||||||
|
{
|
||||||
|
"layers" : [
|
||||||
|
{
|
||||||
|
"glass" : false,
|
||||||
|
"image-name" : "Podcast Waveform.svg",
|
||||||
|
"name" : "Podcast Waveform",
|
||||||
|
"position" : {
|
||||||
|
"scale" : 2,
|
||||||
|
"translation-in-points" : [
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"blend-mode" : "normal",
|
||||||
|
"fill" : "automatic",
|
||||||
|
"glass" : false,
|
||||||
|
"image-name" : "Terminal Cursor.svg",
|
||||||
|
"name" : "Terminal Cursor",
|
||||||
|
"position" : {
|
||||||
|
"scale" : 2,
|
||||||
|
"translation-in-points" : [
|
||||||
|
320.00000000000006,
|
||||||
|
0
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"shadow" : {
|
||||||
|
"kind" : "neutral",
|
||||||
|
"opacity" : 0.5
|
||||||
|
},
|
||||||
|
"translucency" : {
|
||||||
|
"enabled" : true,
|
||||||
|
"value" : 0.5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"supported-platforms" : {
|
||||||
|
"circles" : [
|
||||||
|
"watchOS"
|
||||||
|
],
|
||||||
|
"squares" : "shared"
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
assets/App Icon/App Icon.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
1
assets/App Icon/App Icon.svg
Normal file
|
After Width: | Height: | Size: 5.0 KiB |
BIN
assets/App Icon/App Icon_2x.png
Normal file
|
After Width: | Height: | Size: 26 KiB |
BIN
assets/App Icon/App Icon_4x.png
Normal file
|
After Width: | Height: | Size: 59 KiB |
BIN
assets/App Icon/App Icon_6x.png
Normal file
|
After Width: | Height: | Size: 100 KiB |
15
build.ts
@@ -116,6 +116,21 @@ if (COMPILE) {
|
|||||||
const s = join("dist", lib);
|
const s = join("dist", lib);
|
||||||
if (existsSync(s)) copyFileSync(s, join(tarRoot, lib));
|
if (existsSync(s)) copyFileSync(s, join(tarRoot, lib));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// App icon: bundled into every platform tarball; Linux also gets the
|
||||||
|
// desktop entry so the AUR package can install both system-wide
|
||||||
|
// (icon to hicolor, entry to applications/).
|
||||||
|
const iconSrc = join("assets", "App Icon", "App Icon.png");
|
||||||
|
if (existsSync(iconSrc)) {
|
||||||
|
copyFileSync(iconSrc, join(tarRoot, "podtui.png"));
|
||||||
|
}
|
||||||
|
if (platform === "linux") {
|
||||||
|
const desktopSrc = join("packaging", "podtui.desktop");
|
||||||
|
if (existsSync(desktopSrc)) {
|
||||||
|
copyFileSync(desktopSrc, join(tarRoot, "podtui.desktop"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const tar = Bun.spawnSync([
|
const tar = Bun.spawnSync([
|
||||||
"tar",
|
"tar",
|
||||||
"-czf",
|
"-czf",
|
||||||
|
|||||||
@@ -51,5 +51,13 @@ package() {
|
|||||||
install -Dm644 "${srcdir}/${libdir}/libcavacore.so" "${pkgdir}/usr/lib/podtui/libcavacore.so"
|
install -Dm644 "${srcdir}/${libdir}/libcavacore.so" "${pkgdir}/usr/lib/podtui/libcavacore.so"
|
||||||
install -Dm644 "${srcdir}/${libdir}/libopentui.so" "${pkgdir}/usr/lib/podtui/libopentui.so"
|
install -Dm644 "${srcdir}/${libdir}/libopentui.so" "${pkgdir}/usr/lib/podtui/libopentui.so"
|
||||||
ln -s /usr/lib/podtui/podtui "${pkgdir}/usr/bin/podtui"
|
ln -s /usr/lib/podtui/podtui "${pkgdir}/usr/bin/podtui"
|
||||||
|
|
||||||
|
# App icon + desktop entry ship inside the release tarball; Terminal=true
|
||||||
|
# makes launchers drop the TUI into a terminal window.
|
||||||
|
install -Dm644 "${srcdir}/${libdir}/podtui.png" \
|
||||||
|
"${pkgdir}/usr/share/icons/hicolor/512x512/apps/podtui.png"
|
||||||
|
install -Dm644 "${srcdir}/${libdir}/podtui.desktop" \
|
||||||
|
"${pkgdir}/usr/share/applications/podtui.desktop"
|
||||||
|
|
||||||
install -Dm644 "${srcdir}/LICENSE" "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
|
install -Dm644 "${srcdir}/LICENSE" "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
|
||||||
}
|
}
|
||||||
11
packaging/podtui.desktop
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
[Desktop Entry]
|
||||||
|
Type=Application
|
||||||
|
Name=PodTui
|
||||||
|
GenericName=Podcast Player
|
||||||
|
Comment=Terminal podcast and audio player with waveform visualization
|
||||||
|
Exec=podtui
|
||||||
|
Icon=podtui
|
||||||
|
Terminal=true
|
||||||
|
Categories=Audio;AudioVideo;Player;
|
||||||
|
Keywords=podcast;audio;player;terminal;
|
||||||
|
StartupNotify=false
|
||||||
@@ -18,22 +18,21 @@ const DEBUG = import.meta.env.DEBUG;
|
|||||||
|
|
||||||
export function App() {
|
export function App() {
|
||||||
const nav = useNavigation();
|
const nav = useNavigation();
|
||||||
const audio = useAudio();
|
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
const renderer = useRenderer();
|
const renderer = useRenderer();
|
||||||
const themeContext = useTheme();
|
const themeContext = useTheme();
|
||||||
const theme = themeContext.theme;
|
const theme = themeContext.theme;
|
||||||
const keybind = useKeybinds();
|
const keybind = useKeybinds();
|
||||||
|
|
||||||
// Multimedia keys (physical play/seek keys) still feed the audio backend
|
// Multimedia keys (physical play/volume/speed keys) still feed the audio
|
||||||
// regardless of the on-screen yazi keybinds.
|
// backend regardless of the on-screen yazi keybinds. Seek lives on the
|
||||||
|
// keybind router (< / > = shift+, / shift+.), so arrows stay on navigation.
|
||||||
useMultimediaKeys({
|
useMultimediaKeys({
|
||||||
playerFocused: () =>
|
playerFocused: () =>
|
||||||
nav.activeTab() === TABS.PLAYER && nav.mode() !== NavMode.NORMAL
|
nav.activeTab() === TABS.PLAYER && nav.mode() !== NavMode.NORMAL
|
||||||
? true
|
? true
|
||||||
: false,
|
: false,
|
||||||
inputFocused: () => nav.inputFocused(),
|
inputFocused: () => nav.inputFocused(),
|
||||||
hasEpisode: () => !!audio.currentEpisode(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Mouse text-selection → clipboard (unchanged from the old shell).
|
// Mouse text-selection → clipboard (unchanged from the old shell).
|
||||||
|
|||||||
@@ -74,15 +74,28 @@ const parseEpisodeType = (raw: string): EpisodeType | undefined => {
|
|||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
export const parseRSSFeed = (xml: string, feedUrl: string): Podcast & { episodes: Episode[] } => {
|
/** Extract the `<item>` blocks from an RSS document. Matches items directly
|
||||||
const channel = xml.match(/<channel[\s\S]*?<\/channel>/i)?.[0] ?? xml
|
* on the full XML string — scoping to <channel> first is a redundant 5MB
|
||||||
const title = cleanField(getTagValue(channel, "title")) || "Untitled Podcast"
|
* regex pass that doubles parse cost with no practical benefit (well-formed
|
||||||
const description = cleanField(getTagValue(channel, "description"))
|
* RSS has no items outside <channel>). */
|
||||||
const author = decodeEntities(getTagValue(channel, "itunes:author"))
|
export const getRSSItems = (xml: string): string[] => {
|
||||||
const lastUpdated = new Date()
|
return xml.match(/<item[\s\S]*?<\/item>/gi) ?? []
|
||||||
|
}
|
||||||
|
|
||||||
const items = channel.match(/<item[\s\S]*?<\/item>/gi) ?? []
|
/** Channel-level artwork: `<itunes:image href>` (podcasts) or RSS 2.0
|
||||||
const episodes = items.map((item, index) => {
|
* `<image><url>`. Works on the full XML — channel-level tags precede
|
||||||
|
* <item> blocks in RSS, so the first match is the channel image. */
|
||||||
|
export const parseChannelCoverUrl = (xml: string): string | undefined => {
|
||||||
|
const itunesHref = getAttr(xml, "itunes:image", "href")
|
||||||
|
if (itunesHref) return itunesHref
|
||||||
|
const url = getTagValue(xml, "image").match(/<url>([\s\S]*?)<\/url>/i)?.[1]
|
||||||
|
return url?.trim() || undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse a single `<item>` into an Episode. Exported so the feed store can
|
||||||
|
* parse large feeds in bounded chunks (yielding to the event loop between
|
||||||
|
* chunks) instead of one synchronous block. */
|
||||||
|
export const parseRSSItem = (item: string, feedUrl: string, index: number): Episode => {
|
||||||
const epTitle = cleanField(getTagValue(item, "title")) || `Episode ${index + 1}`
|
const epTitle = cleanField(getTagValue(item, "title")) || `Episode ${index + 1}`
|
||||||
const epDescription = cleanField(getTagValue(item, "description"))
|
const epDescription = cleanField(getTagValue(item, "description"))
|
||||||
const pubDate = new Date(getTagValue(item, "pubDate") || Date.now())
|
const pubDate = new Date(getTagValue(item, "pubDate") || Date.now())
|
||||||
@@ -132,7 +145,20 @@ export const parseRSSFeed = (xml: string, feedUrl: string): Podcast & { episodes
|
|||||||
if (mimeType) ep.mimeType = mimeType
|
if (mimeType) ep.mimeType = mimeType
|
||||||
|
|
||||||
return ep
|
return ep
|
||||||
})
|
}
|
||||||
|
|
||||||
|
/** Parse a full RSS document (channel metadata + all episodes). The sync
|
||||||
|
* whole-feed variant — callers that parse potentially huge feeds on a UI
|
||||||
|
* thread should prefer the store's chunked incremental parse instead. */
|
||||||
|
export const parseRSSFeed = (xml: string, feedUrl: string): Podcast & { episodes: Episode[] } => {
|
||||||
|
const channel = xml.match(/<channel[\s\S]*?<\/channel>/i)?.[0] ?? xml
|
||||||
|
const title = cleanField(getTagValue(channel, "title")) || "Untitled Podcast"
|
||||||
|
const description = cleanField(getTagValue(channel, "description"))
|
||||||
|
const author = decodeEntities(getTagValue(channel, "itunes:author"))
|
||||||
|
const lastUpdated = new Date()
|
||||||
|
|
||||||
|
const items = getRSSItems(xml)
|
||||||
|
const episodes = items.map((item, index) => parseRSSItem(item, feedUrl, index))
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: feedUrl,
|
id: feedUrl,
|
||||||
@@ -142,6 +168,7 @@ export const parseRSSFeed = (xml: string, feedUrl: string): Podcast & { episodes
|
|||||||
feedUrl,
|
feedUrl,
|
||||||
lastUpdated,
|
lastUpdated,
|
||||||
isSubscribed: true,
|
isSubscribed: true,
|
||||||
|
coverUrl: parseChannelCoverUrl(channel),
|
||||||
episodes,
|
episodes,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
35
src/components/GlobalActivityIndicator.tsx
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import { Show } from "solid-js";
|
||||||
|
import { useFeedStore } from "@/stores/feed";
|
||||||
|
import { useSearchStore } from "@/stores/search";
|
||||||
|
import { useDownloadStore } from "@/stores/download";
|
||||||
|
import { useActivityStore } from "@/stores/activity";
|
||||||
|
import { LoadingIndicator } from "@/components/LoadingIndicator";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GlobalActivityIndicator — one global top-right signal that ANY feed
|
||||||
|
* refresh, fetch-more, subscribe fetch, search, or download is in flight.
|
||||||
|
* Per-page spinners are unchanged; this overlays the content row and status
|
||||||
|
* bar as a single app-wide "something is happening" indicator.
|
||||||
|
*/
|
||||||
|
export function GlobalActivityIndicator() {
|
||||||
|
const feedStore = useFeedStore();
|
||||||
|
const searchStore = useSearchStore();
|
||||||
|
const downloadStore = useDownloadStore();
|
||||||
|
const activity = useActivityStore();
|
||||||
|
|
||||||
|
/** True while any tracked activity is in flight */
|
||||||
|
const isActive = () =>
|
||||||
|
feedStore.isLoadingFeeds() ||
|
||||||
|
feedStore.isLoadingMore() ||
|
||||||
|
searchStore.isSearching() ||
|
||||||
|
downloadStore.getActiveCount() + downloadStore.getQueue().length > 0 ||
|
||||||
|
activity.isActive();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Show when={isActive()}>
|
||||||
|
<box position="absolute" top={0} right={0} paddingRight={1}>
|
||||||
|
<LoadingIndicator />
|
||||||
|
</box>
|
||||||
|
</Show>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
/**
|
/**
|
||||||
* PaneRow — the shared parent | current | preview 3-pane layout primitive.
|
* PaneRow — the shared parent | current | preview 3-pane layout primitive.
|
||||||
*
|
*
|
||||||
* Implements yazi's `mgr.ratio = [1, 2, 2]` contract: three columns grow at
|
* Implements yazi's `mgr.ratio` contract: three columns grow at
|
||||||
* 1/5 : 2/5 : 2/5 of the row width via Yoga `flexGrow`, so every list tab
|
* 20% : 50% : 30% (PANE_RATIO 2:5:3) of the row width via Yoga `flexGrow`,
|
||||||
* renders an identical, layout-stable shell. Columns use `flexBasis={0}` so
|
* so every list tab renders an identical, layout-stable shell. Columns use
|
||||||
* the ratio is exact regardless of content width — a column's content can
|
* `flexBasis={0}` so the ratio is exact regardless of content width — a
|
||||||
* never stretch its slot.
|
* column's content can never stretch its slot.
|
||||||
*
|
*
|
||||||
* Column semantics (per the yazi depth model):
|
* Column semantics (per the yazi depth model):
|
||||||
* parent — the previous-depth list. Renders a muted `—` placeholder and
|
* parent — the previous-depth list. Renders a muted `—` placeholder and
|
||||||
* KEEPS its 1/5 slot when blank (never collapses to width 0).
|
* KEEPS its 20% slot when blank (never collapses to width 0).
|
||||||
* Borderless (no left/right/top/bottom edge). Carries the single
|
* Borderless (no left/right/top/bottom edge). Carries the single
|
||||||
* header row: the CURRENT column's title renders top-left in the
|
* header row: the CURRENT column's title renders top-left in the
|
||||||
* parent's slot (the panes above current/preview were removed).
|
* parent's slot (the panes above current/preview were removed).
|
||||||
@@ -63,6 +63,9 @@ export type PaneRowProps = {
|
|||||||
/** Number of visible columns. `3` (default) = parent|current|preview;
|
/** Number of visible columns. `3` (default) = parent|current|preview;
|
||||||
* `2` = parent|current (preview omitted, current grows to fill). */
|
* `2` = parent|current (preview omitted, current grows to fill). */
|
||||||
panes?: 2 | 3;
|
panes?: 2 | 3;
|
||||||
|
/** Which sides of the current column's border render. Defaults to
|
||||||
|
* `["left", "right"]` (the standard focused-list frame). */
|
||||||
|
currentBorder?: boolean | BorderSides[];
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── Helpers ─────────────────────────────────────────────────────────────────
|
// ── Helpers ─────────────────────────────────────────────────────────────────
|
||||||
@@ -181,10 +184,13 @@ export function PaneRow(props: PaneRowProps) {
|
|||||||
? PANE_RATIO.current + PANE_RATIO.preview
|
? PANE_RATIO.current + PANE_RATIO.preview
|
||||||
: PANE_RATIO.current,
|
: PANE_RATIO.current,
|
||||||
);
|
);
|
||||||
|
const currentBorder = createMemo<boolean | BorderSides[]>(
|
||||||
|
() => props.currentBorder ?? ["left", "right"],
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<box flexDirection="row" flexGrow={1} width="100%" height="100%">
|
<box flexDirection="row" flexGrow={1} width="100%" height="100%">
|
||||||
{/* ── parent (1/5) — previous-depth list; title row top-left ───────── */}
|
{/* ── parent (20%) — previous-depth list; title row top-left ────────── */}
|
||||||
<Pane
|
<Pane
|
||||||
grow={PANE_RATIO.parent}
|
grow={PANE_RATIO.parent}
|
||||||
label={currentLabel}
|
label={currentLabel}
|
||||||
@@ -197,10 +203,10 @@ export function PaneRow(props: PaneRowProps) {
|
|||||||
grow={currentGrow()}
|
grow={currentGrow()}
|
||||||
label={() => ""}
|
label={() => ""}
|
||||||
content={currentContent}
|
content={currentContent}
|
||||||
border={["left", "right"]}
|
border={currentBorder()}
|
||||||
scrollFocused={() => focused()}
|
scrollFocused={() => focused()}
|
||||||
/>
|
/>
|
||||||
{/* ── preview (2/5) — hovered-item detail; no border, no header ────── */}
|
{/* ── preview (30%) — hovered-item detail; no border, no header ────── */}
|
||||||
<Show when={panes() === 3}>
|
<Show when={panes() === 3}>
|
||||||
<Pane
|
<Pane
|
||||||
grow={PANE_RATIO.preview}
|
grow={PANE_RATIO.preview}
|
||||||
|
|||||||
@@ -11,8 +11,8 @@
|
|||||||
* event bus. There is no sidebar pane.
|
* event bus. There is no sidebar pane.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { createSignal, Show, For } from "solid-js";
|
import { createEffect, createSignal, onCleanup, Show, For } from "solid-js";
|
||||||
import { useKeyboard, useRenderer } from "@opentui/solid";
|
import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/solid";
|
||||||
import { useTheme } from "@/context/ThemeContext";
|
import { useTheme } from "@/context/ThemeContext";
|
||||||
import { useKeybinds, type KeybindActionName } from "@/context/KeybindContext";
|
import { useKeybinds, type KeybindActionName } from "@/context/KeybindContext";
|
||||||
import { useNavigation, NavMode } from "@/context/NavigationContext";
|
import { useNavigation, NavMode } from "@/context/NavigationContext";
|
||||||
@@ -27,6 +27,7 @@ import { TABS } from "@/utils/navigation";
|
|||||||
import { createDispatcher } from "@/utils/dispatch";
|
import { createDispatcher } from "@/utils/dispatch";
|
||||||
import { TabListPane } from "@/components/TabPanel";
|
import { TabListPane } from "@/components/TabPanel";
|
||||||
import { PaneRow } from "@/components/PaneRow";
|
import { PaneRow } from "@/components/PaneRow";
|
||||||
|
import { GlobalActivityIndicator } from "@/components/GlobalActivityIndicator";
|
||||||
|
|
||||||
export function Shell() {
|
export function Shell() {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
@@ -216,11 +217,18 @@ export function Shell() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// ── Status bar fragments ──────────────────────────────────────────────────
|
// ── Status bar fragments ──────────────────────────────────────────────────
|
||||||
const nowPlaying = () => {
|
// Now-playing text carries the podcast name (custom name when set) when
|
||||||
|
// the episode's feed is resolvable, mirroring advanceEpisode's lookup.
|
||||||
|
const nowPlayingText = () => {
|
||||||
const ep = audio.currentEpisode();
|
const ep = audio.currentEpisode();
|
||||||
if (!ep) return null;
|
if (!ep) return null;
|
||||||
const title = ep.title.length > 40 ? ep.title.slice(0, 38) + "…" : ep.title;
|
const feeds = feedStore.getFilteredFeeds();
|
||||||
return `♪ ${title}`;
|
const feed =
|
||||||
|
feeds.find((f) => f.podcast.id === ep.podcastId) ??
|
||||||
|
feeds.find((f) => f.episodes.some((e) => e.id === ep.id));
|
||||||
|
return feed
|
||||||
|
? `♪ ${feed.customName || feed.podcast.title} — ${ep.title}`
|
||||||
|
: `♪ ${ep.title}`;
|
||||||
};
|
};
|
||||||
const modeLabel = () =>
|
const modeLabel = () =>
|
||||||
nav.mode() === NavMode.NORMAL ? "" : `-- ${nav.mode()} --`;
|
nav.mode() === NavMode.NORMAL ? "" : `-- ${nav.mode()} --`;
|
||||||
@@ -230,6 +238,68 @@ export function Shell() {
|
|||||||
.map((s) => s.key)
|
.map((s) => s.key)
|
||||||
.join(" ");
|
.join(" ");
|
||||||
|
|
||||||
|
// ── Now-playing marquee ────────────────────────────────────────────────────
|
||||||
|
// The now-playing segment takes the full remaining status-bar width and
|
||||||
|
// marquee-scrolls when its text overflows; when it fits (or the bar is too
|
||||||
|
// narrow to show anything) it renders statically. Each pass scrolls at
|
||||||
|
// SCROLL_STEP_MS per char, then holds at the start for SCROLL_HOLD_MS
|
||||||
|
// before scrolling again.
|
||||||
|
const dims = useTerminalDimensions();
|
||||||
|
const GAP = 3;
|
||||||
|
const SCROLL_STEP_MS = 150;
|
||||||
|
const SCROLL_HOLD_MS = 10_000;
|
||||||
|
const [scrollOffset, setScrollOffset] = createSignal(0);
|
||||||
|
const leftFixed = () =>
|
||||||
|
modeLabel().length +
|
||||||
|
(nav.selectedIds().length > 0
|
||||||
|
? 4 + String(nav.selectedIds().length).length
|
||||||
|
: 0);
|
||||||
|
const rightFixed = () => k.pending().map((p) => p.key).join(" ").length + 3;
|
||||||
|
const availableWidth = () =>
|
||||||
|
Math.max(0, dims().width - leftFixed() - rightFixed() - 2);
|
||||||
|
const visible = () => {
|
||||||
|
const text = nowPlayingText();
|
||||||
|
const avail = availableWidth();
|
||||||
|
if (!text || avail <= 0) return "";
|
||||||
|
if (text.length <= avail) return text;
|
||||||
|
// Double the text with a gap so the wrap is seamless: the window
|
||||||
|
// slides over text + gap + text without ever hitting the tail.
|
||||||
|
return (text + " ".repeat(GAP) + text).slice(
|
||||||
|
scrollOffset(),
|
||||||
|
scrollOffset() + avail,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
createEffect(() => {
|
||||||
|
const text = nowPlayingText();
|
||||||
|
const avail = availableWidth();
|
||||||
|
setScrollOffset(0);
|
||||||
|
if (!text || avail <= 0 || text.length <= avail) return;
|
||||||
|
const cycle = text.length + GAP - avail;
|
||||||
|
// Hold at the start position for SCROLL_HOLD_MS, scroll one pass,
|
||||||
|
// then hold again before the next pass.
|
||||||
|
let holdId: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
let scrollId: ReturnType<typeof setInterval> | null = null;
|
||||||
|
const startHold = () => {
|
||||||
|
setScrollOffset(0);
|
||||||
|
holdId = setTimeout(() => {
|
||||||
|
scrollId = setInterval(() => {
|
||||||
|
const next = scrollOffset() + 1;
|
||||||
|
if (next >= cycle) {
|
||||||
|
clearInterval(scrollId!);
|
||||||
|
startHold();
|
||||||
|
} else {
|
||||||
|
setScrollOffset(next);
|
||||||
|
}
|
||||||
|
}, SCROLL_STEP_MS);
|
||||||
|
}, SCROLL_HOLD_MS);
|
||||||
|
};
|
||||||
|
startHold();
|
||||||
|
onCleanup(() => {
|
||||||
|
if (holdId) clearTimeout(holdId);
|
||||||
|
if (scrollId) clearInterval(scrollId);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<box
|
<box
|
||||||
flexDirection="column"
|
flexDirection="column"
|
||||||
@@ -290,12 +360,14 @@ export function Shell() {
|
|||||||
● {nav.selectedIds().length}
|
● {nav.selectedIds().length}
|
||||||
</text>
|
</text>
|
||||||
</Show>
|
</Show>
|
||||||
<Show when={nowPlaying()}>
|
<Show when={nowPlayingText()}>
|
||||||
<text fg={t.primary} paddingLeft={1}>
|
<box flexGrow={1} paddingLeft={1}>
|
||||||
{nowPlaying()}
|
{/* content prop (not a text child): the babel-preset-solid JSX
|
||||||
</text>
|
* transform HTML-escapes static string children (`<` → `<`),
|
||||||
|
* which opentui renders verbatim; content bypasses that. */}
|
||||||
|
<text fg={t.primary} content={visible()} />
|
||||||
|
</box>
|
||||||
</Show>
|
</Show>
|
||||||
<box flexGrow={1} />
|
|
||||||
<text fg={t.textMuted} paddingRight={1}>
|
<text fg={t.textMuted} paddingRight={1}>
|
||||||
{pendingLabel()}
|
{pendingLabel()}
|
||||||
</text>
|
</text>
|
||||||
@@ -325,6 +397,8 @@ export function Shell() {
|
|||||||
theme={t as any}
|
theme={t as any}
|
||||||
/>
|
/>
|
||||||
</Show>
|
</Show>
|
||||||
|
{/* ── Global activity indicator (top-right overlay) ─────────────────────── */}
|
||||||
|
<GlobalActivityIndicator />
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -376,6 +450,7 @@ function helpSections(k: ReturnType<typeof useKeybinds>) {
|
|||||||
["enter", "open"],
|
["enter", "open"],
|
||||||
["r", "refresh"],
|
["r", "refresh"],
|
||||||
["s", "search"],
|
["s", "search"],
|
||||||
|
[p("search-scope-toggle"), "shows/episodes"],
|
||||||
["f", "filter"],
|
["f", "filter"],
|
||||||
[",", "sort"],
|
[",", "sort"],
|
||||||
[".", "hidden"],
|
[".", "hidden"],
|
||||||
|
|||||||
@@ -19,7 +19,9 @@ import { For } from "solid-js";
|
|||||||
import { useTheme } from "@/context/ThemeContext";
|
import { useTheme } from "@/context/ThemeContext";
|
||||||
import { useNavigation } from "@/context/NavigationContext";
|
import { useNavigation } from "@/context/NavigationContext";
|
||||||
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
||||||
|
import { useSelectionMarker } from "@/hooks/useSelectionMarker";
|
||||||
import { TABS } from "@/utils/navigation";
|
import { TABS } from "@/utils/navigation";
|
||||||
|
import { NF_ICONS, supportsNerdFonts } from "@/utils/nerd-fonts";
|
||||||
|
|
||||||
const TAB_LABEL: Record<TABS, string> = {
|
const TAB_LABEL: Record<TABS, string> = {
|
||||||
[TABS.FEED]: "Feed",
|
[TABS.FEED]: "Feed",
|
||||||
@@ -30,14 +32,27 @@ const TAB_LABEL: Record<TABS, string> = {
|
|||||||
[TABS.SETTINGS]: "Settings",
|
[TABS.SETTINGS]: "Settings",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Nerd Font glyph per tab (rendered only when the terminal supports them). */
|
||||||
|
const TAB_ICON: Record<TABS, string> = {
|
||||||
|
[TABS.FEED]: NF_ICONS.feed,
|
||||||
|
[TABS.MYSHOWS]: NF_ICONS.shows,
|
||||||
|
[TABS.DISCOVER]: NF_ICONS.discover,
|
||||||
|
[TABS.SEARCH]: NF_ICONS.search,
|
||||||
|
[TABS.PLAYER]: NF_ICONS.player,
|
||||||
|
[TABS.SETTINGS]: NF_ICONS.settings,
|
||||||
|
};
|
||||||
|
|
||||||
/** Numeric TABS values, in declaration order (1..TabsCount). */
|
/** Numeric TABS values, in declaration order (1..TabsCount). */
|
||||||
const TAB_ORDER = Object.values(TABS).filter(
|
const TAB_ORDER = Object.values(TABS).filter(
|
||||||
(v): v is TABS => typeof v === "number",
|
(v): v is TABS => typeof v === "number",
|
||||||
) as TABS[];
|
) as TABS[];
|
||||||
|
|
||||||
export function TabListPane(props: { muted?: boolean }) {
|
export function TabListPane(props: { muted?: boolean }) {
|
||||||
|
// Static: detection never changes mid-session.
|
||||||
|
const nerd = supportsNerdFonts();
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const nav = useNavigation();
|
const nav = useNavigation();
|
||||||
|
const marker = useSelectionMarker();
|
||||||
|
|
||||||
const cursor = () => nav.tabCursor();
|
const cursor = () => nav.tabCursor();
|
||||||
const activeTab = () => nav.activeTab();
|
const activeTab = () => nav.activeTab();
|
||||||
@@ -91,8 +106,12 @@ export function TabListPane(props: { muted?: boolean }) {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{/* ── selection marker (j/k cursor) ─────────────────────────── */}
|
{/* ── selection marker (j/k cursor) ─────────────────────────── */}
|
||||||
<text fg={focusFg(tab)}>{isCursor() ? "❯" : " "}</text>
|
<text fg={focusFg(tab)}>{isCursor() ? marker() : " "}</text>
|
||||||
<text fg={isCursor() ? focusFg(tab) : theme.textMuted}>{tab}</text>
|
{nerd && (
|
||||||
|
<text fg={focusFg(tab)} paddingRight={1}>
|
||||||
|
{TAB_ICON[tab]}
|
||||||
|
</text>
|
||||||
|
)}
|
||||||
<text fg={labelFg()} paddingLeft={1}>
|
<text fg={labelFg()} paddingLeft={1}>
|
||||||
{TAB_LABEL[tab]}
|
{TAB_LABEL[tab]}
|
||||||
</text>
|
</text>
|
||||||
|
|||||||
@@ -60,18 +60,27 @@
|
|||||||
|
|
||||||
// ── List operations (yazi: s search, f filter, , sort, . hidden, r refresh)
|
// ── List operations (yazi: s search, f filter, , sort, . hidden, r refresh)
|
||||||
"search": ["s"],
|
"search": ["s"],
|
||||||
|
// tab toggles the Search page between show and episode scope (re-runs the
|
||||||
|
// current query when viewing results)
|
||||||
|
"search-scope-toggle": ["tab"],
|
||||||
"filter": ["f"],
|
"filter": ["f"],
|
||||||
"sort": [","],
|
"sort": [","],
|
||||||
"toggle-hidden": ["."],
|
"toggle-hidden": ["."],
|
||||||
"refresh": ["r"],
|
"refresh": ["r"],
|
||||||
|
"subscribe": ["a"], // subscribe focused show/episode result in place (Search)
|
||||||
"unsubscribe": ["x"], // unsubscribe focused show in My Shows
|
"unsubscribe": ["x"], // unsubscribe focused show in My Shows
|
||||||
|
|
||||||
|
// ── Downloads & auto-download whitelist ───────────────────────────────────
|
||||||
|
"download": ["d"], // download the focused episode (detail pane)
|
||||||
|
"delete-download": ["D"], // delete the focused episode's download (if any)
|
||||||
|
"whitelist-toggle": ["w"], // add/remove the focused show from the auto-download whitelist (My Shows)
|
||||||
|
|
||||||
// ── Audio transport (preserved) ──────────────────────────────────────────
|
// ── Audio transport (preserved) ──────────────────────────────────────────
|
||||||
// Kept on shifted single keys so they never collide with the yazi core
|
// Kept on shifted single keys so they never collide with the yazi core
|
||||||
// (space=select, s=search, f=filter, etc.). Edit freely in this file.
|
// (space=select, s=search, f=filter, etc.). Edit freely in this file.
|
||||||
"audio-toggle": ["P"], // play / pause (shift+p)
|
"audio-toggle": ["P"], // play / pause (shift+p)
|
||||||
"audio-next": ["N"], // next episode (shift+n)
|
"audio-next": ["N"], // next episode (shift+n)
|
||||||
"audio-prev": ["B"], // prev episode (shift+b)
|
"audio-prev": ["B"], // prev episode (shift+b)
|
||||||
"audio-seek-forward": ["shift-."], // seek forward (shift+.)
|
"audio-seek-forward": ["shift-."], // seek forward (> = shift+.)
|
||||||
"audio-seek-backward": ["shift-,"] // seek backward (shift+,)
|
"audio-seek-backward": ["shift-,"] // seek backward (< = shift+,)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,11 +63,16 @@ export type KeybindActionName =
|
|||||||
| "quit"
|
| "quit"
|
||||||
| "help"
|
| "help"
|
||||||
| "search"
|
| "search"
|
||||||
|
| "search-scope-toggle"
|
||||||
| "filter"
|
| "filter"
|
||||||
| "sort"
|
| "sort"
|
||||||
| "toggle-hidden"
|
| "toggle-hidden"
|
||||||
| "refresh"
|
| "refresh"
|
||||||
|
| "subscribe"
|
||||||
| "unsubscribe"
|
| "unsubscribe"
|
||||||
|
| "download"
|
||||||
|
| "delete-download"
|
||||||
|
| "whitelist-toggle"
|
||||||
| "audio-toggle"
|
| "audio-toggle"
|
||||||
| "audio-next"
|
| "audio-next"
|
||||||
| "audio-prev"
|
| "audio-prev"
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
*
|
*
|
||||||
* parent | current | preview
|
* parent | current | preview
|
||||||
*
|
*
|
||||||
* Layout ratios (1/5 : 2/5 : 2/5 in the final remake) live in
|
* Layout ratios (20% : 50% : 30% — PANE_RATIO 2:5:3) live in
|
||||||
* `@/utils/navigation` (PANE_RATIO). This module owns only the *focusable*
|
* `@/utils/navigation` (PANE_RATIO). This module owns only the *focusable*
|
||||||
* nav model — which column is focused and where its list cursor lives. The
|
* nav model — which column is focused and where its list cursor lives. The
|
||||||
* parent/preview columns are always derived, never focused.
|
* parent/preview columns are always derived, never focused.
|
||||||
|
|||||||
@@ -12,7 +12,11 @@
|
|||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { createSignal, onCleanup } from "solid-js";
|
import { onCleanup } from "solid-js";
|
||||||
|
import {
|
||||||
|
cachedCoverPath,
|
||||||
|
fetchCoverArt,
|
||||||
|
} from "../utils/cover-art";
|
||||||
import {
|
import {
|
||||||
createAudioBackend,
|
createAudioBackend,
|
||||||
detectPlayers,
|
detectPlayers,
|
||||||
@@ -20,13 +24,39 @@ import {
|
|||||||
type BackendName,
|
type BackendName,
|
||||||
type DetectedPlayer,
|
type DetectedPlayer,
|
||||||
} from "../utils/audio-player";
|
} from "../utils/audio-player";
|
||||||
|
import {
|
||||||
|
isPlaying,
|
||||||
|
setIsPlaying,
|
||||||
|
position,
|
||||||
|
setPosition,
|
||||||
|
duration,
|
||||||
|
setDuration,
|
||||||
|
volume,
|
||||||
|
setVolume,
|
||||||
|
speed,
|
||||||
|
setSpeed,
|
||||||
|
backendName,
|
||||||
|
setBackendName,
|
||||||
|
error,
|
||||||
|
setError,
|
||||||
|
currentEpisode,
|
||||||
|
setCurrentEpisode,
|
||||||
|
availablePlayers,
|
||||||
|
setAvailablePlayers,
|
||||||
|
} from "../utils/audio-signals";
|
||||||
import { emit, on } from "../utils/event-bus";
|
import { emit, on } from "../utils/event-bus";
|
||||||
import { useAppStore } from "../stores/app";
|
import { useAppStore } from "../stores/app";
|
||||||
import { useProgressStore } from "../stores/progress";
|
import { useProgressStore } from "../stores/progress";
|
||||||
import { useMediaRegistry } from "../utils/media-registry";
|
import { useMediaRegistry } from "../utils/media-registry";
|
||||||
import type { Episode } from "../types/episode";
|
import {
|
||||||
|
loadLastPlayerFromFile,
|
||||||
|
saveLastPlayerToFile,
|
||||||
|
saveLastPlayerSync,
|
||||||
|
} from "../utils/app-persistence";
|
||||||
|
import type { Episode, Progress } from "../types/episode";
|
||||||
import type { Feed } from "../types/feed";
|
import type { Feed } from "../types/feed";
|
||||||
import { useAudioNavStore, AudioSource } from "../stores/audio-nav";
|
import { useAudioNavStore, AudioSource } from "../stores/audio-nav";
|
||||||
|
import { useDownloadStore } from "../stores/download";
|
||||||
import { useFeedStore } from "../stores/feed";
|
import { useFeedStore } from "../stores/feed";
|
||||||
|
|
||||||
export interface AudioControls {
|
export interface AudioControls {
|
||||||
@@ -43,6 +73,8 @@ export interface AudioControls {
|
|||||||
|
|
||||||
// Actions
|
// Actions
|
||||||
play: (episode: Episode) => Promise<void>;
|
play: (episode: Episode) => Promise<void>;
|
||||||
|
/** Load an episode into the player WITHOUT starting playback. */
|
||||||
|
load: (episode: Episode) => Promise<void>;
|
||||||
pause: () => Promise<void>;
|
pause: () => Promise<void>;
|
||||||
resume: () => Promise<void>;
|
resume: () => Promise<void>;
|
||||||
togglePlayback: () => Promise<void>;
|
togglePlayback: () => Promise<void>;
|
||||||
@@ -62,17 +94,26 @@ let pollTimer: ReturnType<typeof setInterval> | null = null;
|
|||||||
let refCount = 0;
|
let refCount = 0;
|
||||||
let pollCount = 0; // Counts poll ticks for throttling progress saves
|
let pollCount = 0; // Counts poll ticks for throttling progress saves
|
||||||
|
|
||||||
const [isPlaying, setIsPlaying] = createSignal(false);
|
// Playback signals are declared in utils/audio-signals.ts (imported above)
|
||||||
const [position, setPosition] = createSignal(0);
|
// so non-component consumers (the visualizer store) can subscribe without
|
||||||
const [duration, setDuration] = createSignal(0);
|
// mounting a useAudio() owner.
|
||||||
const [volume, setVolume] = createSignal(0.7);
|
|
||||||
const [speed, setSpeed] = createSignal(1);
|
/** True once the current episode has been handed to the backend (play
|
||||||
const [backendName, setBackendName] = createSignal<BackendName>("none");
|
* started). `false` means the episode is only LOADED in the player (e.g.
|
||||||
const [error, setError] = createSignal<string | null>(null);
|
* restored at boot) and the first play action must start the backend
|
||||||
const [currentEpisode, setCurrentEpisode] = createSignal<Episode | null>(null);
|
* instead of unpausing it. */
|
||||||
const [availablePlayers, setAvailablePlayers] = createSignal<DetectedPlayer[]>(
|
let startedPlayback = false;
|
||||||
[],
|
|
||||||
);
|
/** Completion fraction at/above which an episode is NOT restored at boot. */
|
||||||
|
const RESTORE_COMPLETION_THRESHOLD = 0.98;
|
||||||
|
|
||||||
|
/** True when saved progress is below the restore cutoff. Episodes with no
|
||||||
|
* progress (never reached the persist threshold) or unknown duration count
|
||||||
|
* as eligible — they restore from the start. */
|
||||||
|
function isRestoreEligible(progress: Progress | undefined): boolean {
|
||||||
|
if (!progress || progress.duration <= 0) return true;
|
||||||
|
return progress.position / progress.duration < RESTORE_COMPLETION_THRESHOLD;
|
||||||
|
}
|
||||||
|
|
||||||
function ensureBackend(): AudioBackend {
|
function ensureBackend(): AudioBackend {
|
||||||
if (!backend) {
|
if (!backend) {
|
||||||
@@ -99,6 +140,17 @@ function registerExitTeardown(): void {
|
|||||||
exitTeardownRegistered = true;
|
exitTeardownRegistered = true;
|
||||||
const teardown = (): void => {
|
const teardown = (): void => {
|
||||||
stopPolling();
|
stopPolling();
|
||||||
|
// Persist "what's loaded in the player right now" synchronously —
|
||||||
|
// process.exit(0) runs this handler synchronously and an async write
|
||||||
|
// would never land. The next launch restores this episode paused.
|
||||||
|
try {
|
||||||
|
const ep = currentEpisode();
|
||||||
|
if (ep) {
|
||||||
|
saveLastPlayerSync({ episodeId: ep.id, timestamp: new Date() });
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* best-effort at exit */
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
backend?.dispose();
|
backend?.dispose();
|
||||||
} catch {
|
} catch {
|
||||||
@@ -119,20 +171,89 @@ function registerExitTeardown(): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Poll ticks between paused-state checks (~1s at 150ms/tick). While the
|
||||||
|
* UI believes playback is paused we only need to catch an external
|
||||||
|
* resume (AirPod play tap, lock-screen/media-center play); checking every
|
||||||
|
* tick would just hammer mpv IPC for nothing. */
|
||||||
|
const PAUSE_WATCH_TICKS = 7;
|
||||||
|
|
||||||
|
/** The player process died while we believed playback was live — track
|
||||||
|
* ended (mpv quits at EOF) or the process crashed. Persist the final
|
||||||
|
* position and stop polling. */
|
||||||
|
function finalizeTrackEnd(): void {
|
||||||
|
setIsPlaying(false);
|
||||||
|
stopPolling();
|
||||||
|
const ep = currentEpisode();
|
||||||
|
if (ep) {
|
||||||
|
const progressStore = useProgressStore();
|
||||||
|
progressStore.update(ep.id, position(), duration(), speed());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** mpv paused itself OUTSIDE PodTUI — system sleep/lock, AirPod removal,
|
||||||
|
* device swap, OS media keys, the Now Playing center. Bring the UI in
|
||||||
|
* sync; the poll stays armed so an external resume is caught too. */
|
||||||
|
function reconcileExternalPause(): void {
|
||||||
|
setIsPlaying(false);
|
||||||
|
const ep = currentEpisode();
|
||||||
|
if (ep) {
|
||||||
|
const progressStore = useProgressStore();
|
||||||
|
progressStore.update(ep.id, position(), duration(), speed());
|
||||||
|
emit("player.pause", { episodeId: ep.id });
|
||||||
|
const media = useMediaRegistry();
|
||||||
|
media.setPlaybackState(false);
|
||||||
|
media.setPosition(position());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Playback was restarted from outside PodTUI (AirPods, lock-screen or
|
||||||
|
* media-center play, OS media keys). Bring the UI back to "playing". */
|
||||||
|
function reconcileExternalResume(): void {
|
||||||
|
setIsPlaying(true);
|
||||||
|
const ep = currentEpisode();
|
||||||
|
if (ep) {
|
||||||
|
emit("player.play", { episodeId: ep.id });
|
||||||
|
useMediaRegistry().setPlaybackState(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function startPolling(): void {
|
function startPolling(): void {
|
||||||
stopPolling();
|
stopPolling();
|
||||||
pollCount = 0;
|
pollCount = 0;
|
||||||
|
// Guard against overlapping ticks if a socket read ever outlives the
|
||||||
|
// interval (getPosition opens a fresh mpv IPC connection per call).
|
||||||
|
let pollInFlight = false;
|
||||||
pollTimer = setInterval(async () => {
|
pollTimer = setInterval(async () => {
|
||||||
if (!backend || !isPlaying()) return;
|
if (!backend || pollInFlight) return;
|
||||||
|
pollInFlight = true;
|
||||||
try {
|
try {
|
||||||
|
pollCount++;
|
||||||
|
if (isPlaying()) {
|
||||||
|
// Track ended (eof-reached observed) or process died. Check
|
||||||
|
// BEFORE pause reconciliation: mpv keeps the file open at EOF
|
||||||
|
// and reports pause=true there, which would otherwise be
|
||||||
|
// mistaken for an external pause and never finalize.
|
||||||
|
if (!backend.isPlaying()) {
|
||||||
|
finalizeTrackEnd();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// mpv can pause itself outside PodTUI. Reconcile instead of
|
||||||
|
// staying stuck on "playing" with a frozen waveform
|
||||||
|
// (getPosition would just re-read the same frozen time-pos).
|
||||||
|
const paused = await backend.getPauseState();
|
||||||
|
if (paused === true) {
|
||||||
|
reconcileExternalPause();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const pos = await backend.getPosition();
|
const pos = await backend.getPosition();
|
||||||
const dur = await backend.getDuration();
|
const dur = await backend.getDuration();
|
||||||
setPosition(pos);
|
setPosition(pos);
|
||||||
if (dur > 0) setDuration(dur);
|
if (dur > 0) setDuration(dur);
|
||||||
|
|
||||||
// Save progress every ~5 seconds (10 ticks * 500ms)
|
// Save progress every ~5 seconds (33 ticks * 150ms)
|
||||||
pollCount++;
|
if (pollCount % 33 === 0) {
|
||||||
if (pollCount % 10 === 0) {
|
|
||||||
const ep = currentEpisode();
|
const ep = currentEpisode();
|
||||||
if (ep) {
|
if (ep) {
|
||||||
const progressStore = useProgressStore();
|
const progressStore = useProgressStore();
|
||||||
@@ -142,22 +263,26 @@ function startPolling(): void {
|
|||||||
media.setPosition(pos);
|
media.setPosition(pos);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else if (pollCount % PAUSE_WATCH_TICKS === 0) {
|
||||||
// Check if backend stopped playing (track ended)
|
// Paused — watch for playback restarted from outside (AirPods,
|
||||||
if (!backend.isPlaying() && isPlaying()) {
|
// lock-screen/media-center play). Only while the player is
|
||||||
setIsPlaying(false);
|
// still alive: a dead player while we thought we were paused
|
||||||
stopPolling();
|
// means the track ended (mpv quits at EOF) or it crashed.
|
||||||
// Save final position on track end
|
if (!backend.isAlive()) {
|
||||||
const ep = currentEpisode();
|
finalizeTrackEnd();
|
||||||
if (ep) {
|
return;
|
||||||
const progressStore = useProgressStore();
|
}
|
||||||
progressStore.update(ep.id, pos, dur > 0 ? dur : duration(), speed());
|
const paused = await backend.getPauseState();
|
||||||
|
if (paused === false) {
|
||||||
|
reconcileExternalResume();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Backend may have been disposed
|
// Backend may have been disposed
|
||||||
|
} finally {
|
||||||
|
pollInFlight = false;
|
||||||
}
|
}
|
||||||
}, 500);
|
}, 150);
|
||||||
}
|
}
|
||||||
|
|
||||||
function stopPolling(): void {
|
function stopPolling(): void {
|
||||||
@@ -167,6 +292,11 @@ function stopPolling(): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Cover art for system Now Playing ─────────────────────────────────────────
|
||||||
|
// macOS shows the media session's albumart in the audio center; mpv reads it
|
||||||
|
// from `--cover-art-files`. Shared helper (utils/cover-art.ts) fetches the
|
||||||
|
// podcast cover to a temp file BEFORE playback starts, bounded to 3s.
|
||||||
|
|
||||||
async function play(episode: Episode): Promise<void> {
|
async function play(episode: Episode): Promise<void> {
|
||||||
const b = ensureBackend();
|
const b = ensureBackend();
|
||||||
setError(null);
|
setError(null);
|
||||||
@@ -183,6 +313,30 @@ async function play(episode: Episode): Promise<void> {
|
|||||||
const vol = volume();
|
const vol = volume();
|
||||||
const spd = storeSpeed || speed();
|
const spd = storeSpeed || speed();
|
||||||
|
|
||||||
|
const feedStore = useFeedStore();
|
||||||
|
const feed = feedStore.feeds().find((f) => f.podcast.id === episode.podcastId);
|
||||||
|
const podcastTitle = feed?.customName || feed?.podcast.title || "";
|
||||||
|
// Play the downloaded file when present (offline + no network stalls);
|
||||||
|
// otherwise stream. Cover resolves to the feed art, falling back to the
|
||||||
|
// episode's own image (feeds added by URL may lack a channel cover).
|
||||||
|
const downloadStore = useDownloadStore();
|
||||||
|
const url = downloadStore.getDownloadedFilePath(episode.id) ?? episode.audioUrl;
|
||||||
|
const coverUrl = feed?.podcast.coverUrl ?? episode.imageUrl;
|
||||||
|
// Cover art only applies at file LOAD (the runtime video-add fallback
|
||||||
|
// never becomes an albumart track), so a cold-cache play must wait for
|
||||||
|
// the fetch or play artless. Serve the disk cache synchronously; on a
|
||||||
|
// miss, await the single-flight fetch with a 1.2s cap (covers fetch in
|
||||||
|
// ~300ms typically) — past the cap, play bare and let the fetch warm
|
||||||
|
// the cache for next time.
|
||||||
|
let coverArtPath = coverUrl ? cachedCoverPath(coverUrl) : null;
|
||||||
|
if (coverUrl && !coverArtPath) {
|
||||||
|
const path = await Promise.race([
|
||||||
|
fetchCoverArt(coverUrl),
|
||||||
|
new Promise<null>((resolve) => setTimeout(() => resolve(null), 1200)),
|
||||||
|
]);
|
||||||
|
if (path) coverArtPath = path;
|
||||||
|
}
|
||||||
|
|
||||||
// Resume from saved progress if available and not completed
|
// Resume from saved progress if available and not completed
|
||||||
const savedProgress = progressStore.get(episode.id);
|
const savedProgress = progressStore.get(episode.id);
|
||||||
let startPos = 0;
|
let startPos = 0;
|
||||||
@@ -190,10 +344,12 @@ async function play(episode: Episode): Promise<void> {
|
|||||||
startPos = savedProgress.position;
|
startPos = savedProgress.position;
|
||||||
}
|
}
|
||||||
|
|
||||||
await b.play(episode.audioUrl, {
|
await b.play(url, {
|
||||||
volume: vol,
|
volume: vol,
|
||||||
speed: spd,
|
speed: spd,
|
||||||
startPosition: startPos > 0 ? startPos : undefined,
|
startPosition: startPos > 0 ? startPos : undefined,
|
||||||
|
mediaTitle: episode.title,
|
||||||
|
coverArtPath: coverArtPath ?? undefined,
|
||||||
});
|
});
|
||||||
|
|
||||||
setCurrentEpisode(episode);
|
setCurrentEpisode(episode);
|
||||||
@@ -201,12 +357,17 @@ async function play(episode: Episode): Promise<void> {
|
|||||||
setPosition(startPos);
|
setPosition(startPos);
|
||||||
setSpeed(spd);
|
setSpeed(spd);
|
||||||
if (episode.duration) setDuration(episode.duration);
|
if (episode.duration) setDuration(episode.duration);
|
||||||
|
startedPlayback = true;
|
||||||
|
|
||||||
|
// Remember this episode as "loaded in the player" so the next launch
|
||||||
|
// can restore it paused (cleared by stop()).
|
||||||
|
saveLastPlayerToFile({ episodeId: episode.id, timestamp: new Date() });
|
||||||
|
|
||||||
// Register with platform media controls
|
// Register with platform media controls
|
||||||
const media = useMediaRegistry();
|
const media = useMediaRegistry();
|
||||||
media.setNowPlaying({
|
media.setNowPlaying({
|
||||||
title: episode.title,
|
title: episode.title,
|
||||||
artist: episode.podcastId,
|
artist: podcastTitle || episode.podcastId,
|
||||||
duration: episode.duration,
|
duration: episode.duration,
|
||||||
});
|
});
|
||||||
media.setPlaybackState(true);
|
media.setPlaybackState(true);
|
||||||
@@ -223,12 +384,83 @@ async function play(episode: Episode): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load an episode into the player WITHOUT starting playback. The player tab
|
||||||
|
* renders it paused at its saved position; the first play action starts the
|
||||||
|
* backend from there (see togglePlayback). Used to restore the last player
|
||||||
|
* session at boot.
|
||||||
|
*/
|
||||||
|
async function load(episode: Episode): Promise<void> {
|
||||||
|
ensureBackend();
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
setCurrentEpisode(episode);
|
||||||
|
setIsPlaying(false);
|
||||||
|
startedPlayback = false;
|
||||||
|
|
||||||
|
// Show the saved position so the player tab reflects where playback
|
||||||
|
// will resume; episodes at/above the completion threshold start from 0.
|
||||||
|
const progressStore = useProgressStore();
|
||||||
|
const saved = progressStore.get(episode.id);
|
||||||
|
const pos = saved && isRestoreEligible(saved) ? saved.position : 0;
|
||||||
|
setPosition(pos);
|
||||||
|
if (episode.duration) setDuration(episode.duration);
|
||||||
|
|
||||||
|
const appStore = useAppStore();
|
||||||
|
const storeSpeed = appStore.state().settings.playbackSpeed;
|
||||||
|
setSpeed(storeSpeed || speed());
|
||||||
|
|
||||||
|
// Surface the loaded-but-paused track to the OS media controls.
|
||||||
|
const feedStore = useFeedStore();
|
||||||
|
const feed = feedStore.feeds().find((f) => f.podcast.id === episode.podcastId);
|
||||||
|
const podcastTitle = feed?.customName || feed?.podcast.title || "";
|
||||||
|
const media = useMediaRegistry();
|
||||||
|
media.setNowPlaying({
|
||||||
|
title: episode.title,
|
||||||
|
artist: podcastTitle || episode.podcastId,
|
||||||
|
duration: episode.duration,
|
||||||
|
});
|
||||||
|
media.setPlaybackState(false);
|
||||||
|
if (pos > 0) media.setPosition(pos);
|
||||||
|
|
||||||
|
// Preload the episode into the backend PAUSED: mpv opens the stream and
|
||||||
|
// fills its demuxer cache while parked, so the user's first Play flips
|
||||||
|
// `pause` off instead of paying the ~2s stream-open cold. Fire-and-forget
|
||||||
|
// — a failed preload just makes the first play take the cold path.
|
||||||
|
const downloadStore = useDownloadStore();
|
||||||
|
const url = downloadStore.getDownloadedFilePath(episode.id) ?? episode.audioUrl;
|
||||||
|
if (episode.audioUrl && backend) {
|
||||||
|
// The preload must carry the cover AT LOAD: cover-art-files only
|
||||||
|
// applies when the file loads, and the runtime video-add fallback
|
||||||
|
// never becomes an albumart track (verified). Restore already waits
|
||||||
|
// on feeds/progress at boot, so the bounded fetch (~300ms typical,
|
||||||
|
// 8s worst case) is free. Falls back to the episode's own image when
|
||||||
|
// the feed has no channel cover.
|
||||||
|
const coverUrl = feed?.podcast.coverUrl ?? episode.imageUrl;
|
||||||
|
const coverArtPath = coverUrl ? await fetchCoverArt(coverUrl) : null;
|
||||||
|
const backendSnap = backend;
|
||||||
|
backendSnap
|
||||||
|
.preload(url, {
|
||||||
|
volume: volume(),
|
||||||
|
speed: storeSpeed || speed(),
|
||||||
|
startPosition: pos > 0 ? pos : undefined,
|
||||||
|
mediaTitle: episode.title,
|
||||||
|
coverArtPath: coverArtPath ?? undefined,
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
saveLastPlayerToFile({ episodeId: episode.id, timestamp: new Date() });
|
||||||
|
}
|
||||||
|
|
||||||
async function pause(): Promise<void> {
|
async function pause(): Promise<void> {
|
||||||
if (!backend) return;
|
if (!backend) return;
|
||||||
try {
|
try {
|
||||||
await backend.pause();
|
await backend.pause();
|
||||||
setIsPlaying(false);
|
setIsPlaying(false);
|
||||||
stopPolling();
|
// Polling stays armed (paused-watch mode): playback can be resumed
|
||||||
|
// from OUTSIDE PodTUI — AirPods, lock-screen/media-center play —
|
||||||
|
// and the poll must be live to catch it.
|
||||||
const ep = currentEpisode();
|
const ep = currentEpisode();
|
||||||
if (ep) {
|
if (ep) {
|
||||||
// Save progress on pause
|
// Save progress on pause
|
||||||
@@ -267,7 +499,15 @@ async function togglePlayback(): Promise<void> {
|
|||||||
if (isPlaying()) {
|
if (isPlaying()) {
|
||||||
await pause();
|
await pause();
|
||||||
} else if (currentEpisode()) {
|
} else if (currentEpisode()) {
|
||||||
|
if (startedPlayback) {
|
||||||
await resume();
|
await resume();
|
||||||
|
} else {
|
||||||
|
// Episode is only LOADED (e.g. restored at boot) — the backend
|
||||||
|
// was never started, so unpausing a dead player would fail
|
||||||
|
// silently. Start playback from the saved position instead.
|
||||||
|
const ep = currentEpisode();
|
||||||
|
if (ep) await play(ep);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -284,9 +524,13 @@ async function stop(): Promise<void> {
|
|||||||
setIsPlaying(false);
|
setIsPlaying(false);
|
||||||
setPosition(0);
|
setPosition(0);
|
||||||
setCurrentEpisode(null);
|
setCurrentEpisode(null);
|
||||||
|
startedPlayback = false;
|
||||||
stopPolling();
|
stopPolling();
|
||||||
emit("player.stop", {});
|
emit("player.stop", {});
|
||||||
|
|
||||||
|
// Player is empty again — nothing to restore on the next launch.
|
||||||
|
saveLastPlayerToFile({ episodeId: null, timestamp: null });
|
||||||
|
|
||||||
const media = useMediaRegistry();
|
const media = useMediaRegistry();
|
||||||
media.clearNowPlaying();
|
media.clearNowPlaying();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -319,6 +563,10 @@ async function doSetVolume(vol: number): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
setVolume(clamped);
|
setVolume(clamped);
|
||||||
|
|
||||||
|
// Sync back to app store (persisted to config.json for the next launch).
|
||||||
|
const appStore = useAppStore();
|
||||||
|
appStore.updateSettings({ volume: clamped });
|
||||||
}
|
}
|
||||||
|
|
||||||
async function doSetSpeed(spd: number): Promise<void> {
|
async function doSetSpeed(spd: number): Promise<void> {
|
||||||
@@ -357,12 +605,24 @@ async function switchBackend(name: BackendName): Promise<void> {
|
|||||||
// Resume playback if we were playing
|
// Resume playback if we were playing
|
||||||
if (wasPlaying && ep && ep.audioUrl) {
|
if (wasPlaying && ep && ep.audioUrl) {
|
||||||
try {
|
try {
|
||||||
await backend.play(ep.audioUrl, {
|
const feedStore = useFeedStore();
|
||||||
|
const feed = feedStore
|
||||||
|
.feeds()
|
||||||
|
.find((f) => f.podcast.id === ep.podcastId);
|
||||||
|
const podcastTitle = feed?.customName || feed?.podcast.title || "";
|
||||||
|
const url =
|
||||||
|
useDownloadStore().getDownloadedFilePath(ep.id) ?? ep.audioUrl;
|
||||||
|
const coverUrl = feed?.podcast.coverUrl ?? ep.imageUrl;
|
||||||
|
const coverArtPath = coverUrl ? cachedCoverPath(coverUrl) : null;
|
||||||
|
await backend.play(url, {
|
||||||
startPosition: pos,
|
startPosition: pos,
|
||||||
volume: vol,
|
volume: vol,
|
||||||
speed: spd,
|
speed: spd,
|
||||||
|
mediaTitle: ep.title,
|
||||||
|
coverArtPath: coverArtPath ?? undefined,
|
||||||
});
|
});
|
||||||
setIsPlaying(true);
|
setIsPlaying(true);
|
||||||
|
startedPlayback = true;
|
||||||
startPolling();
|
startPolling();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : "Backend switch failed");
|
setError(err instanceof Error ? err.message : "Backend switch failed");
|
||||||
@@ -371,6 +631,46 @@ async function switchBackend(name: BackendName): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Serialized restore chain: the boot-triggered restore and any explicit
|
||||||
|
* call run one after another, so a late-finishing earlier restore can never
|
||||||
|
* overwrite state changed by a later one (and callers can await the latest
|
||||||
|
* attempt deterministically). */
|
||||||
|
let restoreChain: Promise<void> = Promise.resolve();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Boot-time session restore: reload the episode that was loaded in the
|
||||||
|
* player when the previous run ended (persisted on play/load and at exit),
|
||||||
|
* paused at its saved position — never autostarted. Episodes at/above the
|
||||||
|
* completion threshold are skipped. Silently no-ops when there is nothing
|
||||||
|
* to restore (empty player, unsubscribed show, or completed episode).
|
||||||
|
*/
|
||||||
|
export async function restoreLastSession(): Promise<void> {
|
||||||
|
const attempt = restoreChain.then(async () => {
|
||||||
|
const marker = await loadLastPlayerFromFile();
|
||||||
|
if (!marker?.episodeId) return;
|
||||||
|
|
||||||
|
// Feeds and progress load asynchronously at boot; wait for both
|
||||||
|
// before looking the episode up.
|
||||||
|
await Promise.all([
|
||||||
|
useProgressStore().whenReady(),
|
||||||
|
useFeedStore().whenReady(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const episode = useFeedStore().findEpisode(marker.episodeId);
|
||||||
|
if (!episode) return;
|
||||||
|
|
||||||
|
// Only restore episodes below the completion threshold.
|
||||||
|
const saved = useProgressStore().get(episode.id);
|
||||||
|
if (!isRestoreEligible(saved)) return;
|
||||||
|
|
||||||
|
await load(episode);
|
||||||
|
});
|
||||||
|
// Keep the chain alive even when an attempt fails; the caller awaiting
|
||||||
|
// this attempt still observes its own outcome.
|
||||||
|
restoreChain = attempt.catch(() => {});
|
||||||
|
await attempt;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reactive audio controls hook.
|
* Reactive audio controls hook.
|
||||||
*
|
*
|
||||||
@@ -381,13 +681,29 @@ export function useAudio(): AudioControls {
|
|||||||
// Initialize backend on first use
|
// Initialize backend on first use
|
||||||
ensureBackend();
|
ensureBackend();
|
||||||
|
|
||||||
// Sync initial speed from app store
|
// Sync initial speed/volume from app store (reuse the previous session's
|
||||||
|
// playback levels; defaults are 1x and 100%).
|
||||||
if (refCount === 0) {
|
if (refCount === 0) {
|
||||||
const appStore = useAppStore();
|
const appStore = useAppStore();
|
||||||
const storeSpeed = appStore.state().settings.playbackSpeed;
|
const storeSpeed = appStore.state().settings.playbackSpeed;
|
||||||
if (storeSpeed && storeSpeed !== speed()) {
|
if (storeSpeed && storeSpeed !== speed()) {
|
||||||
setSpeed(storeSpeed);
|
setSpeed(storeSpeed);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Volume re-syncs once settings finish loading (async config read)
|
||||||
|
// so a level persisted last session is applied at boot.
|
||||||
|
appStore
|
||||||
|
.whenReady()
|
||||||
|
.then(() => {
|
||||||
|
const storeVolume = appStore.state().settings.volume;
|
||||||
|
if (storeVolume !== undefined && storeVolume !== volume()) {
|
||||||
|
setVolume(storeVolume);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
|
||||||
|
// Restore the last player session once at boot (loaded, not playing).
|
||||||
|
restoreLastSession().catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
refCount++;
|
refCount++;
|
||||||
@@ -421,14 +737,6 @@ export function useAudio(): AudioControls {
|
|||||||
await doSetVolume(Math.max(0, Number((volume() - 0.05).toFixed(2))));
|
await doSetVolume(Math.max(0, Number((volume() - 0.05).toFixed(2))));
|
||||||
});
|
});
|
||||||
|
|
||||||
const unsubMediaSeekFwd = on("media.seekForward", async () => {
|
|
||||||
await seekRelative(10);
|
|
||||||
});
|
|
||||||
|
|
||||||
const unsubMediaSeekBack = on("media.seekBackward", async () => {
|
|
||||||
await seekRelative(-10);
|
|
||||||
});
|
|
||||||
|
|
||||||
const unsubMediaSpeed = on("media.speedCycle", async () => {
|
const unsubMediaSpeed = on("media.speedCycle", async () => {
|
||||||
const next = speed() >= 2 ? 0.5 : Number((speed() + 0.25).toFixed(2));
|
const next = speed() >= 2 ? 0.5 : Number((speed() + 0.25).toFixed(2));
|
||||||
await doSetSpeed(next);
|
await doSetSpeed(next);
|
||||||
@@ -515,8 +823,6 @@ export function useAudio(): AudioControls {
|
|||||||
unsubMediaToggle();
|
unsubMediaToggle();
|
||||||
unsubMediaVolUp();
|
unsubMediaVolUp();
|
||||||
unsubMediaVolDown();
|
unsubMediaVolDown();
|
||||||
unsubMediaSeekFwd();
|
|
||||||
unsubMediaSeekBack();
|
|
||||||
unsubMediaSpeed();
|
unsubMediaSpeed();
|
||||||
|
|
||||||
if (refCount <= 0) {
|
if (refCount <= 0) {
|
||||||
@@ -545,6 +851,7 @@ export function useAudio(): AudioControls {
|
|||||||
availablePlayers,
|
availablePlayers,
|
||||||
|
|
||||||
play,
|
play,
|
||||||
|
load,
|
||||||
pause,
|
pause,
|
||||||
resume,
|
resume,
|
||||||
togglePlayback,
|
togglePlayback,
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
/**
|
/**
|
||||||
* Global multimedia key handler hook.
|
* Global multimedia key handler hook.
|
||||||
*
|
*
|
||||||
* Captures media-related key events (play/pause, volume, seek, speed)
|
* Captures media-related key events (play/pause, volume, speed)
|
||||||
* regardless of which component is focused. Uses the event bus to
|
* regardless of which component is focused. Uses the event bus to
|
||||||
* decouple key detection from audio control logic.
|
* decouple key detection from audio control logic.
|
||||||
*
|
*
|
||||||
* Volume and speed are app-level settings — adjustable with or without
|
* Volume and speed are app-level settings — adjustable with or without
|
||||||
* an episode loaded (they apply to the next playback and persist). Seek
|
* an episode loaded (they apply to the next playback and persist). Seek
|
||||||
* is playback-dependent, so it still requires a loaded episode.
|
* is NOT handled here: it lives on the yazi keybind router (`<` / `>` =
|
||||||
|
* shift+, / shift+.), so the arrow keys stay free for navigation.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { useKeyboard } from "@opentui/solid";
|
import { useKeyboard } from "@opentui/solid";
|
||||||
@@ -17,8 +18,6 @@ export type MediaKeyAction =
|
|||||||
| "media.toggle"
|
| "media.toggle"
|
||||||
| "media.volumeUp"
|
| "media.volumeUp"
|
||||||
| "media.volumeDown"
|
| "media.volumeDown"
|
||||||
| "media.seekForward"
|
|
||||||
| "media.seekBackward"
|
|
||||||
| "media.speedCycle";
|
| "media.speedCycle";
|
||||||
|
|
||||||
export interface MultimediaKeysOptions {
|
export interface MultimediaKeysOptions {
|
||||||
@@ -26,8 +25,6 @@ export interface MultimediaKeysOptions {
|
|||||||
playerFocused?: () => boolean;
|
playerFocused?: () => boolean;
|
||||||
/** When true, skip handling (text input has focus) */
|
/** When true, skip handling (text input has focus) */
|
||||||
inputFocused?: () => boolean;
|
inputFocused?: () => boolean;
|
||||||
/** Whether an episode is currently loaded */
|
|
||||||
hasEpisode?: () => boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -59,17 +56,9 @@ export function useMultimediaKeys(options: MultimediaKeysOptions = {}) {
|
|||||||
emit("media.volumeDown", {});
|
emit("media.volumeDown", {});
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "left":
|
|
||||||
if (!options.hasEpisode?.()) return;
|
|
||||||
emit("media.seekBackward", {});
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "right":
|
|
||||||
if (!options.hasEpisode?.()) return;
|
|
||||||
emit("media.seekForward", {});
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "s":
|
case "s":
|
||||||
|
// Speed is shift+s (S) so plain `s` stays free for search.
|
||||||
|
if (!key.shift) return;
|
||||||
emit("media.speedCycle", {});
|
emit("media.speedCycle", {});
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
|||||||
16
src/hooks/useSelectionMarker.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
/**
|
||||||
|
* useSelectionMarker — reactive accessor for the row-selection marker glyph.
|
||||||
|
*
|
||||||
|
* When the `showSelectionMarker` setting is on, the focused row of every list
|
||||||
|
* renders `❯`; when off (the default), it renders a space so column alignment
|
||||||
|
* is preserved. Every list pane in the app reads the marker through this hook
|
||||||
|
* so the setting applies consistently everywhere.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useAppStore } from "@/stores/app";
|
||||||
|
|
||||||
|
export function useSelectionMarker(): () => string {
|
||||||
|
const app = useAppStore();
|
||||||
|
return () =>
|
||||||
|
app.state().settings.showSelectionMarker ? "❯" : " ";
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { Feed } from "./types/feed"
|
import type { Feed } from "./types/feed"
|
||||||
import type { Episode } from "./types/episode"
|
import type { Episode } from "./types/episode"
|
||||||
|
|
||||||
const VERSION = "0.3.1";
|
const VERSION = "0.6.0";
|
||||||
|
|
||||||
interface CliArgs {
|
interface CliArgs {
|
||||||
version: boolean;
|
version: boolean;
|
||||||
@@ -182,9 +182,22 @@ async function handlePlay(feeds: Feed[], arg: string): Promise<void> {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const { createAudioBackend } = await import("./utils/audio-player")
|
const { createAudioBackend } = await import("./utils/audio-player")
|
||||||
|
const { fetchCoverArt } = await import("./utils/cover-art")
|
||||||
const backend = createAudioBackend()
|
const backend = createAudioBackend()
|
||||||
if (episodeResult.audioUrl) {
|
if (episodeResult.audioUrl) {
|
||||||
await backend.play(episodeResult.audioUrl)
|
// Stage the podcast cover so the system Now Playing shows
|
||||||
|
// artwork (mpv --cover-art-files), like the UI path does. Falls
|
||||||
|
// back to the episode's own image when the feed has no channel
|
||||||
|
// cover (URL-added feeds).
|
||||||
|
const coverUrl =
|
||||||
|
feedResult.podcast.coverUrl ?? episodeResult.imageUrl;
|
||||||
|
const coverArtPath = coverUrl
|
||||||
|
? await fetchCoverArt(coverUrl)
|
||||||
|
: null
|
||||||
|
await backend.play(episodeResult.audioUrl, {
|
||||||
|
mediaTitle: episodeResult.title,
|
||||||
|
coverArtPath: coverArtPath ?? undefined,
|
||||||
|
})
|
||||||
console.log("Playback started (use the UI to control)")
|
console.log("Playback started (use the UI to control)")
|
||||||
} else {
|
} else {
|
||||||
console.log("No audio URL available for this episode")
|
console.log("No audio URL available for this episode")
|
||||||
|
|||||||
@@ -27,19 +27,24 @@ import {
|
|||||||
type DepthFrame,
|
type DepthFrame,
|
||||||
} from "@/context/NavigationContext";
|
} from "@/context/NavigationContext";
|
||||||
import { on, off } from "@/utils/event-bus";
|
import { on, off } from "@/utils/event-bus";
|
||||||
|
import { supportsNerdFonts } from "@/utils/nerd-fonts";
|
||||||
import type { KeybindActionName } from "@/context/KeybindContext";
|
import type { KeybindActionName } from "@/context/KeybindContext";
|
||||||
import { PaneRow } from "@/components/PaneRow";
|
import { PaneRow } from "@/components/PaneRow";
|
||||||
import { TabListPane } from "@/components/TabPanel";
|
import { TabListPane } from "@/components/TabPanel";
|
||||||
import { LoadingIndicator } from "@/components/LoadingIndicator";
|
import { LoadingIndicator } from "@/components/LoadingIndicator";
|
||||||
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
||||||
|
import { useSelectionMarker } from "@/hooks/useSelectionMarker";
|
||||||
|
|
||||||
export const DiscoverPaneCount = 1;
|
export const DiscoverPaneCount = 1;
|
||||||
|
|
||||||
function DiscoverPage() {
|
function DiscoverPage() {
|
||||||
|
// Static: detection never changes mid-session.
|
||||||
|
const nerd = supportsNerdFonts();
|
||||||
const discoverStore = useDiscoverStore();
|
const discoverStore = useDiscoverStore();
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const muted = () => theme.muted || theme.text;
|
const muted = () => theme.muted || theme.text;
|
||||||
const nav = useNavigation();
|
const nav = useNavigation();
|
||||||
|
const marker = useSelectionMarker();
|
||||||
|
|
||||||
const depth = nav.currentDepth;
|
const depth = nav.currentDepth;
|
||||||
const focus = (d: number = depth()) => nav.depthFocus(d);
|
const focus = (d: number = depth()) => nav.depthFocus(d);
|
||||||
@@ -159,10 +164,17 @@ function DiscoverPage() {
|
|||||||
: `${focusedCategory()?.name ?? "Discover"} · ${podcasts().length}`;
|
: `${focusedCategory()?.name ?? "Discover"} · ${podcasts().length}`;
|
||||||
|
|
||||||
// ── parent pane: previous-depth list (muted/blank at depth 0) ─────────────
|
// ── parent pane: previous-depth list (muted/blank at depth 0) ─────────────
|
||||||
// Stable <Show> gate (not a ternary root swap) so the parent list
|
// Sibling <Show> blocks per depth (the known-good opentui disposal
|
||||||
// mounts/unmounts cleanly on depth change.
|
// pattern, mirrors Settings): a STABLE fragment root whose inner <Show>
|
||||||
|
// children toggle on depth change, so the old subtree is disposed instead
|
||||||
|
// of left orphaned next to the new one (single <Show with fallback> and
|
||||||
|
// ternary root swaps both leak the previous root).
|
||||||
const parentContent = () => (
|
const parentContent = () => (
|
||||||
<Show when={depth() >= 1} fallback={<TabListPane muted />}>
|
<>
|
||||||
|
<Show when={depth() === 0}>
|
||||||
|
<TabListPane muted />
|
||||||
|
</Show>
|
||||||
|
<Show when={depth() >= 1}>
|
||||||
<For each={categories()}>
|
<For each={categories()}>
|
||||||
{(cat, index) => {
|
{(cat, index) => {
|
||||||
const lf = () => nav.depthFocus(0);
|
const lf = () => nav.depthFocus(0);
|
||||||
@@ -172,13 +184,17 @@ function DiscoverPage() {
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
flexDirection="row"
|
flexDirection="row"
|
||||||
gap={1}
|
gap={1}
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
paddingRight={1}
|
||||||
backgroundColor={focusBg(index(), lf(), false)}
|
backgroundColor={focusBg(index(), lf(), false)}
|
||||||
>
|
>
|
||||||
<text fg={focusFg(index(), nav.depthFocus(0), false)}>
|
<text fg={focusFg(index(), nav.depthFocus(0), false)}>
|
||||||
{index() === nav.depthFocus(0) ? "❯" : " "}
|
{index() === nav.depthFocus(0) ? marker() : " "}
|
||||||
</text>
|
</text>
|
||||||
|
{nerd && (
|
||||||
|
<text fg={focusFg(index(), nav.depthFocus(0), false)}>
|
||||||
|
{cat.icon}
|
||||||
|
</text>
|
||||||
|
)}
|
||||||
<text fg={focusFg(index(), nav.depthFocus(0), false)}>
|
<text fg={focusFg(index(), nav.depthFocus(0), false)}>
|
||||||
{cat.name}
|
{cat.name}
|
||||||
</text>
|
</text>
|
||||||
@@ -187,6 +203,7 @@ function DiscoverPage() {
|
|||||||
}}
|
}}
|
||||||
</For>
|
</For>
|
||||||
</Show>
|
</Show>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
|
|
||||||
// ── current pane ───────────────────────────────────────────────────────────
|
// ── current pane ───────────────────────────────────────────────────────────
|
||||||
@@ -203,7 +220,6 @@ function DiscoverPage() {
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
flexDirection="row"
|
flexDirection="row"
|
||||||
gap={1}
|
gap={1}
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
paddingRight={1}
|
||||||
backgroundColor={focusBg(index(), lf(), isActive())}
|
backgroundColor={focusBg(index(), lf(), isActive())}
|
||||||
onMouseDown={() => {
|
onMouseDown={() => {
|
||||||
@@ -213,8 +229,13 @@ function DiscoverPage() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<text fg={focusFg(index(), lf(), isActive())}>
|
<text fg={focusFg(index(), lf(), isActive())}>
|
||||||
{index() === lf() ? "❯" : " "}
|
{index() === lf() ? marker() : " "}
|
||||||
</text>
|
</text>
|
||||||
|
{nerd && (
|
||||||
|
<text fg={focusFg(index(), lf(), isActive())}>
|
||||||
|
{cat.icon}
|
||||||
|
</text>
|
||||||
|
)}
|
||||||
<text fg={focusFg(index(), lf(), isActive())}>{cat.name}</text>
|
<text fg={focusFg(index(), lf(), isActive())}>{cat.name}</text>
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
@@ -247,7 +268,6 @@ function DiscoverPage() {
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
flexDirection="column"
|
flexDirection="column"
|
||||||
gap={0}
|
gap={0}
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
paddingRight={1}
|
||||||
backgroundColor={focusBg(index(), lf(), isActive())}
|
backgroundColor={focusBg(index(), lf(), isActive())}
|
||||||
onMouseDown={() => {
|
onMouseDown={() => {
|
||||||
@@ -257,7 +277,7 @@ function DiscoverPage() {
|
|||||||
>
|
>
|
||||||
<box flexDirection="row" gap={1}>
|
<box flexDirection="row" gap={1}>
|
||||||
<text fg={focusFg(index(), lf(), isActive())}>
|
<text fg={focusFg(index(), lf(), isActive())}>
|
||||||
{index() === lf() ? "❯" : " "}
|
{index() === lf() ? marker() : " "}
|
||||||
</text>
|
</text>
|
||||||
<text fg={focusFg(index(), lf(), isActive())}>
|
<text fg={focusFg(index(), lf(), isActive())}>
|
||||||
{podcast.title}
|
{podcast.title}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import { createMemo, createEffect, For, Show, onMount, onCleanup } from "solid-j
|
|||||||
import { useFeedStore } from "@/stores/feed";
|
import { useFeedStore } from "@/stores/feed";
|
||||||
import { useDownloadStore } from "@/stores/download";
|
import { useDownloadStore } from "@/stores/download";
|
||||||
import { useAppStore } from "@/stores/app";
|
import { useAppStore } from "@/stores/app";
|
||||||
|
import { prefetchCoverArt } from "@/utils/cover-art";
|
||||||
import { DownloadStatus } from "@/types/episode";
|
import { DownloadStatus } from "@/types/episode";
|
||||||
import { format } from "date-fns";
|
import { format } from "date-fns";
|
||||||
import { useTheme } from "@/context/ThemeContext";
|
import { useTheme } from "@/context/ThemeContext";
|
||||||
@@ -32,6 +33,7 @@ import {
|
|||||||
} from "@/context/NavigationContext";
|
} from "@/context/NavigationContext";
|
||||||
import { useAudio } from "@/hooks/useAudio";
|
import { useAudio } from "@/hooks/useAudio";
|
||||||
import { on, off } from "@/utils/event-bus";
|
import { on, off } from "@/utils/event-bus";
|
||||||
|
import { NF_ICONS, supportsNerdFonts } from "@/utils/nerd-fonts";
|
||||||
import type { KeybindActionName } from "@/context/KeybindContext";
|
import type { KeybindActionName } from "@/context/KeybindContext";
|
||||||
import type { Episode } from "@/types/episode";
|
import type { Episode } from "@/types/episode";
|
||||||
import type { Feed } from "@/types/feed";
|
import type { Feed } from "@/types/feed";
|
||||||
@@ -39,12 +41,15 @@ import { LoadingIndicator } from "@/components/LoadingIndicator";
|
|||||||
import { PaneRow } from "@/components/PaneRow";
|
import { PaneRow } from "@/components/PaneRow";
|
||||||
import { TabListPane } from "@/components/TabPanel";
|
import { TabListPane } from "@/components/TabPanel";
|
||||||
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
||||||
|
import { useSelectionMarker } from "@/hooks/useSelectionMarker";
|
||||||
|
|
||||||
export const FeedPaneCount = 1;
|
export const FeedPaneCount = 1;
|
||||||
|
|
||||||
type EpItem = { episode: Episode; feed: Feed };
|
type EpItem = { episode: Episode; feed: Feed };
|
||||||
|
|
||||||
function FeedPage() {
|
function FeedPage() {
|
||||||
|
// Static: detection never changes mid-session.
|
||||||
|
const nerd = supportsNerdFonts();
|
||||||
const feedStore = useFeedStore();
|
const feedStore = useFeedStore();
|
||||||
const downloadStore = useDownloadStore();
|
const downloadStore = useDownloadStore();
|
||||||
const audioNav = useAudioNavStore();
|
const audioNav = useAudioNavStore();
|
||||||
@@ -52,18 +57,35 @@ function FeedPage() {
|
|||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const muted = () => theme.muted || theme.text;
|
const muted = () => theme.muted || theme.text;
|
||||||
const nav = useNavigation();
|
const nav = useNavigation();
|
||||||
|
const marker = useSelectionMarker();
|
||||||
|
|
||||||
// ── flat episode list (depth 0 — the only depth Feed has) ────────────────
|
// ── flat episode list (depth 0 — the only depth Feed has) ────────────────
|
||||||
const episodes = createMemo<EpItem[]>(
|
const episodes = createMemo<EpItem[]>(
|
||||||
() => feedStore.getAllEpisodesChronological() as EpItem[],
|
() => feedStore.getAllEpisodesChronological() as EpItem[],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ── Cover warm-up ────────────────────────────────────────────────────────
|
||||||
|
// Prefetch covers for episodes around the focus (plus the top of the
|
||||||
|
// list) so plays land on a warm cache: cover-art-files only applies at
|
||||||
|
// file load, and there is no working runtime fallback. Single-flight +
|
||||||
|
// cache short-circuit keep repeat runs cheap (hits resolve immediately).
|
||||||
|
createEffect(() => {
|
||||||
|
const list = episodes();
|
||||||
|
const focusIdx = focusedEpIdx();
|
||||||
|
const start = Math.max(0, focusIdx - 10);
|
||||||
|
const end = Math.min(list.length, focusIdx + 11);
|
||||||
|
for (let i = start; i < end; i++) {
|
||||||
|
const item = list[i];
|
||||||
|
if (item?.feed.podcast.coverUrl) prefetchCoverArt(item.feed.podcast.coverUrl);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// ── Fetch More ───────────────────────────────────────────────────────────
|
// ── Fetch More ───────────────────────────────────────────────────────────
|
||||||
// A "[Fetch More]" row at the bottom of the list advances every feed's
|
// A "[Fetch More]" row at the bottom of the list advances every feed's
|
||||||
// loaded window by 50 episodes. manual mode: Enter on the row. auto mode:
|
// loaded window by 50 episodes. manual mode: Enter on the row. auto mode:
|
||||||
// reaching the bottom row fetches automatically (see the effect below).
|
// reaching the bottom row fetches automatically (see the effect below).
|
||||||
const app = useAppStore();
|
const app = useAppStore();
|
||||||
const fetchMoreMode = () => app.state().preferences.fetchMoreMode ?? "manual";
|
const fetchMoreMode = () => app.state().preferences.fetchMoreMode ?? "auto";
|
||||||
const showFetchMore = () => feedStore.hasMoreAcrossAll();
|
const showFetchMore = () => feedStore.hasMoreAcrossAll();
|
||||||
// Total navigable rows: episodes + the optional Fetch More row.
|
// Total navigable rows: episodes + the optional Fetch More row.
|
||||||
const rowCount = () => episodes().length + (showFetchMore() ? 1 : 0);
|
const rowCount = () => episodes().length + (showFetchMore() ? 1 : 0);
|
||||||
@@ -171,6 +193,18 @@ function FeedPage() {
|
|||||||
const item = focusedItem();
|
const item = focusedItem();
|
||||||
if (item) nav.toggleSelected(item.episode.id);
|
if (item) nav.toggleSelected(item.episode.id);
|
||||||
},
|
},
|
||||||
|
download: () => {
|
||||||
|
const item = focusedItem();
|
||||||
|
if (item) downloadStore.startDownload(item.episode, item.feed.id);
|
||||||
|
},
|
||||||
|
"delete-download": () => {
|
||||||
|
const item = focusedItem();
|
||||||
|
if (!item) return;
|
||||||
|
const id = item.episode.id;
|
||||||
|
if (downloadStore.getDownloadStatus(id) === DownloadStatus.NONE) return;
|
||||||
|
downloadStore.cancelDownload(id);
|
||||||
|
downloadStore.removeDownload(id).catch(() => {});
|
||||||
|
},
|
||||||
refresh: () => {
|
refresh: () => {
|
||||||
feedStore.refreshAllFeeds().catch(() => {});
|
feedStore.refreshAllFeeds().catch(() => {});
|
||||||
},
|
},
|
||||||
@@ -219,7 +253,7 @@ function FeedPage() {
|
|||||||
<Show
|
<Show
|
||||||
when={episodes().length > 0}
|
when={episodes().length > 0}
|
||||||
fallback={
|
fallback={
|
||||||
<box padding={1}>
|
<box padding={1} alignItems="center">
|
||||||
<Show
|
<Show
|
||||||
when={feedStore.isLoadingFeeds()}
|
when={feedStore.isLoadingFeeds()}
|
||||||
fallback={
|
fallback={
|
||||||
@@ -242,7 +276,6 @@ function FeedPage() {
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
flexDirection="column"
|
flexDirection="column"
|
||||||
gap={0}
|
gap={0}
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
paddingRight={1}
|
||||||
backgroundColor={focusBg(index(), fi(), isActive())}
|
backgroundColor={focusBg(index(), fi(), isActive())}
|
||||||
onMouseDown={() => {
|
onMouseDown={() => {
|
||||||
@@ -251,31 +284,55 @@ function FeedPage() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<box flexDirection="row" gap={1}>
|
<box flexDirection="row" gap={1}>
|
||||||
<text fg={focusFg(index(), fi(), isActive())}>
|
<text
|
||||||
{index() === fi() ? "❯" : " "}
|
flexShrink={0}
|
||||||
|
fg={focusFg(index(), fi(), isActive())}
|
||||||
|
>
|
||||||
|
{index() === fi() ? marker() : " "}
|
||||||
</text>
|
</text>
|
||||||
<text fg={focusFg(index(), fi(), isActive())}>
|
<text
|
||||||
|
wrapMode="none"
|
||||||
|
truncate
|
||||||
|
fg={focusFg(index(), fi(), isActive())}
|
||||||
|
>
|
||||||
{item.episode.episodeNumber
|
{item.episode.episodeNumber
|
||||||
? `#${item.episode.episodeNumber} `
|
? `#${item.episode.episodeNumber} `
|
||||||
: ""}
|
: ""}
|
||||||
{item.episode.title}
|
{item.episode.title}
|
||||||
</text>
|
</text>
|
||||||
</box>
|
</box>
|
||||||
<box flexDirection="row" gap={2} paddingLeft={2}>
|
{/* podcast name on its own row — readable at a glance; the
|
||||||
<text fg={index() === fi() ? theme.surface : theme.info}>
|
50% current pane fits it in full for typical names, and
|
||||||
{formatDate(item.episode.pubDate)}
|
truncate keeps the row one line tall either way */}
|
||||||
</text>
|
<box paddingLeft={2}>
|
||||||
<text fg={index() === fi() ? theme.surface : muted()}>
|
<text
|
||||||
{formatDuration(item.episode.duration)}
|
wrapMode="none"
|
||||||
</text>
|
truncate
|
||||||
<text fg={index() === fi() ? theme.surface : muted()}>
|
fg={index() === fi() ? theme.surface : theme.textSecondary}
|
||||||
|
>
|
||||||
{item.feed.customName || item.feed.podcast.title}
|
{item.feed.customName || item.feed.podcast.title}
|
||||||
</text>
|
</text>
|
||||||
|
</box>
|
||||||
|
<box flexDirection="row" gap={2} paddingLeft={2}>
|
||||||
|
<text
|
||||||
|
flexShrink={0}
|
||||||
|
fg={index() === fi() ? theme.surface : theme.info}
|
||||||
|
>
|
||||||
|
{formatDate(item.episode.pubDate)}
|
||||||
|
</text>
|
||||||
|
<text
|
||||||
|
flexShrink={0}
|
||||||
|
fg={index() === fi() ? theme.surface : muted()}
|
||||||
|
>
|
||||||
|
{formatDuration(item.episode.duration)}
|
||||||
|
</text>
|
||||||
<Show when={nav.isSelected(item.episode.id)}>
|
<Show when={nav.isSelected(item.episode.id)}>
|
||||||
<text fg={theme.warning}>●</text>
|
<text flexShrink={0} fg={theme.warning}>
|
||||||
|
●
|
||||||
|
</text>
|
||||||
</Show>
|
</Show>
|
||||||
<Show when={downloadLabel(item.episode.id)}>
|
<Show when={downloadLabel(item.episode.id)}>
|
||||||
<text fg={downloadColor(item.episode.id)}>
|
<text flexShrink={0} fg={downloadColor(item.episode.id)}>
|
||||||
{downloadLabel(item.episode.id)}
|
{downloadLabel(item.episode.id)}
|
||||||
</text>
|
</text>
|
||||||
</Show>
|
</Show>
|
||||||
@@ -289,7 +346,6 @@ function FeedPage() {
|
|||||||
ref={moreRef}
|
ref={moreRef}
|
||||||
flexDirection="row"
|
flexDirection="row"
|
||||||
gap={1}
|
gap={1}
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
paddingRight={1}
|
||||||
backgroundColor={focusBg(episodes().length, focusedRow(), isActive())}
|
backgroundColor={focusBg(episodes().length, focusedRow(), isActive())}
|
||||||
onMouseDown={() => {
|
onMouseDown={() => {
|
||||||
@@ -298,8 +354,13 @@ function FeedPage() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<text fg={focusFg(episodes().length, focusedRow(), isActive())}>
|
<text fg={focusFg(episodes().length, focusedRow(), isActive())}>
|
||||||
{focusedOnMore() ? "❯" : " "}
|
{focusedOnMore() ? marker() : " "}
|
||||||
</text>
|
</text>
|
||||||
|
{nerd && (
|
||||||
|
<text fg={focusFg(episodes().length, focusedRow(), isActive())}>
|
||||||
|
{NF_ICONS.more}
|
||||||
|
</text>
|
||||||
|
)}
|
||||||
<Show
|
<Show
|
||||||
when={!feedStore.isLoadingMore()}
|
when={!feedStore.isLoadingMore()}
|
||||||
fallback={<LoadingIndicator label="Fetching…" />}
|
fallback={<LoadingIndicator label="Fetching…" />}
|
||||||
@@ -311,7 +372,7 @@ function FeedPage() {
|
|||||||
</box>
|
</box>
|
||||||
</Show>
|
</Show>
|
||||||
<Show when={feedStore.isLoadingFeeds()}>
|
<Show when={feedStore.isLoadingFeeds()}>
|
||||||
<box paddingLeft={2} paddingTop={1}>
|
<box alignItems="center" paddingTop={1}>
|
||||||
<LoadingIndicator label="Refreshing…" />
|
<LoadingIndicator label="Refreshing…" />
|
||||||
</box>
|
</box>
|
||||||
</Show>
|
</Show>
|
||||||
@@ -378,7 +439,14 @@ function FeedPage() {
|
|||||||
{(item().episode.description?.length ?? 0) > 400 ? "…" : ""}
|
{(item().episode.description?.length ?? 0) > 400 ? "…" : ""}
|
||||||
</text>
|
</text>
|
||||||
<box height={1} />
|
<box height={1} />
|
||||||
<text fg={muted()}>enter: play · space: select · h back</text>
|
<text fg={muted()}>
|
||||||
|
enter: play · d: download
|
||||||
|
{downloadStore.getDownloadStatus(item().episode.id) !==
|
||||||
|
DownloadStatus.NONE
|
||||||
|
? " · D: delete"
|
||||||
|
: ""}{" "}
|
||||||
|
· space: select · h back
|
||||||
|
</text>
|
||||||
</box>
|
</box>
|
||||||
)}
|
)}
|
||||||
</Show>
|
</Show>
|
||||||
|
|||||||
@@ -6,14 +6,18 @@
|
|||||||
* depth 1 (current) — episodes of the drilled show. Parent pane = shows.
|
* depth 1 (current) — episodes of the drilled show. Parent pane = shows.
|
||||||
* preview — detail of the hovered item in the current column.
|
* preview — detail of the hovered item in the current column.
|
||||||
*
|
*
|
||||||
|
* Depth 1 ends with a "[Fetch More]" row (same preference-driven behavior
|
||||||
|
* as the Feed tab) that loads the next batch of episodes for that show.
|
||||||
|
*
|
||||||
* Renders entirely through `<PaneRow>`; no bespoke 3-column flexbox JSX
|
* Renders entirely through `<PaneRow>`; no bespoke 3-column flexbox JSX
|
||||||
* remains. `l`/Enter drills in (show → episodes); `h` pops a depth (noop at
|
* remains. `l`/Enter drills in (show → episodes); `h` pops a depth (noop at
|
||||||
* 0). j/k move only within the current column.
|
* 0). j/k move only within the current column.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { createMemo, For, Show, onMount, onCleanup } from "solid-js";
|
import { createMemo, createEffect, For, Show, onMount, onCleanup } from "solid-js";
|
||||||
import { useFeedStore } from "@/stores/feed";
|
import { useFeedStore } from "@/stores/feed";
|
||||||
import { useDownloadStore } from "@/stores/download";
|
import { useDownloadStore } from "@/stores/download";
|
||||||
|
import { useAppStore } from "@/stores/app";
|
||||||
import { DownloadStatus } from "@/types/episode";
|
import { DownloadStatus } from "@/types/episode";
|
||||||
import { format } from "date-fns";
|
import { format } from "date-fns";
|
||||||
import { useTheme } from "@/context/ThemeContext";
|
import { useTheme } from "@/context/ThemeContext";
|
||||||
@@ -27,24 +31,30 @@ import {
|
|||||||
} from "@/context/NavigationContext";
|
} from "@/context/NavigationContext";
|
||||||
import { useAudio } from "@/hooks/useAudio";
|
import { useAudio } from "@/hooks/useAudio";
|
||||||
import { on, off } from "@/utils/event-bus";
|
import { on, off } from "@/utils/event-bus";
|
||||||
|
import { NF_ICONS, supportsNerdFonts } from "@/utils/nerd-fonts";
|
||||||
import type { KeybindActionName } from "@/context/KeybindContext";
|
import type { KeybindActionName } from "@/context/KeybindContext";
|
||||||
import type { Episode } from "@/types/episode";
|
import type { Episode, DownloadedEpisode } from "@/types/episode";
|
||||||
import type { Feed } from "@/types/feed";
|
import type { Feed } from "@/types/feed";
|
||||||
import { LoadingIndicator } from "@/components/LoadingIndicator";
|
import { LoadingIndicator } from "@/components/LoadingIndicator";
|
||||||
import { PaneRow } from "@/components/PaneRow";
|
import { PaneRow } from "@/components/PaneRow";
|
||||||
import { TabListPane } from "@/components/TabPanel";
|
import { TabListPane } from "@/components/TabPanel";
|
||||||
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
||||||
|
import { useSelectionMarker } from "@/hooks/useSelectionMarker";
|
||||||
|
|
||||||
export const MyShowsPaneCount = 1;
|
export const MyShowsPaneCount = 1;
|
||||||
|
|
||||||
export function MyShowsPage() {
|
export function MyShowsPage() {
|
||||||
|
// Static: detection never changes mid-session.
|
||||||
|
const nerd = supportsNerdFonts();
|
||||||
const feedStore = useFeedStore();
|
const feedStore = useFeedStore();
|
||||||
const downloadStore = useDownloadStore();
|
const downloadStore = useDownloadStore();
|
||||||
|
const app = useAppStore();
|
||||||
const audioNav = useAudioNavStore();
|
const audioNav = useAudioNavStore();
|
||||||
const audio = useAudio();
|
const audio = useAudio();
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const muted = () => theme.muted || theme.text;
|
const muted = () => theme.muted || theme.text;
|
||||||
const nav = useNavigation();
|
const nav = useNavigation();
|
||||||
|
const marker = useSelectionMarker();
|
||||||
|
|
||||||
const stack = nav.depthStack;
|
const stack = nav.depthStack;
|
||||||
const depth = nav.currentDepth;
|
const depth = nav.currentDepth;
|
||||||
@@ -52,9 +62,28 @@ export function MyShowsPage() {
|
|||||||
|
|
||||||
const shows = () => feedStore.getFilteredFeeds();
|
const shows = () => feedStore.getFilteredFeeds();
|
||||||
|
|
||||||
|
// Downloads of shows that are NOT subscribed (made from episode search) —
|
||||||
|
// listed as their own section under the shows list. Reads feeds() so an
|
||||||
|
// entry drops out the moment the user subscribes to its show.
|
||||||
|
const unsubs = () => downloadStore.getUnsubscribedDownloads();
|
||||||
|
|
||||||
|
// Total depth-0 rows: subscribed shows + unsubscribed-show downloads.
|
||||||
|
const depth0Count = () => shows().length + unsubs().length;
|
||||||
|
|
||||||
const focusedShowIdx = () =>
|
const focusedShowIdx = () =>
|
||||||
shows().length === 0 ? 0 : Math.min(focus(0), shows().length - 1);
|
shows().length === 0 ? 0 : Math.min(focus(0), shows().length - 1);
|
||||||
const selectedShow = (): Feed | undefined => shows()[focusedShowIdx()];
|
/** True when the depth-0 cursor sits on an unsubscribed-show download
|
||||||
|
* row (past the shows list). */
|
||||||
|
const focusedOnUnsub = () =>
|
||||||
|
depth() === 0 && focus(0) >= shows().length && unsubs().length > 0;
|
||||||
|
const focusedUnsub = (): DownloadedEpisode | undefined => {
|
||||||
|
if (!focusedOnUnsub()) return undefined;
|
||||||
|
return unsubs()[Math.min(focus(0) - shows().length, unsubs().length - 1)];
|
||||||
|
};
|
||||||
|
const selectedShow = (): Feed | undefined => {
|
||||||
|
if (focusedOnUnsub()) return undefined;
|
||||||
|
return shows()[focusedShowIdx()];
|
||||||
|
};
|
||||||
|
|
||||||
// depth-1 frame ctx = the drilled feed id
|
// depth-1 frame ctx = the drilled feed id
|
||||||
const drilledShowId = (): string => stack()[1]?.ctx ?? "";
|
const drilledShowId = (): string => stack()[1]?.ctx ?? "";
|
||||||
@@ -67,27 +96,64 @@ export function MyShowsPage() {
|
|||||||
(a, b) => b.pubDate.getTime() - a.pubDate.getTime(),
|
(a, b) => b.pubDate.getTime() - a.pubDate.getTime(),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
// ── Fetch More ───────────────────────────────────────────────────────────
|
||||||
|
// A "[Fetch More]" row at the bottom of a drilled show's episode list
|
||||||
|
// advances that show's loaded window by 50 episodes — the per-show
|
||||||
|
// counterpart to the Feed page's row (which loads every feed). manual
|
||||||
|
// mode: Enter on the row. auto mode: reaching the bottom row fetches
|
||||||
|
// automatically (see the effect below).
|
||||||
|
const fetchMoreMode = () => app.state().preferences.fetchMoreMode ?? "auto";
|
||||||
|
const showFetchMore = () =>
|
||||||
|
depth() >= 1 &&
|
||||||
|
!!drilledShowId() &&
|
||||||
|
feedStore.hasMoreEpisodes(drilledShowId());
|
||||||
|
// Total navigable rows at depth 1: episodes + the optional Fetch More row.
|
||||||
|
const rowCount = () => episodes().length + (showFetchMore() ? 1 : 0);
|
||||||
|
const focusedRow = () =>
|
||||||
|
rowCount() === 0 ? 0 : Math.min(focus(1), rowCount() - 1);
|
||||||
|
const focusedOnMore = () =>
|
||||||
|
showFetchMore() && focusedRow() === episodes().length;
|
||||||
|
// -1 while the Fetch More row is focused so no episode row renders the
|
||||||
|
// cursor/highlight (the button is the focused row, not the last episode).
|
||||||
const focusedEpIdx = () =>
|
const focusedEpIdx = () =>
|
||||||
episodes().length === 0 ? 0 : Math.min(focus(1), episodes().length - 1);
|
focusedOnMore()
|
||||||
const focusedEpisode = () => episodes()[focusedEpIdx()];
|
? -1
|
||||||
|
: Math.min(focusedRow(), Math.max(episodes().length - 1, 0));
|
||||||
|
const focusedEpisode = () =>
|
||||||
|
focusedOnMore() ? undefined : episodes()[focusedEpIdx()];
|
||||||
|
const moreRef = useScrollIntoView(() => focusedOnMore());
|
||||||
|
|
||||||
const curLen = () => (depth() === 0 ? shows().length : episodes().length);
|
const curLen = () => (depth() === 0 ? depth0Count() : rowCount());
|
||||||
|
|
||||||
const ensureFocus = () => {
|
const ensureFocus = () => {
|
||||||
if (shows().length > 0 && focus(0) >= shows().length)
|
if (depth() === 0 && depth0Count() > 0 && focus(0) >= depth0Count())
|
||||||
nav.setDepthFocus(shows().length - 1, 0);
|
nav.setDepthFocus(depth0Count() - 1, 0);
|
||||||
if (depth() >= 1 && episodes().length > 0 && focus(1) >= episodes().length)
|
if (depth() >= 1 && rowCount() > 0 && focus(1) >= rowCount())
|
||||||
nav.setDepthFocus(episodes().length - 1, 1);
|
nav.setDepthFocus(rowCount() - 1, 1);
|
||||||
};
|
};
|
||||||
onMount(ensureFocus);
|
onMount(ensureFocus);
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
nav.registerResolver(`${nav.activeTab()}:${DEPTH_CENTER_PANE}`, (i) => {
|
nav.registerResolver(`${nav.activeTab()}:${DEPTH_CENTER_PANE}`, (i) => {
|
||||||
if (depth() === 0) return shows()[i]?.id;
|
if (depth() === 0) {
|
||||||
|
if (i < shows().length) return shows()[i]?.id;
|
||||||
|
return unsubs()[i - shows().length]?.episodeId;
|
||||||
|
}
|
||||||
return episodes()[i]?.id;
|
return episodes()[i]?.id;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Auto mode: reaching the bottom of a drilled show's list loads its next
|
||||||
|
// batch. Guarded by isLoadingMore so concurrent loads never stack.
|
||||||
|
createEffect(() => {
|
||||||
|
if (depth() < 1) return;
|
||||||
|
if (fetchMoreMode() !== "auto") return;
|
||||||
|
if (!showFetchMore()) return;
|
||||||
|
if (feedStore.isLoadingMore()) return;
|
||||||
|
if (focusedRow() < rowCount() - 1) return;
|
||||||
|
feedStore.loadMoreEpisodes(drilledShowId()).catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
// ── helpers ─────────────────────────────────────────────────────────────────
|
// ── helpers ─────────────────────────────────────────────────────────────────
|
||||||
const formatDate = (d: Date) => format(d, "MMM d, yyyy");
|
const formatDate = (d: Date) => format(d, "MMM d, yyyy");
|
||||||
const formatDuration = (s: number) => {
|
const formatDuration = (s: number) => {
|
||||||
@@ -128,9 +194,31 @@ export function MyShowsPage() {
|
|||||||
audioNav.setSource(AudioSource.MY_SHOWS, selectedShow()?.podcast.id);
|
audioNav.setSource(AudioSource.MY_SHOWS, selectedShow()?.podcast.id);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Stream an unsubscribed-show download. The record carries only what was
|
||||||
|
* persisted at download time, so a minimal Episode is reconstructed. */
|
||||||
|
const playUnsubscribedDownload = (d: DownloadedEpisode) => {
|
||||||
|
audio
|
||||||
|
.play({
|
||||||
|
id: d.episodeId,
|
||||||
|
podcastId: d.feedId,
|
||||||
|
title: d.episodeTitle ?? d.episodeId,
|
||||||
|
description: "",
|
||||||
|
audioUrl: d.audioUrl ?? "",
|
||||||
|
duration: 0,
|
||||||
|
pubDate: d.pubDate ? new Date(d.pubDate) : new Date(),
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
audioNav.setSource(AudioSource.SEARCH, d.feedId);
|
||||||
|
};
|
||||||
|
|
||||||
// ── drill / open ───────────────────────────────────────────────────────────
|
// ── drill / open ───────────────────────────────────────────────────────────
|
||||||
function open() {
|
function open() {
|
||||||
if (depth() === 0) {
|
if (depth() === 0) {
|
||||||
|
const d = focusedUnsub();
|
||||||
|
if (d) {
|
||||||
|
playUnsubscribedDownload(d);
|
||||||
|
return;
|
||||||
|
}
|
||||||
const show = selectedShow();
|
const show = selectedShow();
|
||||||
if (!show) return;
|
if (!show) return;
|
||||||
nav.pushDepth({ kind: "episodes", ctx: show.id, focus: 0 } as DepthFrame);
|
nav.pushDepth({ kind: "episodes", ctx: show.id, focus: 0 } as DepthFrame);
|
||||||
@@ -139,6 +227,10 @@ export function MyShowsPage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (depth() >= 1) {
|
if (depth() >= 1) {
|
||||||
|
if (focusedOnMore()) {
|
||||||
|
feedStore.loadMoreEpisodes(drilledShowId()).catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
const ep = focusedEpisode();
|
const ep = focusedEpisode();
|
||||||
if (ep) playEpisode(ep);
|
if (ep) playEpisode(ep);
|
||||||
}
|
}
|
||||||
@@ -161,6 +253,41 @@ export function MyShowsPage() {
|
|||||||
if (ep) nav.toggleSelected(ep.id);
|
if (ep) nav.toggleSelected(ep.id);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
download: () => {
|
||||||
|
if (depth() < 1) return;
|
||||||
|
const ep = focusedEpisode();
|
||||||
|
if (ep) downloadStore.startDownload(ep, drilledShowId());
|
||||||
|
},
|
||||||
|
"delete-download": () => {
|
||||||
|
if (depth() === 0) {
|
||||||
|
const d = focusedUnsub();
|
||||||
|
if (d) {
|
||||||
|
downloadStore.cancelDownload(d.episodeId);
|
||||||
|
downloadStore.removeDownload(d.episodeId).catch(() => {});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (depth() < 1) return;
|
||||||
|
const ep = focusedEpisode();
|
||||||
|
if (!ep) return;
|
||||||
|
const id = ep.id;
|
||||||
|
if (downloadStore.getDownloadStatus(id) === DownloadStatus.NONE) return;
|
||||||
|
downloadStore.cancelDownload(id);
|
||||||
|
downloadStore.removeDownload(id).catch(() => {});
|
||||||
|
},
|
||||||
|
"whitelist-toggle": () => {
|
||||||
|
const prefs = app.state().preferences;
|
||||||
|
if (prefs.autoDownloadScope !== "whitelist") return;
|
||||||
|
// depth 0: the focused show; depth ≥1: the drilled show.
|
||||||
|
const id = depth() >= 1 ? drilledShowId() : selectedShow()?.id;
|
||||||
|
if (!id) return;
|
||||||
|
const cur = prefs.autoDownloadWhitelist ?? [];
|
||||||
|
const next = cur.includes(id)
|
||||||
|
? cur.filter((x) => x !== id)
|
||||||
|
: [...cur, id];
|
||||||
|
app.updatePreferences({ autoDownloadWhitelist: next });
|
||||||
|
feedStore.runAutoDownload();
|
||||||
|
},
|
||||||
refresh: () => {
|
refresh: () => {
|
||||||
const show = selectedShow();
|
const show = selectedShow();
|
||||||
if (show) feedStore.refreshFeed(show.id).catch(() => {});
|
if (show) feedStore.refreshFeed(show.id).catch(() => {});
|
||||||
@@ -208,7 +335,9 @@ export function MyShowsPage() {
|
|||||||
|
|
||||||
const currentLabel = () =>
|
const currentLabel = () =>
|
||||||
depth() === 0
|
depth() === 0
|
||||||
? `Shows (${shows().length})`
|
? `Shows (${shows().length})${
|
||||||
|
unsubs().length > 0 ? ` · Unsub DL (${unsubs().length})` : ""
|
||||||
|
}`
|
||||||
: `${selectedShow() ? showTitle(selectedShow()!) : "Episodes"} · ${episodes().length}`;
|
: `${selectedShow() ? showTitle(selectedShow()!) : "Episodes"} · ${episodes().length}`;
|
||||||
|
|
||||||
// ── parent pane: previous-depth list (muted/blank at depth 0) ─────────────
|
// ── parent pane: previous-depth list (muted/blank at depth 0) ─────────────
|
||||||
@@ -225,12 +354,11 @@ export function MyShowsPage() {
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
flexDirection="row"
|
flexDirection="row"
|
||||||
gap={1}
|
gap={1}
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
paddingRight={1}
|
||||||
backgroundColor={focusBg(index(), lf(), false)}
|
backgroundColor={focusBg(index(), lf(), false)}
|
||||||
>
|
>
|
||||||
<text fg={focusFg(index(), lf(), false)}>
|
<text fg={focusFg(index(), lf(), false)}>
|
||||||
{index() === lf() ? "❯" : " "}
|
{index() === lf() ? marker() : " "}
|
||||||
</text>
|
</text>
|
||||||
<text fg={focusFg(index(), lf(), false)}>{showTitle(feed)}</text>
|
<text fg={focusFg(index(), lf(), false)}>{showTitle(feed)}</text>
|
||||||
<text fg={muted()}>({feed.episodes.length})</text>
|
<text fg={muted()}>({feed.episodes.length})</text>
|
||||||
@@ -247,7 +375,7 @@ export function MyShowsPage() {
|
|||||||
{/* depth 0: shows — stable sibling <Show> so the swap disposes cleanly */}
|
{/* depth 0: shows — stable sibling <Show> so the swap disposes cleanly */}
|
||||||
<Show when={depth() === 0}>
|
<Show when={depth() === 0}>
|
||||||
<Show
|
<Show
|
||||||
when={shows().length > 0}
|
when={depth0Count() > 0}
|
||||||
fallback={
|
fallback={
|
||||||
<box padding={1}>
|
<box padding={1}>
|
||||||
<text fg={muted()}>
|
<text fg={muted()}>
|
||||||
@@ -260,12 +388,16 @@ export function MyShowsPage() {
|
|||||||
{(feed, index) => {
|
{(feed, index) => {
|
||||||
const lf = () => focusedShowIdx();
|
const lf = () => focusedShowIdx();
|
||||||
const ref = useScrollIntoView(() => index() === lf());
|
const ref = useScrollIntoView(() => index() === lf());
|
||||||
|
const wlScope =
|
||||||
|
app.state().preferences.autoDownloadScope === "whitelist";
|
||||||
|
const wlInList = (
|
||||||
|
app.state().preferences.autoDownloadWhitelist ?? []
|
||||||
|
).includes(feed.id);
|
||||||
return (
|
return (
|
||||||
<box
|
<box
|
||||||
ref={ref}
|
ref={ref}
|
||||||
flexDirection="row"
|
flexDirection="row"
|
||||||
gap={1}
|
gap={1}
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
paddingRight={1}
|
||||||
backgroundColor={focusBg(index(), lf(), isActive())}
|
backgroundColor={focusBg(index(), lf(), isActive())}
|
||||||
onMouseDown={() => {
|
onMouseDown={() => {
|
||||||
@@ -274,7 +406,7 @@ export function MyShowsPage() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<text fg={focusFg(index(), lf(), isActive())}>
|
<text fg={focusFg(index(), lf(), isActive())}>
|
||||||
{index() === lf() ? "❯" : " "}
|
{index() === lf() ? marker() : " "}
|
||||||
</text>
|
</text>
|
||||||
<text fg={focusFg(index(), lf(), isActive())}>
|
<text fg={focusFg(index(), lf(), isActive())}>
|
||||||
{showTitle(feed)}
|
{showTitle(feed)}
|
||||||
@@ -282,10 +414,88 @@ export function MyShowsPage() {
|
|||||||
<text fg={index() === lf() ? theme.surface : muted()}>
|
<text fg={index() === lf() ? theme.surface : muted()}>
|
||||||
({feed.episodes.length})
|
({feed.episodes.length})
|
||||||
</text>
|
</text>
|
||||||
|
<Show when={wlScope}>
|
||||||
|
<text
|
||||||
|
fg={
|
||||||
|
index() === lf()
|
||||||
|
? theme.surface
|
||||||
|
: wlInList
|
||||||
|
? theme.warning
|
||||||
|
: muted()
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{wlInList ? "●" : "○"}
|
||||||
|
</text>
|
||||||
|
</Show>
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
}}
|
}}
|
||||||
</For>
|
</For>
|
||||||
|
<Show when={unsubs().length > 0}>
|
||||||
|
<box paddingLeft={1} paddingTop={1}>
|
||||||
|
<text fg={theme.textSecondary}>
|
||||||
|
Unsubscribed Show Downloads
|
||||||
|
</text>
|
||||||
|
</box>
|
||||||
|
<For each={unsubs()}>
|
||||||
|
{(d, index) => {
|
||||||
|
// Rows continue after the shows list.
|
||||||
|
const rowIdx = () => shows().length + index();
|
||||||
|
const lf = () => nav.depthFocus(0);
|
||||||
|
const ref = useScrollIntoView(() => rowIdx() === lf());
|
||||||
|
return (
|
||||||
|
<box
|
||||||
|
ref={ref}
|
||||||
|
flexDirection="column"
|
||||||
|
gap={0}
|
||||||
|
paddingRight={1}
|
||||||
|
backgroundColor={focusBg(rowIdx(), lf(), isActive())}
|
||||||
|
onMouseDown={() => {
|
||||||
|
nav.setActivePane(DEPTH_CENTER_PANE);
|
||||||
|
nav.setDepthFocus(rowIdx(), 0);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<box flexDirection="row" gap={1}>
|
||||||
|
<text
|
||||||
|
flexShrink={0}
|
||||||
|
fg={focusFg(rowIdx(), lf(), isActive())}
|
||||||
|
>
|
||||||
|
{rowIdx() === lf() ? marker() : " "}
|
||||||
|
</text>
|
||||||
|
<text
|
||||||
|
wrapMode="none"
|
||||||
|
truncate
|
||||||
|
fg={focusFg(rowIdx(), lf(), isActive())}
|
||||||
|
>
|
||||||
|
{d.episodeTitle ?? d.episodeId}
|
||||||
|
</text>
|
||||||
|
<Show when={downloadLabel(d.episodeId)}>
|
||||||
|
<text
|
||||||
|
flexShrink={0}
|
||||||
|
fg={downloadColor(d.episodeId)}
|
||||||
|
>
|
||||||
|
{downloadLabel(d.episodeId)}
|
||||||
|
</text>
|
||||||
|
</Show>
|
||||||
|
</box>
|
||||||
|
<box paddingLeft={2}>
|
||||||
|
<text
|
||||||
|
wrapMode="none"
|
||||||
|
truncate
|
||||||
|
fg={
|
||||||
|
rowIdx() === lf()
|
||||||
|
? theme.surface
|
||||||
|
: theme.textSecondary
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{d.podcastTitle ?? d.feedId}
|
||||||
|
</text>
|
||||||
|
</box>
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
</For>
|
||||||
|
</Show>
|
||||||
</Show>
|
</Show>
|
||||||
</Show>
|
</Show>
|
||||||
{/* depth ≥1: episodes */}
|
{/* depth ≥1: episodes */}
|
||||||
@@ -307,7 +517,6 @@ export function MyShowsPage() {
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
flexDirection="column"
|
flexDirection="column"
|
||||||
gap={0}
|
gap={0}
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
paddingRight={1}
|
||||||
backgroundColor={focusBg(index(), lf(), isActive())}
|
backgroundColor={focusBg(index(), lf(), isActive())}
|
||||||
onMouseDown={() => {
|
onMouseDown={() => {
|
||||||
@@ -316,26 +525,41 @@ export function MyShowsPage() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<box flexDirection="row" gap={1}>
|
<box flexDirection="row" gap={1}>
|
||||||
<text fg={focusFg(index(), lf(), isActive())}>
|
<text
|
||||||
{index() === lf() ? "❯" : " "}
|
flexShrink={0}
|
||||||
|
fg={focusFg(index(), lf(), isActive())}
|
||||||
|
>
|
||||||
|
{index() === lf() ? marker() : " "}
|
||||||
</text>
|
</text>
|
||||||
<text fg={focusFg(index(), lf(), isActive())}>
|
<text
|
||||||
|
wrapMode="none"
|
||||||
|
truncate
|
||||||
|
fg={focusFg(index(), lf(), isActive())}
|
||||||
|
>
|
||||||
{ep.episodeNumber ? `#${ep.episodeNumber} ` : ""}
|
{ep.episodeNumber ? `#${ep.episodeNumber} ` : ""}
|
||||||
{ep.title}
|
{ep.title}
|
||||||
</text>
|
</text>
|
||||||
</box>
|
</box>
|
||||||
<box flexDirection="row" gap={2} paddingLeft={2}>
|
<box flexDirection="row" gap={2} paddingLeft={2}>
|
||||||
<text fg={index() === lf() ? theme.surface : theme.info}>
|
<text
|
||||||
|
flexShrink={0}
|
||||||
|
fg={index() === lf() ? theme.surface : theme.info}
|
||||||
|
>
|
||||||
{formatDate(ep.pubDate)}
|
{formatDate(ep.pubDate)}
|
||||||
</text>
|
</text>
|
||||||
<text fg={index() === lf() ? theme.surface : muted()}>
|
<text
|
||||||
|
flexShrink={0}
|
||||||
|
fg={index() === lf() ? theme.surface : muted()}
|
||||||
|
>
|
||||||
{formatDuration(ep.duration)}
|
{formatDuration(ep.duration)}
|
||||||
</text>
|
</text>
|
||||||
<Show when={nav.isSelected(ep.id)}>
|
<Show when={nav.isSelected(ep.id)}>
|
||||||
<text fg={theme.warning}>●</text>
|
<text flexShrink={0} fg={theme.warning}>
|
||||||
|
●
|
||||||
|
</text>
|
||||||
</Show>
|
</Show>
|
||||||
<Show when={downloadLabel(ep.id)}>
|
<Show when={downloadLabel(ep.id)}>
|
||||||
<text fg={downloadColor(ep.id)}>
|
<text flexShrink={0} fg={downloadColor(ep.id)}>
|
||||||
{downloadLabel(ep.id)}
|
{downloadLabel(ep.id)}
|
||||||
</text>
|
</text>
|
||||||
</Show>
|
</Show>
|
||||||
@@ -344,9 +568,38 @@ export function MyShowsPage() {
|
|||||||
);
|
);
|
||||||
}}
|
}}
|
||||||
</For>
|
</For>
|
||||||
<Show when={feedStore.isLoadingMore()}>
|
<Show when={showFetchMore()}>
|
||||||
<box paddingLeft={2} paddingTop={1}>
|
<box
|
||||||
<LoadingIndicator label="Loading more…" />
|
ref={moreRef}
|
||||||
|
flexDirection="row"
|
||||||
|
gap={1}
|
||||||
|
paddingRight={1}
|
||||||
|
backgroundColor={focusBg(
|
||||||
|
episodes().length,
|
||||||
|
focusedRow(),
|
||||||
|
isActive(),
|
||||||
|
)}
|
||||||
|
onMouseDown={() => {
|
||||||
|
nav.setActivePane(DEPTH_CENTER_PANE);
|
||||||
|
nav.setDepthFocus(episodes().length, 1);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<text fg={focusFg(episodes().length, focusedRow(), isActive())}>
|
||||||
|
{focusedOnMore() ? marker() : " "}
|
||||||
|
</text>
|
||||||
|
{nerd && (
|
||||||
|
<text fg={focusFg(episodes().length, focusedRow(), isActive())}>
|
||||||
|
{NF_ICONS.more}
|
||||||
|
</text>
|
||||||
|
)}
|
||||||
|
<Show
|
||||||
|
when={!feedStore.isLoadingMore()}
|
||||||
|
fallback={<LoadingIndicator label="Fetching…" />}
|
||||||
|
>
|
||||||
|
<text fg={focusFg(episodes().length, focusedRow(), isActive())}>
|
||||||
|
[Fetch More]
|
||||||
|
</text>
|
||||||
|
</Show>
|
||||||
</box>
|
</box>
|
||||||
</Show>
|
</Show>
|
||||||
</Show>
|
</Show>
|
||||||
@@ -357,7 +610,11 @@ export function MyShowsPage() {
|
|||||||
// ── preview pane ───────────────────────────────────────────────────────────
|
// ── preview pane ───────────────────────────────────────────────────────────
|
||||||
const previewContent = () =>
|
const previewContent = () =>
|
||||||
depth() === 0 ? (
|
depth() === 0 ? (
|
||||||
// depth 0 preview: hovered show
|
// depth 0 preview: hovered unsubscribed-show download, else the
|
||||||
|
// hovered show.
|
||||||
|
<Show
|
||||||
|
when={focusedUnsub()}
|
||||||
|
fallback={
|
||||||
<Show
|
<Show
|
||||||
when={selectedShow()}
|
when={selectedShow()}
|
||||||
fallback={
|
fallback={
|
||||||
@@ -378,15 +635,77 @@ export function MyShowsPage() {
|
|||||||
{show().episodes.length} episodes
|
{show().episodes.length} episodes
|
||||||
</text>
|
</text>
|
||||||
<text fg={muted()}>
|
<text fg={muted()}>
|
||||||
{show().podcast.description?.slice(0, 400) ?? "No description."}
|
{show().podcast.description?.slice(0, 400) ??
|
||||||
|
"No description."}
|
||||||
</text>
|
</text>
|
||||||
<box height={1} />
|
<box height={1} />
|
||||||
<text fg={muted()}>enter/l: open · h: back · x: unsubscribe</text>
|
<text fg={muted()}>
|
||||||
|
enter/l: open · h: back · x: unsubscribe
|
||||||
|
{app.state().preferences.autoDownloadScope ===
|
||||||
|
"whitelist"
|
||||||
|
? (app.state().preferences.autoDownloadWhitelist ??
|
||||||
|
[]
|
||||||
|
).includes(show().id)
|
||||||
|
? " · w: un-whitelist"
|
||||||
|
: " · w: whitelist"
|
||||||
|
: ""}
|
||||||
|
</text>
|
||||||
|
</box>
|
||||||
|
)}
|
||||||
|
</Show>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{(d) => (
|
||||||
|
<box flexDirection="column" gap={1} padding={1}>
|
||||||
|
<text fg={theme.textPrimary ?? theme.text}>
|
||||||
|
<strong>{d().episodeTitle ?? d().episodeId}</strong>
|
||||||
|
</text>
|
||||||
|
<text fg={theme.textSecondary}>
|
||||||
|
{d().podcastTitle ?? d().feedId}
|
||||||
|
</text>
|
||||||
|
<box flexDirection="row" gap={2}>
|
||||||
|
<Show when={d().pubDate}>
|
||||||
|
<text fg={theme.info}>
|
||||||
|
{formatDate(new Date(d().pubDate!))}
|
||||||
|
</text>
|
||||||
|
</Show>
|
||||||
|
<Show when={downloadLabel(d().episodeId)}>
|
||||||
|
<text fg={downloadColor(d().episodeId)}>
|
||||||
|
{downloadLabel(d().episodeId)}
|
||||||
|
</text>
|
||||||
|
</Show>
|
||||||
|
</box>
|
||||||
|
<text fg={muted()}>
|
||||||
|
Downloaded from episode search — the show is not
|
||||||
|
subscribed.
|
||||||
|
</text>
|
||||||
|
<box height={1} />
|
||||||
|
<text fg={muted()}>
|
||||||
|
enter: play · D: delete download · h: back
|
||||||
|
</text>
|
||||||
</box>
|
</box>
|
||||||
)}
|
)}
|
||||||
</Show>
|
</Show>
|
||||||
) : (
|
) : (
|
||||||
// depth ≥1 preview: hovered episode
|
// depth ≥1 preview: hovered episode (or the Fetch More row)
|
||||||
|
<>
|
||||||
|
<Show when={focusedOnMore()}>
|
||||||
|
<box flexDirection="column" gap={1} padding={1}>
|
||||||
|
<text fg={theme.textPrimary ?? theme.text}>
|
||||||
|
<strong>[Fetch More]</strong>
|
||||||
|
</text>
|
||||||
|
<text fg={muted()}>
|
||||||
|
{feedStore.isLoadingMore()
|
||||||
|
? "Loading the next batch of episodes…"
|
||||||
|
: fetchMoreMode() === "auto"
|
||||||
|
? "Auto mode: the next batch loads automatically at the bottom of the list."
|
||||||
|
: "Load the next batch of older episodes for this show (Enter)."}
|
||||||
|
</text>
|
||||||
|
<box height={1} />
|
||||||
|
<text fg={muted()}>enter: load more · h back</text>
|
||||||
|
</box>
|
||||||
|
</Show>
|
||||||
|
<Show when={!focusedOnMore()}>
|
||||||
<Show
|
<Show
|
||||||
when={focusedEpisode()}
|
when={focusedEpisode()}
|
||||||
fallback={
|
fallback={
|
||||||
@@ -421,10 +740,26 @@ export function MyShowsPage() {
|
|||||||
{(ep().description?.length ?? 0) > 400 ? "…" : ""}
|
{(ep().description?.length ?? 0) > 400 ? "…" : ""}
|
||||||
</text>
|
</text>
|
||||||
<box height={1} />
|
<box height={1} />
|
||||||
<text fg={muted()}>enter: play · space: select · h: back</text>
|
<text fg={muted()}>
|
||||||
|
enter: play · d: download
|
||||||
|
{downloadStore.getDownloadStatus(ep().id) !==
|
||||||
|
DownloadStatus.NONE
|
||||||
|
? " · D: delete"
|
||||||
|
: ""}
|
||||||
|
{app.state().preferences.autoDownloadScope === "whitelist"
|
||||||
|
? (app.state().preferences.autoDownloadWhitelist ?? []).includes(
|
||||||
|
drilledShowId(),
|
||||||
|
)
|
||||||
|
? " · w: un-whitelist"
|
||||||
|
: " · w: whitelist"
|
||||||
|
: ""}{" "}
|
||||||
|
· space: select · h: back
|
||||||
|
</text>
|
||||||
</box>
|
</box>
|
||||||
)}
|
)}
|
||||||
</Show>
|
</Show>
|
||||||
|
</Show>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -14,29 +14,28 @@ type PlaybackControlsProps = {
|
|||||||
onSpeedChange: (value: number) => void;
|
onSpeedChange: (value: number) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const BACKEND_LABELS: Record<BackendName, string> = {
|
|
||||||
mpv: "mpv",
|
|
||||||
none: "none",
|
|
||||||
};
|
|
||||||
|
|
||||||
export function PlaybackControls(props: PlaybackControlsProps) {
|
export function PlaybackControls(props: PlaybackControlsProps) {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
return (
|
return (
|
||||||
<box
|
<box
|
||||||
flexDirection="row"
|
flexDirection="row"
|
||||||
|
flexWrap="wrap"
|
||||||
gap={1}
|
gap={1}
|
||||||
alignItems="center"
|
alignItems="center"
|
||||||
|
justifyContent="center"
|
||||||
border
|
border
|
||||||
padding={1}
|
padding={1}
|
||||||
borderColor={theme.border}
|
borderColor={theme.border}
|
||||||
>
|
>
|
||||||
|
{/* transport buttons — wrap as a unit, centered on their own line */}
|
||||||
|
<box flexDirection="row" gap={1} alignItems="center" flexShrink={0}>
|
||||||
<box
|
<box
|
||||||
border
|
border
|
||||||
padding={0}
|
padding={0}
|
||||||
onMouseDown={props.onPrev}
|
onMouseDown={props.onPrev}
|
||||||
borderColor={theme.border}
|
borderColor={theme.border}
|
||||||
>
|
>
|
||||||
<text fg={theme.primary}>[Prev]</text>
|
<text fg={theme.primary} wrapMode="none">[Prev]</text>
|
||||||
</box>
|
</box>
|
||||||
<box
|
<box
|
||||||
border
|
border
|
||||||
@@ -44,7 +43,7 @@ export function PlaybackControls(props: PlaybackControlsProps) {
|
|||||||
onMouseDown={props.onToggle}
|
onMouseDown={props.onToggle}
|
||||||
borderColor={theme.border}
|
borderColor={theme.border}
|
||||||
>
|
>
|
||||||
<text fg={theme.primary}>{props.isPlaying ? "[Pause]" : "[Play]"}</text>
|
<text fg={theme.primary} wrapMode="none">{props.isPlaying ? "[Pause]" : "[Play]"}</text>
|
||||||
</box>
|
</box>
|
||||||
<box
|
<box
|
||||||
border
|
border
|
||||||
@@ -52,24 +51,34 @@ export function PlaybackControls(props: PlaybackControlsProps) {
|
|||||||
onMouseDown={props.onNext}
|
onMouseDown={props.onNext}
|
||||||
borderColor={theme.border}
|
borderColor={theme.border}
|
||||||
>
|
>
|
||||||
<text fg={theme.primary}>[Next]</text>
|
<text fg={theme.primary} wrapMode="none">[Next]</text>
|
||||||
</box>
|
</box>
|
||||||
<box flexDirection="row" gap={1} marginLeft={2}>
|
</box>
|
||||||
|
{/* status group — always follows the buttons; wrap point is here */}
|
||||||
|
<box
|
||||||
|
flexDirection="row"
|
||||||
|
gap={1}
|
||||||
|
alignItems="center"
|
||||||
|
marginLeft={2}
|
||||||
|
flexShrink={0}
|
||||||
|
>
|
||||||
<text fg={theme.textMuted}>Vol</text>
|
<text fg={theme.textMuted}>Vol</text>
|
||||||
<text fg={theme.text}>{Math.round(props.volume * 100)}%</text>
|
<text fg={theme.text}>{Math.round(props.volume * 100)}%</text>
|
||||||
<text fg={theme.textMuted}>↑↓</text>
|
<text fg={theme.textMuted}>↑↓</text>
|
||||||
</box>
|
|
||||||
<box flexDirection="row" gap={1} marginLeft={2}>
|
<box flexDirection="row" gap={1} marginLeft={2}>
|
||||||
<text fg={theme.textMuted}>Speed</text>
|
<text fg={theme.textMuted}>Speed</text>
|
||||||
<text fg={theme.text}>{props.speed}x</text>
|
<text fg={theme.text}>{props.speed}x</text>
|
||||||
<text fg={theme.textMuted}>s</text>
|
<text fg={theme.textMuted}>S</text>
|
||||||
</box>
|
</box>
|
||||||
{props.backendName && props.backendName !== "none" && (
|
|
||||||
<box flexDirection="row" gap={1} marginLeft={2}>
|
|
||||||
<text fg={theme.textMuted}>via</text>
|
|
||||||
<text fg={theme.primary}>{BACKEND_LABELS[props.backendName]}</text>
|
|
||||||
</box>
|
</box>
|
||||||
)}
|
{/* audio warnings — wrap to their own (3rd) line when the row is tight */}
|
||||||
|
{(props.backendName === "none" || props.hasAudioUrl === false) && (
|
||||||
|
<box
|
||||||
|
flexDirection="row"
|
||||||
|
gap={1}
|
||||||
|
alignItems="center"
|
||||||
|
flexShrink={0}
|
||||||
|
>
|
||||||
{props.backendName === "none" && (
|
{props.backendName === "none" && (
|
||||||
<box marginLeft={2}>
|
<box marginLeft={2}>
|
||||||
<text fg={theme.warning}>No audio player found</text>
|
<text fg={theme.warning}>No audio player found</text>
|
||||||
@@ -81,5 +90,7 @@ export function PlaybackControls(props: PlaybackControlsProps) {
|
|||||||
</box>
|
</box>
|
||||||
)}
|
)}
|
||||||
</box>
|
</box>
|
||||||
|
)}
|
||||||
|
</box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,10 +10,12 @@
|
|||||||
* tab root.
|
* tab root.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Show } from "solid-js";
|
import { Show, onMount, onCleanup } from "solid-js";
|
||||||
import { PlaybackControls } from "./PlaybackControls";
|
import { PlaybackControls } from "./PlaybackControls";
|
||||||
|
import { ProgressBar } from "./ProgressBar";
|
||||||
import { RealtimeWaveform } from "./RealtimeWaveform";
|
import { RealtimeWaveform } from "./RealtimeWaveform";
|
||||||
import { useAudio } from "@/hooks/useAudio";
|
import { useAudio } from "@/hooks/useAudio";
|
||||||
|
import { useVisualizer } from "@/stores/visualizer";
|
||||||
import { useAppStore } from "@/stores/app";
|
import { useAppStore } from "@/stores/app";
|
||||||
import { useTheme } from "@/context/ThemeContext";
|
import { useTheme } from "@/context/ThemeContext";
|
||||||
import { useNavigation, DEPTH_CENTER_PANE } from "@/context/NavigationContext";
|
import { useNavigation, DEPTH_CENTER_PANE } from "@/context/NavigationContext";
|
||||||
@@ -26,7 +28,19 @@ export function PlayerPage() {
|
|||||||
const audio = useAudio();
|
const audio = useAudio();
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const nav = useNavigation();
|
const nav = useNavigation();
|
||||||
|
const viz = useVisualizer();
|
||||||
|
const app = useAppStore();
|
||||||
const muted = () => theme.muted || theme.text;
|
const muted = () => theme.muted || theme.text;
|
||||||
|
// Settings master switch: off hides the waveform entirely (the store
|
||||||
|
// also stops the decode+FFT pipeline, see stores/visualizer.ts).
|
||||||
|
const vizEnabled = () => app.state().settings.visualizer.enabled;
|
||||||
|
|
||||||
|
// The page is mounted exactly while the Player tab is in focus (Shell
|
||||||
|
// renders only the active tab), so mount ⇔ focused. Report it to the
|
||||||
|
// visualizer store: losing focus starts the unload grace timer instead
|
||||||
|
// of killing the pipeline with the page; regaining focus restarts it.
|
||||||
|
onMount(() => viz.setFocused(true));
|
||||||
|
onCleanup(() => viz.setFocused(false));
|
||||||
|
|
||||||
const isActive = () => nav.activePane() === DEPTH_CENTER_PANE;
|
const isActive = () => nav.activePane() === DEPTH_CENTER_PANE;
|
||||||
|
|
||||||
@@ -79,18 +93,11 @@ export function PlayerPage() {
|
|||||||
{ep().description?.slice(0, 500) ?? "No description available."}
|
{ep().description?.slice(0, 500) ?? "No description available."}
|
||||||
</text>
|
</text>
|
||||||
|
|
||||||
<RealtimeWaveform
|
<ProgressBar />
|
||||||
visualizerConfig={(() => {
|
|
||||||
const viz = useAppStore().state().settings.visualizer;
|
<Show when={vizEnabled()}>
|
||||||
// bars is width-derived in RealtimeWaveform; pass only the
|
<RealtimeWaveform />
|
||||||
// audio-processing params here.
|
</Show>
|
||||||
return {
|
|
||||||
noiseReduction: viz.noiseReduction,
|
|
||||||
lowCutOff: viz.lowCutOff,
|
|
||||||
highCutOff: viz.highCutOff,
|
|
||||||
};
|
|
||||||
})()}
|
|
||||||
/>
|
|
||||||
</box>
|
</box>
|
||||||
)}
|
)}
|
||||||
</Show>
|
</Show>
|
||||||
@@ -109,9 +116,13 @@ export function PlayerPage() {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<box height={1} />
|
<box height={1} />
|
||||||
<text fg={muted()}>
|
{/* content prop (not a text child): the babel-preset-solid JSX
|
||||||
{"P play/pause N next B prev ◀▶ seek h back"}
|
* transform HTML-escapes static string children (`<` → `<`),
|
||||||
</text>
|
* which opentui renders verbatim; content bypasses that. */}
|
||||||
|
<text
|
||||||
|
fg={muted()}
|
||||||
|
content={"P play/pause N next B prev < > seek h back"}
|
||||||
|
/>
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -122,6 +133,7 @@ export function PlayerPage() {
|
|||||||
currentLabel="Player"
|
currentLabel="Player"
|
||||||
panes={2}
|
panes={2}
|
||||||
focused={isActive}
|
focused={isActive}
|
||||||
|
currentBorder={["left"]}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
74
src/pages/Player/ProgressBar.tsx
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
/**
|
||||||
|
* ProgressBar — one-row, click-to-seek playback progress bar for the
|
||||||
|
* player pane. Played portion renders as full blocks (█) in the theme's
|
||||||
|
* primary color, the remainder as light shade blocks (░) in the muted
|
||||||
|
* color. The header time/percent text lives in PlayerPage — this is only
|
||||||
|
* the bar itself.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useTerminalDimensions } from "@opentui/solid";
|
||||||
|
import type { Renderable } from "@opentui/core";
|
||||||
|
import { useAudio } from "@/hooks/useAudio";
|
||||||
|
import { useTheme } from "@/context/ThemeContext";
|
||||||
|
|
||||||
|
// ── Component ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function ProgressBar() {
|
||||||
|
const audio = useAudio();
|
||||||
|
const { theme } = useTheme();
|
||||||
|
const dimensions = useTerminalDimensions();
|
||||||
|
|
||||||
|
// The bar's renderable, captured for its absolute left edge: MouseEvent.x
|
||||||
|
// is terminal-absolute (not bar-relative), so local x needs the offset
|
||||||
|
// of the bar inside the 2-pane row (parent pane ≈ 20% of the width).
|
||||||
|
let bar: Renderable | undefined;
|
||||||
|
|
||||||
|
// Full content width of the player pane: the player is a 2-pane row
|
||||||
|
// (parent 1/5 + current 4/5 of the terminal width). Subtract ~8 chars
|
||||||
|
// of border/padding chrome (same math as RealtimeWaveform's numBars).
|
||||||
|
const width = () => Math.max(8, Math.floor((dimensions().width * 4) / 5) - 8);
|
||||||
|
|
||||||
|
const clamp01 = (value: number) => Math.max(0, Math.min(1, value));
|
||||||
|
|
||||||
|
const playedChars = () => {
|
||||||
|
const duration = audio.duration();
|
||||||
|
if (duration <= 0) return 0;
|
||||||
|
return Math.round(clamp01(audio.position() / duration) * width());
|
||||||
|
};
|
||||||
|
|
||||||
|
const remainingColor = theme.muted || theme.text;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<box
|
||||||
|
border
|
||||||
|
borderColor={theme.border}
|
||||||
|
padding={0}
|
||||||
|
flexDirection="row"
|
||||||
|
gap={0}
|
||||||
|
// The bar's block-char texts are non-selectable below: a drag
|
||||||
|
// over the bar is a seek gesture, not a text selection — otherwise
|
||||||
|
// mouse-up would copy █/░ to the clipboard via the global
|
||||||
|
// selection handler.
|
||||||
|
ref={(el) => {
|
||||||
|
bar = el;
|
||||||
|
}}
|
||||||
|
onMouseDown={(e: { x: number }) => {
|
||||||
|
const duration = audio.duration();
|
||||||
|
if (duration <= 0 || !bar) return;
|
||||||
|
// localX = 0 is the box border; content starts at localX = 1.
|
||||||
|
const localX = e.x - bar.x;
|
||||||
|
const ratio = Math.max(0, Math.min(1, (localX - 1) / width()));
|
||||||
|
void audio.seek(ratio * duration);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{playedChars() > 0 && (
|
||||||
|
<text fg={theme.primary} selectable={false}>
|
||||||
|
{"\u2588".repeat(playedChars())}
|
||||||
|
</text>
|
||||||
|
)}
|
||||||
|
<text fg={remainingColor} selectable={false}>
|
||||||
|
{"\u2591".repeat(width() - playedChars())}
|
||||||
|
</text>
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,62 +1,30 @@
|
|||||||
/**
|
/**
|
||||||
* RealtimeWaveform — live audio frequency visualization using cavacore.
|
* RealtimeWaveform — renders the shared visualizer pipeline state.
|
||||||
*
|
*
|
||||||
* Spawns an independent ffmpeg
|
* The pipeline (ffmpeg decode + cavacore FFT) lives in the module-level
|
||||||
* process to decode the audio stream, feeds PCM samples through cavacore
|
* visualizer store (`@/stores/visualizer`), not in this component, so it
|
||||||
* for FFT analysis, and renders frequency bars as colored terminal
|
* survives PlayerPage unmounts: leaving the Player tab keeps the waveform
|
||||||
* characters at ~30fps.
|
* warm for VISUALIZER_UNLOAD_DELAY_MS, then the store tears it down.
|
||||||
|
*
|
||||||
|
* This component only subscribes to store state, reports the width-derived
|
||||||
|
* bar count (terminal resize re-inits the running pipeline), and renders:
|
||||||
|
* a braille spinner while the pipeline is loading its first frames, the
|
||||||
|
* frequency bars once frames arrive, and a dotted placeholder when idle.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { createSignal, createEffect, onCleanup, on, untrack } from "solid-js";
|
import { createEffect, on } from "solid-js";
|
||||||
import { useTerminalDimensions } from "@opentui/solid";
|
import { useTerminalDimensions } from "@opentui/solid";
|
||||||
import {
|
import { useVisualizer } from "@/stores/visualizer";
|
||||||
loadCavaCore,
|
|
||||||
type CavaCore,
|
|
||||||
type CavaCoreConfig,
|
|
||||||
} from "@/utils/cavacore";
|
|
||||||
import { AudioStreamReader } from "@/utils/audio-stream-reader";
|
|
||||||
import { useAudio } from "@/hooks/useAudio";
|
|
||||||
import { useTheme } from "@/context/ThemeContext";
|
import { useTheme } from "@/context/ThemeContext";
|
||||||
|
import { LoadingIndicator } from "@/components/LoadingIndicator";
|
||||||
|
import { BAR_LEVELS, barChars } from "@/utils/bar-mapping";
|
||||||
import { PANE_RATIO } from "@/utils/navigation";
|
import { PANE_RATIO } from "@/utils/navigation";
|
||||||
|
|
||||||
// ── Types ────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export type RealtimeWaveformProps = {
|
|
||||||
visualizerConfig?: Partial<CavaCoreConfig>;
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Unicode lower block elements: space (silence) through full block (max) */
|
|
||||||
const BARS = [
|
|
||||||
" ",
|
|
||||||
"\u2581",
|
|
||||||
"\u2582",
|
|
||||||
"\u2583",
|
|
||||||
"\u2584",
|
|
||||||
"\u2585",
|
|
||||||
"\u2586",
|
|
||||||
"\u2587",
|
|
||||||
"\u2588",
|
|
||||||
];
|
|
||||||
|
|
||||||
/** Target frame interval in ms (~30 fps) */
|
|
||||||
const FRAME_INTERVAL = 33;
|
|
||||||
|
|
||||||
/** Number of PCM samples to read per frame (512 is a good FFT window) */
|
|
||||||
const SAMPLES_PER_FRAME = 512;
|
|
||||||
|
|
||||||
// ── Component ────────────────────────────────────────────────────────
|
// ── Component ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function RealtimeWaveform(props: RealtimeWaveformProps) {
|
export function RealtimeWaveform() {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const audio = useAudio();
|
const viz = useVisualizer();
|
||||||
|
|
||||||
// Frequency bar values (0.0–1.0 per bar)
|
|
||||||
const [barData, setBarData] = createSignal<number[]>([]);
|
|
||||||
|
|
||||||
let cava: CavaCore | null = null;
|
|
||||||
let reader: AudioStreamReader | null = null;
|
|
||||||
let frameTimer: ReturnType<typeof setInterval> | null = null;
|
|
||||||
let sampleBuffer: Float64Array | null = null;
|
|
||||||
|
|
||||||
// Bar count scales with terminal width so the waveform fills its pane.
|
// Bar count scales with terminal width so the waveform fills its pane.
|
||||||
// The player is a 2-pane row: current column = (current+preview) of
|
// The player is a 2-pane row: current column = (current+preview) of
|
||||||
@@ -75,197 +43,49 @@ export function RealtimeWaveform(props: RealtimeWaveformProps) {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── Lifecycle: init cavacore once ──────────────────────────────────
|
// Keep the store's bar count in sync with the terminal width; the store
|
||||||
|
// re-inits the running pipeline when it changes (terminal resize).
|
||||||
const initCava = () => {
|
createEffect(on(numBars, (n) => viz.setBarCount(n)));
|
||||||
if (cava) return true;
|
|
||||||
|
|
||||||
cava = loadCavaCore();
|
|
||||||
if (!cava) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
|
|
||||||
// ── Start/stop the visualization pipeline ──────────────────────────
|
|
||||||
|
|
||||||
const startVisualization = (url: string, position: number, speed: number) => {
|
|
||||||
stopVisualization();
|
|
||||||
|
|
||||||
if (!url || !initCava() || !cava) return;
|
|
||||||
|
|
||||||
// Initialize cavacore with current resolution + any overrides.
|
|
||||||
// bars is width-derived (see numBars); visualizerConfig supplies the
|
|
||||||
// audio-processing params (noise reduction, cutoffs, etc.).
|
|
||||||
const config: CavaCoreConfig = {
|
|
||||||
bars: numBars(),
|
|
||||||
sampleRate: 44100,
|
|
||||||
channels: 1,
|
|
||||||
...props.visualizerConfig,
|
|
||||||
};
|
|
||||||
cava.init(config);
|
|
||||||
|
|
||||||
// Pre-allocate sample read buffer
|
|
||||||
sampleBuffer = new Float64Array(SAMPLES_PER_FRAME);
|
|
||||||
|
|
||||||
// Start ffmpeg decode stream (reuse reader if same URL, else create new)
|
|
||||||
if (!reader || reader.url !== url) {
|
|
||||||
if (reader) reader.stop();
|
|
||||||
reader = new AudioStreamReader({ url });
|
|
||||||
}
|
|
||||||
reader.start(position, speed);
|
|
||||||
|
|
||||||
frameTimer = setInterval(renderFrame, FRAME_INTERVAL);
|
|
||||||
};
|
|
||||||
|
|
||||||
const stopVisualization = () => {
|
|
||||||
if (frameTimer) {
|
|
||||||
clearInterval(frameTimer);
|
|
||||||
frameTimer = null;
|
|
||||||
}
|
|
||||||
if (reader) {
|
|
||||||
reader.stop();
|
|
||||||
// Don't null reader — we reuse it across start/stop cycles
|
|
||||||
}
|
|
||||||
if (cava?.isReady) {
|
|
||||||
cava.destroy();
|
|
||||||
}
|
|
||||||
sampleBuffer = null;
|
|
||||||
};
|
|
||||||
|
|
||||||
// ── Render loop (called at ~30fps) ─────────────────────────────────
|
|
||||||
|
|
||||||
const renderFrame = () => {
|
|
||||||
if (!cava?.isReady || !reader?.running || !sampleBuffer) return;
|
|
||||||
|
|
||||||
const count = reader.read(sampleBuffer);
|
|
||||||
if (count === 0) return;
|
|
||||||
|
|
||||||
const input =
|
|
||||||
count < sampleBuffer.length
|
|
||||||
? sampleBuffer.subarray(0, count)
|
|
||||||
: sampleBuffer;
|
|
||||||
const output = cava.execute(input);
|
|
||||||
|
|
||||||
// Copy bar values to a new array for the signal
|
|
||||||
setBarData(Array.from(output as Float64Array));
|
|
||||||
};
|
|
||||||
|
|
||||||
createEffect(
|
|
||||||
on(
|
|
||||||
[
|
|
||||||
audio.isPlaying,
|
|
||||||
() => audio.currentEpisode()?.audioUrl ?? "",
|
|
||||||
audio.speed,
|
|
||||||
numBars,
|
|
||||||
],
|
|
||||||
([playing, url, speed]) => {
|
|
||||||
if (playing && url) {
|
|
||||||
const pos = untrack(audio.position);
|
|
||||||
startVisualization(url, pos, speed);
|
|
||||||
} else {
|
|
||||||
stopVisualization();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
// ── Seek detection: lightweight effect for position jumps ──────────
|
|
||||||
//
|
|
||||||
// Watches position and restarts the reader (not the whole pipeline)
|
|
||||||
// only on significant jumps (>2s), which indicate a user seek.
|
|
||||||
// This is intentionally a separate effect — it should NOT trigger a
|
|
||||||
// full pipeline restart, just restart the ffmpeg stream at the new pos.
|
|
||||||
|
|
||||||
let lastSyncPosition = 0;
|
|
||||||
createEffect(
|
|
||||||
on(audio.position, (pos) => {
|
|
||||||
if (!audio.isPlaying || !reader?.running) {
|
|
||||||
lastSyncPosition = pos;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const delta = Math.abs(pos - lastSyncPosition);
|
|
||||||
lastSyncPosition = pos;
|
|
||||||
|
|
||||||
if (delta > 2) {
|
|
||||||
reader.restart(pos, audio.speed() ?? 1);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
onCleanup(() => {
|
|
||||||
stopVisualization();
|
|
||||||
if (reader) {
|
|
||||||
reader.stop();
|
|
||||||
reader = null;
|
|
||||||
}
|
|
||||||
// Don't null cava itself — it can be reused. But do destroy its plan.
|
|
||||||
if (cava?.isReady) {
|
|
||||||
cava.destroy();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// ── Rendering ──────────────────────────────────────────────────────
|
// ── Rendering ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
const playedRatio = () =>
|
|
||||||
audio.duration() <= 0
|
|
||||||
? 0
|
|
||||||
: Math.min(1, audio.position() / audio.duration());
|
|
||||||
|
|
||||||
const renderLine = () => {
|
const renderLine = () => {
|
||||||
const bars = barData();
|
const bars = viz.barData();
|
||||||
const count = numBars();
|
const count = numBars();
|
||||||
|
|
||||||
|
// Loading state: the braille spinner shows while the pipeline warms
|
||||||
|
// up — but only when there are no bars to render yet (first play /
|
||||||
|
// after an unload). On resume/seek the last bars stay on screen
|
||||||
|
// until fresh frames arrive, so the waveform never blanks out for
|
||||||
|
// the (multi-second, network-bound) cold start.
|
||||||
|
if (bars.length === 0 && viz.isLoading()) {
|
||||||
|
return <LoadingIndicator />;
|
||||||
|
}
|
||||||
|
|
||||||
if (bars.length === 0) {
|
if (bars.length === 0) {
|
||||||
const placeholder = ".".repeat(count);
|
const placeholder = ".".repeat(count);
|
||||||
return (
|
return (
|
||||||
<box flexDirection="row" gap={0}>
|
<box flexDirection="column" gap={0}>
|
||||||
<text fg="#3b4252">{placeholder}</text>
|
<text fg={theme.primary}>{placeholder}</text>
|
||||||
|
<text fg={theme.primary}>{placeholder}</text>
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const played = Math.floor(count * playedRatio());
|
const pairs = bars.map((v) => barChars(Math.floor(v * BAR_LEVELS)));
|
||||||
const playedColor = audio.isPlaying() ? "#6fa8ff" : "#7d8590";
|
const top = pairs.map((pair) => pair.top).join("");
|
||||||
const futureColor = "#3b4252";
|
const bottom = pairs.map((pair) => pair.bottom).join("");
|
||||||
|
|
||||||
const playedChars = bars
|
|
||||||
.slice(0, played)
|
|
||||||
.map((v) => BARS[Math.min(BARS.length - 1, Math.floor(v * BARS.length))])
|
|
||||||
.join("");
|
|
||||||
|
|
||||||
const futureChars = bars
|
|
||||||
.slice(played)
|
|
||||||
.map((v) => BARS[Math.min(BARS.length - 1, Math.floor(v * BARS.length))])
|
|
||||||
.join("");
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<box flexDirection="row" gap={0}>
|
<box flexDirection="column" gap={0}>
|
||||||
<text fg={playedColor}>{playedChars || " "}</text>
|
<text fg={theme.primary}>{top}</text>
|
||||||
<text fg={futureColor}>{futureChars || " "}</text>
|
<text fg={theme.primary}>{bottom}</text>
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleClick = (event: { x: number }) => {
|
|
||||||
const count = numBars();
|
|
||||||
const ratio = event.x / count;
|
|
||||||
const next = Math.max(
|
|
||||||
0,
|
|
||||||
Math.min(audio.duration(), Math.round(audio.duration() * ratio)),
|
|
||||||
);
|
|
||||||
audio.seek(next);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<box
|
<box border borderColor={theme.border} padding={1}>
|
||||||
border
|
|
||||||
borderColor={theme.border}
|
|
||||||
padding={1}
|
|
||||||
onMouseDown={handleClick}
|
|
||||||
>
|
|
||||||
{renderLine()}
|
{renderLine()}
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -8,6 +8,10 @@
|
|||||||
* query (muted, read-only); preview shows the detail of
|
* query (muted, read-only); preview shows the detail of
|
||||||
* the focused result.
|
* the focused result.
|
||||||
*
|
*
|
||||||
|
* Search scope: `tab` (search-scope-toggle) flips between shows and episodes
|
||||||
|
* (clickable pills on the query depth too); toggling while viewing results
|
||||||
|
* re-runs the current query in the new scope.
|
||||||
|
*
|
||||||
* Typed input owns its keys while `nav.inputFocused()` is true (the Shell
|
* Typed input owns its keys while `nav.inputFocused()` is true (the Shell
|
||||||
* router yields). Escape defocuses the input (handled in Shell) so j/k/h
|
* router yields). Escape defocuses the input (handled in Shell) so j/k/h
|
||||||
* navigation resumes; `s` (the `search` action) refocuses it. Enter on the
|
* navigation resumes; `s` (the `search` action) refocuses it. Enter on the
|
||||||
@@ -26,6 +30,11 @@ import {
|
|||||||
} from "solid-js";
|
} from "solid-js";
|
||||||
import { useSearchStore } from "@/stores/search";
|
import { useSearchStore } from "@/stores/search";
|
||||||
import { useFeedStore } from "@/stores/feed";
|
import { useFeedStore } from "@/stores/feed";
|
||||||
|
import { useDownloadStore } from "@/stores/download";
|
||||||
|
import { useAudio } from "@/hooks/useAudio";
|
||||||
|
import { useAudioNavStore, AudioSource } from "@/stores/audio-nav";
|
||||||
|
import { DownloadStatus } from "@/types/episode";
|
||||||
|
import { useToast } from "@/ui/toast";
|
||||||
import { format } from "date-fns";
|
import { format } from "date-fns";
|
||||||
import { useTheme } from "@/context/ThemeContext";
|
import { useTheme } from "@/context/ThemeContext";
|
||||||
import {
|
import {
|
||||||
@@ -37,21 +46,28 @@ import {
|
|||||||
} from "@/context/NavigationContext";
|
} from "@/context/NavigationContext";
|
||||||
import { on, off } from "@/utils/event-bus";
|
import { on, off } from "@/utils/event-bus";
|
||||||
import type { KeybindActionName } from "@/context/KeybindContext";
|
import type { KeybindActionName } from "@/context/KeybindContext";
|
||||||
import type { SearchResult } from "@/types/source";
|
import type { SearchResult, SearchScope } from "@/types/source";
|
||||||
import { PaneRow } from "@/components/PaneRow";
|
import { PaneRow } from "@/components/PaneRow";
|
||||||
import { TabListPane } from "@/components/TabPanel";
|
import { TabListPane } from "@/components/TabPanel";
|
||||||
import { LoadingIndicator } from "@/components/LoadingIndicator";
|
import { LoadingIndicator } from "@/components/LoadingIndicator";
|
||||||
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
||||||
|
import { useSelectionMarker } from "@/hooks/useSelectionMarker";
|
||||||
|
import { useInputFocusNav } from "@/hooks/useInputFocusNav";
|
||||||
|
|
||||||
export const SearchPaneCount = 1;
|
export const SearchPaneCount = 1;
|
||||||
|
|
||||||
function SearchPage() {
|
function SearchPage() {
|
||||||
const searchStore = useSearchStore();
|
const searchStore = useSearchStore();
|
||||||
const feedStore = useFeedStore();
|
const feedStore = useFeedStore();
|
||||||
|
const downloadStore = useDownloadStore();
|
||||||
|
const audio = useAudio();
|
||||||
|
const audioNav = useAudioNavStore();
|
||||||
|
const toast = useToast();
|
||||||
const [inputValue, setInputValue] = createSignal("");
|
const [inputValue, setInputValue] = createSignal("");
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const muted = () => theme.muted || theme.text;
|
const muted = () => theme.muted || theme.text;
|
||||||
const nav = useNavigation();
|
const nav = useNavigation();
|
||||||
|
const marker = useSelectionMarker();
|
||||||
|
|
||||||
const stack = nav.depthStack;
|
const stack = nav.depthStack;
|
||||||
const depth = nav.currentDepth;
|
const depth = nav.currentDepth;
|
||||||
@@ -65,21 +81,32 @@ function SearchPage() {
|
|||||||
// router yields keys to the <input> while this is true; Escape (in Shell)
|
// router yields keys to the <input> while this is true; Escape (in Shell)
|
||||||
// sets it false so navigation resumes; `s` (search action) sets it true.
|
// sets it false so navigation resumes; `s` (search action) sets it true.
|
||||||
//
|
//
|
||||||
// Typing is the default only on the query depth (0); the results depth
|
// The input's REAL focus is the source of truth for the flag:
|
||||||
// (1) is always list-navigation. Drive `inputFocused` straight off
|
// useInputFocusNav (the same hook the Settings forms use) flips
|
||||||
// `depth()` rather than seeding it `true` on mount and patching on change:
|
// `inputFocused` from the input's FOCUSED/BLURRED events, keeping the flag
|
||||||
// the depth stack persists across tab switches, so re-mounting this page
|
// and the renderable in lockstep. That matters when the user clicks OFF the
|
||||||
// at depth 1 (e.g. after searching, leaving, and returning to the tab)
|
// input: opentui's mouse dispatch auto-focuses the clicked target's nearest
|
||||||
// must NOT leave `inputFocused` stuck on — otherwise the Shell swallows
|
// focusable ancestor (a pane scrollbox), blurring the input. The BLURRED
|
||||||
// j/k (yielding to a non-existent input) and only the scrollbox's native
|
// event drops the flag, so the Shell router immediately resumes j/k/h
|
||||||
// scroll responds.
|
// instead of swallowing keys with no input to receive them — no more
|
||||||
|
// stuck "typing" state where Esc/j/k/s all do nothing.
|
||||||
//
|
//
|
||||||
// The effect only re-runs on a depth transition, so Escape (defocus) and
|
// The depth stack still SEEDS the flag on transitions, since the query
|
||||||
// `s` (refocus) at the same depth are not clobbered.
|
// depth defaults to typing: re-entering depth 0 (h back from results, or a
|
||||||
|
// fresh mount) focuses the input; mounting at depth 1 (returning to the
|
||||||
|
// tab after a search) stays list-navigation — a stuck-on flag there would
|
||||||
|
// have the Shell yield j/k to a non-existent input. The depth STACK signal
|
||||||
|
// is also written by focus moves (setDepthFocus), so gate the seed on the
|
||||||
|
// depth VALUE via a memo: the effect must re-run only on an actual depth
|
||||||
|
// transition. Without the memo every j/k at the query depth re-focuses the
|
||||||
|
// input (undoing Escape), which keeps the recents list unreachable by
|
||||||
|
// keyboard.
|
||||||
onMount(() => nav.setInputFocused(depth() === 0));
|
onMount(() => nav.setInputFocused(depth() === 0));
|
||||||
onCleanup(() => nav.setInputFocused(false));
|
onCleanup(() => nav.setInputFocused(false));
|
||||||
|
const focusNavRef = useInputFocusNav();
|
||||||
|
const isQueryDepth = createMemo(() => depth() === 0);
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
nav.setInputFocused(depth() === 0);
|
nav.setInputFocused(isQueryDepth());
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── results (depth 1) ─────────────────────────────────────────────────────
|
// ── results (depth 1) ─────────────────────────────────────────────────────
|
||||||
@@ -105,12 +132,44 @@ function SearchPage() {
|
|||||||
// Register a visual-mode resolver for the results list (depth 1).
|
// Register a visual-mode resolver for the results list (depth 1).
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
const key = `${nav.activeTab()}:${DEPTH_CENTER_PANE}`;
|
const key = `${nav.activeTab()}:${DEPTH_CENTER_PANE}`;
|
||||||
nav.registerResolver(key, (i) => results()[i]?.podcast.id);
|
nav.registerResolver(key, (i) => {
|
||||||
|
const r = results()[i];
|
||||||
|
return r?.kind === "episode" ? r.episode.id : r?.podcast.id;
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── helpers ─────────────────────────────────────────────────────────────────
|
// ── helpers ─────────────────────────────────────────────────────────────────
|
||||||
const formatDate = (d: Date) => format(d, "MMM d, yyyy");
|
const formatDate = (d: Date) => format(d, "MMM d, yyyy");
|
||||||
|
|
||||||
|
const downloadLabel = (id: string) => {
|
||||||
|
switch (downloadStore.getDownloadStatus(id)) {
|
||||||
|
case DownloadStatus.QUEUED:
|
||||||
|
return "[Q]";
|
||||||
|
case DownloadStatus.DOWNLOADING:
|
||||||
|
return `[${downloadStore.getDownloadProgress(id)}%]`;
|
||||||
|
case DownloadStatus.COMPLETED:
|
||||||
|
return "[DL]";
|
||||||
|
case DownloadStatus.FAILED:
|
||||||
|
return "[ERR]";
|
||||||
|
default:
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const downloadColor = (id: string) => {
|
||||||
|
switch (downloadStore.getDownloadStatus(id)) {
|
||||||
|
case DownloadStatus.QUEUED:
|
||||||
|
return theme.warning;
|
||||||
|
case DownloadStatus.DOWNLOADING:
|
||||||
|
return theme.primary;
|
||||||
|
case DownloadStatus.COMPLETED:
|
||||||
|
return theme.success;
|
||||||
|
case DownloadStatus.FAILED:
|
||||||
|
return theme.error;
|
||||||
|
default:
|
||||||
|
return muted();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const runSearch = (query: string) => {
|
const runSearch = (query: string) => {
|
||||||
const q = query.trim();
|
const q = query.trim();
|
||||||
if (!q) return;
|
if (!q) return;
|
||||||
@@ -130,10 +189,89 @@ function SearchPage() {
|
|||||||
runSearch(query);
|
runSearch(query);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSubscribe = (result: SearchResult) => {
|
/** Set show/episode scope; when viewing results, re-run the current query
|
||||||
// Actually add the feed to the feed store, then mark the result subscribed
|
* so the list switches immediately (the toggle is otherwise invisible on
|
||||||
feedStore.addFeed(result.podcast, result.sourceId).catch(() => {});
|
* a list of results). */
|
||||||
searchStore.markSubscribed(result.podcast.id);
|
const applyScope = (next: SearchScope) => {
|
||||||
|
searchStore.setScope(next);
|
||||||
|
if (depth() >= 1) {
|
||||||
|
const q = submittedQuery() || inputValue().trim();
|
||||||
|
if (q) searchStore.search(q).catch(() => {});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const toggleScope = () =>
|
||||||
|
applyScope(searchStore.scope() === "podcast" ? "episode" : "podcast");
|
||||||
|
|
||||||
|
const handleSubscribe = async (result: SearchResult) => {
|
||||||
|
// Actually add the feed to the feed store, then mark the result
|
||||||
|
// subscribed. addFeed returns null when a feedless directory stub
|
||||||
|
// (delisted show) can't be resolved — tell the user why.
|
||||||
|
const feed = await feedStore
|
||||||
|
.addFeed(result.podcast, result.sourceId)
|
||||||
|
.catch(() => null);
|
||||||
|
if (!feed && !result.podcast.feedUrl) {
|
||||||
|
toast.show({
|
||||||
|
title: "Can't subscribe",
|
||||||
|
message:
|
||||||
|
"No RSS feed is listed for this show and the feed couldn't be resolved. Try adding it by feed URL.",
|
||||||
|
variant: "error",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (feed) searchStore.markSubscribed(result.podcast.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The subscribed feed backing a search result, if any (matched by
|
||||||
|
* directory id or feed URL). */
|
||||||
|
const feedForResult = (r: SearchResult) =>
|
||||||
|
feedStore.feeds().find(
|
||||||
|
(f) =>
|
||||||
|
f.podcast.id === r.podcast.id ||
|
||||||
|
(!!r.podcast.feedUrl && f.podcast.feedUrl === r.podcast.feedUrl),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Download the focused episode: under its subscribed feed when the show
|
||||||
|
* is subscribed, otherwise as an "unsubscribed show" download (listed
|
||||||
|
* under Unsubscribed Show Downloads in My Shows / the download manager). */
|
||||||
|
const downloadFocusedEpisode = () => {
|
||||||
|
if (depth() !== 1) return;
|
||||||
|
const r = focusedResult();
|
||||||
|
if (!r || r.kind !== "episode") return;
|
||||||
|
const feed = feedForResult(r);
|
||||||
|
if (feed) downloadStore.startDownload(r.episode, feed.id);
|
||||||
|
else downloadStore.startUnsubscribedDownload(r.episode, r.podcast);
|
||||||
|
};
|
||||||
|
|
||||||
|
const playFocusedEpisode = () => {
|
||||||
|
if (depth() !== 1) return;
|
||||||
|
const r = focusedResult();
|
||||||
|
if (!r || r.kind !== "episode") return;
|
||||||
|
audio.play(r.episode).catch(() => {});
|
||||||
|
audioNav.setSource(AudioSource.SEARCH, r.podcast.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
const unsubscribeFocused = () => {
|
||||||
|
if (depth() !== 1) return;
|
||||||
|
const r = focusedResult();
|
||||||
|
if (!r || !r.podcast.isSubscribed) return;
|
||||||
|
const feed = feedForResult(r);
|
||||||
|
if (feed) {
|
||||||
|
feedStore.removeFeed(feed.id);
|
||||||
|
downloadStore
|
||||||
|
.removeDownloadsForFeed(feed.id, feed.podcast.feedUrl || undefined)
|
||||||
|
.catch(() => {});
|
||||||
|
searchStore.markUnsubscribed(r.podcast.id, r.podcast.feedUrl);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Subscribe the focused result's show in place (episode or podcast
|
||||||
|
* result). `enter` plays episodes regardless of subscription, so an
|
||||||
|
* unsubscribed show's episode needs this explicit path. */
|
||||||
|
const subscribeFocused = () => {
|
||||||
|
if (depth() !== 1) return;
|
||||||
|
const r = focusedResult();
|
||||||
|
if (!r || r.podcast.isSubscribed) return;
|
||||||
|
handleSubscribe(r);
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── nav.action handler ──────────────────────────────────────────────────────
|
// ── nav.action handler ──────────────────────────────────────────────────────
|
||||||
@@ -150,13 +288,29 @@ function SearchPage() {
|
|||||||
"toggle-select": () => {
|
"toggle-select": () => {
|
||||||
if (depth() === 1) {
|
if (depth() === 1) {
|
||||||
const r = focusedResult();
|
const r = focusedResult();
|
||||||
if (r) nav.toggleSelected(r.podcast.id);
|
if (r)
|
||||||
|
nav.toggleSelected(
|
||||||
|
r.kind === "episode" ? r.episode.id : r.podcast.id,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
download: () => downloadFocusedEpisode(),
|
||||||
|
"delete-download": () => {
|
||||||
|
if (depth() !== 1) return;
|
||||||
|
const r = focusedResult();
|
||||||
|
if (!r || r.kind !== "episode") return;
|
||||||
|
const id = r.episode.id;
|
||||||
|
if (downloadStore.getDownloadStatus(id) === DownloadStatus.NONE) return;
|
||||||
|
downloadStore.cancelDownload(id);
|
||||||
|
downloadStore.removeDownload(id).catch(() => {});
|
||||||
|
},
|
||||||
|
unsubscribe: () => unsubscribeFocused(),
|
||||||
|
subscribe: () => subscribeFocused(),
|
||||||
search: () => {
|
search: () => {
|
||||||
// `s` refocuses the query input (typing mode) when on the query depth.
|
// `s` refocuses the query input (typing mode) when on the query depth.
|
||||||
if (depth() === 0) nav.setInputFocused(true);
|
if (depth() === 0) nav.setInputFocused(true);
|
||||||
},
|
},
|
||||||
|
"search-scope-toggle": () => toggleScope(),
|
||||||
refresh: () => {
|
refresh: () => {
|
||||||
const q = submittedQuery() || inputValue().trim();
|
const q = submittedQuery() || inputValue().trim();
|
||||||
if (q) searchStore.search(q).catch(() => {});
|
if (q) searchStore.search(q).catch(() => {});
|
||||||
@@ -177,7 +331,15 @@ function SearchPage() {
|
|||||||
}
|
}
|
||||||
if (depth() === 1) {
|
if (depth() === 1) {
|
||||||
const r = focusedResult();
|
const r = focusedResult();
|
||||||
if (r) handleSubscribe(r);
|
if (!r) return;
|
||||||
|
if (r.kind === "episode") {
|
||||||
|
// Any episode result streams directly — subscribed or not
|
||||||
|
// (matches Feed/My Shows). `a` subscribes an unsubscribed
|
||||||
|
// show's episode in place.
|
||||||
|
playFocusedEpisode();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
handleSubscribe(r);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,15 +375,28 @@ function SearchPage() {
|
|||||||
: theme.text;
|
: theme.text;
|
||||||
|
|
||||||
// ── parent pane: previous-depth content (tab list at depth 0) ──────────────
|
// ── parent pane: previous-depth content (tab list at depth 0) ──────────────
|
||||||
|
// Sibling <Show> blocks per depth (the known-good opentui disposal
|
||||||
|
// pattern, mirrors Settings): a STABLE fragment root whose inner <Show>
|
||||||
|
// children toggle on depth change, so the old subtree is disposed instead
|
||||||
|
// of left orphaned next to the new one (single <Show with fallback> and
|
||||||
|
// ternary root swaps both leak the previous root).
|
||||||
const parentContent = () => (
|
const parentContent = () => (
|
||||||
<Show when={depth() >= 1} fallback={<TabListPane muted />}>
|
<>
|
||||||
|
<Show when={depth() === 0}>
|
||||||
|
<TabListPane muted />
|
||||||
|
</Show>
|
||||||
|
<Show when={depth() >= 1}>
|
||||||
<box flexDirection="column" gap={1} padding={1}>
|
<box flexDirection="column" gap={1} padding={1}>
|
||||||
<text fg={theme.textSecondary}>Query</text>
|
<text fg={theme.textSecondary}>Query</text>
|
||||||
<text fg={muted()}>{submittedQuery() || "(empty)"}</text>
|
<text fg={muted()}>{submittedQuery() || "(empty)"}</text>
|
||||||
<box height={1} />
|
<box height={1} />
|
||||||
|
<text fg={theme.textSecondary}>
|
||||||
|
Scope · {searchStore.scope() === "episode" ? "episodes" : "shows"}
|
||||||
|
</text>
|
||||||
<text fg={muted()}>h: back to query</text>
|
<text fg={muted()}>h: back to query</text>
|
||||||
</box>
|
</box>
|
||||||
</Show>
|
</Show>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
|
|
||||||
// ── current pane ────────────────────────────────────────────────────────────
|
// ── current pane ────────────────────────────────────────────────────────────
|
||||||
@@ -233,14 +408,78 @@ function SearchPage() {
|
|||||||
<box flexDirection="row" gap={1} alignItems="center">
|
<box flexDirection="row" gap={1} alignItems="center">
|
||||||
<text fg={muted()}>Query:</text>
|
<text fg={muted()}>Query:</text>
|
||||||
<input
|
<input
|
||||||
|
ref={focusNavRef}
|
||||||
value={inputValue()}
|
value={inputValue()}
|
||||||
onInput={setInputValue}
|
onInput={setInputValue}
|
||||||
onSubmit={() => handleSubmit()}
|
onSubmit={() => handleSubmit()}
|
||||||
placeholder="Enter podcast name..."
|
onMouseDown={(evt) => {
|
||||||
|
// Clicking the input must focus it (typing mode).
|
||||||
|
// preventDefault stops opentui's click auto-focus from
|
||||||
|
// grabbing the pane scrollbox instead; setting the flag
|
||||||
|
// drives the `focused` prop → renderable focus → the
|
||||||
|
// useInputFocusNav FOCUSED handler.
|
||||||
|
evt.preventDefault();
|
||||||
|
nav.setInputFocused(true);
|
||||||
|
}}
|
||||||
|
onKeyDown={(evt) => {
|
||||||
|
// While the input owns keys the Shell router never sees
|
||||||
|
// Tab, so the scope toggle must be handled here (the
|
||||||
|
// pills and the tab keybind cover the defocused cases).
|
||||||
|
if (evt.name === "tab") {
|
||||||
|
evt.preventDefault();
|
||||||
|
toggleScope();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
placeholder={
|
||||||
|
searchStore.scope() === "episode"
|
||||||
|
? "Enter episode, guest, topic..."
|
||||||
|
: "Enter podcast name..."
|
||||||
|
}
|
||||||
focused={inputActive()}
|
focused={inputActive()}
|
||||||
width={28}
|
width={28}
|
||||||
|
textColor={theme.text}
|
||||||
|
focusedTextColor={theme.accent}
|
||||||
|
cursorColor={theme.accent}
|
||||||
/>
|
/>
|
||||||
</box>
|
</box>
|
||||||
|
<box flexDirection="row" gap={1} alignItems="center">
|
||||||
|
<text fg={theme.textSecondary}>Scope:</text>
|
||||||
|
<box
|
||||||
|
backgroundColor={
|
||||||
|
searchStore.scope() === "podcast" ? theme.primary : undefined
|
||||||
|
}
|
||||||
|
onMouseDown={() => applyScope("podcast")}
|
||||||
|
>
|
||||||
|
<text
|
||||||
|
fg={
|
||||||
|
searchStore.scope() === "podcast"
|
||||||
|
? theme.surface
|
||||||
|
: muted()
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{" "}
|
||||||
|
Shows{" "}
|
||||||
|
</text>
|
||||||
|
</box>
|
||||||
|
<box
|
||||||
|
backgroundColor={
|
||||||
|
searchStore.scope() === "episode" ? theme.primary : undefined
|
||||||
|
}
|
||||||
|
onMouseDown={() => applyScope("episode")}
|
||||||
|
>
|
||||||
|
<text
|
||||||
|
fg={
|
||||||
|
searchStore.scope() === "episode"
|
||||||
|
? theme.surface
|
||||||
|
: muted()
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{" "}
|
||||||
|
Episodes{" "}
|
||||||
|
</text>
|
||||||
|
</box>
|
||||||
|
<text fg={muted()}>tab to toggle</text>
|
||||||
|
</box>
|
||||||
<Show when={searchStore.isSearching()}>
|
<Show when={searchStore.isSearching()}>
|
||||||
<LoadingIndicator label="Searching…" />
|
<LoadingIndicator label="Searching…" />
|
||||||
</Show>
|
</Show>
|
||||||
@@ -263,23 +502,47 @@ function SearchPage() {
|
|||||||
{(query, index) => {
|
{(query, index) => {
|
||||||
const lf = () => focus(0);
|
const lf = () => focus(0);
|
||||||
const ref = useScrollIntoView(() => index() === lf());
|
const ref = useScrollIntoView(() => index() === lf());
|
||||||
|
// While the input is focused (typing), the list is not
|
||||||
|
// in focus: no bg, no accent fg, no `❯` on any entry.
|
||||||
|
const typing = () => inputActive();
|
||||||
return (
|
return (
|
||||||
<box
|
<box
|
||||||
ref={ref}
|
ref={ref}
|
||||||
flexDirection="row"
|
flexDirection="row"
|
||||||
gap={1}
|
gap={1}
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
paddingRight={1}
|
||||||
backgroundColor={focusBg(index(), lf(), isActive())}
|
backgroundColor={
|
||||||
|
typing()
|
||||||
|
? undefined
|
||||||
|
: focusBg(index(), lf(), isActive())
|
||||||
|
}
|
||||||
onMouseDown={() => {
|
onMouseDown={() => {
|
||||||
nav.setActivePane(DEPTH_CENTER_PANE);
|
nav.setActivePane(DEPTH_CENTER_PANE);
|
||||||
nav.setDepthFocus(index(), 0);
|
nav.setDepthFocus(index(), 0);
|
||||||
|
// A recent is an action, not an item: clicking
|
||||||
|
// it re-runs that search (focus-only would be
|
||||||
|
// invisible — the input still owns the keys).
|
||||||
|
selectRecent(query);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<text fg={focusFg(index(), lf(), isActive())}>
|
<text
|
||||||
{index() === lf() ? "❯" : " "}
|
fg={
|
||||||
|
typing()
|
||||||
|
? theme.text
|
||||||
|
: focusFg(index(), lf(), isActive())
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{index() === lf() && !typing() ? marker() : " "}
|
||||||
|
</text>
|
||||||
|
<text
|
||||||
|
fg={
|
||||||
|
typing()
|
||||||
|
? theme.text
|
||||||
|
: focusFg(index(), lf(), isActive())
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{query}
|
||||||
</text>
|
</text>
|
||||||
<text fg={focusFg(index(), lf(), isActive())}>{query}</text>
|
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
}}
|
}}
|
||||||
@@ -289,7 +552,7 @@ function SearchPage() {
|
|||||||
<text fg={muted()}>
|
<text fg={muted()}>
|
||||||
{inputActive()
|
{inputActive()
|
||||||
? "Enter to search · Esc to defocus"
|
? "Enter to search · Esc to defocus"
|
||||||
: "j/k recents · s to type · h back"}
|
: "j/k recents · s to type · tab scope · h back"}
|
||||||
</text>
|
</text>
|
||||||
</box>
|
</box>
|
||||||
</Show>
|
</Show>
|
||||||
@@ -305,6 +568,8 @@ function SearchPage() {
|
|||||||
<text fg={muted()}>
|
<text fg={muted()}>
|
||||||
{searchStore.query()
|
{searchStore.query()
|
||||||
? "No results found"
|
? "No results found"
|
||||||
|
: searchStore.scope() === "episode"
|
||||||
|
? "Enter a search term to find episodes"
|
||||||
: "Enter a search term to find podcasts"}
|
: "Enter a search term to find podcasts"}
|
||||||
</text>
|
</text>
|
||||||
}
|
}
|
||||||
@@ -318,12 +583,18 @@ function SearchPage() {
|
|||||||
{(result, index) => {
|
{(result, index) => {
|
||||||
const fi = () => focusedResultIdx();
|
const fi = () => focusedResultIdx();
|
||||||
const ref = useScrollIntoView(() => index() === fi());
|
const ref = useScrollIntoView(() => index() === fi());
|
||||||
|
// Episode download status badge ("" when absent).
|
||||||
|
const dlLabel = () =>
|
||||||
|
result.kind === "episode"
|
||||||
|
? downloadLabel(result.episode.id)
|
||||||
|
: "";
|
||||||
|
const dlEpId = () =>
|
||||||
|
result.kind === "episode" ? result.episode.id : "";
|
||||||
return (
|
return (
|
||||||
<box
|
<box
|
||||||
ref={ref}
|
ref={ref}
|
||||||
flexDirection="column"
|
flexDirection="column"
|
||||||
gap={0}
|
gap={0}
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
paddingRight={1}
|
||||||
backgroundColor={focusBg(index(), fi(), isActive())}
|
backgroundColor={focusBg(index(), fi(), isActive())}
|
||||||
onMouseDown={() => {
|
onMouseDown={() => {
|
||||||
@@ -333,11 +604,18 @@ function SearchPage() {
|
|||||||
>
|
>
|
||||||
<box flexDirection="row" gap={1}>
|
<box flexDirection="row" gap={1}>
|
||||||
<text fg={focusFg(index(), fi(), isActive())}>
|
<text fg={focusFg(index(), fi(), isActive())}>
|
||||||
{index() === fi() ? "❯" : " "}
|
{index() === fi() ? marker() : " "}
|
||||||
</text>
|
</text>
|
||||||
<text fg={focusFg(index(), fi(), isActive())}>
|
<text fg={focusFg(index(), fi(), isActive())}>
|
||||||
{result.podcast.title}
|
{result.kind === "episode"
|
||||||
|
? result.episode.title
|
||||||
|
: result.podcast.title}
|
||||||
</text>
|
</text>
|
||||||
|
<Show when={dlLabel()}>
|
||||||
|
<text fg={downloadColor(dlEpId())}>
|
||||||
|
{dlLabel()}
|
||||||
|
</text>
|
||||||
|
</Show>
|
||||||
<Show when={result.podcast.isSubscribed}>
|
<Show when={result.podcast.isSubscribed}>
|
||||||
<text
|
<text
|
||||||
fg={index() === fi() ? theme.surface : theme.success}
|
fg={index() === fi() ? theme.surface : theme.success}
|
||||||
@@ -346,6 +624,15 @@ function SearchPage() {
|
|||||||
</text>
|
</text>
|
||||||
</Show>
|
</Show>
|
||||||
</box>
|
</box>
|
||||||
|
{result.kind === "episode" ? (
|
||||||
|
<text
|
||||||
|
fg={index() === fi() ? theme.surface : muted()}
|
||||||
|
paddingLeft={2}
|
||||||
|
>
|
||||||
|
{result.podcast.title} ·{" "}
|
||||||
|
{formatDate(result.episode.pubDate)}
|
||||||
|
</text>
|
||||||
|
) : (
|
||||||
<Show when={result.podcast.author}>
|
<Show when={result.podcast.author}>
|
||||||
<text
|
<text
|
||||||
fg={index() === fi() ? theme.surface : muted()}
|
fg={index() === fi() ? theme.surface : muted()}
|
||||||
@@ -354,6 +641,7 @@ function SearchPage() {
|
|||||||
by {result.podcast.author}
|
by {result.podcast.author}
|
||||||
</text>
|
</text>
|
||||||
</Show>
|
</Show>
|
||||||
|
)}
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
}}
|
}}
|
||||||
@@ -371,6 +659,10 @@ function SearchPage() {
|
|||||||
<strong>Search</strong>
|
<strong>Search</strong>
|
||||||
</text>
|
</text>
|
||||||
<text fg={muted()}>Type a query, press Enter to search.</text>
|
<text fg={muted()}>Type a query, press Enter to search.</text>
|
||||||
|
<text fg={muted()}>
|
||||||
|
Tab toggles Shows ↔ Episodes (episode search finds guests
|
||||||
|
and topics).
|
||||||
|
</text>
|
||||||
<text fg={muted()}>Esc defocuses the input; h goes back.</text>
|
<text fg={muted()}>Esc defocuses the input; h goes back.</text>
|
||||||
<box height={1} />
|
<box height={1} />
|
||||||
<text fg={theme.textSecondary}>Recent · {recents().length}</text>
|
<text fg={theme.textSecondary}>Recent · {recents().length}</text>
|
||||||
@@ -387,52 +679,131 @@ function SearchPage() {
|
|||||||
</box>
|
</box>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{(result) => (
|
{(result) => {
|
||||||
|
const r = result();
|
||||||
|
if (r.kind === "episode") {
|
||||||
|
return (
|
||||||
<box flexDirection="column" gap={1} padding={1}>
|
<box flexDirection="column" gap={1} padding={1}>
|
||||||
<text fg={theme.text}>
|
<text fg={theme.text}>
|
||||||
<strong>{result().podcast.title}</strong>
|
<strong>{r.episode.title}</strong>
|
||||||
</text>
|
</text>
|
||||||
<Show when={result().podcast.author}>
|
<text fg={theme.textSecondary}>{r.podcast.title}</text>
|
||||||
<text fg={muted()}>by {result().podcast.author}</text>
|
<Show when={r.podcast.author}>
|
||||||
|
<text fg={muted()}>by {r.podcast.author}</text>
|
||||||
</Show>
|
</Show>
|
||||||
<Show when={result().podcast.description}>
|
<Show when={r.episode.description}>
|
||||||
<text fg={theme.textSecondary}>
|
<text fg={theme.textSecondary}>
|
||||||
{result().podcast.description!.slice(0, 400)}
|
{r.episode.description!.slice(0, 400)}
|
||||||
{(result().podcast.description?.length ?? 0) > 400 ? "…" : ""}
|
{(r.episode.description?.length ?? 0) > 400 ? "…" : ""}
|
||||||
</text>
|
</text>
|
||||||
</Show>
|
</Show>
|
||||||
<Show when={(result().podcast.categories ?? []).length > 0}>
|
<box flexDirection="row" gap={2}>
|
||||||
|
<text fg={muted()}>
|
||||||
|
Published: {formatDate(r.episode.pubDate)}
|
||||||
|
</text>
|
||||||
|
<Show when={downloadLabel(r.episode.id)}>
|
||||||
|
<text fg={downloadColor(r.episode.id)}>
|
||||||
|
{downloadLabel(r.episode.id)}
|
||||||
|
</text>
|
||||||
|
</Show>
|
||||||
|
</box>
|
||||||
|
<Show when={(r.podcast.categories ?? []).length > 0}>
|
||||||
<box flexDirection="row" gap={1}>
|
<box flexDirection="row" gap={1}>
|
||||||
<For each={(result().podcast.categories ?? []).slice(0, 4)}>
|
<For each={(r.podcast.categories ?? []).slice(0, 4)}>
|
||||||
{(cat) => <text fg={theme.warning}>[{cat}]</text>}
|
{(cat) => <text fg={theme.warning}>[{cat}]</text>}
|
||||||
</For>
|
</For>
|
||||||
</box>
|
</box>
|
||||||
</Show>
|
</Show>
|
||||||
<text fg={muted()}>Feed: {result().podcast.feedUrl}</text>
|
<Show when={r.sourceName}>
|
||||||
<text fg={muted()}>
|
<text fg={muted()}>Source: {r.sourceName}</text>
|
||||||
Updated: {formatDate(result().podcast.lastUpdated)}
|
|
||||||
</text>
|
|
||||||
<Show when={result().sourceName}>
|
|
||||||
<text fg={muted()}>Source: {result().sourceName}</text>
|
|
||||||
</Show>
|
</Show>
|
||||||
<box height={1} />
|
<box height={1} />
|
||||||
<Show when={!result().podcast.isSubscribed}>
|
<Show when={!r.podcast.isSubscribed}>
|
||||||
|
<text fg={theme.primary}>[+] Subscribe (a)</text>
|
||||||
|
</Show>
|
||||||
|
<Show when={r.podcast.isSubscribed}>
|
||||||
|
<text fg={theme.success}>
|
||||||
|
Subscribed · x: unsubscribe
|
||||||
|
</text>
|
||||||
|
</Show>
|
||||||
|
<box height={1} />
|
||||||
|
<Show
|
||||||
|
when={r.podcast.isSubscribed}
|
||||||
|
fallback={
|
||||||
|
<text fg={muted()}>
|
||||||
|
enter: play · a: subscribe · d: download · h: back to query
|
||||||
|
</text>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<text fg={muted()}>
|
||||||
|
enter: play · d: download · x: unsubscribe
|
||||||
|
{downloadStore.getDownloadStatus(r.episode.id) !==
|
||||||
|
DownloadStatus.NONE
|
||||||
|
? " · D: delete"
|
||||||
|
: ""}{" "}
|
||||||
|
· h: back to query
|
||||||
|
</text>
|
||||||
|
</Show>
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<box flexDirection="column" gap={1} padding={1}>
|
||||||
|
<text fg={theme.text}>
|
||||||
|
<strong>{r.podcast.title}</strong>
|
||||||
|
</text>
|
||||||
|
<Show when={r.podcast.author}>
|
||||||
|
<text fg={muted()}>by {r.podcast.author}</text>
|
||||||
|
</Show>
|
||||||
|
<Show when={r.podcast.description}>
|
||||||
|
<text fg={theme.textSecondary}>
|
||||||
|
{r.podcast.description!.slice(0, 400)}
|
||||||
|
{(r.podcast.description?.length ?? 0) > 400 ? "…" : ""}
|
||||||
|
</text>
|
||||||
|
</Show>
|
||||||
|
<Show when={(r.podcast.categories ?? []).length > 0}>
|
||||||
|
<box flexDirection="row" gap={1}>
|
||||||
|
<For each={(r.podcast.categories ?? []).slice(0, 4)}>
|
||||||
|
{(cat) => <text fg={theme.warning}>[{cat}]</text>}
|
||||||
|
</For>
|
||||||
|
</box>
|
||||||
|
</Show>
|
||||||
|
<text fg={muted()}>
|
||||||
|
Feed:{" "}
|
||||||
|
{r.podcast.feedUrl ||
|
||||||
|
"not listed by source — resolves on subscribe"}
|
||||||
|
</text>
|
||||||
|
<text fg={muted()}>
|
||||||
|
Updated: {formatDate(r.podcast.lastUpdated)}
|
||||||
|
</text>
|
||||||
|
<Show when={r.sourceName}>
|
||||||
|
<text fg={muted()}>Source: {r.sourceName}</text>
|
||||||
|
</Show>
|
||||||
|
<box height={1} />
|
||||||
|
<Show when={!r.podcast.isSubscribed}>
|
||||||
<text fg={theme.primary}>[+] Subscribe (enter)</text>
|
<text fg={theme.primary}>[+] Subscribe (enter)</text>
|
||||||
</Show>
|
</Show>
|
||||||
<Show when={result().podcast.isSubscribed}>
|
<Show when={r.podcast.isSubscribed}>
|
||||||
<text fg={theme.success}>Already subscribed</text>
|
<text fg={theme.success}>
|
||||||
|
Subscribed · x: unsubscribe
|
||||||
|
</text>
|
||||||
</Show>
|
</Show>
|
||||||
<box height={1} />
|
<box height={1} />
|
||||||
<text fg={muted()}>enter: subscribe · h: back to query</text>
|
<text fg={muted()}>
|
||||||
|
enter: subscribe
|
||||||
|
{r.podcast.isSubscribed ? " · x: unsubscribe" : ""}{" "}
|
||||||
|
· h: back to query
|
||||||
|
</text>
|
||||||
</box>
|
</box>
|
||||||
)}
|
);
|
||||||
|
}}
|
||||||
</Show>
|
</Show>
|
||||||
);
|
);
|
||||||
|
|
||||||
const currentLabel = () =>
|
const currentLabel = () =>
|
||||||
depth() === 0
|
depth() === 0
|
||||||
? `Search · ${recents().length} recent`
|
? `Search · ${recents().length} recent`
|
||||||
: `Results · ${results().length}`;
|
: `Results (${searchStore.scope() === "episode" ? "episodes" : "shows"}) · ${results().length}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PaneRow
|
<PaneRow
|
||||||
|
|||||||
@@ -2,13 +2,18 @@
|
|||||||
* DownloadManager — exposes downloads as SettingItems for the depth-stack.
|
* DownloadManager — exposes downloads as SettingItems for the depth-stack.
|
||||||
*
|
*
|
||||||
* • "Delete All Downloads" — action item; Enter wipes every download.
|
* • "Delete All Downloads" — action item; Enter wipes every download.
|
||||||
* • one item per show — action item; Enter deletes all that show's
|
* • one item per subscribed show — action item; Enter deletes all that
|
||||||
* downloads (file + metadata, aborts in-flight).
|
* show's downloads (file + metadata, aborts
|
||||||
|
* in-flight).
|
||||||
|
* • "Unsubscribed Show Downloads" — downloads made from episode search for
|
||||||
|
* shows that aren't subscribed, grouped
|
||||||
|
* under their own header.
|
||||||
* • one item per episode — action item; Enter deletes a single download.
|
* • one item per episode — action item; Enter deletes a single download.
|
||||||
*
|
*
|
||||||
* Titles resolve from the feed store at render time (reactive), falling back
|
* Titles resolve from the feed store at render time (reactive), falling back
|
||||||
* to the episode id when the feed is no longer loaded. Movement flows through
|
* to the persisted episode/show titles for unsubscribed-show downloads.
|
||||||
* nav.action — no own useKeyboard (matches the other panels).
|
* Movement flows through nav.action — no own useKeyboard (matches the other
|
||||||
|
* panels).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { useFeedStore } from "@/stores/feed";
|
import { useFeedStore } from "@/stores/feed";
|
||||||
@@ -40,23 +45,26 @@ function statusLabel(s: DownloadStatus): string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Episode title for a download, resolved from the feed store (reactive). */
|
/** Episode title for a download, resolved from the feed store (reactive);
|
||||||
|
* falls back to the persisted title (kept for unsubscribed-show downloads). */
|
||||||
function episodeTitle(
|
function episodeTitle(
|
||||||
feedStore: ReturnType<typeof useFeedStore>,
|
feedStore: ReturnType<typeof useFeedStore>,
|
||||||
d: DownloadedEpisode,
|
d: DownloadedEpisode,
|
||||||
): string {
|
): string {
|
||||||
const feed = feedStore.getFeed(d.feedId);
|
const feed = feedStore.getFeed(d.feedId);
|
||||||
const ep = feed?.episodes.find((e) => e.id === d.episodeId);
|
const ep = feed?.episodes.find((e) => e.id === d.episodeId);
|
||||||
return ep?.title ?? d.episodeId;
|
return ep?.title ?? d.episodeTitle ?? d.episodeId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Show title for a download's feed id. */
|
/** Show title for a download's feed id; falls back to the persisted show
|
||||||
|
* title (unsubscribed-show downloads have no feed to resolve from). */
|
||||||
function feedTitle(
|
function feedTitle(
|
||||||
feedStore: ReturnType<typeof useFeedStore>,
|
feedStore: ReturnType<typeof useFeedStore>,
|
||||||
feedId: string,
|
d: DownloadedEpisode,
|
||||||
): string {
|
): string {
|
||||||
const feed = feedStore.getFeed(feedId);
|
const feed = feedStore.getFeed(d.feedId);
|
||||||
return feed ? feed.customName || feed.podcast.title : feedId;
|
if (feed) return feed.customName || feed.podcast.title;
|
||||||
|
return d.podcastTitle ?? d.feedId;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDownloadItems(): SettingItem[] {
|
export function useDownloadItems(): SettingItem[] {
|
||||||
@@ -82,9 +90,15 @@ export function useDownloadItems(): SettingItem[] {
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
// Group downloads by feed so each show gets a delete-by-show item.
|
// Group downloads by feed so each subscribed show gets a delete-by-show
|
||||||
|
// item. Unsubscribed-show downloads (search downloads, synthetic feed
|
||||||
|
// ids) are kept out of these groups and listed under their own section
|
||||||
|
// below.
|
||||||
|
const unsubscribed = downloadStore.getUnsubscribedDownloads();
|
||||||
|
const unsubscribedIds = new Set(unsubscribed.map((d) => d.episodeId));
|
||||||
const byFeed = new Map<string, DownloadedEpisode[]>();
|
const byFeed = new Map<string, DownloadedEpisode[]>();
|
||||||
for (const d of downloads()) {
|
for (const d of downloads()) {
|
||||||
|
if (unsubscribedIds.has(d.episodeId)) continue;
|
||||||
const arr = byFeed.get(d.feedId) ?? [];
|
const arr = byFeed.get(d.feedId) ?? [];
|
||||||
arr.push(d);
|
arr.push(d);
|
||||||
byFeed.set(d.feedId, arr);
|
byFeed.set(d.feedId, arr);
|
||||||
@@ -93,25 +107,54 @@ export function useDownloadItems(): SettingItem[] {
|
|||||||
const size = eps.reduce((s, e) => s + e.fileSize, 0);
|
const size = eps.reduce((s, e) => s + e.fileSize, 0);
|
||||||
items.push({
|
items.push({
|
||||||
id: `feed:${feedId}`,
|
id: `feed:${feedId}`,
|
||||||
label: `Show: ${feedTitle(feedStore, feedId)}`,
|
label: `Show: ${feedTitle(feedStore, eps[0])}`,
|
||||||
kind: "action",
|
kind: "action",
|
||||||
display: () => `${eps.length} · ${fmtBytes(size)}`,
|
display: () => `${eps.length} · ${fmtBytes(size)}`,
|
||||||
help: () =>
|
help: () =>
|
||||||
`Delete all ${eps.length} downloads for this show (files + metadata,\naborts any in-flight transfers). Enter to run.`,
|
`Delete all ${eps.length} downloads for this show (files + metadata,\naborts any in-flight transfers). Enter to run.`,
|
||||||
run: () => {
|
run: () => {
|
||||||
downloadStore.removeDownloadsForFeed(feedId).catch(() => {});
|
downloadStore
|
||||||
|
.removeDownloadsForFeed(feedId, eps[0].podcastFeedUrl)
|
||||||
|
.catch(() => {});
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// One item per individual episode download.
|
// Unsubscribed-show downloads: a section header + one item per episode.
|
||||||
|
if (unsubscribed.length > 0) {
|
||||||
|
items.push({
|
||||||
|
id: "unsubscribed-header",
|
||||||
|
label: "Unsubscribed Show Downloads",
|
||||||
|
kind: "info",
|
||||||
|
display: () => `${unsubscribed.length} files`,
|
||||||
|
help: () =>
|
||||||
|
`Downloads made from episode search for shows that are not\nsubscribed. Subscribe to a show and these move into its group.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (const d of unsubscribed) {
|
||||||
|
items.push({
|
||||||
|
id: `unsub:${d.episodeId}`,
|
||||||
|
label: episodeTitle(feedStore, d),
|
||||||
|
kind: "action",
|
||||||
|
display: () =>
|
||||||
|
`${feedTitle(feedStore, d)} · ${statusLabel(d.status)} · ${fmtBytes(d.fileSize)}`,
|
||||||
|
help: () =>
|
||||||
|
`Delete this single download (file + metadata). Enter to run.`,
|
||||||
|
run: () => {
|
||||||
|
downloadStore.removeDownload(d.episodeId).catch(() => {});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// One item per individual (subscribed-show) episode download.
|
||||||
for (const d of downloads()) {
|
for (const d of downloads()) {
|
||||||
|
if (unsubscribedIds.has(d.episodeId)) continue;
|
||||||
items.push({
|
items.push({
|
||||||
id: `ep:${d.episodeId}`,
|
id: `ep:${d.episodeId}`,
|
||||||
label: episodeTitle(feedStore, d),
|
label: episodeTitle(feedStore, d),
|
||||||
kind: "action",
|
kind: "action",
|
||||||
display: () =>
|
display: () =>
|
||||||
`${feedTitle(feedStore, d.feedId)} · ${statusLabel(d.status)} · ${fmtBytes(d.fileSize)}`,
|
`${feedTitle(feedStore, d)} · ${statusLabel(d.status)} · ${fmtBytes(d.fileSize)}`,
|
||||||
help: () =>
|
help: () =>
|
||||||
`Delete this single download (file + metadata). Enter to run.`,
|
`Delete this single download (file + metadata). Enter to run.`,
|
||||||
run: () => {
|
run: () => {
|
||||||
|
|||||||
@@ -32,6 +32,9 @@ export function ExportDialog() {
|
|||||||
value={filename[0]()}
|
value={filename[0]()}
|
||||||
onInput={filename[1]}
|
onInput={filename[1]}
|
||||||
style={{ width: 30 }}
|
style={{ width: 30 }}
|
||||||
|
textColor={theme.text}
|
||||||
|
focusedTextColor={theme.accent}
|
||||||
|
cursorColor={theme.accent}
|
||||||
/>
|
/>
|
||||||
</box>
|
</box>
|
||||||
<box style={{ flexDirection: "row", gap: 1 }}>
|
<box style={{ flexDirection: "row", gap: 1 }}>
|
||||||
|
|||||||
@@ -21,6 +21,9 @@ export function FilePicker(props: FilePickerProps) {
|
|||||||
onInput={props.onChange}
|
onInput={props.onChange}
|
||||||
placeholder="/path/to/sync-file.json"
|
placeholder="/path/to/sync-file.json"
|
||||||
style={{ width: 40 }}
|
style={{ width: 40 }}
|
||||||
|
textColor={theme.text}
|
||||||
|
focusedTextColor={theme.accent}
|
||||||
|
cursorColor={theme.accent}
|
||||||
/>
|
/>
|
||||||
<text fg={theme.text}>Format: {format}</text>
|
<text fg={theme.text}>Format: {format}</text>
|
||||||
</box>
|
</box>
|
||||||
|
|||||||
@@ -2,10 +2,36 @@
|
|||||||
* PreferencesPanel — exposes theme/font/speed/explicit/auto-download as
|
* PreferencesPanel — exposes theme/font/speed/explicit/auto-download as
|
||||||
* SettingItems for the yazi depth-stack. No own useKeyboard; all movement is
|
* SettingItems for the yazi depth-stack. No own useKeyboard; all movement is
|
||||||
* driven by the Shell router via nav.action.
|
* driven by the Shell router via nav.action.
|
||||||
|
*
|
||||||
|
* Auto-download (global setting, see stores/feed.ts runAutoDownload):
|
||||||
|
* • Auto Download — master toggle (default: off)
|
||||||
|
* • Auto Download Count — X most recent episodes per show (default: 2,
|
||||||
|
* any positive integer — type it in the editor)
|
||||||
|
* • Auto Download Scope — which shows: all / none / whitelist (default: all)
|
||||||
|
* • Auto Download Whitelist — shown only when scope is "whitelist": search
|
||||||
|
* field over subscribed shows; suggestions toggle
|
||||||
|
* in/out with Space (j/k to move, Esc to browse).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { createSignal, Show, For, onMount, onCleanup } from "solid-js";
|
||||||
|
import { RenderableEvents, type InputRenderable } from "@opentui/core";
|
||||||
import { useAppStore } from "@/stores/app";
|
import { useAppStore } from "@/stores/app";
|
||||||
import type { ThemeName } from "@/types/settings";
|
import { useFeedStore } from "@/stores/feed";
|
||||||
|
import { useTheme } from "@/context/ThemeContext";
|
||||||
|
import { useInputFocusNav } from "@/hooks/useInputFocusNav";
|
||||||
|
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
||||||
|
import { useSelectionMarker } from "@/hooks/useSelectionMarker";
|
||||||
|
import {
|
||||||
|
NavMode,
|
||||||
|
useNavigation,
|
||||||
|
DEPTH_CENTER_PANE,
|
||||||
|
type PaneId,
|
||||||
|
} from "@/context/NavigationContext";
|
||||||
|
import { on } from "@/utils/event-bus";
|
||||||
|
import type { KeybindActionName } from "@/context/KeybindContext";
|
||||||
|
import { TABS } from "@/utils/navigation";
|
||||||
|
import type { AutoDownloadScope, ThemeName } from "@/types/settings";
|
||||||
|
import type { Feed } from "@/types/feed";
|
||||||
import type { SettingItem } from "./types";
|
import type { SettingItem } from "./types";
|
||||||
|
|
||||||
const THEME_LABELS: Array<{ value: ThemeName; label: string }> = [
|
const THEME_LABELS: Array<{ value: ThemeName; label: string }> = [
|
||||||
@@ -17,13 +43,24 @@ const THEME_LABELS: Array<{ value: ThemeName; label: string }> = [
|
|||||||
{ value: "custom", label: "Custom" },
|
{ value: "custom", label: "Custom" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const SCOPE_LABELS: Array<{ value: AutoDownloadScope; label: string }> = [
|
||||||
|
{ value: "all", label: "All" },
|
||||||
|
{ value: "none", label: "None" },
|
||||||
|
{ value: "whitelist", label: "Whitelist" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function scopeLabel(scope: AutoDownloadScope): string {
|
||||||
|
return SCOPE_LABELS.find((s) => s.value === scope)?.label ?? scope;
|
||||||
|
}
|
||||||
|
|
||||||
export function usePreferencesItems(): SettingItem[] {
|
export function usePreferencesItems(): SettingItem[] {
|
||||||
const app = useAppStore();
|
const app = useAppStore();
|
||||||
|
const feedStore = useFeedStore();
|
||||||
|
|
||||||
const settings = () => app.state().settings;
|
const settings = () => app.state().settings;
|
||||||
const prefs = () => app.state().preferences;
|
const prefs = () => app.state().preferences;
|
||||||
|
|
||||||
return [
|
const items: SettingItem[] = [
|
||||||
{
|
{
|
||||||
id: "theme",
|
id: "theme",
|
||||||
label: "Theme",
|
label: "Theme",
|
||||||
@@ -52,6 +89,18 @@ export function usePreferencesItems(): SettingItem[] {
|
|||||||
transparentBackground: !settings().transparentBackground,
|
transparentBackground: !settings().transparentBackground,
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "showSelectionMarker",
|
||||||
|
label: "Selection Marker",
|
||||||
|
kind: "toggle",
|
||||||
|
display: () => (settings().showSelectionMarker ? "On" : "Off"),
|
||||||
|
help: () =>
|
||||||
|
`Show the ❯ marker on the focused row of every list (tabs, shows, episodes, results).\nType: toggle\nDefault: off\nCurrent: ${settings().showSelectionMarker ? "On" : "Off"}\nSpace/Enter to toggle.`,
|
||||||
|
toggle: () =>
|
||||||
|
app.updateSettings({
|
||||||
|
showSelectionMarker: !settings().showSelectionMarker,
|
||||||
|
}),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: "fontSize",
|
id: "fontSize",
|
||||||
label: "Font Size",
|
label: "Font Size",
|
||||||
@@ -97,11 +146,52 @@ export function usePreferencesItems(): SettingItem[] {
|
|||||||
kind: "toggle",
|
kind: "toggle",
|
||||||
display: () => (prefs().autoDownload ? "On" : "Off"),
|
display: () => (prefs().autoDownload ? "On" : "Off"),
|
||||||
help: () =>
|
help: () =>
|
||||||
`Download new episodes automatically.\nType: toggle\nDefault: false\nCurrent: ${prefs().autoDownload}\nSpace/Enter to toggle.`,
|
`Download the ${prefs().autoDownloadCount} most recent episodes of your shows automatically (see Count/Scope below).\nType: toggle\nDefault: false\nCurrent: ${prefs().autoDownload ? "On" : "Off"}\nSpace/Enter to toggle.`,
|
||||||
toggle: () =>
|
toggle: () => {
|
||||||
app.updatePreferences({
|
app.updatePreferences({ autoDownload: !prefs().autoDownload });
|
||||||
autoDownload: !prefs().autoDownload,
|
feedStore.runAutoDownload();
|
||||||
}),
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "autoDownloadCount",
|
||||||
|
label: "Auto Download Count",
|
||||||
|
kind: "number",
|
||||||
|
display: () => `${prefs().autoDownloadCount} per show`,
|
||||||
|
help: () =>
|
||||||
|
`How many of the most recent episodes to auto-download per in-scope show.\nType: number (any positive integer)\nDefault: 2\nCurrent: ${prefs().autoDownloadCount}\nj/k to −/+1 · Enter to type a value.`,
|
||||||
|
cycle: (dir) => {
|
||||||
|
const next = Math.max(1, prefs().autoDownloadCount + dir);
|
||||||
|
app.updatePreferences({ autoDownloadCount: next });
|
||||||
|
feedStore.runAutoDownload();
|
||||||
|
},
|
||||||
|
renderEditor: () => (
|
||||||
|
<NumberInputEditor
|
||||||
|
label="Auto Download Count"
|
||||||
|
value={() => prefs().autoDownloadCount}
|
||||||
|
commit={(n) => {
|
||||||
|
app.updatePreferences({ autoDownloadCount: n });
|
||||||
|
feedStore.runAutoDownload();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "autoDownloadScope",
|
||||||
|
label: "Auto Download Scope",
|
||||||
|
kind: "select",
|
||||||
|
display: () => scopeLabel(prefs().autoDownloadScope),
|
||||||
|
help: () =>
|
||||||
|
`Which shows auto-download applies to.\nAll: every subscribed show.\nNone: nothing.\nWhitelist: only the shows you add (in My Shows press ${"w"} on the focused show; or open the Whitelist item below).\nType: select\nDefault: all\nCurrent: ${scopeLabel(prefs().autoDownloadScope)}\nCycle with j/k; Enter to apply.`,
|
||||||
|
cycle: (dir) => {
|
||||||
|
const idx = SCOPE_LABELS.findIndex(
|
||||||
|
(s) => s.value === prefs().autoDownloadScope,
|
||||||
|
);
|
||||||
|
const next =
|
||||||
|
SCOPE_LABELS[(idx + dir + SCOPE_LABELS.length) % SCOPE_LABELS.length]
|
||||||
|
.value;
|
||||||
|
app.updatePreferences({ autoDownloadScope: next });
|
||||||
|
feedStore.runAutoDownload();
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "autoJumpToPlayer",
|
id: "autoJumpToPlayer",
|
||||||
@@ -121,13 +211,292 @@ export function usePreferencesItems(): SettingItem[] {
|
|||||||
kind: "select",
|
kind: "select",
|
||||||
display: () => (prefs().fetchMoreMode === "auto" ? "Auto" : "Manual"),
|
display: () => (prefs().fetchMoreMode === "auto" ? "Auto" : "Manual"),
|
||||||
help: () =>
|
help: () =>
|
||||||
`How the Feed list loads older episodes.\nManual: a "[Fetch More]" button at the bottom of the list.\nAuto: fetches automatically when reaching the bottom.\nType: select\nDefault: manual\nCurrent: ${prefs().fetchMoreMode === "auto" ? "Auto" : "Manual"}\nCycle with j/k; Enter to apply.`,
|
`How the Feed and per-show episode lists load older episodes.\nManual: a "[Fetch More]" button at the bottom of the list.\nAuto: fetches automatically when reaching the bottom.\nType: select\nDefault: auto\nCurrent: ${prefs().fetchMoreMode === "auto" ? "Auto" : "Manual"}\nCycle with j/k; Enter to apply.`,
|
||||||
cycle: (dir) => {
|
cycle: (dir) => {
|
||||||
const modes: Array<"manual" | "auto"> = ["manual", "auto"];
|
const modes: Array<"manual" | "auto"> = ["manual", "auto"];
|
||||||
const idx = modes.indexOf(prefs().fetchMoreMode ?? "manual");
|
const idx = modes.indexOf(prefs().fetchMoreMode ?? "auto");
|
||||||
const next = modes[(idx + dir + modes.length) % modes.length];
|
const next = modes[(idx + dir + modes.length) % modes.length];
|
||||||
app.updatePreferences({ fetchMoreMode: next });
|
app.updatePreferences({ fetchMoreMode: next });
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "refreshInterval",
|
||||||
|
label: "Feed Refresh Interval",
|
||||||
|
kind: "number",
|
||||||
|
display: () => `${prefs().refreshIntervalMinutes} min`,
|
||||||
|
help: () =>
|
||||||
|
`How often subscribed feeds are re-fetched in the background, so new episodes appear without a restart or manual refresh (r).\nType: number (1–120 minutes)\nDefault: 30\nCurrent: ${prefs().refreshIntervalMinutes} min\nj/k to −/+5 · Enter to type a value.`,
|
||||||
|
cycle: (dir) => {
|
||||||
|
const next = Math.min(
|
||||||
|
120,
|
||||||
|
Math.max(1, prefs().refreshIntervalMinutes + dir * 5),
|
||||||
|
);
|
||||||
|
app.updatePreferences({ refreshIntervalMinutes: next });
|
||||||
|
},
|
||||||
|
renderEditor: () => (
|
||||||
|
<NumberInputEditor
|
||||||
|
label="Feed Refresh Interval (minutes)"
|
||||||
|
value={() => prefs().refreshIntervalMinutes}
|
||||||
|
commit={(n) => {
|
||||||
|
app.updatePreferences({
|
||||||
|
refreshIntervalMinutes: Math.min(120, n),
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Whitelist management only appears while scope is set to "whitelist".
|
||||||
|
if (prefs().autoDownloadScope === "whitelist") {
|
||||||
|
items.push({
|
||||||
|
id: "autoDownloadWhitelist",
|
||||||
|
label: "Auto Download Whitelist",
|
||||||
|
kind: "editor",
|
||||||
|
display: () => `${prefs().autoDownloadWhitelist.length} shows`,
|
||||||
|
help: () =>
|
||||||
|
`Shows included in auto-download (scope: whitelist).\nSearch your subscribed shows; suggestions toggle in/out with Space.\nType: editor\nCurrent: ${prefs().autoDownloadWhitelist.length} shows`,
|
||||||
|
renderEditor: () => <WhitelistEditor />,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Number editor ────────────────────────────────────────────────────────────
|
||||||
|
// Lets the user type any positive integer (Enter commits; Esc defocuses and
|
||||||
|
// j/k ±1 cycling takes over — SettingsPage's depth-2 step handler).
|
||||||
|
|
||||||
|
function NumberInputEditor(props: {
|
||||||
|
label: string;
|
||||||
|
value: () => number;
|
||||||
|
commit: (n: number) => void;
|
||||||
|
}) {
|
||||||
|
const { theme } = useTheme();
|
||||||
|
const ref = useInputFocusNav();
|
||||||
|
const [draft, setDraft] = createSignal(String(props.value()));
|
||||||
|
const [error, setError] = createSignal<string | null>(null);
|
||||||
|
|
||||||
|
const submit = () => {
|
||||||
|
const n = Number(draft().trim());
|
||||||
|
if (!Number.isInteger(n) || n < 1) {
|
||||||
|
setError("Enter a whole number ≥ 1");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
props.commit(n);
|
||||||
|
setError(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<box flexDirection="column" padding={1} gap={1}>
|
||||||
|
<text fg={theme.text}>
|
||||||
|
<strong>{props.label}</strong>
|
||||||
|
</text>
|
||||||
|
<box flexDirection="row" gap={1} alignItems="center">
|
||||||
|
<text fg={theme.textMuted}>Episodes per show:</text>
|
||||||
|
<input
|
||||||
|
ref={ref}
|
||||||
|
value={draft()}
|
||||||
|
onInput={(v) => {
|
||||||
|
setDraft(v);
|
||||||
|
setError(null);
|
||||||
|
}}
|
||||||
|
onSubmit={submit}
|
||||||
|
focused
|
||||||
|
width={8}
|
||||||
|
textColor={theme.text}
|
||||||
|
focusedTextColor={theme.accent}
|
||||||
|
/>
|
||||||
|
</box>
|
||||||
|
<Show when={error()}>
|
||||||
|
<text fg={theme.error}>{error()}</text>
|
||||||
|
</Show>
|
||||||
|
<text fg={theme.muted ?? theme.textMuted}>
|
||||||
|
Type a number, Enter to apply · Esc to browse (j/k ±1) · h back
|
||||||
|
</text>
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Whitelist editor ─────────────────────────────────────────────────────────
|
||||||
|
// Search field over subscribed shows + a navigable suggestion list. Space
|
||||||
|
// (toggle-select) toggles the focused show in/out of the whitelist; Enter
|
||||||
|
// does the same. While the input is focused, keys type; Esc (handled in the
|
||||||
|
// Shell) defocuses so j/k move the list.
|
||||||
|
//
|
||||||
|
// Transient UI state lives at module level so preference updates (which
|
||||||
|
// rebuild the item list) never reset the search or yank focus back into the
|
||||||
|
// input mid-browse.
|
||||||
|
//
|
||||||
|
// The nav.action listener is registered ONCE at module level, not per
|
||||||
|
// component instance: toggling a show updates preferences, which remounts
|
||||||
|
// the editor (SettingsPage re-resolves the item's renderEditor), and
|
||||||
|
// re-registering the listener via onMount/onCleanup during a bus emit
|
||||||
|
// mutates the handler set mid-iteration — the event bus then re-delivers to
|
||||||
|
// the fresh listener forever. A single stable listener guarded by an active
|
||||||
|
// flag sidesteps that entirely.
|
||||||
|
|
||||||
|
const [wlQuery, setWlQuery] = createSignal("");
|
||||||
|
const [wlCursor, setWlCursor] = createSignal(0);
|
||||||
|
const [wlTyping, setWlTyping] = createSignal(true);
|
||||||
|
let wlEditorActive = false;
|
||||||
|
// Indirection for refocusing the search input from the module-level nav.action
|
||||||
|
// listener (which cannot call useNavigation — that needs the provider).
|
||||||
|
let wlFocusInput: (() => void) | null = null;
|
||||||
|
|
||||||
|
function wlSuggestions(): Feed[] {
|
||||||
|
const q = wlQuery().trim().toLowerCase();
|
||||||
|
const all = useFeedStore().getFilteredFeeds();
|
||||||
|
if (!q) return all;
|
||||||
|
return all.filter((f) =>
|
||||||
|
(f.customName || f.podcast.title).toLowerCase().includes(q),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep the cursor inside the (possibly shrinking) suggestion list. */
|
||||||
|
function wlCursorClamped(): number {
|
||||||
|
return Math.min(wlCursor(), Math.max(wlSuggestions().length - 1, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
function wlToggle(feedId: string): void {
|
||||||
|
const app = useAppStore();
|
||||||
|
const cur = app.state().preferences.autoDownloadWhitelist ?? [];
|
||||||
|
const next = cur.includes(feedId)
|
||||||
|
? cur.filter((id) => id !== feedId)
|
||||||
|
: [...cur, feedId];
|
||||||
|
app.updatePreferences({ autoDownloadWhitelist: next });
|
||||||
|
useFeedStore().runAutoDownload();
|
||||||
|
}
|
||||||
|
|
||||||
|
const wlOnAction = (data: {
|
||||||
|
action: KeybindActionName;
|
||||||
|
tab: TABS;
|
||||||
|
pane: PaneId;
|
||||||
|
mode: NavMode;
|
||||||
|
}) => {
|
||||||
|
// Fire at most once per dispatch: the editor is only ever open inside the
|
||||||
|
// Settings tab's depth-2 pane, so scope on tab + pane and gate on the
|
||||||
|
// mount flag (which flips during remounts without re-registering).
|
||||||
|
if (!wlEditorActive) return;
|
||||||
|
if (data.tab !== TABS.SETTINGS) return;
|
||||||
|
if (data.pane !== DEPTH_CENTER_PANE) return;
|
||||||
|
const list = wlSuggestions();
|
||||||
|
if (list.length === 0) return;
|
||||||
|
switch (data.action) {
|
||||||
|
case "move-down":
|
||||||
|
setWlCursor((c) => Math.min(c + 1, list.length - 1));
|
||||||
|
break;
|
||||||
|
case "move-up":
|
||||||
|
setWlCursor((c) => Math.max(c - 1, 0));
|
||||||
|
break;
|
||||||
|
case "toggle-select":
|
||||||
|
case "open":
|
||||||
|
wlToggle(list[wlCursorClamped()].id);
|
||||||
|
break;
|
||||||
|
case "search":
|
||||||
|
// `s` while browsing re-enters typing mode (mirrors SearchPage).
|
||||||
|
wlFocusInput?.();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
on("nav.action", wlOnAction);
|
||||||
|
|
||||||
|
function WhitelistEditor() {
|
||||||
|
const { theme } = useTheme();
|
||||||
|
const nav = useNavigation();
|
||||||
|
const feedStore = useFeedStore();
|
||||||
|
const app = useAppStore();
|
||||||
|
|
||||||
|
const whitelist = () => app.state().preferences.autoDownloadWhitelist ?? [];
|
||||||
|
const inList = (feedId: string) => whitelist().includes(feedId);
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
wlEditorActive = true;
|
||||||
|
// Restore the last typing/browsing mode across the remounts that
|
||||||
|
// preference updates trigger. nav.inputFocused() drives the input's
|
||||||
|
// focused prop (deterministic Esc-to-blur, same as SearchPage), so
|
||||||
|
// keep the store in sync with the persisted module mode.
|
||||||
|
nav.setInputFocused(wlTyping());
|
||||||
|
wlFocusInput = () => nav.setInputFocused(true);
|
||||||
|
onCleanup(() => {
|
||||||
|
wlEditorActive = false;
|
||||||
|
nav.setInputFocused(false);
|
||||||
|
wlFocusInput = null;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const focusNavRef = useInputFocusNav();
|
||||||
|
const inputRef = (el: InputRenderable | null | undefined) => {
|
||||||
|
focusNavRef(el);
|
||||||
|
if (el) {
|
||||||
|
// Sync the persisted mode with real focus changes so remounts
|
||||||
|
// (e.g. after a toggle) restore the right state.
|
||||||
|
el.on(RenderableEvents.FOCUSED, () => setWlTyping(true));
|
||||||
|
el.on(RenderableEvents.BLURRED, () => setWlTyping(false));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<box flexDirection="column" padding={1} gap={1}>
|
||||||
|
<text fg={theme.text}>
|
||||||
|
<strong>Auto Download Whitelist</strong>
|
||||||
|
</text>
|
||||||
|
<box flexDirection="row" gap={1} alignItems="center">
|
||||||
|
<text fg={theme.textMuted}>Search:</text>
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
value={wlQuery()}
|
||||||
|
onInput={setWlQuery}
|
||||||
|
focused={nav.inputFocused()}
|
||||||
|
placeholder="Type to filter shows…"
|
||||||
|
width={30}
|
||||||
|
textColor={theme.text}
|
||||||
|
focusedTextColor={theme.accent}
|
||||||
|
/>
|
||||||
|
</box>
|
||||||
|
<Show when={wlSuggestions().length === 0}>
|
||||||
|
<text fg={theme.muted ?? theme.textMuted}>
|
||||||
|
No subscribed shows match.
|
||||||
|
</text>
|
||||||
|
</Show>
|
||||||
|
<For each={wlSuggestions()}>
|
||||||
|
{(feed, index) => {
|
||||||
|
// While the input is focused (typing), no row shows the
|
||||||
|
// accent highlight or `❯` — only the input is "in focus".
|
||||||
|
const focused = () =>
|
||||||
|
!nav.inputFocused() && index() === wlCursorClamped();
|
||||||
|
const ref = useScrollIntoView(focused);
|
||||||
|
const marker = useSelectionMarker();
|
||||||
|
const bg = () => (focused() ? theme.primary : undefined);
|
||||||
|
const fg = () => (focused() ? theme.surface : theme.text);
|
||||||
|
return (
|
||||||
|
<box
|
||||||
|
ref={ref}
|
||||||
|
flexDirection="row"
|
||||||
|
gap={1}
|
||||||
|
paddingRight={1}
|
||||||
|
backgroundColor={bg()}
|
||||||
|
onMouseDown={() => {
|
||||||
|
nav.setActivePane(DEPTH_CENTER_PANE);
|
||||||
|
setWlCursor(index());
|
||||||
|
// Click toggles membership directly (works even
|
||||||
|
// while typing, where Space is input text).
|
||||||
|
wlToggle(feed.id);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<text fg={fg()}>{focused() ? marker() : " "}</text>
|
||||||
|
<text fg={fg()}>{inList(feed.id) ? "●" : "○"}</text>
|
||||||
|
<text fg={fg()}>
|
||||||
|
{feed.customName || feed.podcast.title}
|
||||||
|
</text>
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
</For>
|
||||||
|
<text fg={theme.muted ?? theme.textMuted}>
|
||||||
|
Type to search · Esc to browse · j/k move · Space toggles · s to
|
||||||
|
type · h back
|
||||||
|
</text>
|
||||||
|
</box>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import {
|
|||||||
type PaneId,
|
type PaneId,
|
||||||
} from "@/context/NavigationContext";
|
} from "@/context/NavigationContext";
|
||||||
import { on, off } from "@/utils/event-bus";
|
import { on, off } from "@/utils/event-bus";
|
||||||
|
import { NF_ICONS, supportsNerdFonts } from "@/utils/nerd-fonts";
|
||||||
import type { KeybindActionName } from "@/context/KeybindContext";
|
import type { KeybindActionName } from "@/context/KeybindContext";
|
||||||
import type { SettingItem, SettingsSectionDef } from "./types";
|
import type { SettingItem, SettingsSectionDef } from "./types";
|
||||||
import { usePreferencesItems } from "./PreferencesPanel";
|
import { usePreferencesItems } from "./PreferencesPanel";
|
||||||
@@ -37,6 +38,7 @@ import { useDownloadItems } from "./DownloadManager";
|
|||||||
import { PaneRow } from "@/components/PaneRow";
|
import { PaneRow } from "@/components/PaneRow";
|
||||||
import { TabListPane } from "@/components/TabPanel";
|
import { TabListPane } from "@/components/TabPanel";
|
||||||
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
|
||||||
|
import { useSelectionMarker } from "@/hooks/useSelectionMarker";
|
||||||
|
|
||||||
export const SettingsPaneCount = 1;
|
export const SettingsPaneCount = 1;
|
||||||
|
|
||||||
@@ -45,29 +47,38 @@ const SECTIONS: SettingsSectionDef[] = [
|
|||||||
id: 0,
|
id: 0,
|
||||||
label: "Sync",
|
label: "Sync",
|
||||||
description: "Import/export subscriptions and sync status.",
|
description: "Import/export subscriptions and sync status.",
|
||||||
|
icon: NF_ICONS.sync,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
label: "Sources",
|
label: "Sources",
|
||||||
description: "Podcast search/RSS sources — add, enable, remove.",
|
description: "Podcast search/RSS sources — add, enable, remove.",
|
||||||
|
icon: NF_ICONS.sources,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
label: "Preferences",
|
label: "Preferences",
|
||||||
description: "Theme, font, playback speed, explicit/auto-download.",
|
description: "Theme, font, playback speed, explicit/auto-download.",
|
||||||
|
icon: NF_ICONS.preferences,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 3,
|
id: 3,
|
||||||
label: "Visualizer",
|
label: "Visualizer",
|
||||||
description: "Audio visualizer: bars, sensitivity, cutoffs.",
|
description: "Audio visualizer: on/off, bars, sensitivity, cutoffs.",
|
||||||
|
icon: NF_ICONS.visualizer,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 4,
|
id: 4,
|
||||||
label: "Downloads",
|
label: "Downloads",
|
||||||
description: "Manage downloaded episodes — delete by show or individually.",
|
description: "Manage downloaded episodes — delete by show or individually.",
|
||||||
|
icon: NF_ICONS.downloads,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Static: detection never changes mid-session. Module-level because the Row
|
||||||
|
// component below (a sibling module function) needs it too.
|
||||||
|
const nerd = supportsNerdFonts();
|
||||||
|
|
||||||
/** Resolve the items for a section id at render time. */
|
/** Resolve the items for a section id at render time. */
|
||||||
function sectionItems(sectionId: number): SettingItem[] {
|
function sectionItems(sectionId: number): SettingItem[] {
|
||||||
switch (sectionId) {
|
switch (sectionId) {
|
||||||
@@ -286,6 +297,7 @@ export function SettingsPage() {
|
|||||||
{(section, index) => (
|
{(section, index) => (
|
||||||
<Row
|
<Row
|
||||||
label={section.label}
|
label={section.label}
|
||||||
|
icon={section.icon}
|
||||||
focused={index() === focusedSectionIdx()}
|
focused={index() === focusedSectionIdx()}
|
||||||
active={false}
|
active={false}
|
||||||
/>
|
/>
|
||||||
@@ -315,6 +327,7 @@ export function SettingsPage() {
|
|||||||
{(section, index) => (
|
{(section, index) => (
|
||||||
<Row
|
<Row
|
||||||
label={section.label}
|
label={section.label}
|
||||||
|
icon={section.icon}
|
||||||
focused={index() === focusedSectionIdx()}
|
focused={index() === focusedSectionIdx()}
|
||||||
active={isActive()}
|
active={isActive()}
|
||||||
onMouseDown={() => {
|
onMouseDown={() => {
|
||||||
@@ -407,6 +420,7 @@ function Row(props: {
|
|||||||
focused: boolean;
|
focused: boolean;
|
||||||
active: boolean;
|
active: boolean;
|
||||||
hint?: string;
|
hint?: string;
|
||||||
|
icon?: string;
|
||||||
onMouseDown?: () => void;
|
onMouseDown?: () => void;
|
||||||
}) {
|
}) {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
@@ -423,17 +437,18 @@ function Row(props: {
|
|||||||
? theme.selectedListItemText ?? theme.text
|
? theme.selectedListItemText ?? theme.text
|
||||||
: theme.text;
|
: theme.text;
|
||||||
const ref = useScrollIntoView(() => props.focused);
|
const ref = useScrollIntoView(() => props.focused);
|
||||||
|
const marker = useSelectionMarker();
|
||||||
return (
|
return (
|
||||||
<box
|
<box
|
||||||
ref={ref}
|
ref={ref}
|
||||||
flexDirection="row"
|
flexDirection="row"
|
||||||
gap={1}
|
gap={1}
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
paddingRight={1}
|
||||||
backgroundColor={bg()}
|
backgroundColor={bg()}
|
||||||
onMouseDown={props.onMouseDown}
|
onMouseDown={props.onMouseDown}
|
||||||
>
|
>
|
||||||
<text fg={fg()}>{props.focused ? "❯" : " "}</text>
|
<text fg={fg()}>{props.focused ? marker() : " "}</text>
|
||||||
|
{props.icon && nerd && <text fg={fg()}>{props.icon}</text>}
|
||||||
<text fg={fg()}>{props.label}</text>
|
<text fg={fg()}>{props.label}</text>
|
||||||
<Show when={props.value}>
|
<Show when={props.value}>
|
||||||
<box flexGrow={1} />
|
<box flexGrow={1} />
|
||||||
|
|||||||
@@ -11,16 +11,24 @@
|
|||||||
* right-pane key conflicts).
|
* right-pane key conflicts).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { createSignal, For, Show } from "solid-js";
|
import { createSignal, For, Show, onMount } from "solid-js";
|
||||||
|
import { Renderable } from "@opentui/core";
|
||||||
import { useFeedStore } from "@/stores/feed";
|
import { useFeedStore } from "@/stores/feed";
|
||||||
import { useTheme } from "@/context/ThemeContext";
|
import { useTheme } from "@/context/ThemeContext";
|
||||||
import { useInputFocusNav } from "@/hooks/useInputFocusNav";
|
import { useInputFocusNav } from "@/hooks/useInputFocusNav";
|
||||||
|
import { useDialog } from "@/ui/dialog";
|
||||||
|
import { useToast } from "@/ui/toast";
|
||||||
|
import {
|
||||||
|
resolveSourceCredentials,
|
||||||
|
savePodcastIndexCredentials,
|
||||||
|
} from "@/utils/source-credentials";
|
||||||
import { SourceType } from "@/types/source";
|
import { SourceType } from "@/types/source";
|
||||||
import type { PodcastSource } from "@/types/source";
|
import type { PodcastSource } from "@/types/source";
|
||||||
import type { SettingItem } from "./types";
|
import type { SettingItem } from "./types";
|
||||||
|
|
||||||
export function useSourceItems(): SettingItem[] {
|
export function useSourceItems(): SettingItem[] {
|
||||||
const feedStore = useFeedStore();
|
const feedStore = useFeedStore();
|
||||||
|
const dialog = useDialog();
|
||||||
|
|
||||||
const typeBadge = (s: PodcastSource) =>
|
const typeBadge = (s: PodcastSource) =>
|
||||||
s.type === SourceType.API
|
s.type === SourceType.API
|
||||||
@@ -48,8 +56,20 @@ export function useSourceItems(): SettingItem[] {
|
|||||||
kind: "toggle",
|
kind: "toggle",
|
||||||
display: () => `${typeBadge(s)} ${s.enabled ? "on" : "off"}`,
|
display: () => `${typeBadge(s)} ${s.enabled ? "on" : "off"}`,
|
||||||
help: () =>
|
help: () =>
|
||||||
`Source: ${s.name}\nType: ${s.type}\nEnabled: ${s.enabled}\nURL: ${s.baseUrl ?? "(none)"}\nSpace/Enter to toggle.`,
|
s.id === "podcastindex"
|
||||||
toggle: () => feedStore.toggleSource(s.id),
|
? `Source: ${s.name} (open podcast directory)\nEnabled: ${s.enabled}\nSpace to ${s.enabled ? "disable" : "enable"}: enabling asks for API keys.\nKeys are masked in the UI and stored in the macOS keychain\n(encrypted at rest), falling back to config.json when the\nkeychain is unavailable; they are kept when disabled.`
|
||||||
|
: `Source: ${s.name}\nType: ${s.type}\nEnabled: ${s.enabled}\nURL: ${s.baseUrl ?? "(none)"}\nSpace/Enter to toggle.`,
|
||||||
|
toggle: () => {
|
||||||
|
// Enabling Podcast Index requires credentials: ask first
|
||||||
|
// (prefilled with the stored key, masked) instead of flipping
|
||||||
|
// the source into a key-less "on" state. Disabling never
|
||||||
|
// clears the stored credentials.
|
||||||
|
if (s.id === "podcastindex" && !s.enabled) {
|
||||||
|
dialog.push(() => <PodcastIndexCredentialsDialog />);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
feedStore.toggleSource(s.id);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,6 +123,9 @@ function AddSourceForm() {
|
|||||||
onInput={setName}
|
onInput={setName}
|
||||||
placeholder="My Custom Feed"
|
placeholder="My Custom Feed"
|
||||||
width={25}
|
width={25}
|
||||||
|
textColor={theme.text}
|
||||||
|
focusedTextColor={theme.accent}
|
||||||
|
cursorColor={theme.accent}
|
||||||
/>
|
/>
|
||||||
</box>
|
</box>
|
||||||
<box flexDirection="row" gap={1}>
|
<box flexDirection="row" gap={1}>
|
||||||
@@ -116,6 +139,9 @@ function AddSourceForm() {
|
|||||||
}}
|
}}
|
||||||
placeholder="https://example.com/feed.rss"
|
placeholder="https://example.com/feed.rss"
|
||||||
width={35}
|
width={35}
|
||||||
|
textColor={theme.text}
|
||||||
|
focusedTextColor={theme.accent}
|
||||||
|
cursorColor={theme.accent}
|
||||||
/>
|
/>
|
||||||
</box>
|
</box>
|
||||||
<box
|
<box
|
||||||
@@ -145,3 +171,152 @@ function AddSourceForm() {
|
|||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Mask a stored credential for prefill: first 3 chars then "...". */
|
||||||
|
const maskCredential = (value: string): string => `${value.slice(0, 3)}...`;
|
||||||
|
|
||||||
|
/** Credentials popup shown when enabling the Podcast Index source. Prefilled
|
||||||
|
* (masked) with stored credentials so re-enabling just needs Enter; leaving
|
||||||
|
* a masked field untouched keeps the stored value. Credentials are saved to
|
||||||
|
* the macOS keychain (encrypted at rest) with a plaintext config.json
|
||||||
|
* fallback when the keychain is unavailable. */
|
||||||
|
function PodcastIndexCredentialsDialog() {
|
||||||
|
const feedStore = useFeedStore();
|
||||||
|
const { theme } = useTheme();
|
||||||
|
const dialog = useDialog();
|
||||||
|
const toast = useToast();
|
||||||
|
const source = feedStore.sources().find((s) => s.id === "podcastindex");
|
||||||
|
const [key, setKey] = createSignal("");
|
||||||
|
const [secret, setSecret] = createSignal("");
|
||||||
|
const [error, setError] = createSignal<string | null>(null);
|
||||||
|
const [saving, setSaving] = createSignal(false);
|
||||||
|
// Yield navigation keybinds to the Shell router while an input is focused.
|
||||||
|
const keyRef = useInputFocusNav();
|
||||||
|
const secretRef = useInputFocusNav();
|
||||||
|
let keyEl: Renderable | null | undefined;
|
||||||
|
let secretEl: Renderable | null | undefined;
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
// Prefill stored credentials (masked) when re-enabling after a
|
||||||
|
// disable — toggling off never clears them. Masked either way, so a
|
||||||
|
// plaintext-stored key never appears in full in the UI.
|
||||||
|
if (source) {
|
||||||
|
resolveSourceCredentials(source)
|
||||||
|
.then((stored) => {
|
||||||
|
if (stored?.apiKey) setKey(maskCredential(stored.apiKey));
|
||||||
|
if (stored?.apiSecret) setSecret(maskCredential(stored.apiSecret));
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
setTimeout(() => keyEl?.focus(), 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
const save = async () => {
|
||||||
|
if (saving()) return;
|
||||||
|
const stored = source
|
||||||
|
? await resolveSourceCredentials(source).catch(() => null)
|
||||||
|
: null;
|
||||||
|
const keyValue = key().trim();
|
||||||
|
const secretValue = secret().trim();
|
||||||
|
// A field still showing its masked prefill means "keep what's stored".
|
||||||
|
const apiKey =
|
||||||
|
stored?.apiKey && keyValue === maskCredential(stored.apiKey)
|
||||||
|
? stored.apiKey
|
||||||
|
: keyValue;
|
||||||
|
const apiSecret =
|
||||||
|
stored?.apiSecret && secretValue === maskCredential(stored.apiSecret)
|
||||||
|
? stored.apiSecret
|
||||||
|
: secretValue;
|
||||||
|
if (!apiKey || !apiSecret) {
|
||||||
|
setError(
|
||||||
|
"Both API key and secret are required (free at podcastindex.org)",
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSaving(true);
|
||||||
|
const ok = await savePodcastIndexCredentials(apiKey, apiSecret).catch(
|
||||||
|
() => false,
|
||||||
|
);
|
||||||
|
setSaving(false);
|
||||||
|
if (!ok) {
|
||||||
|
// Keychain unavailable (non-macOS, locked, sandboxed): plaintext
|
||||||
|
// fallback on the source so the fallback search still works.
|
||||||
|
feedStore.updateSource("podcastindex", {
|
||||||
|
hasCredentials: true,
|
||||||
|
credentialStorage: "plaintext",
|
||||||
|
apiKey,
|
||||||
|
apiSecret,
|
||||||
|
enabled: true,
|
||||||
|
});
|
||||||
|
toast.show({
|
||||||
|
title: "Credentials stored in config.json",
|
||||||
|
message: "macOS keychain unavailable — API keys saved unencrypted.",
|
||||||
|
variant: "warning",
|
||||||
|
});
|
||||||
|
dialog.pop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
feedStore.updateSource("podcastindex", {
|
||||||
|
hasCredentials: true,
|
||||||
|
credentialStorage: "keychain",
|
||||||
|
enabled: true,
|
||||||
|
});
|
||||||
|
dialog.pop();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<box
|
||||||
|
border
|
||||||
|
title="Podcast Index API Keys"
|
||||||
|
padding={1}
|
||||||
|
flexDirection="column"
|
||||||
|
gap={1}
|
||||||
|
>
|
||||||
|
<text fg={theme.textMuted}>
|
||||||
|
Free key + secret from https://podcastindex.org/. Used as a
|
||||||
|
fallback when other sources return fewer than 3 results.
|
||||||
|
</text>
|
||||||
|
<box flexDirection="row" gap={1}>
|
||||||
|
<text fg={theme.text}>API Key:</text>
|
||||||
|
<input
|
||||||
|
ref={(el: Renderable | null | undefined) => {
|
||||||
|
keyRef(el);
|
||||||
|
keyEl = el;
|
||||||
|
}}
|
||||||
|
value={key()}
|
||||||
|
onInput={setKey}
|
||||||
|
onSubmit={() => secretEl?.focus()}
|
||||||
|
placeholder="e.g. UXKCGDSYGUUEVQJSYDZH"
|
||||||
|
width={30}
|
||||||
|
textColor={theme.text}
|
||||||
|
focusedTextColor={theme.accent}
|
||||||
|
cursorColor={theme.accent}
|
||||||
|
/>
|
||||||
|
</box>
|
||||||
|
<box flexDirection="row" gap={1}>
|
||||||
|
<text fg={theme.text}>API Secret:</text>
|
||||||
|
<input
|
||||||
|
ref={(el: Renderable | null | undefined) => {
|
||||||
|
secretRef(el);
|
||||||
|
secretEl = el;
|
||||||
|
}}
|
||||||
|
value={secret()}
|
||||||
|
onInput={setSecret}
|
||||||
|
onSubmit={() => save()}
|
||||||
|
placeholder="e.g. yzJe2eE7XV-3eY576dyRZ6wXyAbndh6LUrCZ8KN|"
|
||||||
|
width={40}
|
||||||
|
textColor={theme.text}
|
||||||
|
focusedTextColor={theme.accent}
|
||||||
|
cursorColor={theme.accent}
|
||||||
|
/>
|
||||||
|
</box>
|
||||||
|
<Show when={error()}>{(e) => <text fg={theme.error}>{e()}</text>}</Show>
|
||||||
|
<Show when={saving()}>
|
||||||
|
<text fg={theme.textMuted}>Storing credentials...</text>
|
||||||
|
</Show>
|
||||||
|
<text fg={theme.textMuted}>
|
||||||
|
[Enter] save · [Esc] cancel — keys stay stored when disabled.
|
||||||
|
</text>
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -11,6 +11,15 @@ export function useVisualizerItems(): SettingItem[] {
|
|||||||
const viz = () => app.state().settings.visualizer;
|
const viz = () => app.state().settings.visualizer;
|
||||||
|
|
||||||
return [
|
return [
|
||||||
|
{
|
||||||
|
id: "enabled",
|
||||||
|
label: "Waveform",
|
||||||
|
kind: "toggle",
|
||||||
|
display: () => (viz().enabled ? "On" : "Off"),
|
||||||
|
help: () =>
|
||||||
|
`Realtime waveform visualizer in the player.\nType: toggle\nDefault: on\nCurrent: ${viz().enabled ? "on" : "off"}\nSpace/Enter to toggle.`,
|
||||||
|
toggle: () => app.updateVisualizer({ enabled: !viz().enabled }),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: "bars",
|
id: "bars",
|
||||||
label: "Bars",
|
label: "Bars",
|
||||||
|
|||||||
@@ -41,5 +41,7 @@ export interface SettingsSectionDef {
|
|||||||
id: number;
|
id: number;
|
||||||
label: string;
|
label: string;
|
||||||
description: string;
|
description: string;
|
||||||
|
/** Nerd Font glyph for the section row (rendered only when supported). */
|
||||||
|
icon: string;
|
||||||
items?: () => SettingItem[];
|
items?: () => SettingItem[];
|
||||||
}
|
}
|
||||||
|
|||||||
75
src/stores/activity.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
/**
|
||||||
|
* Activity store for PodTUI
|
||||||
|
*
|
||||||
|
* Shared leak-proof activity counter: any store can surface "something is
|
||||||
|
* loading/downloading" to the global top-right indicator. beginActivity
|
||||||
|
* returns an end token that removes exactly THAT instance, so concurrent
|
||||||
|
* overlapping activities compose correctly; prefer track() so callers
|
||||||
|
* cannot strand the counter.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { createSignal } from "solid-js";
|
||||||
|
|
||||||
|
/** Create activity store */
|
||||||
|
function createActivityStore() {
|
||||||
|
const [count, setCount] = createSignal(0);
|
||||||
|
const [labels, setLabels] = createSignal<string[]>([]);
|
||||||
|
|
||||||
|
/** Begin a tracked activity and return its end function. Every begin
|
||||||
|
* MUST be paired with exactly one call of the returned end (via the
|
||||||
|
* token); prefer track() so the pairing is automatic. Duplicate labels
|
||||||
|
* are allowed — each end removes exactly one instance (found by
|
||||||
|
* indexOf). */
|
||||||
|
const beginActivity = (label: string): (() => void) => {
|
||||||
|
setLabels((prev) => [...prev, label]);
|
||||||
|
setCount((c) => c + 1);
|
||||||
|
let ended = false;
|
||||||
|
return () => {
|
||||||
|
if (ended) return;
|
||||||
|
ended = true;
|
||||||
|
setLabels((prev) => {
|
||||||
|
const idx = prev.indexOf(label);
|
||||||
|
if (idx === -1) return prev;
|
||||||
|
const next = [...prev];
|
||||||
|
next.splice(idx, 1);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
setCount((c) => Math.max(0, c - 1));
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Track a promise: begin an activity, auto-end when it settles, and
|
||||||
|
* re-throw on rejection so the caller's error handling is untouched. */
|
||||||
|
const track = async <T,>(p: Promise<T>, label: string): Promise<T> => {
|
||||||
|
const end = beginActivity(label);
|
||||||
|
try {
|
||||||
|
return await p;
|
||||||
|
} finally {
|
||||||
|
end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** True while at least one activity is in flight */
|
||||||
|
const isActive = (): boolean => count() > 0;
|
||||||
|
|
||||||
|
return {
|
||||||
|
// State
|
||||||
|
count,
|
||||||
|
labels,
|
||||||
|
// Actions
|
||||||
|
beginActivity,
|
||||||
|
track,
|
||||||
|
// Getters
|
||||||
|
isActive,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Singleton activity store */
|
||||||
|
let activityStoreInstance: ReturnType<typeof createActivityStore> | null = null;
|
||||||
|
|
||||||
|
export function useActivityStore() {
|
||||||
|
if (!activityStoreInstance) {
|
||||||
|
activityStoreInstance = createActivityStore();
|
||||||
|
}
|
||||||
|
return activityStoreInstance;
|
||||||
|
}
|
||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
} from "../utils/app-persistence";
|
} from "../utils/app-persistence";
|
||||||
|
|
||||||
const defaultVisualizerSettings: VisualizerSettings = {
|
const defaultVisualizerSettings: VisualizerSettings = {
|
||||||
|
enabled: true,
|
||||||
bars: 64,
|
bars: 64,
|
||||||
sensitivity: 1,
|
sensitivity: 1,
|
||||||
noiseReduction: 0.77,
|
noiseReduction: 0.77,
|
||||||
@@ -28,16 +29,22 @@ const defaultSettings: AppSettings = {
|
|||||||
theme: "system",
|
theme: "system",
|
||||||
fontSize: 14,
|
fontSize: 14,
|
||||||
playbackSpeed: 1,
|
playbackSpeed: 1,
|
||||||
|
volume: 1,
|
||||||
downloadPath: "",
|
downloadPath: "",
|
||||||
transparentBackground: false,
|
transparentBackground: false,
|
||||||
|
showSelectionMarker: false,
|
||||||
visualizer: defaultVisualizerSettings,
|
visualizer: defaultVisualizerSettings,
|
||||||
};
|
};
|
||||||
|
|
||||||
const defaultPreferences: UserPreferences = {
|
const defaultPreferences: UserPreferences = {
|
||||||
showExplicit: false,
|
showExplicit: false,
|
||||||
autoDownload: false,
|
autoDownload: false,
|
||||||
|
autoDownloadCount: 2,
|
||||||
|
autoDownloadScope: "all",
|
||||||
|
autoDownloadWhitelist: [],
|
||||||
autoJumpToPlayer: true,
|
autoJumpToPlayer: true,
|
||||||
fetchMoreMode: "manual",
|
fetchMoreMode: "auto",
|
||||||
|
refreshIntervalMinutes: 30,
|
||||||
};
|
};
|
||||||
|
|
||||||
const defaultState: AppState = {
|
const defaultState: AppState = {
|
||||||
@@ -50,12 +57,14 @@ function createAppStore() {
|
|||||||
// Start with defaults; async load will update once ready
|
// Start with defaults; async load will update once ready
|
||||||
const [state, setState] = createSignal<AppState>(defaultState);
|
const [state, setState] = createSignal<AppState>(defaultState);
|
||||||
|
|
||||||
// Fire-and-forget async initialisation
|
// Fire-and-forget async initialisation; the promise is exposed via
|
||||||
|
// whenReady() so boot-time consumers (audio-level restore) can await
|
||||||
|
// the config read before reading settings.
|
||||||
const init = async () => {
|
const init = async () => {
|
||||||
const loaded = await loadAppStateFromFile();
|
const loaded = await loadAppStateFromFile();
|
||||||
setState(loaded);
|
setState(loaded);
|
||||||
};
|
};
|
||||||
init();
|
const appInit = init();
|
||||||
|
|
||||||
const saveState = (next: AppState) => {
|
const saveState = (next: AppState) => {
|
||||||
saveAppStateToFile(next);
|
saveAppStateToFile(next);
|
||||||
@@ -114,6 +123,8 @@ function createAppStore() {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
|
/** Resolves once persisted settings are loaded from disk. */
|
||||||
|
whenReady: () => appInit,
|
||||||
updateSettings,
|
updateSettings,
|
||||||
updatePreferences,
|
updatePreferences,
|
||||||
updateCustomTheme,
|
updateCustomTheme,
|
||||||
|
|||||||
@@ -20,17 +20,17 @@ export interface DiscoverCategory {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const DISCOVER_CATEGORIES: DiscoverCategory[] = [
|
export const DISCOVER_CATEGORIES: DiscoverCategory[] = [
|
||||||
{ id: "all", name: "All", icon: "*" },
|
{ id: "all", name: "All", icon: "\uF0CA" },
|
||||||
{ id: "technology", name: "Technology", icon: ">" },
|
{ id: "technology", name: "Technology", icon: "\uF2DB" },
|
||||||
{ id: "science", name: "Science", icon: "~" },
|
{ id: "science", name: "Science", icon: "\uF0C3" },
|
||||||
{ id: "comedy", name: "Comedy", icon: ")" },
|
{ id: "comedy", name: "Comedy", icon: "\uF118" },
|
||||||
{ id: "news", name: "News", icon: "!" },
|
{ id: "news", name: "News", icon: "\uF1EA" },
|
||||||
{ id: "business", name: "Business", icon: "$" },
|
{ id: "business", name: "Business", icon: "\uF0B1" },
|
||||||
{ id: "health", name: "Health", icon: "+" },
|
{ id: "health", name: "Health", icon: "\uF21E" },
|
||||||
{ id: "education", name: "Education", icon: "?" },
|
{ id: "education", name: "Education", icon: "\uF19D" },
|
||||||
{ id: "sports", name: "Sports", icon: "#" },
|
{ id: "sports", name: "Sports", icon: "\uF1E3" },
|
||||||
{ id: "true-crime", name: "True Crime", icon: "%" },
|
{ id: "true-crime", name: "True Crime", icon: "\uF00E" },
|
||||||
{ id: "arts", name: "Arts", icon: "@" },
|
{ id: "arts", name: "Arts", icon: "\uF1FC" },
|
||||||
];
|
];
|
||||||
|
|
||||||
// ── Remote featured-shows manifest ───────────────────────────────────────────
|
// ── Remote featured-shows manifest ───────────────────────────────────────────
|
||||||
|
|||||||
@@ -10,12 +10,32 @@ import { createSignal } from "solid-js";
|
|||||||
import { DownloadStatus } from "../types/episode";
|
import { DownloadStatus } from "../types/episode";
|
||||||
import type { DownloadedEpisode } from "../types/episode";
|
import type { DownloadedEpisode } from "../types/episode";
|
||||||
import type { Episode } from "../types/episode";
|
import type { Episode } from "../types/episode";
|
||||||
|
import type { Podcast } from "../types/podcast";
|
||||||
import { downloadEpisode } from "../utils/episode-downloader";
|
import { downloadEpisode } from "../utils/episode-downloader";
|
||||||
import { ensureConfigDir, getConfigFilePath } from "../utils/config-dir";
|
import { ensureConfigDir, getConfigFilePath } from "../utils/config-dir";
|
||||||
|
import { useFeedStore } from "./feed";
|
||||||
|
|
||||||
const DOWNLOADS_FILE = "downloads.json";
|
const DOWNLOADS_FILE = "downloads.json";
|
||||||
const MAX_CONCURRENT = 2;
|
const MAX_CONCURRENT = 2;
|
||||||
|
|
||||||
|
/** Prefix for synthetic feed ids of unsubscribed-show downloads (search
|
||||||
|
* downloads). The id doubles as the file subdirectory name, so it must be
|
||||||
|
* filesystem-safe. */
|
||||||
|
const UNSUBSCRIBED_FEED_PREFIX = "unsub-";
|
||||||
|
|
||||||
|
/** Deterministic synthetic feed id for a show that isn't subscribed: groups
|
||||||
|
* its search downloads together (and names their file subdirectory) without
|
||||||
|
* colliding with real feed ids (UUIDs). */
|
||||||
|
function unsubscribedFeedId(podcast: Pick<Podcast, "feedUrl" | "title">): string {
|
||||||
|
const base = podcast.feedUrl || podcast.title;
|
||||||
|
const slug = base
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, "-")
|
||||||
|
.replace(/^-+|-+$/g, "")
|
||||||
|
.slice(0, 48);
|
||||||
|
return `${UNSUBSCRIBED_FEED_PREFIX}${slug || "podcast"}`;
|
||||||
|
}
|
||||||
|
|
||||||
/** Serializable download record for persistence */
|
/** Serializable download record for persistence */
|
||||||
interface DownloadRecord {
|
interface DownloadRecord {
|
||||||
episodeId: string;
|
episodeId: string;
|
||||||
@@ -27,6 +47,12 @@ interface DownloadRecord {
|
|||||||
error: string | null;
|
error: string | null;
|
||||||
audioUrl: string;
|
audioUrl: string;
|
||||||
episodeTitle: string;
|
episodeTitle: string;
|
||||||
|
/** ISO publication date, for unsubscribed-show downloads. */
|
||||||
|
pubDate?: string;
|
||||||
|
/** Show title, for downloads whose show isn't subscribed. */
|
||||||
|
podcastTitle?: string;
|
||||||
|
/** The show's RSS feed URL (re-classifies the download once subscribed). */
|
||||||
|
podcastFeedUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Queue item for pending downloads */
|
/** Queue item for pending downloads */
|
||||||
@@ -80,6 +106,11 @@ function createDownloadStore() {
|
|||||||
speed: 0,
|
speed: 0,
|
||||||
fileSize: rec.fileSize,
|
fileSize: rec.fileSize,
|
||||||
error: rec.error,
|
error: rec.error,
|
||||||
|
episodeTitle: rec.episodeTitle || undefined,
|
||||||
|
audioUrl: rec.audioUrl || undefined,
|
||||||
|
pubDate: rec.pubDate || undefined,
|
||||||
|
podcastTitle: rec.podcastTitle || undefined,
|
||||||
|
podcastFeedUrl: rec.podcastFeedUrl || undefined,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
@@ -105,8 +136,11 @@ function createDownloadStore() {
|
|||||||
downloadedAt: dl.downloadedAt?.toISOString() ?? null,
|
downloadedAt: dl.downloadedAt?.toISOString() ?? null,
|
||||||
fileSize: dl.fileSize,
|
fileSize: dl.fileSize,
|
||||||
error: dl.error,
|
error: dl.error,
|
||||||
audioUrl: qItem?.audioUrl ?? "",
|
audioUrl: dl.audioUrl ?? qItem?.audioUrl ?? "",
|
||||||
episodeTitle: qItem?.episodeTitle ?? "",
|
episodeTitle: dl.episodeTitle ?? qItem?.episodeTitle ?? "",
|
||||||
|
pubDate: dl.pubDate,
|
||||||
|
podcastTitle: dl.podcastTitle,
|
||||||
|
podcastFeedUrl: dl.podcastFeedUrl,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const filePath = getConfigFilePath(DOWNLOADS_FILE);
|
const filePath = getConfigFilePath(DOWNLOADS_FILE);
|
||||||
@@ -201,6 +235,73 @@ function createDownloadStore() {
|
|||||||
speed: 0,
|
speed: 0,
|
||||||
error: null,
|
error: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Write the podcast cover beside the audio so mpv's
|
||||||
|
// --cover-art-auto=exact picks it up for Now Playing art when the
|
||||||
|
// local file plays (same basename, .jpg extension — verified
|
||||||
|
// against mpv 0.41). curl, NOT fetch: Bun's fetch hangs in
|
||||||
|
// compiled binaries, so the shipped app never wrote this file.
|
||||||
|
// Falls back to the episode's own image when the feed has no
|
||||||
|
// channel cover (URL-added feeds).
|
||||||
|
const feedStore = useFeedStore();
|
||||||
|
const episode = feedStore.findEpisode(item.episodeId);
|
||||||
|
const coverUrl =
|
||||||
|
feedStore
|
||||||
|
.feeds()
|
||||||
|
.find((f) => f.id === item.feedId)?.podcast.coverUrl ??
|
||||||
|
episode?.imageUrl;
|
||||||
|
if (coverUrl && result.filePath) {
|
||||||
|
const dot = result.filePath.lastIndexOf(".");
|
||||||
|
if (dot > 0) {
|
||||||
|
const coverPath = result.filePath.slice(0, dot) + ".jpg";
|
||||||
|
Bun.spawn([
|
||||||
|
"curl",
|
||||||
|
"-sS",
|
||||||
|
"--fail",
|
||||||
|
"-m",
|
||||||
|
"8",
|
||||||
|
"--max-filesize",
|
||||||
|
"2097152",
|
||||||
|
"-o",
|
||||||
|
coverPath,
|
||||||
|
coverUrl,
|
||||||
|
])
|
||||||
|
.exited.catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tag the local file (codec-copy, no re-encode) so mpv's Now
|
||||||
|
// Playing metadata for local playback is title=episode,
|
||||||
|
// artist=podcast — the source streams carry no usable tags and
|
||||||
|
// macOS composes "title - artist" from exactly these fields.
|
||||||
|
// Atomic: ffmpeg writes a temp file, then renames into place.
|
||||||
|
if (result.filePath && episode) {
|
||||||
|
const podcastTitle =
|
||||||
|
feedStore.feeds().find((f) => f.id === item.feedId)?.podcast.title ??
|
||||||
|
downloads().get(item.episodeId)?.podcastTitle;
|
||||||
|
if (podcastTitle) {
|
||||||
|
const tmp = `${result.filePath}.tag.mp3`;
|
||||||
|
Bun.spawn([
|
||||||
|
"ffmpeg",
|
||||||
|
"-y",
|
||||||
|
"-i",
|
||||||
|
result.filePath,
|
||||||
|
"-c",
|
||||||
|
"copy",
|
||||||
|
"-metadata",
|
||||||
|
`title=${episode.title}`,
|
||||||
|
"-metadata",
|
||||||
|
`artist=${podcastTitle}`,
|
||||||
|
tmp,
|
||||||
|
])
|
||||||
|
.exited.then(async (code) => {
|
||||||
|
if (code !== 0) return;
|
||||||
|
const { renameSync } = await import("node:fs");
|
||||||
|
renameSync(tmp, result.filePath);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
updateDownload(item.episodeId, {
|
updateDownload(item.episodeId, {
|
||||||
status: DownloadStatus.FAILED,
|
status: DownloadStatus.FAILED,
|
||||||
@@ -238,8 +339,20 @@ function createDownloadStore() {
|
|||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Optional metadata for a download whose show isn't subscribed (search
|
||||||
|
* downloads) — without it the record cannot render a title or be
|
||||||
|
* re-classified once the show is subscribed. */
|
||||||
|
interface UnsubscribedMeta {
|
||||||
|
podcastTitle: string;
|
||||||
|
podcastFeedUrl?: string;
|
||||||
|
}
|
||||||
|
|
||||||
/** Start downloading an episode */
|
/** Start downloading an episode */
|
||||||
const startDownload = (episode: Episode, feedId: string): void => {
|
const startDownload = (
|
||||||
|
episode: Episode,
|
||||||
|
feedId: string,
|
||||||
|
meta?: UnsubscribedMeta,
|
||||||
|
): void => {
|
||||||
const existing = downloads().get(episode.id);
|
const existing = downloads().get(episode.id);
|
||||||
if (
|
if (
|
||||||
existing?.status === DownloadStatus.DOWNLOADING ||
|
existing?.status === DownloadStatus.DOWNLOADING ||
|
||||||
@@ -258,6 +371,11 @@ function createDownloadStore() {
|
|||||||
speed: 0,
|
speed: 0,
|
||||||
fileSize: episode.fileSize ?? 0,
|
fileSize: episode.fileSize ?? 0,
|
||||||
error: null,
|
error: null,
|
||||||
|
episodeTitle: episode.title,
|
||||||
|
audioUrl: episode.audioUrl,
|
||||||
|
pubDate: episode.pubDate.toISOString(),
|
||||||
|
podcastTitle: meta?.podcastTitle,
|
||||||
|
podcastFeedUrl: meta?.podcastFeedUrl,
|
||||||
};
|
};
|
||||||
|
|
||||||
setDownloads((prev) => {
|
setDownloads((prev) => {
|
||||||
@@ -278,6 +396,21 @@ function createDownloadStore() {
|
|||||||
processQueue();
|
processQueue();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Start downloading an episode of a show that is NOT subscribed. The
|
||||||
|
* download gets a deterministic synthetic feed id (also its file
|
||||||
|
* subdirectory) plus the show's metadata so it can render under
|
||||||
|
* "Unsubscribed Show Downloads" and re-classify if the user later
|
||||||
|
* subscribes to the show. */
|
||||||
|
const startUnsubscribedDownload = (
|
||||||
|
episode: Episode,
|
||||||
|
podcast: Podcast,
|
||||||
|
): void => {
|
||||||
|
startDownload(episode, unsubscribedFeedId(podcast), {
|
||||||
|
podcastTitle: podcast.title,
|
||||||
|
podcastFeedUrl: podcast.feedUrl || undefined,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
/** Cancel a download */
|
/** Cancel a download */
|
||||||
const cancelDownload = (episodeId: string): void => {
|
const cancelDownload = (episodeId: string): void => {
|
||||||
// Abort active download
|
// Abort active download
|
||||||
@@ -306,6 +439,11 @@ function createDownloadStore() {
|
|||||||
try {
|
try {
|
||||||
const { unlink } = await import("fs/promises");
|
const { unlink } = await import("fs/promises");
|
||||||
await unlink(dl.filePath);
|
await unlink(dl.filePath);
|
||||||
|
const dot = dl.filePath.lastIndexOf(".");
|
||||||
|
if (dot > 0) {
|
||||||
|
const coverPath = dl.filePath.slice(0, dot) + ".jpg";
|
||||||
|
await unlink(coverPath);
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// File may already be gone
|
// File may already be gone
|
||||||
}
|
}
|
||||||
@@ -321,10 +459,18 @@ function createDownloadStore() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/** Remove every download (active/queued/completed) belonging to a feed —
|
/** Remove every download (active/queued/completed) belonging to a feed —
|
||||||
* abort in-flight transfers, drop queued items, delete files + metadata. */
|
* abort in-flight transfers, drop queued items, delete files + metadata.
|
||||||
const removeDownloadsForFeed = async (feedId: string): Promise<void> => {
|
* Also removes downloads of the same show made while it was unsubscribed
|
||||||
|
* (matched by podcastFeedUrl) so unsubscribing purges search downloads
|
||||||
|
* of that show too. */
|
||||||
|
const removeDownloadsForFeed = async (
|
||||||
|
feedId: string,
|
||||||
|
podcastFeedUrl?: string,
|
||||||
|
): Promise<void> => {
|
||||||
const eps = Array.from(downloads().values()).filter(
|
const eps = Array.from(downloads().values()).filter(
|
||||||
(d) => d.feedId === feedId,
|
(d) =>
|
||||||
|
d.feedId === feedId ||
|
||||||
|
(podcastFeedUrl && d.podcastFeedUrl === podcastFeedUrl),
|
||||||
);
|
);
|
||||||
for (const d of eps) {
|
for (const d of eps) {
|
||||||
cancelDownload(d.episodeId);
|
cancelDownload(d.episodeId);
|
||||||
@@ -337,6 +483,24 @@ function createDownloadStore() {
|
|||||||
return Array.from(downloads().values());
|
return Array.from(downloads().values());
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Downloads whose show is not subscribed — the "Unsubscribed Show
|
||||||
|
* Downloads" list shown in My Shows and the settings download manager.
|
||||||
|
* Reads feeds() so the list re-classifies (drops out) the moment the
|
||||||
|
* user subscribes to the show. Matched by feed id, or by the show's
|
||||||
|
* feed URL (covers downloads made before the show was subscribed). */
|
||||||
|
const getUnsubscribedDownloads = (): DownloadedEpisode[] => {
|
||||||
|
const feeds = useFeedStore().feeds();
|
||||||
|
return Array.from(downloads().values()).filter((d) => {
|
||||||
|
if (feeds.some((f) => f.id === d.feedId)) return false;
|
||||||
|
if (d.podcastFeedUrl) {
|
||||||
|
return !feeds.some(
|
||||||
|
(f) => f.podcast.feedUrl === d.podcastFeedUrl,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
/** Get the current queue */
|
/** Get the current queue */
|
||||||
const getQueue = (): QueueItem[] => {
|
const getQueue = (): QueueItem[] => {
|
||||||
return queue();
|
return queue();
|
||||||
@@ -354,11 +518,13 @@ function createDownloadStore() {
|
|||||||
getDownload,
|
getDownload,
|
||||||
getDownloadedFilePath,
|
getDownloadedFilePath,
|
||||||
getAllDownloads,
|
getAllDownloads,
|
||||||
|
getUnsubscribedDownloads,
|
||||||
getQueue,
|
getQueue,
|
||||||
getActiveCount,
|
getActiveCount,
|
||||||
|
|
||||||
// Actions
|
// Actions
|
||||||
startDownload,
|
startDownload,
|
||||||
|
startUnsubscribedDownload,
|
||||||
cancelDownload,
|
cancelDownload,
|
||||||
removeDownload,
|
removeDownload,
|
||||||
removeDownloadsForFeed,
|
removeDownloadsForFeed,
|
||||||
|
|||||||
@@ -10,14 +10,19 @@ import type { Podcast } from "../types/podcast";
|
|||||||
import type { Episode } from "../types/episode";
|
import type { Episode } from "../types/episode";
|
||||||
import type { PodcastSource } from "../types/source";
|
import type { PodcastSource } from "../types/source";
|
||||||
import { DEFAULT_SOURCES } from "../types/source";
|
import { DEFAULT_SOURCES } from "../types/source";
|
||||||
import { parseRSSFeed } from "../api/rss-parser";
|
import { getRSSItems, parseRSSItem, parseChannelCoverUrl } from "../api/rss-parser";
|
||||||
|
import { resolveItunesFeedUrl } from "../utils/itunes-feed-resolver";
|
||||||
|
import { savePodcastIndexCredentials } from "../utils/source-credentials";
|
||||||
|
import { mergeEpisodes } from "../utils/episode-merge";
|
||||||
import {
|
import {
|
||||||
loadFeedsFromFile,
|
loadFeedsFromFile,
|
||||||
saveFeedsToFile,
|
saveFeedsToFile,
|
||||||
loadSourcesFromFile,
|
loadSourcesFromFile,
|
||||||
saveSourcesToFile,
|
saveSourcesToFile,
|
||||||
} from "../utils/feeds-persistence";
|
} from "../utils/feeds-persistence";
|
||||||
|
import { useActivityStore } from "./activity";
|
||||||
import { useDownloadStore } from "./download";
|
import { useDownloadStore } from "./download";
|
||||||
|
import { useAppStore } from "./app";
|
||||||
import { DownloadStatus } from "../types/episode";
|
import { DownloadStatus } from "../types/episode";
|
||||||
|
|
||||||
/** Max episodes to load per page/chunk */
|
/** Max episodes to load per page/chunk */
|
||||||
@@ -26,6 +31,68 @@ const MAX_EPISODES_REFRESH = 50;
|
|||||||
/** Max episodes to fetch on initial subscribe */
|
/** Max episodes to fetch on initial subscribe */
|
||||||
const MAX_EPISODES_SUBSCRIBE = 20;
|
const MAX_EPISODES_SUBSCRIBE = 20;
|
||||||
|
|
||||||
|
/** Per-feed bound on both the cached parse results and the merged in-memory
|
||||||
|
* window; 500 covers years of a weekly show's history while capping a
|
||||||
|
* 20-subscription install at 10k episodes. */
|
||||||
|
export const MAX_EPISODES_IN_MEMORY = 500;
|
||||||
|
|
||||||
|
/** Per-feed fetch timeout — a hung feed must not stall a refresh batch or
|
||||||
|
* the background refresh loop. */
|
||||||
|
const FETCH_TIMEOUT_MS = 20_000;
|
||||||
|
|
||||||
|
/** Bounds simultaneous RSS requests during a refresh batch — a hung feed
|
||||||
|
* burns at most one slot for FETCH_TIMEOUT_MS instead of pinning the whole
|
||||||
|
* batch. */
|
||||||
|
const FETCH_CONCURRENCY = 4;
|
||||||
|
|
||||||
|
/** Default minutes between automatic background feed refreshes. */
|
||||||
|
const DEFAULT_REFRESH_INTERVAL_MINUTES = 30;
|
||||||
|
|
||||||
|
/** Max episodes parsed per chunk before yielding to the event loop — bounds
|
||||||
|
* the synchronous regex work per frame so one huge feed (or a batch of
|
||||||
|
* feeds) can't stall the renderer. */
|
||||||
|
const PARSE_CHUNK_SIZE = 5;
|
||||||
|
|
||||||
|
/** Yield to the event loop (task queue) so the renderer can paint between
|
||||||
|
* parse chunks. MessageChannel instead of setTimeout/setImmediate because
|
||||||
|
* bun:test fake timers trap those (feed-refresh/pagination tests run under
|
||||||
|
* vi.useFakeTimers and await refreshes, so a trapped yield would deadlock
|
||||||
|
* them); MessageChannel posts are real task-queue turns that fire in both
|
||||||
|
* environments. */
|
||||||
|
const yieldToUI = (): Promise<void> =>
|
||||||
|
new Promise((resolve) => {
|
||||||
|
const { port1, port2 } = new MessageChannel();
|
||||||
|
port1.onmessage = () => {
|
||||||
|
port1.close();
|
||||||
|
port2.close();
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
port2.postMessage(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Parse all episodes from feed XML in bounded chunks, yielding to the event
|
||||||
|
* loop between chunks. The whole-feed sync `parseRSSFeed` would otherwise
|
||||||
|
* block the UI thread for the combined parse time of every feed in a
|
||||||
|
* refresh batch. */
|
||||||
|
const parseEpisodesIncremental = async (
|
||||||
|
xml: string,
|
||||||
|
feedUrl: string,
|
||||||
|
): Promise<Episode[]> => {
|
||||||
|
const items = getRSSItems(xml);
|
||||||
|
// Yield after the item-extraction regex (which scans the full XML
|
||||||
|
// synchronously) so the renderer paints before the first parse chunk.
|
||||||
|
await yieldToUI();
|
||||||
|
const episodes: Episode[] = new Array(items.length);
|
||||||
|
for (let start = 0; start < items.length; start += PARSE_CHUNK_SIZE) {
|
||||||
|
const end = Math.min(start + PARSE_CHUNK_SIZE, items.length);
|
||||||
|
for (let i = start; i < end; i++) {
|
||||||
|
episodes[i] = parseRSSItem(items[i], feedUrl, i);
|
||||||
|
}
|
||||||
|
if (end < items.length) await yieldToUI();
|
||||||
|
}
|
||||||
|
return episodes;
|
||||||
|
};
|
||||||
|
|
||||||
/** Cache of all parsed episodes per feed (feedId -> Episode[]) */
|
/** Cache of all parsed episodes per feed (feedId -> Episode[]) */
|
||||||
const fullEpisodeCache = new Map<string, Episode[]>();
|
const fullEpisodeCache = new Map<string, Episode[]>();
|
||||||
|
|
||||||
@@ -42,6 +109,88 @@ function saveSources(sources: PodcastSource[]): void {
|
|||||||
saveSourcesToFile(sources);
|
saveSourcesToFile(sources);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Move plaintext apiKey/apiSecret (pre-keychain persistence) into the macOS
|
||||||
|
* keychain, marking the source hasCredentials and stripping the plaintext.
|
||||||
|
* When the keychain is unavailable the plaintext stays (marked as the
|
||||||
|
* plaintext storage backend) so the source keeps working.
|
||||||
|
* Returns the same array when nothing needed migrating. */
|
||||||
|
async function migratePlaintextCredentials(
|
||||||
|
sources: PodcastSource[],
|
||||||
|
): Promise<PodcastSource[]> {
|
||||||
|
let changed = false;
|
||||||
|
const migrated: PodcastSource[] = [];
|
||||||
|
for (const source of sources) {
|
||||||
|
if (
|
||||||
|
source.id === "podcastindex" &&
|
||||||
|
source.apiKey &&
|
||||||
|
source.apiSecret &&
|
||||||
|
!source.hasCredentials
|
||||||
|
) {
|
||||||
|
const ok = await savePodcastIndexCredentials(
|
||||||
|
source.apiKey,
|
||||||
|
source.apiSecret,
|
||||||
|
);
|
||||||
|
if (ok) {
|
||||||
|
migrated.push({
|
||||||
|
...source,
|
||||||
|
apiKey: undefined,
|
||||||
|
apiSecret: undefined,
|
||||||
|
hasCredentials: true,
|
||||||
|
credentialStorage: "keychain",
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
migrated.push({
|
||||||
|
...source,
|
||||||
|
hasCredentials: true,
|
||||||
|
credentialStorage: "plaintext",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
changed = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
migrated.push(source);
|
||||||
|
}
|
||||||
|
return changed ? migrated : sources;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when the freshly fetched window matches the corresponding PREFIX of
|
||||||
|
* the existing episode list (id-set equality, order-insensitive). With
|
||||||
|
* union semantics the merged list legitimately contains episodes BEYOND the
|
||||||
|
* fetched window, so unchanged-detection must compare the fetched window
|
||||||
|
* against the existing list's prefix — comparing full lists would bump
|
||||||
|
* `lastUpdated` on every refresh. */
|
||||||
|
function sameRefreshWindow(existing: Episode[], fetched: Episode[]): boolean {
|
||||||
|
if (fetched.length === 0) return true;
|
||||||
|
const prefix = existing.slice(0, fetched.length);
|
||||||
|
const ids = new Set(prefix.map((e) => e.id));
|
||||||
|
return fetched.every((e) => ids.has(e.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Run `fn` over every item with at most `limit` executions in flight — a
|
||||||
|
* classic worker pool. Workers pull indexes from a shared counter, so the
|
||||||
|
* first `limit` calls start immediately and each completion frees its slot
|
||||||
|
* for the next item; results are assembled in INPUT order regardless of
|
||||||
|
* completion order. A hung `fn` holds at most one slot. */
|
||||||
|
async function mapWithConcurrency<T, R>(
|
||||||
|
items: T[],
|
||||||
|
limit: number,
|
||||||
|
fn: (item: T) => Promise<R>,
|
||||||
|
): Promise<R[]> {
|
||||||
|
const results = new Array<R>(items.length);
|
||||||
|
let nextIndex = 0;
|
||||||
|
const workers = Array.from(
|
||||||
|
{ length: Math.min(limit, items.length) },
|
||||||
|
async () => {
|
||||||
|
let i: number;
|
||||||
|
while ((i = nextIndex++) < items.length) {
|
||||||
|
results[i] = await fn(items[i]);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await Promise.all(workers);
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
/** Create feed store */
|
/** Create feed store */
|
||||||
function createFeedStore() {
|
function createFeedStore() {
|
||||||
const [feeds, setFeeds] = createSignal<Feed[]>([]);
|
const [feeds, setFeeds] = createSignal<Feed[]>([]);
|
||||||
@@ -57,6 +206,39 @@ function createFeedStore() {
|
|||||||
const [isLoadingMore, setIsLoadingMore] = createSignal(false);
|
const [isLoadingMore, setIsLoadingMore] = createSignal(false);
|
||||||
const [isLoadingFeeds, setIsLoadingFeeds] = createSignal(false);
|
const [isLoadingFeeds, setIsLoadingFeeds] = createSignal(false);
|
||||||
|
|
||||||
|
// ── Debounced persistence ───────────────────────────────────────────────
|
||||||
|
/** Trailing-edge debounce window for config.json writes. */
|
||||||
|
const SAVE_DEBOUNCE_MS = 250;
|
||||||
|
/** True when a save is scheduled but has not flushed yet. */
|
||||||
|
let savePending = false;
|
||||||
|
let pendingSaveTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
|
/** Schedule a config.json write (trailing edge) — rapid state changes
|
||||||
|
* (a refresh batch landing feed-by-feed, pin toggles, load-more pages)
|
||||||
|
* collapse into one final write instead of one file rewrite per step. */
|
||||||
|
const scheduleSaveFeeds = (): void => {
|
||||||
|
savePending = true;
|
||||||
|
if (pendingSaveTimer) clearTimeout(pendingSaveTimer);
|
||||||
|
pendingSaveTimer = setTimeout(() => {
|
||||||
|
pendingSaveTimer = null;
|
||||||
|
flushPendingSave();
|
||||||
|
}, SAVE_DEBOUNCE_MS);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Persist immediately when anything is dirty; exported for tests and
|
||||||
|
* quit hooks. Cancels a pending debounced save — the state it would
|
||||||
|
* have written is already reflected in feeds(), so writing now is
|
||||||
|
* strictly more current. */
|
||||||
|
const flushPendingSave = (): void => {
|
||||||
|
if (pendingSaveTimer) {
|
||||||
|
clearTimeout(pendingSaveTimer);
|
||||||
|
pendingSaveTimer = null;
|
||||||
|
}
|
||||||
|
if (!savePending) return;
|
||||||
|
savePending = false;
|
||||||
|
saveFeeds(feeds());
|
||||||
|
};
|
||||||
|
|
||||||
/** Get filtered and sorted feeds */
|
/** Get filtered and sorted feeds */
|
||||||
const getFilteredFeeds = (): Feed[] => {
|
const getFilteredFeeds = (): Feed[] => {
|
||||||
let result = [...feeds()];
|
let result = [...feeds()];
|
||||||
@@ -143,33 +325,49 @@ function createFeedStore() {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Fetch latest episodes from an RSS feed URL, caching all parsed episodes */
|
/** Fetch latest episodes from an RSS feed URL, caching all parsed episodes.
|
||||||
|
* Returns NULL when the feed could not be fetched (network error, non-OK
|
||||||
|
/** Fetch latest episodes from an RSS feed URL, caching all parsed episodes.
|
||||||
|
* Also returns the channel-level artwork so callers can backfill a feed's
|
||||||
|
* coverUrl (subscribe + refresh). Null episodes on any failure — a
|
||||||
|
* failed fetch must not look like an empty feed, or the store would wipe
|
||||||
|
* a subscribed show's episodes. */
|
||||||
const fetchEpisodes = async (
|
const fetchEpisodes = async (
|
||||||
feedUrl: string,
|
feedUrl: string,
|
||||||
limit: number,
|
limit: number,
|
||||||
feedId?: string,
|
feedId?: string,
|
||||||
): Promise<Episode[]> => {
|
): Promise<{ episodes: Episode[] | null; coverUrl: string | undefined }> => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(feedUrl, {
|
const response = await fetch(feedUrl, {
|
||||||
headers: {
|
headers: {
|
||||||
"Accept-Encoding": "identity",
|
"Accept-Encoding": "identity",
|
||||||
Accept: "application/rss+xml, application/xml, text/xml, */*",
|
Accept: "application/rss+xml, application/xml, text/xml, */*",
|
||||||
},
|
},
|
||||||
|
// Hung feeds must not stall a refresh batch (or the
|
||||||
|
// background refresh loop) indefinitely.
|
||||||
|
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||||
});
|
});
|
||||||
if (!response.ok) return [];
|
if (!response.ok) return { episodes: null, coverUrl: undefined };
|
||||||
const xml = await response.text();
|
const xml = await response.text();
|
||||||
const parsed = parseRSSFeed(xml, feedUrl);
|
// Yield after the network read so the renderer gets a turn
|
||||||
const allEpisodes = sortEpisodesReverseChronological(parsed.episodes);
|
// before the sync regex + parse work begins.
|
||||||
|
await yieldToUI();
|
||||||
|
const allEpisodes = sortEpisodesReverseChronological(
|
||||||
|
await parseEpisodesIncremental(xml, feedUrl),
|
||||||
|
);
|
||||||
|
|
||||||
// Cache all parsed episodes for pagination
|
// Cache all parsed episodes for pagination
|
||||||
if (feedId) {
|
if (feedId) {
|
||||||
fullEpisodeCache.set(feedId, allEpisodes);
|
fullEpisodeCache.set(feedId, allEpisodes.slice(0, MAX_EPISODES_IN_MEMORY));
|
||||||
episodeLoadCount.set(feedId, Math.min(limit, allEpisodes.length));
|
episodeLoadCount.set(feedId, Math.min(limit, allEpisodes.length));
|
||||||
}
|
}
|
||||||
|
|
||||||
return allEpisodes.slice(0, limit);
|
return {
|
||||||
|
episodes: allEpisodes.slice(0, limit),
|
||||||
|
coverUrl: parseChannelCoverUrl(xml),
|
||||||
|
};
|
||||||
} catch {
|
} catch {
|
||||||
return [];
|
return { episodes: null, coverUrl: undefined };
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -184,21 +382,40 @@ function createFeedStore() {
|
|||||||
sourceId: string,
|
sourceId: string,
|
||||||
visibility: FeedVisibility = FeedVisibility.PUBLIC,
|
visibility: FeedVisibility = FeedVisibility.PUBLIC,
|
||||||
): Promise<Feed | null> => {
|
): Promise<Feed | null> => {
|
||||||
|
const activity = useActivityStore();
|
||||||
|
// The "Subscribing" label covers the directory-resolve + subscribe
|
||||||
|
// fetch stretch — the gaps no existing signal (isLoadingFeeds,
|
||||||
|
// per-pane spinners) covers.
|
||||||
|
return activity.track((async () => {
|
||||||
|
// A directory stub (e.g. a show delisted from Apple Podcasts) has no
|
||||||
|
// feed URL; resolve the real feed from its directory page before
|
||||||
|
// subscribing. Refuse when it can't be resolved rather than adding a
|
||||||
|
// broken feed.
|
||||||
|
if (!podcast.feedUrl) {
|
||||||
|
if (!podcast.directoryUrl) return null;
|
||||||
|
const resolved = await resolveItunesFeedUrl(podcast.directoryUrl);
|
||||||
|
if (!resolved) return null;
|
||||||
|
podcast = { ...podcast, feedUrl: resolved, directoryUrl: undefined };
|
||||||
|
}
|
||||||
|
|
||||||
// Guard: don't add a feed we already have (matched by feedUrl)
|
// Guard: don't add a feed we already have (matched by feedUrl)
|
||||||
if (hasFeedByUrl(podcast.feedUrl)) {
|
if (hasFeedByUrl(podcast.feedUrl)) {
|
||||||
return feeds().find((f) => f.podcast.feedUrl === podcast.feedUrl) ?? null;
|
return feeds().find((f) => f.podcast.feedUrl === podcast.feedUrl) ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const feedId = crypto.randomUUID();
|
const feedId = crypto.randomUUID();
|
||||||
const episodes = await fetchEpisodes(
|
const { episodes, coverUrl } = await fetchEpisodes(
|
||||||
podcast.feedUrl,
|
podcast.feedUrl,
|
||||||
MAX_EPISODES_SUBSCRIBE,
|
MAX_EPISODES_SUBSCRIBE,
|
||||||
feedId,
|
feedId,
|
||||||
);
|
);
|
||||||
|
if (!podcast.coverUrl && coverUrl) {
|
||||||
|
podcast = { ...podcast, coverUrl };
|
||||||
|
}
|
||||||
const newFeed: Feed = {
|
const newFeed: Feed = {
|
||||||
id: feedId,
|
id: feedId,
|
||||||
podcast,
|
podcast,
|
||||||
episodes,
|
episodes: episodes ?? [],
|
||||||
visibility,
|
visibility,
|
||||||
sourceId,
|
sourceId,
|
||||||
lastUpdated: new Date(),
|
lastUpdated: new Date(),
|
||||||
@@ -206,91 +423,222 @@ function createFeedStore() {
|
|||||||
};
|
};
|
||||||
setFeeds((prev) => {
|
setFeeds((prev) => {
|
||||||
const updated = [...prev, newFeed];
|
const updated = [...prev, newFeed];
|
||||||
saveFeeds(updated);
|
scheduleSaveFeeds();
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
|
// Global auto-download: newly subscribed shows join the next pass.
|
||||||
|
runAutoDownload();
|
||||||
return newFeed;
|
return newFeed;
|
||||||
|
})(), "Subscribing");
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Auto-download newest episodes for a feed */
|
/** Download the N most recent episodes of every in-scope show, per the
|
||||||
const autoDownloadEpisodes = (
|
* global auto-download preferences (master toggle + scope + whitelist +
|
||||||
feedId: string,
|
* count). Skips episodes already downloaded, queued, or in flight;
|
||||||
newEpisodes: Episode[],
|
* retries failed ones. Idempotent — safe to run after any settings
|
||||||
count: number,
|
* change, feed refresh, or subscribe. */
|
||||||
) => {
|
const runAutoDownload = (): void => {
|
||||||
|
const app = useAppStore();
|
||||||
|
const prefs = app.state().preferences;
|
||||||
|
if (!prefs.autoDownload || prefs.autoDownloadScope === "none") return;
|
||||||
|
const whitelist = prefs.autoDownloadWhitelist ?? [];
|
||||||
|
const count = Math.max(1, prefs.autoDownloadCount ?? 2);
|
||||||
const dlStore = useDownloadStore();
|
const dlStore = useDownloadStore();
|
||||||
// Sort by pubDate descending (newest first)
|
for (const feed of feeds()) {
|
||||||
const sorted = [...newEpisodes].sort(
|
if (
|
||||||
|
prefs.autoDownloadScope === "whitelist" &&
|
||||||
|
!whitelist.includes(feed.id)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const sorted = [...feed.episodes].sort(
|
||||||
(a, b) => b.pubDate.getTime() - a.pubDate.getTime(),
|
(a, b) => b.pubDate.getTime() - a.pubDate.getTime(),
|
||||||
);
|
);
|
||||||
// count = 0 means download all new episodes
|
for (const ep of sorted.slice(0, count)) {
|
||||||
const toDownload = count > 0 ? sorted.slice(0, count) : sorted;
|
|
||||||
for (const ep of toDownload) {
|
|
||||||
const status = dlStore.getDownloadStatus(ep.id);
|
const status = dlStore.getDownloadStatus(ep.id);
|
||||||
if (
|
if (
|
||||||
status === DownloadStatus.NONE ||
|
status === DownloadStatus.NONE ||
|
||||||
status === DownloadStatus.FAILED
|
status === DownloadStatus.FAILED
|
||||||
) {
|
) {
|
||||||
dlStore.startDownload(ep, feedId);
|
dlStore.startDownload(ep, feed.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Apply a freshly fetched episode list to one feed, bumping `lastUpdated`
|
||||||
|
* only when the content actually changed (see sameRefreshWindow). The
|
||||||
|
* fetched window is MERGED into the existing episodes (fetched copy wins
|
||||||
|
* on id collision) so a refresh never shrinks the in-memory list; the
|
||||||
|
* union is capped at MAX_EPISODES_IN_MEMORY. Returns the ORIGINAL array
|
||||||
|
* reference when nothing changed so callers skip persistence entirely —
|
||||||
|
* a refresh that fetched identical episodes must not re-sort the
|
||||||
|
* "updated" view. */
|
||||||
|
const applyRefreshedEpisodes = (
|
||||||
|
prev: Feed[],
|
||||||
|
feedId: string,
|
||||||
|
episodes: Episode[],
|
||||||
|
): Feed[] => {
|
||||||
|
let changed = false;
|
||||||
|
const updated = prev.map((f) => {
|
||||||
|
if (f.id !== feedId) return f;
|
||||||
|
const merged = mergeEpisodes(f.episodes, episodes, MAX_EPISODES_IN_MEMORY);
|
||||||
|
if (sameRefreshWindow(f.episodes, episodes)) return f;
|
||||||
|
changed = true;
|
||||||
|
return { ...f, episodes: merged, lastUpdated: new Date() };
|
||||||
|
});
|
||||||
|
return changed ? updated : prev;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Refresh a single feed - re-fetch latest 50 episodes */
|
/** Refresh a single feed - re-fetch latest 50 episodes */
|
||||||
const refreshFeed = async (feedId: string) => {
|
const refreshFeed = async (feedId: string) => {
|
||||||
|
const activity = useActivityStore();
|
||||||
|
return activity.track((async () => {
|
||||||
const feed = getFeed(feedId);
|
const feed = getFeed(feedId);
|
||||||
if (!feed) return;
|
if (!feed) return;
|
||||||
const oldEpisodeIds = new Set(feed.episodes.map((e) => e.id));
|
const { episodes, coverUrl } = await fetchEpisodes(
|
||||||
const episodes = await fetchEpisodes(
|
|
||||||
feed.podcast.feedUrl,
|
feed.podcast.feedUrl,
|
||||||
MAX_EPISODES_REFRESH,
|
MAX_EPISODES_REFRESH,
|
||||||
feedId,
|
feedId,
|
||||||
);
|
);
|
||||||
|
// Fetch failed (null): keep the currently loaded episodes untouched.
|
||||||
|
if (!episodes) return;
|
||||||
setFeeds((prev) => {
|
setFeeds((prev) => {
|
||||||
const updated = prev.map((f) =>
|
let updated = applyRefreshedEpisodes(prev, feedId, episodes);
|
||||||
f.id === feedId ? { ...f, episodes, lastUpdated: new Date() } : f,
|
if (coverUrl) {
|
||||||
|
updated = updated.map((f) =>
|
||||||
|
f.id === feedId && !f.podcast.coverUrl && coverUrl
|
||||||
|
? { ...f, podcast: { ...f.podcast, coverUrl } }
|
||||||
|
: f,
|
||||||
);
|
);
|
||||||
saveFeeds(updated);
|
}
|
||||||
|
if (updated !== prev) scheduleSaveFeeds();
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
|
|
||||||
// Auto-download new episodes if enabled for this feed
|
// Global auto-download: ensure the N most recent episodes of in-scope
|
||||||
if (feed.autoDownload) {
|
// shows are available offline after every refresh (idempotent).
|
||||||
const newEpisodes = episodes.filter((e) => !oldEpisodeIds.has(e.id));
|
runAutoDownload();
|
||||||
if (newEpisodes.length > 0) {
|
})(), "Refreshing");
|
||||||
autoDownloadEpisodes(feedId, newEpisodes, feed.autoDownloadCount ?? 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Refresh all feeds */
|
/** Refresh all feeds — bounded concurrency (at most FETCH_CONCURRENCY
|
||||||
|
* in-flight requests), and each feed's refreshed episodes are applied
|
||||||
|
* AS ITS OWN FETCH LANDS (no Promise.all barrier). Per-feed apply is
|
||||||
|
* safe because applyRefreshedEpisodes keeps unchanged feeds' object
|
||||||
|
* identity and lastUpdated (union merge), so each feed's refreshed
|
||||||
|
* episodes render as its own fetch resolves — the order flapping the
|
||||||
|
* old atomic barrier existed to hide can no longer happen. */
|
||||||
const refreshAllFeeds = async () => {
|
const refreshAllFeeds = async () => {
|
||||||
setIsLoadingFeeds(true);
|
setIsLoadingFeeds(true);
|
||||||
try {
|
try {
|
||||||
const currentFeeds = feeds();
|
await mapWithConcurrency(
|
||||||
for (const feed of currentFeeds) {
|
feeds(),
|
||||||
await refreshFeed(feed.id);
|
FETCH_CONCURRENCY,
|
||||||
|
async (feed) => {
|
||||||
|
const { episodes, coverUrl } = await fetchEpisodes(
|
||||||
|
feed.podcast.feedUrl,
|
||||||
|
MAX_EPISODES_REFRESH,
|
||||||
|
feed.id,
|
||||||
|
);
|
||||||
|
// A failed fetch (null) leaves that feed untouched.
|
||||||
|
if (!episodes) return;
|
||||||
|
setFeeds((prev) => {
|
||||||
|
let updated = applyRefreshedEpisodes(prev, feed.id, episodes);
|
||||||
|
if (coverUrl) {
|
||||||
|
updated = updated.map((f) =>
|
||||||
|
f.id === feed.id && !f.podcast.coverUrl && coverUrl
|
||||||
|
? { ...f, podcast: { ...f.podcast, coverUrl } }
|
||||||
|
: f,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
if (updated !== prev) scheduleSaveFeeds();
|
||||||
|
return updated;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
// Global auto-download: one idempotent pass after the batch.
|
||||||
|
runAutoDownload();
|
||||||
|
// A refresh batch always ends with a persisted write when
|
||||||
|
// anything changed — never leave the debounce's trailing edge
|
||||||
|
// pending across a process exit.
|
||||||
|
flushPendingSave();
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoadingFeeds(false);
|
setIsLoadingFeeds(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Resolves once the persisted feeds are loaded and visible to feeds() —
|
||||||
|
// before the background refresh so boot-time consumers (player-session
|
||||||
|
// restore) don't wait on the network.
|
||||||
|
const { promise: feedsReady, resolve: resolveFeedsReady } =
|
||||||
|
Promise.withResolvers<void>();
|
||||||
(async () => {
|
(async () => {
|
||||||
const loadedFeeds = await loadFeedsFromFile();
|
const loadedFeeds = await loadFeedsFromFile();
|
||||||
if (loadedFeeds.length > 0) setFeeds(loadedFeeds);
|
if (loadedFeeds.length > 0) setFeeds(loadedFeeds);
|
||||||
|
resolveFeedsReady();
|
||||||
const loadedSources = await loadSourcesFromFile<PodcastSource>();
|
const loadedSources = await loadSourcesFromFile<PodcastSource>();
|
||||||
if (loadedSources && loadedSources.length > 0) setSources(loadedSources);
|
// The default "rss" placeholder source fabricated fake search results
|
||||||
|
// and was removed from DEFAULT_SOURCES; drop it from persisted configs
|
||||||
|
// too. User-added custom feeds keep their own ids and are untouched.
|
||||||
|
const migratedSources =
|
||||||
|
loadedSources?.filter((source) => source.id !== "rss") ?? [];
|
||||||
|
// Default sources fill gaps in persisted configs (so new defaults like
|
||||||
|
// the Podcast Index fallback reach existing installs), while a
|
||||||
|
// persisted source with the same id always wins over its default —
|
||||||
|
// user edits (keys, enabled, country) are never clobbered.
|
||||||
|
const mergedSources = [
|
||||||
|
...migratedSources,
|
||||||
|
...DEFAULT_SOURCES.filter(
|
||||||
|
(defaultSource) =>
|
||||||
|
!migratedSources.some((s) => s.id === defaultSource.id),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
if (mergedSources.length > 0) {
|
||||||
|
// One-time credential migration: sources persisted with plaintext
|
||||||
|
// apiKey/apiSecret (pre-keychain builds) move into the macOS
|
||||||
|
// keychain and are stripped from config.json.
|
||||||
|
const secured = await migratePlaintextCredentials(mergedSources);
|
||||||
|
setSources(secured);
|
||||||
|
if (secured !== mergedSources) saveSources(secured);
|
||||||
|
}
|
||||||
await refreshAllFeeds();
|
await refreshAllFeeds();
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
// ── Background refresh ──────────────────────────────────────────────────
|
||||||
|
// New episodes only reach the app while it runs if feeds are re-fetched
|
||||||
|
// on a schedule: startup and manual `r` alone leave a subscribed show's
|
||||||
|
// latest episode invisible until the user restarts (or presses r). A
|
||||||
|
// self-rescheduling timer re-reads the interval preference on every tick
|
||||||
|
// so a settings change takes effect without a restart, and skips a tick
|
||||||
|
// that would overlap an in-flight refresh (manual or background).
|
||||||
|
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
const scheduleNextRefresh = () => {
|
||||||
|
if (refreshTimer) clearTimeout(refreshTimer);
|
||||||
|
const minutes = Math.max(
|
||||||
|
1,
|
||||||
|
useAppStore().state().preferences.refreshIntervalMinutes ??
|
||||||
|
DEFAULT_REFRESH_INTERVAL_MINUTES,
|
||||||
|
);
|
||||||
|
refreshTimer = setTimeout(() => {
|
||||||
|
if (!isLoadingFeeds()) {
|
||||||
|
refreshAllFeeds().catch(() => {});
|
||||||
|
}
|
||||||
|
scheduleNextRefresh();
|
||||||
|
}, minutes * 60_000);
|
||||||
|
};
|
||||||
|
scheduleNextRefresh();
|
||||||
|
|
||||||
/** Remove a feed */
|
/** Remove a feed */
|
||||||
const removeFeed = (feedId: string) => {
|
const removeFeed = (feedId: string) => {
|
||||||
fullEpisodeCache.delete(feedId);
|
fullEpisodeCache.delete(feedId);
|
||||||
episodeLoadCount.delete(feedId);
|
episodeLoadCount.delete(feedId);
|
||||||
setFeeds((prev) => {
|
setFeeds((prev) => {
|
||||||
const updated = prev.filter((f) => f.id !== feedId);
|
const updated = prev.filter((f) => f.id !== feedId);
|
||||||
saveFeeds(updated);
|
// Unsubscribe intent must not sit in the debounce window if the
|
||||||
|
// process exits — persist the removal immediately.
|
||||||
|
scheduleSaveFeeds();
|
||||||
|
flushPendingSave();
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -303,7 +651,10 @@ function createFeedStore() {
|
|||||||
episodeLoadCount.delete(feed.id);
|
episodeLoadCount.delete(feed.id);
|
||||||
setFeeds((prev) => {
|
setFeeds((prev) => {
|
||||||
const updated = prev.filter((f) => f.podcast.feedUrl !== feedUrl);
|
const updated = prev.filter((f) => f.podcast.feedUrl !== feedUrl);
|
||||||
saveFeeds(updated);
|
// Unsubscribe intent must not sit in the debounce window if
|
||||||
|
// the process exits — persist the removal immediately.
|
||||||
|
scheduleSaveFeeds();
|
||||||
|
flushPendingSave();
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -315,7 +666,7 @@ function createFeedStore() {
|
|||||||
const updated = prev.map((f) =>
|
const updated = prev.map((f) =>
|
||||||
f.id === feedId ? { ...f, ...updates, lastUpdated: new Date() } : f,
|
f.id === feedId ? { ...f, ...updates, lastUpdated: new Date() } : f,
|
||||||
);
|
);
|
||||||
saveFeeds(updated);
|
scheduleSaveFeeds();
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -326,7 +677,7 @@ function createFeedStore() {
|
|||||||
const updated = prev.map((f) =>
|
const updated = prev.map((f) =>
|
||||||
f.id === feedId ? { ...f, isPinned: !f.isPinned } : f,
|
f.id === feedId ? { ...f, isPinned: !f.isPinned } : f,
|
||||||
);
|
);
|
||||||
saveFeeds(updated);
|
scheduleSaveFeeds();
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -359,7 +710,7 @@ function createFeedStore() {
|
|||||||
/** Remove a source */
|
/** Remove a source */
|
||||||
const removeSource = (sourceId: string) => {
|
const removeSource = (sourceId: string) => {
|
||||||
// Don't remove default sources
|
// Don't remove default sources
|
||||||
if (sourceId === "itunes" || sourceId === "rss") return false;
|
if (DEFAULT_SOURCES.some((s) => s.id === sourceId)) return false;
|
||||||
|
|
||||||
setSources((prev) => {
|
setSources((prev) => {
|
||||||
const updated = prev.filter((s) => s.id !== sourceId);
|
const updated = prev.filter((s) => s.id !== sourceId);
|
||||||
@@ -385,6 +736,16 @@ function createFeedStore() {
|
|||||||
return feeds().find((f) => f.id === feedId);
|
return feeds().find((f) => f.id === feedId);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Find an episode by ID across all loaded feeds (undefined when the
|
||||||
|
* episode isn't in any loaded window, e.g. an unsubscribed show). */
|
||||||
|
const findEpisode = (episodeId: string): Episode | undefined => {
|
||||||
|
for (const feed of feeds()) {
|
||||||
|
const ep = feed.episodes.find((e) => e.id === episodeId);
|
||||||
|
if (ep) return ep;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
};
|
||||||
|
|
||||||
/** Get selected feed */
|
/** Get selected feed */
|
||||||
const getSelectedFeed = (): Feed | undefined => {
|
const getSelectedFeed = (): Feed | undefined => {
|
||||||
const id = selectedFeedId();
|
const id = selectedFeedId();
|
||||||
@@ -410,16 +771,32 @@ function createFeedStore() {
|
|||||||
|
|
||||||
// If no cache, re-fetch and parse the full feed
|
// If no cache, re-fetch and parse the full feed
|
||||||
if (!cached) {
|
if (!cached) {
|
||||||
|
try {
|
||||||
const response = await fetch(feed.podcast.feedUrl, {
|
const response = await fetch(feed.podcast.feedUrl, {
|
||||||
headers: {
|
headers: {
|
||||||
"Accept-Encoding": "identity",
|
"Accept-Encoding": "identity",
|
||||||
Accept: "application/rss+xml, application/xml, text/xml, */*",
|
Accept: "application/rss+xml, application/xml, text/xml, */*",
|
||||||
},
|
},
|
||||||
|
// A hung feed must not stall the load-more path forever —
|
||||||
|
// mirror fetchEpisodes' per-feed timeout.
|
||||||
|
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||||
});
|
});
|
||||||
if (!response.ok) return;
|
if (!response.ok) return;
|
||||||
const xml = await response.text();
|
const xml = await response.text();
|
||||||
const parsed = parseRSSFeed(xml, feed.podcast.feedUrl);
|
cached = await parseEpisodesIncremental(xml, feed.podcast.feedUrl);
|
||||||
cached = parsed.episodes;
|
} catch {
|
||||||
|
// Failed/hung refetch: leave the feed's loaded episodes
|
||||||
|
// untouched rather than throwing out of loadMoreEpisodes.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Cold-refetch parse output is unsorted; sort and cap it so the
|
||||||
|
// cache and the pagination window stay newest-first and bounded.
|
||||||
|
// Yield before the sync sort (the parse already yielded before
|
||||||
|
// this point, but the sort of potentially hundreds of episodes
|
||||||
|
// is its own sync block).
|
||||||
|
await yieldToUI();
|
||||||
|
cached = sortEpisodesReverseChronological(cached);
|
||||||
|
cached = cached.slice(0, MAX_EPISODES_IN_MEMORY);
|
||||||
fullEpisodeCache.set(feedId, cached);
|
fullEpisodeCache.set(feedId, cached);
|
||||||
// Set current load count to match what's already displayed
|
// Set current load count to match what's already displayed
|
||||||
episodeLoadCount.set(feedId, feed.episodes.length);
|
episodeLoadCount.set(feedId, feed.episodes.length);
|
||||||
@@ -436,11 +813,18 @@ function createFeedStore() {
|
|||||||
episodeLoadCount.set(feedId, newCount);
|
episodeLoadCount.set(feedId, newCount);
|
||||||
const episodes = cached.slice(0, newCount);
|
const episodes = cached.slice(0, newCount);
|
||||||
|
|
||||||
|
// Yield a real macrotask turn before the sync state update so the
|
||||||
|
// renderer paints the spinner and processes keyboard input before the
|
||||||
|
// (potentially large, per-feed in loadMoreAllFeeds) setFeeds + sort
|
||||||
|
// runs. Without this, the whole body executes in one microtask batch
|
||||||
|
// and the UI freezes through every feed in the batch.
|
||||||
|
await yieldToUI();
|
||||||
|
|
||||||
setFeeds((prev) => {
|
setFeeds((prev) => {
|
||||||
const updated = prev.map((f) =>
|
const updated = prev.map((f) =>
|
||||||
f.id === feedId ? { ...f, episodes } : f,
|
f.id === feedId ? { ...f, episodes } : f,
|
||||||
);
|
);
|
||||||
saveFeeds(updated);
|
scheduleSaveFeeds();
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -477,13 +861,9 @@ function createFeedStore() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Set auto-download settings for a feed */
|
/** Run the global auto-download pass (see runAutoDownload above). */
|
||||||
const setAutoDownload = (
|
const runAutoDownloadNow = (): void => {
|
||||||
feedId: string,
|
runAutoDownload();
|
||||||
enabled: boolean,
|
|
||||||
count: number = 0,
|
|
||||||
) => {
|
|
||||||
updateFeed(feedId, { autoDownload: enabled, autoDownloadCount: count });
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -494,10 +874,15 @@ function createFeedStore() {
|
|||||||
selectedFeedId,
|
selectedFeedId,
|
||||||
isLoadingMore,
|
isLoadingMore,
|
||||||
|
|
||||||
|
/** Resolves once persisted feeds are loaded from disk (before the
|
||||||
|
* background refresh). */
|
||||||
|
whenReady: () => feedsReady,
|
||||||
|
|
||||||
// Computed
|
// Computed
|
||||||
getFilteredFeeds,
|
getFilteredFeeds,
|
||||||
getAllEpisodesChronological,
|
getAllEpisodesChronological,
|
||||||
getFeed,
|
getFeed,
|
||||||
|
findEpisode,
|
||||||
getSelectedFeed,
|
getSelectedFeed,
|
||||||
hasMoreEpisodes,
|
hasMoreEpisodes,
|
||||||
isLoadingFeeds,
|
isLoadingFeeds,
|
||||||
@@ -516,11 +901,12 @@ function createFeedStore() {
|
|||||||
loadMoreEpisodes,
|
loadMoreEpisodes,
|
||||||
loadMoreAllFeeds,
|
loadMoreAllFeeds,
|
||||||
hasMoreAcrossAll,
|
hasMoreAcrossAll,
|
||||||
|
flushPendingSave,
|
||||||
addSource,
|
addSource,
|
||||||
removeSource,
|
removeSource,
|
||||||
toggleSource,
|
toggleSource,
|
||||||
updateSource,
|
updateSource,
|
||||||
setAutoDownload,
|
runAutoDownload: runAutoDownloadNow,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -53,11 +53,17 @@ async function initProgress(): Promise<void> {
|
|||||||
setProgressMap(parsed);
|
setProgressMap(parsed);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fire-and-forget init
|
// Fire-and-forget init; the promise is exposed via whenReady() so boot-time
|
||||||
initProgress();
|
// consumers (e.g. player-session restore) can await the file load.
|
||||||
|
const progressInit = initProgress();
|
||||||
|
|
||||||
function createProgressStore() {
|
function createProgressStore() {
|
||||||
return {
|
return {
|
||||||
|
/**
|
||||||
|
* Resolves once the persisted progress map has been loaded from disk.
|
||||||
|
*/
|
||||||
|
whenReady: () => progressInit,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get progress for a specific episode.
|
* Get progress for a specific episode.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -4,12 +4,16 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { createSignal } from "solid-js";
|
import { createSignal } from "solid-js";
|
||||||
import { searchPodcasts, searchByFeedUrl } from "../utils/search";
|
import { searchPodcasts, searchEpisodes, searchByFeedUrl } from "../utils/search";
|
||||||
|
import {
|
||||||
|
loadSearchHistoryFromFile,
|
||||||
|
saveSearchHistoryToFile,
|
||||||
|
} from "../utils/app-persistence";
|
||||||
import { useFeedStore } from "./feed";
|
import { useFeedStore } from "./feed";
|
||||||
import type { SearchResult } from "../types/source";
|
import type { SearchResult, SearchScope } from "../types/source";
|
||||||
|
|
||||||
const STORAGE_KEY = "podtui_search_history";
|
const STORAGE_SCOPE_KEY = "podtui_search_scope";
|
||||||
const MAX_HISTORY = 20;
|
const MAX_HISTORY = 10;
|
||||||
|
|
||||||
export interface SearchState {
|
export interface SearchState {
|
||||||
query: string;
|
query: string;
|
||||||
@@ -20,22 +24,37 @@ export interface SearchState {
|
|||||||
|
|
||||||
const CACHE_TTL = 1000 * 60 * 5;
|
const CACHE_TTL = 1000 * 60 * 5;
|
||||||
|
|
||||||
/** Load search history from localStorage */
|
/** Normalize raw history: drop blanks, dedupe case-insensitively (newest
|
||||||
function loadHistory(): string[] {
|
* wins), cap at MAX_HISTORY. */
|
||||||
if (typeof localStorage === "undefined") return [];
|
function sanitizeHistory(items: string[]): string[] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const cleaned: string[] = [];
|
||||||
|
for (const item of items) {
|
||||||
|
const trimmed = item.trim();
|
||||||
|
const key = trimmed.toLowerCase();
|
||||||
|
if (!key || seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
cleaned.push(trimmed);
|
||||||
|
}
|
||||||
|
return cleaned.slice(0, MAX_HISTORY);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Load persisted search scope ("podcast" | "episode"), defaulting to shows. */
|
||||||
|
function loadScope(): SearchScope {
|
||||||
|
if (typeof localStorage === "undefined") return "podcast";
|
||||||
try {
|
try {
|
||||||
const stored = localStorage.getItem(STORAGE_KEY);
|
const stored = localStorage.getItem(STORAGE_SCOPE_KEY);
|
||||||
return stored ? JSON.parse(stored) : [];
|
return stored === "episode" ? "episode" : "podcast";
|
||||||
} catch {
|
} catch {
|
||||||
return [];
|
return "podcast";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Save search history to localStorage */
|
/** Save search scope to localStorage */
|
||||||
function saveHistory(history: string[]): void {
|
function saveScope(scope: SearchScope): void {
|
||||||
if (typeof localStorage === "undefined") return;
|
if (typeof localStorage === "undefined") return;
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(history));
|
localStorage.setItem(STORAGE_SCOPE_KEY, scope);
|
||||||
} catch {
|
} catch {
|
||||||
// Ignore errors
|
// Ignore errors
|
||||||
}
|
}
|
||||||
@@ -48,8 +67,24 @@ export function createSearchStore() {
|
|||||||
const [isSearching, setIsSearching] = createSignal(false);
|
const [isSearching, setIsSearching] = createSignal(false);
|
||||||
const [results, setResults] = createSignal<SearchResult[]>([]);
|
const [results, setResults] = createSignal<SearchResult[]>([]);
|
||||||
const [error, setError] = createSignal<string | null>(null);
|
const [error, setError] = createSignal<string | null>(null);
|
||||||
const [history, setHistory] = createSignal<string[]>(loadHistory());
|
const [history, setHistory] = createSignal<string[]>([]);
|
||||||
const [selectedSources, setSelectedSources] = createSignal<string[]>([]);
|
const [selectedSources, setSelectedSources] = createSignal<string[]>([]);
|
||||||
|
const [scope, setScopeState] = createSignal<SearchScope>(loadScope());
|
||||||
|
|
||||||
|
/** Load search history from file (fire-and-forget; recents appear as
|
||||||
|
* soon as the file is read). */
|
||||||
|
async function init(): Promise<void> {
|
||||||
|
const loaded = await loadSearchHistoryFromFile();
|
||||||
|
if (loaded.length > 0) setHistory(sanitizeHistory(loaded));
|
||||||
|
}
|
||||||
|
|
||||||
|
init();
|
||||||
|
|
||||||
|
/** Set the search scope (shows vs episodes) and persist it. */
|
||||||
|
const setScope = (next: SearchScope) => {
|
||||||
|
setScopeState(next);
|
||||||
|
saveScope(next);
|
||||||
|
};
|
||||||
|
|
||||||
const applySubscribedStatus = (items: SearchResult[]): SearchResult[] => {
|
const applySubscribedStatus = (items: SearchResult[]): SearchResult[] => {
|
||||||
const feeds = feedStore.feeds();
|
const feeds = feedStore.feeds();
|
||||||
@@ -110,7 +145,12 @@ export function createSearchStore() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const searchResults = await searchPodcasts(q, sourceIds, sources, {
|
const searchResults =
|
||||||
|
scope() === "episode"
|
||||||
|
? await searchEpisodes(q, sourceIds, sources, {
|
||||||
|
cacheTtl: CACHE_TTL,
|
||||||
|
})
|
||||||
|
: await searchPodcasts(q, sourceIds, sources, {
|
||||||
cacheTtl: CACHE_TTL,
|
cacheTtl: CACHE_TTL,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -130,9 +170,8 @@ export function createSearchStore() {
|
|||||||
/** Add query to history */
|
/** Add query to history */
|
||||||
const addToHistory = (q: string) => {
|
const addToHistory = (q: string) => {
|
||||||
setHistory((prev) => {
|
setHistory((prev) => {
|
||||||
const filtered = prev.filter((h) => h.toLowerCase() !== q.toLowerCase());
|
const updated = sanitizeHistory([q, ...prev]);
|
||||||
const updated = [q, ...filtered].slice(0, MAX_HISTORY);
|
saveSearchHistoryToFile(updated);
|
||||||
saveHistory(updated);
|
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -140,14 +179,14 @@ export function createSearchStore() {
|
|||||||
/** Clear search history */
|
/** Clear search history */
|
||||||
const clearHistory = () => {
|
const clearHistory = () => {
|
||||||
setHistory([]);
|
setHistory([]);
|
||||||
saveHistory([]);
|
saveSearchHistoryToFile([]);
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Remove single history item */
|
/** Remove single history item */
|
||||||
const removeFromHistory = (q: string) => {
|
const removeFromHistory = (q: string) => {
|
||||||
setHistory((prev) => {
|
setHistory((prev) => {
|
||||||
const updated = prev.filter((h) => h !== q);
|
const updated = prev.filter((h) => h !== q);
|
||||||
saveHistory(updated);
|
saveSearchHistoryToFile(updated);
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -179,6 +218,27 @@ export function createSearchStore() {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Mark a podcast as unsubscribed in results (after an in-place
|
||||||
|
* unsubscribe from the results list). */
|
||||||
|
const markUnsubscribed = (podcastId: string, feedUrl?: string) => {
|
||||||
|
setResults((prev) =>
|
||||||
|
prev.map((result) => {
|
||||||
|
const matchesId = result.podcast.id === podcastId;
|
||||||
|
const matchesUrl = feedUrl ? result.podcast.feedUrl === feedUrl : false;
|
||||||
|
if (matchesId || matchesUrl) {
|
||||||
|
return {
|
||||||
|
...result,
|
||||||
|
podcast: {
|
||||||
|
...result.podcast,
|
||||||
|
isSubscribed: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
// State
|
// State
|
||||||
query,
|
query,
|
||||||
@@ -187,6 +247,7 @@ export function createSearchStore() {
|
|||||||
error,
|
error,
|
||||||
history,
|
history,
|
||||||
selectedSources,
|
selectedSources,
|
||||||
|
scope,
|
||||||
|
|
||||||
// Actions
|
// Actions
|
||||||
search,
|
search,
|
||||||
@@ -195,7 +256,9 @@ export function createSearchStore() {
|
|||||||
clearHistory,
|
clearHistory,
|
||||||
removeFromHistory,
|
removeFromHistory,
|
||||||
setSelectedSources,
|
setSelectedSources,
|
||||||
|
setScope,
|
||||||
markSubscribed,
|
markSubscribed,
|
||||||
|
markUnsubscribed,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
450
src/stores/visualizer.ts
Normal file
@@ -0,0 +1,450 @@
|
|||||||
|
/**
|
||||||
|
* visualizer-store — module-level singleton owning the realtime waveform
|
||||||
|
* pipeline (ffmpeg decode + cavacore FFT), shared across PlayerPage mounts.
|
||||||
|
*
|
||||||
|
* Pipeline shape (see utils/audio-pcm-cache.ts for the rationale):
|
||||||
|
* an ffmpeg process decodes the episode at full speed into a
|
||||||
|
* position-indexed PCM cache; the render loop reads the window ending at
|
||||||
|
* the player's current position from that cache. Because reads are
|
||||||
|
* indexed by playback time, PAUSE/RESUME/SEEK/SPEED need no pipeline
|
||||||
|
* choreography at all — and cannot desync:
|
||||||
|
*
|
||||||
|
* - Pause: stop the render loop and the decode pass; the PCM cache stays
|
||||||
|
* resident. Bars freeze on the last rendered frame.
|
||||||
|
* - Resume: re-arm the render loop — bars render instantly from the cache
|
||||||
|
* — and continue the tail decode in the background. No cold start, no
|
||||||
|
* coverage guessing, no clamped-buffer freeze (the old bug: resume
|
||||||
|
* re-armed the loop over a DEAD ffmpeg and the bars exhausted the ring
|
||||||
|
* buffer, then froze on a repeated stale window forever).
|
||||||
|
* - Seek into decoded audio: nothing to do. Seek into a hole: kick off a
|
||||||
|
* decode segment there; the last frame holds until data arrives.
|
||||||
|
* - Speed changes: nothing. The cache is position-indexed raw PCM.
|
||||||
|
*
|
||||||
|
* Focus lifecycle: Shell unmounts a tab's page when it loses focus, but the
|
||||||
|
* pipeline outlives the page so playback keeps visualizing; UNLOAD_DELAY_MS
|
||||||
|
* after the Player tab stops being focused it tears down. Reads outside
|
||||||
|
* decoded coverage return empty — the renderer simply holds the last frame
|
||||||
|
* until the decode frontier arrives.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import {
|
||||||
|
createSignal,
|
||||||
|
createEffect,
|
||||||
|
createRoot,
|
||||||
|
on,
|
||||||
|
untrack,
|
||||||
|
} from "solid-js";
|
||||||
|
import {
|
||||||
|
loadCavaCore,
|
||||||
|
type CavaCore,
|
||||||
|
type CavaCoreConfig,
|
||||||
|
} from "@/utils/cavacore";
|
||||||
|
import { EpisodePcmCache, PCM_SAMPLE_RATE } from "@/utils/audio-pcm-cache";
|
||||||
|
import { createBarScaler } from "@/utils/bar-mapping";
|
||||||
|
import { audioPlaybackSignals } from "@/utils/audio-signals";
|
||||||
|
import { useAppStore } from "@/stores/app";
|
||||||
|
|
||||||
|
// ── Constants ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** How long the pipeline keeps running after the Player tab loses focus. */
|
||||||
|
export const VISUALIZER_UNLOAD_DELAY_MS = 30_000;
|
||||||
|
|
||||||
|
/** Target frame interval in ms (~30 fps) */
|
||||||
|
const FRAME_INTERVAL = 33;
|
||||||
|
|
||||||
|
/** Number of PCM samples to read per frame (512 is a good FFT window) */
|
||||||
|
const SAMPLES_PER_FRAME = 512;
|
||||||
|
|
||||||
|
/** Timer handle as returned by setTimeout/setInterval in this runtime. */
|
||||||
|
type TimerHandle = ReturnType<typeof setTimeout>;
|
||||||
|
|
||||||
|
// ── Types ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface VisualizerStore {
|
||||||
|
/** Frequency bar values (0.0–1.0 per bar), empty until the first frame. */
|
||||||
|
barData: () => number[];
|
||||||
|
/** True from pipeline start until the first complete FFT frame renders. */
|
||||||
|
isLoading: () => boolean;
|
||||||
|
/** True while the ~30fps render loop is armed. */
|
||||||
|
isRunning: () => boolean;
|
||||||
|
/** Report whether the Player tab is the visible tab. */
|
||||||
|
setFocused: (focused: boolean) => void;
|
||||||
|
/** Report the terminal-width-derived bar count (resize re-inits). */
|
||||||
|
setBarCount: (count: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Store factory ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function createVisualizerStore(): VisualizerStore {
|
||||||
|
// Frequency bar values (0.0–1.0 per bar)
|
||||||
|
const [barData, setBarData] = createSignal<number[]>([]);
|
||||||
|
|
||||||
|
// True from pipeline start until the first complete FFT frame renders.
|
||||||
|
const [isLoading, setIsLoading] = createSignal(false);
|
||||||
|
|
||||||
|
// Whether the Player tab is the visible tab (fed by PlayerPage).
|
||||||
|
const [focused, setFocused] = createSignal(false);
|
||||||
|
|
||||||
|
// Width-derived bar count (fed by RealtimeWaveform; default before the
|
||||||
|
// renderer reports a real size).
|
||||||
|
const [barCount, setBarCount] = createSignal(64);
|
||||||
|
|
||||||
|
// Peak-follower scaler replaces cava's autosens: normalizes each FFT
|
||||||
|
// frame against the running peak so a loud start can't pin every bar
|
||||||
|
// at full height and quiet content still gets normalized up.
|
||||||
|
const scaler = createBarScaler();
|
||||||
|
|
||||||
|
let cava: CavaCore | null = null;
|
||||||
|
// Position-indexed PCM cache for the current episode. Kept across
|
||||||
|
// pause/resume (segments survive; only the ffmpeg pass is killed) and
|
||||||
|
// dropped only on episode change, stop, disable, or unload.
|
||||||
|
let pcm: EpisodePcmCache | null = null;
|
||||||
|
let frameTimer: TimerHandle | null = null;
|
||||||
|
let sampleBuffer: Float64Array | null = null;
|
||||||
|
let unloadTimer: TimerHandle | null = null;
|
||||||
|
|
||||||
|
// What the running pipeline was started with — lets the playback effect
|
||||||
|
// tell "nothing changed, stay warm" from "must restart".
|
||||||
|
let activeUrl = "";
|
||||||
|
let activeBars = 64;
|
||||||
|
|
||||||
|
// ── Lifecycle helpers ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
const clearUnloadTimer = () => {
|
||||||
|
if (unloadTimer) {
|
||||||
|
clearTimeout(unloadTimer);
|
||||||
|
unloadTimer = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const initCava = () => {
|
||||||
|
if (cava) return true;
|
||||||
|
|
||||||
|
cava = loadCavaCore();
|
||||||
|
if (!cava) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Smooth position clock ──────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// audio.position() updates at the useAudio poll rate (~150ms). Between
|
||||||
|
// polls, interpolate the position from wall time so the FFT window
|
||||||
|
// tracks the audio continuously instead of stepping. The 0.5s cap
|
||||||
|
// prevents extrapolating far beyond reality when the player stalls
|
||||||
|
// (e.g. network re-buffering).
|
||||||
|
|
||||||
|
let lastPolledPosition = 0;
|
||||||
|
let lastPolledAt = 0;
|
||||||
|
const smoothPosition = () => {
|
||||||
|
const pos = audioPlaybackSignals.position();
|
||||||
|
const now = performance.now();
|
||||||
|
if (pos !== lastPolledPosition) {
|
||||||
|
lastPolledPosition = pos;
|
||||||
|
lastPolledAt = now;
|
||||||
|
return pos;
|
||||||
|
}
|
||||||
|
if (lastPolledAt === 0) return pos;
|
||||||
|
const elapsed = Math.min((now - lastPolledAt) / 1000, 0.5);
|
||||||
|
return lastPolledPosition + elapsed * (audioPlaybackSignals.speed() ?? 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Start/stop the visualization pipeline ──────────────────────────
|
||||||
|
|
||||||
|
const startVisualization = (url: string, position: number) => {
|
||||||
|
stopVisualization();
|
||||||
|
|
||||||
|
if (!url || !initCava() || !cava) return;
|
||||||
|
|
||||||
|
// Initialize cavacore with current resolution + the user's
|
||||||
|
// audio-processing params (noise reduction, cutoffs, etc.).
|
||||||
|
// autosens is disabled (after the spread so it always wins): cava's
|
||||||
|
// autosens gain-ramps during silence then clips everything to 1.0
|
||||||
|
// when audio arrives — the JS peak scaler handles dynamics instead.
|
||||||
|
const viz = useAppStore().state().settings.visualizer;
|
||||||
|
const config: CavaCoreConfig = {
|
||||||
|
bars: barCount(),
|
||||||
|
sampleRate: PCM_SAMPLE_RATE,
|
||||||
|
channels: 1,
|
||||||
|
noiseReduction: viz.noiseReduction,
|
||||||
|
lowCutOff: viz.lowCutOff,
|
||||||
|
highCutOff: viz.highCutOff,
|
||||||
|
autosens: 0,
|
||||||
|
};
|
||||||
|
cava.init(config);
|
||||||
|
|
||||||
|
// Pre-warm the FFT window: libcavacore's window is malloc'd
|
||||||
|
// uninitialized, so the first real frame would FFT garbage and
|
||||||
|
// render full-scale bars. One zero frame the size of the whole
|
||||||
|
// input buffer clears it.
|
||||||
|
cava.execute(new Float64Array(8192));
|
||||||
|
|
||||||
|
// Pre-allocate sample read buffer
|
||||||
|
sampleBuffer = new Float64Array(SAMPLES_PER_FRAME);
|
||||||
|
|
||||||
|
// PCM cache per episode (reuse when the episode is unchanged)
|
||||||
|
if (!pcm || pcm.url !== url) {
|
||||||
|
if (pcm) pcm.stop();
|
||||||
|
pcm = new EpisodePcmCache({ url });
|
||||||
|
}
|
||||||
|
// Decode from 1s before the position so the window ENDING at the
|
||||||
|
// position is covered as soon as the first PCM lands.
|
||||||
|
pcm.startDecode(Math.max(0, position - 1));
|
||||||
|
|
||||||
|
// Seed the smooth position clock with the start position. Without
|
||||||
|
// this, a fresh play at position 0 would sample the window ending at
|
||||||
|
// exactly 0 — a 1-sample slice — so bars would be starved until the
|
||||||
|
// first mpv poll advanced the position clock.
|
||||||
|
lastPolledPosition = position;
|
||||||
|
lastPolledAt = performance.now();
|
||||||
|
|
||||||
|
activeUrl = url;
|
||||||
|
activeBars = barCount();
|
||||||
|
setIsLoading(true);
|
||||||
|
frameTimer = setInterval(renderFrame, FRAME_INTERVAL);
|
||||||
|
};
|
||||||
|
|
||||||
|
const stopVisualization = () => {
|
||||||
|
clearUnloadTimer();
|
||||||
|
if (frameTimer) {
|
||||||
|
clearInterval(frameTimer);
|
||||||
|
frameTimer = null;
|
||||||
|
}
|
||||||
|
clearTimeout(seekDecodeTimer);
|
||||||
|
seekDecodeTimer = undefined;
|
||||||
|
if (pcm) {
|
||||||
|
pcm.stop();
|
||||||
|
// Keep the (now cache-less, url-tagged) object: a re-start of the
|
||||||
|
// same episode reuses it; segments re-decode in seconds at 80x.
|
||||||
|
}
|
||||||
|
if (cava?.isReady) {
|
||||||
|
cava.destroy();
|
||||||
|
}
|
||||||
|
sampleBuffer = null;
|
||||||
|
setIsLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Pause: freeze the loop, keep the cache ──────────────────────────
|
||||||
|
//
|
||||||
|
// The render loop stops (bars hold their last frame) and the ffmpeg
|
||||||
|
// pass dies (no background CPU), but the decoded PCM stays: resume
|
||||||
|
// serves it instantly.
|
||||||
|
|
||||||
|
const suspendVisualization = () => {
|
||||||
|
clearUnloadTimer();
|
||||||
|
if (frameTimer) {
|
||||||
|
clearInterval(frameTimer);
|
||||||
|
frameTimer = null;
|
||||||
|
}
|
||||||
|
// Cancel any debounced seek-decode: it would restart ffmpeg while
|
||||||
|
// paused, defeating the "no background CPU while paused" contract.
|
||||||
|
clearTimeout(seekDecodeTimer);
|
||||||
|
seekDecodeTimer = undefined;
|
||||||
|
if (pcm) pcm.pauseDecode();
|
||||||
|
// Cava plan + sampleBuffer stay alive — cheap to reuse on resume.
|
||||||
|
// Clear the loading spinner: if the pipeline never produced bars
|
||||||
|
// (still cold-starting when paused), the component should fall back
|
||||||
|
// to the placeholder, not freeze on a spinner.
|
||||||
|
setIsLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Resume: re-arm the render loop, top up the cache ───────────────
|
||||||
|
//
|
||||||
|
// Returns true if the pipeline resumed, false if there was nothing to
|
||||||
|
// resume (no prior pipeline).
|
||||||
|
|
||||||
|
const resumeVisualization = (): boolean => {
|
||||||
|
// Already running — nothing to do.
|
||||||
|
if (frameTimer !== null) return true;
|
||||||
|
if (!pcm || !cava?.isReady || !sampleBuffer) return false;
|
||||||
|
|
||||||
|
const pos = untrack(audioPlaybackSignals.position);
|
||||||
|
|
||||||
|
// Bars come from the cache on the next frame tick (~33ms) whenever
|
||||||
|
// the position is covered; any gap (uncached region) restarts the
|
||||||
|
// decode pass in the background with the last frame holding.
|
||||||
|
pcm.ensureDecodeAround(pos);
|
||||||
|
|
||||||
|
lastPolledPosition = pos;
|
||||||
|
lastPolledAt = performance.now();
|
||||||
|
frameTimer = setInterval(renderFrame, FRAME_INTERVAL);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Render loop (called at ~30fps) ─────────────────────────────────
|
||||||
|
|
||||||
|
const renderFrame = () => {
|
||||||
|
if (!cava?.isReady || !sampleBuffer || !pcm) return;
|
||||||
|
|
||||||
|
// Sample the FFT window at the player's position. Outside decoded
|
||||||
|
// coverage (decode cold start, seek into a hole) the read is empty
|
||||||
|
// and the LAST FRAME simply holds — never clamped/repeated junk.
|
||||||
|
const target = smoothPosition();
|
||||||
|
const count = pcm.readWindow(sampleBuffer, target);
|
||||||
|
// Never feed a partial FFT window to cava.
|
||||||
|
if (count < sampleBuffer.length) return;
|
||||||
|
|
||||||
|
const output = cava.execute(sampleBuffer);
|
||||||
|
|
||||||
|
// Normalize against the running peak and copy to a new array
|
||||||
|
setBarData(scaler(output));
|
||||||
|
if (isLoading()) setIsLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Playback subscription ──────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// Keeps the pipeline matched to playback. Pause suspends (render loop +
|
||||||
|
// decode pass die, cache survives) so resume is instant. Stop/track-end/
|
||||||
|
// disable fully tears down. `focused` is a dep so focus regain
|
||||||
|
// re-evaluates; the guards make a focus flip on an already-correct warm
|
||||||
|
// pipeline a no-op. Speed is deliberately NOT a dep — the PCM cache is
|
||||||
|
// position-indexed, so playback-rate changes need no pipeline restart.
|
||||||
|
|
||||||
|
createEffect(
|
||||||
|
on(
|
||||||
|
[
|
||||||
|
audioPlaybackSignals.isPlaying,
|
||||||
|
() => audioPlaybackSignals.currentEpisode()?.audioUrl ?? "",
|
||||||
|
barCount,
|
||||||
|
focused,
|
||||||
|
() => useAppStore().state().settings.visualizer.enabled,
|
||||||
|
],
|
||||||
|
([playing, url, , , enabled]) => {
|
||||||
|
if (!url || !enabled) {
|
||||||
|
stopVisualization();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!playing) {
|
||||||
|
// Pause: freeze the loop, keep the cache. Only if the
|
||||||
|
// pipeline is actually running — otherwise no-op.
|
||||||
|
if (frameTimer !== null) suspendVisualization();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Playing — try a fast resume first. If it succeeds and the
|
||||||
|
// pipeline matches, done.
|
||||||
|
if (
|
||||||
|
frameTimer === null &&
|
||||||
|
pcm &&
|
||||||
|
cava?.isReady &&
|
||||||
|
url === activeUrl &&
|
||||||
|
barCount() === activeBars
|
||||||
|
) {
|
||||||
|
if (resumeVisualization()) return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warm and already correct — nothing to do (e.g. focus
|
||||||
|
// regained within the unload delay while still playing).
|
||||||
|
if (frameTimer !== null && url === activeUrl && barCount() === activeBars) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!focused()) return; // playing away: stay warm; unload timer decides
|
||||||
|
startVisualization(url, untrack(audioPlaybackSignals.position));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Focus subscription: unload after the grace delay ───────────────
|
||||||
|
|
||||||
|
createEffect(
|
||||||
|
on(focused, (f) => {
|
||||||
|
clearUnloadTimer();
|
||||||
|
if (f) {
|
||||||
|
// Pipeline was unloaded (or never started) but playback is
|
||||||
|
// still going — restart from the current position. When the
|
||||||
|
// pipeline is warm the playback effect above is the one that
|
||||||
|
// acts (guard: no-op for an unchanged warm pipeline).
|
||||||
|
if (
|
||||||
|
audioPlaybackSignals.isPlaying() &&
|
||||||
|
audioPlaybackSignals.currentEpisode()?.audioUrl &&
|
||||||
|
useAppStore().state().settings.visualizer.enabled &&
|
||||||
|
frameTimer === null
|
||||||
|
) {
|
||||||
|
startVisualization(
|
||||||
|
audioPlaybackSignals.currentEpisode()!.audioUrl,
|
||||||
|
untrack(audioPlaybackSignals.position),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else if (frameTimer !== null) {
|
||||||
|
unloadTimer = setTimeout(() => {
|
||||||
|
unloadTimer = null;
|
||||||
|
stopVisualization();
|
||||||
|
}, VISUALIZER_UNLOAD_DELAY_MS);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Seek detection: jump coverage, not pipeline restarts ───────────
|
||||||
|
//
|
||||||
|
// Watches position for significant jumps (>2s = user seek). Decoded
|
||||||
|
// audio at the new position is served instantly with zero action; a
|
||||||
|
// jump into an undecoded hole kicks a background segment decode there
|
||||||
|
// while the last frame holds.
|
||||||
|
|
||||||
|
let lastSyncPosition = 0;
|
||||||
|
let seekDecodeTimer: TimerHandle | undefined;
|
||||||
|
createEffect(
|
||||||
|
on(audioPlaybackSignals.position, (pos) => {
|
||||||
|
if (!audioPlaybackSignals.isPlaying() || !pcm) {
|
||||||
|
lastSyncPosition = pos;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const delta = Math.abs(pos - lastSyncPosition);
|
||||||
|
lastSyncPosition = pos;
|
||||||
|
|
||||||
|
if (delta > 2) {
|
||||||
|
// Debounce: holding the seek key fires a jump per poll tick —
|
||||||
|
// without debounce each one restarts ffmpeg, spamming network
|
||||||
|
// reconnects against the stream's server. Wait for the user to
|
||||||
|
// settle, then decode at the final position.
|
||||||
|
clearTimeout(seekDecodeTimer);
|
||||||
|
const target = pcm; // capture for the timer
|
||||||
|
seekDecodeTimer = setTimeout(() => {
|
||||||
|
seekDecodeTimer = undefined;
|
||||||
|
target.ensureDecodeAround(untrack(audioPlaybackSignals.position));
|
||||||
|
}, 400);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
// ── Process-exit teardown ──────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// The pipeline lives in a detached createRoot that is never disposed,
|
||||||
|
// so Solid's onCleanup never runs. `q`/`:quit` call process.exit(0)
|
||||||
|
// (bypassing onCleanup); SIGINT/TERM/HUP are caught by useAudio's
|
||||||
|
// handler. This handler runs synchronously on `exit` and kills the
|
||||||
|
// ffmpeg child + destroys the cava plan so they don't outlive the host.
|
||||||
|
// Without it, a warm pipeline leaks an orphaned ffmpeg process on quit.
|
||||||
|
process.on("exit", () => {
|
||||||
|
stopVisualization();
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
// state
|
||||||
|
barData,
|
||||||
|
isLoading,
|
||||||
|
isRunning: () => frameTimer !== null,
|
||||||
|
// inputs
|
||||||
|
setFocused,
|
||||||
|
setBarCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Singleton ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
let visualizerStoreInstance: VisualizerStore | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Accessor for the shared visualizer store. Created once inside a
|
||||||
|
* `createRoot` so its effects are owned by a detached root — not by
|
||||||
|
* whichever component happens to call first (PlayerPage unmounts would
|
||||||
|
* otherwise dispose the pipeline effects with it).
|
||||||
|
*/
|
||||||
|
export function useVisualizer(): VisualizerStore {
|
||||||
|
if (!visualizerStoreInstance) {
|
||||||
|
visualizerStoreInstance = createRoot(() => createVisualizerStore());
|
||||||
|
}
|
||||||
|
return visualizerStoreInstance;
|
||||||
|
}
|
||||||
@@ -98,7 +98,9 @@ export enum DownloadStatus {
|
|||||||
export interface DownloadedEpisode {
|
export interface DownloadedEpisode {
|
||||||
/** Episode ID */
|
/** Episode ID */
|
||||||
episodeId: string
|
episodeId: string
|
||||||
/** Feed ID the episode belongs to */
|
/** Feed ID the episode belongs to. For downloads of shows that aren't
|
||||||
|
* subscribed (search downloads) this is a deterministic synthetic id
|
||||||
|
* ("unsub-<slug>") that also names the file subdirectory. */
|
||||||
feedId: string
|
feedId: string
|
||||||
/** Current download status */
|
/** Current download status */
|
||||||
status: DownloadStatus
|
status: DownloadStatus
|
||||||
@@ -114,4 +116,16 @@ export interface DownloadedEpisode {
|
|||||||
fileSize: number
|
fileSize: number
|
||||||
/** Error message if failed */
|
/** Error message if failed */
|
||||||
error: string | null
|
error: string | null
|
||||||
|
/** Episode title, persisted so unsubscribed-show downloads render without
|
||||||
|
* a loaded feed. */
|
||||||
|
episodeTitle?: string
|
||||||
|
/** Audio URL, persisted so queued downloads survive a restart. */
|
||||||
|
audioUrl?: string
|
||||||
|
/** Publication date (ISO), for display of unsubscribed-show downloads. */
|
||||||
|
pubDate?: string
|
||||||
|
/** Show title, kept for downloads whose show isn't subscribed. */
|
||||||
|
podcastTitle?: string
|
||||||
|
/** The show's RSS feed URL, used to re-classify a download as subscribed
|
||||||
|
* once the user subscribes to its show. */
|
||||||
|
podcastFeedUrl?: string
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,10 +33,6 @@ export interface Feed {
|
|||||||
isPinned: boolean
|
isPinned: boolean
|
||||||
/** Feed color for UI */
|
/** Feed color for UI */
|
||||||
color?: string
|
color?: string
|
||||||
/** Whether auto-download is enabled for this feed */
|
|
||||||
autoDownload?: boolean
|
|
||||||
/** Number of newest episodes to auto-download (0 = all new) */
|
|
||||||
autoDownloadCount?: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Feed item for display in lists */
|
/** Feed item for display in lists */
|
||||||
|
|||||||
@@ -12,8 +12,12 @@ export interface Podcast {
|
|||||||
description: string
|
description: string
|
||||||
/** Cover image URL */
|
/** Cover image URL */
|
||||||
coverUrl?: string
|
coverUrl?: string
|
||||||
/** RSS feed URL */
|
/** RSS feed URL. Empty when the directory lists the show without a feed
|
||||||
|
* (e.g. shows delisted from Apple Podcasts); see directoryUrl. */
|
||||||
feedUrl: string
|
feedUrl: string
|
||||||
|
/** Directory listing page (e.g. Apple Podcasts) for shows whose feed URL
|
||||||
|
* the directory omits — used to resolve the real feed at subscribe time. */
|
||||||
|
directoryUrl?: string
|
||||||
/** Author/creator name */
|
/** Author/creator name */
|
||||||
author?: string
|
author?: string
|
||||||
/** Podcast categories */
|
/** Podcast categories */
|
||||||
|
|||||||
@@ -62,6 +62,8 @@ export type DesktopTheme = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type VisualizerSettings = {
|
export type VisualizerSettings = {
|
||||||
|
/** Master on/off switch for the player's realtime waveform (default: on). */
|
||||||
|
enabled: boolean;
|
||||||
/** Number of frequency bars (8–128, default: 64) */
|
/** Number of frequency bars (8–128, default: 64) */
|
||||||
bars: number;
|
bars: number;
|
||||||
/** Automatic sensitivity: 1 = enabled, 0 = disabled (default: 1) */
|
/** Automatic sensitivity: 1 = enabled, 0 = disabled (default: 1) */
|
||||||
@@ -78,22 +80,37 @@ export type AppSettings = {
|
|||||||
theme: ThemeName;
|
theme: ThemeName;
|
||||||
fontSize: number;
|
fontSize: number;
|
||||||
playbackSpeed: number;
|
playbackSpeed: number;
|
||||||
|
/** Playback volume 0–1 (default: 1 = 100%). */
|
||||||
|
volume: number;
|
||||||
downloadPath: string;
|
downloadPath: string;
|
||||||
/** Render the app background transparent (let the terminal's own bg show). */
|
/** Render the app background transparent (let the terminal's own bg show). */
|
||||||
transparentBackground: boolean;
|
transparentBackground: boolean;
|
||||||
|
/** Show the `❯` cursor marker on the focused row of every list (default: off). */
|
||||||
|
showSelectionMarker: boolean;
|
||||||
visualizer: VisualizerSettings;
|
visualizer: VisualizerSettings;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** How the Feed list loads older episodes (default: manual "[Fetch More]"). */
|
/** How the Feed and per-show episode lists load older episodes (default: auto). */
|
||||||
export type FetchMoreMode = "manual" | "auto";
|
export type FetchMoreMode = "manual" | "auto";
|
||||||
|
|
||||||
|
/** Which shows the auto-download setting applies to (default: all). */
|
||||||
|
export type AutoDownloadScope = "all" | "none" | "whitelist";
|
||||||
|
|
||||||
export type UserPreferences = {
|
export type UserPreferences = {
|
||||||
showExplicit: boolean;
|
showExplicit: boolean;
|
||||||
autoDownload: boolean;
|
autoDownload: boolean;
|
||||||
|
/** Most recent episodes to auto-download per in-scope show (default: 2). */
|
||||||
|
autoDownloadCount: number;
|
||||||
|
/** Shows auto-download covers: all / none / whitelist (default: all). */
|
||||||
|
autoDownloadScope: AutoDownloadScope;
|
||||||
|
/** Feed ids in the auto-download whitelist (used when scope is "whitelist"). */
|
||||||
|
autoDownloadWhitelist: string[];
|
||||||
/** Jump to the Player view automatically when playback starts (default: true) */
|
/** Jump to the Player view automatically when playback starts (default: true) */
|
||||||
autoJumpToPlayer: boolean;
|
autoJumpToPlayer: boolean;
|
||||||
/** Load older episodes from the Feed list: manual button or automatic at the bottom (default: manual). */
|
/** Load older episodes from the Feed list: manual button or automatic at the bottom (default: auto). */
|
||||||
fetchMoreMode: FetchMoreMode;
|
fetchMoreMode: FetchMoreMode;
|
||||||
|
/** Minutes between automatic background feed refreshes (default: 30). */
|
||||||
|
refreshIntervalMinutes: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type AppState = {
|
export type AppState = {
|
||||||
|
|||||||
@@ -2,6 +2,9 @@
|
|||||||
* Podcast source type definitions for PodTUI
|
* Podcast source type definitions for PodTUI
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import type { Episode } from "./episode"
|
||||||
|
import type { Podcast } from "./podcast"
|
||||||
|
|
||||||
/** Source type enumeration */
|
/** Source type enumeration */
|
||||||
export enum SourceType {
|
export enum SourceType {
|
||||||
/** RSS feed URL */
|
/** RSS feed URL */
|
||||||
@@ -22,8 +25,21 @@ export interface PodcastSource {
|
|||||||
type: SourceType
|
type: SourceType
|
||||||
/** Base URL for the source */
|
/** Base URL for the source */
|
||||||
baseUrl: string
|
baseUrl: string
|
||||||
/** API key (if required) */
|
/** API key — live only when the keychain is unavailable and the source
|
||||||
|
* uses the plaintext fallback (credentialStorage "plaintext"). Legacy
|
||||||
|
* plaintext keys are migrated to the OS keychain on load and stripped. */
|
||||||
apiKey?: string
|
apiKey?: string
|
||||||
|
/** API secret (e.g. Podcast Index signature auth) — same lifecycle as
|
||||||
|
* apiKey: held in the OS keychain by default, live on the source only
|
||||||
|
* under the plaintext fallback. */
|
||||||
|
apiSecret?: string
|
||||||
|
/** True when this source's credentials are stored. A source is usable once
|
||||||
|
* enabled. */
|
||||||
|
hasCredentials?: boolean
|
||||||
|
/** Where this source's credentials live: the OS keychain (encrypted at
|
||||||
|
* rest) by default, or config.json as a plaintext fallback when the
|
||||||
|
* keychain is unavailable (e.g. non-macOS). */
|
||||||
|
credentialStorage?: "keychain" | "plaintext"
|
||||||
/** Whether source is enabled */
|
/** Whether source is enabled */
|
||||||
enabled: boolean
|
enabled: boolean
|
||||||
/** Source icon/logo URL */
|
/** Source icon/logo URL */
|
||||||
@@ -78,20 +94,39 @@ export enum SearchSortField {
|
|||||||
POPULARITY = "popularity",
|
POPULARITY = "popularity",
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Search result */
|
/** What a directory search targets: shows or individual episodes. */
|
||||||
export interface SearchResult {
|
export type SearchScope = "podcast" | "episode"
|
||||||
|
|
||||||
|
/** Fields shared by every search result. */
|
||||||
|
export interface SearchResultBase {
|
||||||
/** Source that returned this result */
|
/** Source that returned this result */
|
||||||
sourceId: string
|
sourceId: string
|
||||||
/** Source display name */
|
/** Source display name */
|
||||||
sourceName?: string
|
sourceName?: string
|
||||||
/** Source type */
|
/** Source type */
|
||||||
sourceType?: SourceType
|
sourceType?: SourceType
|
||||||
/** Podcast data */
|
|
||||||
podcast: import("./podcast").Podcast
|
|
||||||
/** Relevance score (0-1) */
|
/** Relevance score (0-1) */
|
||||||
score?: number
|
score?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A show found by directory search. */
|
||||||
|
export interface PodcastSearchResult extends SearchResultBase {
|
||||||
|
kind: "podcast"
|
||||||
|
/** Podcast data */
|
||||||
|
podcast: Podcast
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A single episode found by directory search. `podcast` is its parent show
|
||||||
|
* — used for display context and for subscribing to the show. */
|
||||||
|
export interface EpisodeSearchResult extends SearchResultBase {
|
||||||
|
kind: "episode"
|
||||||
|
podcast: Podcast
|
||||||
|
episode: Episode
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Search result */
|
||||||
|
export type SearchResult = PodcastSearchResult | EpisodeSearchResult
|
||||||
|
|
||||||
/** Default podcast sources */
|
/** Default podcast sources */
|
||||||
export const DEFAULT_SOURCES: PodcastSource[] = [
|
export const DEFAULT_SOURCES: PodcastSource[] = [
|
||||||
{
|
{
|
||||||
@@ -106,11 +141,14 @@ export const DEFAULT_SOURCES: PodcastSource[] = [
|
|||||||
allowExplicit: true,
|
allowExplicit: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "rss",
|
id: "podcastindex",
|
||||||
name: "RSS Feed",
|
name: "Podcast Index",
|
||||||
type: SourceType.RSS,
|
type: SourceType.API,
|
||||||
baseUrl: "",
|
baseUrl: "https://api.podcastindex.org/api/1.0/search/byterm",
|
||||||
enabled: true,
|
enabled: false,
|
||||||
description: "Add podcasts via RSS feed URL",
|
description:
|
||||||
|
"Open podcast directory. Fallback when other sources return few results; requires a free API key + secret from podcastindex.org.",
|
||||||
|
language: "en",
|
||||||
|
allowExplicit: true,
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -274,7 +274,7 @@ function CommandDialog(props: {
|
|||||||
{/* Search input */}
|
{/* Search input */}
|
||||||
<box marginBottom={1}>
|
<box marginBottom={1}>
|
||||||
<text fg={theme.textMuted}>{"> "}</text>
|
<text fg={theme.textMuted}>{"> "}</text>
|
||||||
<text fg={theme.text}>{filter() || "Type to search commands..."}</text>
|
<text fg={theme.accent}>{filter() || "Type to search commands..."}</text>
|
||||||
</box>
|
</box>
|
||||||
|
|
||||||
{/* Command list */}
|
{/* Command list */}
|
||||||
|
|||||||
@@ -7,7 +7,8 @@
|
|||||||
* No backups — writes always overwrite.
|
* No backups — writes always overwrite.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { ensureConfigDir, getConfigFilePath } from "./config-dir";
|
import { mkdirSync, writeFileSync } from "fs";
|
||||||
|
import { ensureConfigDir, getConfigDir, getConfigFilePath } from "./config-dir";
|
||||||
import { loadConfig, updateConfig } from "./config";
|
import { loadConfig, updateConfig } from "./config";
|
||||||
import type {
|
import type {
|
||||||
AppState,
|
AppState,
|
||||||
@@ -20,6 +21,7 @@ import { DEFAULT_THEME } from "../constants/themes";
|
|||||||
// --- Defaults ---
|
// --- Defaults ---
|
||||||
|
|
||||||
const defaultVisualizerSettings: VisualizerSettings = {
|
const defaultVisualizerSettings: VisualizerSettings = {
|
||||||
|
enabled: true,
|
||||||
bars: 32,
|
bars: 32,
|
||||||
sensitivity: 1,
|
sensitivity: 1,
|
||||||
noiseReduction: 0.77,
|
noiseReduction: 0.77,
|
||||||
@@ -31,16 +33,22 @@ const defaultSettings: AppSettings = {
|
|||||||
theme: "system",
|
theme: "system",
|
||||||
fontSize: 14,
|
fontSize: 14,
|
||||||
playbackSpeed: 1,
|
playbackSpeed: 1,
|
||||||
|
volume: 1,
|
||||||
downloadPath: "",
|
downloadPath: "",
|
||||||
transparentBackground: false,
|
transparentBackground: false,
|
||||||
|
showSelectionMarker: false,
|
||||||
visualizer: defaultVisualizerSettings,
|
visualizer: defaultVisualizerSettings,
|
||||||
};
|
};
|
||||||
|
|
||||||
const defaultPreferences: UserPreferences = {
|
const defaultPreferences: UserPreferences = {
|
||||||
showExplicit: false,
|
showExplicit: false,
|
||||||
autoDownload: false,
|
autoDownload: false,
|
||||||
|
autoDownloadCount: 2,
|
||||||
|
autoDownloadScope: "all",
|
||||||
|
autoDownloadWhitelist: [],
|
||||||
autoJumpToPlayer: true,
|
autoJumpToPlayer: true,
|
||||||
fetchMoreMode: "manual",
|
fetchMoreMode: "auto",
|
||||||
|
refreshIntervalMinutes: 30,
|
||||||
};
|
};
|
||||||
|
|
||||||
const defaultState: AppState = {
|
const defaultState: AppState = {
|
||||||
@@ -57,7 +65,18 @@ export async function loadAppStateFromFile(): Promise<AppState> {
|
|||||||
const cfg = await loadConfig();
|
const cfg = await loadConfig();
|
||||||
if (!cfg || typeof cfg !== "object") return defaultState;
|
if (!cfg || typeof cfg !== "object") return defaultState;
|
||||||
return {
|
return {
|
||||||
settings: { ...defaultSettings, ...cfg.settings },
|
settings: {
|
||||||
|
...defaultSettings,
|
||||||
|
...cfg.settings,
|
||||||
|
// Visualizer is nested: a plain spread would let a config
|
||||||
|
// saved before a field was added (e.g. `enabled`) clobber
|
||||||
|
// the whole object and leave the new field undefined.
|
||||||
|
// Deep-merge so defaults backfill missing nested keys.
|
||||||
|
visualizer: {
|
||||||
|
...defaultVisualizerSettings,
|
||||||
|
...cfg.settings?.visualizer,
|
||||||
|
},
|
||||||
|
},
|
||||||
preferences: { ...defaultPreferences, ...cfg.preferences },
|
preferences: { ...defaultPreferences, ...cfg.preferences },
|
||||||
customTheme: { ...DEFAULT_THEME, ...cfg.customTheme },
|
customTheme: { ...DEFAULT_THEME, ...cfg.customTheme },
|
||||||
};
|
};
|
||||||
@@ -119,6 +138,39 @@ export function saveProgressToFile(data: Record<string, unknown>): void {
|
|||||||
})();
|
})();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Search History (separate file — changes on every search) ────────────────
|
||||||
|
|
||||||
|
const SEARCH_HISTORY_FILE = "search-history.json";
|
||||||
|
|
||||||
|
/** Load search history from JSON file */
|
||||||
|
export async function loadSearchHistoryFromFile(): Promise<string[]> {
|
||||||
|
try {
|
||||||
|
const file = Bun.file(getConfigFilePath(SEARCH_HISTORY_FILE));
|
||||||
|
if (!(await file.exists())) return [];
|
||||||
|
|
||||||
|
const raw = await file.json();
|
||||||
|
if (!Array.isArray(raw)) return [];
|
||||||
|
return raw.filter((item): item is string => typeof item === "string");
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Save search history to JSON file (overwrite, no backup) */
|
||||||
|
export function saveSearchHistoryToFile(history: string[]): void {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
await ensureConfigDir();
|
||||||
|
await Bun.write(
|
||||||
|
getConfigFilePath(SEARCH_HISTORY_FILE),
|
||||||
|
JSON.stringify(history, null, 2),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// Silently ignore write errors
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
// ── Audio Nav State (separate file — changes on every track change) ──────────
|
// ── Audio Nav State (separate file — changes on every track change) ──────────
|
||||||
|
|
||||||
const AUDIO_NAV_FILE = "audio-nav.json";
|
const AUDIO_NAV_FILE = "audio-nav.json";
|
||||||
@@ -152,3 +204,70 @@ export function saveAudioNavToFile<T>(data: T): void {
|
|||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Last Player State (separate file — written on every load/stop) ──────────
|
||||||
|
|
||||||
|
const LAST_PLAYER_FILE = "last-player.json";
|
||||||
|
|
||||||
|
/** Which episode is currently loaded in the player, persisted so the next
|
||||||
|
* launch can restore it paused. `episodeId: null` means the player is empty
|
||||||
|
* (e.g. after Stop). */
|
||||||
|
export interface LastPlayerState {
|
||||||
|
episodeId: string | null;
|
||||||
|
timestamp: string | Date | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Load the last-loaded-player marker (null when absent or unreadable) */
|
||||||
|
export async function loadLastPlayerFromFile(): Promise<LastPlayerState | null> {
|
||||||
|
try {
|
||||||
|
const file = Bun.file(getConfigFilePath(LAST_PLAYER_FILE));
|
||||||
|
if (!(await file.exists())) return null;
|
||||||
|
|
||||||
|
const raw = await file.json();
|
||||||
|
if (!raw || typeof raw !== "object") return null;
|
||||||
|
|
||||||
|
return raw as LastPlayerState;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Serialized marker-write chain: concurrent writes land in submission
|
||||||
|
* order, and callers can await the last one (tests read the file back
|
||||||
|
* deterministically). Mirrors updateConfig's write serialization. */
|
||||||
|
let lastPlayerWriteChain: Promise<void> = Promise.resolve();
|
||||||
|
|
||||||
|
/** Save the last-loaded-player marker (fire-and-forget) */
|
||||||
|
export function saveLastPlayerToFile(state: LastPlayerState): void {
|
||||||
|
lastPlayerWriteChain = lastPlayerWriteChain.then(async () => {
|
||||||
|
try {
|
||||||
|
await ensureConfigDir();
|
||||||
|
await Bun.write(
|
||||||
|
getConfigFilePath(LAST_PLAYER_FILE),
|
||||||
|
JSON.stringify(state, null, 2),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// Silently ignore write errors
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolves once every marker write submitted so far has landed on disk. */
|
||||||
|
export function waitForLastPlayerWrite(): Promise<void> {
|
||||||
|
return lastPlayerWriteChain;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Synchronous variant for the process-exit teardown. `q` quits through
|
||||||
|
* `process.exit(0)`, which runs exit listeners synchronously — an async
|
||||||
|
* write would never land. */
|
||||||
|
export function saveLastPlayerSync(state: LastPlayerState): void {
|
||||||
|
try {
|
||||||
|
mkdirSync(getConfigDir(), { recursive: true });
|
||||||
|
writeFileSync(
|
||||||
|
getConfigFilePath(LAST_PLAYER_FILE),
|
||||||
|
JSON.stringify(state, null, 2),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// Silently ignore write errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
385
src/utils/audio-pcm-cache.ts
Normal file
@@ -0,0 +1,385 @@
|
|||||||
|
/**
|
||||||
|
* Position-indexed PCM cache for visualization.
|
||||||
|
*
|
||||||
|
* One ffmpeg process decodes the episode's audio at 4x realtime (with an
|
||||||
|
* 8s initial burst — fast enough to serve bars and seeks instantly, throttled
|
||||||
|
* enough that a remote episode isn't ripped at 84x while mpv is trying to
|
||||||
|
* start playback) into an in-memory cache indexed by ABSOLUTE playback time.
|
||||||
|
* The renderer then reads the PCM
|
||||||
|
* window ending at the player's current position with zero sync machinery:
|
||||||
|
* there is no pacing (-readrate), no lead-burst, no decode-head/player
|
||||||
|
* drift math, no ring wrap, and nothing that knows or cares about pause,
|
||||||
|
* resume, seek, or playback speed — those all collapse to "read at a
|
||||||
|
* different position in the cache".
|
||||||
|
*
|
||||||
|
* Pause/resume contract (the failure mode of the old design):
|
||||||
|
* - pauseDecode() kills ffmpeg but KEEPS the cache. Resume reads from it
|
||||||
|
* instantly and resumes the tail decode in the background.
|
||||||
|
* - Reads outside decoded coverage (startup, seek into an undecoded hole)
|
||||||
|
* return 0 — the renderer HOLDS the last rendered frame rather than
|
||||||
|
* freezing on a clamped buffer or decaying into junk bars.
|
||||||
|
*
|
||||||
|
* Seeks into undecoded territory start a fresh SEGMENT (a second decode
|
||||||
|
* pass over just that region) — earlier segments stay valid, mp3 decode of
|
||||||
|
* the same file is deterministic so abutting segments agree.
|
||||||
|
*
|
||||||
|
* Memory: 22050 Hz mono s16 ≈ 44 KB/s ≈ 2.6 MB/min (~80 MB per 30 min),
|
||||||
|
* freed on stop(). 22050 Hz covers Nyquist 11 kHz, above the default 10 kHz
|
||||||
|
* high-cutoff of the visualizer's FFT config.
|
||||||
|
*
|
||||||
|
* Downloads via ffmpeg's own http stack with reconnect flags, matching the
|
||||||
|
* old reader; local files skip them (ffmpeg rejects http-only options for
|
||||||
|
* file inputs).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { Subprocess } from "bun";
|
||||||
|
|
||||||
|
/** PCM output format constants */
|
||||||
|
export const PCM_SAMPLE_RATE = 22050;
|
||||||
|
const BYTES_PER_SAMPLE = 2; // s16le
|
||||||
|
|
||||||
|
/** Initial segment capacity: 4 Mi samples ≈ 190 s of audio (8 MB). */
|
||||||
|
const INITIAL_CAPACITY_SAMPLES = 4 * 1024 * 1024;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gap (seconds) a running decode pass may close on its own before a restart
|
||||||
|
* at the seek target is cheaper than waiting: at 4x pacing, 15s of undecoded
|
||||||
|
* audio closes in ~4s — about the cost of a network reconnect + range
|
||||||
|
* request for a fresh ffmpeg pass. Beyond the gap, restart at the target.
|
||||||
|
*/
|
||||||
|
const CLOSE_IN_PLACE_GAP_SEC = 15;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Monotonically increasing generation counter.
|
||||||
|
* Each startDecode() increments this; the read loop checks it to know
|
||||||
|
* if it's been superseded and should bail out.
|
||||||
|
*/
|
||||||
|
let globalGeneration = 0;
|
||||||
|
|
||||||
|
interface Segment {
|
||||||
|
/** Playback seconds where this segment's first sample sits. */
|
||||||
|
baseSec: number;
|
||||||
|
/** Sample buffer; capacity >= written, doubled on overflow. */
|
||||||
|
samples: Int16Array;
|
||||||
|
/** Samples written so far (== decoded length of the segment). */
|
||||||
|
written: number;
|
||||||
|
/** ffmpeg reached stream EOF while writing this segment — nothing more
|
||||||
|
* will ever arrive after its end. */
|
||||||
|
finished: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EpisodePcmCacheOptions {
|
||||||
|
/** Audio URL or file path to decode */
|
||||||
|
url: string;
|
||||||
|
/** Sample rate (default: 22050) */
|
||||||
|
sampleRate?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class EpisodePcmCache {
|
||||||
|
private proc: Subprocess | null = null;
|
||||||
|
private segments: Segment[] = [];
|
||||||
|
private generation = 0;
|
||||||
|
private _decoding = false;
|
||||||
|
/** The running pass's segment (base + frontier); null when idle. */
|
||||||
|
private activeSegment: Segment | null = null;
|
||||||
|
readonly url: string;
|
||||||
|
readonly sampleRate: number;
|
||||||
|
|
||||||
|
constructor(options: EpisodePcmCacheOptions) {
|
||||||
|
this.url = options.url;
|
||||||
|
this.sampleRate = options.sampleRate ?? PCM_SAMPLE_RATE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether an ffmpeg decode pass is currently running. */
|
||||||
|
get decoding(): boolean {
|
||||||
|
return this._decoding;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Base (playback seconds) of the running decode pass; null when idle. */
|
||||||
|
get activeDecodeBaseSec(): number | null {
|
||||||
|
return this._decoding && this.activeSegment
|
||||||
|
? this.activeSegment.baseSec
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** End (playback seconds) of the furthest-decoded segment. */
|
||||||
|
get coverageEndSec(): number {
|
||||||
|
let end = 0;
|
||||||
|
for (const seg of this.segments) {
|
||||||
|
const segEnd = seg.baseSec + seg.written / this.sampleRate;
|
||||||
|
if (segEnd > end) end = segEnd;
|
||||||
|
}
|
||||||
|
return end;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the furthest segment finished at stream EOF. */
|
||||||
|
get decodeFinished(): boolean {
|
||||||
|
let maxEnd = -1;
|
||||||
|
let finished = false;
|
||||||
|
for (const seg of this.segments) {
|
||||||
|
const segEnd = seg.baseSec + seg.written / this.sampleRate;
|
||||||
|
if (segEnd > maxEnd) {
|
||||||
|
maxEnd = segEnd;
|
||||||
|
finished = seg.finished;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return finished;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start decoding at `fromSec` of playback time into a fresh segment.
|
||||||
|
* Kills any in-flight pass first; existing segments stay readable.
|
||||||
|
*/
|
||||||
|
startDecode(fromSec: number): void {
|
||||||
|
this.killProcess();
|
||||||
|
|
||||||
|
if (!Bun.which("ffmpeg")) {
|
||||||
|
throw new Error("ffmpeg not found — required for audio visualization");
|
||||||
|
}
|
||||||
|
|
||||||
|
this.generation = ++globalGeneration;
|
||||||
|
const myGeneration = this.generation;
|
||||||
|
|
||||||
|
const segment: Segment = {
|
||||||
|
baseSec: Math.max(0, fromSec),
|
||||||
|
samples: new Int16Array(INITIAL_CAPACITY_SAMPLES),
|
||||||
|
written: 0,
|
||||||
|
finished: false,
|
||||||
|
};
|
||||||
|
this.segments.push(segment);
|
||||||
|
|
||||||
|
const args = ["ffmpeg", "-loglevel", "quiet"];
|
||||||
|
|
||||||
|
// Pace the decode at 4x realtime (with an 8s initial burst) instead of
|
||||||
|
// flat-out: unthrottled decode measures ~84x realtime, which pulls the
|
||||||
|
// ENTIRE episode from the network within the first minute of playback
|
||||||
|
// (~160MB/hr) and starves mpv's own buffering right at startup. 4x
|
||||||
|
// still fills the cache 4x faster than playback consumes it, lands a
|
||||||
|
// 75-min episode in ~19 min of background work, and the burst makes
|
||||||
|
// the first bars available immediately.
|
||||||
|
args.push("-readrate", "4", "-readrate_initial_burst", "8");
|
||||||
|
|
||||||
|
// `-reconnect*` are http-protocol options: ffmpeg rejects them at
|
||||||
|
// input-open when the input is a local file, killing the process
|
||||||
|
// before any PCM is produced. Only pass them for network URLs.
|
||||||
|
if (/^https?:\/\//i.test(this.url)) {
|
||||||
|
args.push(
|
||||||
|
"-reconnect",
|
||||||
|
"1",
|
||||||
|
"-reconnect_streamed",
|
||||||
|
"1",
|
||||||
|
"-reconnect_delay_max",
|
||||||
|
"5",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seek before input for network efficiency (container-level skip is
|
||||||
|
// near-instant for mp3/aac; no pre-position decode burn).
|
||||||
|
if (fromSec > 0) {
|
||||||
|
args.push("-ss", String(Math.max(0, fromSec)));
|
||||||
|
}
|
||||||
|
|
||||||
|
args.push(
|
||||||
|
"-i",
|
||||||
|
this.url,
|
||||||
|
"-ac",
|
||||||
|
"1",
|
||||||
|
"-ar",
|
||||||
|
String(this.sampleRate),
|
||||||
|
"-f",
|
||||||
|
"s16le",
|
||||||
|
"-acodec",
|
||||||
|
"pcm_s16le",
|
||||||
|
"-",
|
||||||
|
);
|
||||||
|
|
||||||
|
this.proc = Bun.spawn(args, {
|
||||||
|
stdout: "pipe",
|
||||||
|
stderr: "ignore",
|
||||||
|
stdin: "ignore",
|
||||||
|
});
|
||||||
|
this._decoding = true;
|
||||||
|
this.activeSegment = segment;
|
||||||
|
this.readLoop(myGeneration, segment);
|
||||||
|
|
||||||
|
this.proc.exited
|
||||||
|
.then((code) => {
|
||||||
|
if (this.generation === myGeneration) {
|
||||||
|
this._decoding = false;
|
||||||
|
this.activeSegment = null;
|
||||||
|
// Exit 0 == decoded to stream EOF.
|
||||||
|
if (code === 0) segment.finished = true;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (this.generation === myGeneration) {
|
||||||
|
this._decoding = false;
|
||||||
|
this.activeSegment = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether `sec` of playback time has decoded PCM on hand.
|
||||||
|
*/
|
||||||
|
covers(sec: number): boolean {
|
||||||
|
const idx = Math.round(sec * this.sampleRate);
|
||||||
|
for (const seg of this.segments) {
|
||||||
|
const base = Math.round(seg.baseSec * this.sampleRate);
|
||||||
|
if (idx >= base && idx < base + seg.written) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Make sure decode is progressing toward `sec`: no-op while a pass is
|
||||||
|
* running or the episode is fully decoded; otherwise resumes the tail
|
||||||
|
* decode from the frontier (when `sec` is inside coverage) or starts a
|
||||||
|
* new segment at `sec` (seek into a hole / resume past cached audio).
|
||||||
|
*/
|
||||||
|
ensureDecodeAround(sec: number): void {
|
||||||
|
// Data already on hand: nothing needed here; only keep the tail
|
||||||
|
// filling if the decode is idle and the episode is unfinished.
|
||||||
|
if (this.covers(sec)) {
|
||||||
|
if (this._decoding || this.decodeFinished) return;
|
||||||
|
this.startDecode(this.coverageEndSec > sec ? this.coverageEndSec : sec);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this._decoding && this.activeSegment !== null) {
|
||||||
|
// A decode pass fills monotonically FORWARD from its base. Targets
|
||||||
|
// behind the base are unreachable — restart at the target.
|
||||||
|
if (sec < this.activeSegment.baseSec) {
|
||||||
|
this.startDecode(Math.max(0, sec));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Target past the pass's frontier: a SMALL gap closes on its own
|
||||||
|
// (4x pacing covers 15s in ~4s — about what a cold restart costs
|
||||||
|
// to reconnect + range-request a network stream), but a FAR-FORWARD
|
||||||
|
// seek would otherwise mean minutes of frozen bars while the pass
|
||||||
|
// chews through the skipped region. Restart at the target.
|
||||||
|
const frontier =
|
||||||
|
this.activeSegment.baseSec + this.activeSegment.written / this.sampleRate;
|
||||||
|
if (sec - frontier <= CLOSE_IN_PLACE_GAP_SEC) return;
|
||||||
|
}
|
||||||
|
this.startDecode(Math.max(0, sec));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read the PCM window ENDING at `atSec` of playback into `out`
|
||||||
|
* (Int16 magnitudes widened to f64, the scale cavacore expects).
|
||||||
|
*
|
||||||
|
* Returns the number of samples written: `out.length` on a full hit, 0
|
||||||
|
* when the window is not (fully) decoded yet — the caller HOLDS the
|
||||||
|
* last rendered frame instead of rendering partial/stale data.
|
||||||
|
*/
|
||||||
|
readWindow(out: Float64Array, atSec: number): number {
|
||||||
|
if (out.length === 0) return 0;
|
||||||
|
const endIdx = Math.round(atSec * this.sampleRate);
|
||||||
|
const startIdx = endIdx - out.length + 1;
|
||||||
|
for (const seg of this.segments) {
|
||||||
|
const base = Math.round(seg.baseSec * this.sampleRate);
|
||||||
|
if (startIdx < base || endIdx >= base + seg.written) continue;
|
||||||
|
const rel = startIdx - base;
|
||||||
|
const src = seg.samples;
|
||||||
|
for (let i = 0; i < out.length; i++) {
|
||||||
|
out[i] = src[rel + i];
|
||||||
|
}
|
||||||
|
return out.length;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pause contract: kill the ffmpeg pass but KEEP every decoded segment.
|
||||||
|
* Resume later serves bars from the cache instantly.
|
||||||
|
*/
|
||||||
|
pauseDecode(): void {
|
||||||
|
this.generation = ++globalGeneration;
|
||||||
|
this._decoding = false;
|
||||||
|
this.activeSegment = null;
|
||||||
|
this.killProcess();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Kill the decode pass AND drop all cached audio. */
|
||||||
|
stop(): void {
|
||||||
|
this.pauseDecode();
|
||||||
|
this.segments = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Kill the ffmpeg process without touching generation/state. */
|
||||||
|
private killProcess(): void {
|
||||||
|
if (this.proc) {
|
||||||
|
try {
|
||||||
|
this.proc.kill();
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
this.proc = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Internal: continuously reads stdout from ffmpeg and appends samples
|
||||||
|
* to the segment at their absolute playback-time offsets. */
|
||||||
|
private async readLoop(myGeneration: number, segment: Segment): Promise<void> {
|
||||||
|
const stdout = this.proc?.stdout;
|
||||||
|
if (!stdout || typeof stdout === "number") return;
|
||||||
|
|
||||||
|
const reader = (stdout as ReadableStream<Uint8Array>).getReader();
|
||||||
|
// s16 sample pairs can straddle pipe chunk boundaries: carry a lone
|
||||||
|
// trailing byte into the next chunk (dropping it would byte-flip
|
||||||
|
// every sample that follows).
|
||||||
|
let carry: number | null = null;
|
||||||
|
try {
|
||||||
|
while (this.generation === myGeneration) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done || this.generation !== myGeneration) break;
|
||||||
|
if (!value || value.byteLength === 0) continue;
|
||||||
|
|
||||||
|
let view: Uint8Array = value;
|
||||||
|
if (carry !== null) {
|
||||||
|
const merged = new Uint8Array(1 + value.byteLength);
|
||||||
|
merged[0] = carry;
|
||||||
|
merged.set(value, 1);
|
||||||
|
view = merged;
|
||||||
|
carry = null;
|
||||||
|
}
|
||||||
|
if (view.byteLength % BYTES_PER_SAMPLE !== 0) {
|
||||||
|
carry = view[view.byteLength - 1];
|
||||||
|
view = view.subarray(0, view.byteLength - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sampleCount = view.byteLength / BYTES_PER_SAMPLE;
|
||||||
|
if (sampleCount === 0) continue;
|
||||||
|
|
||||||
|
if (segment.written + sampleCount > segment.samples.length) {
|
||||||
|
const grown = new Int16Array(
|
||||||
|
Math.max(
|
||||||
|
segment.samples.length * 2,
|
||||||
|
segment.written + sampleCount,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
grown.set(segment.samples.subarray(0, segment.written));
|
||||||
|
segment.samples = grown;
|
||||||
|
}
|
||||||
|
// Int16Array view over the byte buffer: s16le is the platform's
|
||||||
|
// native endianness on every supported target (arm64/x64 are LE).
|
||||||
|
const src = new Int16Array(
|
||||||
|
view.buffer,
|
||||||
|
view.byteOffset,
|
||||||
|
sampleCount,
|
||||||
|
);
|
||||||
|
segment.samples.set(src, segment.written);
|
||||||
|
segment.written += sampleCount;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Stream ended or process killed — expected during stop()
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
reader.releaseLock();
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,12 +6,31 @@
|
|||||||
* restart. When mpv isn't installed there is no fallback: the no-op backend
|
* restart. When mpv isn't installed there is no fallback: the no-op backend
|
||||||
* surfaces "No audio player found" honestly rather than degrading through
|
* surfaces "No audio player found" honestly rather than degrading through
|
||||||
* players that can't change speed/volume without restarting.
|
* players that can't change speed/volume without restarting.
|
||||||
|
*
|
||||||
|
* The backend owns ONE RESIDENT mpv daemon (`--idle=yes --keep-open=yes`)
|
||||||
|
* for the app's lifetime instead of spawning a fresh player per episode:
|
||||||
|
*
|
||||||
|
* - Play/pause/seek are IPC commands on a persistent Unix-socket
|
||||||
|
* connection — no process spawn, no socket connect/disconnect churn per
|
||||||
|
* poll, no `waitForSocket` on the play path. Measured command latency is
|
||||||
|
* single-digit ms; a mid-episode resume after pause takes ~300ms on a
|
||||||
|
* network stream.
|
||||||
|
* - State (time-pos, pause, duration) is OBSERVED (`observe_property`):
|
||||||
|
* mpv pushes time-pos at ~20Hz while playing, so `getPosition()` /
|
||||||
|
* `getPauseState()` read a cache instead of round-tripping the socket on
|
||||||
|
* every 150ms UI tick. External pauses (AirPod removal, system sleep,
|
||||||
|
* Now Playing center) arrive as pause property events with zero polling.
|
||||||
|
* - A restored session can PRELOAD: the episode is loaded paused so mpv
|
||||||
|
* fills its demuxer cache ahead of time; the first real play just flips
|
||||||
|
* `pause` to false — the ~2s network open is paid at boot, not on the
|
||||||
|
* user's first Play.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { platform } from "os";
|
import { platform } from "os";
|
||||||
import { existsSync } from "fs";
|
import { existsSync, unlinkSync } from "fs";
|
||||||
import { tmpdir } from "os";
|
import { tmpdir } from "os";
|
||||||
import { join } from "path";
|
import { join } from "path";
|
||||||
|
import type { Socket, Subprocess } from "bun";
|
||||||
|
|
||||||
// ── Types ────────────────────────────────────────────────────────────
|
// ── Types ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -30,6 +49,17 @@ export interface AudioState {
|
|||||||
export interface AudioBackend {
|
export interface AudioBackend {
|
||||||
readonly name: BackendName;
|
readonly name: BackendName;
|
||||||
play(url: string, opts?: PlayOptions): Promise<void>;
|
play(url: string, opts?: PlayOptions): Promise<void>;
|
||||||
|
/**
|
||||||
|
* Load the URL paused WITHOUT starting playback, so the player buffers
|
||||||
|
* ahead of the user's first Play (used for boot session restore).
|
||||||
|
* A subsequent play() of the SAME url flips pause off — near-instant.
|
||||||
|
*/
|
||||||
|
preload(url: string, opts?: PlayOptions): Promise<void>;
|
||||||
|
/**
|
||||||
|
* Attach a cover-art image to the currently-loaded file at runtime
|
||||||
|
* (mpv `video-add`). Lets play() start without waiting on art; the
|
||||||
|
* Now Playing artwork pops in when the download lands.
|
||||||
|
*/
|
||||||
pause(): Promise<void>;
|
pause(): Promise<void>;
|
||||||
resume(): Promise<void>;
|
resume(): Promise<void>;
|
||||||
stop(): Promise<void>;
|
stop(): Promise<void>;
|
||||||
@@ -39,6 +69,15 @@ export interface AudioBackend {
|
|||||||
getPosition(): Promise<number>;
|
getPosition(): Promise<number>;
|
||||||
getDuration(): Promise<number>;
|
getDuration(): Promise<number>;
|
||||||
isPlaying(): boolean;
|
isPlaying(): boolean;
|
||||||
|
/** Live pause state: `true` paused, `false` playing, `undefined` when
|
||||||
|
* unknown (player unreachable / not yet loaded). Unlike `isPlaying()` —
|
||||||
|
* which reflects only commands PodTUI sent — this reflects the player's
|
||||||
|
* real state, including pauses initiated OUTSIDE PodTUI (system
|
||||||
|
* sleep/lock, AirPod removal, device swap, OS media keys, the Now
|
||||||
|
* Playing center). */
|
||||||
|
getPauseState(): Promise<boolean | undefined>;
|
||||||
|
/** True while the player process is running (regardless of pause). */
|
||||||
|
isAlive(): boolean;
|
||||||
dispose(): void;
|
dispose(): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,6 +85,8 @@ export interface PlayOptions {
|
|||||||
startPosition?: number;
|
startPosition?: number;
|
||||||
volume?: number;
|
volume?: number;
|
||||||
speed?: number;
|
speed?: number;
|
||||||
|
mediaTitle?: string;
|
||||||
|
coverArtPath?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Utilities ────────────────────────────────────────────────────────
|
// ── Utilities ────────────────────────────────────────────────────────
|
||||||
@@ -68,278 +109,521 @@ function which(cmd: string): string | null {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mpvInstance = 0;
|
||||||
function mpvSocketPath(): string {
|
function mpvSocketPath(): string {
|
||||||
return join(tmpdir(), `podtui-mpv-${process.pid}.sock`);
|
// Per-instance, not just per-pid: tests (and backend switching) create
|
||||||
|
// several MpvBackend objects in ONE bun process — a pid-only path makes
|
||||||
|
// every daemon bind the same socket, so later daemons unlink the path
|
||||||
|
// out from under each other.
|
||||||
|
return join(
|
||||||
|
tmpdir(),
|
||||||
|
`podtui-mpv-${process.pid}-${mpvInstance++}.sock`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── mpv JSON IPC connection ─────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// One persistent Unix-socket connection to the resident mpv daemon. Lines
|
||||||
|
// from mpv are either command responses (`request_id` present — correlated
|
||||||
|
// to the pending promise) or unsolicited traffic (property-change events
|
||||||
|
// from `observe_property`, end-file, ...), dispatched to the event handler.
|
||||||
|
|
||||||
|
interface MpvResponse {
|
||||||
|
error?: string;
|
||||||
|
data?: unknown;
|
||||||
|
request_id?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MpvEvent {
|
||||||
|
event: string;
|
||||||
|
/** Observation id for property-change events. */
|
||||||
|
id?: number;
|
||||||
|
name?: string;
|
||||||
|
data?: unknown;
|
||||||
|
reason?: string;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type MpvEventHandler = (msg: MpvEvent) => void;
|
||||||
|
|
||||||
|
class MpvConnection {
|
||||||
|
private sock: Socket | null = null;
|
||||||
|
private buf = "";
|
||||||
|
private nextId = 1;
|
||||||
|
private pending = new Map<number, (msg: MpvResponse) => void>();
|
||||||
|
private eventWaiters = new Map<string, Array<(msg: MpvEvent) => void>>();
|
||||||
|
onEvent: MpvEventHandler = () => {};
|
||||||
|
|
||||||
|
async connect(path: string): Promise<void> {
|
||||||
|
const { promise, resolve, reject } = Promise.withResolvers<void>();
|
||||||
|
let settled = false;
|
||||||
|
Bun.connect({
|
||||||
|
unix: path,
|
||||||
|
socket: {
|
||||||
|
open: (socket) => {
|
||||||
|
this.sock = socket;
|
||||||
|
if (!settled) {
|
||||||
|
settled = true;
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
data: (_socket, data) => this.onData(data),
|
||||||
|
error: (_socket, err) => {
|
||||||
|
if (!settled) {
|
||||||
|
settled = true;
|
||||||
|
reject(err);
|
||||||
|
}
|
||||||
|
this.handleTeardown();
|
||||||
|
},
|
||||||
|
close: () => this.handleTeardown(),
|
||||||
|
},
|
||||||
|
}).catch((err) => {
|
||||||
|
if (!settled) {
|
||||||
|
settled = true;
|
||||||
|
reject(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
private onData(data: Uint8Array): void {
|
||||||
|
this.buf += Buffer.from(data).toString();
|
||||||
|
let nl = this.buf.indexOf("\n");
|
||||||
|
while (nl !== -1) {
|
||||||
|
const line = this.buf.slice(0, nl);
|
||||||
|
this.buf = this.buf.slice(nl + 1);
|
||||||
|
nl = this.buf.indexOf("\n");
|
||||||
|
if (!line.trim()) continue;
|
||||||
|
let msg: Record<string, unknown>;
|
||||||
|
try {
|
||||||
|
msg = JSON.parse(line) as Record<string, unknown>;
|
||||||
|
} catch {
|
||||||
|
continue; // skip malformed lines
|
||||||
|
}
|
||||||
|
if (msg.request_id !== undefined) {
|
||||||
|
const resolve = this.pending.get(msg.request_id as number);
|
||||||
|
if (resolve) {
|
||||||
|
this.pending.delete(msg.request_id as number);
|
||||||
|
resolve(msg as MpvResponse);
|
||||||
|
}
|
||||||
|
} else if (typeof msg.event === "string") {
|
||||||
|
const event = msg as unknown as MpvEvent;
|
||||||
|
this.onEvent(event);
|
||||||
|
const waiters = this.eventWaiters.get(event.event);
|
||||||
|
if (waiters) {
|
||||||
|
this.eventWaiters.delete(event.event);
|
||||||
|
for (const w of waiters) w(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Socket died / daemon gone: fail all pending commands so no caller
|
||||||
|
* hangs on a dead connection. */
|
||||||
|
private handleTeardown(): void {
|
||||||
|
for (const resolve of this.pending.values()) {
|
||||||
|
resolve({ error: "connection-lost" });
|
||||||
|
}
|
||||||
|
this.pending.clear();
|
||||||
|
this.sock = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Send a command and await mpv's response (correlated by request_id).
|
||||||
|
* Resolves `{ error: "timeout" }` instead of hanging when mpv stalls. */
|
||||||
|
send(command: unknown[], timeoutMs = 2000): Promise<MpvResponse> {
|
||||||
|
const sock = this.sock;
|
||||||
|
if (!sock) return Promise.resolve({ error: "not-connected" });
|
||||||
|
const id = this.nextId++;
|
||||||
|
const { promise, resolve } = Promise.withResolvers<MpvResponse>();
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
if (this.pending.delete(id)) resolve({ error: "timeout" });
|
||||||
|
}, timeoutMs);
|
||||||
|
this.pending.set(id, (msg) => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
resolve(msg);
|
||||||
|
});
|
||||||
|
sock.write(JSON.stringify({ command, request_id: id }) + "\n");
|
||||||
|
return promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One-shot wait for an mpv event by name. Register BEFORE the command
|
||||||
|
* that triggers it. Resolves null on timeout instead of hanging. */
|
||||||
|
waitEvent(name: string, timeoutMs = 5000): Promise<MpvEvent | null> {
|
||||||
|
const { promise, resolve } = Promise.withResolvers<MpvEvent | null>();
|
||||||
|
const list = this.eventWaiters.get(name) ?? [];
|
||||||
|
list.push(resolve);
|
||||||
|
this.eventWaiters.set(name, list);
|
||||||
|
setTimeout(() => {
|
||||||
|
const current = this.eventWaiters.get(name);
|
||||||
|
if (current) {
|
||||||
|
this.eventWaiters.set(
|
||||||
|
name,
|
||||||
|
current.filter((w) => w !== resolve),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
resolve(null);
|
||||||
|
}, timeoutMs);
|
||||||
|
return promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
try {
|
||||||
|
this.sock?.end();
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
this.handleTeardown();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── mpv Backend ──────────────────────────────────────────────────────
|
// ── mpv Backend ──────────────────────────────────────────────────────
|
||||||
// Uses JSON IPC over a Unix socket for full bidirectional control.
|
// One resident daemon for the app's lifetime, controlled over a single
|
||||||
|
// persistent JSON IPC connection with property observation.
|
||||||
|
|
||||||
|
/** Property observation ids (correlate property-change events). */
|
||||||
|
const OBS_TIME_POS = 1;
|
||||||
|
const OBS_PAUSE = 2;
|
||||||
|
const OBS_DURATION = 3;
|
||||||
|
const OBS_EOF = 4;
|
||||||
|
|
||||||
export class MpvBackend implements AudioBackend {
|
export class MpvBackend implements AudioBackend {
|
||||||
readonly name: BackendName = "mpv";
|
readonly name: BackendName = "mpv";
|
||||||
private proc: ReturnType<typeof Bun.spawn> | null = null;
|
private proc: Subprocess | null = null;
|
||||||
private socketPath = mpvSocketPath();
|
private socketPath = mpvSocketPath();
|
||||||
private _playing = false;
|
private conn: MpvConnection | null = null;
|
||||||
|
/** Guarantee daemon startup runs once (concurrent play/preload). */
|
||||||
|
private startPromise: Promise<void> | null = null;
|
||||||
|
|
||||||
|
// Command intent: what PodTUI asked the player to do.
|
||||||
|
private _intentPlaying = false;
|
||||||
|
/** The file currently loaded via loadfile (null = idle). */
|
||||||
|
private _loadedUrl: string | null = null;
|
||||||
|
/** The current file was loadfile'd paused (preload) and not yet played. */
|
||||||
|
private _loadedPaused = false;
|
||||||
|
/** Set on end-file reason "eof"/"error"; cleared by the next loadfile. */
|
||||||
|
private _ended = false;
|
||||||
|
|
||||||
|
// Observed (player-reported) state, pushed by mpv property-change events.
|
||||||
private _position = 0;
|
private _position = 0;
|
||||||
private _duration = 0;
|
private _duration = 0;
|
||||||
|
/** null until the first pause observation arrives. */
|
||||||
|
private _paused: boolean | null = null;
|
||||||
|
|
||||||
private _volume = 100;
|
private _volume = 100;
|
||||||
private _speed = 1;
|
private _speed = 1;
|
||||||
private pollTimer: ReturnType<typeof setInterval> | null = null;
|
private _exited = false;
|
||||||
|
/** Last playback error reported via end-file reason "error". */
|
||||||
|
private _playbackError: string | null = null;
|
||||||
|
|
||||||
async play(url: string, opts?: PlayOptions): Promise<void> {
|
// ── Daemon lifecycle ─────────────────────────────────────────────
|
||||||
await this.stop();
|
|
||||||
|
|
||||||
|
private async ensureDaemon(): Promise<void> {
|
||||||
|
if (this.proc && !this._exited && this.conn) return;
|
||||||
|
if (this.startPromise) return this.startPromise;
|
||||||
|
this.startPromise = this.spawnDaemon().finally(() => {
|
||||||
|
this.startPromise = null;
|
||||||
|
});
|
||||||
|
return this.startPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async spawnDaemon(): Promise<void> {
|
||||||
// Clean up stale socket
|
// Clean up stale socket
|
||||||
try {
|
try {
|
||||||
if (existsSync(this.socketPath)) {
|
|
||||||
const { unlinkSync } = await import("fs");
|
|
||||||
unlinkSync(this.socketPath);
|
unlinkSync(this.socketPath);
|
||||||
}
|
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
}
|
}
|
||||||
|
|
||||||
const args = [
|
this.proc = Bun.spawn(
|
||||||
|
[
|
||||||
"mpv",
|
"mpv",
|
||||||
"--no-video",
|
"--no-video",
|
||||||
"--no-terminal",
|
"--no-terminal",
|
||||||
"--really-quiet",
|
"--really-quiet",
|
||||||
|
// Stay alive after finishing/unloading files; PodTUI owns one mpv
|
||||||
|
// for its whole session and switches episodes via loadfile.
|
||||||
|
"--idle=yes",
|
||||||
|
"--keep-open=yes",
|
||||||
|
// Cap the demuxer cache. mpv's defaults (150MiB) make it race
|
||||||
|
// to fill while a preload sits paused — measured 45MB pulled
|
||||||
|
// within 12s of a boot-restore preload, saturating the link
|
||||||
|
// exactly when everything else is starting up. ~90s forward
|
||||||
|
// target / 40MiB hard cap is a few MB at podcast bitrates:
|
||||||
|
// plenty for instant resume + stall resilience.
|
||||||
|
"--cache-secs=90",
|
||||||
|
"--demuxer-max-bytes=40MiB",
|
||||||
|
"--demuxer-max-back-bytes=20MiB",
|
||||||
`--input-ipc-server=${this.socketPath}`,
|
`--input-ipc-server=${this.socketPath}`,
|
||||||
`--volume=${Math.round((opts?.volume ?? 1) * 100)}`,
|
],
|
||||||
`--speed=${opts?.speed ?? 1}`,
|
{ stdout: "ignore", stderr: "ignore", stdin: "ignore" },
|
||||||
];
|
);
|
||||||
|
this._exited = false;
|
||||||
if (opts?.startPosition && opts.startPosition > 0) {
|
|
||||||
args.push(`--start=${opts.startPosition}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
args.push(url);
|
|
||||||
|
|
||||||
this.proc = Bun.spawn(args, {
|
|
||||||
stdout: "ignore",
|
|
||||||
stderr: "ignore",
|
|
||||||
stdin: "ignore",
|
|
||||||
});
|
|
||||||
|
|
||||||
this._playing = true;
|
|
||||||
this._position = opts?.startPosition ?? 0;
|
|
||||||
this._volume = Math.round((opts?.volume ?? 1) * 100);
|
|
||||||
this._speed = opts?.speed ?? 1;
|
|
||||||
|
|
||||||
// Wait for socket to appear (mpv creates it async)
|
|
||||||
await this.waitForSocket(2000);
|
|
||||||
|
|
||||||
// Start polling position
|
|
||||||
this.startPolling();
|
|
||||||
|
|
||||||
// Detect process exit
|
|
||||||
this.proc.exited
|
this.proc.exited
|
||||||
.then(() => {
|
.then(() => {
|
||||||
this._playing = false;
|
this._exited = true;
|
||||||
this.stopPolling();
|
this._intentPlaying = false;
|
||||||
|
this._loadedUrl = null;
|
||||||
|
this._paused = null;
|
||||||
})
|
})
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
|
||||||
|
|
||||||
private async waitForSocket(timeoutMs: number): Promise<void> {
|
// mpv creates the socket asynchronously (measured ~600ms cold spawn).
|
||||||
const start = Date.now();
|
const start = Date.now();
|
||||||
while (Date.now() - start < timeoutMs) {
|
while (Date.now() - start < 3000) {
|
||||||
if (existsSync(this.socketPath)) return;
|
if (this._exited) break;
|
||||||
|
if (existsSync(this.socketPath)) break;
|
||||||
await new Promise((r) => setTimeout(r, 50));
|
await new Promise((r) => setTimeout(r, 50));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const conn = new MpvConnection();
|
||||||
|
conn.onEvent = (msg) => this.handleEvent(msg);
|
||||||
|
await conn.connect(this.socketPath);
|
||||||
|
this.conn = conn;
|
||||||
|
|
||||||
|
// Observe the state the UI polls: mpv then pushes changes at ~20Hz
|
||||||
|
// while playing and broadcasts external changes (AirPods pull, OS
|
||||||
|
// media keys) with zero polling from our side.
|
||||||
|
await this.send(["observe_property", OBS_TIME_POS, "time-pos"]);
|
||||||
|
await this.send(["observe_property", OBS_PAUSE, "pause"]);
|
||||||
|
await this.send(["observe_property", OBS_DURATION, "duration"]);
|
||||||
|
// With --keep-open=yes mpv does NOT emit end-file at natural EOF — it
|
||||||
|
// sets eof-reached=true (and pauses at the last frame) instead. That
|
||||||
|
// property is the track-end signal; end-file only covers unload/error.
|
||||||
|
await this.send(["observe_property", OBS_EOF, "eof-reached"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async ipc(command: unknown[]): Promise<unknown> {
|
private async send(
|
||||||
try {
|
command: unknown[],
|
||||||
const socket = await Bun.connect({
|
): Promise<MpvResponse> {
|
||||||
unix: this.socketPath,
|
if (!this.conn) return { error: "not-connected" };
|
||||||
socket: {
|
return this.conn.send(command);
|
||||||
data(_socket, data) {
|
}
|
||||||
// Response handling is done by reading below
|
|
||||||
},
|
private handleEvent(msg: MpvEvent): void {
|
||||||
error(_socket, err) {},
|
if (msg.event === "property-change") {
|
||||||
close() {},
|
if (msg.id === OBS_TIME_POS) {
|
||||||
open() {},
|
// `data` is number while playing; unavailable → undefined while
|
||||||
},
|
// idle. Keep last known on transient gaps, reset on idle.
|
||||||
|
if (typeof msg.data === "number") this._position = msg.data;
|
||||||
|
} else if (msg.id === OBS_PAUSE) {
|
||||||
|
if (typeof msg.data === "boolean") this._paused = msg.data;
|
||||||
|
} else if (msg.id === OBS_DURATION) {
|
||||||
|
if (typeof msg.data === "number" && msg.data > 0) {
|
||||||
|
this._duration = msg.data;
|
||||||
|
}
|
||||||
|
} else if (msg.id === OBS_EOF) {
|
||||||
|
// Natural end-of-file (or a brand-new load reporting false).
|
||||||
|
this._ended = msg.data === true;
|
||||||
|
if (this._ended) this._intentPlaying = false;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg.event === "end-file") {
|
||||||
|
if (msg.reason === "eof") {
|
||||||
|
this._ended = true;
|
||||||
|
this._intentPlaying = false;
|
||||||
|
} else if (msg.reason === "error") {
|
||||||
|
this._ended = true;
|
||||||
|
this._intentPlaying = false;
|
||||||
|
this._playbackError = msg.error ?? "mpv failed to play the stream";
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg.event === "file-loaded") {
|
||||||
|
this._ended = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── File presentation options ────────────────────────────────────
|
||||||
|
//
|
||||||
|
// force-media-title and cover-art-files are set as global properties
|
||||||
|
// BEFORE loadfile (verified: runtime-settable; values containing commas
|
||||||
|
// would corrupt the per-file options string). Numbers (volume, speed,
|
||||||
|
// start, pause) ride as per-file options on loadfile itself so each
|
||||||
|
// loadfile is self-contained.
|
||||||
|
|
||||||
|
private async applyPresentation(opts?: PlayOptions): Promise<void> {
|
||||||
|
await this.send([
|
||||||
|
"set_property",
|
||||||
|
"force-media-title",
|
||||||
|
opts?.mediaTitle ?? "",
|
||||||
|
]);
|
||||||
|
await this.send([
|
||||||
|
"set_property",
|
||||||
|
"cover-art-files",
|
||||||
|
opts?.coverArtPath ?? "",
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadfileOptions(opts: PlayOptions | undefined, paused: boolean): string {
|
||||||
|
const parts: string[] = [`pause=${paused ? "yes" : "no"}`];
|
||||||
|
if (opts?.startPosition && opts.startPosition > 0) {
|
||||||
|
parts.push(`start=${Math.max(0, opts.startPosition)}`);
|
||||||
|
}
|
||||||
|
const vol = Math.round((opts?.volume ?? 1) * 100);
|
||||||
|
if (Number.isFinite(vol)) parts.push(`volume=${vol}`);
|
||||||
|
const speed = opts?.speed ?? 1;
|
||||||
|
if (Number.isFinite(speed) && speed > 0) parts.push(`speed=${speed}`);
|
||||||
|
return parts.join(",");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every loadfile (play, preload, replay) runs under this mutex: useAudio
|
||||||
|
* fires the boot preload unawaited, so without serialization a user
|
||||||
|
* pressing Play mid-preload would send loadfile(no-pause) followed by the
|
||||||
|
* in-flight preload's loadfile(pause=yes) — and the stale preload would
|
||||||
|
* pause the file the user just started. The mutex also prevents
|
||||||
|
* presentation options (title/cover) of one episode from interleaving
|
||||||
|
* with the loadfile of another.
|
||||||
|
*/
|
||||||
|
private loadMutex: Promise<unknown> = Promise.resolve();
|
||||||
|
|
||||||
|
private runLoadExclusive<T>(fn: () => Promise<T>): Promise<T> {
|
||||||
|
const result = this.loadMutex.then(fn);
|
||||||
|
this.loadMutex = result.catch(() => {});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadFileLocked(
|
||||||
|
url: string,
|
||||||
|
opts: PlayOptions | undefined,
|
||||||
|
paused: boolean,
|
||||||
|
): Promise<void> {
|
||||||
|
await this.applyPresentation(opts);
|
||||||
|
// Paused preload of a mid-episode restore: pass NO start= option and
|
||||||
|
// seek while paused instead. mpv defers --start stream work (open,
|
||||||
|
// header probe, demuxer seek) until playback begins — measured: the
|
||||||
|
// demuxer cache stays EMPTY during the whole preload and the eventual
|
||||||
|
// unpause pays 4.3s. A time-pos seek while paused executes at once,
|
||||||
|
// so the stream opens and buffers during the preload, and the first
|
||||||
|
// real Play is a sub-second unpause.
|
||||||
|
const pausedSeek =
|
||||||
|
paused && opts?.startPosition && opts.startPosition > 0
|
||||||
|
? opts.startPosition
|
||||||
|
: null;
|
||||||
|
const loadOpts =
|
||||||
|
pausedSeek && opts ? { ...opts, startPosition: undefined } : opts;
|
||||||
|
// Register the file-loaded waiter BEFORE loadfile: the event can
|
||||||
|
// arrive between the command response and listener setup otherwise.
|
||||||
|
const fileLoaded = pausedSeek && this.conn ? this.conn.waitEvent("file-loaded") : null;
|
||||||
|
const resp = await this.send([
|
||||||
|
"loadfile",
|
||||||
|
url,
|
||||||
|
"replace",
|
||||||
|
-1,
|
||||||
|
this.loadfileOptions(loadOpts, paused),
|
||||||
|
]);
|
||||||
|
if (resp.error && resp.error !== "success") {
|
||||||
|
throw new Error(`mpv loadfile failed: ${resp.error}`);
|
||||||
|
}
|
||||||
|
if (pausedSeek) {
|
||||||
|
// time-pos sent before file-loaded is silently dropped by mpv
|
||||||
|
// (no file yet) — the preload then parked at 0 and the restore
|
||||||
|
// position was lost. Wait for the open, then seek.
|
||||||
|
await fileLoaded;
|
||||||
|
await this.send(["set_property", "time-pos", pausedSeek]);
|
||||||
|
this._position = pausedSeek;
|
||||||
|
}
|
||||||
|
this._loadedUrl = url;
|
||||||
|
this._loadedPaused = paused;
|
||||||
|
this._ended = false;
|
||||||
|
this._playbackError = null;
|
||||||
|
this._position = opts?.startPosition ?? 0;
|
||||||
|
this._duration = 0;
|
||||||
|
this._volume = Math.round((opts?.volume ?? 1) * 100);
|
||||||
|
this._speed = opts?.speed ?? 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── AudioBackend ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async play(url: string, opts?: PlayOptions): Promise<void> {
|
||||||
|
await this.ensureDaemon();
|
||||||
|
// Mark intent before the mutex: a boot preload queued behind this
|
||||||
|
// play checks it and skips its own stale paused-load.
|
||||||
|
this._intentPlaying = true;
|
||||||
|
await this.runLoadExclusive(async () => {
|
||||||
|
// Fast path: this exact URL was PRELOADED paused (boot restore) —
|
||||||
|
// mpv has been buffering it since boot, so flipping pause off starts
|
||||||
|
// audio ~instantly. Re-acquire the start position only when it
|
||||||
|
// moved meaningfully since the preload (progress saved meanwhile).
|
||||||
|
if (this._loadedUrl === url && this._loadedPaused && !this._ended) {
|
||||||
|
const target = opts?.startPosition ?? this._position;
|
||||||
|
if (Math.abs(target - this._position) > 2) {
|
||||||
|
await this.send(["set_property", "time-pos", target]);
|
||||||
|
this._position = target;
|
||||||
|
}
|
||||||
|
await this.send([
|
||||||
|
"set_property",
|
||||||
|
"volume",
|
||||||
|
Math.round((opts?.volume ?? 1) * 100),
|
||||||
|
]);
|
||||||
|
await this.send(["set_property", "speed", opts?.speed ?? 1]);
|
||||||
|
if (opts?.mediaTitle) {
|
||||||
|
await this.send(["set_property", "force-media-title", opts.mediaTitle]);
|
||||||
|
}
|
||||||
|
await this.send(["set_property", "pause", false]);
|
||||||
|
this._loadedPaused = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.loadFileLocked(url, opts, false);
|
||||||
});
|
});
|
||||||
|
|
||||||
const payload = JSON.stringify({ command }) + "\n";
|
|
||||||
socket.write(payload);
|
|
||||||
|
|
||||||
// Read response with timeout
|
|
||||||
const response = await new Promise<string>((resolve) => {
|
|
||||||
let buf = "";
|
|
||||||
const reader = setInterval(() => {
|
|
||||||
// Check if we got a response already
|
|
||||||
if (buf.includes("\n")) {
|
|
||||||
clearInterval(reader);
|
|
||||||
resolve(buf);
|
|
||||||
}
|
}
|
||||||
}, 10);
|
|
||||||
setTimeout(() => {
|
async preload(url: string, opts?: PlayOptions): Promise<void> {
|
||||||
clearInterval(reader);
|
await this.ensureDaemon();
|
||||||
resolve(buf);
|
await this.runLoadExclusive(async () => {
|
||||||
}, 200);
|
// Already loaded (paused park, or actively playing because the
|
||||||
|
// user pressed Play while this preload was queued — either way
|
||||||
|
// the file is in the player and must not be clobbered).
|
||||||
|
if (this._loadedUrl === url) return;
|
||||||
|
await this.loadFileLocked(url, opts, true);
|
||||||
|
this._intentPlaying = false;
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.end();
|
|
||||||
if (response) {
|
|
||||||
try {
|
|
||||||
return JSON.parse(response.split("\n")[0]);
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Send a command over mpv's IPC and get the parsed response data. */
|
|
||||||
private async ipcCommand(command: unknown[]): Promise<unknown> {
|
|
||||||
try {
|
|
||||||
const conn = await Bun.connect({
|
|
||||||
unix: this.socketPath,
|
|
||||||
socket: {
|
|
||||||
data() {},
|
|
||||||
error() {},
|
|
||||||
close() {},
|
|
||||||
open() {},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const payload = JSON.stringify({ command }) + "\n";
|
|
||||||
conn.write(payload);
|
|
||||||
|
|
||||||
// Give mpv a moment to process, then read via a fresh connection
|
|
||||||
await new Promise((r) => setTimeout(r, 30));
|
|
||||||
conn.end();
|
|
||||||
|
|
||||||
return null;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Send a fire-and-forget command (no response needed) */
|
|
||||||
private async send(command: unknown[]): Promise<void> {
|
|
||||||
try {
|
|
||||||
const conn = await Bun.connect({
|
|
||||||
unix: this.socketPath,
|
|
||||||
socket: {
|
|
||||||
data() {},
|
|
||||||
error() {},
|
|
||||||
close() {},
|
|
||||||
open() {},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
conn.write(JSON.stringify({ command }) + "\n");
|
|
||||||
// Don't wait, just schedule a close
|
|
||||||
setTimeout(() => {
|
|
||||||
try {
|
|
||||||
conn.end();
|
|
||||||
} catch {}
|
|
||||||
}, 50);
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Get a property value from mpv via IPC */
|
|
||||||
private async getProperty(name: string): Promise<number> {
|
|
||||||
try {
|
|
||||||
return await new Promise<number>((resolve) => {
|
|
||||||
let result = 0;
|
|
||||||
const timeout = setTimeout(() => resolve(result), 300);
|
|
||||||
|
|
||||||
Bun.connect({
|
|
||||||
unix: this.socketPath,
|
|
||||||
socket: {
|
|
||||||
data(_socket, data) {
|
|
||||||
try {
|
|
||||||
const text = Buffer.from(data).toString();
|
|
||||||
const parsed = JSON.parse(text.split("\n")[0]);
|
|
||||||
if (parsed?.data !== undefined) {
|
|
||||||
result = Number(parsed.data) || 0;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* ignore parse errors */
|
|
||||||
}
|
|
||||||
clearTimeout(timeout);
|
|
||||||
resolve(result);
|
|
||||||
},
|
|
||||||
error() {
|
|
||||||
clearTimeout(timeout);
|
|
||||||
resolve(0);
|
|
||||||
},
|
|
||||||
close() {},
|
|
||||||
open(socket) {
|
|
||||||
socket.write(
|
|
||||||
JSON.stringify({ command: ["get_property", name] }) + "\n",
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}).catch(() => {
|
|
||||||
clearTimeout(timeout);
|
|
||||||
resolve(0);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private startPolling(): void {
|
|
||||||
this.stopPolling();
|
|
||||||
this.pollTimer = setInterval(async () => {
|
|
||||||
if (!this._playing || !this.proc) return;
|
|
||||||
this._position = await this.getProperty("time-pos");
|
|
||||||
if (this._duration <= 0) {
|
|
||||||
this._duration = await this.getProperty("duration");
|
|
||||||
}
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
|
|
||||||
private stopPolling(): void {
|
|
||||||
if (this.pollTimer) {
|
|
||||||
clearInterval(this.pollTimer);
|
|
||||||
this.pollTimer = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async pause(): Promise<void> {
|
async pause(): Promise<void> {
|
||||||
await this.send(["set_property", "pause", true]);
|
await this.send(["set_property", "pause", true]);
|
||||||
this._playing = false;
|
this._intentPlaying = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
async resume(): Promise<void> {
|
async resume(): Promise<void> {
|
||||||
|
if (this._ended && this._loadedUrl) {
|
||||||
|
// Play pressed on a finished episode: replay from the top.
|
||||||
|
this._ended = false;
|
||||||
|
const url = this._loadedUrl;
|
||||||
|
await this.runLoadExclusive(async () => {
|
||||||
|
await this.loadFileLocked(
|
||||||
|
url,
|
||||||
|
{ volume: this._volume / 100, speed: this._speed },
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
this._intentPlaying = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this._loadedPaused && this._loadedUrl) {
|
||||||
|
// Deferred first play of a preloaded file.
|
||||||
|
this._loadedPaused = false;
|
||||||
|
}
|
||||||
|
this._ended = false;
|
||||||
await this.send(["set_property", "pause", false]);
|
await this.send(["set_property", "pause", false]);
|
||||||
this._playing = true;
|
this._intentPlaying = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
async stop(): Promise<void> {
|
async stop(): Promise<void> {
|
||||||
this.stopPolling();
|
if (this.conn && this._loadedUrl) {
|
||||||
if (this.proc) {
|
await this.send(["stop"]);
|
||||||
try {
|
|
||||||
this.proc.kill();
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
}
|
||||||
this.proc = null;
|
this._intentPlaying = false;
|
||||||
}
|
this._loadedUrl = null;
|
||||||
this._playing = false;
|
this._loadedPaused = false;
|
||||||
|
this._ended = false;
|
||||||
this._position = 0;
|
this._position = 0;
|
||||||
|
this._duration = 0;
|
||||||
// Clean up socket
|
await this.send(["set_property", "cover-art-files", ""]);
|
||||||
try {
|
|
||||||
if (existsSync(this.socketPath)) {
|
|
||||||
const { unlinkSync } = await import("fs");
|
|
||||||
unlinkSync(this.socketPath);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async seek(seconds: number): Promise<void> {
|
async seek(seconds: number): Promise<void> {
|
||||||
@@ -359,22 +643,55 @@ export class MpvBackend implements AudioBackend {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getPosition(): Promise<number> {
|
async getPosition(): Promise<number> {
|
||||||
|
// Observed at ~20Hz by mpv — no socket roundtrip on the UI poll.
|
||||||
return this._position;
|
return this._position;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getDuration(): Promise<number> {
|
async getDuration(): Promise<number> {
|
||||||
if (this._duration <= 0) {
|
|
||||||
this._duration = await this.getProperty("duration");
|
|
||||||
}
|
|
||||||
return this._duration;
|
return this._duration;
|
||||||
}
|
}
|
||||||
|
|
||||||
isPlaying(): boolean {
|
isPlaying(): boolean {
|
||||||
return this._playing;
|
return this._intentPlaying && this.isAlive() && !this._ended;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPauseState(): Promise<boolean | undefined> {
|
||||||
|
if (!this.isAlive() || this._paused === null) return undefined;
|
||||||
|
return this._paused;
|
||||||
|
}
|
||||||
|
|
||||||
|
isAlive(): boolean {
|
||||||
|
return this.proc !== null && !this._exited;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Last mpv playback failure (end-file reason "error"), if any. */
|
||||||
|
getPlaybackError(): string | null {
|
||||||
|
return this._playbackError;
|
||||||
}
|
}
|
||||||
|
|
||||||
dispose(): void {
|
dispose(): void {
|
||||||
this.stop();
|
const conn = this.conn;
|
||||||
|
this.conn = null;
|
||||||
|
if (conn) {
|
||||||
|
// Ask nicely, then force: dispose runs inside process-exit
|
||||||
|
// handlers where awaiting is not guaranteed to complete.
|
||||||
|
conn.send(["quit"], 500).catch(() => {});
|
||||||
|
}
|
||||||
|
if (this.proc) {
|
||||||
|
try {
|
||||||
|
this.proc.kill();
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
this.proc = null;
|
||||||
|
}
|
||||||
|
this._exited = true;
|
||||||
|
this._intentPlaying = false;
|
||||||
|
try {
|
||||||
|
unlinkSync(this.socketPath);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -383,6 +700,7 @@ export class MpvBackend implements AudioBackend {
|
|||||||
class NoopBackend implements AudioBackend {
|
class NoopBackend implements AudioBackend {
|
||||||
readonly name: BackendName = "none";
|
readonly name: BackendName = "none";
|
||||||
async play(): Promise<void> {}
|
async play(): Promise<void> {}
|
||||||
|
async preload(): Promise<void> {}
|
||||||
async pause(): Promise<void> {}
|
async pause(): Promise<void> {}
|
||||||
async resume(): Promise<void> {}
|
async resume(): Promise<void> {}
|
||||||
async stop(): Promise<void> {}
|
async stop(): Promise<void> {}
|
||||||
@@ -398,6 +716,13 @@ class NoopBackend implements AudioBackend {
|
|||||||
isPlaying(): boolean {
|
isPlaying(): boolean {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
async getPauseState(): Promise<boolean | undefined> {
|
||||||
|
// Nothing plays on the no-op backend — never externally paused.
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
isAlive(): boolean {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
dispose(): void {}
|
dispose(): void {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
42
src/utils/audio-signals.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
/**
|
||||||
|
* audio-signals — module-level playback state shared by useAudio and
|
||||||
|
* non-component consumers.
|
||||||
|
*
|
||||||
|
* useAudio's playback state is a module-level singleton (signals live at
|
||||||
|
* module scope, every `useAudio()` call shares them). Those signals are
|
||||||
|
* declared here so components that must react to playback WITHOUT mounting
|
||||||
|
* a `useAudio()` owner — the visualizer store — can subscribe directly via
|
||||||
|
* `audioPlaybackSignals` (or the individual accessors/setters), instead of
|
||||||
|
* going through the hook. `useAudio()` re-exports nothing from this module
|
||||||
|
* for callers; it imports the accessors and setters for its own use.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { createSignal } from "solid-js";
|
||||||
|
import type { Episode } from "../types/episode";
|
||||||
|
import type { BackendName, DetectedPlayer } from "./audio-player";
|
||||||
|
|
||||||
|
export const [isPlaying, setIsPlaying] = createSignal(false);
|
||||||
|
export const [position, setPosition] = createSignal(0);
|
||||||
|
export const [duration, setDuration] = createSignal(0);
|
||||||
|
export const [volume, setVolume] = createSignal(1);
|
||||||
|
export const [speed, setSpeed] = createSignal(1);
|
||||||
|
export const [backendName, setBackendName] = createSignal<BackendName>("none");
|
||||||
|
export const [error, setError] = createSignal<string | null>(null);
|
||||||
|
export const [currentEpisode, setCurrentEpisode] = createSignal<Episode | null>(
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
export const [availablePlayers, setAvailablePlayers] = createSignal<
|
||||||
|
DetectedPlayer[]
|
||||||
|
>([]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The playback signals the visualizer pipeline reacts to. `useAudio()`
|
||||||
|
* itself remains the component-facing surface; this is for module-level
|
||||||
|
* consumers that must track playback without a component owner.
|
||||||
|
*/
|
||||||
|
export const audioPlaybackSignals = {
|
||||||
|
isPlaying,
|
||||||
|
position,
|
||||||
|
speed,
|
||||||
|
currentEpisode,
|
||||||
|
} as const;
|
||||||
@@ -1,279 +0,0 @@
|
|||||||
/**
|
|
||||||
* Real-time audio stream reader for visualization.
|
|
||||||
*
|
|
||||||
* Spawns a separate ffmpeg process that decodes the same audio URL
|
|
||||||
* the player is using and outputs raw PCM data (signed 16-bit LE, mono,
|
|
||||||
* 44100 Hz) to a pipe. The reader accumulates samples in a ring buffer
|
|
||||||
* and provides them to the caller on demand.
|
|
||||||
*
|
|
||||||
* This is independent from the actual playback backend — it's a
|
|
||||||
* read-only "tap" on the audio for FFT analysis purposes.
|
|
||||||
*/
|
|
||||||
|
|
||||||
/** PCM output format constants */
|
|
||||||
const SAMPLE_RATE = 44100;
|
|
||||||
const CHANNELS = 1;
|
|
||||||
const BYTES_PER_SAMPLE = 2; // s16le
|
|
||||||
|
|
||||||
/** How many samples to buffer (~1 second) */
|
|
||||||
const RING_BUFFER_SAMPLES = SAMPLE_RATE;
|
|
||||||
|
|
||||||
export interface AudioStreamReaderOptions {
|
|
||||||
/** Audio URL or file path to decode */
|
|
||||||
url: string;
|
|
||||||
/** Sample rate (default: 44100) */
|
|
||||||
sampleRate?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Monotonically increasing generation counter.
|
|
||||||
* Each start() increments this; the read loop checks it to know
|
|
||||||
* if it's been superseded and should bail out.
|
|
||||||
*/
|
|
||||||
let globalGeneration = 0;
|
|
||||||
|
|
||||||
export class AudioStreamReader {
|
|
||||||
private proc: ReturnType<typeof Bun.spawn> | null = null;
|
|
||||||
private ringBuffer: Float64Array;
|
|
||||||
private writePos = 0;
|
|
||||||
private totalSamplesWritten = 0;
|
|
||||||
private _running = false;
|
|
||||||
private generation = 0;
|
|
||||||
readonly url: string;
|
|
||||||
private sampleRate: number;
|
|
||||||
|
|
||||||
constructor(options: AudioStreamReaderOptions) {
|
|
||||||
this.url = options.url;
|
|
||||||
this.sampleRate = options.sampleRate ?? SAMPLE_RATE;
|
|
||||||
this.ringBuffer = new Float64Array(RING_BUFFER_SAMPLES);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Whether the reader is actively reading samples. */
|
|
||||||
get running(): boolean {
|
|
||||||
return this._running;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Total number of samples written since start(). */
|
|
||||||
get samplesWritten(): number {
|
|
||||||
return this.totalSamplesWritten;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Start the ffmpeg decode process and begin reading PCM data.
|
|
||||||
*
|
|
||||||
* If already running, the previous process is killed first.
|
|
||||||
* Uses a generation counter to guarantee that only one read loop
|
|
||||||
* is ever active — stale loops from killed processes bail out
|
|
||||||
* immediately.
|
|
||||||
*
|
|
||||||
* @param startPosition Seek position in seconds (default: 0).
|
|
||||||
* @param speed Playback speed multiplier (default: 1). Applies ffmpeg
|
|
||||||
* atempo filter so visualization stays in sync with audio.
|
|
||||||
*/
|
|
||||||
start(startPosition = 0, speed = 1): void {
|
|
||||||
// Always kill the previous process first — no early return on _running
|
|
||||||
this.killProcess();
|
|
||||||
|
|
||||||
if (!Bun.which("ffmpeg")) {
|
|
||||||
throw new Error("ffmpeg not found — required for audio visualization");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Increment generation so any lingering read loop from a previous
|
|
||||||
// start() will see a mismatch and exit.
|
|
||||||
this.generation = ++globalGeneration;
|
|
||||||
|
|
||||||
const args = [
|
|
||||||
"ffmpeg",
|
|
||||||
"-loglevel",
|
|
||||||
"quiet",
|
|
||||||
// Read input at native frame rate so decoded PCM stays in sync with
|
|
||||||
// real-time playback. Without -re, ffmpeg greedily decodes the whole
|
|
||||||
// file as fast as possible: the ring buffer fills with audio seconds
|
|
||||||
// ahead of the player (laggy bars), then the process exits when it
|
|
||||||
// hits EOF (bars freeze ~10s in).
|
|
||||||
"-re",
|
|
||||||
"-reconnect",
|
|
||||||
"1",
|
|
||||||
"-reconnect_streamed",
|
|
||||||
"1",
|
|
||||||
"-reconnect_delay_max",
|
|
||||||
"5",
|
|
||||||
];
|
|
||||||
|
|
||||||
// Seek before input for network efficiency
|
|
||||||
if (startPosition > 0) {
|
|
||||||
args.push("-ss", String(startPosition));
|
|
||||||
}
|
|
||||||
|
|
||||||
args.push("-i", this.url);
|
|
||||||
|
|
||||||
// Apply speed via atempo filter if not 1x.
|
|
||||||
// ffmpeg atempo only supports 0.5–100.0; chain multiple for extremes.
|
|
||||||
if (speed !== 1 && speed > 0) {
|
|
||||||
args.push("-af", buildAtempoChain(speed));
|
|
||||||
}
|
|
||||||
|
|
||||||
args.push(
|
|
||||||
"-ac",
|
|
||||||
String(CHANNELS),
|
|
||||||
"-ar",
|
|
||||||
String(this.sampleRate),
|
|
||||||
"-f",
|
|
||||||
"s16le",
|
|
||||||
"-acodec",
|
|
||||||
"pcm_s16le",
|
|
||||||
"-",
|
|
||||||
);
|
|
||||||
|
|
||||||
this.proc = Bun.spawn(args, {
|
|
||||||
stdout: "pipe",
|
|
||||||
stderr: "ignore",
|
|
||||||
stdin: "ignore",
|
|
||||||
});
|
|
||||||
|
|
||||||
this._running = true;
|
|
||||||
this.writePos = 0;
|
|
||||||
this.totalSamplesWritten = 0;
|
|
||||||
|
|
||||||
const myGeneration = this.generation;
|
|
||||||
|
|
||||||
this.readLoop(myGeneration);
|
|
||||||
|
|
||||||
// Detect process exit
|
|
||||||
this.proc.exited
|
|
||||||
.then(() => {
|
|
||||||
// Only clear _running if this is still the current generation
|
|
||||||
if (this.generation === myGeneration) {
|
|
||||||
this._running = false;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
if (this.generation === myGeneration) {
|
|
||||||
this._running = false;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Read available samples into the provided buffer.
|
|
||||||
* Returns the number of samples actually copied.
|
|
||||||
*
|
|
||||||
* @param out - Float64Array to fill with samples (scaled ~+/-32768 for cavacore).
|
|
||||||
* @returns Number of samples written to `out`.
|
|
||||||
*/
|
|
||||||
read(out: Float64Array): number {
|
|
||||||
const available = Math.min(
|
|
||||||
out.length,
|
|
||||||
this.totalSamplesWritten,
|
|
||||||
this.ringBuffer.length,
|
|
||||||
);
|
|
||||||
if (available <= 0) return 0;
|
|
||||||
|
|
||||||
// Read the most recent `available` samples from the ring buffer
|
|
||||||
const readStart =
|
|
||||||
(this.writePos - available + this.ringBuffer.length) %
|
|
||||||
this.ringBuffer.length;
|
|
||||||
|
|
||||||
if (readStart + available <= this.ringBuffer.length) {
|
|
||||||
out.set(this.ringBuffer.subarray(readStart, readStart + available));
|
|
||||||
} else {
|
|
||||||
const firstChunk = this.ringBuffer.length - readStart;
|
|
||||||
out.set(this.ringBuffer.subarray(readStart, this.ringBuffer.length));
|
|
||||||
out.set(this.ringBuffer.subarray(0, available - firstChunk), firstChunk);
|
|
||||||
}
|
|
||||||
|
|
||||||
return available;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Stop the ffmpeg process and clean up.
|
|
||||||
* Safe to call multiple times. Guarantees the read loop exits.
|
|
||||||
*/
|
|
||||||
stop(): void {
|
|
||||||
// Bump generation to invalidate any running read loop
|
|
||||||
this.generation = ++globalGeneration;
|
|
||||||
this._running = false;
|
|
||||||
this.killProcess();
|
|
||||||
this.writePos = 0;
|
|
||||||
this.totalSamplesWritten = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Restart the reader at a new position and/or speed.
|
|
||||||
*/
|
|
||||||
restart(startPosition = 0, speed = 1): void {
|
|
||||||
this.start(startPosition, speed);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Kill the ffmpeg process without touching generation/state. */
|
|
||||||
private killProcess(): void {
|
|
||||||
if (this.proc) {
|
|
||||||
try {
|
|
||||||
this.proc.kill();
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
this.proc = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Internal: continuously reads stdout from ffmpeg and fills the ring buffer. */
|
|
||||||
private async readLoop(myGeneration: number): Promise<void> {
|
|
||||||
const stdout = this.proc?.stdout;
|
|
||||||
if (!stdout || typeof stdout === "number") return;
|
|
||||||
|
|
||||||
const reader = (stdout as ReadableStream<Uint8Array>).getReader();
|
|
||||||
try {
|
|
||||||
while (this.generation === myGeneration) {
|
|
||||||
const { done, value } = await reader.read();
|
|
||||||
if (done || this.generation !== myGeneration) break;
|
|
||||||
if (!value || value.byteLength === 0) continue;
|
|
||||||
|
|
||||||
const sampleCount = Math.floor(value.byteLength / BYTES_PER_SAMPLE);
|
|
||||||
if (sampleCount === 0) continue;
|
|
||||||
|
|
||||||
const int16View = new Int16Array(
|
|
||||||
value.buffer,
|
|
||||||
value.byteOffset,
|
|
||||||
sampleCount,
|
|
||||||
);
|
|
||||||
|
|
||||||
for (let i = 0; i < sampleCount; i++) {
|
|
||||||
this.ringBuffer[this.writePos] = int16View[i];
|
|
||||||
this.writePos = (this.writePos + 1) % this.ringBuffer.length;
|
|
||||||
this.totalSamplesWritten++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Stream ended or process killed — expected during stop()
|
|
||||||
} finally {
|
|
||||||
try {
|
|
||||||
reader.releaseLock();
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build an ffmpeg atempo filter chain for a given speed.
|
|
||||||
* atempo only accepts values in [0.5, 100.0], so we chain
|
|
||||||
* multiple filters for extreme values (e.g. 0.25 = atempo=0.5,atempo=0.5).
|
|
||||||
*/
|
|
||||||
function buildAtempoChain(speed: number): string {
|
|
||||||
const parts: string[] = [];
|
|
||||||
let remaining = Math.max(0.25, Math.min(4, speed));
|
|
||||||
|
|
||||||
while (remaining > 100) {
|
|
||||||
parts.push("atempo=100.0");
|
|
||||||
remaining /= 100;
|
|
||||||
}
|
|
||||||
while (remaining < 0.5) {
|
|
||||||
parts.push("atempo=0.5");
|
|
||||||
remaining /= 0.5;
|
|
||||||
}
|
|
||||||
parts.push(`atempo=${remaining}`);
|
|
||||||
|
|
||||||
return parts.join(",");
|
|
||||||
}
|
|
||||||
102
src/utils/bar-mapping.ts
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
/**
|
||||||
|
* Pure bar-scaling helpers for the terminal waveform.
|
||||||
|
*
|
||||||
|
* barChars maps a 0..16 level to the two characters of a 2-row bar built
|
||||||
|
* from Unicode lower block elements (U+2581..U+2588). The partial block
|
||||||
|
* sits in the TOP row (its glyph bottom edge = row bottom), so a full
|
||||||
|
* block below makes a visually continuous 2-cell column — the "double the
|
||||||
|
* default height" requirement (each bar = 2 terminal rows, 16 heights).
|
||||||
|
*
|
||||||
|
* createBarScaler is a stateful fast-attack / slow-release peak follower
|
||||||
|
* that replaces cava's autosens: a loud start cannot pin every bar at
|
||||||
|
* full height (the peak follower absorbs it) and quiet content gets
|
||||||
|
* normalized up.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// ── Types ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface BarScalerOptions {
|
||||||
|
/** Peak follower decay per frame (default: 0.985) */
|
||||||
|
release?: number;
|
||||||
|
/** Power curve applied after normalization (default: 0.7) */
|
||||||
|
curve?: number;
|
||||||
|
/** Silence threshold — below this the input is treated as silent (default: 1e-6) */
|
||||||
|
epsilon?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Constants ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Number of discrete bar heights (2 rows × 8 block levels). */
|
||||||
|
export const BAR_LEVELS = 16;
|
||||||
|
|
||||||
|
/** Lower block elements, index 0 = space (silence) through full block (max). */
|
||||||
|
const LOWER = [
|
||||||
|
" ",
|
||||||
|
"\u2581",
|
||||||
|
"\u2582",
|
||||||
|
"\u2583",
|
||||||
|
"\u2584",
|
||||||
|
"\u2585",
|
||||||
|
"\u2586",
|
||||||
|
"\u2587",
|
||||||
|
"\u2588",
|
||||||
|
];
|
||||||
|
|
||||||
|
// ── Bar mapping ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map a bar level (0..16) to the two characters that render it as a
|
||||||
|
* 2-row column: top row + bottom row.
|
||||||
|
*
|
||||||
|
* level 0 → { top: " ", bottom: " " }
|
||||||
|
* level 1..8 → { top: " ", bottom: LOWER[level] }
|
||||||
|
* level 9..16 → { top: LOWER[level - 8], bottom: "\u2588" }
|
||||||
|
*/
|
||||||
|
export function barChars(level: number): { top: string; bottom: string } {
|
||||||
|
const raw = Math.floor(level);
|
||||||
|
const lvl = Number.isFinite(raw)
|
||||||
|
? Math.max(0, Math.min(BAR_LEVELS, raw))
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
if (lvl === 0) return { top: " ", bottom: " " };
|
||||||
|
if (lvl <= 8) return { top: " ", bottom: LOWER[lvl] };
|
||||||
|
return { top: LOWER[lvl - 8], bottom: "\u2588" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Peak-follower scaler ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
const clamp01 = (value: number): number => Math.max(0, Math.min(1, value));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a stateful bar scaler. Each call normalizes its input against a
|
||||||
|
* peak follower (instant attack, multiplicative release), then applies a
|
||||||
|
* power curve so low-energy content remains visible. Returns a new
|
||||||
|
* number[] per call.
|
||||||
|
*/
|
||||||
|
export function createBarScaler(
|
||||||
|
opts?: BarScalerOptions,
|
||||||
|
): (values: ArrayLike<number>) => number[] {
|
||||||
|
const release = opts?.release ?? 0.985;
|
||||||
|
const curve = opts?.curve ?? 0.7;
|
||||||
|
const epsilon = opts?.epsilon ?? 1e-6;
|
||||||
|
let peak = 0;
|
||||||
|
|
||||||
|
return (values: ArrayLike<number>): number[] => {
|
||||||
|
let frameMax = 0;
|
||||||
|
for (let i = 0; i < values.length; i++) {
|
||||||
|
const magnitude = Math.abs(values[i]);
|
||||||
|
if (magnitude > frameMax) frameMax = magnitude;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fast attack, slow release
|
||||||
|
peak = frameMax > peak ? frameMax : peak * release;
|
||||||
|
|
||||||
|
const gain = peak > epsilon ? 1 / peak : 0;
|
||||||
|
|
||||||
|
const output = new Array<number>(values.length);
|
||||||
|
for (let i = 0; i < values.length; i++) {
|
||||||
|
output[i] = Math.pow(clamp01(values[i] * gain), curve);
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@
|
|||||||
* always overwrite — no backup files are created.
|
* always overwrite — no backup files are created.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { mkdir } from "fs/promises";
|
||||||
import { ensureConfigDir, getConfigDir, getConfigFilePath } from "./config-dir";
|
import { ensureConfigDir, getConfigDir, getConfigFilePath } from "./config-dir";
|
||||||
import type {
|
import type {
|
||||||
AppSettings,
|
AppSettings,
|
||||||
@@ -58,21 +59,47 @@ let writeChain: Promise<void> = Promise.resolve();
|
|||||||
|
|
||||||
/** Update sections of config.json (read-modify-write, serialized, overwrite). */
|
/** Update sections of config.json (read-modify-write, serialized, overwrite). */
|
||||||
export function updateConfig(patch: Partial<PodTuiConfig>): void {
|
export function updateConfig(patch: Partial<PodTuiConfig>): void {
|
||||||
|
// Capture the target path AND the patch data eagerly, at call time:
|
||||||
|
// the write chain defers execution, and both the config dir (tests
|
||||||
|
// re-point XDG_CONFIG_HOME between ops) and the state object (stores
|
||||||
|
// mutate in place) move under a pending write. Without the capture, a
|
||||||
|
// queued save writes the LATEST state into whatever directory is
|
||||||
|
// current when the chain drains — a cross-directory misdelivery that
|
||||||
|
// was the source of a flaky "enabled:false survives reload" test.
|
||||||
|
const configPath = getConfigFilePath(CONFIG_FILE);
|
||||||
|
const configDir = getConfigDir();
|
||||||
|
const snapshot = JSON.parse(JSON.stringify(patch)) as Partial<PodTuiConfig>;
|
||||||
writeChain = writeChain.then(async () => {
|
writeChain = writeChain.then(async () => {
|
||||||
try {
|
try {
|
||||||
await ensureConfigDir();
|
await migrateOnce();
|
||||||
const current = await loadConfig();
|
await mkdir(configDir, { recursive: true });
|
||||||
const next = { ...current, ...patch };
|
let current: PodTuiConfig = {};
|
||||||
await Bun.write(
|
try {
|
||||||
getConfigFilePath(CONFIG_FILE),
|
const file = Bun.file(configPath);
|
||||||
JSON.stringify(next, null, 2),
|
if (await file.exists()) {
|
||||||
);
|
const raw = await file.json();
|
||||||
|
if (raw && typeof raw === "object") {
|
||||||
|
current = raw as PodTuiConfig;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* unreadable existing config — treat as empty */
|
||||||
|
}
|
||||||
|
const next = { ...current, ...snapshot };
|
||||||
|
await Bun.write(configPath, JSON.stringify(next, null, 2));
|
||||||
} catch {
|
} catch {
|
||||||
// Fire-and-forget persistence — silently ignore write errors.
|
// Fire-and-forget persistence — silently ignore write errors.
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Resolve once every queued config write has flushed. Tests await this to
|
||||||
|
* observe the serialized result of pending saveFeedsToFile/updateConfig
|
||||||
|
* calls before asserting on config.json. */
|
||||||
|
export function whenConfigIdle(): Promise<void> {
|
||||||
|
return writeChain;
|
||||||
|
}
|
||||||
|
|
||||||
/** Guards so migration runs exactly once per process. */
|
/** Guards so migration runs exactly once per process. */
|
||||||
let migrationDone = false;
|
let migrationDone = false;
|
||||||
let migrationPromise: Promise<void> | null = null;
|
let migrationPromise: Promise<void> | null = null;
|
||||||
|
|||||||
141
src/utils/cover-art.ts
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
/**
|
||||||
|
* Cover-art staging for the system Now Playing session.
|
||||||
|
*
|
||||||
|
* macOS shows the media session's albumart in the audio center (Control
|
||||||
|
* Center / lock screen). mpv reads artwork from `--cover-art-files` (loads
|
||||||
|
* the file as an albumart video track), so the podcast cover must exist on
|
||||||
|
* disk before (cover-art-files) or right after (video-add) playback starts.
|
||||||
|
*
|
||||||
|
* Covers are cached persistently under `$XDG_CACHE_HOME/podtui/covers`
|
||||||
|
* (~/.cache/podtui/covers by default), keyed by the URL hash, so the
|
||||||
|
* download happens ONCE per feed — subsequent plays (including the
|
||||||
|
* boot-restored episode) hit the disk cache and never wait on the network.
|
||||||
|
* The play path must never block on art: `cachedCoverPath` is the sync
|
||||||
|
* fast path; `fetchCoverArt` is awaited only by flows where latency does
|
||||||
|
* not matter (CLI play) or fired in the background with the result
|
||||||
|
* applied to a live mpv via `video-add`.
|
||||||
|
*
|
||||||
|
* Downloaded via `curl` (not `fetch`): Bun's `fetch` hangs in compiled
|
||||||
|
* `bun build --compile` binaries (Bun 1.3.8), timing out on any host —
|
||||||
|
* which would silently drop every cover in shipped builds. curl is present
|
||||||
|
* on macOS and Linux. Bounded: a slow cover server must never stall audio.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { existsSync, mkdirSync, renameSync, statSync } from "fs";
|
||||||
|
import { createHash } from "crypto";
|
||||||
|
import { join } from "path";
|
||||||
|
|
||||||
|
/** Resolved once per process; null when no home directory is detectable. */
|
||||||
|
let cacheDir: string | null | undefined;
|
||||||
|
|
||||||
|
function coversDir(): string | null {
|
||||||
|
if (cacheDir !== undefined) return cacheDir;
|
||||||
|
let dir: string | null = null;
|
||||||
|
try {
|
||||||
|
const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
|
||||||
|
if (home) {
|
||||||
|
dir = join(process.env.XDG_CACHE_HOME ?? join(home, ".cache"), "podtui", "covers");
|
||||||
|
mkdirSync(dir, { recursive: true });
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
dir = null;
|
||||||
|
}
|
||||||
|
cacheDir = dir;
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cachePathFor(url: string): string | null {
|
||||||
|
const dir = coversDir();
|
||||||
|
if (!dir) return null;
|
||||||
|
return join(dir, `${createHash("sha1").update(url).digest("hex")}.jpg`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sync fast path: the cached cover file for `url`, or null when it has not
|
||||||
|
* been downloaded yet. This is what keeps cover art off the play() critical
|
||||||
|
* path — a cache hit costs one stat() and a miss simply plays without art
|
||||||
|
* (or applies it late via video-add).
|
||||||
|
*/
|
||||||
|
export function cachedCoverPath(url: string): string | null {
|
||||||
|
const path = cachePathFor(url);
|
||||||
|
if (!path) return null;
|
||||||
|
try {
|
||||||
|
return existsSync(path) && statSync(path).size > 0 ? path : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** In-flight downloads keyed by URL — a burst of plays of the same show
|
||||||
|
* shares one curl instead of racing ephemeral files. */
|
||||||
|
const inflight = new Map<string, Promise<string | null>>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch the cover for `url`, returns its cache path. Cache hits return
|
||||||
|
* immediately. Downloads are single-flight per URL and time-bounded (8s);
|
||||||
|
* failure resolves null and retries on the next call. The file is written
|
||||||
|
* to a temp name and renamed into place so a killed process can never
|
||||||
|
* poison the cache with a truncated file.
|
||||||
|
*/
|
||||||
|
export function fetchCoverArt(url: string): Promise<string | null> {
|
||||||
|
const cached = cachedCoverPath(url);
|
||||||
|
if (cached) return Promise.resolve(cached);
|
||||||
|
|
||||||
|
const dest = cachePathFor(url);
|
||||||
|
if (!dest) return Promise.resolve(null);
|
||||||
|
|
||||||
|
const pending = inflight.get(url);
|
||||||
|
if (pending) return pending;
|
||||||
|
|
||||||
|
const task = (async (): Promise<string | null> => {
|
||||||
|
const staging = `${dest}.${process.pid}.tmp`;
|
||||||
|
try {
|
||||||
|
const { promise, resolve } = Promise.withResolvers<string | null>();
|
||||||
|
const proc = Bun.spawn(
|
||||||
|
[
|
||||||
|
"curl",
|
||||||
|
"-sS",
|
||||||
|
"--fail",
|
||||||
|
"-m",
|
||||||
|
"8",
|
||||||
|
"--max-filesize",
|
||||||
|
"2097152",
|
||||||
|
"-o",
|
||||||
|
staging,
|
||||||
|
url,
|
||||||
|
],
|
||||||
|
{ stdout: "ignore", stderr: "ignore", stdin: "ignore" },
|
||||||
|
);
|
||||||
|
proc.exited
|
||||||
|
.then((code) => {
|
||||||
|
if (code !== 0) return resolve(null);
|
||||||
|
try {
|
||||||
|
if (statSync(staging).size <= 0) return resolve(null);
|
||||||
|
renameSync(staging, dest);
|
||||||
|
resolve(dest);
|
||||||
|
} catch {
|
||||||
|
resolve(null);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => resolve(null));
|
||||||
|
setTimeout(() => resolve(null), 8000);
|
||||||
|
return await promise;
|
||||||
|
} finally {
|
||||||
|
inflight.delete(url);
|
||||||
|
// Best-effort staging cleanup (no-op after a successful rename).
|
||||||
|
try {
|
||||||
|
Bun.spawn(["rm", "-f", staging], { stdout: "ignore", stderr: "ignore" });
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
inflight.set(url, task);
|
||||||
|
return task;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fire-and-forget warm-up used by the boot/restore path. */
|
||||||
|
export function prefetchCoverArt(url: string): void {
|
||||||
|
fetchCoverArt(url).catch(() => {});
|
||||||
|
}
|
||||||
@@ -71,11 +71,16 @@ export const PAGE_ACTIONS: ReadonlySet<KeybindActionName> =
|
|||||||
"open",
|
"open",
|
||||||
"open-interactive",
|
"open-interactive",
|
||||||
"search",
|
"search",
|
||||||
|
"search-scope-toggle",
|
||||||
"filter",
|
"filter",
|
||||||
"sort",
|
"sort",
|
||||||
"toggle-hidden",
|
"toggle-hidden",
|
||||||
"refresh",
|
"refresh",
|
||||||
|
"subscribe",
|
||||||
"unsubscribe",
|
"unsubscribe",
|
||||||
|
"download",
|
||||||
|
"delete-download",
|
||||||
|
"whitelist-toggle",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
/** Resolve a `tab-goto-N` digit action (1..TabsCount) to a TABS value, or null. */
|
/** Resolve a `tab-goto-N` digit action (1..TabsCount) to a TABS value, or null. */
|
||||||
|
|||||||
26
src/utils/episode-merge.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import type { Episode } from "../types/episode"
|
||||||
|
|
||||||
|
/** Sort key for an episode's pubDate — missing/invalid dates sort as NEWEST
|
||||||
|
* (Infinity) so undated episodes float to the top instead of dropping into
|
||||||
|
* the oldest slot. */
|
||||||
|
const ts = (ep: Episode): number => {
|
||||||
|
const t = ep.pubDate?.getTime()
|
||||||
|
return t === undefined || Number.isNaN(t) ? Infinity : t
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Union of two episode lists keyed by id — on collision the fetched copy
|
||||||
|
* wins (fresh metadata). Result is sorted newest-first by pubDate and capped
|
||||||
|
* at `cap` entries (oldest dropped). Never mutates either input.
|
||||||
|
*/
|
||||||
|
export function mergeEpisodes(
|
||||||
|
existing: Episode[],
|
||||||
|
fetched: Episode[],
|
||||||
|
cap: number,
|
||||||
|
): Episode[] {
|
||||||
|
const byId = new Map<string, Episode>()
|
||||||
|
for (const ep of existing) byId.set(ep.id, ep)
|
||||||
|
for (const ep of fetched) byId.set(ep.id, ep)
|
||||||
|
const sorted = [...byId.values()].sort((a, b) => ts(b) - ts(a))
|
||||||
|
return sorted.slice(0, cap)
|
||||||
|
}
|
||||||
@@ -132,8 +132,6 @@ export type AppEvents = {
|
|||||||
"media.toggle": {};
|
"media.toggle": {};
|
||||||
"media.volumeUp": {};
|
"media.volumeUp": {};
|
||||||
"media.volumeDown": {};
|
"media.volumeDown": {};
|
||||||
"media.seekForward": {};
|
|
||||||
"media.seekBackward": {};
|
|
||||||
"media.speedCycle": {};
|
"media.speedCycle": {};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,57 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { loadConfig, updateConfig } from "./config";
|
import { loadConfig, updateConfig } from "./config";
|
||||||
|
import { getConfigFilePath } from "./config-dir";
|
||||||
|
import { DownloadStatus } from "../types/episode";
|
||||||
|
import type { Episode } from "../types/episode";
|
||||||
import type { Feed } from "../types/feed";
|
import type { Feed } from "../types/feed";
|
||||||
import type { PodcastSource } from "../types/source";
|
import type { PodcastSource } from "../types/source";
|
||||||
|
|
||||||
|
/** Retention window for persisted episodes: older episodes are dropped when
|
||||||
|
* feeds are written to config.json unless they are completed downloads. */
|
||||||
|
export const PERSISTED_WINDOW_DAYS = 30;
|
||||||
|
|
||||||
|
/** True when an episode may be persisted: it is a completed download, or its
|
||||||
|
* pubDate is missing/invalid (fail-safe: never drop an undatable episode),
|
||||||
|
* or it falls inside the retention window. */
|
||||||
|
export function episodeIsPersistable(
|
||||||
|
ep: Episode,
|
||||||
|
downloadedIds: Set<string>,
|
||||||
|
now: Date,
|
||||||
|
): boolean {
|
||||||
|
if (downloadedIds.has(ep.id)) return true;
|
||||||
|
const t = ep.pubDate?.getTime();
|
||||||
|
if (!t || Number.isNaN(t)) return true;
|
||||||
|
return t >= now.getTime() - PERSISTED_WINDOW_DAYS * 24 * 3600 * 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Episode ids of completed downloads, read from downloads.json. In-flight
|
||||||
|
* downloads are NOT exempted from the retention window — a just-completed
|
||||||
|
* download is re-included by the next save because the in-memory
|
||||||
|
* feed.episodes still holds it. Missing/unreadable/invalid file → empty set. */
|
||||||
|
async function readDownloadedEpisodeIds(): Promise<Set<string>> {
|
||||||
|
try {
|
||||||
|
const file = Bun.file(getConfigFilePath("downloads.json"));
|
||||||
|
if (!(await file.exists())) return new Set();
|
||||||
|
const raw = await file.json();
|
||||||
|
if (!Array.isArray(raw)) return new Set();
|
||||||
|
const ids = new Set<string>();
|
||||||
|
for (const rec of raw) {
|
||||||
|
if (
|
||||||
|
rec &&
|
||||||
|
typeof rec === "object" &&
|
||||||
|
rec.status === DownloadStatus.COMPLETED &&
|
||||||
|
typeof rec.episodeId === "string"
|
||||||
|
) {
|
||||||
|
ids.add(rec.episodeId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
} catch {
|
||||||
|
return new Set();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Deserialize date strings back to Date objects in feed data */
|
/** Deserialize date strings back to Date objects in feed data */
|
||||||
function reviveDates(feed: Feed): Feed {
|
function reviveDates(feed: Feed): Feed {
|
||||||
return {
|
return {
|
||||||
@@ -23,20 +71,54 @@ function reviveDates(feed: Feed): Feed {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Load feeds from config.json */
|
/** Load feeds from config.json, pruning episodes outside the retention
|
||||||
|
* window (completed downloads always kept). When anything was pruned, the
|
||||||
|
* pruned list is rewritten to config.json (startup cleanup for legacy
|
||||||
|
* configs). The read path is awaited so the returned value is deterministic. */
|
||||||
export async function loadFeedsFromFile(): Promise<Feed[]> {
|
export async function loadFeedsFromFile(): Promise<Feed[]> {
|
||||||
try {
|
try {
|
||||||
const cfg = await loadConfig();
|
const cfg = await loadConfig();
|
||||||
if (!Array.isArray(cfg.feeds)) return [];
|
if (!Array.isArray(cfg.feeds)) return [];
|
||||||
return cfg.feeds.map(reviveDates);
|
const feeds = cfg.feeds.map(reviveDates);
|
||||||
|
const downloadedIds = await readDownloadedEpisodeIds();
|
||||||
|
const now = new Date();
|
||||||
|
let prunedAny = false;
|
||||||
|
const pruned = feeds.map((f) => {
|
||||||
|
const kept = f.episodes.filter((ep) =>
|
||||||
|
episodeIsPersistable(ep, downloadedIds, now),
|
||||||
|
);
|
||||||
|
if (kept.length !== f.episodes.length) prunedAny = true;
|
||||||
|
return { ...f, episodes: kept };
|
||||||
|
});
|
||||||
|
if (prunedAny) {
|
||||||
|
// Fire-and-forget cleanup rewrite of the legacy config.
|
||||||
|
saveFeedsToFile(pruned);
|
||||||
|
}
|
||||||
|
return pruned;
|
||||||
} catch {
|
} catch {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Save feeds to config.json */
|
/** Save feeds to config.json, pruning episodes outside the retention window
|
||||||
|
* (completed downloads always kept). Fire-and-forget: the prune reads
|
||||||
|
* downloads.json asynchronously, then enqueues the write. On any error the
|
||||||
|
* UNPRUNED feeds are saved instead, so data is never lost. */
|
||||||
export function saveFeedsToFile(feeds: Feed[]): void {
|
export function saveFeedsToFile(feeds: Feed[]): void {
|
||||||
updateConfig({ feeds });
|
(async () => {
|
||||||
|
try {
|
||||||
|
const downloadedIds = await readDownloadedEpisodeIds();
|
||||||
|
const pruned = feeds.map((f) => ({
|
||||||
|
...f,
|
||||||
|
episodes: f.episodes.filter((ep) =>
|
||||||
|
episodeIsPersistable(ep, downloadedIds, new Date()),
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
updateConfig({ feeds: pruned });
|
||||||
|
} catch {
|
||||||
|
updateConfig({ feeds }); /* never lose data on an error path */
|
||||||
|
}
|
||||||
|
})().catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Load sources from config.json */
|
/** Load sources from config.json */
|
||||||
|
|||||||
61
src/utils/itunes-feed-resolver.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
/**
|
||||||
|
* iTunes feed resolution for shows delisted from Apple Podcasts.
|
||||||
|
*
|
||||||
|
* The iTunes Search API returns `feedUrl: null` for shows that left Apple
|
||||||
|
* Podcasts (e.g. The Daily Wire's shows in 2021) — the directory keeps a
|
||||||
|
* metadata-only stub. The show's public Apple Podcasts page still embeds the
|
||||||
|
* real feed URL in its JSON state (`showOffer.feedUrl`), so subscribing can
|
||||||
|
* resolve it from there.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** `"feedUrl":"https://..."` as embedded in the Apple page's JSON state. */
|
||||||
|
const FEED_URL_RE = /"feedUrl"\s*:\s*"(https?:\/\/[^"]+)"/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract the show's feed URL from an Apple Podcasts page's HTML.
|
||||||
|
*
|
||||||
|
* The page embeds `showOffer` blocks for the show AND for related shows, each
|
||||||
|
* with its own feedUrl, and Apple serves multiple JSON variants — the main
|
||||||
|
* show's showOffer may sit adjacent to its adamId or thousands of chars later.
|
||||||
|
* Anchor on the collection id from `directoryUrl` (`"adamId":"<id>"`) and take
|
||||||
|
* the FIRST feedUrl after it (the main show's content precedes related shows'
|
||||||
|
* in the document). Falls back to the first feedUrl in the document only when
|
||||||
|
* the id isn't present in the URL. Returns null when no trustworthy match
|
||||||
|
* exists (page restructured, no feed) — callers must not guess.
|
||||||
|
*/
|
||||||
|
export const extractFeedUrlFromPage = (
|
||||||
|
html: string,
|
||||||
|
directoryUrl: string,
|
||||||
|
): string | null => {
|
||||||
|
const idMatch = /[?/]id(\d+)/.exec(directoryUrl)
|
||||||
|
if (!idMatch) {
|
||||||
|
const fallback = FEED_URL_RE.exec(html)
|
||||||
|
return fallback ? fallback[1] : null
|
||||||
|
}
|
||||||
|
|
||||||
|
const adamIdx = html.search(new RegExp(`"adamId"\\s*:\\s*"${idMatch[1]}"`))
|
||||||
|
if (adamIdx < 0) return null
|
||||||
|
|
||||||
|
const fromAdam = new RegExp(FEED_URL_RE.source, "g")
|
||||||
|
fromAdam.lastIndex = adamIdx
|
||||||
|
const match = fromAdam.exec(html)
|
||||||
|
return match ? match[1] : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a delisted show's RSS feed from its Apple Podcasts page.
|
||||||
|
* Returns null on network failure or when the page has no resolvable feed.
|
||||||
|
*/
|
||||||
|
export const resolveItunesFeedUrl = async (
|
||||||
|
directoryUrl: string,
|
||||||
|
): Promise<string | null> => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(directoryUrl, {
|
||||||
|
headers: { "User-Agent": "PodTUI/1.0" },
|
||||||
|
})
|
||||||
|
if (!response.ok) return null
|
||||||
|
return extractFeedUrlFromPage(await response.text(), directoryUrl)
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -60,17 +60,24 @@ const DEFAULT_KEYBINDS: KeybindsResolved = {
|
|||||||
help: ["~", "f1"],
|
help: ["~", "f1"],
|
||||||
// list ops
|
// list ops
|
||||||
search: ["s"],
|
search: ["s"],
|
||||||
|
"search-scope-toggle": ["tab"],
|
||||||
filter: ["f"],
|
filter: ["f"],
|
||||||
sort: [","],
|
sort: [","],
|
||||||
"toggle-hidden": ["."],
|
"toggle-hidden": ["."],
|
||||||
refresh: ["r"],
|
refresh: ["r"],
|
||||||
|
// a subscribes the focused show/episode result in place (x unsubscribes)
|
||||||
|
subscribe: ["a"],
|
||||||
unsubscribe: ["x"],
|
unsubscribe: ["x"],
|
||||||
|
// downloads
|
||||||
|
download: ["d"],
|
||||||
|
"delete-download": ["D"],
|
||||||
|
"whitelist-toggle": ["w"],
|
||||||
// audio transport (preserved; shifted single keys, no collisions)
|
// audio transport (preserved; shifted single keys, no collisions)
|
||||||
"audio-toggle": ["P"],
|
"audio-toggle": ["P"],
|
||||||
"audio-next": ["N"],
|
"audio-next": ["N"],
|
||||||
"audio-prev": ["B"],
|
"audio-prev": ["B"],
|
||||||
"audio-seek-forward": ["shift-."],
|
"audio-seek-forward": ["shift-."], // > = shift+.
|
||||||
"audio-seek-backward": ["shift-,"],
|
"audio-seek-backward": ["shift-,"], // < = shift+,
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Copy keybinds.jsonc to user config directory on first run */
|
/** Copy keybinds.jsonc to user config directory on first run */
|
||||||
|
|||||||
@@ -57,13 +57,13 @@ export function rootFrameFor(
|
|||||||
// terminal size — more robust than fixed percentages and exactly mirrors
|
// terminal size — more robust than fixed percentages and exactly mirrors
|
||||||
// yazi's `mgr.ratio` config. Set a slot's ratio to 0 to hide it (2-pane tabs).
|
// yazi's `mgr.ratio` config. Set a slot's ratio to 0 to hide it (2-pane tabs).
|
||||||
//
|
//
|
||||||
// Current ratios: parent : current : preview = 1 : 2 : 2, i.e. 1/5 : 2/5 : 2/5
|
// Current ratios: parent : current : preview = 2 : 5 : 3, i.e. 20% / 50% / 30%
|
||||||
// (20% / 40% / 40% of the row width). 2-pane tabs drop the preview slot and
|
// of the row width (2 : 5 : 3 of 10). 2-pane tabs drop the preview slot and
|
||||||
// give `current` the combined 4/5.
|
// give `current` the combined 8/10 (80%).
|
||||||
export const PANE_RATIO = {
|
export const PANE_RATIO = {
|
||||||
parent: 1,
|
parent: 2,
|
||||||
current: 2,
|
current: 5,
|
||||||
preview: 2,
|
preview: 3,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
// Number of *focusable* content panes per tab. The three visible columns
|
// Number of *focusable* content panes per tab. The three visible columns
|
||||||
|
|||||||
115
src/utils/nerd-fonts.ts
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
/**
|
||||||
|
* Nerd Font support detection + icon codepoints for PodTui.
|
||||||
|
*
|
||||||
|
* The app prepends Nerd Font glyphs to hard-defined list rows (tabs, Discover
|
||||||
|
* categories, Settings sections, the Feed "Fetch More" row). When the user's
|
||||||
|
* terminal font is NOT Nerd Font capable those glyphs must not render at all —
|
||||||
|
* no tofu boxes, no empty columns — so every call site gates the icon on
|
||||||
|
* `supportsNerdFonts()`.
|
||||||
|
*
|
||||||
|
* Detection is a heuristic (see `supportsNerdFonts`); the `PODTUI_NERD_FONTS`
|
||||||
|
* env override wins over everything so a wrong guess is always fixable.
|
||||||
|
* Under tmux the outer terminal decides — `TMUX` being set counts as
|
||||||
|
* capable (the multiplexer passes glyphs through), matching the same choice
|
||||||
|
* made for `screen`-prefixed TERM values. See README → Configuration → Fonts.
|
||||||
|
*
|
||||||
|
* This module is deliberately free of Solid/JSX imports so it stays
|
||||||
|
* unit-testable in isolation.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// ── Detection ────────────────────────────────────────────────────────────────
|
||||||
|
// Memoized: the terminal does not change mid-session, so detect once.
|
||||||
|
let cached: boolean | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the terminal is (very likely) using a Nerd Font-patched font.
|
||||||
|
*
|
||||||
|
* Order:
|
||||||
|
* a. `PODTUI_NERD_FONTS` env override ("1"/"true" → true, "0"/"false" →
|
||||||
|
* false) — wins over everything.
|
||||||
|
* b. Allowlist: TERM_PROGRAM ∈ {iTerm.app, WezTerm, vscode, ghostty, rio,
|
||||||
|
* hyper, tabby, contour}, or TERM starts with {xterm-kitty, foot,
|
||||||
|
* alacritty, contour, screen} (tmux/screen passthrough — the outer
|
||||||
|
* terminal decides), or WT_SESSION set (Windows Terminal), or TMUX set.
|
||||||
|
* Case-insensitive.
|
||||||
|
* c. Everything else (Terminal.app default SF Mono, plain xterm, unknown)
|
||||||
|
* → false.
|
||||||
|
*/
|
||||||
|
export function supportsNerdFonts(): boolean {
|
||||||
|
if (cached !== null) return cached;
|
||||||
|
|
||||||
|
// a. Env override wins over everything.
|
||||||
|
const override = process.env.PODTUI_NERD_FONTS?.trim().toLowerCase();
|
||||||
|
if (override === "1" || override === "true") {
|
||||||
|
cached = true;
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
if (override === "0" || override === "false") {
|
||||||
|
cached = false;
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
// b. Allowlist.
|
||||||
|
const termProgram = process.env.TERM_PROGRAM?.toLowerCase() ?? "";
|
||||||
|
const term = process.env.TERM?.toLowerCase() ?? "";
|
||||||
|
const TERM_PROGRAM_ALLOWLIST: Record<string, true> = {
|
||||||
|
"iterm.app": true,
|
||||||
|
wezterm: true,
|
||||||
|
vscode: true,
|
||||||
|
ghostty: true,
|
||||||
|
rio: true,
|
||||||
|
hyper: true,
|
||||||
|
tabby: true,
|
||||||
|
contour: true,
|
||||||
|
};
|
||||||
|
const TERM_PREFIX_ALLOWLIST = [
|
||||||
|
"xterm-kitty",
|
||||||
|
"foot",
|
||||||
|
"alacritty",
|
||||||
|
"contour",
|
||||||
|
"screen",
|
||||||
|
];
|
||||||
|
cached =
|
||||||
|
TERM_PROGRAM_ALLOWLIST[termProgram] === true ||
|
||||||
|
TERM_PREFIX_ALLOWLIST.some((prefix) => term.startsWith(prefix)) ||
|
||||||
|
!!process.env.WT_SESSION ||
|
||||||
|
!!process.env.TMUX;
|
||||||
|
|
||||||
|
// c. Everything else falls through to false.
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Icon codepoints ──────────────────────────────────────────────────────────
|
||||||
|
// Font Awesome codepoints in the Nerd Font PUA range — stable across Nerd
|
||||||
|
// Font versions. Keyed by the semantic names the list rows use.
|
||||||
|
export const NF_ICONS: Record<string, string> = {
|
||||||
|
feed: "\uF09E",
|
||||||
|
shows: "\uF005",
|
||||||
|
discover: "\uF14E",
|
||||||
|
search: "\uF002",
|
||||||
|
player: "\uF144",
|
||||||
|
settings: "\uF013",
|
||||||
|
sync: "\uF021",
|
||||||
|
sources: "\uF143",
|
||||||
|
preferences: "\uF1DE",
|
||||||
|
visualizer: "\uF080",
|
||||||
|
downloads: "\uF019",
|
||||||
|
all: "\uF0CA",
|
||||||
|
technology: "\uF2DB",
|
||||||
|
science: "\uF0C3",
|
||||||
|
comedy: "\uF118",
|
||||||
|
news: "\uF1EA",
|
||||||
|
business: "\uF0B1",
|
||||||
|
health: "\uF21E",
|
||||||
|
education: "\uF19D",
|
||||||
|
sports: "\uF1E3",
|
||||||
|
"true-crime": "\uF00E",
|
||||||
|
arts: "\uF1FC",
|
||||||
|
more: "\uF141",
|
||||||
|
add: "\uF067",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Glyph for a named icon when Nerd Fonts are supported, else "". */
|
||||||
|
export function nfIcon(name: string): string {
|
||||||
|
return supportsNerdFonts() ? NF_ICONS[name] ?? "" : "";
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { searchSourceByType } from "./source-searcher";
|
import { searchSourceByType, searchEpisodesByType } from "./source-searcher";
|
||||||
import { parseRSSFeed } from "../api/rss-parser";
|
import { parseRSSFeed } from "../api/rss-parser";
|
||||||
import { SourceType } from "../types/source";
|
import { SourceType } from "../types/source";
|
||||||
import type { PodcastSource, SearchResult } from "../types/source";
|
import type { PodcastSource, SearchResult } from "../types/source";
|
||||||
@@ -17,6 +17,12 @@ const rateLimitState = new Map<string, number[]>();
|
|||||||
const RATE_LIMIT_WINDOW_MS = 60000;
|
const RATE_LIMIT_WINDOW_MS = 60000;
|
||||||
const RATE_LIMIT_MAX_CALLS = 20;
|
const RATE_LIMIT_MAX_CALLS = 20;
|
||||||
|
|
||||||
|
/** Minimum results a primary search must return before the Podcast Index
|
||||||
|
* fallback runs — the open directory is only consulted when Apple's came up
|
||||||
|
* thin, exactly the case where it adds shows Apple lacks. */
|
||||||
|
const FALLBACK_MIN_RESULTS = 3;
|
||||||
|
const FALLBACK_SOURCE_ID = "podcastindex";
|
||||||
|
|
||||||
const throttleSource = async (sourceId: string) => {
|
const throttleSource = async (sourceId: string) => {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const windowStart = now - RATE_LIMIT_WINDOW_MS;
|
const windowStart = now - RATE_LIMIT_WINDOW_MS;
|
||||||
@@ -36,9 +42,9 @@ const throttleSource = async (sourceId: string) => {
|
|||||||
rateLimitState.set(sourceId, updated);
|
rateLimitState.set(sourceId, updated);
|
||||||
};
|
};
|
||||||
|
|
||||||
const buildCacheKey = (query: string, sourceIds: string[]) => {
|
const buildCacheKey = (query: string, sourceIds: string[], prefix: string) => {
|
||||||
const keySources = [...sourceIds].sort().join(",");
|
const keySources = [...sourceIds].sort().join(",");
|
||||||
return `${query.toLowerCase()}::${keySources}`;
|
return `${prefix}:${query.toLowerCase()}::${keySources}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
const isCacheValid = (entry: SearchCacheEntry, ttl: number) =>
|
const isCacheValid = (entry: SearchCacheEntry, ttl: number) =>
|
||||||
@@ -47,8 +53,12 @@ const isCacheValid = (entry: SearchCacheEntry, ttl: number) =>
|
|||||||
const dedupeResults = (results: SearchResult[]): SearchResult[] => {
|
const dedupeResults = (results: SearchResult[]): SearchResult[] => {
|
||||||
const map = new Map<string, SearchResult>();
|
const map = new Map<string, SearchResult>();
|
||||||
for (const result of results) {
|
for (const result of results) {
|
||||||
|
// Episodes dedupe on the episode id; shows on feedUrl/id/title. The two
|
||||||
|
// scopes never mix within one result set, so keys can't collide.
|
||||||
const key =
|
const key =
|
||||||
result.podcast.feedUrl || result.podcast.id || result.podcast.title;
|
result.kind === "episode"
|
||||||
|
? `episode:${result.episode.id}`
|
||||||
|
: result.podcast.feedUrl || result.podcast.id || result.podcast.title;
|
||||||
const existing = map.get(key);
|
const existing = map.get(key);
|
||||||
if (!existing || (result.score ?? 0) > (existing.score ?? 0)) {
|
if (!existing || (result.score ?? 0) > (existing.score ?? 0)) {
|
||||||
map.set(key, result);
|
map.set(key, result);
|
||||||
@@ -87,6 +97,7 @@ export const searchByFeedUrl = async (
|
|||||||
sourceId: "direct-rss",
|
sourceId: "direct-rss",
|
||||||
sourceName: "RSS Feed",
|
sourceName: "RSS Feed",
|
||||||
sourceType: SourceType.RSS,
|
sourceType: SourceType.RSS,
|
||||||
|
kind: "podcast",
|
||||||
// parseRSSFeed marks feeds subscribed; a search result should start
|
// parseRSSFeed marks feeds subscribed; a search result should start
|
||||||
// unsubscribed so the store can flag it correctly if already added.
|
// unsubscribed so the store can flag it correctly if already added.
|
||||||
podcast: { ...podcast, isSubscribed: false },
|
podcast: { ...podcast, isSubscribed: false },
|
||||||
@@ -98,11 +109,20 @@ export const searchByFeedUrl = async (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const searchPodcasts = async (
|
type SourceSearcher = (
|
||||||
|
query: string,
|
||||||
|
source: PodcastSource,
|
||||||
|
) => Promise<SearchResult[]>;
|
||||||
|
|
||||||
|
const searchSources = async (
|
||||||
query: string,
|
query: string,
|
||||||
sourceIds: string[],
|
sourceIds: string[],
|
||||||
sources: PodcastSource[],
|
sources: PodcastSource[],
|
||||||
|
searcher: SourceSearcher,
|
||||||
|
cachePrefix: string,
|
||||||
options: SearchOptions = {},
|
options: SearchOptions = {},
|
||||||
|
/** Optional source id consulted as a low-result fallback (show scope only). */
|
||||||
|
fallbackSourceId?: string,
|
||||||
): Promise<SearchResult[]> => {
|
): Promise<SearchResult[]> => {
|
||||||
const trimmed = query.trim();
|
const trimmed = query.trim();
|
||||||
if (!trimmed) return [];
|
if (!trimmed) return [];
|
||||||
@@ -124,6 +144,7 @@ export const searchPodcasts = async (
|
|||||||
const cacheKey = buildCacheKey(
|
const cacheKey = buildCacheKey(
|
||||||
trimmed,
|
trimmed,
|
||||||
activeSources.map((s) => s.id),
|
activeSources.map((s) => s.id),
|
||||||
|
cachePrefix,
|
||||||
);
|
);
|
||||||
const cached = searchCache.get(cacheKey);
|
const cached = searchCache.get(cacheKey);
|
||||||
if (cached && isCacheValid(cached, cacheTtl)) {
|
if (cached && isCacheValid(cached, cacheTtl)) {
|
||||||
@@ -137,7 +158,7 @@ export const searchPodcasts = async (
|
|||||||
activeSources.map(async (source) => {
|
activeSources.map(async (source) => {
|
||||||
try {
|
try {
|
||||||
await throttleSource(source.id);
|
await throttleSource(source.id);
|
||||||
const sourceResults = await searchSourceByType(trimmed, source);
|
const sourceResults = await searcher(trimmed, source);
|
||||||
results.push(...sourceResults);
|
results.push(...sourceResults);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
errors.push(error as Error);
|
errors.push(error as Error);
|
||||||
@@ -146,7 +167,32 @@ export const searchPodcasts = async (
|
|||||||
);
|
);
|
||||||
|
|
||||||
const deduped = dedupeResults(results);
|
const deduped = dedupeResults(results);
|
||||||
const sorted = deduped.sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
|
let sorted = deduped.sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
|
||||||
|
|
||||||
|
// Low-result fallback: when the primary sources came back thin, consult
|
||||||
|
// the fallback source — but only when it's enabled AND keyed (a key-less
|
||||||
|
// default must never send requests) and it didn't already run as a primary
|
||||||
|
// source above. A fallback failure never sinks the primary results.
|
||||||
|
if (sorted.length < FALLBACK_MIN_RESULTS && fallbackSourceId) {
|
||||||
|
const fallback = sources.find(
|
||||||
|
(s) =>
|
||||||
|
s.id === fallbackSourceId &&
|
||||||
|
s.enabled &&
|
||||||
|
s.hasCredentials === true &&
|
||||||
|
!activeSources.includes(s),
|
||||||
|
);
|
||||||
|
if (fallback) {
|
||||||
|
try {
|
||||||
|
await throttleSource(fallback.id);
|
||||||
|
const fallbackResults = await searcher(trimmed, fallback);
|
||||||
|
sorted = dedupeResults([...sorted, ...fallbackResults]).sort(
|
||||||
|
(a, b) => (b.score ?? 0) - (a.score ?? 0),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
errors.push(error as Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (sorted.length === 0 && errors.length > 0) {
|
if (sorted.length === 0 && errors.length > 0) {
|
||||||
throw new Error("Search failed for all sources");
|
throw new Error("Search failed for all sources");
|
||||||
@@ -156,4 +202,39 @@ export const searchPodcasts = async (
|
|||||||
return sorted;
|
return sorted;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const searchPodcasts = (
|
||||||
|
query: string,
|
||||||
|
sourceIds: string[],
|
||||||
|
sources: PodcastSource[],
|
||||||
|
options: SearchOptions = {},
|
||||||
|
): Promise<SearchResult[]> =>
|
||||||
|
searchSources(
|
||||||
|
query,
|
||||||
|
sourceIds,
|
||||||
|
sources,
|
||||||
|
searchSourceByType,
|
||||||
|
"show",
|
||||||
|
options,
|
||||||
|
FALLBACK_SOURCE_ID,
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Episode-scope search: find individual episodes (e.g. a guest appearing
|
||||||
|
* across shows). Shares the source guard, rate limiting, and cache with
|
||||||
|
* searchPodcasts; the cache key is scoped separately so the two result
|
||||||
|
* kinds never collide for the same query. */
|
||||||
|
export const searchEpisodes = (
|
||||||
|
query: string,
|
||||||
|
sourceIds: string[],
|
||||||
|
sources: PodcastSource[],
|
||||||
|
options: SearchOptions = {},
|
||||||
|
): Promise<SearchResult[]> =>
|
||||||
|
searchSources(
|
||||||
|
query,
|
||||||
|
sourceIds,
|
||||||
|
sources,
|
||||||
|
searchEpisodesByType,
|
||||||
|
"episode",
|
||||||
|
options,
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
100
src/utils/source-credentials.ts
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
/**
|
||||||
|
* Credential storage for keyed podcast sources.
|
||||||
|
*
|
||||||
|
* Preferred storage is the macOS keychain (encrypted at rest by the OS),
|
||||||
|
* written through the `security` CLI — no native dependencies. When the
|
||||||
|
* keychain is unavailable (non-macOS, locked, sandboxed) credentials fall
|
||||||
|
* back to plaintext on the source itself (config.json) so the source still
|
||||||
|
* works; `credentialStorage` on the source records which backend was used.
|
||||||
|
*
|
||||||
|
* Credentials are never presented in full — the UI always masks them (first
|
||||||
|
* 3 chars + "..."). The keychain password is passed as an argv value to
|
||||||
|
* `add-generic-password` (standard practice for CLI-driven keychain writes;
|
||||||
|
* the item lands in the login keychain immediately).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { PodcastSource } from "../types/source"
|
||||||
|
|
||||||
|
const KEYCHAIN_SERVICE = "podtui"
|
||||||
|
const KEYCHAIN_ACCOUNT = "podcastindex"
|
||||||
|
|
||||||
|
export type Credentials = {
|
||||||
|
apiKey: string
|
||||||
|
apiSecret: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Run a `security` subcommand; resolves with exit status + stdout. */
|
||||||
|
async function runSecurity(
|
||||||
|
args: string[],
|
||||||
|
): Promise<{ ok: boolean; stdout: string }> {
|
||||||
|
try {
|
||||||
|
const proc = Bun.spawn({
|
||||||
|
cmd: ["security", ...args],
|
||||||
|
stdin: "ignore",
|
||||||
|
stdout: "pipe",
|
||||||
|
stderr: "pipe",
|
||||||
|
})
|
||||||
|
const [stdout] = await Promise.all([
|
||||||
|
new Response(proc.stdout).text(),
|
||||||
|
new Response(proc.stderr).text(),
|
||||||
|
])
|
||||||
|
const exitCode = await proc.exited
|
||||||
|
return { ok: exitCode === 0, stdout }
|
||||||
|
} catch {
|
||||||
|
return { ok: false, stdout: "" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Store Podcast Index credentials in the macOS keychain. True on success. */
|
||||||
|
export async function savePodcastIndexCredentials(
|
||||||
|
apiKey: string,
|
||||||
|
apiSecret: string,
|
||||||
|
): Promise<boolean> {
|
||||||
|
const payload = JSON.stringify({ apiKey, apiSecret })
|
||||||
|
const { ok } = await runSecurity([
|
||||||
|
"add-generic-password",
|
||||||
|
"-a",
|
||||||
|
KEYCHAIN_ACCOUNT,
|
||||||
|
"-s",
|
||||||
|
KEYCHAIN_SERVICE,
|
||||||
|
"-w",
|
||||||
|
payload,
|
||||||
|
"-U",
|
||||||
|
])
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read Podcast Index credentials from the macOS keychain. Null when absent
|
||||||
|
* or unreadable (non-macOS, item deleted, keychain locked). */
|
||||||
|
export async function loadPodcastIndexCredentials(): Promise<Credentials | null> {
|
||||||
|
const { ok, stdout } = await runSecurity([
|
||||||
|
"find-generic-password",
|
||||||
|
"-a",
|
||||||
|
KEYCHAIN_ACCOUNT,
|
||||||
|
"-s",
|
||||||
|
KEYCHAIN_SERVICE,
|
||||||
|
"-w",
|
||||||
|
])
|
||||||
|
if (!ok) return null
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(stdout.trim()) as Credentials
|
||||||
|
if (!parsed.apiKey || !parsed.apiSecret) return null
|
||||||
|
return parsed
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve a source's stored credentials: its plaintext fields when saved
|
||||||
|
* with the plaintext fallback, else the macOS keychain. Null when the
|
||||||
|
* source has no usable credentials. */
|
||||||
|
export async function resolveSourceCredentials(
|
||||||
|
source: PodcastSource,
|
||||||
|
): Promise<Credentials | null> {
|
||||||
|
if (source.credentialStorage === "plaintext") {
|
||||||
|
return source.apiKey && source.apiSecret
|
||||||
|
? { apiKey: source.apiKey, apiSecret: source.apiSecret }
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
return loadPodcastIndexCredentials()
|
||||||
|
}
|
||||||