BookController.php 22 KB

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