2
0

BookController.php 22 KB

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