diff --git a/app/src/App.js b/app/src/App.js index 61d648a5..93be4c00 100644 --- a/app/src/App.js +++ b/app/src/App.js @@ -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(}/> }/> }/> - }/> - }/> - }/> + + }> + }/> + }/> + }/> + }/> + }/> + }/> + }/> + + }/> + }/> }/> }/> - }/> + }/> }/> }/> }/> diff --git a/app/src/api.js b/app/src/api.js index bd90df62..6cced9eb 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -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', diff --git a/app/src/components/Archive.js b/app/src/components/Archive.js index 8296945a..e70d4b88 100644 --- a/app/src/components/Archive.js +++ b/app/src/components/Archive.js @@ -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 =

Unknown

; if (domain) { - const domainUrl = `/archive?domain=${domain}`; + const domainUrl = `/archives?domain=${domain}`; domainHeader =
{domain}
; @@ -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 = {title}; @@ -400,7 +400,7 @@ export function ArchiveCard({file}) { } - + @@ -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 = <>
{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 @@ -1360,7 +1360,7 @@ export function ArchiveRoute() { }/> }/> }/> - }/> + }/> } diff --git a/app/src/components/Headline.js b/app/src/components/Headline.js index 747cdf3e..5cf1b391 100644 --- a/app/src/components/Headline.js +++ b/app/src/components/Headline.js @@ -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, ]; } else if (model === 'archive' && !_.isEmpty(data)) { - headlines = [...headlines, ]; + headlines = [...headlines, ]; } else { headlines = [...headlines, ]; } diff --git a/app/src/components/KeyboardShortcutsProvider.js b/app/src/components/KeyboardShortcutsProvider.js index b80867d9..62194ff9 100644 --- a/app/src/components/KeyboardShortcutsProvider.js +++ b/app/src/components/KeyboardShortcutsProvider.js @@ -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', diff --git a/app/src/components/Nav.js b/app/src/components/Nav.js index 6bb2a367..9c947fdf 100644 --- a/app/src/components/Nav.js +++ b/app/src/components/Nav.js @@ -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'; } diff --git a/app/src/components/Search.js b/app/src/components/Search.js index ea97083b..27d042f5 100644 --- a/app/src/components/Search.js +++ b/app/src/components/Search.js @@ -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}` } }) } diff --git a/app/src/components/VideoPlayer.js b/app/src/components/VideoPlayer.js index f3f57775..f6a605f7 100644 --- a/app/src/components/VideoPlayer.js +++ b/app/src/components/VideoPlayer.js @@ -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 } -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() { ; } -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 - - }/> - }/> - }/> - }/> - }/> - }/> - }/> - }/> - + } @@ -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 = ; @@ -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; diff --git a/app/src/components/collections/BatchReorganizeModal.js b/app/src/components/collections/BatchReorganizeModal.js index a7d52863..f7bef805 100644 --- a/app/src/components/collections/BatchReorganizeModal.js +++ b/app/src/components/collections/BatchReorganizeModal.js @@ -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' > diff --git a/app/src/components/collections/CollectionTable.test.js b/app/src/components/collections/CollectionTable.test.js index 2e8e261f..e813c25e 100644 --- a/app/src/components/collections/CollectionTable.test.js +++ b/app/src/components/collections/CollectionTable.test.js @@ -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' }; diff --git a/app/src/components/collections/ConflictResolutionModal.js b/app/src/components/collections/ConflictResolutionModal.js index 3c5da129..e9341009 100644 --- a/app/src/components/collections/ConflictResolutionModal.js +++ b/app/src/components/collections/ConflictResolutionModal.js @@ -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]); } diff --git a/app/src/components/collections/ConflictResolutionModal.test.js b/app/src/components/collections/ConflictResolutionModal.test.js index 4a608077..c90a3c1e 100644 --- a/app/src/components/collections/ConflictResolutionModal.test.js +++ b/app/src/components/collections/ConflictResolutionModal.test.js @@ -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, }, ], diff --git a/app/src/hooks/customHooks.js b/app/src/hooks/customHooks.js index 90bc650b..397de385 100644 --- a/app/src/hooks/customHooks.js +++ b/app/src/hooks/customHooks.js @@ -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} } diff --git a/modules/archive/__init__.py b/modules/archive/__init__.py index 3145e3ed..75980466 100644 --- a/modules/archive/__init__.py +++ b/modules/archive/__init__.py @@ -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.""" diff --git a/modules/archive/api.py b/modules/archive/api.py index eb89dff3..4b6b61e5 100644 --- a/modules/archive/api.py +++ b/modules/archive/api.py @@ -31,28 +31,28 @@ async def statistics(_: Request): return json_response(ret, HTTPStatus.OK) -@archive_bp.get('/') -@openapi.description('Get an archive') +@archive_bp.get('/') +@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('/', name='archive_delete_one') -@archive_bp.delete('/', name='archive_delete_many') -@openapi.description('Delete Archives') +@archive_bp.delete('/', name='archive_delete_one') +@archive_bp.delete('/', 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('//generate_screenshot') +@archive_bp.post('//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)) diff --git a/modules/archive/lib.py b/modules/archive/lib.py index 184d9310..72caaf88 100644 --- a/modules/archive/lib.py +++ b/modules/archive/lib.py @@ -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() diff --git a/modules/archive/models.py b/modules/archive/models.py index a49fe8e9..96495626 100644 --- a/modules/archive/models.py +++ b/modules/archive/models.py @@ -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: diff --git a/modules/archive/test/test_api.py b/modules/archive/test/test_api.py index d35feb1d..6c76d231 100644 --- a/modules/archive/test/test_api.py +++ b/modules/archive/test/test_api.py @@ -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) diff --git a/modules/archive/test/test_lib.py b/modules/archive/test/test_lib.py index 286781d3..1fc4659a 100644 --- a/modules/archive/test/test_lib.py +++ b/modules/archive/test/test_lib.py @@ -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 diff --git a/modules/videos/channel/test/test_api.py b/modules/videos/channel/test/test_api.py index fde982da..ed088ba9 100644 --- a/modules/videos/channel/test/test_api.py +++ b/modules/videos/channel/test/test_api.py @@ -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' diff --git a/modules/videos/downloader.py b/modules/videos/downloader.py index 4d28dd1c..ad1bc23d 100755 --- a/modules/videos/downloader.py +++ b/modules/videos/downloader.py @@ -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: diff --git a/modules/videos/models.py b/modules/videos/models.py index cc7e9d98..fe77f541 100644 --- a/modules/videos/models.py +++ b/modules/videos/models.py @@ -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') diff --git a/modules/videos/test/test_api.py b/modules/videos/test/test_api.py index 0d30e0c8..145304b1 100644 --- a/modules/videos/test/test_api.py +++ b/modules/videos/test/test_api.py @@ -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.' diff --git a/modules/videos/test/test_downloader.py b/modules/videos/test/test_downloader.py index 258d8752..83756668 100644 --- a/modules/videos/test/test_downloader.py +++ b/modules/videos/test/test_downloader.py @@ -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() diff --git a/modules/videos/test/test_lib.py b/modules/videos/test/test_lib.py index 48959875..cdd2070d 100644 --- a/modules/videos/test/test_lib.py +++ b/modules/videos/test/test_lib.py @@ -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): diff --git a/modules/videos/video/api.py b/modules/videos/video/api.py index de8cb275..63a125f0 100644 --- a/modules/videos/video/api.py +++ b/modules/videos/video/api.py @@ -19,30 +19,30 @@ video_bp = Blueprint('Video', '/api/videos') logger = logger.getChild(__name__) -@video_bp.get('/video/') +@video_bp.get('/') @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//comments') +@video_bp.get('//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//captions') +@video_bp.get('//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/', name='Video Delete Many') -@video_bp.delete('/video/', name='Video Delete One') +@video_bp.delete('/', name='Video Delete Many') +@video_bp.delete('/', 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() diff --git a/modules/videos/video/lib.py b/modules/videos/video/lib.py index ddd37dff..876a1998 100644 --- a/modules/videos/video/lib.py +++ b/modules/videos/video/lib.py @@ -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') diff --git a/modules/videos/video/test/test_api.py b/modules/videos/video/test/test_api.py index f820a682..27cd7f2e 100644 --- a/modules/videos/video/test/test_api.py +++ b/modules/videos/video/test/test_api.py @@ -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 diff --git a/scripts/delete_similarly_named_videos.py b/scripts/delete_similarly_named_videos.py index ccb7dcaf..63c7b3e6 100644 --- a/scripts/delete_similarly_named_videos.py +++ b/scripts/delete_similarly_named_videos.py @@ -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.') diff --git a/wrolpi/collections/reorganize.py b/wrolpi/collections/reorganize.py index cd2dd157..5b48fc90 100644 --- a/wrolpi/collections/reorganize.py +++ b/wrolpi/collections/reorganize.py @@ -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() diff --git a/wrolpi/collections/test/test_reorganize.py b/wrolpi/collections/test/test_reorganize.py index 185487d1..4a70eed8 100644 --- a/wrolpi/collections/test/test_reorganize.py +++ b/wrolpi/collections/test/test_reorganize.py @@ -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" # ============================================================================ diff --git a/wrolpi/files/test/test_api.py b/wrolpi/files/test/test_api.py index 2edeaa24..15596599 100644 --- a/wrolpi/files/test/test_api.py +++ b/wrolpi/files/test/test_api.py @@ -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