BookController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. namespace App\Http\Controllers\Library;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Http\Request;
  5. use App\Models\ProgressChapter;
  6. use App\Models\PaliText;
  7. use App\Models\Sentence;
  8. use App\Services\ChapterService;
  9. use App\Services\PaliTextService;
  10. use App\Services\OpenSearchService;
  11. use App\DTO\Search\HitItemDTO;
  12. class BookController extends Controller
  13. {
  14. protected $maxChapterLen = 50000;
  15. protected $minChapterLen = 100;
  16. /**
  17. * 构造函数,注入 OpenSearchService
  18. *
  19. * @param \App\Services\OpenSearchService $searchService
  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, $id) {
  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)) return $html;
  61. return preg_replace_callback(
  62. '/(<div class=\'sentence\' data-sid=\'([^\']+)\')/',
  63. function ($matches) use ($notesMap) {
  64. $sid = $matches[2];
  65. if (!isset($notesMap[$sid])) return $matches[0];
  66. $uid = $notesMap[$sid];
  67. return $matches[1] . " data-note-id='{$uid}'";
  68. },
  69. $html
  70. );
  71. }
  72. public function read(Request $request, string $id)
  73. {
  74. $channelId = $request->input('channel');
  75. $openSearchId = "tipitaka_chapter_{$id}_{$channelId}";
  76. $chapter = HitItemDTO::fromArray($this->searchService->get($openSearchId))->toArray();
  77. [$bookId, $paraId] = explode('-', $id);
  78. if ($request->has('comm')) {
  79. $currChapter = $this->paliTextService->getCurrChapter($bookId, $paraId);
  80. $commentaries = $this->fetchCommentary($bookId, $paraId, $paraId + $currChapter->chapter_len - 1, $request->input('comm'));
  81. // sid 格式:{book_id}-{paragraph}-{word_start}-{word_end}
  82. $notesMap = collect($commentaries)->keyBy(function ($note) {
  83. return "{$note['book_id']}-{$note['paragraph']}-{$note['word_start']}-{$note['word_end']}";
  84. })->map(fn($note) => $note['uid'])->toArray();
  85. }
  86. $chapterService = app(ChapterService::class);
  87. $book = [];
  88. $book['toc'] = $this->getBookToc((int)$bookId, (int)$paraId, $channelId, 2, 7);
  89. $book['categories'] = $chapter['category'];
  90. $book['title'] = $chapter['title'];
  91. $book['author'] = 'author'; // FIXME
  92. $book['tags'] = [];
  93. $book['pagination'] = $this->pagination((int)$bookId, (int)$paraId, $channelId);
  94. if (isset($notesMap)) {
  95. $book['content'] = $this->injectNoteMarkers($chapter['display'], $notesMap);
  96. } else {
  97. $book['content'] = $chapter['display'];
  98. }
  99. $allChannels = $chapterService->publicChannels((int)$bookId, (int)$paraId);
  100. $commentaryChannels = array_filter($allChannels, function ($channel) {
  101. return $channel['type'] === 'commentary';
  102. });
  103. $channels = array_filter($allChannels, function ($channel) {
  104. return $channel['type'] !== 'commentary';
  105. });
  106. $editor_link = config('mint.server.dashboard_base_path')
  107. . "/workspace/tipitaka/chapter/{$id}?channel={$channelId}";
  108. $view = view('library.book.read', compact('book', 'channels', 'editor_link', 'commentaryChannels'));
  109. return $view;
  110. }
  111. private function loadBook(string $id)
  112. {
  113. $book = ProgressChapter::with('channel.owner')->find($id);
  114. return $book;
  115. }
  116. public function toggleTheme(Request $request)
  117. {
  118. $theme = $request->input('theme', 'light');
  119. session(['theme' => $theme]);
  120. return response()->json(['status' => 'success']);
  121. }
  122. private function getBookInfo($book)
  123. {
  124. $title = $book->title;
  125. if (empty($title)) {
  126. $title = PaliText::where('book', $book->book)
  127. ->where('paragraph', $book->para)->first()->toc;
  128. }
  129. return [
  130. "id" => $book->uid,
  131. "title" => $title,
  132. "author" => $book->channel->name,
  133. "publisher" => $book->channel->owner,
  134. "type" => __('label.' . $book->channel->type),
  135. "category_id" => 11,
  136. "cover" => "/assets/images/cover/1/214.jpg",
  137. "description" => $book->summary ?? "",
  138. "language" => __('language.' . $book->channel->lang),
  139. ];
  140. }
  141. private function getBookToc(int $book, int $paragraph, string $channelId, $minLevel = 2, $maxLevel = 2): array
  142. {
  143. $currBook = $this->bookStart($book, $paragraph);
  144. $start = $currBook->paragraph;
  145. $end = $currBook->paragraph + $currBook->chapter_len - 1;
  146. $paliTexts = PaliText::where('book', $book)
  147. ->whereBetween('paragraph', [$start, $end])
  148. ->whereBetween('level', [$minLevel, $maxLevel])
  149. ->orderBy('paragraph')
  150. ->get();
  151. $chapters = ProgressChapter::where('book', $book)
  152. ->whereBetween('para', [$start, $end])
  153. ->where('channel_id', $channelId)
  154. ->orderBy('para')
  155. ->get();
  156. // keyBy 建索引,map 里 O(1) 查找,完全避免 toArray() 序列化和 array_filter O(n×m) 扫描
  157. $chaptersIndexed = $chapters->keyBy('para');
  158. return $paliTexts->map(function ($paliText) use ($chaptersIndexed, $channelId) {
  159. $title = $paliText->toc;
  160. $summary = '';
  161. $progress = 0;
  162. $disabled = true;
  163. /** @var ProgressChapter|null $chapter */
  164. $chapter = $chaptersIndexed->get($paliText->paragraph);
  165. if ($chapter) {
  166. if (!empty($chapter->title)) $title = $chapter->title;
  167. if (!empty($chapter->summary)) $summary = $chapter->summary;
  168. $progress = (int)($chapter->progress * 100);
  169. $disabled = false;
  170. }
  171. return [
  172. 'id' => "{$paliText->book}-{$paliText->paragraph}",
  173. 'channel' => $channelId,
  174. 'title' => $title,
  175. 'summary' => $summary,
  176. 'progress' => $progress,
  177. 'level' => (int)$paliText->level,
  178. 'disabled' => $disabled,
  179. ];
  180. })->all();
  181. }
  182. public function getBookCategory($book, $paragraph)
  183. {
  184. $tags = PaliText::with('tagMaps.tags')
  185. ->where('book', $book)
  186. ->where('paragraph', $paragraph)
  187. ->first()->tagMaps->map(function ($tagMap) {
  188. return $tagMap->tags;
  189. })->toArray();
  190. return $tags;
  191. }
  192. private function bookStart($book, $paragraph)
  193. {
  194. $currBook = PaliText::where('book', $book)
  195. ->where('paragraph', '<=', $paragraph)
  196. ->where('level', 1)
  197. ->orderBy('paragraph', 'desc')
  198. ->first();
  199. return $currBook;
  200. }
  201. public function pagination(int $book, int $para, string $channelId)
  202. {
  203. $currBook = $this->bookStart($book, $para);
  204. $start = $currBook->paragraph;
  205. $end = $currBook->paragraph + $currBook->chapter_len - 1;
  206. // 查询起始段落
  207. $paragraphs = PaliText::where('book', $book)
  208. ->whereBetween('paragraph', [$start, $end])
  209. ->where('level', '<', 8)
  210. ->orderBy('paragraph')
  211. ->get();
  212. $curr = $paragraphs->firstWhere('paragraph', $para);
  213. $current = $curr; //实际显示的段落
  214. $endParagraph = $curr->paragraph + $curr->chapter_len - 1;
  215. if ($curr->chapter_strlen > $this->maxChapterLen) {
  216. //太大了,修改结束位置 找到下一级
  217. foreach ($paragraphs as $key => $paragraph) {
  218. if ($paragraph->paragraph > $curr->paragraph) {
  219. if ($paragraph->chapter_strlen <= $this->maxChapterLen) {
  220. $endParagraph = $paragraph->paragraph + $paragraph->chapter_len - 1;
  221. $current = $paragraph;
  222. break;
  223. }
  224. if ($paragraph->level <= $curr->level) {
  225. //不能往下走了,就是它了
  226. $endParagraph = $paragraphs[$key - 1]->paragraph + $paragraphs[$key - 1]->chapter_len - 1;
  227. $current = $paragraph;
  228. break;
  229. }
  230. }
  231. }
  232. }
  233. $start = $curr->paragraph;
  234. $end = $endParagraph;
  235. $nextPali = $this->next($current->book, $current->paragraph, $current->level);
  236. $prevPali = $this->prev($current->book, $current->paragraph, $current->level);
  237. $next = null;
  238. if ($nextPali) {
  239. $nextTranslation = ProgressChapter::with('channel.owner')
  240. ->where('book', $nextPali->book)
  241. ->where('para', $nextPali->paragraph)
  242. ->where('channel_id', $channelId)
  243. ->first();
  244. if ($nextTranslation) {
  245. if (!empty($nextTranslation->title)) {
  246. $next['title'] = $nextTranslation->title;
  247. } else {
  248. $next['title'] = $nextPali->toc;
  249. }
  250. $next['id'] = "{$nextPali->book}-{$nextPali->paragraph}";
  251. }
  252. }
  253. $prev = null;
  254. if ($prevPali) {
  255. $prevTranslation = ProgressChapter::with('channel.owner')
  256. ->where('book', $prevPali->book)
  257. ->where('para', $prevPali->paragraph)
  258. ->where('channel_id', $channelId)
  259. ->first();
  260. if ($prevTranslation) {
  261. if (!empty($prevTranslation->title)) {
  262. $prev['title'] = $prevTranslation->title;
  263. } else {
  264. $prev['title'] = $prevPali->toc;
  265. }
  266. $prev['id'] = "{$prevPali->book}-{$prevPali->paragraph}";
  267. }
  268. }
  269. return compact('start', 'end', 'next', 'prev');
  270. }
  271. public function next($book, $paragraph, $level)
  272. {
  273. $next = PaliText::where('book', $book)
  274. ->where('paragraph', '>', $paragraph)
  275. ->where('level', $level)
  276. ->orderBy('paragraph')
  277. ->first();
  278. return $next ?? null;
  279. }
  280. public function prev($book, $paragraph, $level)
  281. {
  282. $prev = PaliText::where('book', $book)
  283. ->where('paragraph', '<', $paragraph)
  284. ->where('level', $level)
  285. ->orderBy('paragraph', 'desc')
  286. ->first();
  287. return $prev ?? null;
  288. }
  289. public function show2($id)
  290. {
  291. // Sample book data (replace with database query)
  292. $book = [
  293. 'title' => 'Sample Book Title',
  294. 'author' => 'John Doe',
  295. 'category' => 'Fiction',
  296. 'tags' => ['Adventure', 'Mystery', 'Bestseller'],
  297. 'toc' => ['Introduction', 'Chapter 1', 'Chapter 2', 'Conclusion'],
  298. 'content' => [
  299. 'This is the introduction to the book...',
  300. 'Chapter 1 content goes here...',
  301. 'Chapter 2 content goes here...',
  302. 'Conclusion of the book...',
  303. ],
  304. 'downloads' => [
  305. ['format' => 'PDF', 'url' => '#'],
  306. ['format' => 'EPUB', 'url' => '#'],
  307. ['format' => 'MOBI', 'url' => '#'],
  308. ],
  309. ];
  310. // Sample related books (replace with database query)
  311. $relatedBooks = [
  312. [
  313. 'title' => 'Related Book 1',
  314. 'description' => 'A thrilling adventure...',
  315. 'image' => 'https://via.placeholder.com/300x200',
  316. 'link' => '#',
  317. ],
  318. [
  319. 'title' => 'Related Book 2',
  320. 'description' => 'A mystery novel...',
  321. 'image' => 'https://via.placeholder.com/300x200',
  322. 'link' => '#',
  323. ],
  324. [
  325. 'title' => 'Related Book 3',
  326. 'description' => 'A bestseller...',
  327. 'image' => 'https://via.placeholder.com/300x200',
  328. 'link' => '#',
  329. ],
  330. ];
  331. return view('library.book.read2', compact('book', 'relatedBooks'));
  332. }
  333. }