mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-19 22:46:20 -05:00
Video page: edit the description in Edit > Edit
PUT /api/videos/<file_group_id> now takes optional title and description and changes only the fields given; an empty description clears it. The modal sends only what changed and refetches the description after saving. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
cc25e342d4
commit
ca1dc82aa9
9 changed files with 111 additions and 29 deletions
|
|
@ -236,9 +236,10 @@ export async function getVideo(fileGroupId) {
|
|||
return [data['file_group'], data['prev'], data['next']];
|
||||
}
|
||||
|
||||
export async function updateVideo(fileGroupId, {title}) {
|
||||
// Edits the Video's details (written to its info json). Returns the updated video file group.
|
||||
const response = await apiPut(`${VIDEOS_API}/${fileGroupId}`, {title});
|
||||
export async function updateVideo(fileGroupId, {title, description}) {
|
||||
// Edits the Video's details (written to its info json). Only the fields given are changed.
|
||||
// Returns the updated video file group.
|
||||
const response = await apiPut(`${VIDEOS_API}/${fileGroupId}`, {title, description});
|
||||
if (!response.ok) {
|
||||
const message = await getErrorMessage(response, 'Unable to save the video. See server logs.');
|
||||
toast({type: 'error', title: 'Failed to save', description: message, time: 5000});
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import React, {useEffect, useRef, useState} from 'react';
|
||||
import {cancelJob, fetchVideoDownloadDefaults, getJob, transcodeVideo, updateVideo} from '../api';
|
||||
import {useWROLMode} from '../hooks/customHooks';
|
||||
import {Button, Confirm, Group, Icon, Menu, Modal, Progress, Select, Stack, Status, Text, TextInput, toast} from './ui';
|
||||
import {Button, Confirm, Group, Icon, Menu, Modal, Progress, Select, Stack, Status, Text, Textarea, TextInput, toast} from './ui';
|
||||
import {
|
||||
TRANSCODE_COPY,
|
||||
transcodeAudioCodecOptions,
|
||||
|
|
@ -272,24 +272,32 @@ export function TranscodeModal({open, onClose, fileGroupId, video, onComplete})
|
|||
* Edit a Video's details. The change is written to the Video's info json, so it survives a
|
||||
* refresh; a re-download of the Video's metadata will overwrite it.
|
||||
*/
|
||||
export function EditVideoModal({open, onClose, fileGroupId, videoFile, onSaved}) {
|
||||
export function EditVideoModal({open, onClose, fileGroupId, videoFile, description: currentDescription, onSaved}) {
|
||||
const [title, setTitle] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
// Start from the current details on every open, discarding an abandoned edit.
|
||||
setTitle(videoFile?.title || '');
|
||||
setDescription(currentDescription || '');
|
||||
}
|
||||
}, [open, videoFile?.title]);
|
||||
}, [open, videoFile?.title, currentDescription]);
|
||||
|
||||
const trimmed = title.trim();
|
||||
const unchanged = trimmed === (videoFile?.title || '');
|
||||
const titleChanged = trimmed !== (videoFile?.title || '');
|
||||
const descriptionChanged = description !== (currentDescription || '');
|
||||
const unchanged = !titleChanged && !descriptionChanged;
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const updated = await updateVideo(fileGroupId, {title: trimmed});
|
||||
// Send only what changed, so an untouched field is never rewritten.
|
||||
const changes = {};
|
||||
if (titleChanged) changes.title = trimmed;
|
||||
if (descriptionChanged) changes.description = description;
|
||||
const updated = await updateVideo(fileGroupId, changes);
|
||||
toast({type: 'success', title: 'Saved', description: 'The video was updated.', time: 3000});
|
||||
if (onSaved) await onSaved(updated);
|
||||
onClose();
|
||||
|
|
@ -304,10 +312,8 @@ export function EditVideoModal({open, onClose, fileGroupId, videoFile, onSaved})
|
|||
return <Modal open={open} onClose={onClose} size='small'>
|
||||
<Modal.Header>Edit Video</Modal.Header>
|
||||
<Modal.Content>
|
||||
<form onSubmit={e => {
|
||||
e.preventDefault();
|
||||
if (trimmed && !unchanged && !saving) handleSave();
|
||||
}}>
|
||||
{/* No submit-on-Enter: Enter belongs to the description's new lines. */}
|
||||
<form onSubmit={e => e.preventDefault()}>
|
||||
<TextInput
|
||||
label='Title'
|
||||
value={title}
|
||||
|
|
@ -315,6 +321,15 @@ export function EditVideoModal({open, onClose, fileGroupId, videoFile, onSaved})
|
|||
error={!trimmed ? 'A title is required' : null}
|
||||
data-autofocus
|
||||
/>
|
||||
<Textarea
|
||||
label='Description'
|
||||
value={description}
|
||||
onChange={e => setDescription(e.currentTarget.value)}
|
||||
autosize
|
||||
minRows={4}
|
||||
maxRows={14}
|
||||
mt='sm'
|
||||
/>
|
||||
<Text size='sm' c='var(--muted)' mt='sm'>
|
||||
Saved to the video's info json. Refreshing the video from its source will replace it.
|
||||
</Text>
|
||||
|
|
@ -342,7 +357,7 @@ export function EditVideoModal({open, onClose, fileGroupId, videoFile, onSaved})
|
|||
* page can fetch the Video again (its path and codecs changed). `onDelete` is awaited after the
|
||||
* user confirms; the page decides what happens next (navigate away, or the tagged-files prompt).
|
||||
*/
|
||||
export function VideoEditMenu({videoFile, video, onRefresh, onTranscodeComplete, onDelete, onSaved}) {
|
||||
export function VideoEditMenu({videoFile, video, description, onRefresh, onTranscodeComplete, onDelete, onSaved}) {
|
||||
const wrolModeEnabled = useWROLMode();
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [transcodeOpen, setTranscodeOpen] = useState(false);
|
||||
|
|
@ -414,6 +429,7 @@ export function VideoEditMenu({videoFile, video, onRefresh, onTranscodeComplete,
|
|||
onClose={() => setEditOpen(false)}
|
||||
fileGroupId={videoFile?.id}
|
||||
videoFile={videoFile}
|
||||
description={description}
|
||||
onSaved={onSaved}
|
||||
/>
|
||||
<Confirm
|
||||
|
|
|
|||
|
|
@ -106,22 +106,34 @@ describe('EditVideoModal', () => {
|
|||
const onSaved = jest.fn().mockResolvedValue(undefined);
|
||||
const onClose = jest.fn();
|
||||
renderWithProviders(
|
||||
<EditVideoModal open={true} onClose={onClose} fileGroupId={7} videoFile={videoFile} onSaved={onSaved}/>,
|
||||
<EditVideoModal open={true} onClose={onClose} fileGroupId={7} videoFile={videoFile}
|
||||
description='Old words' onSaved={onSaved}/>,
|
||||
);
|
||||
|
||||
const input = screen.getByLabelText('Title');
|
||||
expect(input).toHaveValue('Old Title');
|
||||
expect(screen.getByLabelText('Description')).toHaveValue('Old words');
|
||||
// Nothing changed yet: Save is disabled.
|
||||
expect(screen.getByRole('button', {name: /Save/})).toBeDisabled();
|
||||
|
||||
fireEvent.change(input, {target: {value: ' New Title '}});
|
||||
fireEvent.click(screen.getByRole('button', {name: /Save/}));
|
||||
|
||||
// Only the changed field is sent.
|
||||
await waitFor(() => expect(updateVideo).toHaveBeenCalledWith(7, {title: 'New Title'}));
|
||||
await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1));
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('saves a changed description on its own, including clearing it', async () => {
|
||||
renderWithProviders(
|
||||
<EditVideoModal open={true} onClose={jest.fn()} fileGroupId={7} videoFile={videoFile} description='Old words'/>,
|
||||
);
|
||||
fireEvent.change(screen.getByLabelText('Description'), {target: {value: ''}});
|
||||
fireEvent.click(screen.getByRole('button', {name: /Save/}));
|
||||
await waitFor(() => expect(updateVideo).toHaveBeenCalledWith(7, {description: ''}));
|
||||
});
|
||||
|
||||
test('an empty title cannot be saved', () => {
|
||||
renderWithProviders(<EditVideoModal open={true} onClose={jest.fn()} fileGroupId={7} videoFile={videoFile}/>);
|
||||
fireEvent.change(screen.getByLabelText('Title'), {target: {value: ' '}});
|
||||
|
|
|
|||
|
|
@ -231,7 +231,7 @@ function VideoPage({videoFile, prevFile, nextFile, fetchVideo, ...props}) {
|
|||
// Get the Video's channel, fallback to the URL's channel id.
|
||||
const {channelId} = useParams();
|
||||
const {channel} = useChannel(video && video.channel_id ? video.channel_id : channelId);
|
||||
const {comments, description: videoDescription} = useVideoExtras(videoFile?.id);
|
||||
const {comments, description: videoDescription, fetchDescription} = useVideoExtras(videoFile?.id);
|
||||
const {captions, captionsLoading, fetchCaptions} = useVideoCaptions(videoFile?.id);
|
||||
|
||||
const mediaTitle = videoFile ? (videoFile.title || videoFile.stem || videoFile.name) : null;
|
||||
|
|
@ -495,7 +495,11 @@ function VideoPage({videoFile, prevFile, nextFile, fetchVideo, ...props}) {
|
|||
onRefresh={handleRefresh}
|
||||
onTranscodeComplete={fetchVideo}
|
||||
onDelete={async () => await handleDeleteVideo(videoFile.id)}
|
||||
onSaved={fetchVideo}
|
||||
description={videoDescription}
|
||||
onSaved={async () => {
|
||||
await fetchVideo();
|
||||
await fetchDescription();
|
||||
}}
|
||||
/>
|
||||
<AddToPlaylistButton fileGroupId={videoFile.id}/>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -771,7 +771,7 @@ export const useVideoExtras = (fileGroupId) => {
|
|||
}
|
||||
}, [fileGroupId]);
|
||||
|
||||
return {comments, description}
|
||||
return {comments, description, fetchDescription}
|
||||
}
|
||||
|
||||
export const useVideoCaptions = (fileGroupId) => {
|
||||
|
|
|
|||
|
|
@ -188,7 +188,9 @@ class VideoSearchRequest:
|
|||
|
||||
@dataclass
|
||||
class VideoUpdateRequest:
|
||||
title: str
|
||||
# Only the fields given are changed.
|
||||
title: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
|
|||
|
|
@ -44,6 +44,36 @@ def test_update_video_title_creates_info_json(test_session, test_directory, vide
|
|||
assert video.info_json_path.name in [i['path'] for i in video.file_group.files], 'The new file is tracked'
|
||||
|
||||
|
||||
def test_update_video_description(test_session, test_directory, video_factory):
|
||||
"""The description is written to the info json and indexed; the title is untouched when not
|
||||
given. An empty description clears it."""
|
||||
video = video_factory(with_info_json={'title': 'Kept', 'description': 'old words'})
|
||||
test_session.commit()
|
||||
assert video.file_group.c_text == 'old words'
|
||||
|
||||
update_video(video.file_group_id, description='new words\nsecond line')
|
||||
|
||||
test_session.expire_all()
|
||||
video = Video.find_by_file_group_id(test_session, video.file_group_id)
|
||||
assert video.file_group.title == 'Kept'
|
||||
assert video.file_group.c_text == 'new words\nsecond line'
|
||||
assert video.get_description() == 'new words\nsecond line'
|
||||
assert json.loads(video.info_json_path.read_text())['description'] == 'new words\nsecond line'
|
||||
|
||||
update_video(video.file_group_id, description='')
|
||||
test_session.expire_all()
|
||||
video = Video.find_by_file_group_id(test_session, video.file_group_id)
|
||||
assert video.get_description() is None
|
||||
assert video.file_group.title == 'Kept'
|
||||
|
||||
|
||||
def test_update_video_nothing(test_session, video_factory):
|
||||
video = video_factory(with_info_json={'title': 'Old'})
|
||||
test_session.commit()
|
||||
with pytest.raises(ValidationError):
|
||||
update_video(video.file_group_id)
|
||||
|
||||
|
||||
def test_update_video_title_empty(test_session, video_factory):
|
||||
video = video_factory(with_info_json={'title': 'Old'})
|
||||
test_session.commit()
|
||||
|
|
@ -67,6 +97,16 @@ async def test_video_update_api(async_client, test_session, video_factory, wrol_
|
|||
request, response = await async_client.put(f'/api/videos/{video.file_group_id}', content=json.dumps({'title': ''}))
|
||||
assert response.status == 400
|
||||
|
||||
request, response = await async_client.put(f'/api/videos/{video.file_group_id}', content=json.dumps({}))
|
||||
assert response.status == 400
|
||||
|
||||
request, response = await async_client.put(f'/api/videos/{video.file_group_id}',
|
||||
content=json.dumps({'description': 'about it'}))
|
||||
assert response.status == 200, response.json
|
||||
assert response.json['file_group']['title'] == 'Edited', 'Title untouched'
|
||||
request, response = await async_client.get(f'/api/videos/{video.file_group_id}/description')
|
||||
assert response.json['description'] == 'about it'
|
||||
|
||||
request, response = await async_client.put('/api/videos/999999', content=json.dumps({'title': 'x'}))
|
||||
assert response.status == 404
|
||||
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ def video_get(request: Request, file_group_id: int):
|
|||
@validate(schema.VideoUpdateRequest)
|
||||
@wrol_mode_check
|
||||
async def video_update(_: Request, file_group_id: int, body: schema.VideoUpdateRequest):
|
||||
lib.update_video(file_group_id, body.title)
|
||||
lib.update_video(file_group_id, title=body.title, description=body.description)
|
||||
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})
|
||||
|
||||
|
|
|
|||
|
|
@ -50,28 +50,35 @@ def get_video(file_group_id: int) -> Video:
|
|||
return video
|
||||
|
||||
|
||||
def update_video(file_group_id: int, title: str) -> Video:
|
||||
def update_video(file_group_id: int, title: str = None, description: str = None) -> Video:
|
||||
"""Edit a Video's details. The files are the source of truth, so the change is written to the
|
||||
Video's .info.json (created if missing) and the Video is validated again from it.
|
||||
Video's .info.json (created if missing) and the Video is validated again from it. Only the
|
||||
fields given (not None) are changed; an empty description clears it.
|
||||
|
||||
A later re-download of the Video's metadata will overwrite the info json, and this edit with
|
||||
it.
|
||||
|
||||
@raise UnknownVideo: if the Video can not be found
|
||||
@raise ValidationError: when the title is empty
|
||||
@raise ValidationError: when nothing is given, or the title is empty
|
||||
"""
|
||||
from wrolpi.errors import ValidationError
|
||||
title = (title or '').strip()
|
||||
if not title:
|
||||
raise ValidationError('Video title cannot be empty')
|
||||
if title is None and description is None:
|
||||
raise ValidationError('Nothing to change')
|
||||
if title is not None:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValidationError('Video title cannot be empty')
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
video = Video.find_by_file_group_id(session, file_group_id)
|
||||
info_json = video.get_info_json() or dict()
|
||||
# `extract_video_info_json` prefers fulltitle over title; keep the two in agreement.
|
||||
info_json['title'] = title
|
||||
info_json['fulltitle'] = title
|
||||
# Keep the file as it was, other than the title.
|
||||
if title is not None:
|
||||
# `extract_video_info_json` prefers fulltitle over title; keep the two in agreement.
|
||||
info_json['title'] = title
|
||||
info_json['fulltitle'] = title
|
||||
if description is not None:
|
||||
info_json['description'] = description
|
||||
# Keep the file as it was, other than the edited fields.
|
||||
video.replace_info_json(info_json, clean=False)
|
||||
# Re-derive the title (and search text) from the file just written.
|
||||
video.validate(session)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue