BookController.php 14 KB

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