修复跳屏问题

This commit is contained in:
eson 2025-06-03 00:44:35 +08:00
parent 728ba79eb6
commit 90c8df4ceb
5 changed files with 441 additions and 277 deletions

View File

@ -146,7 +146,7 @@ func MovieList(c *gin.Context) {
sortBy := c.Query("sort") sortBy := c.Query("sort")
order := c.Query("order") order := c.Query("order")
if sortBy == "" { if sortBy == "" {
sortBy = "created_time" // 默认按创建时间排序 sortBy = "duration" // 默认按创建时间排序
} }
// 应用排序 // 应用排序

View File

@ -13,6 +13,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
"time"
) )
// Movie 电影信息结构 // Movie 电影信息结构
@ -74,7 +75,7 @@ var Movies []*Movie // 存储所有电影信息的全局切
var MovieDict = make(map[string]*Movie) // 存储需要处理缩略图的视频字典 var MovieDict = make(map[string]*Movie) // 存储需要处理缩略图的视频字典
var MovieDictLock sync.Mutex // 保护MovieDict的并发访问 var MovieDictLock sync.Mutex // 保护MovieDict的并发访问
var IsRemakePNG = false // 是否重新生成所有PNG缩略图 var IsRemakePNG = true // 是否重新生成所有PNG缩略图
var Categories = []string{ // 分类 var Categories = []string{ // 分类
"15min", "30min", "60min", "大于60min", "最新添加"} "15min", "30min", "60min", "大于60min", "最新添加"}
@ -223,38 +224,55 @@ func generateThumbnail(movie *Movie) {
baseName := strings.TrimSuffix(movie.FileName, filepath.Ext(movie.FileName)) baseName := strings.TrimSuffix(movie.FileName, filepath.Ext(movie.FileName))
outputPath := filepath.Join("movie", baseName+".png") outputPath := filepath.Join("movie", baseName+".png")
// 根据时长选择不同的采样策略 // --- Start of improved logic ---
var filter string
switch {
case movie.Duration <= 2:
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,5)',scale=320:180,tile=3x3"
case movie.Duration <= 5:
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,10)',scale=320:180,tile=3x3"
case movie.Duration <= 30:
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,20)',scale=320:180,tile=3x3"
case movie.Duration <= 60:
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,35)',scale=320:180,tile=3x3"
default:
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,60)',scale=320:180,tile=3x3"
}
// 执行ffmpeg命令生成缩略图 // Fixed skip for the beginning of the video, as per original code's ffmpeg args
const skipStartSeconds = 10.0
// Number of frames we want in the tile (for a 3x3 grid)
const numFramesInTile = 9.0 // Use float for calculations
durationAfterSkip := float64(movie.Duration) - skipStartSeconds
var intervalSeconds float64
if durationAfterSkip <= 0.1 { // Use a small threshold like 0.1s
intervalSeconds = 0.05 // A very small interval to grab whatever is there.
} else {
if numFramesInTile > 1 {
intervalSeconds = durationAfterSkip / (numFramesInTile - 1.0)
} else {
intervalSeconds = durationAfterSkip
}
if intervalSeconds <= 0 {
intervalSeconds = 0.05 // Fallback to a tiny interval
}
}
filter := fmt.Sprintf("select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,%.3f)',scale=320:180,tile=3x3", intervalSeconds)
log.Printf("Movie: %s, OriginalDuration: %ds, SkipStart: %.1fs, DurationForSampling: %.2fs, CalculatedInterval: %.3fs",
movie.FileName, movie.Duration, skipStartSeconds, durationAfterSkip, intervalSeconds)
// Execute ffmpeg command
cmd := exec.Command("ffmpeg", cmd := exec.Command("ffmpeg",
"-ss", fmt.Sprintf("%.0f", skipStartSeconds), // Using the defined skipStartSeconds
"-i", movie.VideoPath, "-i", movie.VideoPath,
"-vf", filter, "-vf", filter,
"-frames:v", "1", "-frames:v", "1", // Crucial for outputting a single tiled image
"-q:v", "3", "-q:v", "3", // Quality for the frames before tiling/PNG compression
"-y", // 覆盖已存在文件 "-y", // Overwrite output file if it exists
outputPath, outputPath,
) )
var stderr bytes.Buffer var stderr bytes.Buffer
cmd.Stderr = &stderr cmd.Stderr = &stderr
startTime := time.Now()
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
log.Printf("生成缩略图失败: %s (%d min): %v\n错误输出: %s", // Assuming movie.Duration is in seconds, adjusted log from (%d min) to (%d s)
log.Printf("生成缩略图失败: %s (%d s): %v\n错误输出: %s",
movie.VideoPath, movie.Duration, err, stderr.String()) movie.VideoPath, movie.Duration, err, stderr.String())
} else { } else {
log.Printf("成功生成缩略图: %s", outputPath) log.Printf("成功生成缩略图: %s (耗时: %v)", outputPath, time.Since(startTime))
} }
} }

View File

@ -23,11 +23,11 @@ const categories = [
{ label: '最新添加', value: '最新添加' }, { label: '最新添加', value: '最新添加' },
]; ];
//
const SEARCH_CATEGORY = 'search'; const SEARCH_CATEGORY = 'search';
const LIMIT = 20; const LIMIT = 20;
const DEFAULT_CATEGORY = categories[0].value; const DEFAULT_CATEGORY = categories[0].value;
const usePersistedState = (key, defaultValue) => { const usePersistedState = (key, defaultValue) => {
const [state, setState] = useState(() => { const [state, setState] = useState(() => {
const stored = localStorage.getItem(key); const stored = localStorage.getItem(key);
@ -46,281 +46,307 @@ const Main = () => {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const isFirstLoad = useRef(true); const isFirstLoad = useRef(true);
const scrollListenerActive = useRef(false); const scrollListenerActive = useRef(false);
const skipScrollRestore = useRef(false);
const isPaginating = useRef(false); // New ref for pagination
// -
const [params, setParams] = usePersistedState('params', { const [params, setParams] = usePersistedState('params', {
lastCategory: DEFAULT_CATEGORY, lastCategory: DEFAULT_CATEGORY,
history: Object.fromEntries([ history: Object.fromEntries([
...categories.map(cat => [ ...categories.map(cat => [cat.value, { lastPage: 1, scrollPos: 0 }]),
cat.value, [SEARCH_CATEGORY, { lastPage: 1, scrollPos: 0, searchQuery: '' }] // Ensure searchQuery is part of history for search
{ lastPage: 1, scrollPos: 0 }
]),
//
[SEARCH_CATEGORY, { lastPage: 1, scrollPos: 0 }]
]), ]),
// searchQuery: '' // Global search query, might be redundant if using history.searchQuery
searchQuery: ''
}); });
const [movies, setMovies] = useState([]); const [movies, setMovies] = useState([]);
const [pagination, setPagination] = useState({ page: 1, total: 0, pages: 1 }); const [pagination, setPagination] = useState({ page: 1, total: 0, pages: 1 });
const currentCategory = params.lastCategory || DEFAULT_CATEGORY;
//
const [searchInput, setSearchInput] = useState(params.searchQuery || ''); const [searchInput, setSearchInput] = useState(params.searchQuery || '');
// const currentCategory = params.lastCategory || DEFAULT_CATEGORY;
const saveScrollPosition = useCallback((category = currentCategory) => { const currentCategoryHistory = params.history[currentCategory] || { lastPage: 1, scrollPos: 0 };
const currentScrollPos = window.scrollY;
setParams(prev => {
const updatedHistory = { const handleScrollPosition = useCallback((action, category = currentCategory) => {
...prev.history, if (action === 'save') {
[category]: { const currentScrollPos = window.scrollY;
...(prev.history[category] || { lastPage: 1, scrollPos: 0 }), setParams(prev => ({
scrollPos: currentScrollPos ...prev,
history: {
...prev.history,
[category]: {
...(prev.history[category] || { lastPage: 1 }),
scrollPos: currentScrollPos
}
} }
}; }));
} else if (action === 'restore') {
const scrollPos = params.history?.[category]?.scrollPos || 0;
// console.log(`Attempting to restore scroll for ${category} to ${scrollPos}`);
requestAnimationFrame(() => {
// Increased timeout slightly for better rendering chance
setTimeout(() => {
window.scrollTo(0, scrollPos);
// console.log(`Scrolled to ${scrollPos} for ${category}`);
}, 150);
});
}
}, [setParams, params.history, currentCategory]);
return { ...prev, history: updatedHistory };
});
}, [setParams, currentCategory]);
const setupScrollListener = useCallback(() => { const manageScrollListener = useCallback((action) => {
if (scrollListenerActive.current) return; const scrollHandler = () => {
const handleScroll = () => {
clearTimeout(window.scrollTimer); clearTimeout(window.scrollTimer);
window.scrollTimer = setTimeout(() => saveScrollPosition(), 100); window.scrollTimer = setTimeout(() => handleScrollPosition('save'), 200); // Debounce save
}; };
window.scrollHandler = scrollHandler; // Store to remove the correct one
window.addEventListener('scroll', handleScroll); if (action === 'setup' && !scrollListenerActive.current) {
scrollListenerActive.current = true; window.addEventListener('scroll', window.scrollHandler);
scrollListenerActive.current = true;
return () => { } else if (action === 'remove' && scrollListenerActive.current) {
window.removeEventListener('scroll', handleScroll);
clearTimeout(window.scrollTimer);
scrollListenerActive.current = false;
};
}, [saveScrollPosition]);
const removeScrollListener = useCallback(() => {
if (scrollListenerActive.current) {
window.removeEventListener('scroll', window.scrollHandler); window.removeEventListener('scroll', window.scrollHandler);
scrollListenerActive.current = false; scrollListenerActive.current = false;
clearTimeout(window.scrollTimer);
}
}, [handleScrollPosition]);
const fetchMovies = useCallback(async (category, page, search = '', options = {}) => {
if (options.skipRestore) {
skipScrollRestore.current = true;
} }
}, []);
// fetchMovies
const fetchMovies = useCallback(async (category, page, search = '') => {
setLoading(true); setLoading(true);
try { try {
const isSearch = category === SEARCH_CATEGORY; const isSearch = category === SEARCH_CATEGORY;
const isLatest = category === '最新添加'; const isLatest = category === '最新添加';
let apiUrl = `/movie/list?page=${page}&limit=${LIMIT}`; let apiUrl = `/movie/list?page=${page}&limit=${LIMIT}`;
if (isSearch) apiUrl += `&search=${encodeURIComponent(search)}`;
if (isSearch) { else if (isLatest) apiUrl += `&sort=created_time&order=desc`;
// else apiUrl += `&category=${encodeURIComponent(category)}`;
apiUrl += `&search=${encodeURIComponent(search)}`;
} else if (isLatest) {
//
apiUrl += `&sort=created_time&order=desc`;
} else {
//
apiUrl += `&category=${encodeURIComponent(category)}`;
}
const response = await axios.get(apiUrl); const response = await axios.get(apiUrl);
if (response.status !== 200) return; if (response.status !== 200) {
console.error("API Error:", response);
setMovies([]);
setPagination({ page, total: 0, pages: 1 });
return;
}
const { items, total } = response.data.data; const { items, total } = response.data.data;
const totalPages = Math.ceil(total / LIMIT); const totalPages = Math.ceil(total / LIMIT);
if (items.length === 0 && page > 1) { if (items.length === 0 && page > 1 && !isSearch) { // Don't auto-decrement page for search
setParams(prev => ({ setParams(prev => ({
...prev, ...prev,
history: { history: {
...prev.history, ...prev.history,
[category]: { ...prev.history[category], lastPage: page - 1 } [category]: { ...prev.history[category], lastPage: Math.max(1, page - 1) }
} }
})); }));
// Optionally, fetch page - 1 here, or let user do it.
// For now, just update the state and show no movies.
setMovies([]);
setPagination({ page: Math.max(1, page - 1), total, pages: totalPages });
return; return;
} }
setMovies(items); setMovies(items);
setPagination({ page, total, pages: totalPages }); setPagination({ page, total, pages: totalPages });
} catch (error) { } catch (error) {
console.error('Error fetching movies:', error); console.error('Error fetching movies:', error);
setMovies([]);
setPagination({ page, total: 0, pages: 1 });
} finally { } finally {
setLoading(false); setLoading(false); // This will trigger the useEffect[loading]
} }
}, [setParams]); }, [setParams]); // Removed currentCategory from deps as fetchMovies doesn't directly use it for scroll
//
const restoreScrollPosition = useCallback((category) => {
const scrollPos = params.history?.[category]?.scrollPos || 0;
requestAnimationFrame(() => { const handleTransition = useCallback((actionCallback) => {
setTimeout(() => window.scrollTo(0, scrollPos), 100); // console.log(`Transition: Saving scroll for ${currentCategory}`);
}); manageScrollListener('remove');
}, [params.history]); handleScrollPosition('save'); // Save scroll for the category we are leaving
actionCallback();
// manageScrollListener will be set up again in useEffect[loading]
}, [manageScrollListener, handleScrollPosition, currentCategory]);
//
// Initial Load
useEffect(() => { useEffect(() => {
if (!isFirstLoad.current) return; if (!isFirstLoad.current) return;
const category = currentCategory; const categoryToLoad = params.lastCategory || DEFAULT_CATEGORY;
const categoryHistory = params.history[category] || { lastPage: 1 }; const historyForCategory = params.history[categoryToLoad] || { lastPage: 1, scrollPos: 0 };
const pageToLoad = historyForCategory.lastPage;
let searchQueryToLoad = '';
if (categoryToLoad === SEARCH_CATEGORY) {
searchQueryToLoad = params.searchQuery || (historyForCategory.searchQuery || '');
setSearchInput(searchQueryToLoad); // Sync search input
}
// console.log(`Initial Load: Fetching ${categoryToLoad}, page ${pageToLoad}, search: "${searchQueryToLoad}"`);
fetchMovies(categoryToLoad, pageToLoad, searchQueryToLoad);
isFirstLoad.current = false;
}, []); // Runs only once on mount
//
if (category === SEARCH_CATEGORY) { // Scroll Management after data loading
fetchMovies(category, categoryHistory.lastPage, params.searchQuery); useEffect(() => {
if (loading || isFirstLoad.current) return; // Don't run if loading or still initial phase
manageScrollListener('remove'); // Ensure no listener interference
if (isPaginating.current) {
// console.log("Pagination: Scrolling to top");
window.scrollTo(0, 0);
isPaginating.current = false;
} else if (skipScrollRestore.current) {
// console.log(`Skipping scroll restore for ${currentCategory} (e.g., after rename)`);
skipScrollRestore.current = false;
} else { } else {
fetchMovies(category, categoryHistory.lastPage); // console.log(`Restoring scroll for ${currentCategory} (normal flow)`);
handleScrollPosition('restore', currentCategory);
} }
isFirstLoad.current = false; manageScrollListener('setup'); // Setup listener after scroll decision
}, [fetchMovies, currentCategory, params.history, params.searchQuery]);
}, [loading, currentCategory, handleScrollPosition, manageScrollListener]);
//
useEffect(() => {
if (loading || isFirstLoad.current) return;
restoreScrollPosition(currentCategory);
setupScrollListener();
}, [loading, restoreScrollPosition, currentCategory, setupScrollListener]);
// -
const handleCategoryChange = useCallback((newCategory) => { const handleCategoryChange = useCallback((newCategory) => {
removeScrollListener(); handleTransition(() => {
saveScrollPosition(); const newCategoryHistory = params.history[newCategory] || { lastPage: 1, scrollPos: 0 };
let searchQueryForNewCategory = '';
setParams(prev => {
const categoryHistory = prev.history[newCategory] || { lastPage: 1 };
// 使
if (newCategory === SEARCH_CATEGORY) { if (newCategory === SEARCH_CATEGORY) {
fetchMovies(newCategory, categoryHistory.lastPage, prev.searchQuery); searchQueryForNewCategory = params.searchQuery || (newCategoryHistory.searchQuery || '');
setSearchInput(searchQueryForNewCategory); // Sync search input
} else { } else {
fetchMovies(newCategory, categoryHistory.lastPage); setSearchInput(''); // Clear search input if not search category
} }
return { setParams(prev => ({ ...prev, lastCategory: newCategory }));
...prev, // console.log(`Category Change: Fetching ${newCategory}, page ${newCategoryHistory.lastPage}`);
lastCategory: newCategory fetchMovies(newCategory, newCategoryHistory.lastPage, searchQueryForNewCategory);
};
}); });
}, [removeScrollListener, saveScrollPosition, setParams, fetchMovies]); }, [handleTransition, setParams, fetchMovies, params.history, params.searchQuery]);
// -
const handlePageChange = useCallback((_, page) => { const handlePageChange = useCallback((_, page) => {
removeScrollListener(); // Save scroll position for the current page of the current category BEFORE fetching new page data
saveScrollPosition(); handleScrollPosition('save', currentCategory);
isPaginating.current = true; // Signal that this is a pagination action
setParams(prev => ({ setParams(prev => ({
...prev, ...prev,
history: { history: {
...prev.history, ...prev.history,
[currentCategory]: { [currentCategory]: { ...currentCategoryHistory, lastPage: page }
...prev.history[currentCategory],
lastPage: page,
scrollPos: 0
}
} }
})); }));
// const searchQueryForPageChange = currentCategory === SEARCH_CATEGORY ? (params.searchQuery || currentCategoryHistory.searchQuery || '') : '';
if (currentCategory === SEARCH_CATEGORY) { // console.log(`Page Change: Fetching ${currentCategory}, page ${page}, search: "${searchQueryForPageChange}"`);
fetchMovies(currentCategory, page, params.searchQuery); fetchMovies(currentCategory, page, searchQueryForPageChange);
} else { // Scrolling to top will be handled by useEffect[loading] due to isPaginating.current
fetchMovies(currentCategory, page); }, [setParams, fetchMovies, currentCategory, params.searchQuery, currentCategoryHistory, handleScrollPosition]);
}
window.scrollTo(0, 0);
}, [removeScrollListener, saveScrollPosition, setParams, fetchMovies, currentCategory, params.searchQuery]);
//
const handleMovieCardClick = useCallback(() => {
removeScrollListener();
saveScrollPosition();
}, [removeScrollListener, saveScrollPosition]);
//
const handleSearchSubmit = useCallback(() => { const handleSearchSubmit = useCallback(() => {
if (!searchInput.trim()) return; const trimmedSearch = searchInput.trim();
if (!trimmedSearch) return;
removeScrollListener(); handleTransition(() => {
saveScrollPosition(); setParams(prev => ({
setParams(prev => {
//
const updatedParams = {
...prev, ...prev,
lastCategory: SEARCH_CATEGORY, lastCategory: SEARCH_CATEGORY,
searchQuery: searchInput.trim(), searchQuery: trimmedSearch, // Update global search query
history: { history: {
...prev.history, ...prev.history,
[SEARCH_CATEGORY]: { [SEARCH_CATEGORY]: { // Reset search history to page 1 for new search
...prev.history[SEARCH_CATEGORY], lastPage: 1,
lastPage: 1 // scrollPos: 0, // New search starts at top
searchQuery: trimmedSearch
} }
} }
}; }));
// console.log(`Search Submit: Fetching ${SEARCH_CATEGORY}, page 1, search: "${trimmedSearch}"`);
// fetchMovies(SEARCH_CATEGORY, 1, trimmedSearch);
fetchMovies(SEARCH_CATEGORY, 1, searchInput.trim());
return updatedParams;
}); });
}, [removeScrollListener, saveScrollPosition, setParams, fetchMovies, searchInput]); }, [handleTransition, setParams, fetchMovies, searchInput]);
//
const handleClearSearch = useCallback(() => { const handleClearSearch = useCallback(() => {
if (!searchInput) return; if (!searchInput && currentCategory !== SEARCH_CATEGORY) return;
setSearchInput(''); setSearchInput('');
// If we are currently in search results, transition to default category
//
if (currentCategory === SEARCH_CATEGORY) { if (currentCategory === SEARCH_CATEGORY) {
setParams(prev => ({ handleTransition(() => {
...prev, const defaultCategoryHistory = params.history[DEFAULT_CATEGORY] || { lastPage: 1, scrollPos: 0 };
lastCategory: DEFAULT_CATEGORY, setParams(prev => ({
searchQuery: '' ...prev,
})); lastCategory: DEFAULT_CATEGORY,
searchQuery: '', // Clear global search query
// // We can choose to preserve or reset params.history[SEARCH_CATEGORY].searchQuery
const categoryHistory = params.history[DEFAULT_CATEGORY] || { lastPage: 1 }; // For now, let's clear it in history as well if we are clearing and navigating away
fetchMovies(DEFAULT_CATEGORY, categoryHistory.lastPage); history: {
...prev.history,
[SEARCH_CATEGORY]: { ...params.history[SEARCH_CATEGORY], searchQuery: '' }
}
}));
// console.log(`Clear Search (was search category): Fetching ${DEFAULT_CATEGORY}, page ${defaultCategoryHistory.lastPage}`);
fetchMovies(DEFAULT_CATEGORY, defaultCategoryHistory.lastPage);
});
} else { } else {
// // If not in search results, just clear the persisted search query
setParams(prev => ({ setParams(prev => ({ ...prev, searchQuery: '' }));
...prev,
searchQuery: ''
}));
} }
}, [currentCategory, fetchMovies, params.history, searchInput, setParams]); }, [currentCategory, fetchMovies, params.history, searchInput, setParams, handleTransition]);
//
const handleSearchChange = useCallback((e) => {
setSearchInput(e.target.value);
}, []);
// const handleRename = useCallback(async (oldName, newName) => {
try {
const response = await axios.post('/movie/rename', { old_name: oldName, new_name: newName });
if (response.data.code === 200) {
// Refresh current view data, but skip scroll restoration
const pageToRefresh = currentCategoryHistory.lastPage;
const searchQueryForRefresh = currentCategory === SEARCH_CATEGORY ? (params.searchQuery || currentCategoryHistory.searchQuery || '') : '';
// console.log(`Rename: Refreshing ${currentCategory}, page ${pageToRefresh}, search: "${searchQueryForRefresh}" with skipRestore`);
await fetchMovies(currentCategory, pageToRefresh, searchQueryForRefresh, { skipRestore: true });
} else {
throw new Error(response.data.message || '重命名失败');
}
} catch (error) {
console.error('重命名错误:', error);
throw error; // Re-throw to allow MovieCard to handle it if needed
}
}, [fetchMovies, currentCategory, currentCategoryHistory, params.searchQuery]);
const handleMovieCardClick = useCallback(() => {
// This is a navigation, so save scroll state
// console.log(`Movie Card Click: Saving scroll for ${currentCategory} before navigating away.`);
handleScrollPosition('save', currentCategory);
// No need for manageScrollListener('remove') here as the component might unmount
// or if it's an in-app navigation, the next component will manage its own scroll.
}, [handleScrollPosition, currentCategory]);
const handleSearchChange = useCallback((e) => setSearchInput(e.target.value), []);
const handleSearchKeyDown = useCallback((e) => { const handleSearchKeyDown = useCallback((e) => {
if (e.key === 'Enter') { if (e.key === 'Enter') handleSearchSubmit();
handleSearchSubmit();
}
}, [handleSearchSubmit]); }, [handleSearchSubmit]);
// // Cleanup scroll listener on unmount
useEffect(() => removeScrollListener, [removeScrollListener]); useEffect(() => {
return () => {
manageScrollListener('remove');
};
}, [manageScrollListener]);
//
const paginationComponent = ( const paginationComponent = movies.length > 0 && pagination.pages > 1 && (
<Pagination <Pagination
count={pagination.pages} count={pagination.pages}
page={pagination.page} page={pagination.page}
@ -329,35 +355,8 @@ const Main = () => {
/> />
); );
const handleRename = useCallback(async (oldName, newName) => {
try {
const response = await axios.post('/movie/rename', {
old_name: oldName,
new_name: newName
});
if (response.data.code === 200) {
//
const category = params.lastCategory;
const categoryHistory = params.history[category] || { lastPage: 1 };
if (category === SEARCH_CATEGORY) {
await fetchMovies(category, categoryHistory.lastPage, params.searchQuery);
} else {
await fetchMovies(category, categoryHistory.lastPage);
}
} else {
throw new Error(response.data.message || '重命名失败');
}
} catch (error) {
console.error('重命名错误:', error);
throw error;
}
}, [fetchMovies, params.lastCategory, params.history, params.searchQuery]);
return ( return (
<Container style={{ marginTop: 20 }}> <Container style={{ marginTop: 20 }}>
{/* 添加搜索框 */}
<TextField <TextField
fullWidth fullWidth
variant="outlined" variant="outlined"
@ -366,16 +365,10 @@ const Main = () => {
onChange={handleSearchChange} onChange={handleSearchChange}
onKeyDown={handleSearchKeyDown} onKeyDown={handleSearchKeyDown}
InputProps={{ InputProps={{
startAdornment: ( startAdornment: <InputAdornment position="start"><SearchIcon /></InputAdornment>,
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
),
endAdornment: searchInput && ( endAdornment: searchInput && (
<InputAdornment position="end"> <InputAdornment position="end">
<IconButton onClick={handleClearSearch}> <IconButton onClick={handleClearSearch} edge="end"><ClearIcon /></IconButton>
<ClearIcon />
</IconButton>
</InputAdornment> </InputAdornment>
) )
}} }}
@ -384,28 +377,33 @@ const Main = () => {
<CategoryNav <CategoryNav
categories={categories} categories={categories}
currentCategory={currentCategory === SEARCH_CATEGORY ? '' : currentCategory} currentCategory={currentCategory === SEARCH_CATEGORY ? SEARCH_CATEGORY : currentCategory} // Pass SEARCH_CATEGORY special value
onCategoryChange={handleCategoryChange} onCategoryChange={handleCategoryChange}
/> />
{/* 显示当前搜索状态 */}
{currentCategory === SEARCH_CATEGORY && ( {currentCategory === SEARCH_CATEGORY && (
<div style={{ textAlign: 'center', margin: '10px 0' }}> <div style={{ textAlign: 'center', margin: '10px 0' }}>
搜索: "{params.searchQuery}" ({pagination.total} 个结果) 搜索: "{params.searchQuery || currentCategoryHistory.searchQuery}" ({pagination.total} 个结果)
</div> </div>
)} )}
{paginationComponent} {paginationComponent}
{loading ? ( {loading && <CircularProgress sx={{ display: 'block', margin: '20px auto' }} />}
<CircularProgress sx={{ display: 'block', margin: '20px auto' }} />
) : ( {!loading && movies.length === 0 && (
<div style={{ textAlign: 'center', margin: '20px 0', color: 'gray' }}>
没有找到结果
</div>
)}
{!loading && movies.length > 0 && (
<Grid container spacing={2} sx={{ mt: 0.5 }}> <Grid container spacing={2} sx={{ mt: 0.5 }}>
{movies.map(item => ( {movies.map(item => (
<Grid item xs={6} sm={4} md={3} lg={2} key={item.filename}> <Grid item xs={6} sm={4} md={3} lg={2} key={item.filename}>
<Link <Link
to={`/res/${item.filename}`} to={`/res/${item.filename}`}
style={{ textDecoration: 'none', paddingBottom: 10 }} style={{ textDecoration: 'none' }} // Removed paddingBottom, handle in Card
onClick={handleMovieCardClick} onClick={handleMovieCardClick}
> >
<MovieCard movie={item} config={config} onRename={handleRename} /> <MovieCard movie={item} config={config} onRename={handleRename} />

View File

@ -1,11 +1,27 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Card, CardContent, CardMedia, Typography, IconButton, TextField, Dialog, DialogActions, DialogContent, DialogTitle, Button } from '@mui/material'; import {
Card,
CardContent,
CardMedia,
Typography,
IconButton,
TextField,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Button,
Snackbar,
Alert
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit'; import EditIcon from '@mui/icons-material/Edit';
import { styled } from '@mui/system'; import { styled } from '@mui/system';
const MovieCard = ({ movie, config, onRename }) => { const MovieCard = ({ movie, config, onRename }) => {
const [newName, setNewName] = useState(''); const [newName, setNewName] = useState('');
const [openDialog, setOpenDialog] = useState(false); const [openDialog, setOpenDialog] = useState(false);
const [error, setError] = useState(null);
const [openSnackbar, setOpenSnackbar] = useState(false);
const truncateFilename = (filename, maxLength) => { const truncateFilename = (filename, maxLength) => {
return filename.length > maxLength return filename.length > maxLength
@ -15,7 +31,7 @@ const MovieCard = ({ movie, config, onRename }) => {
const handleRenameClick = (e) => { const handleRenameClick = (e) => {
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); // e.preventDefault();
const lastDotIndex = movie.filename.lastIndexOf('.'); const lastDotIndex = movie.filename.lastIndexOf('.');
const nameWithoutExt = lastDotIndex === -1 const nameWithoutExt = lastDotIndex === -1
? movie.filename ? movie.filename
@ -35,7 +51,7 @@ const MovieCard = ({ movie, config, onRename }) => {
const handleRenameSubmit = async (e) => { const handleRenameSubmit = async (e) => {
if (e) { if (e) {
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); // e.preventDefault();
} }
if (!newName.trim()) return; if (!newName.trim()) return;
@ -55,11 +71,21 @@ const MovieCard = ({ movie, config, onRename }) => {
await onRename(movie.filename, fullNewName); await onRename(movie.filename, fullNewName);
handleDialogClose(); handleDialogClose();
} catch (error) { } catch (error) {
console.error('重命名失败:', error);
// message error.message
setError(
error.response?.data?.message ||
error.message ||
'重命名失败,请稍后重试'
);
setOpenSnackbar(true);
} }
}; };
// const handleCloseSnackbar = () => {
setOpenSnackbar(false);
};
const handleKeyPress = (e) => { const handleKeyPress = (e) => {
if (e.key === 'Enter') { if (e.key === 'Enter') {
e.stopPropagation(); e.stopPropagation();
@ -68,7 +94,6 @@ const MovieCard = ({ movie, config, onRename }) => {
} }
}; };
//
const handleDialogContentClick = (e) => { const handleDialogContentClick = (e) => {
e.stopPropagation(); e.stopPropagation();
}; };
@ -123,7 +148,7 @@ const MovieCard = ({ movie, config, onRename }) => {
<Dialog <Dialog
open={openDialog} open={openDialog}
onClose={handleDialogClose} onClose={handleDialogClose}
onClick={handleDialogContentClick} // onClick={handleDialogContentClick}
maxWidth="sm" maxWidth="sm"
fullWidth fullWidth
> >
@ -138,29 +163,42 @@ const MovieCard = ({ movie, config, onRename }) => {
variant="standard" variant="standard"
value={newName} value={newName}
onChange={(e) => setNewName(e.target.value)} onChange={(e) => setNewName(e.target.value)}
onKeyPress={handleKeyPress} // onKeyPress={handleKeyPress}
helperText="请不要修改文件后缀" helperText="请不要修改文件后缀"
onClick={(e) => e.stopPropagation()} // onClick={(e) => e.stopPropagation()}
/> />
</DialogContent> </DialogContent>
<DialogActions onClick={handleDialogContentClick}> <DialogActions onClick={handleDialogContentClick}>
<Button <Button
onClick={handleDialogClose} onClick={handleDialogClose}
onMouseDown={(e) => e.stopPropagation()} // onMouseDown={(e) => e.stopPropagation()}
> >
取消 取消
</Button> </Button>
<Button <Button
onClick={handleRenameSubmit} onClick={handleRenameSubmit}
onMouseDown={(e) => e.stopPropagation()} // onMouseDown={(e) => e.stopPropagation()}
variant="contained" variant="contained"
> >
确定 确定
</Button> </Button>
</DialogActions> </DialogActions>
</Dialog> </Dialog>
<Snackbar
open={openSnackbar}
autoHideDuration={6000}
onClose={handleCloseSnackbar}
anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
>
<Alert onClose={handleCloseSnackbar} severity="error" sx={{ width: '100%' }}>
{error}
</Alert>
</Snackbar>
</> </>
); );
}; };
export default MovieCard; export default MovieCard;

View File

@ -1,43 +1,153 @@
import {React, useContext, useState} from 'react'; import React, { useContext, useState, useRef, useEffect } from 'react';
import { useParams } from 'react-router-dom'; import { useParams, useNavigate } from 'react-router-dom';
import Container from '@mui/material/Container'; import Container from '@mui/material/Container';
import Typography from '@mui/material/Typography'; import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import ConfigContext from '../Config'; import ConfigContext from '../Config';
import ReactPlayer from 'react-player'; import ReactPlayer from 'react-player';
const VideoPlayer = () => { const VideoPlayer = () => {
const config = useContext(ConfigContext); const config = useContext(ConfigContext);
const { filename } = useParams(); const { filename } = useParams();
const navigate = useNavigate();
const playerRef = useRef(null);
const [isFullScreen, setIsFullScreen] = useState(false); const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [isMobile, setIsMobile] = useState(false);
const handleFullScreenChange = (player) => { //
setIsFullScreen(!isFullScreen); useEffect(() => {
if (isFullScreen) { const checkMobile = () => {
player.exitFullscreen(); setIsMobile(window.innerWidth <= 768);
} else { };
player.requestFullscreen();
} checkMobile();
window.addEventListener('resize', checkMobile);
return () => window.removeEventListener('resize', checkMobile);
}, []);
//
const decodedFilename = decodeURIComponent(filename);
const videoUrl = `${window.location.origin}/res/${filename}`;
const handleReady = () => {
setLoading(false);
}; };
const handleError = (error) => {
console.error('Video error:', error);
setError('视频加载失败');
setLoading(false);
};
//
if (error) {
return (
<Container sx={{ mt: 2 }}>
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
<IconButton onClick={() => navigate(-1)} sx={{ mr: 1 }}>
<ArrowBackIcon />
</IconButton>
<Typography variant="h6" noWrap>
{decodedFilename}
</Typography>
</Box>
<Box sx={{ textAlign: 'center', p: 4 }}>
<Typography color="error">{error}</Typography>
</Box>
</Container>
);
}
return ( return (
<Container> <Box sx={{
<Typography variant="h6" gutterBottom> bgcolor: 'black',
{filename} minHeight: '100vh',
</Typography> display: 'flex',
<ReactPlayer flexDirection: 'column'
url={`${window.location.origin}/res/${filename}`} }}>
controls {/* 标题栏 */}
width="100%" <Box sx={{
height="auto" p: isMobile ? 1 : 2,
playing={isFullScreen} display: 'flex',
onReady={handleFullScreenChange} alignItems: 'center',
/> bgcolor: 'rgba(0,0,0,0.8)',
</Container> color: 'white',
position: 'sticky',
top: 0,
zIndex: 1
}}>
<IconButton
onClick={() => navigate(-1)}
sx={{ color: 'white', mr: 1 }}
size={isMobile ? 'small' : 'medium'}
>
<ArrowBackIcon />
</IconButton>
<Typography
variant={isMobile ? 'subtitle1' : 'h6'}
noWrap
sx={{ flexGrow: 1 }}
>
{decodedFilename}
</Typography>
</Box>
{/* 视频播放器容器 */}
<Box sx={{
flexGrow: 1,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
position: 'relative'
}}>
{loading && (
<Typography sx={{ color: 'white', position: 'absolute' }}>
加载中...
</Typography>
)}
<ReactPlayer
ref={playerRef}
url={videoUrl}
controls
width="100%"
height={isMobile ? "50vh" : "70vh"}
onReady={handleReady}
onError={handleError}
config={{
file: {
attributes: {
playsInline: true, //
preload: 'metadata'
}
}
}}
style={{
maxWidth: '100%',
maxHeight: '100%'
}}
/>
</Box>
{/* 底部信息(仅桌面端显示) */}
{!isMobile && (
<Box sx={{
p: 2,
color: 'rgba(255,255,255,0.7)',
textAlign: 'center',
fontSize: '0.8rem'
}}>
<Typography variant="caption">
提示双击视频可全屏播放
</Typography>
</Box>
)}
</Box>
); );
}; };
export default VideoPlayer; export default VideoPlayer;