BookController.php 12 KB

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