From d9bce4de0406114a7ec55f9b5bf586025771a8d5 Mon Sep 17 00:00:00 2001 From: 1xDed Date: Mon, 30 Nov 2026 19:19:51 +0300 Subject: [PATCH] feat: localize UI and improve playback - translate the interface into Russian - add picture-in-picture and video fit modes - derive skip segments from Jellyfin chapter markers - align player navigation and add a window drag region - keep audio playback alive across routes --- index.html | 4 +- src/components/addServerDialog/index.tsx | 14 +- src/components/albumMusicTrack/index.tsx | 4 +- src/components/alphaSelector/index.tsx | 8 +- src/components/appBar/appBar.scss | 4 +- src/components/appBar/appBar.tsx | 26 ++-- src/components/appBar/backOnly.tsx | 2 +- src/components/appBar/navigationDrawer.tsx | 20 +-- src/components/buttons/backButton.tsx | 4 +- src/components/buttons/castButton.tsx | 4 +- src/components/buttons/instantMixButton.tsx | 12 +- src/components/buttons/likeButton.tsx | 2 +- src/components/buttons/markPlayedButton.tsx | 2 +- src/components/buttons/playButton.tsx | 68 +++++---- src/components/buttons/queueButton.tsx | 4 +- src/components/buttons/quickConnectButton.tsx | 27 ++-- src/components/carousel/index.tsx | 10 +- src/components/carouselSlide/index.tsx | 8 +- src/components/filtersDialog/index.tsx | 54 ++++--- src/components/followMe/index.tsx | 18 +-- src/components/itemDetail/castAndCrew.tsx | 10 +- src/components/itemDetail/mediaTracks.tsx | 8 +- src/components/itemDetail/similarItems.tsx | 6 +- .../itemDetail/views/defaultView.tsx | 2 +- .../itemDetail/views/personView.tsx | 8 +- .../itemDetail/views/seriesView.tsx | 4 +- src/components/layouts/artist/artistAlbum.tsx | 6 +- .../homeSection/latestMediaSection.tsx | 6 +- src/components/libraryHeader/index.tsx | 24 ++-- src/components/libraryItemsGrid/index.tsx | 6 +- src/components/loginShell/index.tsx | 2 +- src/components/loginShell/profileAvatar.tsx | 2 +- src/components/musicTrack/index.tsx | 4 +- .../notices/emptyNotice/emptyNotice.tsx | 2 +- .../notices/errorNotice/errorNotice.tsx | 4 +- src/components/outroCard/index.tsx | 6 +- .../audioPlayer/components/DeviceMenu.tsx | 22 +-- .../audioPlayer/components/LyricsPanel.tsx | 6 +- .../audioPlayer/components/PlayerActions.tsx | 8 +- .../audioPlayer/components/PlayerInfo.tsx | 2 +- .../audioPlayer/components/PlayerProgress.tsx | 4 +- .../audioPlayer/components/StatsPanel.tsx | 32 ++--- src/components/playback/audioPlayer/index.tsx | 134 ++++++++++-------- .../playback/videoPlayer/ErrorDisplay.tsx | 8 +- .../playback/videoPlayer/StatsForNerds.tsx | 30 ++-- .../buttons/PictureInPictureButton.tsx | 94 ++++++++++++ .../videoPlayer/buttons/SkipSegmentButton.tsx | 2 +- .../videoPlayer/buttons/VideoFitButton.tsx | 93 ++++++++++++ .../playback/videoPlayer/controls.scss | 47 ++++++ .../playback/videoPlayer/controls.tsx | 113 +++++++++++++-- .../playback/videoPlayer/settingsMenu.tsx | 12 +- .../playback/videoPlayer/upNextFlyout.tsx | 6 +- src/components/qrCode/index.tsx | 2 +- src/components/queue/queueRow.tsx | 6 +- src/components/queue/queueView.tsx | 34 ++--- src/components/quickConnectApproval/index.tsx | 26 ++-- src/components/realtime/index.tsx | 4 +- src/components/remoteControl/index.tsx | 42 +++--- src/components/search/index.tsx | 14 +- src/components/search/item.tsx | 19 ++- src/components/settingOptionSelect/index.tsx | 2 +- src/components/share/index.tsx | 16 +-- src/components/showMoreText/index.tsx | 2 +- src/components/syncPlay/index.tsx | 54 +++---- src/components/updater/index.tsx | 18 +-- src/components/userAvatarMenu/index.tsx | 12 +- src/components/windowControls/index.tsx | 12 +- src/routes/_api/favorite/index.tsx | 26 ++-- src/routes/_api/home/home.scss | 4 +- src/routes/_api/home/homeHeader.tsx | 16 +-- src/routes/_api/home/index.tsx | 28 ++-- src/routes/_api/library/$id.tsx | 2 +- src/routes/_api/login/$userId.$userName.tsx | 24 ++-- src/routes/_api/login/list.tsx | 14 +- src/routes/_api/login/manual.tsx | 26 ++-- src/routes/_api/music/album/$id.tsx | 20 +-- src/routes/_api/music/artist/$id.tsx | 18 +-- src/routes/_api/music/playlist/$id.tsx | 14 +- src/routes/_api/player/audio.tsx | 24 ++-- src/routes/_api/player/index.tsx | 45 +++++- src/routes/_api/player/photos.tsx | 8 +- src/routes/_api/search/index.tsx | 40 +++--- src/routes/_api/settings.tsx | 20 +-- src/routes/_api/settings/about.tsx | 12 +- .../_api/settings/changeServer/index.tsx | 28 ++-- src/routes/_api/settings/preferences.tsx | 32 ++--- src/routes/error/$code.tsx | 10 +- src/routes/setup/server.add.tsx | 12 +- src/routes/setup/server.error.tsx | 6 +- src/routes/setup/server.list.tsx | 8 +- src/utils/constants/library.ts | 58 ++++---- src/utils/date/time.ts | 22 +-- src/utils/methods/mediaSegments.ts | 116 +++++++++++++++ src/utils/methods/pictureInPicture.ts | 102 +++++++++++++ src/utils/methods/startPlayback.ts | 2 +- src/utils/methods/syncPlay.ts | 14 +- src/utils/storage/player.ts | 11 ++ src/utils/storage/settings.ts | 4 +- src/utils/store/playback.ts | 32 ++++- src/utils/types/videoFitMode.ts | 1 + 100 files changed, 1364 insertions(+), 706 deletions(-) create mode 100644 src/components/playback/videoPlayer/buttons/PictureInPictureButton.tsx create mode 100644 src/components/playback/videoPlayer/buttons/VideoFitButton.tsx create mode 100644 src/utils/methods/mediaSegments.ts create mode 100644 src/utils/methods/pictureInPicture.ts create mode 100644 src/utils/types/videoFitMode.ts diff --git a/index.html b/index.html index 2077138..deef253 100644 --- a/index.html +++ b/index.html @@ -1,5 +1,5 @@ - + @@ -57,7 +57,7 @@ -
+
{ console.error(err); enqueueSnackbar(`${err}`, { variant: "error" }); - enqueueSnackbar("Something went wrong", { variant: "error" }); + enqueueSnackbar("Что-то пошло не так", { variant: "error" }); }, onSettled: async (bestServer) => { if (!bestServer) { - enqueueSnackbar("Provided server address is not a Jellyfin server.", { + enqueueSnackbar("Указанный адрес не является сервером Jellyfin.", { variant: "error", }); } @@ -112,7 +112,7 @@ export default function AddServerDialog(props: AddServerDialogProps) { textAlign: "center", }} > - Connect to Server + Подключиться к серверу - Enter your Jellyfin server address to continue + Введите адрес сервера Jellyfin, чтобы продолжить @@ -174,7 +174,7 @@ export default function AddServerDialog(props: AddServerDialogProps) { variant="text" sx={{ borderRadius: 2 }} > - Cancel + Отмена - Connect + Подключиться diff --git a/src/components/albumMusicTrack/index.tsx b/src/components/albumMusicTrack/index.tsx index 46f3323..4f75aec 100644 --- a/src/components/albumMusicTrack/index.tsx +++ b/src/components/albumMusicTrack/index.tsx @@ -45,7 +45,7 @@ export default function AlbumMusicTrack(props: AlbumMusicTrackProps) { ) => { if (!user?.Id || !api) { console.error("User not logged in"); - enqueueSnackbar("You need to be logged in to play music", { + enqueueSnackbar("Войдите, чтобы слушать музыку", { variant: "error", }); return; @@ -96,7 +96,7 @@ export default function AlbumMusicTrack(props: AlbumMusicTrackProps) { fontWeight: 300, }} > - {track.HasLyrics && lyrics} + {track.HasLyrics && Текст песни} {track.Artists?.join(", ")}
diff --git a/src/components/alphaSelector/index.tsx b/src/components/alphaSelector/index.tsx index b7cf65e..fe11695 100644 --- a/src/components/alphaSelector/index.tsx +++ b/src/components/alphaSelector/index.tsx @@ -19,11 +19,11 @@ export const AlphaSelector = React.memo(function AlphaSelector() { const arr = Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i), ); - return ["All", ...arr]; + return ["Все", ...arr]; }, []); const handleSelect = (letter: string) => { - const value = letter === "All" ? undefined : letter; + const value = letter === "Все" ? undefined : letter; if (currentLibraryId) updateLibrary(currentLibraryId, { nameStartsWith: value }); }; @@ -31,13 +31,13 @@ export const AlphaSelector = React.memo(function AlphaSelector() { return (
{letters.map((l) => { - const active = (nameStartsWith || "All") === l; + const active = (nameStartsWith || "Все") === l; return (
@@ -403,15 +417,7 @@ const PlayButton = ({ color="white" size={size} > - {item.UserData?.PlaybackPositionTicks - ? "Continue Watching" - : item?.Type === "MusicAlbum" || - item?.Type === "Audio" || - item?.Type === "AudioBook" || - item?.Type === "Playlist" || - audio - ? "Play Now" - : "Watch Now"} + {playLabel} )}
diff --git a/src/components/buttons/queueButton.tsx b/src/components/buttons/queueButton.tsx index 32eb9c5..70bb83b 100644 --- a/src/components/buttons/queueButton.tsx +++ b/src/components/buttons/queueButton.tsx @@ -10,8 +10,8 @@ const QueueButton = () => { return ( <> - - setOpen(true)} aria-label="Open queue"> + + setOpen(true)} aria-label="Открыть очередь"> queue_music diff --git a/src/components/buttons/quickConnectButton.tsx b/src/components/buttons/quickConnectButton.tsx index d422aa1..3548b44 100644 --- a/src/components/buttons/quickConnectButton.tsx +++ b/src/components/buttons/quickConnectButton.tsx @@ -86,7 +86,7 @@ const QuickConnectButton = (props: LoadingButtonProps) => { const { AccessToken, User } = result?.data ?? {}; if (api && AccessToken && User?.Name && User.Id) { setCheckForQuickConnect(false); - enqueueSnackbar(`Logged in as ${User.Name}!`, { + enqueueSnackbar(`Вы вошли как ${User.Name}!`, { variant: "success", }); createApi(api.basePath, AccessToken); @@ -99,7 +99,7 @@ const QuickConnectButton = (props: LoadingButtonProps) => { } }, onError: (error) => { - enqueueSnackbar("Error authenticating user.", { variant: "error" }); + enqueueSnackbar("Не удалось войти.", { variant: "error" }); console.error(error); }, }); @@ -126,7 +126,7 @@ const QuickConnectButton = (props: LoadingButtonProps) => { mutationKey: ["quick-connect-button", "initiate-connection"], mutationFn: async () => { if (!quickConnectEnabled.data?.data) { - enqueueSnackbar("Quick Connect is not enabled on server.", { + enqueueSnackbar("Quick Connect не включён на сервере.", { variant: "error", }); } @@ -142,7 +142,7 @@ const QuickConnectButton = (props: LoadingButtonProps) => { setCheckForQuickConnect(true); }, onError: (error) => { - enqueueSnackbar("Error initiating Quick Connect.", { variant: "error" }); + enqueueSnackbar("Не удалось запустить Quick Connect.", { variant: "error" }); console.error(error); }, }); @@ -182,8 +182,8 @@ const QuickConnectButton = (props: LoadingButtonProps) => { onClick={() => initQuickConnect.mutate()} > {quickConnectEnabled.data?.data - ? "Use Quick Connect" - : "Quick Connect Disabled"} + ? "Войти через Quick Connect" + : "Quick Connect недоступен"} { mb: 2, }} > - Quick Connect Code: + Код Quick Connect: - Use this code in the Quick Connect tab in your server to login. + Введите этот код в разделе Quick Connect на сервере, чтобы войти.
- + { quickConnectCode && (await writeText(quickConnectCode)); - enqueueSnackbar("Quick Connect Code copied!", { + enqueueSnackbar("Код Quick Connect скопирован!", { variant: "info", key: "copiedText", }); @@ -252,8 +252,7 @@ const QuickConnectButton = (props: LoadingButtonProps) => { variant="body2" sx={{ mt: 2, opacity: 0.75, textAlign: "center" }} > - Or scan this code with Blink on your phone to approve the - login. + Или отсканируйте код в Blink на телефоне, чтобы подтвердить вход.
{ onChange={(e) => setRememberUser(e.target.checked)} /> } - label="Remember device" + label="Запомнить устройство" />
diff --git a/src/components/carousel/index.tsx b/src/components/carousel/index.tsx index 1918217..69285a0 100644 --- a/src/components/carousel/index.tsx +++ b/src/components/carousel/index.tsx @@ -37,7 +37,7 @@ const trendingImageUrl = ( const trendingLabel = (item: BaseItemDto): string => { const genre = item.Genres?.[0]; if (genre) return genre.charAt(0).toUpperCase() + genre.slice(1); - return item.Type === BaseItemKind.Series ? "Series" : "Movie"; + return item.Type === BaseItemKind.Series ? "Сериал" : "Фильм"; }; const Carousel = ({ @@ -97,7 +97,7 @@ const Carousel = ({
setIsPaused(true)} onMouseLeave={() => setIsPaused(false)} > @@ -108,7 +108,7 @@ const Carousel = ({ type="button" className="cinema-arrow right" onClick={next} - aria-label="Next" + aria-label="Далее" > chevron_right @@ -116,7 +116,7 @@ const Carousel = ({
-

Trending now

+

В тренде

{total > 1 && (
{content.map((item, index) => ( @@ -143,7 +143,7 @@ const Carousel = ({ index === currentSlide ? "active" : "" }`} onClick={() => goTo(index)} - aria-label={item.Name ?? "Featured item"} + aria-label={item.Name ?? "Рекомендуемое"} > {imageUrl ? ( { > {item.UserData?.PlaybackPositionTicks - ? "Continue watching" + ? "Продолжить просмотр" : item.Type === BaseItemKind.Series - ? "New series" - : "New movie"} + ? "Новый сериал" + : "Новый фильм"} { } onClick={handleMoreInfo} > - More info + Подробнее = { - isPlayed: "Played", - isUnPlayed: "Unplayed", - isResumable: "Resumable", - isFavorite: "Favorite", - hasSubtitles: "Has Subtitles", - hasTrailer: "Has Trailer", - hasSpecialFeature: "Special Feature", - hasThemeSong: "Theme Song", - hasThemeVideo: "Theme Video", + isPlayed: "Просмотрено", + isUnPlayed: "Не просмотрено", + isResumable: "Можно продолжить", + isFavorite: "Избранное", + hasSubtitles: "Есть субтитры", + hasTrailer: "Есть трейлер", + hasSpecialFeature: "Дополнительные материалы", + hasThemeSong: "Тематическая песня", + hasThemeVideo: "Тематическое видео", isSD: "SD", isHD: "HD", is4K: "4K", @@ -173,7 +173,7 @@ export const FiltersDialog: React.FC = React.memo( paper: { className: "glass-dialog-paper" }, }} > - Filters + Фильтры = React.memo( expand_more } > - General + Общие @@ -252,7 +252,7 @@ export const FiltersDialog: React.FC = React.memo( } > - Video features + Видео @@ -306,7 +306,7 @@ export const FiltersDialog: React.FC = React.memo( } > - Resolution + Разрешение @@ -354,7 +354,7 @@ export const FiltersDialog: React.FC = React.memo( } > - Media type + Тип медиа @@ -374,7 +374,17 @@ export const FiltersDialog: React.FC = React.memo( size="small" /> } - label={k} + label={ + k === "VideoFile" + ? "Видеофайл" + : k === "BluRay" + ? "Blu-ray" + : k === "Dvd" + ? "DVD" + : k === "Iso" + ? "ISO" + : k + } /> ), )} @@ -405,7 +415,7 @@ export const FiltersDialog: React.FC = React.memo( } > - Genres + Жанры @@ -440,7 +450,7 @@ export const FiltersDialog: React.FC = React.memo( color="inherit" disabled={Object.keys(localFilters).length === 0} > - Clear + Сбросить - + @@ -488,11 +498,11 @@ export const FiltersDialogTrigger: React.FC = () => { return ( <> setOpen(true)} - aria-label="Open filters dialog" + aria-label="Открыть фильтры" > { }; const deviceLabel = (session: SessionInfoDto) => - session.DeviceName || session.Client || "another device"; + session.DeviceName || session.Client || "другое устройство"; const posterId = (item: BaseItemDto) => item.ImageTags?.Primary ? item.Id : (item.SeriesId ?? item.Id); @@ -167,13 +167,13 @@ const FollowMe = () => { if (kind === "video") navigate({ to: "/player" }); if (kind === "audio") navigate({ to: "/player/audio" }); if (kind !== "none") { - enqueueSnackbar(`Continuing from ${deviceLabel(candidate.session)}`, { + enqueueSnackbar(`Продолжаем с ${deviceLabel(candidate.session)}`, { variant: "success", }); } } catch (error) { console.error("Follow-me transfer failed", error); - enqueueSnackbar("Could not continue playback here", { + enqueueSnackbar("Не удалось продолжить воспроизведение здесь", { variant: "error", }); } finally { @@ -230,10 +230,10 @@ const FollowMe = () => { variant="overline" sx={{ lineHeight: 1.2, opacity: 0.65, letterSpacing: 0.8 }} > - {paused ? "Paused on" : "Playing on"} {deviceLabel(session)} + {paused ? "Пауза на" : "Идёт на"} {deviceLabel(session)} - {item.SeriesName ?? item.Name ?? "Continue watching"} + {item.SeriesName ?? item.Name ?? "Продолжить просмотр"} {item.SeriesName && item.Name ? `${item.Name} · ` : ""} @@ -247,21 +247,21 @@ const FollowMe = () => { disabled={transferring} sx={{ textTransform: "none", borderRadius: "999px" }} > - {transferring ? "Starting…" : "Continue here"} + {transferring ? "Запуск…" : "Продолжить здесь"} - + dismiss(candidate.key)} sx={{ alignSelf: "flex-start", opacity: 0.55 }} > diff --git a/src/components/itemDetail/castAndCrew.tsx b/src/components/itemDetail/castAndCrew.tsx index ae48cb7..4bac9d3 100644 --- a/src/components/itemDetail/castAndCrew.tsx +++ b/src/components/itemDetail/castAndCrew.tsx @@ -7,10 +7,10 @@ import { getTypeIcon } from "@/components/utils/iconsCollection"; import getImageUrlsApi from "@/utils/methods/getImageUrlsApi"; const groups = [ - { type: "Actor", title: "Actors" }, - { type: "Writer", title: "Writers" }, - { type: "Director", title: "Directors" }, - { type: "Producer", title: "Producers" }, + { type: "Actor", title: "Актёры" }, + { type: "Writer", title: "Сценаристы" }, + { type: "Director", title: "Режиссёры" }, + { type: "Producer", title: "Продюсеры" }, ] as const; type CastAndCrewProps = { @@ -33,7 +33,7 @@ const CastAndCrew = ({ people, api }: CastAndCrewProps) => { return (
- Cast & Crew + Актёры и команда {grouped.map( (group) => diff --git a/src/components/itemDetail/mediaTracks.tsx b/src/components/itemDetail/mediaTracks.tsx index 07c5ff3..fe5b806 100644 --- a/src/components/itemDetail/mediaTracks.tsx +++ b/src/components/itemDetail/mediaTracks.tsx @@ -118,7 +118,7 @@ export const TrackSelectors = ({ <> {tracks.video.length > 0 && ( 0 && ( 0 && ( setSelection({ subtitle: Number(e.target.value) })} > - No Subtitle + Без субтитров {tracks.subtitle.map((track) => ( diff --git a/src/components/itemDetail/similarItems.tsx b/src/components/itemDetail/similarItems.tsx index 3eab410..50d1af7 100644 --- a/src/components/itemDetail/similarItems.tsx +++ b/src/components/itemDetail/similarItems.tsx @@ -19,8 +19,8 @@ export const getItemCardCaption = (item: BaseItemDto) => { } if (item.Type === BaseItemKind.Series) { const end = item.EndDate - ? new Date(item.EndDate).toLocaleString([], { year: "numeric" }) - : "Present"; + ? new Date(item.EndDate).toLocaleString("ru-RU", { year: "numeric" }) + : "н.в."; return `${item.ProductionYear} - ${end}`; } return item.ProductionYear; @@ -38,7 +38,7 @@ const SimilarItems = ({ item }: { item: BaseItemDto }) => { return ( diff --git a/src/components/itemDetail/views/defaultView.tsx b/src/components/itemDetail/views/defaultView.tsx index cb12b7f..6019a90 100644 --- a/src/components/itemDetail/views/defaultView.tsx +++ b/src/components/itemDetail/views/defaultView.tsx @@ -24,7 +24,7 @@ const UpcomingEpisodes = ({ episode }: { episode: BaseItemDto }) => { if (!upcomingEpisodes.data?.Items?.length) return null; return ( - + {upcomingEpisodes.data.Items.map((upcoming) => ( { <> {item.PremiereDate && (
- Birth + Дата рождения - {new Date(item.PremiereDate).toDateString()} + {new Date(item.PremiereDate).toLocaleDateString("ru-RU")}
)} {item.EndDate && (
- Death + Дата смерти - {new Date(item.EndDate).toDateString()} + {new Date(item.EndDate).toLocaleDateString("ru-RU")}
)} diff --git a/src/components/itemDetail/views/seriesView.tsx b/src/components/itemDetail/views/seriesView.tsx index 7928a67..ddc5803 100644 --- a/src/components/itemDetail/views/seriesView.tsx +++ b/src/components/itemDetail/views/seriesView.tsx @@ -36,7 +36,7 @@ import ItemDetailLayout, { ExternalLinks } from "../itemDetailLayout"; import SimilarItems from "../similarItems"; const getEpisodeDateString = (date: Date) => - new Intl.DateTimeFormat(navigator.language ?? "en-US", { + new Intl.DateTimeFormat("ru-RU", { dateStyle: "full", }).format(date); @@ -339,7 +339,7 @@ const SeriesView = ({ item }: { item: BaseItemDto }) => { {(specialFeatures.data?.length ?? 0) > 0 && ( diff --git a/src/components/layouts/artist/artistAlbum.tsx b/src/components/layouts/artist/artistAlbum.tsx index 0c41adf..4a59ef4 100644 --- a/src/components/layouts/artist/artistAlbum.tsx +++ b/src/components/layouts/artist/artistAlbum.tsx @@ -55,7 +55,7 @@ export const ArtistAlbum = ({ user, album, boxProps }: ArtistAlbumProps) => { {!!album.ImageTags?.Primary && (
{album.Name {
tag - Title - Duration + Название + Длительность
{albumTracks.data?.Items?.map((track, index) => ( {
menu
{ >
{libraryName} @@ -324,7 +324,7 @@ export const LibraryHeader = () => { > - View + Вид {compatibleViews.map((v) => ( @@ -335,7 +335,7 @@ export const LibraryHeader = () => {
{ > - Sort By + Сортировка {SORT_BY_OPTIONS.map((option) => { @@ -403,16 +403,16 @@ export const LibraryHeader = () => {
search
favorite
diff --git a/src/components/libraryItemsGrid/index.tsx b/src/components/libraryItemsGrid/index.tsx index 8bdfab1..7e82f56 100644 --- a/src/components/libraryItemsGrid/index.tsx +++ b/src/components/libraryItemsGrid/index.tsx @@ -288,9 +288,9 @@ const LibraryItemsGrid = () => { > sentiment_dissatisfied
-
No items to show
+
Нет элементов для отображения
- Try adjusting filters, sort, or the A–Z selector. + Попробуйте изменить фильтры, сортировку или выбор по алфавиту.
@@ -357,7 +357,7 @@ const LibraryItemsGrid = () => { year: "numeric", }, ) - : "Present" + : "н.в." }` : item?.ProductionYear } diff --git a/src/components/loginShell/index.tsx b/src/components/loginShell/index.tsx index bbb8238..7dba0b8 100644 --- a/src/components/loginShell/index.tsx +++ b/src/components/loginShell/index.tsx @@ -60,7 +60,7 @@ const LoginShell = ({ {serverName ?? serverHost} - Change + Сменить
)} diff --git a/src/components/loginShell/profileAvatar.tsx b/src/components/loginShell/profileAvatar.tsx index 76ba9d2..53fdb4d 100644 --- a/src/components/loginShell/profileAvatar.tsx +++ b/src/components/loginShell/profileAvatar.tsx @@ -47,7 +47,7 @@ export const ProfileAvatar = ({ )} {locked && ( - + lock )} diff --git a/src/components/musicTrack/index.tsx b/src/components/musicTrack/index.tsx index cf7c85d..540ea77 100644 --- a/src/components/musicTrack/index.tsx +++ b/src/components/musicTrack/index.tsx @@ -46,7 +46,7 @@ const MusicTrack = ({
{item.Name )} diff --git a/src/components/notices/emptyNotice/emptyNotice.tsx b/src/components/notices/emptyNotice/emptyNotice.tsx index 6515e1a..1a0a6f2 100644 --- a/src/components/notices/emptyNotice/emptyNotice.tsx +++ b/src/components/notices/emptyNotice/emptyNotice.tsx @@ -34,7 +34,7 @@ export const EmptyNotice = ({ extraMsg }: { extraMsg?: string }) => { fontWeight: 300, }} > - No results found + Ничего не найдено { fontWeight: 300, }} > - Something went wrong. + Что-то пошло не так. { {normalizedError ? normalizedError.stack || `${normalizedError.name}: ${normalizedError.message}` - : "Unknown error"} + : "Неизвестная ошибка"} ); diff --git a/src/components/outroCard/index.tsx b/src/components/outroCard/index.tsx index 6b0a222..00fa119 100644 --- a/src/components/outroCard/index.tsx +++ b/src/components/outroCard/index.tsx @@ -26,7 +26,7 @@ const OutroCard = (props: { handleShowCredits: () => void }) => { if (!item || !item.Type) return null; return (
- Up Next + Далее
{item?.ImageTags?.Primary ? ( void }) => {
} > - Play Now + Смотреть
diff --git a/src/components/playback/audioPlayer/components/DeviceMenu.tsx b/src/components/playback/audioPlayer/components/DeviceMenu.tsx index a96b7ce..6882c2f 100644 --- a/src/components/playback/audioPlayer/components/DeviceMenu.tsx +++ b/src/components/playback/audioPlayer/components/DeviceMenu.tsx @@ -43,9 +43,9 @@ const DeviceMenu = ({ return ( <> - + setAnchor(event.currentTarget)} > devices @@ -68,16 +68,16 @@ const DeviceMenu = ({ computer
{sessions.length === 0 ? ( - + ) : ( sessions.map((session) => ( @@ -95,11 +95,11 @@ const DeviceMenu = ({ @@ -115,7 +115,7 @@ const DeviceMenu = ({ settings_remote - + sync { if (lyrics.isLoading) { return (
- Loading lyrics... + Загрузка текста...
); } @@ -68,7 +68,7 @@ const LyricsPanel = ({ item, api, currentTime, onSeek }: LyricsPanelProps) => { if (lyrics.isError || !lyrics.data || !lyrics.data.Lyrics?.length) { return (
- No lyrics available + Текст недоступен
); } @@ -119,7 +119,7 @@ const LyricsPanel = ({ item, api, currentTime, onSeek }: LyricsPanelProps) => { {!hasSyncedLyrics && (
info - Synced lyrics not available + Синхронизированный текст недоступен
)}
diff --git a/src/components/playback/audioPlayer/components/PlayerActions.tsx b/src/components/playback/audioPlayer/components/PlayerActions.tsx index 20e5fd6..9d309b7 100644 --- a/src/components/playback/audioPlayer/components/PlayerActions.tsx +++ b/src/components/playback/audioPlayer/components/PlayerActions.tsx @@ -42,13 +42,13 @@ const PlayerActions = ({ />}
{children}
- - + + open_in_full - - + + close diff --git a/src/components/playback/audioPlayer/components/PlayerInfo.tsx b/src/components/playback/audioPlayer/components/PlayerInfo.tsx index b881a4b..e5bd5c5 100644 --- a/src/components/playback/audioPlayer/components/PlayerInfo.tsx +++ b/src/components/playback/audioPlayer/components/PlayerInfo.tsx @@ -36,7 +36,7 @@ const PlayerInfo = ({ item, api, onOpen }: PlayerInfoProps) => { type="button" className="audio-player-image-container" onClick={onOpen} - aria-label="Open player" + aria-label="Открыть плеер" > music_note diff --git a/src/components/playback/audioPlayer/components/PlayerProgress.tsx b/src/components/playback/audioPlayer/components/PlayerProgress.tsx index a29b2a5..26b9e97 100644 --- a/src/components/playback/audioPlayer/components/PlayerProgress.tsx +++ b/src/components/playback/audioPlayer/components/PlayerProgress.tsx @@ -56,7 +56,7 @@ const PlayerProgress = ({ max={duration} onChange={handleChange} onChangeCommitted={handleChangeCommitted} - aria-label="Seek" + aria-label="Перемотка" /> ); } @@ -71,7 +71,7 @@ const PlayerProgress = ({ max={duration} onChange={handleChange} onChangeCommitted={handleChangeCommitted} - aria-label="Seek" + aria-label="Перемотка" />
{getRuntimeMusic(sliderValue)} diff --git a/src/components/playback/audioPlayer/components/StatsPanel.tsx b/src/components/playback/audioPlayer/components/StatsPanel.tsx index dbc90b2..27ea390 100644 --- a/src/components/playback/audioPlayer/components/StatsPanel.tsx +++ b/src/components/playback/audioPlayer/components/StatsPanel.tsx @@ -64,7 +64,7 @@ const StatsPanel: React.FC = ({ item, audioRef }) => { return ( - Stats for Nerds + Статистика = ({ item, audioRef }) => { variant="subtitle2" sx={{ mb: 1, opacity: 0.5, textTransform: "uppercase" }} > - Media Source + Источник медиа - + = ({ item, audioRef }) => { } /> - + - Audio Stream + Аудиопоток - - + + - - + + @@ -125,11 +125,11 @@ const StatsPanel: React.FC = ({ item, audioRef }) => { variant="subtitle2" sx={{ mb: 1, opacity: 0.5, textTransform: "uppercase" }} > - Player + Плеер - + = ({ item, audioRef }) => { } /> diff --git a/src/components/playback/audioPlayer/index.tsx b/src/components/playback/audioPlayer/index.tsx index 43349a0..2500525 100644 --- a/src/components/playback/audioPlayer/index.tsx +++ b/src/components/playback/audioPlayer/index.tsx @@ -139,12 +139,12 @@ const AudioPlayer = () => { : (activeItem?.AlbumArtists ?? []); const artistNames = artists.map((artist) => artist.Name).filter(Boolean); const remoteDevice = remote - ? remote.DeviceName || remote.Client || "another device" + ? remote.DeviceName || remote.Client || "другое устройство" : undefined; const subtitle = remote ? artistNames.length > 0 ? `${artistNames.join(", ")} · ${remoteDevice}` - : `Playing on ${remoteDevice}` + : `Идёт на ${remoteDevice}` : artistNames.join(", ") || activeItem?.Album || ""; const coverUrl = api && activeItem?.Id @@ -231,9 +231,9 @@ const AudioPlayer = () => { }) : undefined; navigator.mediaSession.metadata = new MediaMetadata({ - title: item.Name ?? "Unknown Title", - artist: item.Artists?.join(", ") ?? "Unknown Artist", - album: item.Album ?? "Unknown Album", + title: item.Name ?? "Неизвестное название", + artist: item.Artists?.join(", ") ?? "Неизвестный исполнитель", + album: item.Album ?? "Неизвестный альбом", artwork: imageUrl ? [{ src: imageUrl, sizes: "512x512", type: "image/jpeg" }] : [], @@ -368,8 +368,8 @@ const AudioPlayer = () => { }); await sessions.refetch(); } catch (error) { - console.error("Remote command failed", error); - enqueueSnackbar("Remote command failed", { variant: "error" }); + console.error("Команда не выполнена", error); + enqueueSnackbar("Команда не выполнена", { variant: "error" }); } }; @@ -385,7 +385,7 @@ const AudioPlayer = () => { if (kind === "video") navigate({ to: "/player" }); } catch (error) { console.error("Transfer failed", error); - enqueueSnackbar("Could not transfer playback", { variant: "error" }); + enqueueSnackbar("Не удалось перенести воспроизведение", { variant: "error" }); } }; @@ -432,8 +432,8 @@ const AudioPlayer = () => { setSelectedRemoteId(session.Id); await sessions.refetch(); } catch (error) { - console.error("Could not switch device", error); - enqueueSnackbar("Could not switch device", { variant: "error" }); + console.error("Не удалось переключить устройство", error); + enqueueSnackbar("Не удалось переключить устройство", { variant: "error" }); } }; @@ -462,7 +462,7 @@ const AudioPlayer = () => { await sessions.refetch(); } catch (error) { console.error("Remote general command failed", error); - enqueueSnackbar("Remote command failed", { variant: "error" }); + enqueueSnackbar("Команда не выполнена", { variant: "error" }); } }; @@ -512,13 +512,13 @@ const AudioPlayer = () => { try { const { count } = await startInstantMix(api, user.Id, activeItem); if (count === 0) { - enqueueSnackbar("No tracks found for Instant Mix", { + enqueueSnackbar("Нет треков для микса", { variant: "warning", }); } } catch (error) { console.error(error); - enqueueSnackbar("Could not start Instant Mix", { variant: "error" }); + enqueueSnackbar("Не удалось запустить микс", { variant: "error" }); } }; @@ -534,11 +534,34 @@ const AudioPlayer = () => { }); }; - if (!barVisible || isFullPlayer) { + const audioElement = display ? ( +
@@ -585,7 +608,7 @@ const AudioPlayer = () => {
- + { shuffle - + skip_previous - + remote ? remoteCommand(PlaystateCommand.PlayPause) @@ -620,8 +643,8 @@ const AudioPlayer = () => { - - + + skip_next @@ -629,15 +652,15 @@ const AudioPlayer = () => { title={ remote ? remoteRepeat === "RepeatNone" - ? "Repeat off" + ? "Повтор выкл." : remoteRepeat === "RepeatAll" - ? "Repeat all" - : "Repeat one" + ? "Повтор всех" + : "Повтор одного" : repeatMode === "off" - ? "Repeat off" + ? "Повтор выкл." : repeatMode === "all" - ? "Repeat all" - : "Repeat one" + ? "Повтор всех" + : "Повтор одного" } > {
{remote && ( - + @@ -680,7 +703,7 @@ const AudioPlayer = () => { )} {!remote && } - + {remote @@ -700,7 +723,7 @@ const AudioPlayer = () => { min={0} max={1} step={0.01} - aria-label="Volume" + aria-label="Громкость" onChange={(_, value) => { const next = Array.isArray(value) ? value[0] : value; if (remote) { @@ -730,7 +753,7 @@ const AudioPlayer = () => { canSync={canSync} onToggleSync={toggleSync} /> - + open_in_full @@ -747,7 +770,7 @@ const AudioPlayer = () => { radio - + {remote ? ( { system_update_alt - + ) : ( cast - + )} { settings_remote - + { stop - + - {display && ( -
); diff --git a/src/components/playback/videoPlayer/buttons/PictureInPictureButton.tsx b/src/components/playback/videoPlayer/buttons/PictureInPictureButton.tsx new file mode 100644 index 0000000..f838932 --- /dev/null +++ b/src/components/playback/videoPlayer/buttons/PictureInPictureButton.tsx @@ -0,0 +1,94 @@ +import { IconButton, Tooltip } from "@mui/material"; +import { useSnackbar } from "notistack"; +import React, { useEffect, useState } from "react"; +import { + getPlayerVideoElement, + isPictureInPictureActive, + supportsPictureInPicture, + togglePictureInPicture, +} from "@/utils/methods/pictureInPicture"; +import { usePlaybackStore } from "@/utils/store/playback"; + +const PictureInPictureButton = () => { + const playsessionId = usePlaybackStore((state) => state.playsessionId); + const { enqueueSnackbar } = useSnackbar(); + const [supported, setSupported] = useState(() => supportsPictureInPicture()); + const [active, setActive] = useState(false); + const [busy, setBusy] = useState(false); + + useEffect(() => { + const update = () => { + const currentVideo = getPlayerVideoElement(); + if (currentVideo) { + setSupported(supportsPictureInPicture(currentVideo)); + } + setActive(currentVideo ? isPictureInPictureActive(currentVideo) : false); + }; + + const video = getPlayerVideoElement(); + if (video) { + setSupported(supportsPictureInPicture(video)); + setActive(isPictureInPictureActive(video)); + } + + document.addEventListener("enterpictureinpicture", update, true); + document.addEventListener("leavepictureinpicture", update, true); + document.addEventListener("webkitpresentationmodechanged", update, true); + const interval = window.setInterval(update, 1000); + + return () => { + window.clearInterval(interval); + document.removeEventListener("enterpictureinpicture", update, true); + document.removeEventListener("leavepictureinpicture", update, true); + document.removeEventListener( + "webkitpresentationmodechanged", + update, + true, + ); + }; + }, [playsessionId]); + + if (!supported) return null; + + const label = active ? "Выйти из картинки в картинке" : "Картинка в картинке"; + + const handleClick = async () => { + const video = getPlayerVideoElement(); + if (!video) { + enqueueSnackbar("Видео ещё не готово", { variant: "info" }); + return; + } + + try { + setBusy(true); + await togglePictureInPicture(video); + setActive(isPictureInPictureActive(video)); + } catch (error) { + console.error("Picture-in-picture failed", error); + enqueueSnackbar("Не удалось включить картинку в картинке", { + variant: "error", + }); + } finally { + setBusy(false); + } + }; + + return ( + + + + + {active ? "picture_in_picture" : "picture_in_picture_alt"} + + + + + ); +}; + +export default PictureInPictureButton; diff --git a/src/components/playback/videoPlayer/buttons/SkipSegmentButton.tsx b/src/components/playback/videoPlayer/buttons/SkipSegmentButton.tsx index 788885b..7030479 100644 --- a/src/components/playback/videoPlayer/buttons/SkipSegmentButton.tsx +++ b/src/components/playback/videoPlayer/buttons/SkipSegmentButton.tsx @@ -35,7 +35,7 @@ const SkipSegmentButton = () => { currentSegmentIndex >= 0 && activeSegmentId && (segmentType !== "Outro" || !hasNextItem); - const label = segmentType === "Outro" ? "Skip credits" : `Skip ${segmentType}`; + const label = segmentType === "Outro" ? "Пропустить титры" : segmentType === "Intro" ? "Пропустить интро" : segmentType === "Recap" ? "Пропустить рекап" : segmentType === "Commercial" ? "Пропустить рекламу" : segmentType === "Preview" ? "Пропустить превью" : "Пропустить"; return ( diff --git a/src/components/playback/videoPlayer/buttons/VideoFitButton.tsx b/src/components/playback/videoPlayer/buttons/VideoFitButton.tsx new file mode 100644 index 0000000..f556924 --- /dev/null +++ b/src/components/playback/videoPlayer/buttons/VideoFitButton.tsx @@ -0,0 +1,93 @@ +import { + IconButton, + ListItemIcon, + ListItemText, + Menu, + MenuItem, + Tooltip, +} from "@mui/material"; +import React, { useState } from "react"; +import type { VideoFitMode } from "@/utils/types/videoFitMode"; + +const OPTIONS: Array<{ + value: VideoFitMode; + label: string; + icon: string; + hint: string; +}> = [ + { + value: "fit", + label: "По размеру", + icon: "fit_screen", + hint: "Вписать видео целиком", + }, + { + value: "fill", + label: "Заполнить экран", + icon: "zoom_out_map", + hint: "Убрать полосы, обрезав края", + }, + { + value: "stretch", + label: "Растянуть", + icon: "aspect_ratio", + hint: "Растянуть на весь экран", + }, +]; + +type VideoFitButtonProps = { + mode: VideoFitMode; + onChange: (mode: VideoFitMode) => void; +}; + +const VideoFitButton = ({ mode, onChange }: VideoFitButtonProps) => { + const [anchor, setAnchor] = useState(null); + const current = OPTIONS.find((option) => option.value === mode) ?? OPTIONS[0]; + + return ( + <> + + setAnchor(event.currentTarget)} + aria-label="Режим изображения" + > + aspect_ratio + + + setAnchor(null)} + anchorOrigin={{ vertical: "top", horizontal: "center" }} + transformOrigin={{ vertical: "bottom", horizontal: "center" }} + slotProps={{ paper: { className: "glass-menu-paper" } }} + > + {OPTIONS.map((option) => ( + { + onChange(option.value); + setAnchor(null); + }} + > + + {option.icon} + + + {option.value === mode && ( + + check + + )} + + ))} + + + ); +}; + +export default VideoFitButton; diff --git a/src/components/playback/videoPlayer/controls.scss b/src/components/playback/videoPlayer/controls.scss index 44daf43..70f0bb6 100644 --- a/src/components/playback/videoPlayer/controls.scss +++ b/src/components/playback/videoPlayer/controls.scss @@ -1,10 +1,34 @@ .video-player { + --media-object-fit: contain; + background: black; position: absolute; width: 100vw; height: 100vh; top: 0; left: 0; + + video { + object-fit: var(--media-object-fit); + } + + &.video-fit-fill { + --media-object-fit: cover; + } + + &.video-fit-stretch { + --media-object-fit: fill; + } + + &-drag-region { + position: absolute; + inset: 0 0 auto; + height: 38px; + z-index: 4; + cursor: default; + user-select: none; + } + &-osd { position: absolute; width: 100vw; @@ -27,6 +51,29 @@ &.hovering { cursor: default; } + &-back, + &-actions { + position: absolute; + top: 2em; + z-index: 3; + display: flex; + align-items: center; + padding: 0.3em; + border-radius: 999px; + border: 1px solid rgb(255 255 255 / 0.08); + background: rgb(0 0 0 / 0.28); + backdrop-filter: blur(12px); + } + &-back { + left: 3em; + } + &-actions { + right: 3em; + gap: 0.35em; + } + &-info { + margin-top: auto; + } &-controls { display: flex; flex-direction: column; diff --git a/src/components/playback/videoPlayer/controls.tsx b/src/components/playback/videoPlayer/controls.tsx index 1e833fc..f80862d 100644 --- a/src/components/playback/videoPlayer/controls.tsx +++ b/src/components/playback/videoPlayer/controls.tsx @@ -17,19 +17,23 @@ import QueueButton from "@/components/buttons/queueButton"; import BubbleSlider from "@/components/playback/videoPlayer/bubbleSlider"; import { secToTicks, ticksToSec } from "@/utils/date/time"; import { buildPlayDeepLink } from "@/utils/deepLinks"; +import { getPlayerVideoElement } from "@/utils/methods/pictureInPicture"; import { openSyncPlayDialog } from "@/utils/methods/syncPlay"; import { useApiInContext } from "@/utils/store/api"; import { useShareStore } from "@/utils/store/share"; import { usePlaybackStore } from "@/utils/store/playback"; import useSyncPlayback from "@/utils/store/syncPlayback"; +import type { VideoFitMode } from "@/utils/types/videoFitMode"; import CaptionsButton from "./buttons/CaptionsButton"; import ChaptersListButton from "./buttons/ChaptersListButton"; import ForwardButton from "./buttons/ForwardButton"; import FullscreenButton from "./buttons/FullscreenButton"; import NextChapterButton from "./buttons/NextChapterButton"; +import PictureInPictureButton from "./buttons/PictureInPictureButton"; import PlayPauseButton from "./buttons/PlayPauseButton"; import PrevChapterButton from "./buttons/PrevChapterButton"; import RewindButton from "./buttons/RewindButton"; +import VideoFitButton from "./buttons/VideoFitButton"; import EndsAtDisplay from "./EndsAtDisplay"; import VideoPlayerSettingsMenu from "./settingsMenu"; @@ -48,12 +52,16 @@ type VideoPlayerControlsProps = { // isVisible: boolean; onHover?: (event: MouseEvent) => void; onLeave?: (event: MouseEvent) => void; + fitMode: VideoFitMode; + onFitModeChange: (mode: VideoFitMode) => void; }; const VideoPlayerControls = ({ // isVisible, onHover, onLeave, + fitMode, + onFitModeChange, }: VideoPlayerControlsProps) => { const playerOSDRef = useRef(null); @@ -145,6 +153,69 @@ const VideoPlayerControls = ({ const [settingsMenuRef, setSettingsMenuRef] = useState(null); + const [videoFrame, setVideoFrame] = useState<{ + top: number; + left: number; + right: number; + } | null>(null); + + // Keep the back button and the top action buttons on one line inside the + // visible video area, below any letterbox bars. + useEffect(() => { + let frame = 0; + const update = () => { + const video = getPlayerVideoElement(); + if (!video) return; + + const rect = video.getBoundingClientRect(); + const ratio = + video.videoWidth > 0 && video.videoHeight > 0 + ? video.videoWidth / video.videoHeight + : null; + const contentWidth = ratio + ? Math.min(rect.width, rect.height * ratio) + : rect.width; + const contentHeight = ratio ? contentWidth / ratio : rect.height; + const contentLeft = rect.left + (rect.width - contentWidth) / 2; + const contentTop = rect.top + (rect.height - contentHeight) / 2; + + setVideoFrame((current) => { + const next = { + // 14% keeps the controls inside the picture even when the + // file has letterbox bars baked into a 16:9 frame. + top: Math.round( + contentTop + Math.max(28, contentHeight * 0.14), + ), + left: Math.round(contentLeft + 24), + right: Math.round( + window.innerWidth - contentLeft - contentWidth + 24, + ), + }; + return current?.top === next.top && + current?.left === next.left && + current?.right === next.right + ? current + : next; + }); + }; + const schedule = () => { + cancelAnimationFrame(frame); + frame = requestAnimationFrame(update); + }; + + schedule(); + const video = getPlayerVideoElement(); + video?.addEventListener("loadedmetadata", schedule); + window.addEventListener("resize", schedule); + const interval = window.setInterval(schedule, 1000); + + return () => { + cancelAnimationFrame(frame); + window.clearInterval(interval); + video?.removeEventListener("loadedmetadata", schedule); + window.removeEventListener("resize", schedule); + }; + }, [playsessionId]); // const creditInfo = mediaSegments?.Items?.find( // (segment) => segment.Type === "Outro", @@ -229,14 +300,30 @@ const VideoPlayerControls = ({ } }} > -
+
arrow_back +
+
useShareStore @@ -246,25 +333,25 @@ const VideoPlayerControls = ({ itemId ?? "", currentTime > 0 ? ticksToSec(currentTime) : getCurrentTime(), ), - "Share this scene", + "Поделиться этой сценой", ) } - aria-label="Share scene" - title="Share scene" + aria-label="Поделиться сценой" + title="Поделиться сценой" > share groups setSettingsMenuRef(e.currentTarget)} - aria-label="Player settings" - title="Player settings" + aria-label="Настройки плеера" + title="Настройки плеера" > settings @@ -372,10 +459,10 @@ const VideoPlayerControls = ({ })} /> + +
diff --git a/src/components/playback/videoPlayer/settingsMenu.tsx b/src/components/playback/videoPlayer/settingsMenu.tsx index 5fcadf4..266d2b4 100644 --- a/src/components/playback/videoPlayer/settingsMenu.tsx +++ b/src/components/playback/videoPlayer/settingsMenu.tsx @@ -156,7 +156,7 @@ const VideoPlayerSettingsMenu = ({ > - No Subtitle + Без субтитров {mediaSource.subtitle?.allTracks?.map((sub) => ( @@ -194,7 +194,7 @@ const VideoPlayerSettingsMenu = ({ flexGrow: 1, }} > - Stats for Nerds + Статистика @@ -204,7 +204,7 @@ const VideoPlayerSettingsMenu = ({ flexGrow: 1, }} > - Sync playback + Синхронизация воспроизведения - Auto-skip intro & recap + Автопропуск заставок, рекапов, рекламы и превью { quality: 90, fillWidth: 320, })} - alt="next item thumbnail" + alt="Миниатюра следующего элемента" style={{ width: "100%", height: "100%", @@ -142,7 +142,7 @@ const UpNextFlyout = () => { letterSpacing: 1.2, }} > - UP NEXT + ДАЛЕЕ { flex: 1, }} > - Play Now + Смотреть setIsHidden(true)} diff --git a/src/components/qrCode/index.tsx b/src/components/qrCode/index.tsx index c22dc3a..1e1a19a 100644 --- a/src/components/qrCode/index.tsx +++ b/src/components/qrCode/index.tsx @@ -35,7 +35,7 @@ const QRCodeImage = ({ return ( QR code { ? `E${item.IndexNumber}-${item.IndexNumberEnd}` : `E${item.IndexNumber}`; return { - title: item.Name ?? "Unknown episode", + title: item.Name ?? "Неизвестная серия", subtitle: [item.SeriesName, `S${item.ParentIndexNumber}:${episode}`] .filter(Boolean) .join(" · "), }; } return { - title: item.Name ?? "Unknown track", + title: item.Name ?? "Неизвестный трек", subtitle: item.Artists?.join(", ") || item.AlbumArtist || "", }; }; @@ -122,7 +122,7 @@ export const QueueRow = React.forwardRef< {item.RunTimeTicks ? getRuntimeMusic(item.RunTimeTicks) : ""} {onRemove && ( - + { const remove = (item: BaseItemDto, index: number) => { removeFromQueue(index); const { title } = getQueueItemText(item); - enqueueSnackbar(`Removed "${title}"`, { + enqueueSnackbar(`«${title}» удалён`, { variant: "default", action: (key) => ( ), }); @@ -101,7 +101,7 @@ const QueueView = ({ variant, onClose }: QueueViewProps) => { const clearAll = () => { const removed = upcoming; clearUpcoming(); - enqueueSnackbar(`Cleared ${removed.length} tracks from up next`, { + enqueueSnackbar(`Очищено треков из очереди: ${removed.length}`, { action: (key) => ( ), }); @@ -135,35 +135,35 @@ const QueueView = ({ variant, onClose }: QueueViewProps) => { const summary = upcoming.length > 0 ? `${upcoming.length} ${upcoming.length === 1 ? "track" : "tracks"} · ${getRuntimeCompact(upcomingTicks)}` - : "Nothing queued"; + : "Очередь пуста"; return (

- {variant === "drawer" ? "Queue" : "Up next"} + {variant === "drawer" ? "Очередь" : "Далее"}

{summary}
- + shuffle - + playlist_remove @@ -172,7 +172,7 @@ const QueueView = ({ variant, onClose }: QueueViewProps) => { {onClose && ( - + close )} @@ -182,14 +182,14 @@ const QueueView = ({ variant, onClose }: QueueViewProps) => {
{variant === "drawer" && current && (
-

Now playing

+

Сейчас играет

)}
{variant === "drawer" && ( -

Up next

+

Далее

)} {upcoming.length > 0 ? ( <> @@ -219,7 +219,7 @@ const QueueView = ({ variant, onClose }: QueueViewProps) => {

- Click a track to play it now · drag to reorder + Нажмите на трек, чтобы включить его, перетащите для сортировки

) : ( @@ -227,9 +227,9 @@ const QueueView = ({ variant, onClose }: QueueViewProps) => { queue_music - Nothing up next + Очередь пуста - Play an album, playlist or artist to fill the queue. + Включите альбом, плейлист или исполнителя, чтобы заполнить очередь.
)} @@ -244,7 +244,7 @@ const QueueView = ({ variant, onClose }: QueueViewProps) => { aria-expanded={showHistory} > - Previously played · {history.length} + Ранее играло · {history.length} {showHistory ? "expand_less" : "expand_more"} diff --git a/src/components/quickConnectApproval/index.tsx b/src/components/quickConnectApproval/index.tsx index e9ec11e..8b49753 100644 --- a/src/components/quickConnectApproval/index.tsx +++ b/src/components/quickConnectApproval/index.tsx @@ -41,12 +41,12 @@ const QuickConnectApprovalDialog = () => { const approve = async () => { if (!api || !user?.Id) { - setError("Sign in before approving another device"); + setError("Войдите, чтобы подтвердить другое устройство"); return; } const trimmed = code.trim().toUpperCase(); if (!trimmed) { - setError("Enter the code shown on the other device"); + setError("Введите код, показанный на другом устройстве"); return; } setBusy(true); @@ -59,14 +59,14 @@ const QuickConnectApprovalDialog = () => { if (result.data) { setApproved(true); setStoreCode(""); - enqueueSnackbar("Device approved", { variant: "success" }); + enqueueSnackbar("Устройство подтверждено", { variant: "success" }); setTimeout(close, 1200); } else { - setError("This code is invalid or has expired"); + setError("Код недействителен или истёк"); } } catch (reason) { console.error("Quick Connect approval failed", reason); - setError("This code is invalid or has expired"); + setError("Код недействителен или истёк"); } finally { setBusy(false); } @@ -82,18 +82,18 @@ const QuickConnectApprovalDialog = () => { paper: { className: "glass", sx: { borderRadius: "22px" } }, }} > - Approve TV login + Подтвердить вход на ТВ - Enter the Quick Connect code shown on the TV or another device. This - signs that device in as {user?.Name ?? "your account"} without - typing a password on it. + Введите код Quick Connect, показанный на ТВ или другом устройстве. Это + выполнит вход в аккаунт {user?.Name ?? "ваш аккаунт"} без ввода пароля + на этом устройстве. setCode(event.target.value.replace(/\s/g, "").toUpperCase()) @@ -113,17 +113,17 @@ const QuickConnectApprovalDialog = () => { }} /> {error && {error}} - {approved && Device approved} + {approved && Устройство подтверждено} - + diff --git a/src/components/realtime/index.tsx b/src/components/realtime/index.tsx index 581c6f8..72cb301 100644 --- a/src/components/realtime/index.tsx +++ b/src/components/realtime/index.tsx @@ -215,7 +215,7 @@ const RealtimeBridge = () => { case GeneralCommandType.DisplayMessage: enqueueSnackbar( [args?.Header, args?.Text].filter(Boolean).join(": ") || - "Message from the server", + "Сообщение с сервера", { variant: "info", autoHideDuration: Number(args?.TimeoutMs) || 5000, @@ -266,7 +266,7 @@ const RealtimeBridge = () => { }) .catch((error) => { console.error("Remote play failed", error); - enqueueSnackbar("Could not start remote playback", { + enqueueSnackbar("Не удалось запустить удалённое воспроизведение", { variant: "error", }); }); diff --git a/src/components/remoteControl/index.tsx b/src/components/remoteControl/index.tsx index 29bd506..b3524dc 100644 --- a/src/components/remoteControl/index.tsx +++ b/src/components/remoteControl/index.tsx @@ -46,7 +46,7 @@ const formatTime = (ticks: number | null | undefined) => { }; const sessionLabel = (session: SessionInfoDto) => - session.DeviceName || session.Client || session.DeviceId || "Unknown device"; + session.DeviceName || session.Client || session.DeviceId || "Неизвестное устройство"; const RemoteControlDialog = () => { const { open, transfer, closeDialog } = useRemoteControlStore(); @@ -87,7 +87,7 @@ const RemoteControlDialog = () => { }); }, onError: () => - enqueueSnackbar("Command failed", { variant: "error" }), + enqueueSnackbar("Команда не выполнена", { variant: "error" }), onSettled: () => sessions.refetch(), }); @@ -105,8 +105,8 @@ const RemoteControlDialog = () => { onSuccess: async (_data, session) => { enqueueSnackbar( transfer?.kind === "audio" || transfer?.kind === "video" - ? `Playback transferred to ${sessionLabel(session)}` - : `Playing on ${sessionLabel(session)}`, + ? `Воспроизведение перенесено на ${sessionLabel(session)}` + : `Воспроизведение на ${sessionLabel(session)}`, { variant: "success" }, ); if (transfer?.kind === "audio") { @@ -144,7 +144,7 @@ const RemoteControlDialog = () => { closeDialog(); }, onError: () => - enqueueSnackbar("Could not start playback on the device", { + enqueueSnackbar("Не удалось запустить воспроизведение на устройстве", { variant: "error", }), }); @@ -184,16 +184,16 @@ const RemoteControlDialog = () => { cast - {item ? `Play "${item.Name}" on…` : "Remote control"} + {item ? `Воспроизвести «${item.Name}» на…` : "Удалённое управление"} - + close {item && ( - Choose a device to start playback on it. + Выберите устройство для запуска воспроизведения. )} {sessions.isPending ? ( @@ -202,8 +202,8 @@ const RemoteControlDialog = () => {
) : remoteSessions.length === 0 ? ( - No other controllable devices are online. Open a Jellyfin client - (e.g. on your TV) and make sure remote control is allowed. + Нет доступных устройств. Откройте клиент Jellyfin (например, на ТВ) + и разрешите удалённое управление. ) : ( @@ -252,8 +252,8 @@ const RemoteControlDialog = () => { color="warning.main" sx={{ display: "block" }} > - No active control channel (WebSocket) — check the - reverse proxy. + Нет канала управления (WebSocket) — проверьте + обратный прокси. )}
@@ -264,7 +264,7 @@ const RemoteControlDialog = () => { disabled={playOn.isPending || !item.Id} onClick={() => playOn.mutate(session)} > - Play here + Смотреть здесь )}
@@ -300,10 +300,10 @@ const RemoteControlDialog = () => { > {formatTime(position)} / {formatTime(duration)} - {playState?.IsPaused ? " · paused" : ""} + {playState?.IsPaused ? " · пауза" : ""}
- + { - + { { - + { - + { - + { ) : ( - Idle + Свободно )} diff --git a/src/components/search/index.tsx b/src/components/search/index.tsx index 2a814d8..97c901c 100644 --- a/src/components/search/index.tsx +++ b/src/components/search/index.tsx @@ -193,7 +193,7 @@ const Search = () => { { display: "block", }} > - Results + Результаты {searchResults.data.SearchHints.map((item) => ( { display: "block", }} > - Suggestions + Подсказки {suggestions.data?.Items?.map((item) => ( { search_off - No results found for "{debouncedSearchTerm}" + Ничего не найдено по запросу «{debouncedSearchTerm}» )} @@ -420,7 +420,7 @@ const Search = () => { }, }} > - Advanced Search + Расширенный поиск diff --git a/src/components/search/item.tsx b/src/components/search/item.tsx index 41b0965..b6b9f94 100644 --- a/src/components/search/item.tsx +++ b/src/components/search/item.tsx @@ -15,6 +15,23 @@ type SearchItemProps = { itemId: string; }; +const typeLabels: Record = { + Movie: "Фильм", + Series: "Сериал", + Episode: "Серия", + Audio: "Трек", + AudioBook: "Аудиокнига", + MusicAlbum: "Альбом", + MusicArtist: "Исполнитель", + Person: "Человек", + Book: "Книга", + Photo: "Фото", + PhotoAlbum: "Фотоальбом", + Playlist: "Плейлист", + Video: "Видео", + BoxSet: "Коллекция", +}; + const SearchItem = (props: SearchItemProps) => { const { itemName, imageUrl, itemYear, itemType, itemId } = props; const toggleSearchDialog = useSearchStore( @@ -123,7 +140,7 @@ const SearchItem = (props: SearchItemProps) => { color: "text.secondary", }} > - {itemType} + {typeLabels[itemType] ?? itemType} )} diff --git a/src/components/settingOptionSelect/index.tsx b/src/components/settingOptionSelect/index.tsx index 778c24c..0604bba 100644 --- a/src/components/settingOptionSelect/index.tsx +++ b/src/components/settingOptionSelect/index.tsx @@ -25,7 +25,7 @@ const SettingOptionSelect = ({ control={ setValue(e.target.value)}> - Any Language + Любой язык {options.map((option) => ( { const copy = async () => { await writeText(link); - enqueueSnackbar("Link copied", { variant: "success" }); + enqueueSnackbar("Ссылка скопирована", { variant: "success" }); }; const openHere = async () => { @@ -38,7 +38,7 @@ const ShareDialog = () => { close(); } catch (error) { console.error(error); - enqueueSnackbar("Could not open the link", { variant: "error" }); + enqueueSnackbar("Не удалось открыть ссылку", { variant: "error" }); } }; @@ -52,7 +52,7 @@ const ShareDialog = () => { paper: { className: "glass", sx: { borderRadius: "22px" } }, }} > - {title || "Share"} + {title || "Поделиться"} { variant="body2" sx={{ opacity: 0.7, textAlign: "center" }} > - Scan with Blink on a phone or TV, or copy the link to open it on - another device. + Отсканируйте код в Blink на телефоне или ТВ либо скопируйте ссылку, + чтобы открыть её на другом устройстве. { - + - + ); diff --git a/src/components/showMoreText/index.tsx b/src/components/showMoreText/index.tsx index a2ce6a9..f58e121 100644 --- a/src/components/showMoreText/index.tsx +++ b/src/components/showMoreText/index.tsx @@ -62,7 +62,7 @@ const ShowMoreText = ({ onClick={() => setDisplayFull((state) => !state)} // key={displayFull} > - {displayFull ? "Show less" : "Show more"} + {displayFull ? "Свернуть" : "Показать больше"} )}
diff --git a/src/components/syncPlay/index.tsx b/src/components/syncPlay/index.tsx index 67b14bc..76eb2ac 100644 --- a/src/components/syncPlay/index.tsx +++ b/src/components/syncPlay/index.tsx @@ -40,13 +40,13 @@ import useSyncPlayStore from "@/utils/store/syncPlay"; const stateLabel = (state?: string) => { switch (state) { case "Waiting": - return "Waiting for everyone"; + return "Ожидание устройств"; case "Paused": - return "Paused"; + return "Пауза"; case "Playing": - return "Playing"; + return "Идёт"; default: - return "Idle"; + return "Ожидание"; } }; @@ -149,7 +149,7 @@ const SyncPlayDialog = () => { > groups - Watch together + Смотреть вместе {error && ( @@ -161,7 +161,7 @@ const SyncPlayDialog = () => { - {group.GroupName || "SyncPlay group"} + {group.GroupName || "Группа SyncPlay"} { ? `${group.Participants.length} device${ group.Participants.length === 1 ? "" : "s" } connected: ${group.Participants.join(", ")}` - : "This is the first device in the group."} + : "Это первое устройство в группе."} @@ -209,20 +209,20 @@ const SyncPlayDialog = () => { )} - Group queue + Очередь группы {currentItem.data?.Name ?? (queueItemIds.length - ? "Loading item…" - : "Nothing queued yet")} + ? "Загрузка…" + : "Очередь пока пуста")} {queueItemIds.length ? `${queueItemIds.length} item${ queueItemIds.length === 1 ? "" : "s" } · item ${currentQueueIndex + 1}` - : "Start a queue on the device that should lead."} + : "Запустите очередь на устройстве, которое будет ведущим."} @@ -234,8 +234,8 @@ const SyncPlayDialog = () => { onClick={() => api && startSyncPlayQueue(api)} > {queueItemIds.length - ? "Replace with my queue" - : "Share my queue"} + ? "Заменить моей очередью" + : "Поделиться моей очередью"} {queueItemIds.length > 0 && user?.Id && ( )} {loading && } @@ -275,16 +275,16 @@ const SyncPlayDialog = () => { ) : ( - Create a group and start the current queue, or join a group - created on another device. Every device that joins follows the - same timeline. + Создайте группу и запустите текущую очередь или войдите в + группу, созданную на другом устройстве. Все устройства следуют + одному таймлайну. setGroupName(event.target.value)} onKeyDown={(event) => { @@ -297,18 +297,18 @@ const SyncPlayDialog = () => { onClick={handleCreate} sx={{ flex: "0 0 auto" }} > - Create + Создать - Available groups + Доступные группы {groupsQuery.isPending ? ( ) : groups.length === 0 ? ( - No groups yet. Create one above. + Групп пока нет. Создайте выше. ) : ( @@ -327,12 +327,12 @@ const SyncPlayDialog = () => { } }} > - Join + Войти } > { )} - + ); diff --git a/src/components/updater/index.tsx b/src/components/updater/index.tsx index 93ca365..5338f20 100644 --- a/src/components/updater/index.tsx +++ b/src/components/updater/index.tsx @@ -57,7 +57,7 @@ export default function Updater() { } }); enqueueSnackbar( - "Update has been installed! You need to relaunch Blink.", + "Обновление установлено. Перезапустите Blink.", { variant: "success", }, @@ -65,7 +65,7 @@ export default function Updater() { await relaunch(); } catch (error) { console.error(error); - enqueueSnackbar(`Failed to update Blink. ${error}`, { variant: "error" }); + enqueueSnackbar(`Не удалось обновить Blink. ${error}`, { variant: "error" }); } setUpdateDialogButton(false); }, [enqueueSnackbar, updateInfo, downloadSize]); @@ -160,7 +160,7 @@ export default function Updater() { color: "transparent", }} > - Update Available + Доступно обновление - A new version of Blink is ready for you. + Новая версия Blink готова к установке. @@ -193,7 +193,7 @@ export default function Updater() { mb: 0.5, }} > - Current + Текущая - New Version + Новая версия } > - See what's new + Что нового @@ -308,7 +308,7 @@ export default function Updater() { }, }} > - Later + Позже diff --git a/src/components/userAvatarMenu/index.tsx b/src/components/userAvatarMenu/index.tsx index d79e43d..2ca63ed 100644 --- a/src/components/userAvatarMenu/index.tsx +++ b/src/components/userAvatarMenu/index.tsx @@ -65,8 +65,8 @@ export const UserAvatarMenu = () => { {!!user?.Id && (user?.PrimaryImageTag === undefined ? ( @@ -104,7 +104,7 @@ export const UserAvatarMenu = () => { logout - Logout + Выйти { qr_code_2 - Approve device login + Подтвердить вход на устройство { @@ -129,7 +129,7 @@ export const UserAvatarMenu = () => { tune - Preferences + Настройки { @@ -140,7 +140,7 @@ export const UserAvatarMenu = () => { info - About + О приложении
diff --git a/src/components/windowControls/index.tsx b/src/components/windowControls/index.tsx index 2a0fdf8..962fb08 100644 --- a/src/components/windowControls/index.tsx +++ b/src/components/windowControls/index.tsx @@ -35,16 +35,16 @@ const WindowsControls = () => {
)} {showsLibrary?.Id && ( @@ -62,7 +62,7 @@ const HomeHeader = ({ libraries, onNewAndPopular }: HomeHeaderProps) => { className="home-nav-link" onClick={openShows} > - Shows + Сериалы )}
@@ -104,18 +104,18 @@ const HomeHeader = ({ libraries, onNewAndPopular }: HomeHeaderProps) => {
groups - + search navigate({ to: "/favorite" })} > favorite diff --git a/src/routes/_api/home/index.tsx b/src/routes/_api/home/index.tsx index a53f5b6..81006d2 100644 --- a/src/routes/_api/home/index.tsx +++ b/src/routes/_api/home/index.tsx @@ -195,7 +195,7 @@ function HomeContent({ api, user }: { api: Api; user: UserDto }) {
@@ -235,11 +235,11 @@ function HomeContent({ api, user }: { api: Api; user: UserDto }) { - Error with Carousel + Ошибка карусели
} > - + {libraries.data?.Items?.map((item) => { return ( - Error with Libraries + Ошибка библиотек
} > {upNextItems.isSuccess && upNextItems.data?.TotalRecordCount && ( - + {upNextItems.data?.Items?.map((item) => { return ( - Error with resumeItemsVideo + Ошибка продолжения просмотра
} > @@ -323,7 +323,7 @@ function HomeContent({ api, user }: { api: Api; user: UserDto }) { !resumeItemsVideo.data?.TotalRecordCount ? ( <> ) : ( - + {resumeItemsVideo.data?.Items?.map((item) => { return ( - Error with resumeItemsAudio + Ошибка продолжения прослушивания
} > @@ -374,7 +374,7 @@ function HomeContent({ api, user }: { api: Api; user: UserDto }) { !resumeItemsAudio.data?.TotalRecordCount ? ( <> ) : ( - + {resumeItemsAudio.data?.Items?.map((item) => { return ( - Error with LatestMediaSections + Ошибка новых материалов
} > diff --git a/src/routes/_api/library/$id.tsx b/src/routes/_api/library/$id.tsx index 257148e..0fa2e03 100644 --- a/src/routes/_api/library/$id.tsx +++ b/src/routes/_api/library/$id.tsx @@ -87,7 +87,7 @@ function Library() { ); // Derive top app title from Zustand slice (library name) useEffect(() => { - const title = storeLibraryName ?? "Library"; + const title = storeLibraryName ?? "Библиотека"; setPageTitle(title); return () => setPageTitle(null); }, [storeLibraryName, setPageTitle]); diff --git a/src/routes/_api/login/$userId.$userName.tsx b/src/routes/_api/login/$userId.$userName.tsx index 2ea8c67..9c227b8 100644 --- a/src/routes/_api/login/$userId.$userName.tsx +++ b/src/routes/_api/login/$userId.$userName.tsx @@ -46,10 +46,10 @@ function LoginUser() { const handleLogin = useMutation({ mutationKey: ["login", "authenticate"], mutationFn: async () => { - if (!api) throw new Error("API not initialized"); + if (!api) throw new Error("API не инициализировано"); const authenticate = await api.authenticateUserByName(userName, password); if (!authenticate.data.AccessToken) { - throw new Error("No access token received"); + throw new Error("Не удалось получить токен доступа"); } createApi(api.basePath, authenticate.data.AccessToken); if (authenticate.data.SessionInfo?.UserId && rememberMe) { @@ -69,8 +69,8 @@ function LoginUser() { console.error(err); setError( needsPassword - ? "Incorrect password. Please try again." - : "Couldn't sign in. Please try again.", + ? "Неверный пароль. Попробуйте ещё раз." + : "Не удалось войти. Попробуйте ещё раз.", ); setPassword(""); }, @@ -84,16 +84,16 @@ function LoginUser() { return ( switch_account - Not you? Switch user + Не вы? Сменить пользователя } > @@ -110,7 +110,7 @@ function LoginUser() { setShowPassword((show) => !show)} edge="end" aria-label={ - showPassword ? "Hide password" : "Show password" + showPassword ? "Скрыть пароль" : "Показать пароль" } > @@ -156,7 +156,7 @@ function LoginUser() { onChange={(_, checked) => setRememberMe(checked)} /> } - label="Keep me signed in" + label="Запомнить меня" /> @@ -168,7 +168,7 @@ function LoginUser() { fullWidth loading={handleLogin.isPending || handleLogin.isSuccess} > - Sign in + Войти diff --git a/src/routes/_api/login/list.tsx b/src/routes/_api/login/list.tsx index 0e495b7..8a1ed3b 100644 --- a/src/routes/_api/login/list.tsx +++ b/src/routes/_api/login/list.tsx @@ -21,8 +21,8 @@ function LoginPublicUsersList() { return (
{users.isPending && @@ -39,7 +39,7 @@ function LoginPublicUsersList() { className="profile" to="/login/$userId/$userName" params={{ userId: user.Id ?? "", userName: user.Name ?? "" }} - aria-label={`Sign in as ${user.Name}`} + aria-label={`Войти как ${user.Name}`} > person_add - Other user + Другой пользователь )}
{users.isError && (

- Couldn't load profiles from this server. Use "Other user" to sign in - with your username. + Не удалось загрузить профили с этого сервера. Используйте «Другой + пользователь», чтобы войти по имени и паролю.

)}
diff --git a/src/routes/_api/login/manual.tsx b/src/routes/_api/login/manual.tsx index b1e65f7..5b0c82e 100644 --- a/src/routes/_api/login/manual.tsx +++ b/src/routes/_api/login/manual.tsx @@ -39,13 +39,13 @@ function UserLoginManual() { const handleLogin = useMutation({ mutationKey: ["login", "authenticate"], mutationFn: async () => { - if (!api) throw new Error("Api is not available"); + if (!api) throw new Error("API недоступно"); const authenticate = await api.authenticateUserByName( username.trim(), password, ); if (!authenticate.data?.AccessToken) { - throw new Error("Access token not available"); + throw new Error("Не удалось получить токен доступа"); } createApi(api.basePath, authenticate.data.AccessToken); if (rememberMe) { @@ -63,7 +63,7 @@ function UserLoginManual() { }, onError: (err) => { console.error(err); - setError("Incorrect username or password."); + setError("Неверное имя пользователя или пароль."); setPassword(""); }, }); @@ -71,7 +71,7 @@ function UserLoginManual() { const handleSubmit = (event: FormEvent) => { event.preventDefault(); if (!username.trim()) { - setError("Enter your username."); + setError("Введите имя пользователя."); return; } setError(null); @@ -80,12 +80,12 @@ function UserLoginManual() { return ( group - Choose a profile instead + Выбрать профиль } > @@ -93,7 +93,7 @@ function UserLoginManual() { setShowPassword((show) => !show)} edge="end" aria-label={ - showPassword ? "Hide password" : "Show password" + showPassword ? "Скрыть пароль" : "Показать пароль" } > @@ -145,7 +145,7 @@ function UserLoginManual() { onChange={(_, checked) => setRememberMe(checked)} /> } - label="Keep me signed in" + label="Запомнить меня" /> @@ -157,7 +157,7 @@ function UserLoginManual() { fullWidth loading={handleLogin.isPending || handleLogin.isSuccess} > - Sign in + Войти diff --git a/src/routes/_api/music/album/$id.tsx b/src/routes/_api/music/album/$id.tsx index 7d4b1c7..d9f8d51 100644 --- a/src/routes/_api/music/album/$id.tsx +++ b/src/routes/_api/music/album/$id.tsx @@ -173,8 +173,8 @@ function MusicAlbumTitlePage() { {(musicTracks.data?.TotalRecordCount ?? 0) > 1 - ? `${musicTracks.data?.TotalRecordCount} songs` - : "Single"} + ? `${musicTracks.data?.TotalRecordCount} песен` + : "Сингл"} {getRuntimeCompact(item.data.CumulativeRunTimeTicks ?? 0)} @@ -210,12 +210,12 @@ function MusicAlbumTitlePage() { > album - Disc {disc} + Диск {disc}
tag - Title - Duration + Название + Длительность
{musicTracks.data?.Items?.map( (track, index) => @@ -234,8 +234,8 @@ function MusicAlbumTitlePage() {
tag - Title - Duration + Название + Длительность
{musicTracks.data?.Items?.map((track, index) => ( 0 && ( @@ -315,10 +315,10 @@ function MusicAlbumTitlePage() { : similar.Type === BaseItemKind.Series ? `${similar.ProductionYear} - ${ similar.EndDate - ? new Date(similar.EndDate).toLocaleString([], { + ? new Date(similar.EndDate).toLocaleString("ru-RU", { year: "numeric", }) - : "Present" + : "н.в." }` : similar.ProductionYear } diff --git a/src/routes/_api/music/artist/$id.tsx b/src/routes/_api/music/artist/$id.tsx index d155fc7..54f1901 100644 --- a/src/routes/_api/music/artist/$id.tsx +++ b/src/routes/_api/music/artist/$id.tsx @@ -158,9 +158,9 @@ function ArtistTitlePage() { }); const artistTabs = [ - { title: "Discography", data: artistDiscography }, - { title: "Songs", data: artistSongs }, - { title: "Appearances", data: artistAppearances }, + { title: "Дискография", data: artistDiscography }, + { title: "Песни", data: artistSongs }, + { title: "Участие", data: artistAppearances }, ]; const [activeArtistTab, setActiveArtistTab] = useState(0); @@ -260,10 +260,10 @@ function ArtistTitlePage() { />
- + shuffleAndPlay( @@ -323,9 +323,9 @@ function ArtistTitlePage() { > {item.data.PremiereDate && (
- Born + Дата рождения - {new Date(item.data.PremiereDate).toDateString()} + {new Date(item.data.PremiereDate).toLocaleDateString("ru-RU")}
)} @@ -337,10 +337,10 @@ function ArtistTitlePage() { mt: 2, }} > - Death + Дата смерти - {new Date(item.data.EndDate).toDateString()} + {new Date(item.data.EndDate).toLocaleDateString("ru-RU")}
)} diff --git a/src/routes/_api/music/playlist/$id.tsx b/src/routes/_api/music/playlist/$id.tsx index c2ca025..4eda185 100644 --- a/src/routes/_api/music/playlist/$id.tsx +++ b/src/routes/_api/music/playlist/$id.tsx @@ -117,8 +117,8 @@ function PlaylistTitlePage() {
{(musicTracks.data?.TotalRecordCount ?? 0) > 1 - ? `${musicTracks.data?.TotalRecordCount} songs` - : "Single"} + ? `${musicTracks.data?.TotalRecordCount} песен` + : "Сингл"} {getRuntimeCompact(item.data.CumulativeRunTimeTicks ?? 0)} @@ -143,8 +143,8 @@ function PlaylistTitlePage() {
tag - Title - Duration + Название + Длительность
{musicTracks.data?.Items?.map((track, index) => ( 0 && ( @@ -223,10 +223,10 @@ function PlaylistTitlePage() { : similar.Type === BaseItemKind.Series ? `${similar.ProductionYear} - ${ similar.EndDate - ? new Date(similar.EndDate).toLocaleString([], { + ? new Date(similar.EndDate).toLocaleString("ru-RU", { year: "numeric", }) - : "Present" + : "н.в." }` : similar.ProductionYear } diff --git a/src/routes/_api/player/audio.tsx b/src/routes/_api/player/audio.tsx index 5cec597..b6922d4 100644 --- a/src/routes/_api/player/audio.tsx +++ b/src/routes/_api/player/audio.tsx @@ -47,9 +47,9 @@ export const Route = createFileRoute("/_api/player/audio")({ }); const repeatLabels: Record = { - off: "Repeat off", - all: "Repeat all", - one: "Repeat one", + off: "Повтор выкл.", + all: "Повтор всех", + one: "Повтор одного", }; /** Artists (linked) and album (linked) for the current track. */ @@ -186,7 +186,7 @@ function AudioPlayerRoute() {
{imageUrl ? ( - {item?.Name + {item?.Name ) : ( music_note )} @@ -234,12 +234,12 @@ function AudioPlayerRoute() { />
- + shuffle @@ -274,7 +274,7 @@ function AudioPlayerRoute() {
setMenuAnchor(e.currentTarget)} - aria-label="More options" + aria-label="Ещё" > more_horiz @@ -300,7 +300,7 @@ function AudioPlayerRoute() { album - Go to album + Перейти к альбому person - Go to artist + Перейти к исполнителю { @@ -328,7 +328,7 @@ function AudioPlayerRoute() { query_stats - Stats for nerds + Статистика
@@ -336,7 +336,7 @@ function AudioPlayerRoute() {
diff --git a/src/routes/error/$code.tsx b/src/routes/error/$code.tsx index dbca100..3f83e43 100644 --- a/src/routes/error/$code.tsx +++ b/src/routes/error/$code.tsx @@ -28,10 +28,10 @@ function ErrorRoute() { fontWeight: 500, }} > - Error connecting server. + Не удалось подключиться к серверу.
- Check your internet connection or contact your server administrator + Проверьте подключение к интернету или обратитесь к администратору сервера
- Change Server + Сменить сервер
); default: - return
Error
; + return
Ошибка
; } } diff --git a/src/routes/setup/server.add.tsx b/src/routes/setup/server.add.tsx index 50be965..a57bbe8 100644 --- a/src/routes/setup/server.add.tsx +++ b/src/routes/setup/server.add.tsx @@ -41,7 +41,7 @@ function ServerSetup() { setDefaultServer(bestServer.systemInfo?.Id); setServer(bestServer.systemInfo?.Id, bestServer); - enqueueSnackbar("Client added successfully", { + enqueueSnackbar("Сервер добавлен", { variant: "success", }); @@ -51,12 +51,12 @@ function ServerSetup() { onError: (err) => { console.error(err); enqueueSnackbar(`${JSON.stringify(err)}`, { variant: "error" }); - enqueueSnackbar("Something went wrong", { variant: "error" }); + enqueueSnackbar("Что-то пошло не так", { variant: "error" }); }, onSettled: (bestServer) => { console.log(bestServer); if (!bestServer) { - enqueueSnackbar("Provided server address is not a Jellyfin server.", { + enqueueSnackbar("Указанный адрес не является сервером Jellyfin.", { variant: "error", }); } @@ -106,7 +106,7 @@ function ServerSetup() { lineHeight: 1.5, }} > - Enter your Jellyfin server address to get started + Введите адрес сервера Jellyfin, чтобы начать
- Connect + Подключиться
@@ -166,7 +166,7 @@ function ServerSetup() { info - Example: https://demo.jellyfin.org/stable + Пример: https://demo.jellyfin.org/stable diff --git a/src/routes/setup/server.error.tsx b/src/routes/setup/server.error.tsx index 2d0fb18..10e0cb1 100644 --- a/src/routes/setup/server.error.tsx +++ b/src/routes/setup/server.error.tsx @@ -13,20 +13,20 @@ export const Route = createFileRoute("/setup/server/error")({ report - Unable to connect to server! + Не удалось подключиться к серверу!
diff --git a/src/routes/setup/server.list.tsx b/src/routes/setup/server.list.tsx index 0e98cfa..2d44e2c 100644 --- a/src/routes/setup/server.list.tsx +++ b/src/routes/setup/server.list.tsx @@ -62,7 +62,7 @@ function ServerList() { }, onError: (error) => { console.error(error); - enqueueSnackbar("Error changing the server", { + enqueueSnackbar("Не удалось сменить сервер", { variant: "error", }); }, @@ -87,7 +87,7 @@ function ServerList() { queryClient.removeQueries(); navigate({ to: "/" }); } - enqueueSnackbar("Server deleted successfully!", { variant: "success" }); + enqueueSnackbar("Сервер удалён.", { variant: "success" }); await servers.refetch(); await defaultServer.refetch(); @@ -137,7 +137,7 @@ function ServerList() { fontWeight: "bold", }} > - Servers + Серверы setAddServerDialog(true)} @@ -185,7 +185,7 @@ function ServerList() { {server.systemInfo?.ServerName} {server.id === defaultServer.data && ( = [ { - title: "Movies", + title: "Фильмы", value: BaseItemKind.Movie, compatibleCollectionTypes: [CollectionType.Movies], }, { - title: "Shows", + title: "Сериалы", value: BaseItemKind.Series, compatibleCollectionTypes: [CollectionType.Tvshows], }, { - title: "Albums", + title: "Альбомы", value: BaseItemKind.MusicAlbum, compatibleCollectionTypes: [CollectionType.Music], }, { - title: "Collections", + title: "Коллекции", value: BaseItemKind.CollectionFolder, compatibleCollectionTypes: [CollectionType.Movies, CollectionType.Boxsets], }, { - title: "Books", + title: "Книги", value: BaseItemKind.Book, compatibleCollectionTypes: [CollectionType.Books], }, { - title: "Genres", + title: "Жанры", compatibleCollectionTypes: [ CollectionType.Movies, CollectionType.Tvshows, @@ -44,32 +44,32 @@ export const AVAILABLE_VIEWS: Array<{ value: BaseItemKind.Genre, }, { - title: "Trailers", + title: "Трейлеры", value: BaseItemKind.Trailer, compatibleCollectionTypes: [CollectionType.Movies], }, { - title: "TV Networks", + title: "Телеканалы", value: BaseItemKind.Studio, compatibleCollectionTypes: [CollectionType.Tvshows], }, { - title: "Album Artist", + title: "Исполнитель альбома", value: BaseItemKind.MusicArtist, compatibleCollectionTypes: [CollectionType.Music], }, { - title: "Artist", + title: "Исполнитель", value: "Artist", compatibleCollectionTypes: [CollectionType.Music], }, { - title: "Playlist", + title: "Плейлист", value: BaseItemKind.Playlist, compatibleCollectionTypes: [CollectionType.Music, CollectionType.Playlists], }, { - title: "Songs", + title: "Песни", value: BaseItemKind.Audio, compatibleCollectionTypes: [CollectionType.Music], }, @@ -82,7 +82,7 @@ export const SORT_BY_OPTIONS: Array<{ compatibleViewTypes?: BaseItemKind[]; }> = [ { - title: "Name", + title: "Название", value: ItemSortBy.SortName, compatibleCollectionTypes: [ CollectionType.Movies, @@ -92,7 +92,7 @@ export const SORT_BY_OPTIONS: Array<{ ], }, { - title: "Track Name", + title: "Название трека", value: ItemSortBy.Name, compatibleViewTypes: [ BaseItemKind.Audio, @@ -101,22 +101,22 @@ export const SORT_BY_OPTIONS: Array<{ ], }, { - title: "Album", + title: "Альбом", value: ItemSortBy.Album, compatibleViewTypes: [BaseItemKind.Audio], }, { - title: "Album Artist", + title: "Исполнитель альбома", value: ItemSortBy.AlbumArtist, compatibleViewTypes: [BaseItemKind.Audio, BaseItemKind.MusicAlbum], }, { - title: "Artist", + title: "Исполнитель", value: ItemSortBy.Artist, compatibleViewTypes: [BaseItemKind.Audio], }, { - title: "Date Added", + title: "Дата добавления", value: ItemSortBy.DateCreated, compatibleViewTypes: [ BaseItemKind.MusicAlbum, @@ -130,7 +130,7 @@ export const SORT_BY_OPTIONS: Array<{ ], }, { - title: "Date Played", + title: "Дата просмотра", value: ItemSortBy.DatePlayed, compatibleViewTypes: [BaseItemKind.Audio, BaseItemKind.Playlist], compatibleCollectionTypes: [ @@ -140,13 +140,13 @@ export const SORT_BY_OPTIONS: Array<{ ], }, { - title: "Play Count", + title: "Количество просмотров", value: ItemSortBy.PlayCount, compatibleViewTypes: [BaseItemKind.Audio, BaseItemKind.Playlist], compatibleCollectionTypes: [CollectionType.Movies, CollectionType.Boxsets], }, { - title: "Release Date", + title: "Дата выхода", value: ItemSortBy.PremiereDate, compatibleViewTypes: [ BaseItemKind.MusicAlbum, @@ -160,7 +160,7 @@ export const SORT_BY_OPTIONS: Array<{ ], }, { - title: "Runtime", + title: "Длительность", value: ItemSortBy.Runtime, compatibleViewTypes: [ BaseItemKind.MusicAlbum, @@ -170,7 +170,7 @@ export const SORT_BY_OPTIONS: Array<{ compatibleCollectionTypes: [CollectionType.Movies, CollectionType.Boxsets], }, { - title: "Random", + title: "Случайно", value: ItemSortBy.Random, compatibleViewTypes: [ // BaseItemKind.MusicAlbum, @@ -184,7 +184,7 @@ export const SORT_BY_OPTIONS: Array<{ ], }, { - title: "Community Rating", + title: "Рейтинг сообщества", value: ItemSortBy.CommunityRating, compatibleViewTypes: [ BaseItemKind.MusicAlbum, @@ -198,7 +198,7 @@ export const SORT_BY_OPTIONS: Array<{ ], }, { - title: "Critics Rating", + title: "Рейтинг критиков", value: ItemSortBy.CriticRating, compatibleViewTypes: [ BaseItemKind.MusicAlbum, @@ -208,12 +208,12 @@ export const SORT_BY_OPTIONS: Array<{ compatibleCollectionTypes: [CollectionType.Movies, CollectionType.Boxsets], }, { - title: "Folder", + title: "Папка", value: [ItemSortBy.IsFolder, ItemSortBy.SortName], compatibleViewTypes: [BaseItemKind.Playlist], }, { - title: "Parental Rating", + title: "Возрастной рейтинг", value: ItemSortBy.OfficialRating, compatibleViewTypes: [BaseItemKind.Playlist], compatibleCollectionTypes: [ @@ -223,7 +223,7 @@ export const SORT_BY_OPTIONS: Array<{ ], }, { - title: "Release Date", + title: "Дата выхода", value: [ ItemSortBy.ProductionYear, ItemSortBy.PremiereDate, @@ -236,7 +236,7 @@ export const SORT_BY_OPTIONS: Array<{ ], }, { - title: "Date Episode Added", + title: "Дата добавления серии", value: ItemSortBy.DateLastContentAdded, compatibleCollectionTypes: [CollectionType.Tvshows], }, diff --git a/src/utils/date/time.ts b/src/utils/date/time.ts index c3a8433..8a09a8e 100644 --- a/src/utils/date/time.ts +++ b/src/utils/date/time.ts @@ -39,9 +39,9 @@ export const getRuntime = (ticks: number) => { if (timeMin > 60) { const timeHr = Math.floor(timeMin / 60); timeMin -= timeHr * 60; - formatedTime = `${timeHr}hr ${timeMin}min`; + formatedTime = `${timeHr} ч ${timeMin} мин`; } else { - formatedTime = `${timeMin}min`; + formatedTime = `${timeMin} мин`; } return formatedTime; }; @@ -61,15 +61,15 @@ export const getRuntimeMusic = (ticks: number) => { if (timeMin > 60) { const timeHr = Math.floor(timeMin / 60); timeMin -= timeHr * 60; - formatedTime = `${timeHr}:${timeMin.toLocaleString([], { + formatedTime = `${timeHr}:${timeMin.toLocaleString("ru-RU", { minimumIntegerDigits: 2, useGrouping: false, - })}:${timeSec.toLocaleString([], { + })}:${timeSec.toLocaleString("ru-RU", { minimumIntegerDigits: 2, useGrouping: false, })}`; } else { - formatedTime = `${timeMin}:${timeSec.toLocaleString([], { + formatedTime = `${timeMin}:${timeSec.toLocaleString("ru-RU", { minimumIntegerDigits: 2, useGrouping: false, })}`; @@ -91,9 +91,9 @@ export const getRuntimeFull = (ticks: number) => { if (timeMin > 60) { const timeHr = Math.floor(timeMin / 60); timeMin -= timeHr * 60; - formatedTime = `${timeHr} hour ${timeMin} minutes`; + formatedTime = `${timeHr} ч ${timeMin} мин`; } else { - formatedTime = `${timeMin} minutes`; + formatedTime = `${timeMin} мин`; } return formatedTime; }; @@ -112,9 +112,9 @@ export const getRuntimeCompact = (ticks: number) => { if (timeMin > 60) { const timeHr = Math.floor(timeMin / 60); timeMin -= timeHr * 60; - formatedTime = `${timeHr}h ${timeMin}m`; + formatedTime = `${timeHr} ч ${timeMin} мин`; } else { - formatedTime = `${timeMin}m`; + formatedTime = `${timeMin} мин`; } return formatedTime; }; @@ -129,11 +129,11 @@ export const endsAt = (ticks: number) => { const currentTime = current.getTime(); const time = ticksToMs(ticks); const calculatedTime = currentTime + time; - const formated = new Date(calculatedTime).toLocaleString([], { + const formated = new Date(calculatedTime).toLocaleString("ru-RU", { hour: "2-digit", minute: "2-digit", }); // let formated = `${hr - 12}:${min}`; // return `Ends at ${formated.getHours()}:${formated.getMinutes()}`; - return `Ends at ${formated}`; + return `Конец в ${formated}`; }; diff --git a/src/utils/methods/mediaSegments.ts b/src/utils/methods/mediaSegments.ts new file mode 100644 index 0000000..029629d --- /dev/null +++ b/src/utils/methods/mediaSegments.ts @@ -0,0 +1,116 @@ +import type { + BaseItemDto, + MediaSegmentDto, + MediaSegmentDtoQueryResult, + MediaSegmentType, +} from "@jellyfin/sdk/lib/generated-client"; + +const SEGMENT_MATCHERS: Array<{ + type: MediaSegmentType; + pattern: RegExp; +}> = [ + { + type: "Intro", + pattern: + /(intro|opening|title sequence|main title|заставк|опенинг|вступлен|начальн[а-яё]* титр)/i, + }, + { + type: "Recap", + pattern: + /(recap|previously on|previously|ранее|в предыдущ|напоминание|краткое содержание)/i, + }, + { + type: "Outro", + pattern: + /(outro|end credits|closing credits|end titles|closing titles|credits|ending|титр|концовк|финальн|завершен)/i, + }, + { + type: "Preview", + pattern: + /(preview|next episode|next time|on the next|анонс|следующ[а-яё]* сери|превью)/i, + }, + { + type: "Commercial", + pattern: /(commercial|ad break|реклам)/i, + }, +]; + +const detectSegmentType = (name?: string | null) => { + if (!name) return null; + for (const matcher of SEGMENT_MATCHERS) { + if (matcher.pattern.test(name)) return matcher.type; + } + return null; +}; + +const overlaps = (a: MediaSegmentDto, b: MediaSegmentDto) => { + const aStart = a.StartTicks ?? 0; + const aEnd = a.EndTicks ?? aStart; + const bStart = b.StartTicks ?? 0; + const bEnd = b.EndTicks ?? bStart; + return aStart < bEnd && bStart < aEnd; +}; + +/** + * Jellyfin's MediaSegments API needs a server-side segment provider. Many + * libraries only have chapter markers, so derive the standard segment types + * from well-known chapter names (Recap, Opening Credits, End Credits, ...). + * Existing API segments win; chapters only fill in the gaps. + */ +export const addSegmentsFromChapters = ( + item: BaseItemDto | undefined, + mediaSegments: MediaSegmentDtoQueryResult | undefined, + runtimeTicks?: number | null, +): MediaSegmentDtoQueryResult | undefined => { + const chapters = (item?.Chapters ?? []) + .filter((chapter) => typeof chapter.StartPositionTicks === "number") + .sort((a, b) => (a.StartPositionTicks ?? 0) - (b.StartPositionTicks ?? 0)); + if (chapters.length === 0) return mediaSegments; + + const derived: MediaSegmentDto[] = []; + const seen = new Set(); + + for (let index = 0; index < chapters.length; index++) { + const chapter = chapters[index]; + const type = detectSegmentType(chapter.Name); + if (!type) continue; + + const start = chapter.StartPositionTicks ?? 0; + let end = + chapters + .slice(index + 1) + .find((next) => (next.StartPositionTicks ?? 0) > start) + ?.StartPositionTicks ?? undefined; + end ??= runtimeTicks ?? item?.RunTimeTicks ?? undefined; + if (!end || end <= start) continue; + + const key = `${type}:${start}`; + if (seen.has(key)) continue; + seen.add(key); + + derived.push({ + Id: `chapter-${type.toLowerCase()}-${start}`, + ItemId: item?.Id, + Type: type, + StartTicks: start, + EndTicks: end, + }); + } + + if (derived.length === 0) return mediaSegments; + + const merged: MediaSegmentDto[] = [...(mediaSegments?.Items ?? [])]; + for (const segment of derived) { + if (merged.some((existing) => overlaps(existing, segment))) continue; + merged.push(segment); + } + if (merged.length === 0) return mediaSegments; + + merged.sort((a, b) => (a.StartTicks ?? 0) - (b.StartTicks ?? 0)); + return { + ...mediaSegments, + Items: merged, + TotalRecordCount: merged.length, + StartIndex: 0, + }; +}; diff --git a/src/utils/methods/pictureInPicture.ts b/src/utils/methods/pictureInPicture.ts new file mode 100644 index 0000000..f338ad6 --- /dev/null +++ b/src/utils/methods/pictureInPicture.ts @@ -0,0 +1,102 @@ +type WebKitPresentationMode = "inline" | "fullscreen" | "picture-in-picture"; + +type WebKitVideoElement = HTMLVideoElement & { + webkitPresentationMode?: WebKitPresentationMode; + webkitSupportsPresentationMode?: (mode: WebKitPresentationMode) => boolean; + webkitSetPresentationMode?: (mode: WebKitPresentationMode) => void; +}; + +const asWebKitVideo = (video: HTMLVideoElement) => video as WebKitVideoElement; + +const isVideoElement = ( + element: Element | null | undefined, +): element is HTMLVideoElement => element?.tagName === "VIDEO"; + +/** + * ReactPlayer may render HLS video inside the shadow DOM of ``. + * Fall back to a regular video element for direct play and other containers. + */ +export const getPlayerVideoElement = (): HTMLVideoElement | null => { + if (typeof document === "undefined") return null; + + const shadowVideo = document + .querySelector("hls-video") + ?.shadowRoot?.querySelector("video"); + if (isVideoElement(shadowVideo)) return shadowVideo; + + const video = + document.querySelector(".video-player video") ?? + document.querySelector("video"); + return isVideoElement(video) ? video : null; +}; + +export const supportsPictureInPicture = ( + video?: HTMLVideoElement | null, +): boolean => { + if (typeof document === "undefined") return false; + if (document.pictureInPictureEnabled) return true; + + const candidate = + video ?? (document.createElement("video") as WebKitVideoElement); + try { + return Boolean( + asWebKitVideo(candidate).webkitSupportsPresentationMode?.( + "picture-in-picture", + ), + ); + } catch { + return false; + } +}; + +const isPictureInPictureElement = ( + element: Element | null, + video: HTMLVideoElement, +): boolean => { + if (!element) return false; + if (element === video) return true; + const root = video.getRootNode(); + return root instanceof ShadowRoot && root.host === element; +}; + +export const isPictureInPictureActive = (video: HTMLVideoElement): boolean => { + if (typeof document === "undefined") return false; + if (isPictureInPictureElement(document.pictureInPictureElement, video)) { + return true; + } + return asWebKitVideo(video).webkitPresentationMode === "picture-in-picture"; +}; + +export const togglePictureInPicture = async ( + video: HTMLVideoElement, +): Promise => { + if (isPictureInPictureActive(video)) { + if (isPictureInPictureElement(document.pictureInPictureElement, video)) { + await document.exitPictureInPicture(); + return; + } + + const webkitVideo = asWebKitVideo(video); + if (webkitVideo.webkitSetPresentationMode) { + webkitVideo.webkitSetPresentationMode("inline"); + return; + } + return; + } + + if ( + document.pictureInPictureEnabled && + typeof video.requestPictureInPicture === "function" + ) { + await video.requestPictureInPicture(); + return; + } + + const webkitVideo = asWebKitVideo(video); + if (webkitVideo.webkitSupportsPresentationMode?.("picture-in-picture")) { + webkitVideo.webkitSetPresentationMode?.("picture-in-picture"); + return; + } + + throw new Error("Picture-in-picture is not supported"); +}; diff --git a/src/utils/methods/startPlayback.ts b/src/utils/methods/startPlayback.ts index a6e99ea..f3b0b71 100644 --- a/src/utils/methods/startPlayback.ts +++ b/src/utils/methods/startPlayback.ts @@ -99,7 +99,7 @@ export const startPlaybackFromIds = async ( }); if (!playback.mediaSource?.MediaSources?.[0]?.Id) { - throw new Error("No playable media source found"); + throw new Error("Не найден источник для воспроизведения"); } const playbackItems: BaseItemDto[] = playback.item?.Items ?? []; diff --git a/src/utils/methods/syncPlay.ts b/src/utils/methods/syncPlay.ts index a1fce3d..a326856 100644 --- a/src/utils/methods/syncPlay.ts +++ b/src/utils/methods/syncPlay.ts @@ -83,7 +83,7 @@ export const createSyncPlayGroup = async (api: Api, name: string) => { try { const group = ( await syncApi(api).syncPlayCreateGroup({ - newGroupRequestDto: { GroupName: name.trim() || "Watch together" }, + newGroupRequestDto: { GroupName: name.trim() || "Смотреть вместе" }, }) ).data; if (group) { @@ -97,7 +97,7 @@ export const createSyncPlayGroup = async (api: Api, name: string) => { return group; } catch (error) { console.error("Could not create SyncPlay group", error); - store.setError("Could not create a group"); + store.setError("Не удалось создать группу"); return undefined; } finally { store.setLoading(false); @@ -122,7 +122,7 @@ export const joinSyncPlayGroup = async (api: Api, groupId: string) => { await refreshSyncPlayGroups(api); } catch (error) { console.error("Could not join SyncPlay group", error); - store.setError("Could not join this group"); + store.setError("Не удалось войти в группу"); } finally { store.setLoading(false); } @@ -151,7 +151,7 @@ export const startSyncPlayQueue = async (api: Api) => { .map((item) => item.Id) .filter((id): id is string => Boolean(id)); if (ids.length === 0) { - store.setError("Start something first, then share the queue"); + store.setError("Сначала включите что-нибудь, затем поделитесь очередью"); return; } const position = getLocalPlayback(); @@ -173,7 +173,7 @@ export const startSyncPlayQueue = async (api: Api) => { } } catch (error) { console.error("Could not start SyncPlay queue", error); - store.setError("Could not start the group queue"); + store.setError("Не удалось запустить очередь группы"); } finally { store.setLoading(false); } @@ -205,7 +205,7 @@ export const watchSyncPlayQueueHere = async (api: Api, userId: string) => { } } catch (error) { console.error("Could not start the group queue here", error); - store.setError("Could not start playback"); + store.setError("Не удалось запустить воспроизведение"); } finally { store.setLoading(false); } @@ -364,7 +364,7 @@ export const handleSyncPlayGroupUpdate = async ( applyingRemoteUntil = 0; break; case "LibraryAccessDenied": - useSyncPlayStore.getState().setError("No access to this group's library"); + useSyncPlayStore.getState().setError("Нет доступа к библиотеке группы"); break; } }; diff --git a/src/utils/storage/player.ts b/src/utils/storage/player.ts index 18f073b..1e02de6 100644 --- a/src/utils/storage/player.ts +++ b/src/utils/storage/player.ts @@ -1,4 +1,5 @@ import { load } from "@tauri-apps/plugin-store"; +import type { VideoFitMode } from "../types/videoFitMode"; const PlayerStore = await load(".player.dat", { autoSave: true }); @@ -31,3 +32,13 @@ export const getAutoSkipSegments = async () => { const value = await PlayerStore.get("video.autoSkipSegments"); return value ?? false; }; + +export const setVideoFitMode = async (mode: VideoFitMode) => { + await PlayerStore.set("video.fitMode", mode); + await PlayerStore.save(); +}; + +export const getVideoFitMode = async (): Promise => { + const value = await PlayerStore.get("video.fitMode"); + return value === "fill" || value === "stretch" ? value : "fit"; +}; diff --git a/src/utils/storage/settings.ts b/src/utils/storage/settings.ts index 2e55b50..73fd589 100644 --- a/src/utils/storage/settings.ts +++ b/src/utils/storage/settings.ts @@ -23,9 +23,9 @@ export const allSettings = { general: [ { key: "general.enable_skip_intro_outro", - name: "Enable Intro-Skipper plugin", + name: "Включить плагин Intro-Skipper", description: - "Shows a skip button for Intros and End Credit scenes in an episode. Note: this requires jumoog/intro-skipper plugin to be installed on server", + "Показывает кнопку пропуска интро и титров в сериях. Для этого на сервере должен быть установлен плагин jumoog/intro-skipper.", }, ], }; \ No newline at end of file diff --git a/src/utils/store/playback.ts b/src/utils/store/playback.ts index 1f5190d..d974bda 100644 --- a/src/utils/store/playback.ts +++ b/src/utils/store/playback.ts @@ -1,11 +1,13 @@ import type { Api } from "@jellyfin/sdk"; import { type BaseItemDto, + ItemFields, type MediaSegmentDtoQueryResult, type MediaStream, type PlaybackInfoResponse, PlayMethod, } from "@jellyfin/sdk/lib/generated-client"; +import { getLibraryApi } from "@jellyfin/sdk/lib/utils/api/library-api"; import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api"; import { getMediaSegmentApi } from "@jellyfin/sdk/lib/utils/api/media-segment-api"; import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api"; @@ -17,6 +19,7 @@ import { shallow } from "zustand/shallow"; import { createWithEqualityFn } from "zustand/traditional"; import { secToTicks, ticksToSec } from "../date/time"; import getSubtitle from "../methods/getSubtitles"; +import { addSegmentsFromChapters } from "../methods/mediaSegments"; import playbackProfile from "../playback-profiles"; import { getPlayerMuted, @@ -377,7 +380,7 @@ export const usePlaybackStore = create< const activeSegment = metadata.mediaSegments?.Items?.find( (s) => s.Id === activeSegmentId, ); - if (activeSegment && ticks > (activeSegment.EndTicks ?? ticks)) { + if (activeSegment && ticks >= (activeSegment.EndTicks ?? ticks)) { // If the current time is past the active segment's end time, clear it. set((state) => { state.activeSegmentId = null; @@ -650,7 +653,7 @@ export const usePlaybackStore = create< } const segment = segments.find( (s) => - (s.StartTicks ?? ticks) <= ticks && (s.EndTicks ?? ticks) >= ticks, + (s.StartTicks ?? ticks) <= ticks && (s.EndTicks ?? ticks) > ticks, ); const nextIndex = segments.findIndex( (s) => (s.StartTicks ?? ticks) > ticks, @@ -735,6 +738,29 @@ export const initializePlayback = async (args: { const source = mediaSource.MediaSources[0]; const currentUser = (await getUserApi(api).getCurrentUser()).data; + let chapters = item.Chapters; + if (!Array.isArray(chapters) && !mediaSegments?.Items?.length && item.Id) { + try { + const fullItem = ( + await getLibraryApi(api).getItems({ + ids: [item.Id], + userId, + fields: [ItemFields.Chapters], + }) + ).data.Items?.[0]; + chapters = fullItem?.Chapters; + } catch (error) { + console.warn("Не удалось загрузить главы для сегментов", error); + } + } + const segments = addSegmentsFromChapters( + Array.isArray(chapters) && chapters !== item.Chapters + ? { ...item, Chapters: chapters } + : item, + mediaSegments, + item.RunTimeTicks ?? source.RunTimeTicks, + ); + let itemName = item.Name; let episodeTitle = ""; if (item.SeriesId && item.SeriesName) { @@ -819,7 +845,7 @@ export const initializePlayback = async (args: { isEpisode: !!item.SeriesId, itemDuration: item.RunTimeTicks ?? 0, item: item, - mediaSegments: mediaSegments, + mediaSegments: segments, userDataLastPlayedPositionTicks: startPositionTicks ?? item.UserData?.PlaybackPositionTicks ?? 0, }, diff --git a/src/utils/types/videoFitMode.ts b/src/utils/types/videoFitMode.ts new file mode 100644 index 0000000..822f5fc --- /dev/null +++ b/src/utils/types/videoFitMode.ts @@ -0,0 +1 @@ +export type VideoFitMode = "fit" | "fill" | "stretch";