BookController.php 22 KB

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