BookController.php 21 KB

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