BookController.php 14 KB

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