mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-29 19:36:20 -05:00
Refactoring videos and archives UI paths for consistent scheme.
This commit is contained in:
parent
aefc7b1def
commit
66a891c759
33 changed files with 208 additions and 225 deletions
|
|
@ -2,7 +2,7 @@ import React, {useContext} from 'react';
|
|||
import './App.css';
|
||||
import {NavBar} from "./components/Nav";
|
||||
import {createBrowserRouter, createRoutesFromElements, Link, Outlet, Route, RouterProvider} from "react-router";
|
||||
import {VideosRoute, VideoWrapper} from "./components/Videos";
|
||||
import {VideosTabLayout, VideosPage, VideosSettingsPage, VideosStatistics, VideoWrapper} from "./components/Videos";
|
||||
import AdminRoute from "./components/admin/AdminRoute";
|
||||
import {Container} from "semantic-ui-react";
|
||||
import 'semantic-ui-offline/semantic.min.css';
|
||||
|
|
@ -12,6 +12,7 @@ import {ArchiveRoute} from "./components/Archive";
|
|||
import {FilesRoute} from "./components/Files";
|
||||
import {QueryProvider, StatusProvider} from "./hooks/customHooks";
|
||||
import {FileWorkerStatusProvider} from "./contexts/FileWorkerStatusContext";
|
||||
import {ChannelEditPage, ChannelNewPage, ChannelsPage} from "./components/Channels";
|
||||
import {MapRoute} from "./components/Map";
|
||||
import {MediaContextProvider, mediaStyles, StatusContext, ThemeContext} from "./contexts/contexts";
|
||||
import {Header, ThemeProvider} from "./components/Theme";
|
||||
|
|
@ -84,13 +85,22 @@ const router = createBrowserRouter(createRoutesFromElements(<Route
|
|||
<Route index element={<ErrorBoundary><DashboardPage/></ErrorBoundary>}/>
|
||||
<Route path='search/*' element={<ErrorBoundary><DashboardPage/></ErrorBoundary>}/>
|
||||
<Route path='donate' element={<DonatePage/>}/>
|
||||
<Route path='videos/video/:videoId' exact element={<ErrorBoundary><VideoWrapper/></ErrorBoundary>}/>
|
||||
<Route path='videos/channel/:channelId/video/:videoId' exact element={<ErrorBoundary><VideoWrapper/></ErrorBoundary>}/>
|
||||
<Route path="videos/*" element={<ErrorBoundary><VideosRoute/></ErrorBoundary>}/>
|
||||
<Route path='videos'>
|
||||
<Route element={<ErrorBoundary><VideosTabLayout/></ErrorBoundary>}>
|
||||
<Route index element={<ErrorBoundary><VideosPage/></ErrorBoundary>}/>
|
||||
<Route path='channel' element={<ErrorBoundary><ChannelsPage/></ErrorBoundary>}/>
|
||||
<Route path='channel/new' element={<ErrorBoundary><ChannelNewPage/></ErrorBoundary>}/>
|
||||
<Route path='channel/:channelId/edit' element={<ErrorBoundary><ChannelEditPage/></ErrorBoundary>}/>
|
||||
<Route path='channel/:channelId/video' element={<ErrorBoundary><VideosPage/></ErrorBoundary>}/>
|
||||
<Route path='settings' element={<ErrorBoundary><VideosSettingsPage/></ErrorBoundary>}/>
|
||||
<Route path='statistics' element={<ErrorBoundary><VideosStatistics/></ErrorBoundary>}/>
|
||||
</Route>
|
||||
<Route path=':fileGroupId' element={<ErrorBoundary><VideoWrapper/></ErrorBoundary>}/>
|
||||
</Route>
|
||||
<Route path="admin/*" element={<ErrorBoundary><AdminRoute/></ErrorBoundary>}/>
|
||||
<Route path="more/*" element={<ErrorBoundary><MoreRoute/></ErrorBoundary>}/>
|
||||
<Route path="inventory/*" element={<ErrorBoundary><InventoryRoute/></ErrorBoundary>}/>
|
||||
<Route path='archive/*' element={<ErrorBoundary><ArchiveRoute/></ErrorBoundary>}/>
|
||||
<Route path='archives/*' element={<ErrorBoundary><ArchiveRoute/></ErrorBoundary>}/>
|
||||
<Route path='docs/*' element={<ErrorBoundary><DocsRoute/></ErrorBoundary>}/>
|
||||
<Route path='map/*' element={<ErrorBoundary><MapRoute/></ErrorBoundary>}/>
|
||||
<Route path='zim/*' element={<ErrorBoundary><ZimRoute/></ErrorBoundary>}/>
|
||||
|
|
|
|||
|
|
@ -225,30 +225,30 @@ export async function searchVideos(offset, limit, channelId, searchStr, order_by
|
|||
}
|
||||
}
|
||||
|
||||
export async function getVideo(video_id) {
|
||||
const response = await apiGet(`${VIDEOS_API}/video/${video_id}`);
|
||||
export async function getVideo(fileGroupId) {
|
||||
const response = await apiGet(`${VIDEOS_API}/${fileGroupId}`);
|
||||
let data = await response.json();
|
||||
return [data['file_group'], data['prev'], data['next']];
|
||||
}
|
||||
|
||||
export async function getVideoComments(videoId) {
|
||||
const response = await apiGet(`${VIDEOS_API}/video/${videoId}/comments`);
|
||||
export async function getVideoComments(fileGroupId) {
|
||||
const response = await apiGet(`${VIDEOS_API}/${fileGroupId}/comments`);
|
||||
let data = await response.json();
|
||||
return {
|
||||
comments: data.comments,
|
||||
}
|
||||
}
|
||||
|
||||
export async function getVideoCaptions(videoId) {
|
||||
const response = await apiGet(`${VIDEOS_API}/video/${videoId}/captions`);
|
||||
export async function getVideoCaptions(fileGroupId) {
|
||||
const response = await apiGet(`${VIDEOS_API}/${fileGroupId}/captions`);
|
||||
let data = await response.json();
|
||||
return {
|
||||
captions: data.captions,
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteVideos(videoIds) {
|
||||
if (!videoIds || videoIds.length === 0) {
|
||||
export async function deleteVideos(fileGroupIds) {
|
||||
if (!fileGroupIds || fileGroupIds.length === 0) {
|
||||
toast({
|
||||
type: 'error',
|
||||
title: 'Empty request',
|
||||
|
|
@ -256,9 +256,9 @@ export async function deleteVideos(videoIds) {
|
|||
time: 5000,
|
||||
});
|
||||
}
|
||||
console.info(`Deleting Videos: ${videoIds}`);
|
||||
const i = videoIds.join(',');
|
||||
const response = await apiDelete(`${VIDEOS_API}/video/${i}`);
|
||||
console.info(`Deleting Videos: ${fileGroupIds}`);
|
||||
const i = fileGroupIds.join(',');
|
||||
const response = await apiDelete(`${VIDEOS_API}/${i}`);
|
||||
if (response.status !== 204) {
|
||||
const message = await getErrorMessage(response, 'Failed to delete videos.');
|
||||
toast({
|
||||
|
|
@ -746,7 +746,7 @@ export async function deleteArchives(archiveIds) {
|
|||
}
|
||||
console.log(`Deleting Archives: ${archiveIds}`);
|
||||
let i = archiveIds.join(',');
|
||||
const response = await apiDelete(`${API_URI}/archive/${i}`);
|
||||
const response = await apiDelete(`${ARCHIVES_API}/${i}`);
|
||||
if (!response.ok) {
|
||||
const message = await getErrorMessage(response, 'Failed to delete archives');
|
||||
toast({
|
||||
|
|
@ -1110,8 +1110,8 @@ export async function fetchCollectionConflicts(collectionId) {
|
|||
}
|
||||
}
|
||||
|
||||
export async function getArchive(archiveId) {
|
||||
const response = await apiGet(`${ARCHIVES_API}/${archiveId}`);
|
||||
export async function getArchive(fileGroupId) {
|
||||
const response = await apiGet(`${ARCHIVES_API}/${fileGroupId}`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
return {
|
||||
|
|
@ -1126,8 +1126,8 @@ export async function getArchive(archiveId) {
|
|||
}
|
||||
}
|
||||
|
||||
export async function generateArchiveScreenshot(archiveId) {
|
||||
const response = await apiPost(`${ARCHIVES_API}/${archiveId}/generate_screenshot`);
|
||||
export async function generateArchiveScreenshot(fileGroupId) {
|
||||
const response = await apiPost(`${ARCHIVES_API}/${fileGroupId}/generate_screenshot`);
|
||||
if (response.ok) {
|
||||
toast({
|
||||
type: 'success',
|
||||
|
|
|
|||
|
|
@ -104,8 +104,8 @@ function archiveFileLink(path, directory = false) {
|
|||
|
||||
function ArchivePage() {
|
||||
const navigate = useNavigate();
|
||||
const {archiveId} = useParams();
|
||||
const {archiveFile, history, fetchArchive} = useArchive(archiveId);
|
||||
const {fileGroupId} = useParams();
|
||||
const {archiveFile, history, fetchArchive} = useArchive(fileGroupId);
|
||||
const {theme} = useContext(ThemeContext);
|
||||
|
||||
let title = archiveFile ? archiveFile.title ? archiveFile.title : archiveFile.name : null;
|
||||
|
|
@ -144,7 +144,7 @@ function ArchivePage() {
|
|||
null;
|
||||
|
||||
const localDeleteArchive = async () => {
|
||||
await deleteArchives([data.id]);
|
||||
await deleteArchives([archiveFile.id]);
|
||||
toast({
|
||||
type: 'success',
|
||||
title: 'Archive Deleted',
|
||||
|
|
@ -168,7 +168,7 @@ function ArchivePage() {
|
|||
}
|
||||
|
||||
const localGenerateScreenshot = async () => {
|
||||
const success = await generateArchiveScreenshot(data.id);
|
||||
const success = await generateArchiveScreenshot(archiveFile.id);
|
||||
if (success) {
|
||||
// Refresh the archive data after a short delay to show the new screenshot
|
||||
setTimeout(() => fetchArchive(), 2000);
|
||||
|
|
@ -218,7 +218,7 @@ function ArchivePage() {
|
|||
const domain = data.domain ? data.domain : null;
|
||||
let domainHeader = <p>Unknown</p>;
|
||||
if (domain) {
|
||||
const domainUrl = `/archive?domain=${domain}`;
|
||||
const domainUrl = `/archives?domain=${domain}`;
|
||||
domainHeader = <Header as='h4'>
|
||||
<a href={domainUrl}>{domain}</a>
|
||||
</Header>;
|
||||
|
|
@ -364,7 +364,7 @@ export function ArchiveCard({file}) {
|
|||
}
|
||||
|
||||
const domain = data ? data.domain : null;
|
||||
const domainUrl = `/archive?domain=${domain}`;
|
||||
const domainUrl = `/archives?domain=${domain}`;
|
||||
|
||||
const title = file.title || data.url;
|
||||
const header = <ExternalCardLink to={singlefileUrl} className='card-title-ellipsis'>{title}</ExternalCardLink>;
|
||||
|
|
@ -400,7 +400,7 @@ export function ArchiveCard({file}) {
|
|||
}
|
||||
</CardMeta>
|
||||
<CardDescription>
|
||||
<Link to={`/archive/${data.id}`}>
|
||||
<Link to={`/archives/${file.id}`}>
|
||||
<Button icon='file alternate' content='Details'
|
||||
labelPosition='left'/>
|
||||
</Link>
|
||||
|
|
@ -428,9 +428,9 @@ const DOMAIN_COLUMNS = [
|
|||
];
|
||||
|
||||
const DOMAIN_ROUTES = {
|
||||
list: '/archive/domains',
|
||||
edit: '/archive/domain/:id/edit',
|
||||
search: '/archive',
|
||||
list: '/archives/domains',
|
||||
edit: '/archives/domain/:id/edit',
|
||||
search: '/archives',
|
||||
searchParam: 'domain'
|
||||
};
|
||||
|
||||
|
|
@ -606,7 +606,7 @@ export function DomainEditPage() {
|
|||
try {
|
||||
let response = await deleteDomain(parseInt(domainId));
|
||||
if (response.status === 204) {
|
||||
navigate('/archive/domains');
|
||||
navigate('/archives/domains');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to delete domain', e);
|
||||
|
|
@ -663,7 +663,7 @@ export function DomainEditPage() {
|
|||
|
||||
return <>
|
||||
<BackButton/>
|
||||
<Link to={`/archive?domain=${domain?.domain}`}>
|
||||
<Link to={`/archives?domain=${domain?.domain}`}>
|
||||
<Button>Archives</Button>
|
||||
</Link>
|
||||
|
||||
|
|
@ -1185,7 +1185,7 @@ function ArchivesPage() {
|
|||
// Domain header with edit link when filtering by domain
|
||||
let header;
|
||||
if (domainObj && domainObj.domain) {
|
||||
const editLink = `/archive/domain/${domainObj.id}/edit`;
|
||||
const editLink = `/archives/domain/${domainObj.id}/edit`;
|
||||
header = <>
|
||||
<Header as='h1'>
|
||||
{domainObj.domain}
|
||||
|
|
@ -1241,7 +1241,7 @@ export function ArchiveRowCells({file}) {
|
|||
let {sort} = useSearchOrder();
|
||||
sort = sort ? sort.replace(/^-+/, '') : null;
|
||||
|
||||
const archiveUrl = `/archive/${data.id}`;
|
||||
const archiveUrl = `/archives/${file.id}`;
|
||||
const posterPath = findPosterPath(file);
|
||||
const posterUrl = posterPath ? `/media/${encodeMediaPath(posterPath)}` : null;
|
||||
|
||||
|
|
@ -1340,17 +1340,17 @@ export function ArchiveRoute() {
|
|||
const links = [
|
||||
{
|
||||
text: 'Archives',
|
||||
to: '/archive',
|
||||
to: '/archives',
|
||||
end: true,
|
||||
isActive: () => path === '/archive' || /^\/archive\/\d+$/.test(path)
|
||||
isActive: () => path === '/archives' || /^\/archives\/\d+$/.test(path)
|
||||
},
|
||||
{
|
||||
text: 'Domains',
|
||||
to: '/archive/domains',
|
||||
isActive: () => path.startsWith('/archive/domain')
|
||||
to: '/archives/domains',
|
||||
isActive: () => path.startsWith('/archives/domain')
|
||||
},
|
||||
{text: 'Settings', to: '/archive/settings'},
|
||||
{text: 'Statistics', to: '/archive/statistics'},
|
||||
{text: 'Settings', to: '/archives/settings'},
|
||||
{text: 'Statistics', to: '/archives/statistics'},
|
||||
];
|
||||
return <PageContainer>
|
||||
<TabLinks links={links}/>
|
||||
|
|
@ -1360,7 +1360,7 @@ export function ArchiveRoute() {
|
|||
<Route path='domain/:domainId/edit' element={<DomainEditPage/>}/>
|
||||
<Route path='settings' element={<ArchiveSettingsPage/>}/>
|
||||
<Route path='statistics' element={<ArchiveStatistics/>}/>
|
||||
<Route path=':archiveId' element={<ArchivePage/>}/>
|
||||
<Route path=':fileGroupId' element={<ArchivePage/>}/>
|
||||
</Routes>
|
||||
</PageContainer>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -82,13 +82,10 @@ export const Headlines = ({results}) => {
|
|||
const {model, data, video} = result;
|
||||
|
||||
if (model === 'video' && !_.isEmpty(video)) {
|
||||
const {channel} = video;
|
||||
const video_url = channel
|
||||
? `/videos/channel/${channel.id}/video/${video.id}`
|
||||
: `/videos/video/${video.id}`;
|
||||
const video_url = `/videos/${result.id}`;
|
||||
headlines = [...headlines, <FileHeadline key={result['key']} file={result} to={video_url}/>];
|
||||
} else if (model === 'archive' && !_.isEmpty(data)) {
|
||||
headlines = [...headlines, <FileHeadline key={result['key']} file={result} to={`/archive/${data.id}`}/>];
|
||||
headlines = [...headlines, <FileHeadline key={result['key']} file={result} to={`/archives/${result.id}`}/>];
|
||||
} else {
|
||||
headlines = [...headlines, <FileHeadline key={result['key']} file={result}/>];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ export const SHORTCUTS = [
|
|||
// Navigation (g+ sequences)
|
||||
{keys: 'g h', description: 'Go to Home', category: 'Navigation', path: '/'},
|
||||
{keys: 'g v', description: 'Go to Videos', category: 'Navigation', path: '/videos'},
|
||||
{keys: 'g a', description: 'Go to Archives', category: 'Navigation', path: '/archive'},
|
||||
{keys: 'g a', description: 'Go to Archives', category: 'Navigation', path: '/archives'},
|
||||
{keys: 'g m', description: 'Go to Map', category: 'Navigation', path: '/map'},
|
||||
{keys: 'g z', description: 'Go to Zim', category: 'Navigation', path: '/zim'},
|
||||
{keys: 'g f', description: 'Go to Files', category: 'Navigation', path: '/files'},
|
||||
|
|
@ -164,7 +164,7 @@ export function KeyboardShortcutsProvider({children}) {
|
|||
const NAV_KEYS = {
|
||||
'h': '/',
|
||||
'v': '/videos',
|
||||
'a': '/archive',
|
||||
'a': '/archives',
|
||||
'm': '/map',
|
||||
'z': '/zim',
|
||||
'f': '/files',
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ function updateFavicon(colorName) {
|
|||
|
||||
const links = [
|
||||
{text: 'Videos', to: '/videos', key: 'videos'},
|
||||
{text: 'Archive', to: '/archive', key: 'archive'},
|
||||
{text: 'Archive', to: '/archives', key: 'archive'},
|
||||
{text: 'Docs', to: '/docs', key: 'docs'},
|
||||
{text: 'Map', to: '/map', key: 'map'},
|
||||
{text: 'Zim', to: '/zim', key: 'zim'},
|
||||
|
|
@ -208,7 +208,7 @@ export function NavBar() {
|
|||
if (collectionKind === 'channel') {
|
||||
processingLink = `/videos/channel/${collectionId}/edit`;
|
||||
} else if (collectionKind === 'domain') {
|
||||
processingLink = `/archive/domain/${collectionId}/edit`;
|
||||
processingLink = `/archives/domain/${collectionId}/edit`;
|
||||
} else {
|
||||
processingLink = '/files';
|
||||
}
|
||||
|
|
@ -217,7 +217,7 @@ export function NavBar() {
|
|||
if (collectionKind === 'channel') {
|
||||
processingLink = '/videos/settings';
|
||||
} else if (collectionKind === 'domain') {
|
||||
processingLink = '/archive/settings';
|
||||
processingLink = '/archives/settings';
|
||||
} else {
|
||||
processingLink = '/files';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,8 +21,8 @@ const SUGGESTED_APPS = [
|
|||
{location: '/admin/settings', title: 'Shutdown', description: 'Shutdown your WROLPi'},
|
||||
{location: '/admin/status', title: 'Status', description: 'View the status of this WROLPi server'},
|
||||
{location: '/admin/wrol', title: 'WROL Mode', description: 'Enable or disable WROL Mode'},
|
||||
{location: '/archive', title: 'Archives', description: 'View your Archives'},
|
||||
{location: '/archive/domains', title: 'Domains', description: 'View the domains of your Archives'},
|
||||
{location: '/archives', title: 'Archives', description: 'View your Archives'},
|
||||
{location: '/archives/domains', title: 'Domains', description: 'View the domains of your Archives'},
|
||||
{location: '/files', title: 'Files', description: 'View your files'},
|
||||
{location: '/help', title: 'Help', description: 'Help documents for WROLPi'},
|
||||
{location: '/inventory', title: 'Inventory', description: 'Track and organize your food storage'},
|
||||
|
|
@ -273,7 +273,7 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames, anyTag)
|
|||
title: i.domain,
|
||||
id: i.id,
|
||||
domain: i.domain,
|
||||
location: `/archive?domain=${i.domain}`
|
||||
location: `/archives?domain=${i.domain}`
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -175,16 +175,7 @@ const Comments = ({comments, video}) => {
|
|||
// Generate a video page URL for a file object.
|
||||
function getVideoLink(file) {
|
||||
if (!file || !file.video) return null;
|
||||
const {video} = file;
|
||||
const channel = video.channel ? video.channel : null;
|
||||
|
||||
if (file.slug) {
|
||||
return `/videos/video/${file.slug}`;
|
||||
} else if (channel) {
|
||||
return `/videos/channel/${channel.id}/video/${video.id}`;
|
||||
} else {
|
||||
return `/videos/video/${video.id}`;
|
||||
}
|
||||
return `/videos/${file.id}`;
|
||||
}
|
||||
|
||||
function VideoPage({videoFile, prevFile, nextFile, fetchVideo, ...props}) {
|
||||
|
|
@ -463,7 +454,7 @@ function VideoPage({videoFile, prevFile, nextFile, fetchVideo, ...props}) {
|
|||
color='red'
|
||||
confirmContent='Are you sure you want to delete this video? All files related to this video will be deleted. It will not be downloaded again!'
|
||||
confirmButton='Delete'
|
||||
onClick={async () => await handleDeleteVideo(video.id)}
|
||||
onClick={async () => await handleDeleteVideo(videoFile.id)}
|
||||
obeyWROLMode={true}
|
||||
>Delete</APIButton>
|
||||
<APIButton
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import React, {useContext, useEffect, useRef, useState} from 'react';
|
||||
import {Link, Route, Routes, useParams} from "react-router";
|
||||
import {Link, Outlet, useParams} from "react-router";
|
||||
import {useHotkeys} from "react-hotkeys-hook";
|
||||
import {
|
||||
APIButton,
|
||||
|
|
@ -46,7 +46,6 @@ import {
|
|||
StatisticValue,
|
||||
TableCell
|
||||
} from "semantic-ui-react";
|
||||
import {ChannelEditPage, ChannelNewPage, ChannelsPage} from "./Channels";
|
||||
import {useChannel, useSearchOrder, useSearchVideos, useVideo, useVideoStatistics} from "../hooks/customHooks";
|
||||
import {FileRowTagIcon, FilesView} from "./Files";
|
||||
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
|
||||
|
|
@ -72,17 +71,17 @@ import {VideoFormatSelectorForm, VideoResolutionSelectorForm} from "./Download";
|
|||
import {BatchReorganizeModal} from "./collections/BatchReorganizeModal";
|
||||
|
||||
export function VideoWrapper() {
|
||||
const {videoId} = useParams();
|
||||
const {videoFile, prevFile, nextFile, fetchVideo} = useVideo(videoId);
|
||||
const {fileGroupId} = useParams();
|
||||
const {videoFile, prevFile, nextFile, fetchVideo} = useVideo(fileGroupId);
|
||||
|
||||
// Scroll to the top when videoId changes.
|
||||
useEffect(scrollToTop, [videoId]);
|
||||
// Scroll to the top when fileGroupId changes.
|
||||
useEffect(scrollToTop, [fileGroupId]);
|
||||
|
||||
return <VideoPage videoFile={videoFile} prevFile={prevFile} nextFile={nextFile} fetchVideo={fetchVideo}
|
||||
autoplay={true}/>
|
||||
}
|
||||
|
||||
function VideosPage() {
|
||||
export function VideosPage() {
|
||||
|
||||
const {channelId} = useParams();
|
||||
const {searchParams} = React.useContext(QueryContext);
|
||||
|
|
@ -156,8 +155,8 @@ function VideosPage() {
|
|||
}
|
||||
|
||||
const onDelete = async () => {
|
||||
const videoIds = videos.filter(i => selectedVideos.indexOf(i['primary_path']) >= 0).map(i => i['video']['id']);
|
||||
await deleteVideos(videoIds);
|
||||
const fileGroupIds = videos.filter(i => selectedVideos.indexOf(i['primary_path']) >= 0).map(i => i['id']);
|
||||
await deleteVideos(fileGroupIds);
|
||||
await fetchVideos();
|
||||
setSelectedVideos([]);
|
||||
}
|
||||
|
|
@ -308,7 +307,7 @@ function VideoFileNameForm({form}) {
|
|||
/>
|
||||
}
|
||||
|
||||
function VideosSettingsPage() {
|
||||
export function VideosSettingsPage() {
|
||||
useTitle('Videos Settings');
|
||||
|
||||
const [batchModalOpen, setBatchModalOpen] = useState(false);
|
||||
|
|
@ -767,7 +766,7 @@ function CookiesSettingsSection() {
|
|||
</Segment>;
|
||||
}
|
||||
|
||||
function VideosStatistics() {
|
||||
export function VideosStatistics() {
|
||||
useTitle('Video Statistics');
|
||||
|
||||
const {statistics} = useVideoStatistics();
|
||||
|
|
@ -828,7 +827,7 @@ function VideosStatistics() {
|
|||
</>
|
||||
}
|
||||
|
||||
export function VideosRoute(props) {
|
||||
export function VideosTabLayout() {
|
||||
const links = [
|
||||
{text: 'Videos', to: '/videos', key: 'videos', end: true},
|
||||
{text: 'Channels', to: '/videos/channel', key: 'channel'},
|
||||
|
|
@ -838,16 +837,7 @@ export function VideosRoute(props) {
|
|||
|
||||
return <PageContainer>
|
||||
<TabLinks links={links}/>
|
||||
<Routes>
|
||||
<Route path='/' exact element={<VideosPage/>}/>
|
||||
<Route path='channel' exact element={<ChannelsPage/>}/>
|
||||
<Route path='settings' exact element={<VideosSettingsPage/>}/>
|
||||
<Route path='statistics' exact element={<VideosStatistics/>}/>
|
||||
<Route path='channel/new' exact element={<ChannelNewPage/>}/>
|
||||
<Route path='channel/:channelId/edit' exact element={<ChannelEditPage/>}/>
|
||||
<Route path='channel/:channelId/video' exact element={<VideosPage/>}/>
|
||||
<Route path='/video/:videoSlug' exact element={<VideosPage/>}/>
|
||||
</Routes>
|
||||
<Outlet/>
|
||||
</PageContainer>
|
||||
}
|
||||
|
||||
|
|
@ -858,21 +848,13 @@ export function VideoCard({file}) {
|
|||
const sortField = sort ? sort.replace(/^-/, '') : null;
|
||||
|
||||
// Default to video FilePreview for lone video files.
|
||||
let video_url;
|
||||
let video_url = `/videos/${file.id}`;
|
||||
|
||||
// A video may not have a channel.
|
||||
const channel = video.channel ? video.channel : null;
|
||||
let channel_url = null;
|
||||
if (channel) {
|
||||
// Link to Video in the Channel if possible.
|
||||
channel_url = `/videos/channel/${channel.id}/video`;
|
||||
video_url = `/videos/channel/${channel.id}/video/${video.id}`;
|
||||
} else if (file.files.length > 1) {
|
||||
// No Channel, but the video has multiple files (subtitles, etc.). Use the full VideoPage.
|
||||
video_url = `/videos/video/${video.id}`;
|
||||
}
|
||||
if (file.slug) {
|
||||
video_url = `/videos/video/${file.slug}`;
|
||||
}
|
||||
|
||||
let poster = <CardPoster to={video_url} file={file}/>;
|
||||
|
|
@ -929,7 +911,7 @@ export function VideoRowCells({file}) {
|
|||
let {sort} = useSearchOrder();
|
||||
sort = sort ? sort.replace(/^-+/, '') : null;
|
||||
|
||||
let video_url = `/videos/video/${video.id}`;
|
||||
let video_url = `/videos/${file.id}`;
|
||||
const poster_path = findPosterPath(file);
|
||||
const poster_url = poster_path ? `/media/${encodeMediaPath(poster_path)}` : null;
|
||||
|
||||
|
|
|
|||
|
|
@ -336,7 +336,7 @@ export function BatchReorganizeModal({
|
|||
as={Link}
|
||||
to={kind === 'channel'
|
||||
? `/videos/channel/${status.failed_collection.channel_id || status.failed_collection.id}/edit`
|
||||
: `/archive/domain/${status.failed_collection.id}/edit`
|
||||
: `/archives/domain/${status.failed_collection.id}/edit`
|
||||
}
|
||||
size='small'
|
||||
>
|
||||
|
|
|
|||
|
|
@ -54,9 +54,9 @@ const DOMAIN_COLUMNS = [
|
|||
];
|
||||
|
||||
const DOMAIN_ROUTES = {
|
||||
list: '/archive/domains',
|
||||
edit: '/archive/domain/:id/edit',
|
||||
search: '/archive',
|
||||
list: '/archives/domains',
|
||||
edit: '/archives/domain/:id/edit',
|
||||
search: '/archives',
|
||||
searchParam: 'domain'
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,6 @@ import {humanFileSize, isoDatetimeToString} from '../Common';
|
|||
* - title: string - File title
|
||||
* - model_type: 'video'|'archive' - Type of content
|
||||
* - size: number - File size in bytes
|
||||
* - video_id: number|null - Video ID if model_type is 'video'
|
||||
* - archive_id: number|null - Archive ID if model_type is 'archive'
|
||||
* - poster_path: string|null - Path to thumbnail/poster image
|
||||
* - published_datetime: string|null - ISO datetime string
|
||||
|
|
@ -35,8 +34,8 @@ function ConflictFileCard({file, onDelete, isRecommended}) {
|
|||
setLocalError(null);
|
||||
|
||||
try {
|
||||
if (file.model_type === 'video' && file.video_id) {
|
||||
await deleteVideos([file.video_id]);
|
||||
if (file.model_type === 'video' && file.file_group_id) {
|
||||
await deleteVideos([file.file_group_id]);
|
||||
} else if (file.model_type === 'archive' && file.archive_id) {
|
||||
await deleteArchives([file.archive_id]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,7 +26,6 @@ describe('ConflictResolutionModal', () => {
|
|||
title: 'My Video',
|
||||
model_type: 'video',
|
||||
size: 1024000,
|
||||
video_id: 101,
|
||||
archive_id: null,
|
||||
poster_path: 'videos/old/My Video.jpg',
|
||||
published_datetime: '2024-01-15T10:00:00Z',
|
||||
|
|
@ -38,7 +37,6 @@ describe('ConflictResolutionModal', () => {
|
|||
title: 'My Video',
|
||||
model_type: 'video',
|
||||
size: 2048000,
|
||||
video_id: 102,
|
||||
archive_id: null,
|
||||
poster_path: null,
|
||||
published_datetime: '2024-01-15T10:00:00Z',
|
||||
|
|
@ -109,7 +107,7 @@ describe('ConflictResolutionModal', () => {
|
|||
fireEvent.click(deleteButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.deleteVideos).toHaveBeenCalledWith([101]);
|
||||
expect(api.deleteVideos).toHaveBeenCalledWith([1]);
|
||||
});
|
||||
|
||||
// File should be removed from UI (conflict resolved since only 1 file remains)
|
||||
|
|
@ -136,7 +134,6 @@ describe('ConflictResolutionModal', () => {
|
|||
title: 'Example Page',
|
||||
model_type: 'archive',
|
||||
size: 50000,
|
||||
video_id: null,
|
||||
archive_id: 201,
|
||||
poster_path: null,
|
||||
published_datetime: null,
|
||||
|
|
@ -202,15 +199,15 @@ describe('ConflictResolutionModal', () => {
|
|||
{
|
||||
destination_path: 'videos/path1.mp4',
|
||||
conflicting_files: [
|
||||
{file_group_id: 1, current_path: 'a.mp4', title: 'Video 1', model_type: 'video', video_id: 1},
|
||||
{file_group_id: 2, current_path: 'b.mp4', title: 'Video 1', model_type: 'video', video_id: 2},
|
||||
{file_group_id: 1, current_path: 'a.mp4', title: 'Video 1', model_type: 'video'},
|
||||
{file_group_id: 2, current_path: 'b.mp4', title: 'Video 1', model_type: 'video'},
|
||||
],
|
||||
},
|
||||
{
|
||||
destination_path: 'videos/path2.mp4',
|
||||
conflicting_files: [
|
||||
{file_group_id: 3, current_path: 'c.mp4', title: 'Video 2', model_type: 'video', video_id: 3},
|
||||
{file_group_id: 4, current_path: 'd.mp4', title: 'Video 2', model_type: 'video', video_id: 4},
|
||||
{file_group_id: 3, current_path: 'c.mp4', title: 'Video 2', model_type: 'video'},
|
||||
{file_group_id: 4, current_path: 'd.mp4', title: 'Video 2', model_type: 'video'},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
|
@ -267,7 +264,6 @@ describe('ConflictResolutionModal', () => {
|
|||
title: 'My Video',
|
||||
model_type: 'video',
|
||||
size: 1024000,
|
||||
video_id: 101,
|
||||
quality_rank: 12,
|
||||
},
|
||||
{
|
||||
|
|
@ -276,7 +272,6 @@ describe('ConflictResolutionModal', () => {
|
|||
title: 'My Video',
|
||||
model_type: 'video',
|
||||
size: 2048000,
|
||||
video_id: 102,
|
||||
quality_rank: 5,
|
||||
},
|
||||
],
|
||||
|
|
@ -302,7 +297,6 @@ describe('ConflictResolutionModal', () => {
|
|||
current_path: 'videos/old/My Video.mp4',
|
||||
title: 'My Video',
|
||||
model_type: 'video',
|
||||
video_id: 101,
|
||||
quality_rank: 15,
|
||||
},
|
||||
{
|
||||
|
|
@ -310,7 +304,6 @@ describe('ConflictResolutionModal', () => {
|
|||
current_path: 'videos/new/My Video.mp4',
|
||||
title: 'My Video',
|
||||
model_type: 'video',
|
||||
video_id: 102,
|
||||
quality_rank: 8,
|
||||
},
|
||||
],
|
||||
|
|
|
|||
|
|
@ -420,13 +420,13 @@ export const useDomain = (domainId) => {
|
|||
return {domain, form, fetchDomain: form.fetcher};
|
||||
}
|
||||
|
||||
export const useArchive = (archiveId) => {
|
||||
export const useArchive = (fileGroupId) => {
|
||||
const [archiveFileGroup, setArchiveFileGroup] = useState(null);
|
||||
const [history, setHistory] = useState(null);
|
||||
|
||||
const fetchArchive = async () => {
|
||||
try {
|
||||
const {file_group, history} = await getArchive(archiveId);
|
||||
const {file_group, history} = await getArchive(fileGroupId);
|
||||
setArchiveFileGroup(file_group);
|
||||
setHistory(history);
|
||||
} catch (e) {
|
||||
|
|
@ -437,7 +437,7 @@ export const useArchive = (archiveId) => {
|
|||
|
||||
useEffect(() => {
|
||||
fetchArchive();
|
||||
}, [archiveId]);
|
||||
}, [fileGroupId]);
|
||||
|
||||
return {archiveFile: archiveFileGroup, history, fetchArchive};
|
||||
}
|
||||
|
|
@ -651,20 +651,20 @@ export const useSearchVideos = (defaultLimit, channelId, order_by) => {
|
|||
}
|
||||
}
|
||||
|
||||
export const useVideo = (videoId) => {
|
||||
export const useVideo = (fileGroupId) => {
|
||||
const [videoFile, setVideoFile] = useState(null);
|
||||
const [prevFile, setPrevFile] = useState(null);
|
||||
const [nextFile, setNextFile] = useState(null);
|
||||
|
||||
const fetchVideo = async () => {
|
||||
if (videoId && videoFile && Number(videoFile.video.id) !== Number(videoId)) {
|
||||
if (fileGroupId && videoFile && Number(videoFile.id) !== Number(fileGroupId)) {
|
||||
// Video is changing. Clear the old video before fetching.
|
||||
setVideoFile(null);
|
||||
setPrevFile(null);
|
||||
setNextFile(null);
|
||||
}
|
||||
try {
|
||||
const [v, p, n] = await getVideo(videoId);
|
||||
const [v, p, n] = await getVideo(fileGroupId);
|
||||
setVideoFile(v);
|
||||
setPrevFile(p);
|
||||
setNextFile(n);
|
||||
|
|
@ -684,19 +684,19 @@ export const useVideo = (videoId) => {
|
|||
|
||||
useEffect(() => {
|
||||
fetchVideo();
|
||||
}, [videoId]);
|
||||
}, [fileGroupId]);
|
||||
|
||||
return {videoFile, prevFile, nextFile, fetchVideo};
|
||||
}
|
||||
|
||||
export const useVideoExtras = (videoId) => {
|
||||
export const useVideoExtras = (fileGroupId) => {
|
||||
// Fetches extra data to display on a Video's page.
|
||||
const [comments, setComments] = useState(null);
|
||||
const [captions, setCaptions] = useState(null);
|
||||
|
||||
const fetchComments = async () => {
|
||||
try {
|
||||
const result = await getVideoComments(videoId);
|
||||
const result = await getVideoComments(fileGroupId);
|
||||
setComments(result.comments);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
|
|
@ -705,7 +705,7 @@ export const useVideoExtras = (videoId) => {
|
|||
|
||||
const fetchCaptions = async () => {
|
||||
try {
|
||||
const result = await getVideoCaptions(videoId);
|
||||
const result = await getVideoCaptions(fileGroupId);
|
||||
setCaptions(result.captions);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
|
|
@ -713,14 +713,14 @@ export const useVideoExtras = (videoId) => {
|
|||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (videoId) {
|
||||
if (fileGroupId) {
|
||||
fetchComments();
|
||||
fetchCaptions();
|
||||
} else {
|
||||
setComments(null);
|
||||
setCaptions(null);
|
||||
}
|
||||
}, [videoId]);
|
||||
}, [fileGroupId]);
|
||||
|
||||
return {comments, captions}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -90,7 +90,7 @@ class ArchiveDownloader(Downloader, ABC):
|
|||
|
||||
logger.info(f'Successfully downloaded Archive {download.url} {archive}')
|
||||
|
||||
return DownloadResult(success=True, location=f'/archive/{archive.id}')
|
||||
return DownloadResult(success=True, location=archive.location)
|
||||
|
||||
async def do_singlefile(self, download: Download) -> bytes:
|
||||
"""Create a Singlefile from the archive's URL."""
|
||||
|
|
|
|||
|
|
@ -31,28 +31,28 @@ async def statistics(_: Request):
|
|||
return json_response(ret, HTTPStatus.OK)
|
||||
|
||||
|
||||
@archive_bp.get('/<archive_id:int>')
|
||||
@openapi.description('Get an archive')
|
||||
@archive_bp.get('/<file_group_id:int>')
|
||||
@openapi.description('Get an archive by its FileGroup ID')
|
||||
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
|
||||
async def get_archive(request: Request, archive_id: int):
|
||||
async def get_archive(request: Request, file_group_id: int):
|
||||
session = request.ctx.session
|
||||
archive = lib.get_archive(session, archive_id)
|
||||
archive = lib.get_archive_by_file_group_id(session, file_group_id)
|
||||
archive_file_group = archive.file_group.__json__()
|
||||
history = [i.file_group.__json__() for i in archive.history]
|
||||
return json_response({'file_group': archive_file_group, 'history': history})
|
||||
|
||||
|
||||
@archive_bp.delete('/<archive_ids:int>', name='archive_delete_one')
|
||||
@archive_bp.delete('/<archive_ids:[0-9,]+>', name='archive_delete_many')
|
||||
@openapi.description('Delete Archives')
|
||||
@archive_bp.delete('/<file_group_ids:int>', name='archive_delete_one')
|
||||
@archive_bp.delete('/<file_group_ids:[0-9,]+>', name='archive_delete_many')
|
||||
@openapi.description('Delete Archives by FileGroup IDs')
|
||||
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
|
||||
@wrol_mode_check
|
||||
async def delete_archive(_: Request, archive_ids: str):
|
||||
async def delete_archive(_: Request, file_group_ids: str):
|
||||
try:
|
||||
archive_ids = [int(i) for i in str(archive_ids).split(',')]
|
||||
file_group_ids = [int(i) for i in str(file_group_ids).split(',')]
|
||||
except ValueError:
|
||||
raise ValidationError('Could not parse archive ids')
|
||||
lib.delete_archives(*archive_ids)
|
||||
raise ValidationError('Could not parse file group ids')
|
||||
lib.delete_archives_by_file_group_ids(*file_group_ids)
|
||||
return response.empty()
|
||||
|
||||
|
||||
|
|
@ -253,25 +253,26 @@ async def post_upload_singlefile(request: Request):
|
|||
return json_response(dict(), status=HTTPStatus.OK)
|
||||
|
||||
|
||||
@archive_bp.post('/<archive_id:int>/generate_screenshot')
|
||||
@archive_bp.post('/<file_group_id:int>/generate_screenshot')
|
||||
@openapi.description('Generate a screenshot for an Archive that does not have one')
|
||||
@openapi.response(HTTPStatus.OK, description='Screenshot generation queued')
|
||||
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
|
||||
@openapi.response(HTTPStatus.BAD_REQUEST, JSONErrorResponse)
|
||||
@wrol_mode_check
|
||||
async def post_generate_screenshot(request: Request, archive_id: int):
|
||||
async def post_generate_screenshot(request: Request, file_group_id: int):
|
||||
"""Queue a screenshot generation request for an Archive."""
|
||||
session = request.ctx.session
|
||||
# Verify archive exists
|
||||
try:
|
||||
archive = lib.get_archive(session, archive_id)
|
||||
archive = lib.get_archive_by_file_group_id(session, file_group_id)
|
||||
except Exception:
|
||||
return json_response({'error': f'Archive {archive_id} not found'}, status=HTTPStatus.NOT_FOUND)
|
||||
return json_response({'error': f'Archive with FileGroup {file_group_id} not found'}, status=HTTPStatus.NOT_FOUND)
|
||||
|
||||
if not archive.singlefile_path:
|
||||
return json_response({'error': 'Archive has no singlefile'}, status=HTTPStatus.BAD_REQUEST)
|
||||
|
||||
# Queue the screenshot generation request
|
||||
# Queue the screenshot generation request using internal archive ID
|
||||
archive_id = archive.id
|
||||
logger.info(f'Queueing screenshot generation for Archive {archive_id}')
|
||||
api_app.shared_ctx.archive_screenshots.put(archive_id)
|
||||
generate_screenshot_switch_handler.activate_switch(context=dict(archive_id=archive_id))
|
||||
|
|
|
|||
|
|
@ -1110,14 +1110,22 @@ def get_archive(session: Session, archive_id: int) -> Archive:
|
|||
return archive
|
||||
|
||||
|
||||
def delete_archives(*archive_ids: List[int]):
|
||||
"""Delete an Archive and all of its files."""
|
||||
with get_db_session(commit=True) as session:
|
||||
archives: List[Archive] = list(session.query(Archive).filter(Archive.id.in_(archive_ids)))
|
||||
if not archives:
|
||||
raise UnknownArchive(f'Unknown Archives with IDs: {", ".join(map(str, archive_ids))}')
|
||||
def get_archive_by_file_group_id(session: Session, file_group_id: int) -> Archive:
|
||||
"""Get an Archive by its FileGroup ID."""
|
||||
archive = session.query(Archive).filter_by(file_group_id=file_group_id).one_or_none()
|
||||
if not archive:
|
||||
raise UnknownArchive(f'Unknown Archive with FileGroup ID: {file_group_id}')
|
||||
archive.file_group.set_viewed()
|
||||
return archive
|
||||
|
||||
|
||||
def delete_archives_by_file_group_ids(*file_group_ids: List[int]):
|
||||
"""Delete Archives by their FileGroup IDs and all of their files."""
|
||||
with get_db_session(commit=True) as session:
|
||||
archives: List[Archive] = list(session.query(Archive).filter(Archive.file_group_id.in_(file_group_ids)))
|
||||
if not archives:
|
||||
raise UnknownArchive(f'Unknown Archives with FileGroup IDs: {", ".join(map(str, file_group_ids))}')
|
||||
|
||||
# Delete any files associated with this URL.
|
||||
for archive in archives:
|
||||
archive.delete()
|
||||
|
||||
|
|
|
|||
|
|
@ -411,7 +411,7 @@ class Archive(Base, ModelHelper):
|
|||
@property
|
||||
def location(self):
|
||||
"""The location where this Archive can be viewed in the UI."""
|
||||
return f'/archive/{self.id}'
|
||||
return f'/archives/{self.file_group_id}'
|
||||
|
||||
@property
|
||||
def download_directory(self) -> pathlib.Path:
|
||||
|
|
|
|||
|
|
@ -322,7 +322,7 @@ async def test_archive_generate_screenshot(test_session, async_client, archive_f
|
|||
assert archive.singlefile_path is not None, 'Archive should have a singlefile'
|
||||
|
||||
# Request screenshot generation
|
||||
request, response = await async_client.post(f'/api/archive/{archive.id}/generate_screenshot')
|
||||
request, response = await async_client.post(f'/api/archive/{archive.file_group_id}/generate_screenshot')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['message'] == 'Screenshot generation queued'
|
||||
|
||||
|
|
@ -346,7 +346,7 @@ async def test_archive_generate_screenshot(test_session, async_client, archive_f
|
|||
# while the file existed. This scenario is now auto-fixed by Archive.validate() which calls
|
||||
# rebuild_data(), so the simulation is no longer necessary.
|
||||
|
||||
request, response = await async_client.post(f'/api/archive/{archive.id}/generate_screenshot')
|
||||
request, response = await async_client.post(f'/api/archive/{archive.file_group_id}/generate_screenshot')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['message'] == 'Screenshot generation queued'
|
||||
|
||||
|
|
@ -368,7 +368,7 @@ async def test_archive_generate_screenshot(test_session, async_client, archive_f
|
|||
if archive_no_singlefile.singlefile_path and archive_no_singlefile.singlefile_path.is_file():
|
||||
archive_no_singlefile.singlefile_path.unlink()
|
||||
|
||||
request, response = await async_client.post(f'/api/archive/{archive_no_singlefile.id}/generate_screenshot')
|
||||
request, response = await async_client.post(f'/api/archive/{archive_no_singlefile.file_group_id}/generate_screenshot')
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert 'no singlefile' in response.json['error'].lower()
|
||||
|
||||
|
|
@ -377,7 +377,7 @@ async def test_archive_generate_screenshot(test_session, async_client, archive_f
|
|||
archive_wrol = archive_factory('example.com', 'https://example.com/wrol-test', screenshot=False)
|
||||
test_session.commit()
|
||||
|
||||
request, response = await async_client.post(f'/api/archive/{archive_wrol.id}/generate_screenshot')
|
||||
request, response = await async_client.post(f'/api/archive/{archive_wrol.file_group_id}/generate_screenshot')
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN
|
||||
await wrol_mode_fixture(False)
|
||||
|
||||
|
|
|
|||
|
|
@ -13,8 +13,8 @@ from modules.archive import lib
|
|||
from modules.archive.lib import ArchiveDownloaderConfigValidator
|
||||
from modules.archive.lib import format_archive_filename
|
||||
from modules.archive.lib import get_archive_downloader_config
|
||||
from modules.archive.lib import get_or_create_domain_collection, get_new_archive_files, delete_archives, \
|
||||
model_archive_result, get_domains
|
||||
from modules.archive.lib import get_or_create_domain_collection, get_new_archive_files, \
|
||||
delete_archives_by_file_group_ids, model_archive_result, get_domains
|
||||
from modules.archive.models import Archive
|
||||
from wrolpi.api_utils import CustomJSONEncoder
|
||||
from wrolpi.collections import Collection
|
||||
|
|
@ -241,7 +241,7 @@ async def test_delete_archive(async_client, test_session, archive_factory):
|
|||
archive3_paths = list(archive3.my_paths())
|
||||
|
||||
# Delete the oldest.
|
||||
delete_archives(archive1.id, archive3.id)
|
||||
delete_archives_by_file_group_ids(archive1.file_group_id, archive3.file_group_id)
|
||||
assert test_session.query(Archive).count() == 1
|
||||
assert test_session.query(FileGroup).count() == 1
|
||||
# Files were deleted.
|
||||
|
|
@ -251,7 +251,7 @@ async def test_delete_archive(async_client, test_session, archive_factory):
|
|||
assert archive2_paths and all(i.is_file() for i in archive2_paths)
|
||||
|
||||
# Delete the last archive. The domain collection should also be deleted.
|
||||
delete_archives(archive2.id)
|
||||
delete_archives_by_file_group_ids(archive2.file_group_id)
|
||||
assert test_session.query(Archive).count() == 0
|
||||
domain = test_session.query(Collection).filter_by(kind='domain').one_or_none()
|
||||
assert domain is None
|
||||
|
|
|
|||
|
|
@ -42,14 +42,14 @@ async def test_get_video(async_client, test_session, simple_channel, video_facto
|
|||
test_session.commit()
|
||||
|
||||
# Test that a 404 is returned when no video exists
|
||||
_, response = await async_client.get('/api/videos/video/10')
|
||||
_, response = await async_client.get('/api/videos/10')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND, response.json
|
||||
assert response.json == {'code': 'UNKNOWN_VIDEO',
|
||||
'error': 'Cannot find Video with id 10',
|
||||
'error': 'Cannot find Video with file_group_id 10',
|
||||
'message': 'The video could not be found.'}
|
||||
|
||||
# Get the video info we inserted
|
||||
_, response = await async_client.get('/api/videos/video/1')
|
||||
_, response = await async_client.get(f'/api/videos/{video1.file_group_id}')
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
assert_dict_contains(response.json['file_group'], {'title': 'vid1'})
|
||||
|
||||
|
|
@ -97,7 +97,7 @@ async def test_channel_no_download_frequency(async_client, test_session, test_di
|
|||
@pytest.mark.asyncio
|
||||
async def test_video_file_name(test_session, simple_video, async_client):
|
||||
"""If a Video has no title, the front-end can use the file name as the title."""
|
||||
_, resp = await async_client.get(f'/api/videos/video/{simple_video.id}')
|
||||
_, resp = await async_client.get(f'/api/videos/{simple_video.file_group_id}')
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
assert resp.json['file_group']['video']['video_path'] == 'simple_video.mp4'
|
||||
assert resp.json['file_group']['video'].get('stem') == 'simple_video'
|
||||
|
|
|
|||
|
|
@ -1005,9 +1005,7 @@ class VideoDownloader(Downloader, ABC):
|
|||
# Find the existing video, replace its info json.
|
||||
video = Video.get_by_url(url, session)
|
||||
|
||||
location = f'/videos/video/{video.id}'
|
||||
if video.channel_id:
|
||||
location = f'/videos/channel/{video.channel_id}/video/{video.id}'
|
||||
location = video.location
|
||||
|
||||
# Download video info json directly using yt-dlp.
|
||||
try:
|
||||
|
|
|
|||
|
|
@ -366,6 +366,16 @@ class Video(ModelHelper, Base):
|
|||
raise UnknownVideo(f'Cannot find Video with id {id_}')
|
||||
return video
|
||||
|
||||
@staticmethod
|
||||
def find_by_file_group_id(session: Session, file_group_id: int) -> 'Video':
|
||||
"""Find a Video by its FileGroup ID, raises an exception if it cannot be found.
|
||||
|
||||
@raise UnknownVideo: if the Video can not be found"""
|
||||
video = session.query(Video).filter(Video.file_group_id == file_group_id).one_or_none()
|
||||
if not video:
|
||||
raise UnknownVideo(f'Cannot find Video with file_group_id {file_group_id}')
|
||||
return video
|
||||
|
||||
def add_tag(self, session: Session, tag_id_or_name: int | str) -> TagFile:
|
||||
return self.file_group.add_tag(session, tag_id_or_name)
|
||||
|
||||
|
|
@ -526,12 +536,9 @@ class Video(ModelHelper, Base):
|
|||
@property
|
||||
def location(self) -> str:
|
||||
"""The href of the video in the App."""
|
||||
if not self.id:
|
||||
raise RuntimeError('Video id not set. Flush to DB.')
|
||||
|
||||
if self.channel_id:
|
||||
return f'/videos/channel/{self.channel_id}/video/{self.id}'
|
||||
return f'/videos/video/{self.id}'
|
||||
if not self.file_group_id:
|
||||
raise RuntimeError('Video file_group_id not set.')
|
||||
return f'/videos/{self.file_group_id}'
|
||||
|
||||
def get_comments(self) -> list | None:
|
||||
return (self.get_info_json() or dict()).get('comments')
|
||||
|
|
|
|||
|
|
@ -273,7 +273,7 @@ async def test_delete_video(async_client, test_session, video_factory, test_down
|
|||
files = video.file_group.my_paths()
|
||||
test_session.commit()
|
||||
|
||||
request, response = await async_client.delete(f'/api/videos/video/{video.id}')
|
||||
request, response = await async_client.delete(f'/api/videos/{video.file_group_id}')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
assert test_session.query(Video).count() == 0, 'Video was not deleted.'
|
||||
|
|
|
|||
|
|
@ -349,7 +349,8 @@ async def test_download_result(test_session, test_directory, video_download_mana
|
|||
|
||||
download: Download = test_session.query(Download).one()
|
||||
assert download.url == 'https://example.com'
|
||||
assert download.location == '/videos/channel/1/video/1'
|
||||
video = test_session.query(Video).one()
|
||||
assert download.location == f'/videos/{video.file_group_id}'
|
||||
|
||||
# Video has its files.
|
||||
video = test_session.query(Video).one()
|
||||
|
|
|
|||
|
|
@ -372,12 +372,12 @@ async def test_videos_downloader_config_api(async_client, test_directory, test_v
|
|||
def test_video_location(test_session, video_factory, channel_factory, async_client):
|
||||
# Video location without a channel, it opens the preview.
|
||||
video1 = video_factory(title='vid1')
|
||||
assert video1.location == '/videos/video/1'
|
||||
assert video1.location == f'/videos/{video1.file_group_id}'
|
||||
|
||||
# Video location with a channel.
|
||||
channel = channel_factory(name='ChannelName')
|
||||
video2 = video_factory(title='vid2', channel_id=channel.id)
|
||||
assert video2.location == '/videos/channel/1/video/2'
|
||||
assert video2.location == f'/videos/{video2.file_group_id}'
|
||||
|
||||
|
||||
def test_format_video_filename_without_upload_date(test_session, video_factory, test_videos_downloader_config, caplog):
|
||||
|
|
|
|||
|
|
@ -19,30 +19,30 @@ video_bp = Blueprint('Video', '/api/videos')
|
|||
logger = logger.getChild(__name__)
|
||||
|
||||
|
||||
@video_bp.get('/video/<video_id:int>')
|
||||
@video_bp.get('/<file_group_id:int>')
|
||||
@openapi.description('Get Video information')
|
||||
@openapi.response(HTTPStatus.OK, schema.VideoResponse)
|
||||
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
|
||||
def video_get(_: Request, video_id: int):
|
||||
video, previous_video, next_video = lib.get_video_for_app(video_id)
|
||||
def video_get(_: Request, file_group_id: int):
|
||||
video, previous_video, next_video = lib.get_video_for_app(file_group_id)
|
||||
return json_response({'file_group': video, 'prev': previous_video, 'next': next_video})
|
||||
|
||||
|
||||
@video_bp.get('/video/<video_id:int>/comments')
|
||||
@video_bp.get('/<file_group_id:int>/comments')
|
||||
@openapi.description('Get Video comments')
|
||||
@openapi.response(HTTPStatus.OK, schema.VideoCommentsResponse)
|
||||
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
|
||||
def video_get_comments(_: Request, video_id: int):
|
||||
video = lib.get_video(video_id)
|
||||
def video_get_comments(_: Request, file_group_id: int):
|
||||
video = lib.get_video(file_group_id)
|
||||
return json_response({'comments': video.get_comments()})
|
||||
|
||||
|
||||
@video_bp.get('/video/<video_id:int>/captions')
|
||||
@video_bp.get('/<file_group_id:int>/captions')
|
||||
@openapi.description('Get Video captions')
|
||||
@openapi.response(HTTPStatus.OK, schema.VideoCaptionsResponse)
|
||||
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
|
||||
def video_get_captions(_: Request, video_id: int):
|
||||
video = lib.get_video(video_id)
|
||||
def video_get_captions(_: Request, file_group_id: int):
|
||||
video = lib.get_video(file_group_id)
|
||||
return json_response({'captions': video.file_group.d_text})
|
||||
|
||||
|
||||
|
|
@ -72,21 +72,21 @@ async def search_videos(_: Request, body: schema.VideoSearchRequest):
|
|||
return json_response(ret)
|
||||
|
||||
|
||||
@video_bp.delete('/video/<video_ids:[0-9,]+>', name='Video Delete Many')
|
||||
@video_bp.delete('/video/<video_ids:int>', name='Video Delete One')
|
||||
@video_bp.delete('/<file_group_ids:[0-9,]+>', name='Video Delete Many')
|
||||
@video_bp.delete('/<file_group_ids:int>', name='Video Delete One')
|
||||
@openapi.description('Delete videos.')
|
||||
@openapi.response(HTTPStatus.NO_CONTENT)
|
||||
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
|
||||
@wrol_mode_check
|
||||
async def video_delete(request: Request, video_ids: str):
|
||||
async def video_delete(request: Request, file_group_ids: str):
|
||||
try:
|
||||
video_ids = [int(i) for i in str(video_ids).split(',')]
|
||||
file_group_ids = [int(i) for i in str(file_group_ids).split(',')]
|
||||
except Exception:
|
||||
raise ValidationError('Unable to parse video ids')
|
||||
raise ValidationError('Unable to parse file group ids')
|
||||
|
||||
session = request.ctx.session
|
||||
lib.delete_videos(session, *video_ids)
|
||||
lib.delete_videos(session, *file_group_ids)
|
||||
|
||||
save_channels_config.activate_switch()
|
||||
Events.send_deleted(f'Deleted {len(video_ids)} videos')
|
||||
Events.send_deleted(f'Deleted {len(file_group_ids)} videos')
|
||||
return response.empty()
|
||||
|
|
|
|||
|
|
@ -23,12 +23,12 @@ from ..lib import get_yt_dlp_http_headers, get_yt_dlp_sleep_opts
|
|||
logger.getChild(__name__)
|
||||
|
||||
|
||||
def get_video_for_app(video_id: int) -> Tuple[dict, Optional[dict], Optional[dict]]:
|
||||
def get_video_for_app(file_group_id: int) -> Tuple[dict, Optional[dict], Optional[dict]]:
|
||||
"""
|
||||
Get a Video, with it's prev/next videos. Mark the Video as viewed.
|
||||
Get a Video by its FileGroup ID, with its prev/next videos. Mark the Video as viewed.
|
||||
"""
|
||||
with get_db_session(commit=True) as session:
|
||||
video = Video.find_by_id(session, video_id)
|
||||
video = Video.find_by_file_group_id(session, file_group_id)
|
||||
video.file_group.set_viewed()
|
||||
previous_video, next_video = video.get_surrounding_videos()
|
||||
|
||||
|
|
@ -39,12 +39,12 @@ def get_video_for_app(video_id: int) -> Tuple[dict, Optional[dict], Optional[dic
|
|||
return video, previous_video, next_video
|
||||
|
||||
|
||||
def get_video(video_id: int) -> Video:
|
||||
def get_video(file_group_id: int) -> Video:
|
||||
"""
|
||||
Get a Video, with it's prev/next videos. Mark the Video as viewed.
|
||||
Get a Video by its FileGroup ID.
|
||||
"""
|
||||
with get_db_session() as session:
|
||||
video = Video.find_by_id(session, video_id)
|
||||
video = Video.find_by_file_group_id(session, file_group_id)
|
||||
return video
|
||||
|
||||
|
||||
|
|
@ -161,8 +161,8 @@ def search_videos(
|
|||
return results, total
|
||||
|
||||
|
||||
def delete_videos(session: Session, *video_ids: int):
|
||||
videos = list(session.query(Video).filter(Video.id.in_(video_ids)))
|
||||
def delete_videos(session: Session, *file_group_ids: int):
|
||||
videos = list(session.query(Video).filter(Video.file_group_id.in_(file_group_ids)))
|
||||
if not videos:
|
||||
raise UnknownVideo('Could not find videos to delete')
|
||||
|
||||
|
|
|
|||
|
|
@ -125,7 +125,7 @@ async def test_delete_video_api(async_client, test_session, channel_factory, vid
|
|||
assert vid1_video_path.is_file() and vid1_caption_path.is_file()
|
||||
assert vid2_video_path.is_file() and vid2_info_json_path.is_file()
|
||||
|
||||
request, response = await async_client.delete(f'/api/videos/video/{vid1.id}')
|
||||
request, response = await async_client.delete(f'/api/videos/{vid1.file_group_id}')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
# Video was added to skip list.
|
||||
|
|
@ -135,7 +135,7 @@ async def test_delete_video_api(async_client, test_session, channel_factory, vid
|
|||
assert vid1_video_path.is_file() is False and vid1_caption_path.is_file() is False
|
||||
assert vid2_video_path.is_file() and vid2_info_json_path.is_file()
|
||||
|
||||
request, response = await async_client.delete(f'/api/videos/video/{vid2.id}')
|
||||
request, response = await async_client.delete(f'/api/videos/{vid2.file_group_id}')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
assert test_download_manager.is_skipped(vid1.file_group.url, vid2.file_group.url)
|
||||
|
|
@ -144,7 +144,7 @@ async def test_delete_video_api(async_client, test_session, channel_factory, vid
|
|||
assert vid2_video_path.is_file() is False and vid2_info_json_path.is_file() is False
|
||||
|
||||
# 3 does not exist.
|
||||
request, response = await async_client.delete(f'/api/videos/video/3')
|
||||
request, response = await async_client.delete(f'/api/videos/3')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
|
|
@ -169,7 +169,7 @@ async def test_wrol_mode(async_client, simple_channel, simple_video, wrol_mode_f
|
|||
assert resp.json['code'] == 'WROL_MODE_ENABLED'
|
||||
|
||||
# Can't delete a video
|
||||
_, resp = await async_client.delete(f'/api/videos/video/{simple_video.id}')
|
||||
_, resp = await async_client.delete(f'/api/videos/{simple_video.file_group_id}')
|
||||
assert resp.status_code == HTTPStatus.FORBIDDEN
|
||||
assert resp.json['code'] == 'WROL_MODE_ENABLED'
|
||||
|
||||
|
|
@ -195,15 +195,15 @@ async def test_api_video_extras(async_client, simple_channel, video_factory):
|
|||
info_json = {'duration': 5, 'epoch': 12345, 'comments': [{'some': 'comments'}]}
|
||||
video = video_factory(simple_channel.id, with_info_json=info_json, with_caption_file=True)
|
||||
|
||||
request, response = await async_client.get(f'/api/videos/video/{video.id}/captions')
|
||||
request, response = await async_client.get(f'/api/videos/{video.file_group_id}/captions')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json.get('captions')
|
||||
|
||||
request, response = await async_client.get(f'/api/videos/video/{video.id}/comments')
|
||||
request, response = await async_client.get(f'/api/videos/{video.file_group_id}/comments')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json.get('comments')
|
||||
|
||||
request, response = await async_client.get('/api/videos/video/123/captions')
|
||||
request, response = await async_client.get('/api/videos/123/captions')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
request, response = await async_client.get('/api/videos/video/123/comments')
|
||||
request, response = await async_client.get('/api/videos/123/comments')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
|
|
|||
|
|
@ -213,13 +213,13 @@ async def handle_user_delete_duplicates(similar_videos: List[Video], video_url:
|
|||
ranked_videos = sorted(ranked_videos, key=lambda i: (i[0], i[1].file_group.size), reverse=True)
|
||||
for rank, video in ranked_videos:
|
||||
fg = video.file_group
|
||||
id_, title, path, source_id, size = video.id, fg.title, video.video_path, video.source_id, fg.size
|
||||
fg_id, title, path, source_id, size = fg.id, fg.title, video.video_path, video.source_id, fg.size
|
||||
size = f'{size // 1_048_576} MB'
|
||||
path = get_relative_to_media_directory(path)
|
||||
if video_url:
|
||||
print(f'{rank} {repr(title)} {size} {repr(str(path.name))} {source_id} {id_} {video_url + str(id_)}')
|
||||
print(f'{rank} {repr(title)} {size} {repr(str(path.name))} {source_id} {fg_id} {video_url + str(fg_id)}')
|
||||
else:
|
||||
print(f'{rank} {repr(title)} {size} {repr(str(path.name))} {source_id} {id_}')
|
||||
print(f'{rank} {repr(title)} {size} {repr(str(path.name))} {source_id} {fg_id}')
|
||||
|
||||
# Detect re-uploaded videos.
|
||||
# If video with exact title is uploaded day(s) later, then suggest deleting the oldest video.
|
||||
|
|
@ -325,7 +325,7 @@ if __name__ == '__main__':
|
|||
help='The ID of the channel to search. If empty, all channels will be searched.')
|
||||
parser.add_argument('-r', '--rank', type=float, default=MINIMUM_RANK,
|
||||
help=f'The minimum similarity between the titles. Default: {MINIMUM_RANK}')
|
||||
parser.add_argument('-u', '--video-url', default='http://127.0.0.1/videos/video/',
|
||||
parser.add_argument('-u', '--video-url', default='http://127.0.0.1/videos/',
|
||||
help='The URL where the videos can be viewed.')
|
||||
parser.add_argument('-d', '--directory',
|
||||
help='Only search videos in this directory.')
|
||||
|
|
|
|||
|
|
@ -773,7 +773,6 @@ def _detect_conflicts_with_details(
|
|||
'title': source_path.stem,
|
||||
'model_type': collection.kind,
|
||||
'size': 0,
|
||||
'video_id': None,
|
||||
'archive_id': None,
|
||||
'poster_path': None,
|
||||
'published_datetime': None,
|
||||
|
|
@ -789,7 +788,6 @@ def _detect_conflicts_with_details(
|
|||
'title': file_group.title or source_path.stem,
|
||||
'model_type': file_group.model or collection.kind,
|
||||
'size': file_group.size or 0,
|
||||
'video_id': None,
|
||||
'archive_id': None,
|
||||
'poster_path': None,
|
||||
'published_datetime': None,
|
||||
|
|
@ -802,7 +800,6 @@ def _detect_conflicts_with_details(
|
|||
from modules.videos.models import Video
|
||||
video = session.query(Video).filter_by(file_group_id=file_group.id).one_or_none()
|
||||
if video:
|
||||
file_info['video_id'] = video.id
|
||||
file_info['source_id'] = video.source_id
|
||||
# Date is stored on file_group
|
||||
if file_group.published_datetime:
|
||||
|
|
@ -1264,8 +1261,8 @@ async def get_conflict_details_with_ffprobe(
|
|||
videos_processed = 0
|
||||
for conflict in preview.conflicts:
|
||||
for file_info in conflict['conflicting_files']:
|
||||
if file_info.get('video_id'):
|
||||
video = session.query(Video).get(file_info['video_id'])
|
||||
if file_info.get('file_group_id') and file_info.get('model_type') == 'channel':
|
||||
video = session.query(Video).filter_by(file_group_id=file_info['file_group_id']).one_or_none()
|
||||
if video and not video.ffprobe_json:
|
||||
try:
|
||||
await video.get_ffprobe_json()
|
||||
|
|
|
|||
|
|
@ -2136,7 +2136,6 @@ async def test_reorganize_preview_returns_conflict_details(async_client, test_di
|
|||
# Verify file details are included
|
||||
for file_info in conflict['conflicting_files']:
|
||||
assert 'file_group_id' in file_info
|
||||
assert 'video_id' in file_info
|
||||
assert 'current_path' in file_info
|
||||
assert 'title' in file_info
|
||||
assert 'model_type' in file_info
|
||||
|
|
@ -2277,13 +2276,13 @@ async def test_conflict_preview_includes_quality_rank(async_client, test_directo
|
|||
f"Files should be sorted by quality_rank descending. Got: {ranks}"
|
||||
|
||||
# The video with more metadata (video2) should rank higher
|
||||
video2_info = next(f for f in files if f['video_id'] == video2.id)
|
||||
video1_info = next(f for f in files if f['video_id'] == video1.id)
|
||||
video2_info = next(f for f in files if f['file_group_id'] == video2.file_group_id)
|
||||
video1_info = next(f for f in files if f['file_group_id'] == video1.file_group_id)
|
||||
assert video2_info['quality_rank'] > video1_info['quality_rank'], \
|
||||
f"Video with more metadata should rank higher. v2={video2_info['quality_rank']}, v1={video1_info['quality_rank']}"
|
||||
|
||||
# The highest ranked video should be first
|
||||
assert files[0]['video_id'] == video2.id, "Highest ranked video should be first"
|
||||
assert files[0]['file_group_id'] == video2.file_group_id, "Highest ranked video should be first"
|
||||
|
||||
|
||||
# ============================================================================
|
||||
|
|
|
|||
|
|
@ -684,7 +684,7 @@ async def test_post_upload(test_session, async_client, test_directory, make_file
|
|||
assert file_group.indexed, 'File should be indexed after upload.'
|
||||
assert file_group.model, 'File should be modeled'
|
||||
assert isinstance(file_group.get_model_record(), Video)
|
||||
assert file_group.location == '/videos/video/2'
|
||||
assert file_group.location == f'/videos/{file_group.id}'
|
||||
# Video was modeled, but has no Channel.
|
||||
video: Video = test_session.query(Video).one()
|
||||
assert video.video_path
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue