langgraph-controller.ts 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044
  1. /**
  2. * LangGraph 书籍生成 - API 路由
  3. * 支持书籍创建时的预估显示
  4. */
  5. import Router from '@koa/router';
  6. import { Context } from 'koa';
  7. import { langGraphGenerator, getScaleConfig, resolveGenLevel, mapBookTypeToGenLevel } from './index';
  8. import { bookStore } from './book-generator.store';
  9. import { prisma } from '../../models';
  10. import { estimateBookWords, estimateAudioMinutesFromWords, checkBookGenerationQuota, checkAudioQuota } from '../subscription/subscription.service';
  11. import { optionalAuth } from '../../middleware/auth';
  12. import { getAllBookTypes, getDetectableTypes, getBookTypeConfig, BOOK_TYPE_CONFIG, DETECTABLE_TYPES } from './book-type-config';
  13. import { callLLMWithMessages, callLLM, ChatMessage } from '../../services/llm';
  14. import { cleanLlmShortText, extractJsonFromResponse } from '../../services/llm/response-cleaner';
  15. import { createVideoProjectFromBook, generateVideoForProject } from '../video-generator/video-generator.service';
  16. import { mergeChapterAudios } from '../player/player.service';
  17. import { exec } from 'child_process';
  18. import { promisify } from 'util';
  19. import fs from 'fs/promises';
  20. import path from 'path';
  21. import { advanceChapter, regenerateChapter } from './stage-manager';
  22. import { deepPlanBookNode } from './nodes/deep-plan.node';
  23. import { richOutlineNode } from './nodes/rich-outline.node';
  24. import { writeChaptersParallelNode } from './nodes/content.node';
  25. import { continuityEditNode } from './nodes/continuity-edit.node';
  26. import { GraphState } from './graph';
  27. const execPromise = promisify(exec);
  28. // 开发环境测试用户ID
  29. const TEST_USER_ID = '1';
  30. const router = new Router();
  31. /**
  32. * GET /api/book-generator/langgraph/estimate
  33. * 获取书籍规模预估信息
  34. */
  35. router.get('/estimate', async (ctx: Context) => {
  36. const { scale, userId, bookType } = ctx.query as { scale?: string; userId?: string; bookType?: string };
  37. if (!scale) {
  38. ctx.status = 400;
  39. ctx.body = { code: 1, message: '请提供书籍规模' };
  40. return;
  41. }
  42. const scaleConfig = getScaleConfig(scale);
  43. const totalWords = scaleConfig.totalWords;
  44. const audioMinutes = estimateAudioMinutesFromWords(totalWords);
  45. // 章节数
  46. const estimatedChapters = scaleConfig.isShortArticle ? 1 : scaleConfig.chapters;
  47. // 大纲层级(优先使用书籍类型映射)
  48. const genLevel = bookType && bookType !== 'auto'
  49. ? mapBookTypeToGenLevel(bookType)
  50. : resolveGenLevel(scale);
  51. const genLevelDescriptions: Record<number, { label: string; desc: string }> = {
  52. 1: { label: '仅章', desc: '无节和小节,适合短文、小说' },
  53. 2: { label: '章→节', desc: '有节无小节,适合科普、商业书' },
  54. 3: { label: '章→节→小节', desc: '完整三级结构,适合教材、技术书' },
  55. };
  56. const result: any = {
  57. scale,
  58. scaleConfig,
  59. audioMinutes: {
  60. min: estimateAudioMinutesFromWords(Math.round(totalWords * 0.8)),
  61. max: estimateAudioMinutesFromWords(Math.round(totalWords * 1.2)),
  62. avg: audioMinutes
  63. },
  64. estimatedChapters,
  65. defaultGenLevel: genLevel,
  66. genLevelInfo: genLevelDescriptions[genLevel] || { label: '章→节', desc: '' },
  67. };
  68. // 如果提供了 userId,同时检查用户配额
  69. if (userId) {
  70. const quotaCheck = await checkBookGenerationQuota(parseInt(userId), scale);
  71. result.quotaCheck = quotaCheck;
  72. }
  73. ctx.body = {
  74. code: 0,
  75. message: 'success',
  76. data: result
  77. };
  78. });
  79. /**
  80. * POST /api/book-generator/langgraph/detect-scale
  81. * AI 预览检测书籍规模(创建前调用,让用户看到检测结果)
  82. */
  83. router.post('/detect-scale', async (ctx) => {
  84. const { description } = ctx.request.body as { description?: string };
  85. if (!description) {
  86. ctx.body = { code: 1, message: '缺少 description' };
  87. return;
  88. }
  89. const scale = await autoDetectBookType('', description);
  90. const config = getScaleConfig(scale);
  91. ctx.body = {
  92. code: 0,
  93. data: {
  94. bookScale: scale,
  95. totalWords: config.totalWords,
  96. chapters: config.chapters,
  97. isShortArticle: config.isShortArticle,
  98. },
  99. };
  100. });
  101. /**
  102. * GET /api/book-generator/langgraph/book-types
  103. * 获取所有书籍类型配置(供前端显示)
  104. */
  105. router.get('/book-types', async (ctx: Context) => {
  106. const types = getAllBookTypes().map(t => ({
  107. key: t.key,
  108. label: t.label,
  109. description: t.description,
  110. chapters: t.chapters,
  111. totalWords: t.totalWords,
  112. audioMinutes: t.audioMinutes,
  113. chapterWords: t.chapterWords,
  114. structureFormat: t.structureFormat,
  115. readingDifficulty: t.readingDifficulty,
  116. isShortArticle: t.isShortArticle,
  117. }));
  118. ctx.body = {
  119. code: 0,
  120. message: 'success',
  121. data: types,
  122. };
  123. });
  124. /**
  125. * POST /api/book-generator/langgraph/detect-book-type
  126. * AI 自动检测书籍类型
  127. */
  128. router.post('/detect-book-type', async (ctx: Context) => {
  129. const { title, description } = ctx.request.body as {
  130. title?: string;
  131. description?: string;
  132. };
  133. if (!title) {
  134. ctx.status = 400;
  135. ctx.body = { code: 1, message: '请提供书籍标题' };
  136. return;
  137. }
  138. const detectableTypes = DETECTABLE_TYPES;
  139. // 构建类型特征描述,帮助 AI 分类
  140. const typeDescriptions = detectableTypes.map(key => {
  141. const t = BOOK_TYPE_CONFIG[key];
  142. return `- ${t.key}: ${t.description},${t.chapters}章,总字数约${t.totalWords}字,每章约${t.chapterWords}字,结构形式:${t.structureFormat},阅读难度:${t.readingDifficulty}`;
  143. }).join('\n');
  144. const messages: ChatMessage[] = [
  145. {
  146. role: 'system',
  147. content: `你是一位专业的图书分类编辑。根据用户提供的标题和描述,判断这本书最可能属于以下哪种类型:
  148. 可选类型:
  149. ${typeDescriptions}
  150. ## 分类规则
  151. 1. 分析标题中的关键词(如"科普""青少年""专业""小说"等)
  152. 2. 分析描述中的目标读者、写作风格、内容深度
  153. 3. 匹配最符合的类型
  154. ## 输出格式
  155. 必须返回 JSON,不要包含 markdown 代码块标记:
  156. {
  157. "detectedType": "类型 key",
  158. "confidence": 0.85,
  159. "reasoning": "分类理由,1-2句话"
  160. }
  161. confidence 是 0-1 的数值,表示置信程度。`,
  162. },
  163. {
  164. role: 'user',
  165. content: `标题:《${title}》\n描述:${description || '无'}`,
  166. },
  167. ];
  168. try {
  169. const response = await callLLMWithMessages(messages);
  170. const parsed = parseDetectResult(response);
  171. if (!parsed) {
  172. // 降级到关键词匹配
  173. const fallback = keywordFallback(title, description || '');
  174. ctx.body = {
  175. code: 0,
  176. message: 'success',
  177. data: {
  178. detectedType: fallback.detectedType,
  179. confidence: 0.5,
  180. reasoning: '基于关键词匹配(AI 解析失败,使用降级策略)',
  181. config: getBookTypeConfig(fallback.detectedType),
  182. },
  183. };
  184. return;
  185. }
  186. ctx.body = {
  187. code: 0,
  188. message: 'success',
  189. data: {
  190. detectedType: parsed.detectedType,
  191. confidence: parsed.confidence,
  192. reasoning: parsed.reasoning,
  193. config: getBookTypeConfig(parsed.detectedType),
  194. },
  195. };
  196. } catch (error: any) {
  197. // 最终降级:关键词匹配
  198. const fallback = keywordFallback(title, description || '');
  199. ctx.body = {
  200. code: 0,
  201. message: 'success',
  202. data: {
  203. detectedType: fallback.detectedType,
  204. confidence: 0.3,
  205. reasoning: 'LLM 调用失败,使用关键词匹配降级',
  206. config: getBookTypeConfig(fallback.detectedType),
  207. },
  208. };
  209. }
  210. });
  211. function parseDetectResult(text: string): { detectedType: string; confidence: number; reasoning: string } | null {
  212. try {
  213. const match = text.match(/\{[\s\S]*\}/);
  214. if (!match) return null;
  215. const data = JSON.parse(match[0]);
  216. if (!data.detectedType) return null;
  217. // 验证类型是否有效
  218. if (!DETECTABLE_TYPES.includes(data.detectedType)) {
  219. // 尝试模糊匹配
  220. const found = DETECTABLE_TYPES.find(t => data.detectedType.includes(t) || t.includes(data.detectedType));
  221. if (!found) return null;
  222. data.detectedType = found;
  223. }
  224. return {
  225. detectedType: data.detectedType,
  226. confidence: Math.min(1, Math.max(0, data.confidence || 0.5)),
  227. reasoning: data.reasoning || '',
  228. };
  229. } catch {
  230. return null;
  231. }
  232. }
  233. function keywordFallback(_title: string, _description: string): { detectedType: string } {
  234. // 完全由 AI 判断,fallback 只在 LLM 完全失败时作为最后保险
  235. return { detectedType: '1000' }; // 最小规模
  236. }
  237. /**
  238. * AI 根据描述自动生成书名
  239. */
  240. async function autoGenerateTitle(description: string): Promise<string> {
  241. const prompt = `根据以下描述起一个书名。要求:中文不超过20字,英文不超过20个单词。只返回书名,不要任何解释、思考或前缀。
  242. 描述:${description.substring(0, 200)}
  243. 书名:`;
  244. try {
  245. const response = await callLLM(prompt);
  246. const title = cleanLlmShortText(response, {
  247. maxLength: 50,
  248. maxChineseChars: 20,
  249. maxEnglishWords: 20,
  250. });
  251. console.log(`[LangGraph] AI 生成书名: "${title}"`);
  252. return title || '未命名书籍';
  253. } catch (e) {
  254. console.warn('[LangGraph] AI 自动生成书名失败,使用默认:', e);
  255. return '未命名书籍';
  256. }
  257. }
  258. /**
  259. * AI 自动检测书籍规模(字数等级),后端静默调用
  260. * AI 分析描述中的字数要求,以 JSON 格式返回,供程序提取
  261. */
  262. async function autoDetectBookType(title: string, description: string): Promise<string> {
  263. console.log(`[autoDetectBookType] 被调用: title="${title}", desc前50="${description?.substring(0, 50)}"`);
  264. const messages: ChatMessage[] = [
  265. {
  266. role: 'system',
  267. content: `你是一位专业的图书分类编辑。根据标题和描述,判断书籍适合的字数规模。
  268. ## 判断规则
  269. **规则1 - 字数直接返回**:如果描述里有"X字"(如"200字""500字""几千字"),直接返回X作为bookScale值,不要映射到预定义规模。
  270. - 描述含"200字"→返回200
  271. - 描述含"500字"→返回500
  272. - 描述含"几千字"→估计约3000,返回3000
  273. - 描述含"上万字"→估计约10000,返回10000
  274. **规则2 - 无法判断**:描述中没有字数信息 → 返回1000
  275. ## 输出格式(必须严格JSON)
  276. {"bookScale": 数字}
  277. 只返回JSON,不要任何其他文字。`,
  278. },
  279. {
  280. role: 'user',
  281. content: `标题:《${title}》\n描述:${description}`,
  282. },
  283. ];
  284. try {
  285. const response = await callLLMWithMessages(messages);
  286. const trimmed = response.trim();
  287. console.log(`[autoDetectBookType] AI原始响应: ${trimmed.substring(0, 200)}`);
  288. // 尝试解析 JSON,提取 bookScale(实际字数)
  289. const jsonMatch = trimmed.match(/\{[\s\S]*\}/);
  290. if (jsonMatch) {
  291. try {
  292. const data = JSON.parse(jsonMatch[0]);
  293. if (typeof data.bookScale === 'number') {
  294. const wordCount = data.bookScale;
  295. console.log(`[autoDetectBookType] AI返回: bookScale=${wordCount}`);
  296. // 直接返回实际字数,getBookTypeConfig 支持任意数字 key
  297. return String(wordCount);
  298. }
  299. } catch {
  300. // JSON解析失败,忽略
  301. }
  302. }
  303. // JSON解析失败 → 默认返回最小规模
  304. console.log(`[autoDetectBookType] AI响应无法解析,使用默认值1000`);
  305. return '1000';
  306. } catch (error: any) {
  307. console.error(`[autoDetectBookType] AI调用异常:`, error?.message || error);
  308. return '1000';
  309. }
  310. }
  311. /**
  312. * POST /api/book-generator/langgraph/smart-recommend
  313. * 根据书籍描述智能推荐难度、人群、风格、领域
  314. */
  315. router.post('/smart-recommend', async (ctx: Context) => {
  316. try {
  317. const { description, title } = ctx.request.body as { description: string; title?: string };
  318. if (!description || !description.trim()) {
  319. ctx.status = 400;
  320. ctx.body = { code: 1, message: '描述不能为空' };
  321. return;
  322. }
  323. // 默认推荐值
  324. const defaultResult = {
  325. knowledgeLevel: '入门',
  326. targetAudience: '通用',
  327. style: '轻松幽默',
  328. industry: '教育',
  329. reason: '默认推荐',
  330. };
  331. const prompt = `根据以下书籍描述,推荐合适的知识难度、目标人群、写作风格和行业领域。
  332. 书名:${title || '未命名'}
  333. 描述:${description}
  334. 请以 JSON 格式返回推荐结果,不要包含任何其他文字:
  335. {
  336. "knowledgeLevel": "入门|进阶|专业",
  337. "targetAudience": "推荐的目标人群",
  338. "style": "推荐风格",
  339. "industry": "推荐行业领域",
  340. "reason": "简要说明推荐理由"
  341. }`;
  342. const messages: ChatMessage[] = [
  343. { role: 'system', content: '你是一位专业的图书策划编辑,擅长根据书籍内容推荐合适的定位。' },
  344. { role: 'user', content: prompt },
  345. ];
  346. const response = await callLLMWithMessages(messages);
  347. const result = extractJsonFromResponse(response) || defaultResult;
  348. ctx.body = { code: 0, message: 'success', data: result };
  349. } catch (error) {
  350. console.error('智能推荐失败:', error);
  351. // 返回默认值而不是错误
  352. ctx.body = {
  353. code: 0,
  354. message: 'success',
  355. data: {
  356. knowledgeLevel: '入门',
  357. targetAudience: '通用',
  358. style: '轻松幽默',
  359. industry: '教育',
  360. reason: 'AI服务暂时不可用,使用默认推荐',
  361. },
  362. };
  363. }
  364. });
  365. /**
  366. * POST /api/book-generator/langgraph/books
  367. * 使用 LangGraph 创建并生成书籍(异步,自动生成大纲和内容)
  368. * AI 根据标题+描述自动判断书籍类型
  369. *
  370. * 优化策略:
  371. * 1. 并行执行 autoGenerateTitle + autoDetectBookType(串行→并行,耗时减半)
  372. * 2. 先创建书籍返回响应,AI 结果异步回填(用户无需等待 AI 完成即可看到书籍)
  373. */
  374. router.post('/books', optionalAuth, async (ctx: Context) => {
  375. try {
  376. const body = ctx.request.body as {
  377. title: string;
  378. description: string;
  379. bookScale?: string;
  380. bookType?: string;
  381. genLevel?: number;
  382. generateForeword?: boolean;
  383. generateAfterword?: boolean;
  384. immediateGenerate?: boolean;
  385. };
  386. if (!body.description) {
  387. ctx.status = 400;
  388. ctx.body = { code: 1, message: '描述不能为空' };
  389. return;
  390. }
  391. // 获取用户 ID(未登录时使用测试用户)
  392. const userId = ctx.state.user?.userId ? parseInt(ctx.state.user.userId as string) : parseInt(TEST_USER_ID);
  393. const providedTitle = body.title?.trim();
  394. // 只接受数字格式的 bookScale(如 '200', '1000', '130000'),非数字当作未提供
  395. const providedBookScale = body.bookScale && /^\d+$/.test(body.bookScale) ? body.bookScale : undefined;
  396. // ========== 快速路径:用户已提供 title 和 bookScale,无需 AI ==========
  397. if (providedTitle && providedBookScale) {
  398. const bookScale = providedBookScale;
  399. const genLevel = body.genLevel !== undefined
  400. ? resolveGenLevel(bookScale, body.genLevel)
  401. : body.bookType && body.bookType !== 'auto'
  402. ? mapBookTypeToGenLevel(body.bookType)
  403. : resolveGenLevel(bookScale);
  404. const scaleConfig = getScaleConfig(bookScale);
  405. const totalWords = scaleConfig.totalWords;
  406. const audioQuota = await checkAudioQuota(userId, totalWords);
  407. if (!audioQuota.allowed) {
  408. ctx.status = 403;
  409. ctx.body = { code: 1, message: audioQuota.reason, data: { estimatedWords: totalWords, estimatedAudioMinutes: estimateAudioMinutesFromWords(totalWords), remainingMinutes: audioQuota.remainingMinutes, totalMinutes: audioQuota.totalMinutes } };
  410. return;
  411. }
  412. const book = await bookStore.create({
  413. userId,
  414. title: providedTitle,
  415. description: body.description,
  416. bookScale,
  417. totalChapters: scaleConfig.isShortArticle ? 1 : scaleConfig.chapters,
  418. estimatedWords: totalWords,
  419. });
  420. if (body.immediateGenerate === false) {
  421. ctx.body = { code: 0, message: '书籍创建成功(交互模式)', data: { book, genStage: 'draft', mode: 'interactive' } };
  422. return;
  423. }
  424. await bookStore.update(book.id, { genStage: 'outlining' });
  425. langGraphGenerator.generate(book.id.toString(), body.description, bookScale, genLevel)
  426. .then(() => console.log(`[LangGraph] 生成完成: bookId=${book.id}`))
  427. .catch(err => {
  428. console.error(`[LangGraph] 生成失败: bookId=${book.id}`, err);
  429. bookStore.update(book.id.toString(), { genStage: 'failed', errorMsg: err instanceof Error ? err.message : '生成失败', failedStage: 'outlining' });
  430. });
  431. ctx.body = { code: 0, message: '书籍创建成功,生成已开始', data: { book, genStage: 'outlining', mode: 'async' } };
  432. return;
  433. }
  434. // ========== 需要 AI 辅助的路径:先创建书籍,再异步回填 ==========
  435. // 使用临时标题/默认规模先创建书籍,立即返回给前端
  436. // 规模会由 AI 异步回填
  437. const fallbackScale = providedBookScale || '1000';
  438. const fallbackTitle = providedTitle || '正在生成标题...';
  439. const fallbackConfig = getScaleConfig(fallbackScale);
  440. const fallbackWords = fallbackConfig.totalWords;
  441. // 配额预检查(使用默认规模估算,后续可能因 AI 检测结果调整)
  442. const audioQuota = await checkAudioQuota(userId, fallbackWords);
  443. if (!audioQuota.allowed) {
  444. ctx.status = 403;
  445. ctx.body = { code: 1, message: audioQuota.reason, data: { estimatedWords: fallbackWords, estimatedAudioMinutes: estimateAudioMinutesFromWords(fallbackWords), remainingMinutes: audioQuota.remainingMinutes, totalMinutes: audioQuota.totalMinutes } };
  446. return;
  447. }
  448. // 先创建书籍,立即返回
  449. const book = await bookStore.create({
  450. userId,
  451. title: fallbackTitle,
  452. description: body.description,
  453. bookScale: fallbackScale,
  454. totalChapters: fallbackConfig.isShortArticle ? 1 : fallbackConfig.chapters,
  455. estimatedWords: fallbackWords,
  456. });
  457. // 标记为 AI 正在准备中
  458. const needTitle = !providedTitle;
  459. const needScale = !providedBookScale;
  460. const aiPreparing = needTitle || needScale;
  461. if (body.immediateGenerate === false) {
  462. // 交互模式:异步填充 AI 结果,但不需要启动生成
  463. if (aiPreparing) {
  464. fillAiResultsAsync(book.id.toString(), body.description, providedTitle, providedBookScale);
  465. }
  466. ctx.body = { code: 0, message: '书籍创建成功(交互模式)', data: { book, genStage: 'draft', mode: 'interactive', aiPreparing } };
  467. return;
  468. }
  469. // 非交互模式:需要等 AI 完成后才能确定 bookScale/genLevel 启动生成
  470. await bookStore.update(book.id, { genStage: 'outlining' });
  471. // 立即返回响应
  472. ctx.body = {
  473. code: 0,
  474. message: '书籍创建成功,AI 正在准备标题和规模...',
  475. data: {
  476. book,
  477. genStage: 'outlining',
  478. mode: 'async',
  479. aiPreparing,
  480. },
  481. };
  482. // 异步:并行执行 AI 生成标题 + 检测规模,然后启动内容生成
  483. (async () => {
  484. try {
  485. let title = providedTitle;
  486. let bookScale = providedBookScale;
  487. // 并行执行 AI 调用
  488. const aiPromises: Promise<any>[] = [];
  489. const titleIdx = needTitle ? aiPromises.push(autoGenerateTitle(body.description)) - 1 : -1;
  490. const scaleIdx = needScale ? aiPromises.push(autoDetectBookType(providedTitle || '', body.description)) - 1 : -1;
  491. if (aiPromises.length > 0) {
  492. const results = await Promise.all(aiPromises);
  493. if (titleIdx >= 0) {
  494. title = results[titleIdx] as string;
  495. console.log(`[LangGraph] AI 自动生成书名: "${title}"`);
  496. }
  497. if (scaleIdx >= 0) {
  498. bookScale = results[scaleIdx] as string;
  499. console.log(`[LangGraph] AI 自动检测规模: ${title} -> ${bookScale}`);
  500. }
  501. }
  502. // 回填 AI 结果到数据库
  503. const scaleConfig = getScaleConfig(bookScale!);
  504. await bookStore.update(book.id.toString(), {
  505. title: title!,
  506. bookScale: bookScale!,
  507. totalChapters: scaleConfig.isShortArticle ? 1 : scaleConfig.chapters,
  508. estimatedWords: scaleConfig.totalWords,
  509. });
  510. // 确定生成层级并启动内容生成
  511. const genLevel = body.genLevel !== undefined
  512. ? resolveGenLevel(bookScale!, body.genLevel)
  513. : body.bookType && body.bookType !== 'auto'
  514. ? mapBookTypeToGenLevel(body.bookType)
  515. : resolveGenLevel(bookScale!);
  516. await langGraphGenerator.generate(book.id.toString(), body.description, bookScale!, genLevel);
  517. console.log(`[LangGraph] 生成完成: bookId=${book.id}`);
  518. } catch (err) {
  519. console.error(`[LangGraph] AI 准备或生成失败: bookId=${book.id}`, err);
  520. bookStore.update(book.id.toString(), {
  521. genStage: 'failed',
  522. errorMsg: err instanceof Error ? err.message : '生成失败',
  523. failedStage: 'outlining',
  524. });
  525. }
  526. })();
  527. } catch (error) {
  528. console.error('启动失败:', error);
  529. ctx.status = 500;
  530. ctx.body = {
  531. code: 1,
  532. message: error instanceof Error ? error.message : '启动失败',
  533. };
  534. }
  535. });
  536. /**
  537. * 异步填充 AI 结果(交互模式使用,不启动生成)
  538. */
  539. async function fillAiResultsAsync(
  540. bookId: string,
  541. description: string,
  542. providedTitle?: string,
  543. providedBookScale?: string,
  544. ): Promise<void> {
  545. console.log(`[fillAiResultsAsync] 开始: bookId=${bookId}, providedTitle="${providedTitle}", providedBookScale="${providedBookScale}", desc前50字="${description?.substring(0, 50)}"`);
  546. try {
  547. let title = providedTitle;
  548. let bookScale = providedBookScale;
  549. const needTitle = !title;
  550. const needScale = !bookScale;
  551. const aiPromises: Promise<any>[] = [];
  552. const titleIdx = needTitle ? aiPromises.push(autoGenerateTitle(description)) - 1 : -1;
  553. const scaleIdx = needScale ? aiPromises.push(autoDetectBookType(title || '', description)) - 1 : -1;
  554. if (aiPromises.length > 0) {
  555. const results = await Promise.all(aiPromises);
  556. if (titleIdx >= 0) {
  557. title = results[titleIdx] as string;
  558. console.log(`[LangGraph] AI 自动生成书名 (交互): "${title}"`);
  559. }
  560. if (scaleIdx >= 0) {
  561. bookScale = results[scaleIdx] as string;
  562. console.log(`[LangGraph] AI 自动检测规模 (交互): ${title} -> ${bookScale}`);
  563. }
  564. }
  565. const scaleConfig = getScaleConfig(bookScale!);
  566. await bookStore.update(bookId.toString(), {
  567. title: title!,
  568. bookScale: bookScale!,
  569. totalChapters: scaleConfig.isShortArticle ? 1 : scaleConfig.chapters,
  570. estimatedWords: scaleConfig.totalWords,
  571. });
  572. } catch (err) {
  573. console.warn(`[LangGraph] AI 异步填充失败: bookId=${bookId}`, err);
  574. }
  575. }
  576. /**
  577. * GET /api/book-generator/langgraph/books
  578. * 获取书籍列表
  579. * 返回:公开的书籍(有公开音频)+ 当前用户自己的书籍
  580. * 注意:此接口已废弃,请使用 /public-books 或 /my-books
  581. */
  582. router.get('/books', optionalAuth, async (ctx: Context) => {
  583. try {
  584. const userId = ctx.state.user?.userId;
  585. const userIdNum = userId ? parseInt(userId as string) : undefined;
  586. // 获取公开书籍(有公开音频的书籍)
  587. const publicBooks = await bookStore.getPublicBooks();
  588. // 如果用户已登录,获取用户自己的书籍
  589. let userBooks: any[] = [];
  590. if (userIdNum) {
  591. userBooks = await bookStore.getAllByUser(userIdNum, false);
  592. }
  593. // 合并并去重(按 id)
  594. const bookMap = new Map<string, any>();
  595. publicBooks.forEach(b => bookMap.set(b.id, b));
  596. userBooks.forEach(b => {
  597. if (!bookMap.has(b.id)) {
  598. bookMap.set(b.id, b);
  599. }
  600. });
  601. const books = Array.from(bookMap.values());
  602. ctx.body = { code: 0, message: 'success', data: { books } };
  603. } catch (error) {
  604. console.error('查询失败:', error);
  605. ctx.status = 500;
  606. ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  607. }
  608. });
  609. /**
  610. * GET /api/book-generator/langgraph/public-books
  611. * 获取公开书籍列表(首页专用)
  612. * 只返回有公开音频的书籍
  613. */
  614. router.get('/public-books', async (ctx: Context) => {
  615. try {
  616. const publicBooks = await bookStore.getPublicBooks();
  617. ctx.body = { code: 0, message: 'success', data: { books: publicBooks } };
  618. } catch (error) {
  619. console.error('查询公开书籍失败:', error);
  620. ctx.status = 500;
  621. ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  622. }
  623. });
  624. /**
  625. * GET /api/book-generator/langgraph/my-books
  626. * 获取当前用户自己的书籍列表(管理页专用)
  627. * 只返回当前用户创建的书籍
  628. */
  629. router.get('/my-books', optionalAuth, async (ctx: Context) => {
  630. try {
  631. const userId = ctx.state.user?.userId;
  632. if (!userId) {
  633. ctx.status = 401;
  634. ctx.body = { code: 1, message: '请先登录' };
  635. return;
  636. }
  637. const userBooks = await bookStore.getAllByUser(parseInt(userId as string), false);
  638. ctx.body = { code: 0, message: 'success', data: { books: userBooks } };
  639. } catch (error) {
  640. console.error('查询用户书籍失败:', error);
  641. ctx.status = 500;
  642. ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  643. }
  644. });
  645. /**
  646. * PUT /api/book-generator/langgraph/books/:id/publish
  647. * 切换书籍公开状态
  648. */
  649. router.put('/books/:id/publish', optionalAuth, async (ctx: Context) => {
  650. try {
  651. const bookId = ctx.params.id;
  652. const newStatus = await bookStore.togglePublish(bookId);
  653. ctx.body = {
  654. code: 0,
  655. message: 'success',
  656. data: { isPublished: newStatus }
  657. };
  658. } catch (error) {
  659. console.error('切换发布状态失败:', error);
  660. ctx.status = 500;
  661. ctx.body = { code: 1, message: error instanceof Error ? error.message : '操作失败' };
  662. }
  663. });
  664. /**
  665. * GET /api/book-generator/langgraph/books/:id
  666. * 获取书籍详情
  667. * 支持公开过滤:?filterPublic=true&userId=1
  668. */
  669. router.get('/books/:id', optionalAuth, async (ctx: Context) => {
  670. try {
  671. const bookId = ctx.params.id as string;
  672. const userId = ctx.state.user?.userId || TEST_USER_ID;
  673. const filterPublic = ctx.query.filterPublic === 'true';
  674. const book = await bookStore.getById(bookId, filterPublic, parseInt(userId as string));
  675. if (!book) {
  676. ctx.status = 404;
  677. ctx.body = { code: 1, message: '书籍不存在' };
  678. return;
  679. }
  680. ctx.body = { code: 0, message: 'success', data: { book } };
  681. } catch (error) {
  682. console.error('查询失败:', error);
  683. ctx.status = 500;
  684. ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  685. }
  686. });
  687. /**
  688. * GET /api/book-generator/langgraph/books/:id/progress
  689. * 获取书籍生成进度
  690. */
  691. router.get('/books/:id/progress', async (ctx: Context) => {
  692. try {
  693. const bookId = ctx.params.id as string;
  694. const book = await bookStore.getById(bookId);
  695. if (!book) {
  696. ctx.status = 404;
  697. ctx.body = { code: 1, message: '书籍不存在' };
  698. return;
  699. }
  700. // 计算实际进度(基于章节完成情况)
  701. const completedChapters = book.chapters.filter((c) => c.genStage === 'video_completed').length;
  702. const totalChapters = book.outline?.chapters?.length || book.totalChapters || 0;
  703. // 查找当前正在生成的章节
  704. const currentGenerating = book.chapters.find(
  705. (c) => c.genStage === 'content_generating' || c.genStage === 'audio_generating' || c.genStage === 'video_generating'
  706. );
  707. const currentChapter = currentGenerating
  708. ? { number: currentGenerating.number, title: currentGenerating.title, level: currentGenerating.level }
  709. : null;
  710. // 如果有大纲,使用大纲章节数计算进度
  711. let progress = book.progress;
  712. if (totalChapters > 0 && book.genStage !== 'video_completed') {
  713. progress = Math.round((completedChapters / totalChapters) * 100);
  714. }
  715. ctx.body = {
  716. code: 0,
  717. message: 'success',
  718. data: {
  719. bookId,
  720. genStage: book.genStage,
  721. progress,
  722. completedChapters,
  723. totalChapters,
  724. currentChapter,
  725. },
  726. };
  727. } catch (error) {
  728. console.error('查询进度失败:', error);
  729. ctx.status = 500;
  730. ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  731. }
  732. });
  733. /**
  734. * DELETE /api/book-generator/langgraph/books/:id
  735. * 删除书籍
  736. */
  737. router.delete('/books/:id', async (ctx: Context) => {
  738. try {
  739. const bookId = ctx.params.id as string;
  740. await bookStore.delete(bookId);
  741. ctx.body = { code: 0, message: '删除成功' };
  742. } catch (error) {
  743. console.error('删除失败:', error);
  744. ctx.status = 500;
  745. ctx.body = { code: 1, message: error instanceof Error ? error.message : '删除失败' };
  746. }
  747. });
  748. /**
  749. * POST /api/book-generator/langgraph/books/:id/generate
  750. * 对已有书籍使用 LangGraph 生成
  751. */
  752. router.post('/books/:id/generate', optionalAuth, async (ctx: Context) => {
  753. try {
  754. const bookId = ctx.params.id as string;
  755. console.log(`[LangGraph Generate] 收到请求 bookId=${bookId}`);
  756. const body = (ctx.request.body || {}) as { bookScale?: string; genLevel?: number };
  757. const book = await bookStore.getById(bookId);
  758. console.log(`[LangGraph Generate] book对象:`, book ? '存在' : 'null');
  759. if (!book) {
  760. ctx.status = 404;
  761. ctx.body = { code: 1, message: '书籍不存在' };
  762. return;
  763. }
  764. // ========== 确定 bookScale ==========
  765. // 优先级:
  766. // 1) 请求显式指定(body.bookScale)→ 用户选的,直接用
  767. // 2) AI 根据描述自动检测 → LLM 判断
  768. // 3) 书籍已有规模 → 沿用
  769. // 4) 兜底 → 1000(最小规模)
  770. let bookScale: string | undefined;
  771. if (body.bookScale && BOOK_TYPE_CONFIG[body.bookScale]) {
  772. // 用户在当前请求中显式选了规模
  773. bookScale = body.bookScale;
  774. console.log(`[LangGraph Generate] 使用请求指定的 bookScale=${bookScale}`);
  775. } else {
  776. // 未显式选择 → 让 AI 根据描述判断
  777. const desc = book.description || '';
  778. try {
  779. console.log(`[LangGraph Generate] AI 自动检测规模...`);
  780. bookScale = await autoDetectBookType(book.title || '', desc);
  781. console.log(`[LangGraph Generate] AI 检测结果 → bookScale=${bookScale}`);
  782. } catch (e) {
  783. console.warn(`[LangGraph Generate] AI 检测失败,回退:`, e);
  784. }
  785. // AI 失败或返回无效值 → 用书籍已保存的
  786. if (!bookScale || !BOOK_TYPE_CONFIG[bookScale]) {
  787. bookScale = book.bookScale && BOOK_TYPE_CONFIG[book.bookScale] ? book.bookScale : undefined;
  788. }
  789. }
  790. // 最终兜底:用最小规模(1000字),避免误判生成大量无用内容
  791. bookScale = bookScale && BOOK_TYPE_CONFIG[bookScale] ? bookScale : '1000';
  792. // 持久化检测结果
  793. if (bookScale !== book.bookScale) {
  794. await bookStore.update(bookId, { bookScale });
  795. }
  796. const genLevel = resolveGenLevel(bookScale, body.genLevel, book.description);
  797. // ========== 生成前配额检查 ==========
  798. const userId = ctx.state.user?.userId ? parseInt(ctx.state.user.userId as string) : (book.userId || parseInt(TEST_USER_ID));
  799. const scaleConfig = getScaleConfig(bookScale);
  800. const totalWords = scaleConfig.totalWords;
  801. const audioQuota = await checkAudioQuota(userId, totalWords);
  802. if (!audioQuota.allowed) {
  803. ctx.status = 403;
  804. ctx.body = {
  805. code: 1,
  806. message: audioQuota.reason,
  807. data: {
  808. estimatedWords: totalWords,
  809. estimatedAudioMinutes: estimateAudioMinutesFromWords(totalWords),
  810. remainingMinutes: audioQuota.remainingMinutes,
  811. totalMinutes: audioQuota.totalMinutes,
  812. }
  813. };
  814. return;
  815. }
  816. // 防止重复生成:如果书籍正在生成中,拒绝请求
  817. if (book.genStage === 'content_generating' || book.genStage === 'audio_generating' || book.genStage === 'video_generating') {
  818. console.log(`[LangGraph Generate] 书籍正在生成中,拒绝重复请求 bookId=${bookId}`);
  819. ctx.status = 400;
  820. ctx.body = {
  821. code: 1,
  822. message: '书籍正在生成中,请勿重复提交',
  823. data: {
  824. bookId,
  825. genStage: book.genStage,
  826. progress: book.progress,
  827. }
  828. };
  829. return;
  830. }
  831. // 异步生成(跳过队列,开发环境下队列不可靠)
  832. await bookStore.update(bookId, { genStage: 'outlining' });
  833. langGraphGenerator.generate(bookId, book.description, bookScale, genLevel)
  834. .then(() => {
  835. console.log(`[LangGraph] 生成完成: bookId=${bookId}`);
  836. })
  837. .catch(err => {
  838. console.error(`[LangGraph] 生成失败: bookId=${bookId}`, err);
  839. bookStore.update(bookId, {
  840. genStage: 'failed', failedStage: 'outlining',
  841. errorMsg: err instanceof Error ? err.message : '生成失败',
  842. });
  843. });
  844. ctx.body = {
  845. code: 0,
  846. message: 'LangGraph 生成任务已启动',
  847. data: { bookId, genStage: 'outlining', mode: 'async' },
  848. };
  849. } catch (error) {
  850. console.error('启动失败:', error);
  851. ctx.status = 500;
  852. ctx.body = {
  853. code: 1,
  854. message: error instanceof Error ? error.message : '启动失败',
  855. };
  856. }
  857. });
  858. /**
  859. * POST /api/book-generator/langgraph/books/:id/audio
  860. * 批量生成书籍所有小节的音频
  861. */
  862. router.post('/books/:id/audio', async (ctx: Context) => {
  863. try {
  864. const bookId = ctx.params.id as string;
  865. const { voiceId = 'longyingling_v3' } = ctx.request.body as { voiceId?: string };
  866. const book = await bookStore.getById(bookId);
  867. if (!book) {
  868. ctx.status = 404;
  869. ctx.body = { code: 1, message: '书籍不存在' };
  870. return;
  871. }
  872. // 获取章节树
  873. const chapters = await bookStore.getChapterTree(bookId);
  874. // 动态获取叶节点层级(最大level值)
  875. const maxLevel = chapters.length > 0
  876. ? Math.max(...chapters.map((c: any) => c.level || 0))
  877. : 0;
  878. if (maxLevel === 0) {
  879. ctx.body = { code: 1, message: '没有章节' };
  880. return;
  881. }
  882. // 获取叶节点(最大level的所有节点)
  883. const leafNodes = chapters.filter((c: any) => c.level === maxLevel);
  884. // 检查内容状态 - 叶节点必须有content且genStage为content_completed
  885. const leafNodesWithContent = leafNodes.filter((c: any) => c.content && c.genStage === 'content_completed');
  886. if (leafNodes.length === 0) {
  887. ctx.body = { code: 1, message: `没有${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'}` };
  888. return;
  889. }
  890. if (leafNodesWithContent.length === 0) {
  891. ctx.body = {
  892. code: 1,
  893. message: `没有内容生成完成的${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'},请先生成内容`,
  894. data: {
  895. totalSubsections: leafNodes.length,
  896. completedSubsections: 0,
  897. }
  898. };
  899. return;
  900. }
  901. console.log(`[Audio] 书籍 ${bookId} 共有 ${leafNodes.length} 个${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'},其中 ${leafNodesWithContent.length} 个内容已生成完成`);
  902. // 异步生成所有叶节点音频
  903. for (const sub of leafNodesWithContent) {
  904. bookStore.generateChapterAudioById(sub.id, book.userId || 1).catch(err => {
  905. console.error(`[Audio] ${maxLevel === 3 ? '小节' : '节'}${sub.number}音频生成失败:`, err);
  906. });
  907. }
  908. ctx.body = {
  909. code: 0,
  910. message: '音频生成任务已启动',
  911. data: {
  912. totalSubsections: leafNodesWithContent.length,
  913. taskId: `audio_${bookId}_${Date.now()}`,
  914. },
  915. };
  916. } catch (error) {
  917. console.error('音频生成失败:', error);
  918. ctx.status = 500;
  919. ctx.body = { code: 1, message: error instanceof Error ? error.message : '音频生成失败' };
  920. }
  921. });
  922. /**
  923. * POST /api/book-generator/langgraph/books/:id/audio/cancel
  924. * 取消书籍所有章节的音频生成
  925. */
  926. router.post('/books/:id/audio/cancel', async (ctx: Context) => {
  927. try {
  928. const bookId = ctx.params.id as string;
  929. const book = await bookStore.getById(bookId);
  930. if (!book) {
  931. ctx.status = 404;
  932. ctx.body = { code: 1, message: '书籍不存在' };
  933. return;
  934. }
  935. const result = await bookStore.cancelAudioGeneration(bookId);
  936. if (result.cancelledCount === 0) {
  937. ctx.body = {
  938. code: 0,
  939. message: '没有正在运行的音频生成任务',
  940. data: result,
  941. };
  942. return;
  943. }
  944. console.log(`[Audio] 书籍 ${bookId} 取消音频生成,已取消 ${result.cancelledCount} 个任务,回退 ${result.rolledBackChapters.length} 个章节`);
  945. ctx.body = {
  946. code: 0,
  947. message: `已取消 ${result.cancelledCount} 个音频生成任务`,
  948. data: result,
  949. };
  950. } catch (error) {
  951. console.error('取消音频生成失败:', error);
  952. ctx.status = 500;
  953. ctx.body = { code: 1, message: error instanceof Error ? error.message : '取消失败' };
  954. }
  955. });
  956. /**
  957. * GET /api/book-generator/langgraph/books/:id/video-status
  958. * 获取书籍视频生成状态(用于前端轮询)
  959. */
  960. router.get('/books/:id/video-status', async (ctx: Context) => {
  961. try {
  962. const bookId = ctx.params.id as string;
  963. const book = await bookStore.getById(bookId);
  964. if (!book) {
  965. ctx.status = 404;
  966. ctx.body = { code: 1, message: '书籍不存在' };
  967. return;
  968. }
  969. // 获取章节树
  970. const chapters = await bookStore.getChapterTree(bookId);
  971. // 动态获取叶节点层级
  972. const maxLevel = chapters.length > 0
  973. ? Math.max(...chapters.map((c: any) => c.level || 0))
  974. : 0;
  975. // 获取叶节点
  976. const leafNodes = chapters.filter((c: any) => c.level === maxLevel);
  977. // 统计视频状态
  978. const total = leafNodes.length;
  979. const completed = leafNodes.filter((c: any) => c.videoUrl && c.videoUrl !== '').length;
  980. const pending = leafNodes.filter((c: any) => !c.videoUrl || c.videoUrl === '').length;
  981. ctx.body = {
  982. code: 0,
  983. message: 'success',
  984. data: {
  985. bookId,
  986. total,
  987. completed,
  988. pending,
  989. allCompleted: completed >= total && total > 0,
  990. },
  991. };
  992. } catch (error) {
  993. console.error('获取视频状态失败:', error);
  994. ctx.status = 500;
  995. ctx.body = { code: 1, message: error instanceof Error ? error.message : '获取失败' };
  996. }
  997. });
  998. /**
  999. * GET /api/book-generator/langgraph/books/:id/audio-status
  1000. * 获取书籍音频生成状态(用于前端轮询)
  1001. */
  1002. router.get('/books/:id/audio-status', async (ctx: Context) => {
  1003. try {
  1004. const bookId = ctx.params.id as string;
  1005. const book = await bookStore.getById(bookId);
  1006. if (!book) {
  1007. ctx.status = 404;
  1008. ctx.body = { code: 1, message: '书籍不存在' };
  1009. return;
  1010. }
  1011. // 获取章节树
  1012. const chapters = await bookStore.getChapterTree(bookId);
  1013. // 动态获取叶节点层级
  1014. const maxLevel = chapters.length > 0
  1015. ? Math.max(...chapters.map((c: any) => c.level || 0))
  1016. : 0;
  1017. // 获取叶节点
  1018. const leafNodes = chapters.filter((c: any) => c.level === maxLevel);
  1019. // 统计音频状态
  1020. const total = leafNodes.length;
  1021. const completed = leafNodes.filter((c: any) => c.audioUrl && c.audioUrl !== '').length;
  1022. const pending = leafNodes.filter((c: any) => !c.audioUrl || c.audioUrl === '').length;
  1023. ctx.body = {
  1024. code: 0,
  1025. message: 'success',
  1026. data: {
  1027. bookId,
  1028. total,
  1029. completed,
  1030. pending,
  1031. allCompleted: completed >= total && total > 0,
  1032. },
  1033. };
  1034. } catch (error) {
  1035. console.error('获取音频状态失败:', error);
  1036. ctx.status = 500;
  1037. ctx.body = { code: 1, message: error instanceof Error ? error.message : '获取失败' };
  1038. }
  1039. });
  1040. /**
  1041. * GET /api/book-generator/langgraph/books/:id/failed-chapters
  1042. * 获取生成失败的小节列表
  1043. */
  1044. router.get('/books/:id/failed-chapters', async (ctx: Context) => {
  1045. try {
  1046. const bookId = ctx.params.id as string;
  1047. const book = await bookStore.getById(bookId);
  1048. if (!book) {
  1049. ctx.status = 404;
  1050. ctx.body = { code: 1, message: '书籍不存在' };
  1051. return;
  1052. }
  1053. // 获取所有失败的小节
  1054. const chapters = await bookStore.getChapterTree(bookId);
  1055. const failedSubsections = chapters.filter(c => c.genStage === 'failed');
  1056. ctx.body = {
  1057. code: 0,
  1058. message: 'success',
  1059. data: {
  1060. bookId,
  1061. failedCount: failedSubsections.length,
  1062. failedChapters: failedSubsections.map(c => ({
  1063. id: c.id,
  1064. number: c.number,
  1065. title: c.title,
  1066. level: c.level,
  1067. errorMsg: c.errorMsg,
  1068. parentId: c.parentId,
  1069. })),
  1070. },
  1071. };
  1072. } catch (error) {
  1073. console.error('获取失败小节失败:', error);
  1074. ctx.status = 500;
  1075. ctx.body = { code: 1, message: error instanceof Error ? error.message : '获取失败' };
  1076. }
  1077. });
  1078. /**
  1079. * POST /api/book-generator/langgraph/books/:id/resume
  1080. * 从断点处继续生成(重试失败的小节)
  1081. */
  1082. router.post('/books/:id/resume', async (ctx: Context) => {
  1083. try {
  1084. const bookId = ctx.params.id as string;
  1085. const book = await bookStore.getById(bookId);
  1086. if (!book) {
  1087. ctx.status = 404;
  1088. ctx.body = { code: 1, message: '书籍不存在' };
  1089. return;
  1090. }
  1091. if (book.genStage === 'video_completed') {
  1092. ctx.body = { code: 1, message: '书籍已生成完成,无需继续' };
  1093. return;
  1094. }
  1095. // 获取失败的小节
  1096. const chapters = await bookStore.getChapterTree(bookId);
  1097. const failedSubsections = chapters.filter(c => c.genStage === 'failed');
  1098. if (failedSubsections.length === 0) {
  1099. ctx.body = { code: 1, message: '没有失败的小节需要重试' };
  1100. return;
  1101. }
  1102. // 重置失败小节的状态为 pending
  1103. for (const sub of failedSubsections) {
  1104. await bookStore.updateChapterById(sub.id, {
  1105. genStage: 'idle',
  1106. errorMsg: null,
  1107. content: null,
  1108. });
  1109. }
  1110. // 直接重新生成(跳过队列)
  1111. const { langGraphGenerator } = await import('./index.js');
  1112. langGraphGenerator.generate(
  1113. bookId,
  1114. book.description || book.title,
  1115. book.bookScale || '1000'
  1116. ).then(() => {
  1117. console.log(`[LangGraph] 续生成完成: bookId=${bookId}`);
  1118. }).catch(err => {
  1119. console.error(`[LangGraph] 续生成失败: bookId=${bookId}`, err);
  1120. });
  1121. ctx.body = {
  1122. code: 0,
  1123. message: `已重启生成,将重试 ${failedSubsections.length} 个失败的小节`,
  1124. data: {
  1125. bookId,
  1126. retryCount: failedSubsections.length,
  1127. genStage: 'resuming',
  1128. },
  1129. };
  1130. } catch (error) {
  1131. console.error('继续生成失败:', error);
  1132. ctx.status = 500;
  1133. ctx.body = { code: 1, message: error instanceof Error ? error.message : '继续生成失败' };
  1134. }
  1135. });
  1136. /**
  1137. * POST /api/book-generator/langgraph/books/:id/retry-chapter
  1138. * 单独重试某个失败的小节
  1139. */
  1140. router.post('/books/:id/retry-chapter', async (ctx: Context) => {
  1141. try {
  1142. const bookId = ctx.params.id as string;
  1143. const { chapterId } = ctx.request.body as { chapterId: number };
  1144. if (!chapterId) {
  1145. ctx.status = 400;
  1146. ctx.body = { code: 1, message: '请提供章节 ID' };
  1147. return;
  1148. }
  1149. // 获取所有章节查找指定的章节
  1150. const chapters = await bookStore.getChapterTree(bookId);
  1151. const chapter = chapters.find(c => c.id === chapterId);
  1152. if (!chapter) {
  1153. ctx.status = 404;
  1154. ctx.body = { code: 1, message: '章节不存在' };
  1155. return;
  1156. }
  1157. // 重置章节状态
  1158. await bookStore.updateChapterById(chapterId, {
  1159. genStage: 'idle',
  1160. errorMsg: null,
  1161. content: null,
  1162. });
  1163. ctx.body = {
  1164. code: 0,
  1165. message: '章节已重置为待生成状态',
  1166. data: { chapterId },
  1167. };
  1168. } catch (error) {
  1169. console.error('重试章节失败:', error);
  1170. ctx.status = 500;
  1171. ctx.body = { code: 1, message: error instanceof Error ? error.message : '重试失败' };
  1172. }
  1173. });
  1174. /**
  1175. * GET /api/book-generator/langgraph/books/:id/full-content
  1176. * 获取完整书籍内容(所有章节内容合并)
  1177. */
  1178. router.get('/books/:id/full-content', async (ctx: Context) => {
  1179. try {
  1180. const bookId = ctx.params.id as string;
  1181. const book = await bookStore.getById(bookId);
  1182. if (!book) {
  1183. ctx.status = 404;
  1184. ctx.body = { code: 1, message: '书籍不存在' };
  1185. return;
  1186. }
  1187. // 获取章节树
  1188. const chapters = await bookStore.getChapterTree(bookId);
  1189. // 按层级和顺序构建内容
  1190. let fullContent = `# ${book.title}\n\n`;
  1191. if (book.description) {
  1192. fullContent += `## 简介\n${book.description}\n\n`;
  1193. }
  1194. // 递归添加章节内容
  1195. const addChapterContent = (chapter: any, indent: string = '') => {
  1196. if (chapter.content && chapter.genStage === 'content_completed') {
  1197. fullContent += `${indent}${chapter.number}. ${chapter.title}\n\n`;
  1198. fullContent += chapter.content + '\n\n';
  1199. }
  1200. // 处理子章节
  1201. const children = chapters.filter((c: any) => c.parentId === chapter.id);
  1202. children.forEach(child => {
  1203. addChapterContent(child, indent + ' ');
  1204. });
  1205. };
  1206. // 添加一级章节
  1207. const level1Chapters = chapters.filter((c: any) => c.level === 1);
  1208. level1Chapters.forEach(chapter => addChapterContent(chapter));
  1209. ctx.body = {
  1210. code: 0,
  1211. message: 'success',
  1212. data: {
  1213. bookId,
  1214. title: book.title,
  1215. totalChapters: level1Chapters.length,
  1216. content: fullContent,
  1217. wordCount: book.estimatedWords,
  1218. },
  1219. };
  1220. } catch (error) {
  1221. console.error('获取完整内容失败:', error);
  1222. ctx.status = 500;
  1223. ctx.body = { code: 1, message: error instanceof Error ? error.message : '获取失败' };
  1224. }
  1225. });
  1226. /**
  1227. * POST /api/book-generator/langgraph/books/:id/outline
  1228. * 生成书籍大纲
  1229. */
  1230. router.post('/books/:id/outline', async (ctx: Context) => {
  1231. try {
  1232. const bookId = ctx.params.id as string;
  1233. const book = await bookStore.getById(bookId);
  1234. if (!book) {
  1235. ctx.status = 404;
  1236. ctx.body = { code: 1, message: '书籍不存在' };
  1237. return;
  1238. }
  1239. // 检查是否已经有大纲
  1240. if (book.outline && book.outline.chapters && book.outline.chapters.length > 0) {
  1241. ctx.body = {
  1242. code: 0,
  1243. message: '大纲已存在,无需重复生成',
  1244. data: { outline: book.outline },
  1245. };
  1246. return;
  1247. }
  1248. // 获取书籍类型配置
  1249. const scaleConfig = getScaleConfig(book.bookScale || '1000');
  1250. // 调用AI生成大纲
  1251. const { generateOutline } = await import('./index.js');
  1252. const outline = await generateOutline(bookId, book.description, book.bookScale || '1000');
  1253. // 更新书籍的大纲
  1254. await bookStore.update(bookId, { outline });
  1255. ctx.body = {
  1256. code: 0,
  1257. message: '大纲生成成功',
  1258. data: { outline },
  1259. };
  1260. } catch (error) {
  1261. console.error('生成大纲失败:', error);
  1262. ctx.status = 500;
  1263. ctx.body = { code: 1, message: error instanceof Error ? error.message : '生成大纲失败' };
  1264. }
  1265. });
  1266. /**
  1267. * POST /api/book-generator/langgraph/books/:id/chapters
  1268. * 生成单个章节(或全部章节,取决于参数)
  1269. * body: { chapterNumber?: number } - 如果不传chapterNumber,则生成全部
  1270. */
  1271. router.post('/books/:id/chapters', async (ctx: Context) => {
  1272. try {
  1273. const bookId = ctx.params.id as string;
  1274. const body = ctx.request.body as { chapterNumber?: number };
  1275. const book = await bookStore.getById(bookId);
  1276. if (!book) {
  1277. ctx.status = 404;
  1278. ctx.body = { code: 1, message: '书籍不存在' };
  1279. return;
  1280. }
  1281. // 如果指定了章节号,只生成单个章节
  1282. if (body.chapterNumber) {
  1283. // 检查章节是否存在
  1284. const chapters = await bookStore.getChapterTree(bookId);
  1285. const targetChapter = chapters.find((c: any) => c.number === body.chapterNumber);
  1286. if (!targetChapter) {
  1287. ctx.status = 404;
  1288. ctx.body = { code: 1, message: `章节 ${body.chapterNumber} 不存在` };
  1289. return;
  1290. }
  1291. // 异步生成章节内容
  1292. bookStore.generateSingleChapterContent(bookId, targetChapter.id).catch(err => {
  1293. console.error(`[Generate Chapter] 章节${body.chapterNumber}生成失败:`, err);
  1294. });
  1295. ctx.body = {
  1296. code: 0,
  1297. message: `章节 ${body.chapterNumber} 生成任务已启动`,
  1298. data: { chapterId: targetChapter.id, chapterNumber: body.chapterNumber },
  1299. };
  1300. } else {
  1301. // 没有指定章节号,触发整本书生成
  1302. ctx.body = {
  1303. code: 0,
  1304. message: '请使用 /generate 接口生成整本书',
  1305. data: { hint: '使用 POST /books/:id/generate' },
  1306. };
  1307. }
  1308. } catch (error) {
  1309. console.error('生成章节失败:', error);
  1310. ctx.status = 500;
  1311. ctx.body = { code: 1, message: error instanceof Error ? error.message : '生成章节失败' };
  1312. }
  1313. });
  1314. /**
  1315. * POST /api/book-generator/langgraph/books/:id/foreword
  1316. * 生成前言
  1317. */
  1318. router.post('/books/:id/foreword', async (ctx: Context) => {
  1319. try {
  1320. const bookId = ctx.params.id as string;
  1321. const book = await bookStore.getById(bookId);
  1322. if (!book) {
  1323. ctx.status = 404;
  1324. ctx.body = { code: 1, message: '书籍不存在' };
  1325. return;
  1326. }
  1327. // 调用LLM生成前言
  1328. const messages: ChatMessage[] = [
  1329. {
  1330. role: 'system',
  1331. content: `你是一位专业的图书作者。请根据以下信息为书籍生成前言(前言通常介绍写作背景、目标读者、内容概要)。
  1332. 要求:
  1333. 1. 字数控制在300-500字
  1334. 2. 语言正式但亲切
  1335. 3. 不要使用 markdown 格式,直接输出纯文本
  1336. 输出格式:
  1337. 直接输出前言内容,不要包含任何标记。`,
  1338. },
  1339. {
  1340. role: 'user',
  1341. content: `书籍信息:
  1342. - 书名:${book.title}
  1343. - 描述:${book.description}
  1344. - 目标读者:${book.targetAudience || '普通读者'}
  1345. - 风格:${book.style || '专业'}
  1346. 请生成这本书的前言。`,
  1347. },
  1348. ];
  1349. const foreword = await callLLMWithMessages(messages);
  1350. // 更新书籍前言字段
  1351. await bookStore.update(bookId, { foreword });
  1352. ctx.body = {
  1353. code: 0,
  1354. message: '前言生成成功',
  1355. data: { foreword },
  1356. };
  1357. } catch (error) {
  1358. console.error('生成前言失败:', error);
  1359. ctx.status = 500;
  1360. ctx.body = { code: 1, message: error instanceof Error ? error.message : '生成前言失败' };
  1361. }
  1362. });
  1363. /**
  1364. * POST /api/book-generator/langgraph/books/:id/afterword
  1365. * 生成后记
  1366. */
  1367. router.post('/books/:id/afterword', async (ctx: Context) => {
  1368. try {
  1369. const bookId = ctx.params.id as string;
  1370. const book = await bookStore.getById(bookId);
  1371. if (!book) {
  1372. ctx.status = 404;
  1373. ctx.body = { code: 1, message: '书籍不存在' };
  1374. return;
  1375. }
  1376. // 调用LLM生成后记
  1377. const messages: ChatMessage[] = [
  1378. {
  1379. role: 'system',
  1380. content: `你是一位专业的图书作者。请为书籍生成后记(后记通常总结全书核心观点、分享写作心得、感谢读者)。
  1381. 要求:
  1382. 1. 字数控制在300-500字
  1383. 2. 语言真挚、诚恳
  1384. 3. 不要使用 markdown 格式,直接输出纯文本
  1385. 输出格式:
  1386. 直接输出后记内容,不要包含任何标记。`,
  1387. },
  1388. {
  1389. role: 'user',
  1390. content: `书籍信息:
  1391. - 书名:${book.title}
  1392. - 描述:${book.description}
  1393. - 章节数:${book.totalChapters}
  1394. - 总字数:约${book.estimatedWords}字
  1395. 请生成这本书的后记。`,
  1396. },
  1397. ];
  1398. const afterword = await callLLMWithMessages(messages);
  1399. // 更新书籍后记字段
  1400. await bookStore.update(bookId, { afterword });
  1401. ctx.body = {
  1402. code: 0,
  1403. message: '后记生成成功',
  1404. data: { afterword },
  1405. };
  1406. } catch (error) {
  1407. console.error('生成后记失败:', error);
  1408. ctx.status = 500;
  1409. ctx.body = { code: 1, message: error instanceof Error ? error.message : '生成后记失败' };
  1410. }
  1411. });
  1412. /**
  1413. * GET /api/book-generator/langgraph/workflow/:bookId
  1414. * 获取书籍生成工作流状态
  1415. */
  1416. router.get('/workflow/:bookId', async (ctx: Context) => {
  1417. try {
  1418. const bookId = ctx.params.bookId as string;
  1419. const book = await bookStore.getById(bookId);
  1420. if (!book) {
  1421. ctx.status = 404;
  1422. ctx.body = { code: 1, message: '书籍不存在' };
  1423. return;
  1424. }
  1425. // 获取章节树
  1426. const chapters = await bookStore.getChapterTree(bookId);
  1427. // 分析工作流状态
  1428. const completedChapters = chapters.filter((c: any) => ['content_completed', 'audio_completed', 'video_completed'].includes(c.genStage)).length;
  1429. const failedChapters = chapters.filter((c: any) => c.genStage === 'failed').length;
  1430. const pendingChapters = chapters.filter((c: any) => c.genStage === 'idle' || !c.genStage).length;
  1431. const generatingChapters = chapters.filter((c: any) => ['content_generating', 'audio_generating', 'video_generating'].includes(c.genStage)).length;
  1432. // 确定当前阶段
  1433. let phase: 'planning' | 'writing' | 'supplement' | 'done' = 'planning';
  1434. if (['content_generating', 'audio_generating', 'video_generating'].includes(book.genStage)) {
  1435. phase = 'writing';
  1436. } else if (completedChapters > 0 && failedChapters === 0) {
  1437. phase = 'done';
  1438. } else if (failedChapters > 0) {
  1439. phase = 'supplement';
  1440. }
  1441. ctx.body = {
  1442. code: 0,
  1443. message: 'success',
  1444. data: {
  1445. bookId,
  1446. genStage: book.genStage,
  1447. phase,
  1448. progress: book.progress || 0,
  1449. completedChapters,
  1450. failedChapters,
  1451. pendingChapters,
  1452. generatingChapters,
  1453. totalChapters: chapters.length,
  1454. failedChapterIds: chapters.filter((c: any) => c.genStage === 'failed').map((c: any) => c.id),
  1455. },
  1456. };
  1457. } catch (error) {
  1458. console.error('获取工作流状态失败:', error);
  1459. ctx.status = 500;
  1460. ctx.body = { code: 1, message: error instanceof Error ? error.message : '获取失败' };
  1461. }
  1462. });
  1463. /**
  1464. * GET /api/book-generator/langgraph/books/:id/chapters/:chapterId/content
  1465. * 获取指定章节的内容
  1466. */
  1467. router.get('/books/:id/chapters/:chapterId/content', optionalAuth, async (ctx: Context) => {
  1468. try {
  1469. const { id: bookId, chapterId } = ctx.params as { id: string; chapterId: string };
  1470. const chapterIdNum = parseInt(chapterId);
  1471. // 获取书籍
  1472. const book = await bookStore.getById(bookId);
  1473. if (!book) {
  1474. ctx.status = 404;
  1475. ctx.body = { code: 1, message: '书籍不存在' };
  1476. return;
  1477. }
  1478. // 获取章节
  1479. const chapter = await prisma.bookChapter.findUnique({
  1480. where: { id: chapterIdNum },
  1481. });
  1482. if (!chapter) {
  1483. ctx.status = 404;
  1484. ctx.body = { code: 1, message: '章节不存在' };
  1485. return;
  1486. }
  1487. // 检查是否属于该书籍
  1488. if (chapter.bookId !== parseInt(bookId)) {
  1489. ctx.status = 404;
  1490. ctx.body = { code: 1, message: '章节不属于该书籍' };
  1491. return;
  1492. }
  1493. ctx.body = {
  1494. code: 0,
  1495. message: 'success',
  1496. data: {
  1497. id: chapter.id,
  1498. bookId: chapter.bookId,
  1499. number: chapter.number,
  1500. title: chapter.title,
  1501. content: chapter.content || '',
  1502. wordCount: chapter.wordCount || 0,
  1503. genStage: chapter.genStage || null,
  1504. level: chapter.level,
  1505. parentId: chapter.parentId,
  1506. summary: chapter.summary || '',
  1507. keyPoints: chapter.keyPoints ? JSON.parse(chapter.keyPoints) : [],
  1508. audioUrl: chapter.audioUrl || '',
  1509. videoUrl: chapter.videoUrl || '',
  1510. isPublic: chapter.isPublic || false,
  1511. },
  1512. };
  1513. } catch (error) {
  1514. console.error('获取章节内容失败:', error);
  1515. ctx.status = 500;
  1516. ctx.body = { code: 1, message: error instanceof Error ? error.message : '获取章节内容失败' };
  1517. }
  1518. });
  1519. /**
  1520. * POST /api/book-generator/langgraph/books/:id/chapters/:chapterId/content
  1521. * 保存章节内容(手工编辑后保存)
  1522. */
  1523. router.post('/books/:id/chapters/:chapterId/content', optionalAuth, async (ctx: Context) => {
  1524. try {
  1525. const { id: bookId, chapterId } = ctx.params as { id: string; chapterId: string };
  1526. const chapterIdNum = parseInt(chapterId);
  1527. const { content } = ctx.request.body as { content: string };
  1528. if (content === undefined) {
  1529. ctx.status = 400;
  1530. ctx.body = { code: 1, message: '内容不能为空' };
  1531. return;
  1532. }
  1533. // 获取章节
  1534. const chapter = await prisma.bookChapter.findUnique({
  1535. where: { id: chapterIdNum },
  1536. });
  1537. if (!chapter) {
  1538. ctx.status = 404;
  1539. ctx.body = { code: 1, message: '章节不存在' };
  1540. return;
  1541. }
  1542. // 检查是否属于该书籍
  1543. if (chapter.bookId !== parseInt(bookId)) {
  1544. ctx.status = 404;
  1545. ctx.body = { code: 1, message: '章节不属于该书籍' };
  1546. return;
  1547. }
  1548. // 计算字数
  1549. const wordCount = content.replace(/<[^>]*>/g, '').length;
  1550. // 更新章节内容
  1551. await bookStore.updateChapterById(chapterIdNum, {
  1552. content,
  1553. wordCount,
  1554. });
  1555. ctx.body = {
  1556. code: 0,
  1557. message: '保存成功',
  1558. data: { chapterId: chapterIdNum, wordCount },
  1559. };
  1560. } catch (error) {
  1561. console.error('保存章节内容失败:', error);
  1562. ctx.status = 500;
  1563. ctx.body = { code: 1, message: error instanceof Error ? error.message : '保存章节内容失败' };
  1564. }
  1565. });
  1566. /**
  1567. * POST /api/book-generator/langgraph/books/:id/chapters/batch-regenerate
  1568. * 批量重新生成章节内容
  1569. */
  1570. router.post('/books/:id/chapters/batch-regenerate', optionalAuth, async (ctx: Context) => {
  1571. try {
  1572. const { id: bookId } = ctx.params as { id: string };
  1573. const { chapterIds } = ctx.request.body as { chapterIds: number[] };
  1574. if (!chapterIds || !Array.isArray(chapterIds) || chapterIds.length === 0) {
  1575. ctx.status = 400;
  1576. ctx.body = { code: 1, message: '请选择要重新生成的章节' };
  1577. return;
  1578. }
  1579. // 获取书籍
  1580. const book = await bookStore.getById(bookId);
  1581. if (!book) {
  1582. ctx.status = 404;
  1583. ctx.body = { code: 1, message: '书籍不存在' };
  1584. return;
  1585. }
  1586. // 重置并触发每个选中章节的重新生成
  1587. for (const chapterId of chapterIds) {
  1588. await bookStore.updateChapterById(chapterId, {
  1589. genStage: 'idle',
  1590. content: null,
  1591. });
  1592. // 后台异步执行
  1593. bookStore.generateSingleChapterContent(bookId, chapterId).catch(err => {
  1594. console.error(`[BatchRegenerate] 章节${chapterId}内容生成失败:`, err);
  1595. });
  1596. }
  1597. ctx.body = {
  1598. code: 0,
  1599. message: `已提交 ${chapterIds.length} 个章节的重新生成任务`,
  1600. data: { count: chapterIds.length },
  1601. };
  1602. } catch (error) {
  1603. console.error('批量重新生成章节失败:', error);
  1604. ctx.status = 500;
  1605. ctx.body = { code: 1, message: error instanceof Error ? error.message : '批量重新生成失败' };
  1606. }
  1607. });
  1608. /**
  1609. * POST /api/book-generator/langgraph/books/:id/chapters/batch-delete
  1610. * 批量删除章节
  1611. */
  1612. router.post('/books/:id/chapters/batch-delete', optionalAuth, async (ctx: Context) => {
  1613. try {
  1614. const { id: bookId } = ctx.params as { id: string };
  1615. const { chapterIds } = ctx.request.body as { chapterIds: number[] };
  1616. if (!chapterIds || !Array.isArray(chapterIds) || chapterIds.length === 0) {
  1617. ctx.status = 400;
  1618. ctx.body = { code: 1, message: '请选择要删除的章节' };
  1619. return;
  1620. }
  1621. // 获取书籍
  1622. const book = await bookStore.getById(bookId);
  1623. if (!book) {
  1624. ctx.status = 404;
  1625. ctx.body = { code: 1, message: '书籍不存在' };
  1626. return;
  1627. }
  1628. // 删除章节(同时会删除子章节,因为没有设置级联删除,需要手动处理)
  1629. // 对于每个要删除的章节,先删除其所有子节点,再删除自身
  1630. for (const chapterId of chapterIds) {
  1631. // 删除子章节(level > 当前章节)
  1632. await prisma.bookChapter.deleteMany({
  1633. where: {
  1634. bookId: parseInt(bookId),
  1635. parentId: chapterId,
  1636. },
  1637. });
  1638. // 删除自身
  1639. await prisma.bookChapter.deleteMany({
  1640. where: {
  1641. id: chapterId,
  1642. bookId: parseInt(bookId),
  1643. },
  1644. });
  1645. }
  1646. ctx.body = {
  1647. code: 0,
  1648. message: `已删除 ${chapterIds.length} 个章节`,
  1649. data: { count: chapterIds.length },
  1650. };
  1651. } catch (error) {
  1652. console.error('批量删除章节失败:', error);
  1653. ctx.status = 500;
  1654. ctx.body = { code: 1, message: error instanceof Error ? error.message : '批量删除失败' };
  1655. }
  1656. });
  1657. /**
  1658. * POST /api/book-generator/langgraph/books/:id/chapters/:chapterId/regenerate
  1659. * 重新生成指定章节的内容(仅叶节点允许)
  1660. */
  1661. router.post('/books/:id/chapters/:chapterId/regenerate', async (ctx: Context) => {
  1662. try {
  1663. const { id: bookId, chapterId } = ctx.params as { id: string; chapterId: string };
  1664. const chapterIdNum = parseInt(chapterId);
  1665. // 获取书籍
  1666. const book = await bookStore.getById(bookId);
  1667. if (!book) {
  1668. ctx.status = 404;
  1669. ctx.body = { code: 1, message: '书籍不存在' };
  1670. return;
  1671. }
  1672. // 获取章节
  1673. const chapter = await prisma.bookChapter.findUnique({
  1674. where: { id: chapterIdNum },
  1675. });
  1676. if (!chapter) {
  1677. ctx.status = 404;
  1678. ctx.body = { code: 1, message: '章节不存在' };
  1679. return;
  1680. }
  1681. // 检查是否为叶节点(没有子节点的节点)
  1682. const childChapters = await prisma.bookChapter.findMany({
  1683. where: { parentId: chapterIdNum },
  1684. });
  1685. if (childChapters.length > 0) {
  1686. ctx.status = 400;
  1687. ctx.body = { code: 1, message: '只有叶节点(小节)才允许重新生成内容' };
  1688. return;
  1689. }
  1690. // 重置章节状态和内容
  1691. await bookStore.updateChapterById(chapterIdNum, {
  1692. genStage: 'idle',
  1693. errorMsg: null,
  1694. content: null,
  1695. });
  1696. // 直接调用单个章节内容生成(不触发整个书籍生成流程)
  1697. // 在后台异步执行
  1698. bookStore.generateSingleChapterContent(bookId, chapterIdNum).catch(err => {
  1699. console.error(`[Regenerate] 章节${chapterIdNum}内容生成失败:`, err);
  1700. });
  1701. ctx.body = {
  1702. code: 0,
  1703. message: '章节内容重新生成任务已启动',
  1704. data: { chapterId: chapterIdNum },
  1705. };
  1706. } catch (error) {
  1707. console.error('重新生成章节失败:', error);
  1708. ctx.status = 500;
  1709. ctx.body = { code: 1, message: error instanceof Error ? error.message : '重新生成失败' };
  1710. }
  1711. });
  1712. /**
  1713. * POST /api/book-generator/langgraph/books/:id/chapters/:chapterId/regenerate-audio
  1714. * 重新生成章节音频(仅叶节点)
  1715. */
  1716. router.post('/books/:id/chapters/:chapterId/regenerate-audio', async (ctx: Context) => {
  1717. try {
  1718. const { id: bookId, chapterId } = ctx.params as { id: string; chapterId: string };
  1719. const chapterIdNum = parseInt(chapterId);
  1720. // 获取书籍
  1721. const book = await bookStore.getById(bookId);
  1722. if (!book) {
  1723. ctx.status = 404;
  1724. ctx.body = { code: 1, message: '书籍不存在' };
  1725. return;
  1726. }
  1727. // 获取章节
  1728. const chapter = await prisma.bookChapter.findUnique({
  1729. where: { id: chapterIdNum },
  1730. });
  1731. if (!chapter) {
  1732. ctx.status = 404;
  1733. ctx.body = { code: 1, message: '章节不存在' };
  1734. return;
  1735. }
  1736. // 检查是否为叶节点
  1737. const childChapters = await prisma.bookChapter.findMany({
  1738. where: { parentId: chapterIdNum },
  1739. });
  1740. if (childChapters.length > 0) {
  1741. ctx.status = 400;
  1742. ctx.body = { code: 1, message: '只有叶节点(小节)才允许重新生成音频' };
  1743. return;
  1744. }
  1745. // 检查内容是否已完成(有内容即可重生成音频,content_generating 但 content 已存在也允许)
  1746. if (!chapter.content || chapter.genStage === 'idle') {
  1747. ctx.status = 400;
  1748. ctx.body = { code: 1, message: '章节内容未生成完成,无法生成音频' };
  1749. return;
  1750. }
  1751. // 清空现有音频并回退状态
  1752. await bookStore.updateChapterById(chapterIdNum, {
  1753. audioUrl: '',
  1754. audioDuration: 0,
  1755. lrcLyrics: null,
  1756. genStage: 'content_completed',
  1757. });
  1758. // 同时清空父章节的合并音频(因为子节音频变了,合并音频也需要重新生成)
  1759. if (chapter.parentId) {
  1760. const parentChapter = await prisma.bookChapter.findUnique({
  1761. where: { id: chapter.parentId },
  1762. });
  1763. if (parentChapter?.audioUrl?.includes('_merged')) {
  1764. console.log(`[RegenerateAudio] 清除父章节 ${parentChapter.id} 的合并音频(子节${chapterIdNum}已重新生成)`);
  1765. await bookStore.updateChapterById(parentChapter.id, {
  1766. audioUrl: '',
  1767. audioDuration: 0,
  1768. });
  1769. // 如果父章节之上还有更高级的合并音频,也一并清除
  1770. if (parentChapter.parentId) {
  1771. const grandParent = await prisma.bookChapter.findUnique({
  1772. where: { id: parentChapter.parentId },
  1773. });
  1774. if (grandParent?.audioUrl?.includes('_merged')) {
  1775. console.log(`[RegenerateAudio] 清除祖父章节 ${grandParent.id} 的合并音频`);
  1776. await bookStore.updateChapterById(grandParent.id, {
  1777. audioUrl: '',
  1778. audioDuration: 0,
  1779. });
  1780. }
  1781. }
  1782. }
  1783. }
  1784. // 异步生成新音频
  1785. bookStore.generateChapterAudioById(chapterIdNum, book.userId || 1);
  1786. ctx.body = {
  1787. code: 0,
  1788. message: '音频重新生成任务已启动',
  1789. data: { chapterId: chapterIdNum },
  1790. };
  1791. } catch (error) {
  1792. console.error('重新生成音频失败:', error);
  1793. ctx.status = 500;
  1794. ctx.body = { code: 1, message: error instanceof Error ? error.message : '重新生成音频失败' };
  1795. }
  1796. });
  1797. /**
  1798. * POST /api/book-generator/langgraph/books/:id/chapters/:chapterId/video
  1799. * 生成单个章节视频
  1800. */
  1801. router.post('/books/:id/chapters/:chapterId/video', async (ctx: Context) => {
  1802. try {
  1803. const { id: bookId, chapterId } = ctx.params as { id: string; chapterId: string };
  1804. const chapterIdNum = parseInt(chapterId);
  1805. const chapter = await prisma.bookChapter.findUnique({
  1806. where: { id: chapterIdNum },
  1807. });
  1808. if (!chapter) {
  1809. ctx.status = 404;
  1810. ctx.body = { code: 1, message: '章节不存在' };
  1811. return;
  1812. }
  1813. // 检查章节是否有音频
  1814. if (!chapter.audioUrl) {
  1815. ctx.status = 400;
  1816. ctx.body = { code: 1, message: '该章节没有音频,请先生成音频' };
  1817. return;
  1818. }
  1819. // 设置视频状态为生成中
  1820. await advanceChapter(chapterIdNum, 'video_generating');
  1821. // 调用视频服务创建视频项目
  1822. const project = await createVideoProjectFromBook(parseInt(bookId), chapterIdNum);
  1823. if (!project) {
  1824. await regenerateChapter(chapterIdNum, 'failed');
  1825. ctx.status = 400;
  1826. ctx.body = { code: 1, message: '创建视频项目失败' };
  1827. return;
  1828. }
  1829. // 异步生成视频
  1830. generateVideoForProject(project.id)
  1831. .then(async (result) => {
  1832. if (result.success) {
  1833. await bookStore.updateChapterById(chapterIdNum, {
  1834. videoUrl: result.outputUrl,
  1835. videoDuration: result.duration,
  1836. });
  1837. await advanceChapter(chapterIdNum, 'video_completed');
  1838. } else {
  1839. await regenerateChapter(chapterIdNum, 'failed');
  1840. }
  1841. })
  1842. .catch(async (err) => {
  1843. console.error(`[Video] 章节${chapter.number}视频生成失败:`, err);
  1844. await regenerateChapter(chapterIdNum, 'failed');
  1845. });
  1846. ctx.body = {
  1847. code: 0,
  1848. message: '视频生成任务已启动',
  1849. data: {
  1850. projectId: project.id,
  1851. chapterId: String(chapterId),
  1852. },
  1853. };
  1854. } catch (error) {
  1855. console.error('视频生成失败:', error);
  1856. ctx.status = 500;
  1857. ctx.body = { code: 1, message: error instanceof Error ? error.message : '视频生成失败' };
  1858. }
  1859. });
  1860. /**
  1861. * POST /api/book-generator/langgraph/books/:id/videos
  1862. * 批量生成书籍所有章节视频
  1863. */
  1864. router.post('/books/:id/videos', async (ctx: Context) => {
  1865. try {
  1866. const bookId = ctx.params.id as string;
  1867. const book = await bookStore.getById(bookId);
  1868. if (!book) {
  1869. ctx.status = 404;
  1870. ctx.body = { code: 1, message: '书籍不存在' };
  1871. return;
  1872. }
  1873. // 获取章节树
  1874. const chapters = await bookStore.getChapterTree(bookId);
  1875. // 动态获取叶节点层级(最大level值)
  1876. const maxLevel = chapters.length > 0
  1877. ? Math.max(...chapters.map((c: any) => c.level || 0))
  1878. : 0;
  1879. if (maxLevel === 0) {
  1880. ctx.body = { code: 1, message: '没有章节' };
  1881. return;
  1882. }
  1883. // 获取叶节点(最大level的所有节点)
  1884. const leafNodes = chapters.filter((c: any) => c.level === maxLevel);
  1885. // 过滤出有音频的叶节点
  1886. const leafNodesWithAudio = leafNodes.filter((c: any) => c.audioUrl && c.audioUrl !== '');
  1887. const leafTypeName = maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节';
  1888. if (leafNodes.length === 0) {
  1889. ctx.body = { code: 1, message: `没有${leafTypeName}` };
  1890. return;
  1891. }
  1892. if (leafNodesWithAudio.length === 0) {
  1893. ctx.body = {
  1894. code: 1,
  1895. message: `没有音频生成完成的${leafTypeName},请先生成音频`,
  1896. data: {
  1897. totalSubsections: leafNodes.length,
  1898. audioCompletedSubsections: 0,
  1899. }
  1900. };
  1901. return;
  1902. }
  1903. console.log(`[Video] 书籍 ${bookId} 共有 ${leafNodes.length} 个${leafTypeName},其中 ${leafNodesWithAudio.length} 个音频已生成完成`);
  1904. // 异步生成所有叶节点视频
  1905. const taskId = `video_${bookId}_${Date.now()}`;
  1906. console.log(`[Video] 开始批量生成视频: bookId=${bookId}, taskId=${taskId}, 总数=${leafNodesWithAudio.length}`);
  1907. for (const sub of leafNodesWithAudio) {
  1908. // 设置视频状态为生成中
  1909. await advanceChapter(sub.id, 'video_generating').catch(() => {});
  1910. // 异步处理每个章节的视频生成
  1911. (async () => {
  1912. try {
  1913. console.log(`[Video] 开始生成章节 ${sub.number} 的视频: ${sub.title}`);
  1914. // 从书籍章节创建视频项目
  1915. const project = await createVideoProjectFromBook(
  1916. parseInt(bookId),
  1917. sub.id,
  1918. book.userId || 1
  1919. );
  1920. if (!project) {
  1921. console.error(`[Video] 章节 ${sub.number} 视频项目创建失败`);
  1922. await regenerateChapter(sub.id, 'failed').catch(() => {});
  1923. return;
  1924. }
  1925. console.log(`[Video] 章节 ${sub.number} 视频项目创建成功: projectId=${project.id}`);
  1926. // 生成视频
  1927. const result = await generateVideoForProject(project.id);
  1928. if (result.success && result.outputUrl) {
  1929. await bookStore.updateChapterById(sub.id, {
  1930. videoUrl: result.outputUrl,
  1931. videoDuration: result.duration,
  1932. });
  1933. await advanceChapter(sub.id, 'video_completed');
  1934. } else {
  1935. await regenerateChapter(sub.id, 'failed');
  1936. }
  1937. } catch (error) {
  1938. console.error(`[Video] 章节 ${sub.number} 视频生成异常:`, error);
  1939. await regenerateChapter(sub.id, 'failed');
  1940. }
  1941. })();
  1942. }
  1943. ctx.body = {
  1944. code: 0,
  1945. message: '视频生成任务已启动',
  1946. data: {
  1947. taskId,
  1948. totalChapters: leafNodesWithAudio.length,
  1949. totalSubsections: leafNodes.length,
  1950. },
  1951. };
  1952. } catch (error) {
  1953. console.error('批量生成视频失败:', error);
  1954. ctx.status = 500;
  1955. ctx.body = { code: 1, message: error instanceof Error ? error.message : '批量生成视频失败' };
  1956. }
  1957. });
  1958. /**
  1959. * POST /api/book-generator/langgraph/books/:id/merge-audio
  1960. * 合并叶节点音频到上级章节
  1961. */
  1962. router.post('/books/:id/merge-audio', async (ctx: Context) => {
  1963. try {
  1964. const bookId = ctx.params.id as string;
  1965. const book = await bookStore.getById(bookId);
  1966. if (!book) {
  1967. ctx.status = 404;
  1968. ctx.body = { code: 1, message: '书籍不存在' };
  1969. return;
  1970. }
  1971. // 获取章节树
  1972. const chapters = await bookStore.getChapterTree(bookId);
  1973. // 动态获取叶节点层级(最大level值)
  1974. const maxLevel = chapters.length > 0
  1975. ? Math.max(...chapters.map((c: any) => c.level || 0))
  1976. : 0;
  1977. if (maxLevel <= 1) {
  1978. ctx.body = { code: 1, message: '书籍层级不足,无法合并音频' };
  1979. return;
  1980. }
  1981. // 获取叶节点(最大level的所有节点)
  1982. const leafNodes = chapters.filter((c: any) => c.level === maxLevel);
  1983. // 检查所有叶节点是否都有音频
  1984. const leafNodesWithAudio = leafNodes.filter((c: any) => c.audioUrl && c.audioUrl !== '');
  1985. if (leafNodes.length === 0) {
  1986. ctx.body = { code: 1, message: `没有${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'}` };
  1987. return;
  1988. }
  1989. if (leafNodesWithAudio.length !== leafNodes.length) {
  1990. ctx.body = {
  1991. code: 1,
  1992. message: `并非所有${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'}都已完成音频生成,无法合并`,
  1993. data: {
  1994. totalLeafNodes: leafNodes.length,
  1995. completedAudioNodes: leafNodesWithAudio.length,
  1996. }
  1997. };
  1998. return;
  1999. }
  2000. // 构建 sectionId → chapterId 映射(3层树需要,2层树直接 parentId 就是 chapterId)
  2001. const sectionToChapter = new Map<number, number>();
  2002. if (maxLevel >= 3) {
  2003. const sections = chapters.filter((c: any) => c.level === 2);
  2004. for (const sec of sections) {
  2005. if (sec.parentId) {
  2006. sectionToChapter.set(sec.id, sec.parentId);
  2007. }
  2008. }
  2009. }
  2010. // 按章(level=1)分组叶节点
  2011. const groupedByChapter: { [key: number]: any[] } = {};
  2012. const chapterMeta: { [key: number]: any } = {}; // 章的基本信息
  2013. leafNodesWithAudio.forEach(node => {
  2014. // 找到该叶节点所属的1级章ID
  2015. let chapterId: number | null = null;
  2016. if (maxLevel === 2) {
  2017. chapterId = node.parentId; // level=2叶节点的parentId就是章
  2018. } else if (maxLevel === 3 && node.parentId) {
  2019. chapterId = sectionToChapter.get(node.parentId) || null; // 通过节→章映射
  2020. }
  2021. if (chapterId) {
  2022. if (!groupedByChapter[chapterId]) {
  2023. groupedByChapter[chapterId] = [];
  2024. }
  2025. groupedByChapter[chapterId].push(node);
  2026. }
  2027. });
  2028. // 收集各章的元信息
  2029. for (const ch of chapters) {
  2030. if (ch.level === 1) {
  2031. chapterMeta[ch.id] = ch;
  2032. }
  2033. }
  2034. const chapterIds = Object.keys(groupedByChapter);
  2035. // 对每个章下的叶节点音频进行合并
  2036. for (const chapterId of chapterIds) {
  2037. const chId = parseInt(chapterId);
  2038. const childNodes = groupedByChapter[chId];
  2039. const chInfo = chapterMeta[chId];
  2040. if (childNodes.length > 0) {
  2041. try {
  2042. const mergedAudioUrl = await mergeChapterAudios(chId);
  2043. if (mergedAudioUrl) {
  2044. console.log(`[Merge Audio] 章 ${chInfo?.number || chId}(${chInfo?.title || ''}) 音频合并完成: ${mergedAudioUrl}`);
  2045. }
  2046. } catch (error) {
  2047. console.error(`[Merge Audio] 章 ${chInfo?.number || chId}(${chInfo?.title || ''}) 音频合并失败:`, error);
  2048. }
  2049. }
  2050. }
  2051. ctx.body = {
  2052. code: 0,
  2053. message: `音频合并任务已启动,共处理 ${chapterIds.length} 个章`,
  2054. data: {
  2055. processedParents: chapterIds.length,
  2056. totalLeafNodes: leafNodes.length,
  2057. },
  2058. };
  2059. } catch (error) {
  2060. console.error('合并音频失败:', error);
  2061. ctx.status = 500;
  2062. ctx.body = { code: 1, message: error instanceof Error ? error.message : '合并音频失败' };
  2063. }
  2064. });
  2065. /**
  2066. * POST /api/book-generator/langgraph/books/:id/merge-video
  2067. * 合并叶节点视频到上级章节
  2068. */
  2069. router.post('/books/:id/merge-video', async (ctx: Context) => {
  2070. try {
  2071. const bookId = ctx.params.id as string;
  2072. const book = await bookStore.getById(bookId);
  2073. if (!book) {
  2074. ctx.status = 404;
  2075. ctx.body = { code: 1, message: '书籍不存在' };
  2076. return;
  2077. }
  2078. // 获取章节树
  2079. const chapters = await bookStore.getChapterTree(bookId);
  2080. // 动态获取叶节点层级(最大level值)
  2081. const maxLevel = chapters.length > 0
  2082. ? Math.max(...chapters.map((c: any) => c.level || 0))
  2083. : 0;
  2084. if (maxLevel <= 1) {
  2085. ctx.body = { code: 1, message: '书籍层级不足,无法合并视频' };
  2086. return;
  2087. }
  2088. // 获取叶节点(最大level的所有节点)
  2089. const leafNodes = chapters.filter((c: any) => c.level === maxLevel);
  2090. // 检查所有叶节点是否都有视频
  2091. const leafNodesWithVideo = leafNodes.filter((c: any) => c.videoUrl && c.videoUrl !== '');
  2092. if (leafNodes.length === 0) {
  2093. ctx.body = { code: 1, message: `没有${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'}` };
  2094. return;
  2095. }
  2096. if (leafNodesWithVideo.length !== leafNodes.length) {
  2097. ctx.body = {
  2098. code: 1,
  2099. message: `并非所有${maxLevel === 3 ? '小节' : maxLevel === 2 ? '节' : '章节'}都已完成视频生成,无法合并`,
  2100. data: {
  2101. totalLeafNodes: leafNodes.length,
  2102. completedVideoNodes: leafNodesWithVideo.length,
  2103. }
  2104. };
  2105. return;
  2106. }
  2107. // 按父节点分组叶节点(通常是1级章节)
  2108. const groupedByParent: { [key: number]: any[] } = {};
  2109. leafNodesWithVideo.forEach(node => {
  2110. if (node.parentId) {
  2111. if (!groupedByParent[node.parentId]) {
  2112. groupedByParent[node.parentId] = [];
  2113. }
  2114. groupedByParent[node.parentId].push(node);
  2115. }
  2116. });
  2117. // 对每个父节点下的叶节点视频进行合并
  2118. let totalProcessedParents = 0;
  2119. for (const parentId in groupedByParent) {
  2120. const childNodes = groupedByParent[parentId];
  2121. if (childNodes.length > 0) {
  2122. // 获取父章节信息
  2123. const parentChapter = chapters.find((c: any) => c.id === parseInt(parentId));
  2124. if (parentChapter) {
  2125. try {
  2126. // 调用合并函数
  2127. const mergedVideoUrl = await mergeChapterVideos(
  2128. parentChapter,
  2129. childNodes,
  2130. book.userId || 1
  2131. );
  2132. if (mergedVideoUrl) {
  2133. // 更新父章节的视频URL
  2134. await bookStore.updateChapterById(parentChapter.id, {
  2135. videoUrl: mergedVideoUrl,
  2136. });
  2137. console.log(`[Merge Video] 章节 ${parentChapter.number}(${parentChapter.title}) 视频合并完成: ${mergedVideoUrl}`);
  2138. totalProcessedParents++;
  2139. }
  2140. } catch (error) {
  2141. console.error(`[Merge Video] 章节 ${parentChapter.number}(${parentChapter.title}) 视频合并失败:`, error);
  2142. // 不抛出异常,继续处理其他章节
  2143. }
  2144. }
  2145. }
  2146. }
  2147. ctx.body = {
  2148. code: 0,
  2149. message: `视频合并任务已完成,共处理 ${totalProcessedParents} 个上级章节`,
  2150. data: {
  2151. processedParents: totalProcessedParents,
  2152. totalLeafNodes: leafNodes.length,
  2153. },
  2154. };
  2155. } catch (error) {
  2156. console.error('合并视频失败:', error);
  2157. ctx.status = 500;
  2158. ctx.body = { code: 1, message: error instanceof Error ? error.message : '合并视频失败' };
  2159. }
  2160. });
  2161. /**
  2162. * 合并章节视频的辅助函数
  2163. */
  2164. async function mergeChapterVideos(parentChapter: any, childChapters: any[], userId: number) {
  2165. try {
  2166. // 获取项目根目录(假设视频文件存储在特定目录下)
  2167. const videoDir = path.join(__dirname, '../../../../../../uploads/video');
  2168. const outputDir = path.join(videoDir, 'merged');
  2169. // 确保输出目录存在
  2170. await fs.mkdir(outputDir, { recursive: true });
  2171. // 创建合并文件列表
  2172. const fileListPath = path.join(videoDir, `merge_list_${parentChapter.id}.txt`);
  2173. const outputPath = path.join(outputDir, `merged_chapter_${parentChapter.id}_${Date.now()}.mp4`);
  2174. // 准备要合并的视频文件路径
  2175. const videoPaths = [];
  2176. for (const child of childChapters) {
  2177. if (child.videoUrl) {
  2178. // 从URL提取文件名
  2179. const fileName = path.basename(child.videoUrl);
  2180. const fullPath = path.join(videoDir, fileName);
  2181. // 检查文件是否存在
  2182. try {
  2183. await fs.access(fullPath);
  2184. videoPaths.push(fullPath);
  2185. } catch (err) {
  2186. console.error(`[Merge Video] 文件不存在: ${fullPath}`, err);
  2187. continue; // 跳过不存在的文件
  2188. }
  2189. }
  2190. }
  2191. if (videoPaths.length === 0) {
  2192. throw new Error('没有找到有效的视频文件');
  2193. }
  2194. if (videoPaths.length === 1) {
  2195. // 如果只有一个视频,检查格式是否一致
  2196. const srcExt = videoPaths[0].split('.').pop()?.toLowerCase();
  2197. const dstExt = outputPath.split('.').pop()?.toLowerCase();
  2198. if (srcExt !== dstExt) {
  2199. // 格式不同,用 FFmpeg 转码
  2200. const cmd = `ffmpeg -i "${videoPaths[0]}" -c copy -y "${outputPath}"`;
  2201. console.log(`[Merge Video] 格式不同,转码: ${cmd}`);
  2202. await execPromise(cmd);
  2203. } else {
  2204. await fs.copyFile(videoPaths[0], outputPath);
  2205. }
  2206. const relativePath = outputPath.replace(videoDir, '/uploads/video').replace(/\\/g, '/');
  2207. return relativePath;
  2208. }
  2209. // 创建FFmpeg输入列表 - 使用concat协议来合并视频
  2210. const inputLines = videoPaths.map(videoPath => `file '${videoPath}'`).join('\n');
  2211. await fs.writeFile(fileListPath, inputLines);
  2212. // 使用FFmpeg合并视频 - 更安全的方式,避免编码问题
  2213. // 先尝试简单的copy方式
  2214. const cmd = `ffmpeg -f concat -safe 0 -i "${fileListPath}" -c copy -avoid_negative_ts make_zero "${outputPath}"`;
  2215. console.log(`[Merge Video] 执行命令: ${cmd}`);
  2216. let result;
  2217. try {
  2218. result = await execPromise(cmd);
  2219. console.log(`[Merge Video] FFmpeg stdout:`, result.stdout);
  2220. console.log(`[Merge Video] FFmpeg stderr:`, result.stderr);
  2221. } catch (execErr: any) {
  2222. console.warn(`[Merge Video] copy模式失败,尝试重新编码:`, execErr.message);
  2223. // 如果简单copy失败,尝试重新编码
  2224. const reencodeCmd = `ffmpeg -f concat -safe 0 -i "${fileListPath}" -c:v libx264 -c:a aac -avoid_negative_ts make_zero "${outputPath}"`;
  2225. console.log(`[Merge Video] 执行重新编码命令: ${reencodeCmd}`);
  2226. result = await execPromise(reencodeCmd);
  2227. console.log(`[Merge Video] FFmpeg reencode stdout:`, result.stdout);
  2228. console.log(`[Merge Video] FFmpeg reencode stderr:`, result.stderr);
  2229. }
  2230. // 清理临时文件
  2231. await fs.unlink(fileListPath).catch(() => {});
  2232. // 检查输出文件是否成功创建
  2233. try {
  2234. await fs.access(outputPath);
  2235. } catch (err) {
  2236. throw new Error('视频合并后文件未生成');
  2237. }
  2238. // 返回相对路径(相对于上传目录)
  2239. const relativePath = outputPath.replace(videoDir, '/uploads/video').replace(/\\/g, '/');
  2240. return relativePath;
  2241. } catch (error) {
  2242. console.error('[Merge Video] 合并过程中出错:', error);
  2243. throw error;
  2244. }
  2245. }
  2246. /**
  2247. * DEBUG: 手动触发章节音频生成(强制从content_completed重新开始)
  2248. * POST /api/book-generator/debug/trigger-audio
  2249. */
  2250. router.post('/debug/trigger-audio', async (ctx: Context) => {
  2251. try {
  2252. const { chapterId } = ctx.request.body as { chapterId?: number };
  2253. if (!chapterId) {
  2254. ctx.status = 400;
  2255. ctx.body = { code: 1, message: '缺少 chapterId' };
  2256. return;
  2257. }
  2258. // 先检查chapter状态,如果是audio_generating但没有audioUrl,说明之前的生成卡住了
  2259. const chapter = await prisma.bookChapter.findUnique({ where: { id: chapterId } });
  2260. if (chapter?.genStage === 'audio_generating' && !chapter?.audioUrl) {
  2261. console.log(`[DEBUG] 章节${chapterId}卡在audio_generating无audioUrl,重置到content_completed重新生成`);
  2262. await prisma.bookChapter.update({ where: { id: chapterId }, data: { genStage: 'content_completed' } });
  2263. }
  2264. console.log(`[DEBUG] 手动触发章节${chapterId}音频生成`);
  2265. await bookStore.generateChapterAudioById(chapterId);
  2266. const updated = await prisma.bookChapter.findUnique({ where: { id: chapterId } });
  2267. ctx.body = {
  2268. code: 0,
  2269. message: '音频生成已触发',
  2270. data: { chapterId, genStage: updated?.genStage, audioUrl: updated?.audioUrl },
  2271. };
  2272. } catch (error) {
  2273. console.error('[DEBUG] 触发音频失败:', error);
  2274. ctx.status = 500;
  2275. ctx.body = { code: 1, message: error instanceof Error ? error.message : '触发失败' };
  2276. }
  2277. });
  2278. // ============ 交互式生成 API ============
  2279. /**
  2280. * POST /api/book-generator/langgraph/books/:id/interactive/plan
  2281. * 异步启动深度规划,前端通过 GET 同名接口轮询结果
  2282. */
  2283. router.post('/books/:id/interactive/plan', optionalAuth, async (ctx: Context) => {
  2284. try {
  2285. const bookId = ctx.params.id;
  2286. const idNum = parseInt(bookId);
  2287. const book = await prisma.book.findUnique({ where: { id: idNum } });
  2288. if (!book) {
  2289. ctx.status = 404;
  2290. ctx.body = { code: 1, message: '书籍不存在' };
  2291. return;
  2292. }
  2293. // 标记为生成中,立即返回
  2294. await prisma.book.update({
  2295. where: { id: idNum },
  2296. data: { genStage: 'plan_generating' },
  2297. });
  2298. // 构造 minimal state
  2299. const body = (ctx.request as any).body || {};
  2300. const userFeedback = body.feedback || '';
  2301. const initState: any = {
  2302. bookId,
  2303. topic: book.description,
  2304. bookScale: book.bookScale || '1000',
  2305. genLevel: (book as any).genLevel || 2,
  2306. description: book.description,
  2307. title: book.title,
  2308. userId: book.userId,
  2309. completedChapters: [],
  2310. failedChapters: [],
  2311. userFeedback,
  2312. };
  2313. console.log(`[Interactive] 深度规划已启动(异步): bookId=${bookId}${userFeedback ? ', 含用户反馈' : ''}`);
  2314. // 异步执行 AI 调用,不阻塞响应
  2315. setImmediate(async () => {
  2316. try {
  2317. const result = await deepPlanBookNode(initState);
  2318. const bookPlan = result.bookPlan || '';
  2319. await prisma.book.update({
  2320. where: { id: idNum },
  2321. data: { bookAnalysis: bookPlan, genStage: 'plan_ready' },
  2322. });
  2323. console.log(`[Interactive] 深度规划完成: bookId=${bookId}`);
  2324. } catch (err) {
  2325. console.error(`[Interactive] 深度规划失败: bookId=${bookId}`, err);
  2326. await prisma.book.update({
  2327. where: { id: idNum },
  2328. data: { genStage: 'plan_failed', errorMsg: err instanceof Error ? err.message : '规划失败' },
  2329. });
  2330. }
  2331. });
  2332. ctx.body = {
  2333. code: 0,
  2334. message: '规划已启动',
  2335. data: { genStage: 'plan_generating' },
  2336. };
  2337. } catch (error) {
  2338. console.error('[Interactive] plan 启动失败:', error);
  2339. ctx.status = 500;
  2340. ctx.body = { code: 1, message: error instanceof Error ? error.message : '启动失败' };
  2341. }
  2342. });
  2343. /**
  2344. * GET /api/book-generator/langgraph/books/:id/interactive/plan
  2345. * 轮询获取深度规划结果
  2346. */
  2347. router.get('/books/:id/interactive/plan', optionalAuth, async (ctx: Context) => {
  2348. try {
  2349. const bookId = ctx.params.id;
  2350. const book = await prisma.book.findUnique({ where: { id: parseInt(bookId) } });
  2351. if (!book) {
  2352. ctx.status = 404;
  2353. ctx.body = { code: 1, message: '书籍不存在' };
  2354. return;
  2355. }
  2356. const stage = (book as any).genStage || '';
  2357. if (stage === 'plan_failed') {
  2358. ctx.body = { code: 0, data: { genStage: 'plan_failed', error: (book as any).errorMsg || '规划失败' } };
  2359. return;
  2360. }
  2361. if (stage === 'plan_ready' || book.bookAnalysis) {
  2362. const bookPlan = book.bookAnalysis || '';
  2363. let planData: any = null;
  2364. try {
  2365. const fixed_json = bookPlan.replace(/\\u000a/g, '\\n').replace(/\\\\/g, '\\');
  2366. const match = fixed_json.match(/\{[\s\S]*\}/);
  2367. if (match) planData = JSON.parse(match[0]);
  2368. } catch (e) { /* ignore */ }
  2369. ctx.body = {
  2370. code: 0,
  2371. message: '规划完成',
  2372. data: { rawPlan: bookPlan, planData, genStage: 'plan_ready' },
  2373. };
  2374. return;
  2375. }
  2376. // 还在生成中
  2377. ctx.body = {
  2378. code: 0,
  2379. data: { genStage: stage || 'plan_generating' },
  2380. };
  2381. } catch (error) {
  2382. console.error('[Interactive] 查询 plan 失败:', error);
  2383. ctx.status = 500;
  2384. ctx.body = { code: 1, message: '查询失败' };
  2385. }
  2386. });
  2387. /**
  2388. * PUT /api/book-generator/langgraph/books/:id/interactive/plan
  2389. * 保存用户修改后的 plan
  2390. */
  2391. router.put('/books/:id/interactive/plan', optionalAuth, async (ctx: Context) => {
  2392. try {
  2393. const bookId = ctx.params.id;
  2394. const { plan } = ctx.request.body as { plan: string };
  2395. if (!plan) {
  2396. ctx.status = 400;
  2397. ctx.body = { code: 1, message: 'plan 不能为空' };
  2398. return;
  2399. }
  2400. await prisma.book.update({
  2401. where: { id: parseInt(bookId) },
  2402. data: { bookAnalysis: plan },
  2403. });
  2404. ctx.body = { code: 0, message: 'Plan 已保存' };
  2405. } catch (error) {
  2406. console.error('[Interactive] 保存 plan 失败:', error);
  2407. ctx.status = 500;
  2408. ctx.body = { code: 1, message: error instanceof Error ? error.message : '保存失败' };
  2409. }
  2410. });
  2411. /**
  2412. * POST /api/book-generator/langgraph/books/:id/interactive/outline
  2413. * 异步启动大纲生成,前端通过 GET 同名接口轮询结果
  2414. */
  2415. router.post('/books/:id/interactive/outline', optionalAuth, async (ctx: Context) => {
  2416. try {
  2417. const bookId = ctx.params.id;
  2418. const idNum = parseInt(bookId);
  2419. const book = await prisma.book.findUnique({ where: { id: idNum } });
  2420. if (!book) {
  2421. ctx.status = 404;
  2422. ctx.body = { code: 1, message: '书籍不存在' };
  2423. return;
  2424. }
  2425. // 标记为生成中,立即返回
  2426. await prisma.book.update({
  2427. where: { id: idNum },
  2428. data: { genStage: 'outline_generating' },
  2429. });
  2430. // 构造 state,使用已保存的 plan
  2431. const initState: any = {
  2432. bookId,
  2433. topic: book.description,
  2434. bookScale: book.bookScale || '1000',
  2435. genLevel: (book as any).genLevel || 2,
  2436. description: book.description,
  2437. title: book.title,
  2438. userId: book.userId,
  2439. bookPlan: book.bookAnalysis || '',
  2440. completedChapters: [],
  2441. failedChapters: [],
  2442. };
  2443. console.log(`[Interactive] 大纲生成已启动(异步): bookId=${bookId}`);
  2444. // 异步执行 AI 调用
  2445. setImmediate(async () => {
  2446. try {
  2447. await richOutlineNode(initState);
  2448. // richOutlineNode 内部已通过 bookStore.update 写入 outlineJson
  2449. await prisma.book.update({
  2450. where: { id: idNum },
  2451. data: { genStage: 'outline_ready' },
  2452. });
  2453. console.log(`[Interactive] 大纲生成完成: bookId=${bookId}`);
  2454. } catch (err) {
  2455. console.error(`[Interactive] 大纲生成失败: bookId=${bookId}`, err);
  2456. await prisma.book.update({
  2457. where: { id: idNum },
  2458. data: { genStage: 'outline_failed', errorMsg: err instanceof Error ? err.message : '大纲生成失败' },
  2459. });
  2460. }
  2461. });
  2462. ctx.body = {
  2463. code: 0,
  2464. message: '大纲生成已启动',
  2465. data: { genStage: 'outline_generating' },
  2466. };
  2467. } catch (error) {
  2468. console.error('[Interactive] outline 启动失败:', error);
  2469. ctx.status = 500;
  2470. ctx.body = { code: 1, message: error instanceof Error ? error.message : '启动失败' };
  2471. }
  2472. });
  2473. /**
  2474. * GET /api/book-generator/langgraph/books/:id/interactive/outline
  2475. * 轮询获取大纲生成结果
  2476. */
  2477. router.get('/books/:id/interactive/outline', optionalAuth, async (ctx: Context) => {
  2478. try {
  2479. const bookId = ctx.params.id;
  2480. const book = await prisma.book.findUnique({ where: { id: parseInt(bookId) } });
  2481. if (!book) {
  2482. ctx.status = 404;
  2483. ctx.body = { code: 1, message: '书籍不存在' };
  2484. return;
  2485. }
  2486. const stage = (book as any).genStage || '';
  2487. if (stage === 'outline_failed') {
  2488. ctx.body = { code: 0, data: { genStage: 'outline_failed', error: (book as any).errorMsg || '大纲生成失败' } };
  2489. return;
  2490. }
  2491. if (stage === 'outline_ready' || book.outlineJson) {
  2492. const outlineJson = book.outlineJson || '';
  2493. let outlineData: any = null;
  2494. try {
  2495. outlineData = typeof outlineJson === 'string' ? JSON.parse(outlineJson) : outlineJson;
  2496. } catch (e) { /* ignore */ }
  2497. ctx.body = {
  2498. code: 0,
  2499. message: '大纲生成完成',
  2500. data: { rawOutline: outlineJson, outlineData, genStage: 'outline_ready' },
  2501. };
  2502. return;
  2503. }
  2504. // 还在生成中
  2505. ctx.body = {
  2506. code: 0,
  2507. data: { genStage: stage || 'outline_generating' },
  2508. };
  2509. } catch (error) {
  2510. console.error('[Interactive] 查询 outline 失败:', error);
  2511. ctx.status = 500;
  2512. ctx.body = { code: 1, message: '查询失败' };
  2513. }
  2514. });
  2515. /**
  2516. * PUT /api/book-generator/langgraph/books/:id/interactive/outline
  2517. * 保存用户修改后的大纲,并重建章节树
  2518. */
  2519. router.put('/books/:id/interactive/outline', optionalAuth, async (ctx: Context) => {
  2520. try {
  2521. const bookId = ctx.params.id;
  2522. const { outline } = ctx.request.body as { outline: any };
  2523. if (!outline) {
  2524. ctx.status = 400;
  2525. ctx.body = { code: 1, message: 'outline 不能为空' };
  2526. return;
  2527. }
  2528. const outlineStr = typeof outline === 'string' ? outline : JSON.stringify(outline);
  2529. await prisma.book.update({
  2530. where: { id: parseInt(bookId) },
  2531. data: { outlineJson: outlineStr },
  2532. });
  2533. // 根据大纲重建章节树(删除旧章节,创建新章节)
  2534. const chapterData = typeof outline === 'string' ? JSON.parse(outline) : outline;
  2535. const chapters = chapterData.chapters || [];
  2536. // 删除旧章节
  2537. await prisma.bookChapter.deleteMany({ where: { bookId: parseInt(bookId) } });
  2538. // 插入新章节(递归处理章→节→小节)
  2539. let chapterNumber = 0;
  2540. async function insertChapters(parentId: number | null, items: any[], level: number) {
  2541. for (const item of items) {
  2542. chapterNumber++;
  2543. const section = await prisma.bookChapter.create({
  2544. data: {
  2545. bookId: parseInt(bookId),
  2546. title: item.title || '未命名章节',
  2547. summary: item.summary || '',
  2548. content: '',
  2549. wordCount: item.estimatedWords || 0,
  2550. number: chapterNumber,
  2551. level,
  2552. parentId,
  2553. genStage: 'draft',
  2554. },
  2555. });
  2556. // 递归处理子节点(节、小节)
  2557. if (item.sections && item.sections.length > 0) {
  2558. await insertChapters(section.id, item.sections, level + 1);
  2559. }
  2560. if (item.subsections && item.subsections.length > 0) {
  2561. await insertChapters(section.id, item.subsections, level + 1);
  2562. }
  2563. }
  2564. }
  2565. await insertChapters(null, chapters, 1);
  2566. // 更新书籍的章节计数
  2567. await prisma.book.update({
  2568. where: { id: parseInt(bookId) },
  2569. data: { totalChapters: chapterNumber },
  2570. });
  2571. ctx.body = {
  2572. code: 0,
  2573. message: '大纲已保存,章节树已重建',
  2574. data: { chapterCount: chapterNumber },
  2575. };
  2576. } catch (error) {
  2577. console.error('[Interactive] 保存 outline 失败:', error);
  2578. ctx.status = 500;
  2579. ctx.body = { code: 1, message: error instanceof Error ? error.message : '保存失败' };
  2580. }
  2581. });
  2582. /**
  2583. * POST /api/book-generator/langgraph/books/:id/interactive/generate
  2584. * 运行并行内容生成 + 连贯性编辑
  2585. */
  2586. router.post('/books/:id/interactive/generate', optionalAuth, async (ctx: Context) => {
  2587. try {
  2588. const bookId = ctx.params.id;
  2589. const book = await prisma.book.findUnique({ where: { id: parseInt(bookId) } });
  2590. if (!book) {
  2591. ctx.status = 404;
  2592. ctx.body = { code: 1, message: '书籍不存在' };
  2593. return;
  2594. }
  2595. const userId = book.userId || parseInt(TEST_USER_ID);
  2596. // 配额检查
  2597. const scaleConfig = getScaleConfig(book.bookScale || '1000');
  2598. const totalWords = scaleConfig.totalWords;
  2599. const audioQuota = await checkAudioQuota(userId, totalWords);
  2600. if (!audioQuota.allowed) {
  2601. ctx.status = 403;
  2602. ctx.body = { code: 1, message: audioQuota.reason };
  2603. return;
  2604. }
  2605. // 构造 minimal state
  2606. const initState: any = {
  2607. bookId,
  2608. topic: book.description,
  2609. bookScale: book.bookScale || '1000',
  2610. genLevel: (book as any).genLevel || 2,
  2611. description: book.description,
  2612. title: book.title,
  2613. userId,
  2614. bookPlan: book.bookAnalysis || '',
  2615. outline: book.outlineJson || '',
  2616. completedChapters: [],
  2617. failedChapters: [],
  2618. };
  2619. console.log(`[Interactive] 开始并行生成内容: bookId=${bookId}`);
  2620. // ===== 直接异步生成(跳过队列) =====
  2621. const { langGraphGenerator } = await import('./index.js');
  2622. langGraphGenerator.generate(
  2623. bookId,
  2624. book.description,
  2625. book.bookScale || '1000',
  2626. (book as any).genLevel || 2
  2627. ).then(() => {
  2628. console.log(`[Interactive] 生成完成: bookId=${bookId}`);
  2629. }).catch(err => {
  2630. console.error(`[Interactive] 生成失败: bookId=${bookId}`, err);
  2631. });
  2632. await prisma.book.update({
  2633. where: { id: parseInt(bookId) },
  2634. data: { genStage: 'generating_content' },
  2635. });
  2636. ctx.body = {
  2637. code: 0,
  2638. message: '内容生成已启动',
  2639. data: { bookId, genStage: 'generating_content', mode: 'direct' },
  2640. };
  2641. return;
  2642. try {
  2643. await prisma.book.update({
  2644. where: { id: parseInt(bookId) },
  2645. data: { genStage: 'generating_content' },
  2646. });
  2647. // Step 1: 并行生成内容
  2648. const contentResult = await writeChaptersParallelNode(initState);
  2649. console.log(`[Interactive] 并行内容生成完成: bookId=${bookId}`);
  2650. // Step 2: 连贯性编辑
  2651. const mergeState = { ...initState, ...contentResult };
  2652. await continuityEditNode(mergeState);
  2653. console.log(`[Interactive] 连贯性编辑完成: bookId=${bookId}`);
  2654. ctx.body = {
  2655. code: 0,
  2656. message: '内容生成完成',
  2657. data: { bookId, genStage: 'completed', mode: 'sync' },
  2658. };
  2659. } catch (generateError) {
  2660. console.error(`[Interactive] 内容生成失败: bookId=${bookId}`, generateError);
  2661. await prisma.book.update({
  2662. where: { id: parseInt(bookId) },
  2663. data: { genStage: 'failed', errorMsg: generateError instanceof Error ? generateError.message : '生成失败' },
  2664. });
  2665. ctx.status = 500;
  2666. ctx.body = { code: 1, message: generateError instanceof Error ? generateError.message : '生成失败' };
  2667. }
  2668. } catch (error) {
  2669. console.error('[Interactive] generate 失败:', error);
  2670. ctx.status = 500;
  2671. ctx.body = { code: 1, message: error instanceof Error ? error.message : '生成失败' };
  2672. }
  2673. });
  2674. export default router;