BookController.php 12 KB

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