BookController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. <?php
  2. namespace App\Http\Controllers\Library;
  3. use App\Http\Api\ChannelApi;
  4. use App\Http\Api\StudioApi;
  5. use App\Http\Controllers\Controller;
  6. use App\Models\PaliText;
  7. use App\Models\ProgressChapter;
  8. use App\Models\Sentence;
  9. use App\Services\ChapterService;
  10. use App\Services\PaliContentService;
  11. use App\Services\PaliTextService;
  12. use Illuminate\Http\Request;
  13. use Illuminate\Support\Facades\Log;
  14. class BookController extends Controller
  15. {
  16. /**
  17. * chapter 聚合显示的字符数阈值。
  18. *
  19. * ES 中每个 chapter 节点只保存「本节点 → 下一节点」之间的正文,选中含子
  20. * chapter 的父节点时其自身文档往往只有标题。显示时按本阈值决定聚合粒度:
  21. * chapter_strlen 小于该值的节点,连同其覆盖区间内的所有子 chapter 一并展示;
  22. * 超过该值则向下钻取第一个不超过阈值的子 chapter。
  23. */
  24. protected $maxChapterStrlen = 30000;
  25. protected $minChapterLen = 100;
  26. /**
  27. * 构造函数,注入文本与段落内容服务
  28. */
  29. public function __construct(
  30. protected PaliTextService $paliTextService,
  31. protected PaliContentService $paliContentService
  32. ) {}
  33. public function show(string $id)
  34. {
  35. $bookRaw = $this->loadBook($id);
  36. if (! $bookRaw) {
  37. abort(404);
  38. }
  39. // 查询章节
  40. $channelId = $bookRaw->channel_id; // 替换为具体的 channel_id 值
  41. $book = $this->getBookInfo($bookRaw);
  42. $book['contents'] = $this->getBookToc($bookRaw->book, $bookRaw->para, $channelId);
  43. $book['book_title'] = $this->getBookTitle($bookRaw->book, $bookRaw->para, $channelId);
  44. // 获取其他版本
  45. $others = ProgressChapter::with('channel.owner')
  46. ->where('book', $bookRaw->book)
  47. ->where('para', $bookRaw->para)
  48. ->whereHas('channel', function ($query) {
  49. $query->where('status', 30);
  50. })
  51. ->where('progress', '>', 0.2)
  52. ->get();
  53. $otherVersions = [];
  54. $others->each(function ($book) use (&$otherVersions) {
  55. $otherVersions[] = $this->getBookInfo($book);
  56. });
  57. return view('library.tipitaka.show', compact('book', 'otherVersions'));
  58. }
  59. private function fetchCommentary(int $book, int $paraStart, int $paraEnd, string $channelId)
  60. {
  61. $notes = Sentence::where('book_id', $book)
  62. ->whereBetween('paragraph', [$paraStart, $paraEnd])
  63. ->where('channel_uid', $channelId)
  64. ->select(['uid', 'book_id', 'paragraph', 'word_start', 'word_end'])->get()->toArray();
  65. return $notes;
  66. }
  67. private function injectNoteMarkers(string $html, array $notesMap): string
  68. {
  69. if (empty($notesMap)) {
  70. return $html;
  71. }
  72. return preg_replace_callback(
  73. '/(<div class=\'sentence\' data-sid=\'([^\']+)\')/',
  74. function ($matches) use ($notesMap) {
  75. $sid = $matches[2];
  76. if (! isset($notesMap[$sid])) {
  77. return $matches[0];
  78. }
  79. $uid = $notesMap[$sid];
  80. return $matches[1]." data-note-id='{$uid}'";
  81. },
  82. $html
  83. );
  84. }
  85. public function read(Request $request, string $id)
  86. {
  87. $channelId = $request->input('channel');
  88. [$bookId, $paraId] = explode('-', $id);
  89. $bookId = (int) $bookId;
  90. $paraId = (int) $paraId;
  91. // 解析选中 chapter 的实际显示区间(起始/终止段落号),再按段落号聚合 HTML,
  92. // 避免选中父 chapter 时仅显示一个标题。
  93. $range = $this->resolveDisplayRange($bookId, $paraId);
  94. $chapter = $this->fetchRangeContent($bookId, $channelId, $range['start'], $range['end'], $paraId);
  95. if ($request->has('comm')) {
  96. // 注释范围与显示区间保持一致(聚合后可能跨多个段落)
  97. $commentaries = $this->fetchCommentary($bookId, $range['start'], $range['end'], $request->input('comm'));
  98. // sid 格式:{book_id}-{paragraph}-{word_start}-{word_end}
  99. $notesMap = collect($commentaries)->keyBy(function ($note) {
  100. return "{$note['book_id']}-{$note['paragraph']}-{$note['word_start']}-{$note['word_end']}";
  101. })->map(fn ($note) => $note['uid'])->toArray();
  102. }
  103. $chapterService = app(ChapterService::class);
  104. $book = [];
  105. $book['toc'] = $this->getBookToc($bookId, $paraId, $channelId, 2, 7, [$range['start'], $range['end']]);
  106. $channel = ChannelApi::getById($channelId);
  107. $studio = StudioApi::getById($channel['studio_id']);
  108. $book['categories'] = $chapter['category'];
  109. $book['title'] = $chapter['title'];
  110. $book['author'] = $channel['name'];
  111. $book['studio'] = $studio;
  112. $book['tags'] = [];
  113. $book['book_title'] = $this->getBookTitle($bookId, $paraId, $channelId);
  114. $book['pagination'] = $this->pagination($bookId, $paraId, $channelId);
  115. if (isset($notesMap)) {
  116. $book['content'] = $this->injectNoteMarkers($chapter['display'], $notesMap);
  117. } else {
  118. $book['content'] = $chapter['display'];
  119. }
  120. $allChannels = $chapterService->publicChannels((int) $bookId, (int) $paraId);
  121. $commentaryChannels = array_filter($allChannels, function ($channel) {
  122. return $channel['type'] === 'commentary';
  123. });
  124. $channels = array_filter($allChannels, function ($channel) {
  125. return $channel['type'] !== 'commentary';
  126. });
  127. $editor_link = config('mint.server.dashboard_base_path')
  128. ."/workspace/tipitaka/chapter/{$id}?channel={$channelId}";
  129. $view = view('library.book.read', compact('book', 'channels', 'editor_link', 'commentaryChannels'));
  130. return $view;
  131. }
  132. /**
  133. * 解析选中 chapter 的实际显示区间,返回区间的起始与终止段落号。
  134. *
  135. * ES 中每个 chapter 节点仅保存「本节点 → 下一节点」之间的正文,因此选中含
  136. * 子 chapter 的父节点时其自身文档往往只有标题。为完整呈现内容,这里按阈值
  137. * 决定显示区间终点:
  138. * - 选中节点 chapter_strlen 不超过阈值:终点为
  139. * [paragraph + chapter_len - 1];
  140. * - 否则向后下钻,找到第一个不超过阈值的子 chapter,以该子 chapter 的结束
  141. * 段落作为区间终点(起点仍为选中段落,保留上层标题作为阅读上下文)。
  142. *
  143. * @return array{start: int, end: int}
  144. */
  145. private function resolveDisplayRange(int $book, int $para): array
  146. {
  147. $currBook = $this->bookStart($book, $para);
  148. $bookStart = $currBook->paragraph;
  149. $bookEnd = $currBook->paragraph + $currBook->chapter_len - 1;
  150. // 本书内全部 chapter 节点(level < 8,即 book/chapter/subhead 等可导航节点)
  151. $paragraphs = PaliText::where('book', $book)
  152. ->whereBetween('paragraph', [$bookStart, $bookEnd])
  153. ->where('level', '<', 8)
  154. ->orderBy('paragraph')
  155. ->get();
  156. $curr = $paragraphs->firstWhere('paragraph', $para);
  157. $endParagraph = $curr->paragraph + $curr->chapter_len - 1;
  158. if ($curr->chapter_strlen > $this->maxChapterStrlen) {
  159. // 选中节点过大:向后下钻,找到第一个不超过阈值的子 chapter
  160. foreach ($paragraphs as $key => $paragraph) {
  161. if ($paragraph->paragraph <= $curr->paragraph) {
  162. continue;
  163. }
  164. if ($paragraph->chapter_strlen <= $this->maxChapterStrlen) {
  165. $endParagraph = $paragraph->paragraph + $paragraph->chapter_len - 1;
  166. break;
  167. }
  168. if ($paragraph->level <= $curr->level) {
  169. // 已离开选中节点的子树,无法继续下钻,止步于上一个节点
  170. $endParagraph = $paragraphs[$key - 1]->paragraph + $paragraphs[$key - 1]->chapter_len - 1;
  171. break;
  172. }
  173. }
  174. }
  175. return [
  176. 'start' => $curr->paragraph,
  177. 'end' => $endParagraph,
  178. ];
  179. }
  180. /**
  181. * 聚合区间内全部段落的阅读模式 HTML。
  182. *
  183. * 与 TipitakaReadParaController 一致,逐段调用 PaliContentService::readParagraph
  184. * 获取 HTML 并按段落顺序拼接;缺失或获取失败的段落跳过。章节标题优先取
  185. * ProgressChapter.title,回退到 PaliText.toc。
  186. *
  187. * @return array{display: string, title: string, category: array}
  188. */
  189. private function fetchRangeContent(int $book, string $channelId, int $start, int $end, int $selectedPara): array
  190. {
  191. $display = '';
  192. foreach (range($start, $end) as $para) {
  193. $paragraph = $this->paliContentService->readParagraph($book, $para, $channelId, 'html');
  194. if (empty($paragraph['display'])) {
  195. continue;
  196. }
  197. $display .= $paragraph['display'];
  198. }
  199. $title = ProgressChapter::where('book', $book)
  200. ->where('para', $selectedPara)
  201. ->where('channel_id', $channelId)
  202. ->value('title');
  203. if (empty($title)) {
  204. $title = PaliText::where('book', $book)
  205. ->where('paragraph', $selectedPara)
  206. ->value('toc');
  207. }
  208. return [
  209. 'display' => $display,
  210. 'title' => $title ?? '',
  211. 'category' => [],
  212. ];
  213. }
  214. private function loadBook(string $id)
  215. {
  216. $book = ProgressChapter::with('channel.owner')->find($id);
  217. return $book;
  218. }
  219. public function toggleTheme(Request $request)
  220. {
  221. $theme = $request->input('theme', 'light');
  222. session(['theme' => $theme]);
  223. return response()->json(['status' => 'success']);
  224. }
  225. private function getBookInfo($book)
  226. {
  227. $title = $book->title;
  228. if (empty($title)) {
  229. $title = PaliText::where('book', $book->book)
  230. ->where('paragraph', $book->para)->first()->toc;
  231. }
  232. return [
  233. 'id' => $book->uid,
  234. 'title' => $title,
  235. 'author' => $book->channel->name,
  236. 'publisher' => $book->channel->owner,
  237. 'type' => __('label.'.$book->channel->type),
  238. 'category_id' => 11,
  239. 'cover' => '/assets/images/cover/1/214.jpg',
  240. 'description' => $book->summary ?? '',
  241. 'language' => __('language.'.$book->channel->lang),
  242. ];
  243. }
  244. private function getBookTitle(int $book, int $paragraph, string $channelId)
  245. {
  246. $bookTopPara = $this->paliTextService->getBookPara($book, $paragraph)->paragraph;
  247. $title = ProgressChapter::where('book', $book)
  248. ->where('para', $bookTopPara)
  249. ->where('channel_id', $channelId)
  250. ->value('title');
  251. if (empty($title)) {
  252. $title = PaliText::where('book', $book)
  253. ->where('paragraph', $bookTopPara)
  254. ->value('toc');
  255. }
  256. return $title;
  257. }
  258. /**
  259. * @param array{0: int, 1: int}|null $activeRange 实际显示的段落区间 [start, end];
  260. * 传入时区间内的所有 chapter 均高亮(active),
  261. * 用于聚合显示多个 chapter 的场景。不传则仅高亮选中段落。
  262. */
  263. private function getBookToc(int $book, int $paragraph, string $channelId, $minLevel = 2, $maxLevel = 2, ?array $activeRange = null): array
  264. {
  265. $currBook = $this->bookStart($book, $paragraph);
  266. $start = $currBook->paragraph;
  267. $end = $currBook->paragraph + $currBook->chapter_len - 1;
  268. $paliTexts = PaliText::where('book', $book)
  269. ->whereBetween('paragraph', [$start, $end])
  270. ->whereBetween('level', [$minLevel, $maxLevel])
  271. ->orderBy('paragraph')
  272. ->get();
  273. // Log::debug('toc', ['toc' => $paliTexts->toArray()]);
  274. if ($paliTexts->isEmpty()) {
  275. return [];
  276. }
  277. $chapters = ProgressChapter::where('book', $book)
  278. ->whereBetween('para', [$start, $end])
  279. ->where('channel_id', $channelId)
  280. ->orderBy('para')
  281. ->get();
  282. // keyBy 建索引,map 里 O(1) 查找,完全避免 toArray() 序列化和 array_filter O(n×m) 扫描
  283. $chaptersIndexed = $chapters->keyBy('para');
  284. // 当前阅读章节的 toc id,用于高亮(active)与折叠展开(hide)
  285. $currentId = "{$book}-{$paragraph}";
  286. // 折叠逻辑:列表有序,父节点 = 之前最近的更小 level 节点
  287. // 参见 AnthologyReadController::buildCollapsedToc()
  288. $parents = []; // id => parent_id|null
  289. $stack = []; // 祖先栈 [ ['id'=>..., 'level'=>...], ... ]
  290. foreach ($paliTexts as $paliText) {
  291. $id = "{$paliText->book}-{$paliText->paragraph}";
  292. $level = (int) $paliText->level;
  293. while (! empty($stack) && $stack[count($stack) - 1]['level'] >= $level) {
  294. array_pop($stack);
  295. }
  296. $parents[$id] = empty($stack) ? null : $stack[count($stack) - 1]['id'];
  297. $stack[] = ['id' => $id, 'level' => $level];
  298. }
  299. // 高亮(active)集合:聚合显示时为区间内所有 chapter,否则仅选中段落
  300. $activeSet = [];
  301. foreach ($paliTexts as $paliText) {
  302. $id = "{$paliText->book}-{$paliText->paragraph}";
  303. $active = $activeRange !== null
  304. ? ($paliText->paragraph >= $activeRange[0] && $paliText->paragraph <= $activeRange[1])
  305. : ($id === $currentId);
  306. if ($active) {
  307. $activeSet[$id] = true;
  308. }
  309. }
  310. // 需要展开子节点的集合 = 每个 active 节点及其祖先链。
  311. // 聚合显示跨多级时,区间内各级 chapter 都需展开,其子级才能完整显示,
  312. // 否则仅围绕单个当前节点展开,最多只能显示两级。
  313. $expandParentSet = [];
  314. foreach (array_keys($activeSet) as $activeId) {
  315. $expandParentSet[$activeId] = true;
  316. $cursor = $activeId;
  317. while (! empty($parents[$cursor])) {
  318. $cursor = $parents[$cursor];
  319. $expandParentSet[$cursor] = true;
  320. }
  321. }
  322. // 顶层 level(列表中最浅的一层,折叠模式下始终可见)
  323. $topLevel = (int) $paliTexts->min('level');
  324. $output = $paliTexts->map(function ($paliText) use ($chaptersIndexed, $channelId, $parents, $expandParentSet, $activeSet, $topLevel) {
  325. $id = "{$paliText->book}-{$paliText->paragraph}";
  326. $level = (int) $paliText->level;
  327. $title = $paliText->toc;
  328. $summary = '';
  329. $progress = 0;
  330. $disabled = true;
  331. /** @var ProgressChapter|null $chapter */
  332. $chapter = $chaptersIndexed->get($paliText->paragraph);
  333. if ($chapter) {
  334. if (! empty($chapter->title)) {
  335. $title = $chapter->title;
  336. }
  337. if (! empty($chapter->summary)) {
  338. $summary = $chapter->summary;
  339. }
  340. $progress = (int) ($chapter->progress * 100);
  341. $disabled = false;
  342. }
  343. $parentId = $parents[$id];
  344. // 折叠模式可见:顶层节点,或父节点在展开集合中(祖先链 / 当前节点的直接子节点)
  345. $visible = $level === $topLevel
  346. || ($parentId !== null && isset($expandParentSet[$parentId]));
  347. $active = isset($activeSet[$id]);
  348. return [
  349. 'id' => $id,
  350. 'channel' => $channelId,
  351. 'title' => $title,
  352. 'summary' => $summary,
  353. 'progress' => $progress,
  354. 'level' => $level,
  355. 'disabled' => $disabled,
  356. 'active' => $active,
  357. 'hide' => ! $visible,
  358. ];
  359. })->all();
  360. // Log::debug('toc output', ['data' => $output]);
  361. return $output;
  362. }
  363. public function getBookCategory($book, $paragraph)
  364. {
  365. $tags = PaliText::with('tagMaps.tags')
  366. ->where('book', $book)
  367. ->where('paragraph', $paragraph)
  368. ->first()->tagMaps->map(function ($tagMap) {
  369. return $tagMap->tags;
  370. })->toArray();
  371. return $tags;
  372. }
  373. private function bookStart($book, $paragraph)
  374. {
  375. $currBook = PaliText::where('book', $book)
  376. ->where('paragraph', '<=', $paragraph)
  377. ->where('level', 1)
  378. ->orderBy('paragraph', 'desc')
  379. ->first();
  380. return $currBook;
  381. }
  382. public function pagination(int $book, int $para, string $channelId)
  383. {
  384. // 与正文显示共用同一区间解析,保证分页边界与实际展示内容一致
  385. $range = $this->resolveDisplayRange($book, $para);
  386. $start = $range['start'];
  387. $end = $range['end'];
  388. // next/prev 以显示区间为边界,而非某个节点的层级:
  389. // 聚合显示子 chapter 时,下一页应是区间 end 之后的第一个可导航段落,
  390. // 上一页应是区间 start 之前最近的可导航段落。若按 current 的 level 取同级节点,
  391. // 会在章节边界处跳过父级标题页或落入子节点。
  392. $nextPali = $this->nextChapter($book, $end);
  393. $prevPali = $this->prevChapter($book, $start);
  394. $next = null;
  395. if ($nextPali) {
  396. $nextTranslation = ProgressChapter::with('channel.owner')
  397. ->where('book', $nextPali->book)
  398. ->where('para', $nextPali->paragraph)
  399. ->where('channel_id', $channelId)
  400. ->first();
  401. if ($nextTranslation) {
  402. if (! empty($nextTranslation->title)) {
  403. $next['title'] = $nextTranslation->title;
  404. } else {
  405. $next['title'] = $nextPali->toc;
  406. }
  407. $next['id'] = "{$nextPali->book}-{$nextPali->paragraph}";
  408. }
  409. }
  410. $prev = null;
  411. if ($prevPali) {
  412. $prevTranslation = ProgressChapter::with('channel.owner')
  413. ->where('book', $prevPali->book)
  414. ->where('para', $prevPali->paragraph)
  415. ->where('channel_id', $channelId)
  416. ->first();
  417. if ($prevTranslation) {
  418. if (! empty($prevTranslation->title)) {
  419. $prev['title'] = $prevTranslation->title;
  420. } else {
  421. $prev['title'] = $prevPali->toc;
  422. }
  423. $prev['id'] = "{$prevPali->book}-{$prevPali->paragraph}";
  424. }
  425. }
  426. return compact('start', 'end', 'next', 'prev');
  427. }
  428. /**
  429. * 显示区间之后的第一个可导航 chapter 节点(level < 8)。
  430. */
  431. public function nextChapter(int $book, int $endParagraph): ?PaliText
  432. {
  433. return PaliText::where('book', $book)
  434. ->where('paragraph', '>', $endParagraph)
  435. ->where('level', '<', 8)
  436. ->orderBy('paragraph')
  437. ->first();
  438. }
  439. /**
  440. * 显示区间之前最近的一个可导航 chapter 节点(level < 8)。
  441. */
  442. public function prevChapter(int $book, int $startParagraph): ?PaliText
  443. {
  444. return PaliText::where('book', $book)
  445. ->where('paragraph', '<', $startParagraph)
  446. ->where('level', '<', 8)
  447. ->orderBy('paragraph', 'desc')
  448. ->first();
  449. }
  450. public function show2($id)
  451. {
  452. // Sample book data (replace with database query)
  453. $book = [
  454. 'title' => 'Sample Book Title',
  455. 'author' => 'John Doe',
  456. 'category' => 'Fiction',
  457. 'tags' => ['Adventure', 'Mystery', 'Bestseller'],
  458. 'toc' => ['Introduction', 'Chapter 1', 'Chapter 2', 'Conclusion'],
  459. 'content' => [
  460. 'This is the introduction to the book...',
  461. 'Chapter 1 content goes here...',
  462. 'Chapter 2 content goes here...',
  463. 'Conclusion of the book...',
  464. ],
  465. 'downloads' => [
  466. ['format' => 'PDF', 'url' => '#'],
  467. ['format' => 'EPUB', 'url' => '#'],
  468. ['format' => 'MOBI', 'url' => '#'],
  469. ],
  470. ];
  471. // Sample related books (replace with database query)
  472. $relatedBooks = [
  473. [
  474. 'title' => 'Related Book 1',
  475. 'description' => 'A thrilling adventure...',
  476. 'image' => 'https://via.placeholder.com/300x200',
  477. 'link' => '#',
  478. ],
  479. [
  480. 'title' => 'Related Book 2',
  481. 'description' => 'A mystery novel...',
  482. 'image' => 'https://via.placeholder.com/300x200',
  483. 'link' => '#',
  484. ],
  485. [
  486. 'title' => 'Related Book 3',
  487. 'description' => 'A bestseller...',
  488. 'image' => 'https://via.placeholder.com/300x200',
  489. 'link' => '#',
  490. ],
  491. ];
  492. return view('library.book.read2', compact('book', 'relatedBooks'));
  493. }
  494. }