video-generator.service.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. "use strict";
  2. /**
  3. * 视频生成模块 - 业务逻辑
  4. * 处理视频项目的增删改查和生成逻辑
  5. */
  6. var __importDefault = (this && this.__importDefault) || function (mod) {
  7. return (mod && mod.__esModule) ? mod : { "default": mod };
  8. };
  9. Object.defineProperty(exports, "__esModule", { value: true });
  10. exports.createVideoProject = createVideoProject;
  11. exports.getVideoProjects = getVideoProjects;
  12. exports.getVideoProject = getVideoProject;
  13. exports.updateVideoProject = updateVideoProject;
  14. exports.deleteVideoProject = deleteVideoProject;
  15. exports.generateVideoForProject = generateVideoForProject;
  16. exports.getGenerateProgress = getGenerateProgress;
  17. exports.getMaterials = getMaterials;
  18. exports.uploadMaterial = uploadMaterial;
  19. exports.deleteMaterial = deleteMaterial;
  20. exports.createVideoProjectFromBook = createVideoProjectFromBook;
  21. const client_1 = require("@prisma/client");
  22. const path_1 = __importDefault(require("path"));
  23. const uuid_1 = require("uuid");
  24. const video_generator_types_1 = require("./video-generator.types");
  25. const video_generator_ffmpeg_1 = require("./video-generator.ffmpeg");
  26. const prisma = new client_1.PrismaClient();
  27. // ============ 视频项目管理 ============
  28. /**
  29. * 创建视频项目
  30. */
  31. async function createVideoProject(data, userId) {
  32. const config = data.config || video_generator_types_1.PRESET_VIDEO_CONFIGS.portrait;
  33. const project = await prisma.videoProject.create({
  34. data: {
  35. userId: userId,
  36. title: data.title,
  37. description: data.description,
  38. coverUrl: data.coverUrl,
  39. configJson: (0, video_generator_types_1.serializeConfig)(config),
  40. bookId: data.bookId,
  41. chapterId: data.chapterId, // 直接关联章节
  42. status: 'draft',
  43. progress: 0,
  44. },
  45. });
  46. return {
  47. ...project,
  48. config,
  49. };
  50. }
  51. /**
  52. * 获取视频项目列表
  53. */
  54. async function getVideoProjects(query) {
  55. const page = query.page || 1;
  56. const pageSize = query.pageSize || 10;
  57. const skip = (page - 1) * pageSize;
  58. const where = {};
  59. if (query.userId)
  60. where.userId = query.userId;
  61. if (query.status)
  62. where.status = query.status;
  63. const [items, total] = await Promise.all([
  64. prisma.videoProject.findMany({
  65. where,
  66. orderBy: { createdAt: 'desc' },
  67. skip,
  68. take: pageSize,
  69. }),
  70. prisma.videoProject.count({ where }),
  71. ]);
  72. return {
  73. items: items.map((item) => ({
  74. ...item,
  75. config: (0, video_generator_types_1.parseConfig)(item.configJson),
  76. })),
  77. total,
  78. page,
  79. pageSize,
  80. };
  81. }
  82. /**
  83. * 获取视频项目详情
  84. */
  85. async function getVideoProject(id) {
  86. const project = await prisma.videoProject.findUnique({
  87. where: { id },
  88. });
  89. if (!project)
  90. return null;
  91. return {
  92. ...project,
  93. config: (0, video_generator_types_1.parseConfig)(project.configJson),
  94. };
  95. }
  96. /**
  97. * 更新视频项目
  98. */
  99. async function updateVideoProject(id, data) {
  100. const updateData = {};
  101. if (data.title !== undefined)
  102. updateData.title = data.title;
  103. if (data.description !== undefined)
  104. updateData.description = data.description;
  105. if (data.coverUrl !== undefined)
  106. updateData.coverUrl = data.coverUrl;
  107. if (data.config !== undefined)
  108. updateData.configJson = (0, video_generator_types_1.serializeConfig)(data.config);
  109. const project = await prisma.videoProject.update({
  110. where: { id },
  111. data: updateData,
  112. });
  113. return {
  114. ...project,
  115. config: (0, video_generator_types_1.parseConfig)(project.configJson),
  116. };
  117. }
  118. /**
  119. * 删除视频项目
  120. */
  121. async function deleteVideoProject(id) {
  122. try {
  123. await prisma.videoProject.delete({
  124. where: { id },
  125. });
  126. return true;
  127. }
  128. catch {
  129. return false;
  130. }
  131. }
  132. // ============ 视频生成 ============
  133. /**
  134. * 生成视频
  135. */
  136. async function generateVideoForProject(projectId) {
  137. // 1. 获取项目
  138. const project = await getVideoProject(projectId);
  139. if (!project) {
  140. return { success: false, error: '项目不存在' };
  141. }
  142. // 2. 检查状态
  143. if (project.status === 'processing') {
  144. return { success: false, error: '项目正在生成中' };
  145. }
  146. // 3. 更新状态为处理中
  147. await prisma.videoProject.update({
  148. where: { id: projectId },
  149. data: { status: 'processing', progress: 0 },
  150. });
  151. try {
  152. // 4. 获取配置
  153. const config = project.config;
  154. if (!config) {
  155. throw new Error('缺少视频配置');
  156. }
  157. // 5. 如果有 chapterId,优先从章节获取音频
  158. let audioPath = config.audio?.url;
  159. let textContent = '';
  160. if (project.chapterId) {
  161. const chapter = await prisma.bookChapter.findUnique({
  162. where: { id: project.chapterId },
  163. });
  164. if (chapter?.audioUrl) {
  165. audioPath = chapter.audioUrl;
  166. }
  167. if (chapter?.content) {
  168. textContent = chapter.content;
  169. }
  170. }
  171. if (!audioPath || !config.images?.[0]?.url) {
  172. throw new Error('缺少必要的素材:音频或图片');
  173. }
  174. // 转换URL为本地文件路径
  175. const fs = await import('fs');
  176. // 获取 server 目录路径
  177. const serverDir = process.cwd();
  178. // 处理图片路径
  179. let imagePath = config.images[0].url;
  180. // 统一处理:所有非绝对路径都加上 server 目录和 public 前缀
  181. if (!imagePath.match(/^[A-Za-z]:/)) {
  182. // Windows 或 Unix 相对路径
  183. imagePath = path_1.default.join(serverDir, 'public', imagePath.replace(/^\//, ''));
  184. }
  185. // 处理音频路径
  186. if (!audioPath.match(/^[A-Za-z]:/)) {
  187. audioPath = path_1.default.join(serverDir, audioPath.replace(/^\//, ''));
  188. }
  189. // 检查文件是否存在
  190. if (!fs.existsSync(imagePath)) {
  191. throw new Error('图片文件不存在: ' + imagePath);
  192. }
  193. if (!fs.existsSync(audioPath)) {
  194. throw new Error('音频文件不存在: ' + audioPath);
  195. }
  196. // 6. 生成输出路径
  197. const outputFileName = `video_${projectId}_${(0, uuid_1.v4)()}.mp4`;
  198. const outputPath = path_1.default.join(process.cwd(), 'public', 'videos', outputFileName);
  199. // 7. 更新进度
  200. await prisma.videoProject.update({
  201. where: { id: projectId },
  202. data: { progress: 30 },
  203. });
  204. // 8. 生成视频
  205. let result;
  206. if (config.bgm?.url) {
  207. // 带背景音乐
  208. const bgmPath = await downloadFile(config.bgm.url, 'audio');
  209. result = await (0, video_generator_ffmpeg_1.generateVideoWithBgm)(imagePath, audioPath, bgmPath, outputPath, config);
  210. }
  211. else {
  212. // 不带背景音乐
  213. result = await (0, video_generator_ffmpeg_1.generateVideo)(imagePath, audioPath, outputPath, config);
  214. }
  215. // 9. 更新项目状态
  216. const outputUrl = `/videos/${outputFileName}`;
  217. await prisma.videoProject.update({
  218. where: { id: projectId },
  219. data: {
  220. status: 'completed',
  221. progress: 100,
  222. outputUrl,
  223. duration: result.duration,
  224. fileSize: result.fileSize,
  225. },
  226. });
  227. // 10. 如果有章节关联,更新章节的视频URL
  228. if (project.chapterId) {
  229. await prisma.bookChapter.update({
  230. where: { id: project.chapterId },
  231. data: {
  232. videoUrl: outputUrl,
  233. videoDuration: result.duration,
  234. },
  235. });
  236. }
  237. return {
  238. success: true,
  239. outputUrl,
  240. duration: result.duration,
  241. fileSize: result.fileSize,
  242. };
  243. }
  244. catch (error) {
  245. // 生成失败,更新状态
  246. await prisma.videoProject.update({
  247. where: { id: projectId },
  248. data: {
  249. status: 'failed',
  250. errorMsg: error.message,
  251. },
  252. });
  253. return {
  254. success: false,
  255. error: error.message,
  256. };
  257. }
  258. }
  259. /**
  260. * 获取生成进度
  261. */
  262. async function getGenerateProgress(projectId) {
  263. const project = await prisma.videoProject.findUnique({
  264. where: { id: projectId },
  265. select: {
  266. status: true,
  267. progress: true,
  268. outputUrl: true,
  269. duration: true,
  270. fileSize: true,
  271. errorMsg: true,
  272. },
  273. });
  274. if (!project) {
  275. return { status: 'failed', progress: 0, errorMsg: '项目不存在' };
  276. }
  277. return project;
  278. }
  279. // ============ 素材管理 ============
  280. /**
  281. * 获取素材列表
  282. */
  283. async function getMaterials(query) {
  284. const page = query.page || 1;
  285. const pageSize = query.pageSize || 20;
  286. const skip = (page - 1) * pageSize;
  287. const where = {
  288. OR: [{ userId: null }, { userId: query.userId || 0 }],
  289. };
  290. if (query.type)
  291. where.type = query.type;
  292. if (query.category)
  293. where.category = query.category;
  294. const [items, total] = await Promise.all([
  295. prisma.videoMaterial.findMany({
  296. where,
  297. orderBy: { createdAt: 'desc' },
  298. skip,
  299. take: pageSize,
  300. }),
  301. prisma.videoMaterial.count({ where }),
  302. ]);
  303. return {
  304. items: items.map((item) => ({
  305. ...item,
  306. tags: (0, video_generator_types_1.parseTags)(item.tags),
  307. })),
  308. total,
  309. };
  310. }
  311. /**
  312. * 上传素材
  313. */
  314. async function uploadMaterial(data, userId) {
  315. const material = await prisma.videoMaterial.create({
  316. data: {
  317. userId: userId,
  318. type: data.type,
  319. name: data.name,
  320. url: data.url,
  321. thumbnail: data.thumbnail,
  322. tags: (0, video_generator_types_1.serializeTags)(data.tags || []),
  323. category: data.category,
  324. duration: data.duration,
  325. size: data.size,
  326. width: data.width,
  327. height: data.height,
  328. },
  329. });
  330. return {
  331. ...material,
  332. tags: (0, video_generator_types_1.parseTags)(material.tags),
  333. };
  334. }
  335. /**
  336. * 删除素材
  337. */
  338. async function deleteMaterial(id) {
  339. try {
  340. await prisma.videoMaterial.delete({
  341. where: { id },
  342. });
  343. return true;
  344. }
  345. catch {
  346. return false;
  347. }
  348. }
  349. // ============ 辅助函数 ============
  350. /**
  351. * 下载文件到临时目录
  352. */
  353. async function downloadFile(url, type) {
  354. const https = await import('https');
  355. const http = await import('http');
  356. const fs = await import('fs');
  357. const tempDir = path_1.default.join(process.cwd(), 'temp', type);
  358. if (!fs.existsSync(tempDir)) {
  359. fs.mkdirSync(tempDir, { recursive: true });
  360. }
  361. const ext = path_1.default.extname(url) || (type === 'images' ? '.jpg' : '.mp3');
  362. const filePath = path_1.default.join(tempDir, `${(0, uuid_1.v4)()}${ext}`);
  363. return new Promise((resolve, reject) => {
  364. const protocol = url.startsWith('https') ? https : http;
  365. const file = fs.createWriteStream(filePath);
  366. protocol.get(url, (response) => {
  367. if (response.statusCode === 301 || response.statusCode === 302) {
  368. // 重定向
  369. const redirectUrl = response.headers.location;
  370. if (!redirectUrl) {
  371. file.close();
  372. reject(new Error('重定向但没有 location header'));
  373. return;
  374. }
  375. const redirectProtocol = redirectUrl.startsWith('https') ? https : http;
  376. redirectProtocol.get(redirectUrl, (redirectResponse) => {
  377. redirectResponse.pipe(file);
  378. file.on('finish', () => resolve(filePath));
  379. });
  380. }
  381. else {
  382. response.pipe(file);
  383. file.on('finish', () => resolve(filePath));
  384. }
  385. }).on('error', reject);
  386. });
  387. }
  388. /**
  389. * 清理临时文件
  390. */
  391. async function cleanupTempFiles(...filePaths) {
  392. const fs = await import('fs');
  393. for (const filePath of filePaths) {
  394. try {
  395. if (fs.existsSync(filePath)) {
  396. fs.unlinkSync(filePath);
  397. }
  398. }
  399. catch (error) {
  400. console.error(`清理文件失败: ${filePath}`, error);
  401. }
  402. }
  403. }
  404. /**
  405. * 从书籍生成视频项目(基于指定章节)
  406. */
  407. async function createVideoProjectFromBook(bookId, chapterId, userId) {
  408. // 获取书籍信息
  409. const book = await prisma.book.findUnique({
  410. where: { id: bookId },
  411. include: { chapters: { orderBy: { number: 'asc' } } },
  412. });
  413. if (!book)
  414. return null;
  415. // 如果没有指定章节,使用第一个有音频的章节
  416. let targetChapter = book.chapters.find(c => c.audioUrl) || book.chapters[0];
  417. if (chapterId) {
  418. const found = book.chapters.find(c => c.id === chapterId);
  419. if (found)
  420. targetChapter = found;
  421. }
  422. if (!targetChapter)
  423. return null;
  424. // 如果章节没有音频,返回错误
  425. if (!targetChapter.audioUrl) {
  426. console.error(`章节 ${targetChapter.number} 没有音频`);
  427. return null;
  428. }
  429. // 创建视频项目,直接关联到章节
  430. const project = await createVideoProject({
  431. title: `《${book.title}》第${targetChapter.number}章 视频`,
  432. description: targetChapter.summary || book.description,
  433. bookId: book.id,
  434. chapterId: targetChapter.id,
  435. config: {
  436. ...video_generator_types_1.PRESET_VIDEO_CONFIGS.portrait,
  437. audio: {
  438. url: targetChapter.audioUrl,
  439. volume: 1,
  440. },
  441. images: [
  442. {
  443. url: '/images/default-cover.jpg',
  444. duration: 5,
  445. transition: 'fade',
  446. },
  447. ],
  448. subtitle: {
  449. text: targetChapter.title,
  450. position: 'bottom',
  451. fontSize: 28,
  452. fontColor: 'white',
  453. },
  454. },
  455. }, userId);
  456. return project;
  457. }