BookController.php 14 KB

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