BookController.php 14 KB

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