2
0

BookController.php 24 KB

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