BookController.php 22 KB

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