langgraph-controller.ts 105 KB

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