BookController.php 17 KB

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