Files
furumi-web/templates/player/podcast_scripts.html
T
ab eefe8a9777
Build and Publish / Build and Publish Docker Image (push) Successful in 2m6s
Fix podcast page
2026-11-22 17:49:23 +02:00

491 lines
22 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script>
document.addEventListener('alpine:init', () => {
const labels = {
podcasts: ['Podcasts', 'Подкасты'],
episodes: ['Episodes', 'Выпуски'],
subscribeHint: [
'Subscribe to listen and save episodes.',
'Подпишитесь, чтобы слушать и сохранять выпуски.',
],
notFound: ['Podcast not found.', 'Подкаст не найден.'],
showMore: ['Show more', 'Подробнее'],
showLess: ['Show less', 'Свернуть'],
add: ['Add', 'Добавить'],
mine: ['My podcasts', 'Мои подкасты'],
public: ['Public podcasts', 'Публичные подкасты'],
results: ['Podcast search results', 'Результаты поиска подкастов'],
noMatches: ['No matching podcasts.', 'Подходящих подкастов нет.'],
empty: ['Add an RSS or Atom feed.', 'Добавьте RSS или Atom ленту.'],
check: ['Check episodes', 'Проверить выпуски'],
checkAll: ['Check all', 'Проверить все'],
publish: ['Publish', 'Опубликовать'],
unpublish: ['Unpublish', 'Снять публикацию'],
remove: ['Unsubscribe', 'Отписаться'],
subscribe: ['Subscribe', 'Подписаться'],
play: ['Play', 'Слушать'],
open: ['Open', 'Открыть'],
resume: ['Resume', 'Продолжить'],
download: ['Save on server', 'Сохранить на сервере'],
saved: ['Saved on server', 'Сохранено на сервере'],
downloading: ['Downloading…', 'Скачивается…'],
markPlayed: ['Mark played', 'Прослушано'],
markUnplayed: ['Mark unplayed', 'Не прослушано'],
restart: ['Start over', 'С начала'],
filter: ['Filter episodes', 'Поиск выпусков'],
season: ['Season', 'Сезон'],
allSeasons: ['All seasons', 'Все сезоны'],
unplayed: ['unplayed', 'не прослушано'],
unplayedOnly: ['Unplayed only', 'Только непрослушанные'],
description: ['Description', 'Описание'],
noEpisodes: ['No episodes in this filter.', 'В этом фильтре нет выпусков.'],
noPublic: ['No public podcasts yet.', 'Публичных подкастов пока нет.'],
searchNetwork: ['Search podcasts', 'Поиск подкастов'],
search: ['Search', 'Найти'],
working: ['Working…', 'Выполняется…'],
done: ['Done', 'Готово'],
removeConfirm: [
'Remove only your subscription? Other subscribers keep access.',
'Удалить только вашу подписку? Доступ других подписчиков сохранится.',
],
shareConfirm: [
'Publish this feed URL to other users and Frid?',
'Опубликовать ссылку на ленту для других пользователей и Frid?',
],
privateConfirm: [
'This URL may contain private access credentials. Publish these exact URLs?',
'Ссылка может содержать приватный токен доступа. Опубликовать именно эти ссылки?',
],
pending: [
'Saved. Frid publication will retry when federation is available.',
'Сохранено. Публикация в Frid повторится, когда федерация будет доступна.',
],
checked: ['New episodes: ', 'Новых выпусков: '],
failed: [
'Operation failed. Please try again.',
'Не удалось выполнить действие. Повторите попытку.',
],
};
Alpine.store('podcasts', {
mine: [],
public: [],
hits: [],
searched: false,
episodes: [],
hasMore: false,
selected: null,
selectedId: null,
loading: false,
adding: false,
failedArtwork: {},
descriptionExpanded: false,
_navigation: 0,
url: '',
query: '',
filter: '',
season: '',
unplayedOnly: false,
busy: false,
message: '',
poller: null,
lastCheckpoint: 0,
text(key) {
if (key === 'loadMore')
return document.documentElement.lang.startsWith('ru')
? 'Загрузить ещё выпуски'
: 'Load more episodes';
return labels[key]?.[document.documentElement.lang.startsWith('ru') ? 1 : 0] || key;
},
async api(action, body = {}) {
const res = await fetch('/api/podcasts/action', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action, ...body }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || this.text('failed'));
return data;
},
async task(fn) {
if (this.busy) return;
this.busy = true;
this.message = this.text('working');
try {
await fn();
} catch (e) {
this.message = e.message || this.text('failed');
} finally {
this.busy = false;
}
},
async load() {
const data = await this.api('list');
this.mine = data.mine.map((pod) => ({ ...pod, subscribed: true }));
this.public = data.public;
if (this.selected) {
const current =
this.mine.find((p) => p.id === this.selected.id) ||
this.public.find((p) => p.id === this.selected.id);
this.selected = {
...this.selected,
...current,
subscribed: this.mine.some((p) => p.id === this.selected.id),
};
}
},
artwork(pod) {
const url = pod?.metadata?.image_url;
return url && !this.failedArtwork[url] ? url : null;
},
artworkFailed(pod) {
const url = pod?.metadata?.image_url;
if (url) this.failedArtwork[url] = true;
},
description(pod) {
const text = pod?.metadata?.description || '';
return !this.descriptionExpanded && text.length > 360
? text.slice(0, 360).trimEnd() + '…'
: text;
},
navigate(hash, view, options = {}) {
const library = Alpine.store('library');
library._beginNavigation(hash, options);
library.view = view;
library.currentArtist = null;
library.currentRelease = null;
library.currentPlaylist = null;
Alpine.store('mobile')?.closeLibrary();
this.ensurePolling();
},
ensurePolling() {
if (!this.poller)
this.poller = setInterval(() => {
if (
['podcasts', 'podcast_detail'].includes(Alpine.store('library').view) &&
!this.busy &&
!this.loading
)
this.update().catch(() => {});
}, 5000);
},
async enter(options = {}) {
const token = ++this._navigation;
this.navigate('#podcasts', 'podcasts', options);
this.selected = null;
this.selectedId = null;
this.episodes = [];
this.message = '';
this.loading = true;
try {
await this.load();
} catch (error) {
if (token === this._navigation) this.message = error.message;
} finally {
if (token === this._navigation) {
this.loading = false;
Alpine.store('library')._afterNavigation(options);
}
}
},
async update() {
await this.load();
if (this.selected?.subscribed) await this.loadEpisodes();
else this.episodes = [];
},
async loadEpisodes(append = false) {
const id = this.selected.id;
const offset = append ? this.episodes.length : 0;
const data = await this.api('episodes', { id, offset });
if (this.selected?.id !== id) return;
const old = this.episodes;
this.episodes = append
? [...old, ...data.episodes]
: [...new Map([...data.episodes, ...old].map((e) => [e.id, e])).values()];
if (append || old.length <= 200) this.hasMore = !!data.has_more;
},
more() {
return this.task(async () => {
await this.loadEpisodes(true);
this.message = '';
});
},
async open(pod, options = {}) {
const id = typeof pod === 'string' ? pod : pod.id;
const token = ++this._navigation;
this.selectedId = id;
this.descriptionExpanded = false;
const cached =
this.mine.find((p) => p.id === id) ||
this.public.find((p) => p.id === id) ||
(typeof pod === 'object' ? pod : null);
this.selected = cached
? {
...cached,
subscribed: this.mine.some((p) => p.id === id) || !!cached.subscribed,
}
: null;
this.episodes = [];
this.hasMore = false;
this.filter = '';
this.season = '';
this.message = '';
this.loading = true;
this.navigate('#podcast?id=' + encodeURIComponent(id), 'podcast_detail', options);
try {
await this.load();
if (token !== this._navigation) return;
const detail =
this.mine.find((p) => p.id === id) ||
this.public.find((p) => p.id === id) ||
this.selected ||
(await this.api('detail', { id }));
if (token !== this._navigation) return;
this.selected = { ...detail, subscribed: this.mine.some((p) => p.id === id) };
if (this.selected.subscribed) await this.loadEpisodes();
} catch (error) {
if (token === this._navigation)
this.message = error.message || this.text('notFound');
} finally {
if (token === this._navigation) {
this.loading = false;
Alpine.store('library')._afterNavigation(options);
}
}
},
openResult(pod) {
return this.open(pod);
},
subscribe(pod = this.selected) {
return this.task(async () => {
await this.api('add', { url: pod.url || pod.metadata.feed_url });
await this.load();
if (this.selectedId === pod.id) {
this.selected = this.mine.find((p) => p.id === pod.id) || {
...pod,
subscribed: true,
};
await this.loadEpisodes();
}
this.message = '';
});
},
add(url) {
this.task(async () => {
const result = await this.api('add', { url: url || this.url });
this.url = '';
await this.load();
this.adding = false;
if (result.id) await this.open(result.id);
this.message = result.warning || this.text('done');
});
},
remove(pod) {
if (!confirm(this.text('removeConfirm'))) return;
this.task(async () => {
const result = await this.api('remove', { id: pod.id });
if (this.selected?.id === pod.id) {
++this._navigation;
this.loading = false;
this.selected = null;
this.selectedId = null;
this.episodes = [];
this.navigate('#podcasts', 'podcasts');
Alpine.store('library')._afterNavigation();
}
await this.load();
this.message = this.text(result.publication_pending ? 'pending' : 'done');
});
},
share(pod) {
if (
!pod.shared &&
!confirm(this.text('shareConfirm') + '\n' + pod.metadata.feed_url)
)
return;
this.task(async () => {
let result = await this.api('share', { id: pod.id, shared: !pod.shared });
if (result.confirmation_required) {
if (
!confirm(
this.text('privateConfirm') +
'\n' +
result.urls.filter(Boolean).join('\n'),
)
) {
this.message = '';
return;
}
result = await this.api('share', {
id: pod.id,
shared: true,
confirmed: true,
});
}
await this.load();
this.message = this.text(result.publication_pending ? 'pending' : 'done');
});
},
refresh(pod) {
this.task(async () => {
const data = await this.api('refresh', { id: pod.id });
await this.update();
this.message = this.text('checked') + data.added;
});
},
refreshAll() {
this.task(async () => {
let count = 0;
for (const pod of this.mine) {
const data = await this.api('refresh', { id: pod.id });
count += data.added;
}
await this.update();
this.message = this.text('checked') + count;
});
},
download(episode) {
this.task(async () => {
await this.api('download', { id: episode.id });
episode.downloading = true;
this.message = this.text('downloading');
});
},
search() {
const query = this.query.trim();
return this.task(async () => {
const data = await this.api('search', { query });
if (this.query.trim() !== query) {
this.message = '';
return;
}
this.hits = data.hits;
this.searched = true;
this.message = this.text('done');
});
},
resetSearch() {
this.searched = false;
this.hits = [];
},
publicCards() {
return [
...new Map(
(this.searched ? this.hits : this.public).map((p) => [p.id, p]),
).values(),
];
},
seasons() {
return [
...new Set(
this.episodes.map((e) => e.metadata.season).filter((s) => s != null),
),
].sort((a, b) => a - b);
},
filteredEpisodes() {
const filter = this.filter.toLocaleLowerCase();
return this.episodes.filter(
(e) =>
(!filter || e.metadata.title.toLocaleLowerCase().includes(filter)) &&
(!this.season || String(e.metadata.season) === String(this.season)) &&
(!this.unplayedOnly || !e.completed),
);
},
date(ms) {
return ms ? new Date(ms).toLocaleDateString() : '';
},
play(episode) {
return this.task(async () => {
const devices = Alpine.store('devices');
if (devices && !devices.isActive()) await devices.select(devices.id);
const position = episode.completed ? 0 : episode.position_ms;
const session = await this.api('progress', {
id: episode.id,
position_ms: position,
explicit: true,
});
const player = Alpine.store('player');
player._playLocal(
{
id: episode.id,
podcast: true,
podcast_generation: session.generation,
podcast_id: episode.metadata.podcast_id,
title: episode.metadata.title,
artists: [{ id: null, name: this.selected.metadata.title }],
featured_artists: [],
release_id: null,
release_title: this.selected.metadata.title,
duration_seconds: (episode.metadata.duration_ms || 0) / 1000,
stream_url: '/api/podcasts/media/' + encodeURIComponent(episode.id),
cover_url:
episode.metadata.image_url || this.selected.metadata.image_url,
},
{ position_seconds: position / 1000 },
);
this.lastCheckpoint = Date.now();
this.message = '';
});
},
checkpoint(player, completed = false, unloading = false) {
const track = player.currentTrack;
if (!track?.podcast) return;
const payload = {
action: 'progress',
id: track.id,
position_ms: Math.round((player.currentTime || 0) * 1000),
completed,
generation: track.podcast_generation,
sequence: Date.now(),
};
const episode = this.episodes.find((e) => e.id === track.id);
if (episode) {
episode.position_ms = payload.position_ms;
episode.completed = completed;
}
if (unloading) {
navigator.sendBeacon(
'/api/podcasts/action',
new Blob([JSON.stringify(payload)], { type: 'application/json' }),
);
} else {
this.api('progress', payload).catch(() => {});
}
this.lastCheckpoint = Date.now();
},
tick(player) {
if (
player.currentTrack?.podcast &&
player.isPlaying &&
Date.now() - this.lastCheckpoint > 10000
)
this.checkpoint(player, !!player.currentTrack.podcast_completed);
},
mark(episode) {
return this.task(async () => {
const completed = !episode.completed;
const position = completed ? episode.position_ms : 0;
const result = await this.api('progress', {
id: episode.id,
position_ms: position,
completed,
explicit: true,
});
episode.completed = completed;
episode.position_ms = position;
const player = Alpine.store('player');
if (player.currentTrack?.id === episode.id) {
player.currentTrack.podcast_generation = result.generation;
player.currentTrack.podcast_completed = completed;
if (!completed) player.seek(0);
}
this.message = this.text('done');
});
},
restart(episode) {
episode.position_ms = 0;
episode.completed = false;
return this.play(episode);
},
});
});
</script>