BookController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. class BookController extends Controller
  15. {
  16. protected $maxChapterLen = 50000;
  17. protected $minChapterLen = 100;
  18. /**
  19. * 构造函数,注入 OpenSearchService
  20. */
  21. public function __construct(
  22. protected OpenSearchService $searchService,
  23. protected PaliTextService $paliTextService
  24. ) {}
  25. public function show(string $id)
  26. {
  27. $bookRaw = $this->loadBook($id);
  28. if (! $bookRaw) {
  29. abort(404);
  30. }
  31. // 查询章节
  32. $channelId = $bookRaw->channel_id; // 替换为具体的 channel_id 值
  33. $book = $this->getBookInfo($bookRaw);
  34. $book['contents'] = $this->getBookToc($bookRaw->book, $bookRaw->para, $channelId);
  35. // 获取其他版本
  36. $others = ProgressChapter::with('channel.owner')
  37. ->where('book', $bookRaw->book)
  38. ->where('para', $bookRaw->para)
  39. ->whereHas('channel', function ($query) {
  40. $query->where('status', 30);
  41. })
  42. ->where('progress', '>', 0.2)
  43. ->get();
  44. $otherVersions = [];
  45. $others->each(function ($book) use (&$otherVersions) {
  46. $otherVersions[] = $this->getBookInfo($book);
  47. });
  48. return view('library.tipitaka.show', compact('book', 'otherVersions'));
  49. }
  50. private function fetchCommentary(int $book, int $paraStart, int $paraEnd, string $channelId)
  51. {
  52. $notes = Sentence::where('book_id', $book)
  53. ->whereBetween('paragraph', [$paraStart, $paraEnd])
  54. ->where('channel_uid', $channelId)
  55. ->select(['uid', 'book_id', 'paragraph', 'word_start', 'word_end'])->get()->toArray();
  56. return $notes;
  57. }
  58. private function injectNoteMarkers(string $html, array $notesMap): string
  59. {
  60. if (empty($notesMap)) {
  61. return $html;
  62. }
  63. return preg_replace_callback(
  64. '/(<div class=\'sentence\' data-sid=\'([^\']+)\')/',
  65. function ($matches) use ($notesMap) {
  66. $sid = $matches[2];
  67. if (! isset($notesMap[$sid])) {
  68. return $matches[0];
  69. }
  70. $uid = $notesMap[$sid];
  71. return $matches[1]." data-note-id='{$uid}'";
  72. },
  73. $html
  74. );
  75. }
  76. public function read(Request $request, string $id)
  77. {
  78. $channelId = $request->input('channel');
  79. $openSearchId = "tipitaka_chapter_{$id}_{$channelId}";
  80. try {
  81. $chapter = HitItemDTO::fromArray($this->searchService->get($openSearchId))->toArray();
  82. } catch (\Throwable $th) {
  83. $chapter = [
  84. 'category' => [],
  85. 'title' => '',
  86. 'display' => '',
  87. ];
  88. }
  89. [$bookId, $paraId] = explode('-', $id);
  90. if ($request->has('comm')) {
  91. $currChapter = $this->paliTextService->getCurrChapter($bookId, $paraId);
  92. $commentaries = $this->fetchCommentary($bookId, $paraId, $paraId + $currChapter->chapter_len - 1, $request->input('comm'));
  93. // sid 格式:{book_id}-{paragraph}-{word_start}-{word_end}
  94. $notesMap = collect($commentaries)->keyBy(function ($note) {
  95. return "{$note['book_id']}-{$note['paragraph']}-{$note['word_start']}-{$note['word_end']}";
  96. })->map(fn ($note) => $note['uid'])->toArray();
  97. }
  98. $chapterService = app(ChapterService::class);
  99. $book = [];
  100. $book['toc'] = $this->getBookToc((int) $bookId, (int) $paraId, $channelId, 2, 7);
  101. $channel = ChannelApi::getById($channelId);
  102. $studio = StudioApi::getById($channel['studio_id']);
  103. $book['categories'] = $chapter['category'];
  104. $book['title'] = $chapter['title'];
  105. $book['author'] = $channel['name'];
  106. $book['studio'] = $studio;
  107. $book['tags'] = [];
  108. $book['pagination'] = $this->pagination((int) $bookId, (int) $paraId, $channelId);
  109. if (isset($notesMap)) {
  110. $book['content'] = $this->injectNoteMarkers($chapter['display'], $notesMap);
  111. } else {
  112. $book['content'] = $chapter['display'];
  113. }
  114. $allChannels = $chapterService->publicChannels((int) $bookId, (int) $paraId);
  115. $commentaryChannels = array_filter($allChannels, function ($channel) {
  116. return $channel['type'] === 'commentary';
  117. });
  118. $channels = array_filter($allChannels, function ($channel) {
  119. return $channel['type'] !== 'commentary';
  120. });
  121. $editor_link = config('mint.server.dashboard_base_path')
  122. ."/workspace/tipitaka/chapter/{$id}?channel={$channelId}";
  123. $view = view('library.book.read', compact('book', 'channels', 'editor_link', 'commentaryChannels'));
  124. return $view;
  125. }
  126. private function loadBook(string $id)
  127. {
  128. $book = ProgressChapter::with('channel.owner')->find($id);
  129. return $book;
  130. }
  131. public function toggleTheme(Request $request)
  132. {
  133. $theme = $request->input('theme', 'light');
  134. session(['theme' => $theme]);
  135. return response()->json(['status' => 'success']);
  136. }
  137. private function getBookInfo($book)
  138. {
  139. $title = $book->title;
  140. if (empty($title)) {
  141. $title = PaliText::where('book', $book->book)
  142. ->where('paragraph', $book->para)->first()->toc;
  143. }
  144. return [
  145. 'id' => $book->uid,
  146. 'title' => $title,
  147. 'author' => $book->channel->name,
  148. 'publisher' => $book->channel->owner,
  149. 'type' => __('label.'.$book->channel->type),
  150. 'category_id' => 11,
  151. 'cover' => '/assets/images/cover/1/214.jpg',
  152. 'description' => $book->summary ?? '',
  153. 'language' => __('language.'.$book->channel->lang),
  154. ];
  155. }
  156. private function getBookToc(int $book, int $paragraph, string $channelId, $minLevel = 2, $maxLevel = 2): array
  157. {
  158. $currBook = $this->bookStart($book, $paragraph);
  159. $start = $currBook->paragraph;
  160. $end = $currBook->paragraph + $currBook->chapter_len - 1;
  161. $paliTexts = PaliText::where('book', $book)
  162. ->whereBetween('paragraph', [$start, $end])
  163. ->whereBetween('level', [$minLevel, $maxLevel])
  164. ->orderBy('paragraph')
  165. ->get();
  166. if ($paliTexts->isEmpty()) {
  167. return [];
  168. }
  169. $chapters = ProgressChapter::where('book', $book)
  170. ->whereBetween('para', [$start, $end])
  171. ->where('channel_id', $channelId)
  172. ->orderBy('para')
  173. ->get();
  174. // keyBy 建索引,map 里 O(1) 查找,完全避免 toArray() 序列化和 array_filter O(n×m) 扫描
  175. $chaptersIndexed = $chapters->keyBy('para');
  176. // 当前阅读章节的 toc id,用于高亮(active)与折叠展开(hide)
  177. $currentId = "{$book}-{$paragraph}";
  178. // 折叠逻辑:列表有序,父节点 = 之前最近的更小 level 节点
  179. // 参见 AnthologyReadController::buildCollapsedToc()
  180. $parents = []; // id => parent_id|null
  181. $stack = []; // 祖先栈 [ ['id'=>..., 'level'=>...], ... ]
  182. foreach ($paliTexts as $paliText) {
  183. $id = "{$paliText->book}-{$paliText->paragraph}";
  184. $level = (int) $paliText->level;
  185. while (! empty($stack) && $stack[count($stack) - 1]['level'] >= $level) {
  186. array_pop($stack);
  187. }
  188. $parents[$id] = empty($stack) ? null : $stack[count($stack) - 1]['id'];
  189. $stack[] = ['id' => $id, 'level' => $level];
  190. }
  191. // 当前节点的祖先链
  192. $ancestorSet = [];
  193. $cursor = $currentId;
  194. while (! empty($parents[$cursor])) {
  195. $cursor = $parents[$cursor];
  196. $ancestorSet[$cursor] = true;
  197. }
  198. // 需要展开子节点的集合 = 祖先链 + 当前节点
  199. $expandParentSet = $ancestorSet;
  200. $expandParentSet[$currentId] = true;
  201. // 顶层 level(列表中最浅的一层,折叠模式下始终可见)
  202. $topLevel = (int) $paliTexts->min('level');
  203. return $paliTexts->map(function ($paliText) use ($chaptersIndexed, $channelId, $currentId, $parents, $expandParentSet, $topLevel) {
  204. $id = "{$paliText->book}-{$paliText->paragraph}";
  205. $level = (int) $paliText->level;
  206. $title = $paliText->toc;
  207. $summary = '';
  208. $progress = 0;
  209. $disabled = true;
  210. /** @var ProgressChapter|null $chapter */
  211. $chapter = $chaptersIndexed->get($paliText->paragraph);
  212. if ($chapter) {
  213. if (! empty($chapter->title)) {
  214. $title = $chapter->title;
  215. }
  216. if (! empty($chapter->summary)) {
  217. $summary = $chapter->summary;
  218. }
  219. $progress = (int) ($chapter->progress * 100);
  220. $disabled = false;
  221. }
  222. $parentId = $parents[$id];
  223. // 折叠模式可见:顶层节点,或父节点在展开集合中(祖先链 / 当前节点的直接子节点)
  224. $visible = $level === $topLevel
  225. || ($parentId !== null && isset($expandParentSet[$parentId]));
  226. return [
  227. 'id' => $id,
  228. 'channel' => $channelId,
  229. 'title' => $title,
  230. 'summary' => $summary,
  231. 'progress' => $progress,
  232. 'level' => $level,
  233. 'disabled' => $disabled,
  234. 'active' => $id === $currentId,
  235. 'hide' => ! $visible,
  236. ];
  237. })->all();
  238. }
  239. public function getBookCategory($book, $paragraph)
  240. {
  241. $tags = PaliText::with('tagMaps.tags')
  242. ->where('book', $book)
  243. ->where('paragraph', $paragraph)
  244. ->first()->tagMaps->map(function ($tagMap) {
  245. return $tagMap->tags;
  246. })->toArray();
  247. return $tags;
  248. }
  249. private function bookStart($book, $paragraph)
  250. {
  251. $currBook = PaliText::where('book', $book)
  252. ->where('paragraph', '<=', $paragraph)
  253. ->where('level', 1)
  254. ->orderBy('paragraph', 'desc')
  255. ->first();
  256. return $currBook;
  257. }
  258. public function pagination(int $book, int $para, string $channelId)
  259. {
  260. $currBook = $this->bookStart($book, $para);
  261. $start = $currBook->paragraph;
  262. $end = $currBook->paragraph + $currBook->chapter_len - 1;
  263. // 查询起始段落
  264. $paragraphs = PaliText::where('book', $book)
  265. ->whereBetween('paragraph', [$start, $end])
  266. ->where('level', '<', 8)
  267. ->orderBy('paragraph')
  268. ->get();
  269. $curr = $paragraphs->firstWhere('paragraph', $para);
  270. $current = $curr; // 实际显示的段落
  271. $endParagraph = $curr->paragraph + $curr->chapter_len - 1;
  272. if ($curr->chapter_strlen > $this->maxChapterLen) {
  273. // 太大了,修改结束位置 找到下一级
  274. foreach ($paragraphs as $key => $paragraph) {
  275. if ($paragraph->paragraph > $curr->paragraph) {
  276. if ($paragraph->chapter_strlen <= $this->maxChapterLen) {
  277. $endParagraph = $paragraph->paragraph + $paragraph->chapter_len - 1;
  278. $current = $paragraph;
  279. break;
  280. }
  281. if ($paragraph->level <= $curr->level) {
  282. // 不能往下走了,就是它了
  283. $endParagraph = $paragraphs[$key - 1]->paragraph + $paragraphs[$key - 1]->chapter_len - 1;
  284. $current = $paragraph;
  285. break;
  286. }
  287. }
  288. }
  289. }
  290. $start = $curr->paragraph;
  291. $end = $endParagraph;
  292. $nextPali = $this->next($current->book, $current->paragraph, $current->level);
  293. $prevPali = $this->prev($current->book, $current->paragraph, $current->level);
  294. $next = null;
  295. if ($nextPali) {
  296. $nextTranslation = ProgressChapter::with('channel.owner')
  297. ->where('book', $nextPali->book)
  298. ->where('para', $nextPali->paragraph)
  299. ->where('channel_id', $channelId)
  300. ->first();
  301. if ($nextTranslation) {
  302. if (! empty($nextTranslation->title)) {
  303. $next['title'] = $nextTranslation->title;
  304. } else {
  305. $next['title'] = $nextPali->toc;
  306. }
  307. $next['id'] = "{$nextPali->book}-{$nextPali->paragraph}";
  308. }
  309. }
  310. $prev = null;
  311. if ($prevPali) {
  312. $prevTranslation = ProgressChapter::with('channel.owner')
  313. ->where('book', $prevPali->book)
  314. ->where('para', $prevPali->paragraph)
  315. ->where('channel_id', $channelId)
  316. ->first();
  317. if ($prevTranslation) {
  318. if (! empty($prevTranslation->title)) {
  319. $prev['title'] = $prevTranslation->title;
  320. } else {
  321. $prev['title'] = $prevPali->toc;
  322. }
  323. $prev['id'] = "{$prevPali->book}-{$prevPali->paragraph}";
  324. }
  325. }
  326. return compact('start', 'end', 'next', 'prev');
  327. }
  328. public function next($book, $paragraph, $level)
  329. {
  330. $next = PaliText::where('book', $book)
  331. ->where('paragraph', '>', $paragraph)
  332. ->where('level', $level)
  333. ->orderBy('paragraph')
  334. ->first();
  335. return $next ?? null;
  336. }
  337. public function prev($book, $paragraph, $level)
  338. {
  339. $prev = PaliText::where('book', $book)
  340. ->where('paragraph', '<', $paragraph)
  341. ->where('level', $level)
  342. ->orderBy('paragraph', 'desc')
  343. ->first();
  344. return $prev ?? null;
  345. }
  346. public function show2($id)
  347. {
  348. // Sample book data (replace with database query)
  349. $book = [
  350. 'title' => 'Sample Book Title',
  351. 'author' => 'John Doe',
  352. 'category' => 'Fiction',
  353. 'tags' => ['Adventure', 'Mystery', 'Bestseller'],
  354. 'toc' => ['Introduction', 'Chapter 1', 'Chapter 2', 'Conclusion'],
  355. 'content' => [
  356. 'This is the introduction to the book...',
  357. 'Chapter 1 content goes here...',
  358. 'Chapter 2 content goes here...',
  359. 'Conclusion of the book...',
  360. ],
  361. 'downloads' => [
  362. ['format' => 'PDF', 'url' => '#'],
  363. ['format' => 'EPUB', 'url' => '#'],
  364. ['format' => 'MOBI', 'url' => '#'],
  365. ],
  366. ];
  367. // Sample related books (replace with database query)
  368. $relatedBooks = [
  369. [
  370. 'title' => 'Related Book 1',
  371. 'description' => 'A thrilling adventure...',
  372. 'image' => 'https://via.placeholder.com/300x200',
  373. 'link' => '#',
  374. ],
  375. [
  376. 'title' => 'Related Book 2',
  377. 'description' => 'A mystery novel...',
  378. 'image' => 'https://via.placeholder.com/300x200',
  379. 'link' => '#',
  380. ],
  381. [
  382. 'title' => 'Related Book 3',
  383. 'description' => 'A bestseller...',
  384. 'image' => 'https://via.placeholder.com/300x200',
  385. 'link' => '#',
  386. ],
  387. ];
  388. return view('library.book.read2', compact('book', 'relatedBooks'));
  389. }
  390. }