Files
furumi-web/templates/player/podcast_scripts.html
T

490 lines
22 KiB
HTML
Raw Normal View History

2026-11-22 16:05:37 +02:00
<script>
document.addEventListener('alpine:init', () => {
const labels = {
podcasts: ['Podcasts', 'Подкасты'],
2026-11-22 17:49:23 +02:00
episodes: ['Episodes', 'Выпуски'],
subscribeHint: [
'Subscribe to listen and save episodes.',
'Подпишитесь, чтобы слушать и сохранять выпуски.',
],
notFound: ['Podcast not found.', 'Подкаст не найден.'],
showMore: ['Show more', 'Подробнее'],
showLess: ['Show less', 'Свернуть'],
2026-11-22 16:05:37 +02:00
add: ['Add', 'Добавить'],
mine: ['My podcasts', 'Мои подкасты'],
public: ['Public podcasts', 'Публичные подкасты'],
2026-11-22 17:49:23 +02:00
results: ['Podcast search results', 'Результаты поиска подкастов'],
noMatches: ['No matching podcasts.', 'Подходящих подкастов нет.'],
2026-11-22 16:05:37 +02:00
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', 'Слушать'],
2026-11-22 17:11:37 +02:00
open: ['Open', 'Открыть'],
2026-11-22 16:05:37 +02:00
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.', 'Публичных подкастов пока нет.'],
2026-11-22 17:11:37 +02:00
searchNetwork: ['Search podcasts', 'Поиск подкастов'],
2026-11-22 16:05:37 +02:00
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: [],
2026-11-22 17:11:37 +02:00
searched: false,
2026-11-22 16:05:37 +02:00
episodes: [],
hasMore: false,
selected: null,
2026-11-22 17:49:23 +02:00
selectedId: null,
loading: false,
adding: false,
failedArtwork: {},
descriptionExpanded: false,
_navigation: 0,
2026-11-22 16:05:37 +02:00
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');
2026-11-22 17:49:23 +02:00
this.mine = data.mine.map((pod) => ({ ...pod, subscribed: true }));
2026-11-22 16:05:37 +02:00
this.public = data.public;
2026-11-22 17:49:23 +02:00
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),
};
}
2026-11-22 16:05:37 +02:00
},
2026-11-22 17:49:23 +02:00
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;
2026-11-22 16:05:37 +02:00
Alpine.store('mobile')?.closeLibrary();
2026-11-22 17:49:23 +02:00
this.ensurePolling();
},
ensurePolling() {
2026-11-22 16:05:37 +02:00
if (!this.poller)
this.poller = setInterval(() => {
2026-11-22 17:49:23 +02:00
if (
['podcasts', 'podcast_detail'].includes(Alpine.store('library').view) &&
!this.busy &&
!this.loading
)
2026-11-22 16:05:37 +02:00
this.update().catch(() => {});
}, 5000);
2026-11-22 17:49:23 +02:00
},
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);
}
}
2026-11-22 16:05:37 +02:00
},
async update() {
await this.load();
2026-11-22 17:49:23 +02:00
if (this.selected?.subscribed) await this.loadEpisodes();
else this.episodes = [];
2026-11-22 16:05:37 +02:00
},
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]
2026-11-22 17:11:37 +02:00
: [...new Map([...data.episodes, ...old].map((e) => [e.id, e])).values()];
2026-11-22 16:05:37 +02:00
if (append || old.length <= 200) this.hasMore = !!data.has_more;
},
more() {
return this.task(async () => {
await this.loadEpisodes(true);
this.message = '';
});
},
2026-11-22 17:49:23 +02:00
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;
2026-11-22 16:05:37 +02:00
this.episodes = [];
this.hasMore = false;
this.filter = '';
this.season = '';
2026-11-22 17:49:23 +02:00
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);
}
}
2026-11-22 16:05:37 +02:00
},
2026-11-22 17:11:37 +02:00
openResult(pod) {
2026-11-22 17:49:23 +02:00
return this.open(pod);
},
subscribe(pod = this.selected) {
2026-11-22 17:11:37 +02:00
return this.task(async () => {
2026-11-22 17:49:23 +02:00
await this.api('add', { url: pod.url || pod.metadata.feed_url });
2026-11-22 17:11:37 +02:00
await this.load();
2026-11-22 17:49:23 +02:00
if (this.selectedId === pod.id) {
this.selected = this.mine.find((p) => p.id === pod.id) || {
...pod,
subscribed: true,
};
await this.loadEpisodes();
}
2026-11-22 17:11:37 +02:00
this.message = '';
});
},
2026-11-22 16:05:37 +02:00
add(url) {
this.task(async () => {
const result = await this.api('add', { url: url || this.url });
this.url = '';
await this.load();
2026-11-22 17:49:23 +02:00
this.adding = false;
if (result.id) await this.open(result.id);
2026-11-22 16:05:37 +02:00
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) {
2026-11-22 17:49:23 +02:00
++this._navigation;
this.loading = false;
2026-11-22 16:05:37 +02:00
this.selected = null;
2026-11-22 17:49:23 +02:00
this.selectedId = null;
2026-11-22 16:05:37 +02:00
this.episodes = [];
2026-11-22 17:49:23 +02:00
this.navigate('#podcasts', 'podcasts');
Alpine.store('library')._afterNavigation();
2026-11-22 16:05:37 +02:00
}
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() {
2026-11-22 17:49:23 +02:00
const query = this.query.trim();
2026-11-22 17:11:37 +02:00
return this.task(async () => {
const data = await this.api('search', { query });
2026-11-22 17:49:23 +02:00
if (this.query.trim() !== query) {
this.message = '';
return;
}
2026-11-22 16:05:37 +02:00
this.hits = data.hits;
2026-11-22 17:49:23 +02:00
this.searched = true;
2026-11-22 16:05:37 +02:00
this.message = this.text('done');
});
},
2026-11-22 17:49:23 +02:00
resetSearch() {
this.searched = false;
this.hits = [];
},
2026-11-22 16:05:37 +02:00
publicCards() {
2026-11-22 17:49:23 +02:00
return [
...new Map(
(this.searched ? this.hits : this.public).map((p) => [p.id, p]),
).values(),
];
2026-11-22 16:05:37 +02:00
},
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>