From 3ebfc45abb6e2b076bdd8304a881b604bffe2b37 Mon Sep 17 00:00:00 2001 From: Sanapach Date: Thu, 19 Nov 2026 21:13:27 +0200 Subject: [PATCH] Play podcast episodes in the web player Episodes in the queue are no longer skipped. The player asks the podcast API for the audio source and the resume position, plays the publisher URL (or the same-origin proxy when the administrator enabled it and the direct URL fails or is http:// on an https:// page) and seeks before it starts, so it never reports a resumed episode that plays from elsewhere: a server that cannot seek to the saved position shows that and keeps the position until the user plays from the start. Progress follows the contract: Play starts a listening session as an explicit action above the handed-off generation, checkpoints go out every 20 s and on pause, a seek is an explicit action, the end of the stream completes the episode, and a stop, a page hide (beacon) or a handoff saves the final position. Writes of a session run one after another in the background; a superseded session stops writing, and a device that loses the playback role ends its session without a report. Reports always carry the position of their own episode. Jam placeholders stay unplayable and episodes stay private for Jam rules. A podcasts store holds the list, the podcast page and the explicit episode actions for the UI of the next commit. Co-Authored-By: Claude Opus 5.5 --- src/i18n/phrases.rs | 58 +- templates/player/scripts.html | 928 +++++++++++++++++++++++++++- tests/player_podcasts.test.cjs | 532 ++++++++++++++++ tests/player_queue_sources.test.cjs | 112 ++-- 4 files changed, 1566 insertions(+), 64 deletions(-) create mode 100644 tests/player_podcasts.test.cjs diff --git a/src/i18n/phrases.rs b/src/i18n/phrases.rs index ca71a59..6e5855a 100644 --- a/src/i18n/phrases.rs +++ b/src/i18n/phrases.rs @@ -382,8 +382,64 @@ translations! { player_clear: "Clear" , "Очистить"; player_remove: "Remove" , "Удалить"; player_queue_empty: "Queue is empty" , "Очередь пуста"; - player_queue_podcast_unplayable: "Podcast · not playable in the web player yet", "Подкаст · пока не воспроизводится в веб-плеере"; + player_queue_podcast_item: "Podcast episode" , "Выпуск подкаста"; player_queue_private_item: "Private item · hidden by its owner", "Приватный элемент · скрыт владельцем"; + player_podcasts: "Podcasts", "Подкасты"; + player_podcast_add_placeholder: "RSS feed URL", "Адрес RSS-ленты"; + player_podcast_add: "Add", "Добавить"; + player_podcast_adding: "Loading the feed…", "Загружаем ленту…"; + player_podcast_added: "Subscribed", "Подписка добавлена"; + player_podcast_already: "Already subscribed", "Вы уже подписаны"; + player_podcast_private_note: "New subscriptions are private: they sync only between your own devices.", "Новые подписки приватны: они синхронизируются только между вашими устройствами."; + player_podcasts_empty: "No podcasts yet. Add an RSS feed to subscribe.", "Подкастов пока нет. Добавьте RSS-ленту, чтобы подписаться."; + player_podcast_show_unsubscribed: "Show unsubscribed", "Показать без подписки"; + player_podcast_unplayed: "unplayed", "не прослушано"; + player_podcast_episodes: "episodes", "выпусков"; + player_podcast_seasons: "seasons", "сезонов"; + player_podcast_unsubscribed: "Not subscribed", "Нет подписки"; + player_podcast_refresh: "Refresh", "Обновить"; + player_podcast_refreshing: "Checking the feed…", "Проверяем ленту…"; + player_podcast_refresh_updated: "Feed updated", "Лента обновлена"; + player_podcast_refresh_not_modified: "No changes in the feed", "Изменений в ленте нет"; + player_podcast_refresh_failed: "Could not refresh the feed", "Не удалось обновить ленту"; + player_podcast_last_checked: "Checked", "Проверено"; + player_podcast_never_checked: "Not checked yet", "Ещё не проверялась"; + player_podcast_fetch_error: "Last check failed", "Последняя проверка не удалась"; + player_podcast_next_check: "next check", "следующая проверка"; + player_podcast_unsubscribe: "Unsubscribe", "Отписаться"; + player_podcast_unsubscribe_confirm: "Unsubscribe from “{title}”? The feed will no longer be checked. Your progress and listening history are kept: subscribing again continues where you stopped.", "Отписаться от «{title}»? Лента больше не будет проверяться. Прогресс и история прослушиваний сохранятся: при повторной подписке вы продолжите с того же места."; + player_podcast_subscribe: "Subscribe", "Подписаться"; + player_podcast_all_seasons: "All seasons", "Все сезоны"; + player_podcast_season: "Season", "Сезон"; + player_podcast_no_season: "No season", "Без сезона"; + player_podcast_filter_all: "All episodes", "Все выпуски"; + player_podcast_filter_unplayed: "Unplayed", "Не прослушано"; + player_podcast_filter_in_progress: "In progress", "Начато"; + player_podcast_filter_played: "Played", "Прослушано"; + player_podcast_sort_newest: "Newest first", "Сначала новые"; + player_podcast_sort_oldest: "Oldest first", "Сначала старые"; + player_podcast_sort_number: "By number", "По номеру"; + player_podcast_search: "Search episodes", "Поиск по выпускам"; + player_podcast_no_episodes: "No episodes match.", "Подходящих выпусков нет."; + player_podcast_play: "Play", "Слушать"; + player_podcast_resume: "Resume", "Продолжить"; + player_podcast_restart: "Start over", "Начать сначала"; + player_podcast_mark_played: "Mark played", "Прослушано"; + player_podcast_mark_unplayed: "Mark unplayed", "Не прослушано"; + player_podcast_add_queue: "Add to queue", "В очередь"; + player_podcast_left: "left", "осталось"; + player_podcast_saved_at: "Saved at", "Сохранено на"; + player_podcast_played_badge: "Played", "Прослушано"; + player_podcast_played_times: "Completed listens", "Полных прослушиваний"; + player_podcast_not_in_feed: "No longer in the feed", "Больше нет в ленте"; + player_podcast_load_more: "Load more", "Показать ещё"; + player_podcast_history: "Recently listened", "Недавно прослушано"; + player_podcast_jam_blocked: "Podcast episodes are private and cannot be added to a Jam.", "Выпуски подкастов приватны и не добавляются в Jam."; + player_podcast_source_failed: "Could not load this episode from the publisher.", "Не удалось загрузить выпуск у издателя."; + player_podcast_cannot_seek: "The publisher server cannot seek to the saved position. Press Play to listen from the start; until then the saved position is kept.", "Сервер издателя не умеет перематывать к сохранённой позиции. Нажмите Play, чтобы слушать с начала; до этого сохранённая позиция не меняется."; + player_podcast_loading: "Preparing the episode…", "Готовим выпуск…"; + player_podcast_feed: "Feed", "Лента"; + player_podcast_request_failed: "Request failed", "Запрос не выполнен"; player_shuffle: "Shuffle" , "Перемешать"; player_repeat: "Repeat" , "Повтор"; player_volume: "Volume" , "Громкость"; diff --git a/templates/player/scripts.html b/templates/player/scripts.html index 83890f7..cc7f1e9 100644 --- a/templates/player/scripts.html +++ b/templates/player/scripts.html @@ -64,7 +64,28 @@ const T = { lastfmDisconnectFailed: "{{ t.player_lastfm_disconnect_failed }}", download: "{{ t.track_download }}", shareUnavailable: "{{ t.share_unavailable }}", - queuePodcastUnplayable: "{{ t.player_queue_podcast_unplayable }}", + queuePodcastItem: "{{ t.player_queue_podcast_item }}", + podcastAdded: "{{ t.player_podcast_added }}", + podcastAlready: "{{ t.player_podcast_already }}", + podcastRefreshUpdated: "{{ t.player_podcast_refresh_updated }}", + podcastRefreshNotModified: "{{ t.player_podcast_refresh_not_modified }}", + podcastRefreshFailed: "{{ t.player_podcast_refresh_failed }}", + podcastLastChecked: "{{ t.player_podcast_last_checked }}", + podcastNeverChecked: "{{ t.player_podcast_never_checked }}", + podcastFetchError: "{{ t.player_podcast_fetch_error }}", + podcastNextCheck: "{{ t.player_podcast_next_check }}", + podcastUnsubscribeConfirm: "{{ t.player_podcast_unsubscribe_confirm }}", + podcastSeason: "{{ t.player_podcast_season }}", + podcastNoSeason: "{{ t.player_podcast_no_season }}", + podcastLeft: "{{ t.player_podcast_left }}", + podcastSavedAt: "{{ t.player_podcast_saved_at }}", + podcastJamBlocked: "{{ t.player_podcast_jam_blocked }}", + podcastSourceFailed: "{{ t.player_podcast_source_failed }}", + podcastCannotSeek: "{{ t.player_podcast_cannot_seek }}", + podcastRequestFailed: "{{ t.player_podcast_request_failed }}", + podcastEpisodes: "{{ t.player_podcast_episodes }}", + podcastUnplayed: "{{ t.player_podcast_unplayed }}", + podcastSeasons: "{{ t.player_podcast_seasons }}", queuePrivateItem: "{{ t.player_queue_private_item }}", searchSimilarTo: "{{ t.player_search_similar_to }}", findSimilar: "{{ t.player_find_similar }}", @@ -758,8 +779,17 @@ document.addEventListener('alpine:init', () => { _lastAudioTime: 0, _localSourceTrackId: null, // The current item is one this player cannot play and nobody told it - // that item's position (see _showUnplayableQueueItem). + // that item's position (see _showUnplayableQueueItem), or a podcast + // episode whose resume position the server has not sent yet. _positionUnknown: false, + // Podcast episode playback (see _playEpisodeLocal): what the UI + // shows about the current episode and its listening session. + episodeNotice: '', + episodeLoading: false, + _episode: null, + _episodeToken: 0, + _episodeSeekTimer: null, + _episodeCheckpointMs: 20000, _remoteExecuting: false, _remoteStateBaseTime: 0, _remoteStateReceivedAt: 0, @@ -781,6 +811,7 @@ document.addEventListener('alpine:init', () => { // timeupdate at 0; keep that item's handed-off position. if (!this._currentItemHasLocalAudio()) return; this.currentTime = audio.currentTime; + if (this._episode) this._episode.lastPosition = audio.currentTime; this.duration = audio.duration || 0; this.progress = this.duration > 0 ? (this.currentTime / this.duration) * 100 : 0; this._trackListenedDelta(); @@ -790,6 +821,7 @@ document.addEventListener('alpine:init', () => { audio.addEventListener('ended', () => { this._trackListenedDelta(); this._recordHistory('finished'); + if (this._episode?.ready) this._reportEpisode('ended'); if (Alpine.store('devices')?.shouldPlayJamLocally()) { this.isPlaying = false; return; @@ -807,7 +839,9 @@ document.addEventListener('alpine:init', () => { this._trackListenedDelta(); this.isPlaying = false; this._lastAudioTime = audio.currentTime || 0; + this._onEpisodePaused(); }); + audio.addEventListener('error', () => this._onEpisodeAudioError()); audio.addEventListener('loadedmetadata', () => { this.duration = audio.duration || 0; @@ -820,6 +854,13 @@ document.addEventListener('alpine:init', () => { this._remoteStateTimer = setInterval(() => { this._tickRemoteProgress(); }, 250); + // Episode checkpoints (the interval itself is _episodeCheckpointMs). + setInterval(() => this._episodeTick(), 5000); + document.addEventListener('visibilitychange', () => { + if (document.hidden && this.isPlaying && this._isLocalPlaybackDevice()) { + this._reportEpisode('checkpoint', { keepalive: true }); + } + }); // Restore state if (!this._hasInitialShareLink()) { @@ -831,6 +872,7 @@ document.addEventListener('alpine:init', () => { if (this._isLocalPlaybackDevice()) { this._saveStateSync(); this._recordHistory('stopped', true); + this._reportEpisode('stop', { beacon: true }); } }); window.addEventListener('pageshow', (event) => { @@ -932,7 +974,14 @@ document.addEventListener('alpine:init', () => { this._showUnplayableQueueItem(track, options.position_seconds); return; } + if (this._isPodcastEpisode(track)) { + // Without a position the episode resumes from its progress. + this._recordHistory('replaced'); + this._playEpisodeLocal(track, options); + return; + } this._recordHistory('replaced'); + this._endEpisode('stop'); this._positionUnknown = false; this.currentTrack = track; this._historyTrack = track; @@ -976,6 +1025,7 @@ document.addEventListener('alpine:init', () => { this._sendRemote('pause'); return; } + if (this._episode) this._episode.wantPlay = false; this._pauseLocal(); }, @@ -995,6 +1045,10 @@ document.addEventListener('alpine:init', () => { this._skipUnplayableCurrentItem(); return; } + if (this._isPodcastEpisode(this.currentTrack)) { + this._resumeEpisode(); + return; + } audio.play().catch(() => {}); }, @@ -1040,6 +1094,10 @@ document.addEventListener('alpine:init', () => { this._showUnplayableQueueItem(this.currentTrack, nextTime); return; } + if (this._isPodcastEpisode(this.currentTrack)) { + this._seekEpisode(nextTime); + return; + } audio.currentTime = nextTime; this._lastAudioTime = audio.currentTime || 0; }, @@ -1047,7 +1105,7 @@ document.addEventListener('alpine:init', () => { seekRelative(delta) { if (!this.currentTrack) return; const duration = this.duration || audio.duration || 0; - const current = this._shouldSendRemote() || this._isUnplayableQueueItem(this.currentTrack) ? this.currentTime : audio.currentTime; + const current = this._shouldSendRemote() || !this._currentItemHasLocalAudio(this.currentTrack) ? this.currentTime : audio.currentTime; const max = duration > 0 ? duration : Number.MAX_SAFE_INTEGER; this.seek(Math.max(0, Math.min(max, current + delta))); }, @@ -1348,7 +1406,9 @@ document.addEventListener('alpine:init', () => { this._remoteStateBaseTime = desiredTime; this._remoteStateReceivedAt = Date.now(); - if (this._isUnplayableQueueItem(track)) { + // A mirrored Jam state never plays (or writes progress for) an + // episode here; guests only ever receive placeholders anyway. + if (this._isUnplayableQueueItem(track) || this._isPodcastEpisode(track)) { this._showUnplayableQueueItem(track, state.position_unknown ? null : desiredTime); this._updateMediaSession(); return; @@ -1413,7 +1473,15 @@ document.addEventListener('alpine:init', () => { queue.currentIndex = Math.max(0, Math.min(Number(payload.index || 0), queue.tracks.length - 1)); } const track = payload.track || queue.tracks[queue.currentIndex]; - if (track?.unavailable || (track && !track.stream_url)) { + if (this._isPodcastEpisode(track) && !this._isUnplayableQueueItem(track)) { + // A transfer carries the episode's position and pause + // state; play commands start it at its resume position. + const known = command.command === 'transfer_state' && payload.position_unknown !== true; + this._playEpisodeLocal(track, { + position_seconds: known ? payload.position_seconds : null, + paused: !!payload.paused, + }); + } else if (this._isUnplayableQueueItem(track) || track?.unavailable || (track && !track.stream_url)) { this._applyRemotePlaybackState({ ...payload, track, paused: true }); // This device is now active, so _applyRemotePlaybackState // does not set the time: keep the handed-off position as @@ -1477,15 +1545,31 @@ document.addEventListener('alpine:init', () => { }, _isUnplayableQueueItem(track) { + // Jam placeholders of someone else's private items. Episodes play + // here, except on a shared-link guest page (no podcast API). + const kind = this._queueItemSourceKind(track); + if (kind === 'private') return true; + return kind === 'podcast_episode' && typeof GUEST !== 'undefined' && GUEST === true; + }, + + _isPodcastEpisode(track) { + return this._queueItemSourceKind(track) === 'podcast_episode'; + }, + + _isPrivateQueueItem(track) { + // What a Jam participant may neither see nor change: the host's + // podcast episodes and the placeholders standing for them. const kind = this._queueItemSourceKind(track); return kind === 'podcast_episode' || kind === 'private'; }, _unplayableQueueLabel(track) { - const kind = this._queueItemSourceKind(track); - if (kind === 'podcast_episode') return T.queuePodcastUnplayable; - if (kind === 'private') return T.queuePrivateItem; - return ''; + if (!this._isUnplayableQueueItem(track)) return ''; + return this._isPodcastEpisode(track) ? T.queuePodcastItem : T.queuePrivateItem; + }, + + _queueItemNote(track) { + return this._unplayableQueueLabel(track) || (this._isPodcastEpisode(track) ? T.queuePodcastItem : ''); }, _playableQueueIndex(tracks, start, step = 1) { @@ -1497,14 +1581,22 @@ document.addEventListener('alpine:init', () => { }, _currentItemHasLocalAudio(track = this.currentTrack) { - // Whether