langgraph-controller.ts 98 KB

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