langgraph-controller.ts 96 KB

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