feat: task scheduler; feat: ffmpeg compress webp to avif

This commit is contained in:
2025-06-30 10:36:31 +08:00
parent 81d73cf17c
commit f34ce4aed0
8 changed files with 507 additions and 30 deletions
+85
View File
@@ -0,0 +1,85 @@
import { NextRequest, NextResponse } from 'next/server';
import { taskScheduler } from '../../../lib/scheduler';
export async function GET(request: NextRequest) {
try {
const url = new URL(request.url);
const action = url.searchParams.get('action');
const taskName = url.searchParams.get('task');
switch (action) {
case 'status':
if (taskName) {
const status = taskScheduler.getTaskStatus(taskName);
return NextResponse.json({
task: taskName,
running: status
});
} else {
const tasks = taskScheduler.listTasks();
const statuses = tasks.map(task => ({
name: task,
running: taskScheduler.getTaskStatus(task)
}));
return NextResponse.json({ tasks: statuses });
}
case 'list':
const allTasks = taskScheduler.listTasks();
return NextResponse.json({ tasks: allTasks });
default:
return NextResponse.json({
message: 'Task scheduler is running',
availableActions: ['status', 'list'],
tasks: taskScheduler.listTasks()
});
}
} catch (error) {
console.error('Task scheduler API error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
export async function POST(request: NextRequest) {
try {
const { action, taskName } = await request.json();
switch (action) {
case 'stop':
if (taskName) {
taskScheduler.stopTask(taskName);
return NextResponse.json({
message: `Task ${taskName} stopped`
});
} else {
taskScheduler.stopAll();
return NextResponse.json({
message: 'All tasks stopped'
});
}
case 'start':
// 重新启动所有任务
taskScheduler.startAll();
return NextResponse.json({
message: 'All tasks started'
});
default:
return NextResponse.json(
{ error: 'Invalid action' },
{ status: 400 }
);
}
} catch (error) {
console.error('Task scheduler API error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
+83 -24
View File
@@ -3,6 +3,10 @@ import { prisma } from '@/lib/prisma'
import { storeFile } from '@/lib/fileStorage'
import { push } from '@/lib/push'
import { withCors } from '@/lib/middleware'
import ffmpeg from 'fluent-ffmpeg'
import { writeFileSync, unlinkSync, mkdtempSync, readFileSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
interface WindowInfo {
title: string
@@ -17,7 +21,7 @@ async function handleScreenshotUpload(req: NextRequest) {
const pathSegments = req.nextUrl.pathname.split('/')
const hostnameIndex = pathSegments.indexOf('hosts') + 1
const hostname = pathSegments[hostnameIndex]
if (!hostname) {
return NextResponse.json({ error: '缺少主机名' }, { status: 400 })
}
@@ -25,7 +29,7 @@ async function handleScreenshotUpload(req: NextRequest) {
const formData = await req.formData()
const files: File[] = []
const windowsInfo: WindowInfo[] = JSON.parse(formData.get('windows_info') as string || '[]')
// Extract files from formData
for (const [key, value] of formData.entries()) {
if (key.startsWith('screenshot_') && value instanceof File) {
@@ -38,23 +42,78 @@ async function handleScreenshotUpload(req: NextRequest) {
}
// Process screenshots
const processingStartTime = Date.now()
console.log(`[${hostname}] 开始处理 ${files.length} 张截图`)
const screenshots = await Promise.all(files.map(async (file, index) => {
const ext = file.name ? file.name.split('.').pop() : 'webp'
const filename = `${hostname}-${Date.now()}-${Math.round(Math.random() * 1E9)}.${ext}`
const imageStartTime = Date.now()
// Convert image to AV1 format using FFmpeg
const buffer = Buffer.from(await file.arrayBuffer())
const storedFile = await storeFile(buffer, filename, file.type, 'screenshot', hostname)
return {
fileId: storedFile.id,
objectName: storedFile.objectName,
filename: storedFile.filename,
contentType: storedFile.contentType,
fileSize: storedFile.size,
monitorName: formData.get(`monitor_name_${index}`) as string || `Monitor ${index + 1}`
const originalSize = buffer.length
// Create temporary files
const tempDir = mkdtempSync(join(tmpdir(), 'ffmpeg-'))
const inputPath = join(tempDir, `input_${index}.png`)
const outputPath = join(tempDir, `output_${index}.avif`)
try {
// Write input file
writeFileSync(inputPath, buffer)
const conversionStartTime = Date.now()
// Convert using FFmpeg with libsvtav1
await new Promise<void>((resolve, reject) => {
ffmpeg(inputPath)
.videoCodec('libsvtav1')
.outputOptions([
'-crf 30', // 质量控制,值越小质量越好
'-preset 6', // 编码速度预设,0-12,值越大速度越快但质量可能下降
'-pix_fmt yuv420p' // 像素格式
])
.output(outputPath)
.on('end', () => resolve())
.on('error', (err) => reject(err))
.run()
})
const conversionTime = Date.now() - conversionStartTime
// Read the converted file
const avifBuffer = readFileSync(outputPath)
const filename = `${hostname}-${Date.now()}-${Math.round(Math.random() * 1E9)}.avif`
const storageStartTime = Date.now()
const storedFile = await storeFile(avifBuffer, filename, 'image/avif', 'screenshot', hostname)
const storageTime = Date.now() - storageStartTime
const totalImageTime = Date.now() - imageStartTime
const compressionRatio = ((originalSize - avifBuffer.length) / originalSize * 100).toFixed(2)
console.log(`[${hostname}] 图片 ${index + 1}: FFmpeg转换 ${conversionTime}ms, 存储 ${storageTime}ms, 总计 ${totalImageTime}ms, 压缩率 ${compressionRatio}% (${originalSize} -> ${avifBuffer.length} bytes)`)
return {
fileId: storedFile.id,
objectName: storedFile.objectName,
filename: storedFile.filename,
contentType: storedFile.contentType,
fileSize: storedFile.size,
monitorName: formData.get(`monitor_name_${index}`) as string || `Monitor ${index + 1}`
}
} finally {
// Clean up temporary files
try {
rmSync(tempDir, { recursive: true, force: true })
} catch (err) {
console.warn(`清理临时文件失败: ${err}`)
}
}
}))
const totalProcessingTime = Date.now() - processingStartTime
console.log(`[${hostname}] 完成处理 ${files.length} 张截图,总耗时 ${totalProcessingTime}ms,平均每张 ${(totalProcessingTime / files.length).toFixed(2)}ms`)
// Ensure host exists first
await prisma.host.upsert({
where: { hostname },
@@ -124,7 +183,7 @@ async function handleGetScreenshots(req: NextRequest) {
const pathSegments = req.nextUrl.pathname.split('/')
const hostnameIndex = pathSegments.indexOf('hosts') + 1
const hostname = pathSegments[hostnameIndex]
if (!hostname) {
return NextResponse.json({ error: '缺少主机名' }, { status: 400 })
}
@@ -132,27 +191,27 @@ async function handleGetScreenshots(req: NextRequest) {
const { searchParams } = req.nextUrl
const startTimeParam = searchParams.get('startTime')
const endTimeParam = searchParams.get('endTime')
let startTime: Date | undefined
let endTime: Date | undefined
if (startTimeParam) {
const timestamp = isNaN(Number(startTimeParam)) ?
new Date(startTimeParam) :
const timestamp = isNaN(Number(startTimeParam)) ?
new Date(startTimeParam) :
new Date(Number(startTimeParam) * 1000)
startTime = timestamp
}
if (endTimeParam) {
const timestamp = isNaN(Number(endTimeParam)) ?
new Date(endTimeParam) :
const timestamp = isNaN(Number(endTimeParam)) ?
new Date(endTimeParam) :
new Date(Number(endTimeParam) * 1000)
endTime = timestamp
}
// Build query conditions
const whereClause: any = { hostname }
if (startTime || endTime) {
whereClause.timestamp = {}
if (startTime) whereClause.timestamp.gte = startTime
@@ -179,7 +238,7 @@ async function handleGetScreenshots(req: NextRequest) {
lastUpdate: true
}
})
if (!host) {
return NextResponse.json({ error: '未找到主机记录' }, { status: 404 })
}
+17 -1
View File
@@ -51,7 +51,23 @@ export default function Home() {
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
<div className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
<div className="px-4 py-6 sm:px-0">
<h1 className="text-3xl font-semibold text-gray-900 dark:text-white mb-8">屏幕截图监控系统</h1>
<div className="flex justify-between items-center mb-8">
<h1 className="text-3xl font-semibold text-gray-900 dark:text-white">屏幕截图监控系统</h1>
<div className="space-x-4">
<button
onClick={() => router.push('/tasks')}
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
>
定时任务管理
</button>
<button
onClick={() => router.push('/upload')}
className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors"
>
上传新版本客户端
</button>
</div>
</div>
{/* 主机列表卡片网格 */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
+160
View File
@@ -0,0 +1,160 @@
'use client';
import { useState, useEffect } from 'react';
interface TaskStatus {
name: string;
running: boolean;
}
export default function TasksPage() {
const [tasks, setTasks] = useState<TaskStatus[]>([]);
const [loading, setLoading] = useState(true);
const [message, setMessage] = useState('');
useEffect(() => {
fetchTasks();
}, []);
const fetchTasks = async () => {
try {
const response = await fetch('/api/tasks?action=status');
const data = await response.json();
setTasks(data.tasks || []);
} catch (error) {
console.error('Failed to fetch tasks:', error);
setMessage('获取任务状态失败');
} finally {
setLoading(false);
}
};
const handleAction = async (action: string, taskName?: string) => {
try {
const response = await fetch('/api/tasks', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action, taskName }),
});
const data = await response.json();
setMessage(data.message || '操作完成');
// 刷新任务状态
await fetchTasks();
} catch (error) {
console.error('Failed to perform action:', error);
setMessage('操作失败');
}
};
if (loading) {
return (
<div className="container mx-auto px-4 py-8">
<div className="text-center">加载中...</div>
</div>
);
}
return (
<div className="container mx-auto px-4 py-8">
<h1 className="text-2xl font-bold mb-6">定时任务管理</h1>
{message && (
<div className="mb-4 p-4 bg-blue-100 border border-blue-300 rounded">
{message}
</div>
)}
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
<div className="flex justify-between items-center mb-4">
<h2 className="text-lg font-semibold">任务列表</h2>
<div className="space-x-2">
<button
onClick={() => handleAction('start')}
className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
>
启动所有任务
</button>
<button
onClick={() => handleAction('stop')}
className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
>
停止所有任务
</button>
<button
onClick={fetchTasks}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
>
刷新状态
</button>
</div>
</div>
{tasks.length === 0 ? (
<div className="text-center py-8 text-gray-500">
没有找到定时任务
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full border-collapse border border-gray-300">
<thead>
<tr className="bg-gray-50 dark:bg-gray-700">
<th className="border border-gray-300 px-4 py-2 text-left">任务名称</th>
<th className="border border-gray-300 px-4 py-2 text-left">状态</th>
<th className="border border-gray-300 px-4 py-2 text-left">描述</th>
<th className="border border-gray-300 px-4 py-2 text-left">操作</th>
</tr>
</thead>
<tbody>
{tasks.map((task) => (
<tr key={task.name} className="hover:bg-gray-50 dark:hover:bg-gray-700">
<td className="border border-gray-300 px-4 py-2 font-medium">
{task.name}
</td>
<td className="border border-gray-300 px-4 py-2">
<span className={`px-2 py-1 rounded text-sm ${
task.running
? 'bg-green-100 text-green-800'
: 'bg-red-100 text-red-800'
}`}>
{task.running ? '运行中' : '已停止'}
</span>
</td>
<td className="border border-gray-300 px-4 py-2">
{task.name === 'hourlyTask' && '每小时第30分钟执行'}
{task.name === 'dailyCleanup' && '每日凌晨2点清理任务'}
</td>
<td className="border border-gray-300 px-4 py-2">
<button
onClick={() => handleAction('stop', task.name)}
className="px-3 py-1 bg-red-500 text-white rounded text-sm hover:bg-red-600"
disabled={!task.running}
>
停止
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
<div className="mt-8 bg-white dark:bg-gray-800 rounded-lg shadow p-6">
<h2 className="text-lg font-semibold mb-4">Cron 表达式说明</h2>
<div className="space-y-2 text-sm text-gray-600 dark:text-gray-400">
<div><code>30 * * * *</code> - 每小时的第30分钟执行</div>
<div><code>0 2 * * *</code> - 每天凌晨2点执行</div>
<div><code>0 */2 * * *</code> - 每2小时执行一次</div>
<div><code>0 9 * * 1-5</code> - 周一到周五上午9点执行</div>
<div><code>0 0 1 * *</code> - 每月1号凌晨执行</div>
<div><code>*/15 * * * *</code> - 每15分钟执行一次</div>
</div>
</div>
</div>
);
}