TipitakaExportBuilder.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\Channel;
  4. use App\Services\TipitakaCatalogService;
  5. use DOMDocument;
  6. use DOMXPath;
  7. use Illuminate\Support\Facades\App;
  8. use Illuminate\Support\Facades\File;
  9. use Illuminate\Support\Str;
  10. use RuntimeException;
  11. use Symfony\Component\Process\Process;
  12. use ZipArchive;
  13. /**
  14. * 生成三藏下载的文件(由 TipitakaExportService::run() 在 worker 里调用)。
  15. *
  16. * 正文一律经 TipitakaReadingService::page() 取,和 `/v3/tipitaka-reading` 是同一份渲染:
  17. * html / offline 用 display(段落 HTML),markdown / epub / docx 用逐句的 markdown
  18. * (句末附脚注正文,这里整章重新编号)。epub、docx 由 pandoc 从 markdown 转换,
  19. * 这样脚注能变成电子书 / Word 里真正的脚注。
  20. *
  21. * 中间文件写在 storage/app/tmp/tipitaka-export/ 下的临时目录,每部作品写完就落盘,
  22. * zip 最后用 addFile 收集——整个 channel 的正文不会同时留在内存里。
  23. */
  24. class TipitakaExportBuilder
  25. {
  26. public function __construct(
  27. private readonly TipitakaReadingService $reading,
  28. private readonly TipitakaCatalogService $catalog,
  29. private readonly PaliTextService $paliTexts,
  30. ) {}
  31. /**
  32. * 生成文件,返回文件字节。
  33. *
  34. * @param array<string, mixed> $status 导出状态(TipitakaExportService::spec() 的字段)
  35. * @param array{kind: string, works: list<array<string, mixed>>, title: string} $scope
  36. * @param callable(float, string): void $progress 进度 0–1 与说明
  37. */
  38. public function build(array $status, array $scope, callable $progress): string
  39. {
  40. $dir = storage_path('app/tmp/tipitaka-export/'.$status['id'].'-'.Str::random(6));
  41. File::ensureDirectoryExists($dir);
  42. $context = $this->context($status['channel']);
  43. // 文件里的界面文字(目录、生成日期…)跟着译文的语言走,而不是 worker 进程的默认语言
  44. $previousLocale = App::getLocale();
  45. App::setLocale(self::locale($context['lang']));
  46. try {
  47. $format = $status['format'];
  48. $single = $scope['kind'] === 'work';
  49. $works = $scope['works'];
  50. $count = count($works);
  51. // 打包时 zip 里套一层与文件名同名的目录,解压后不会散落一地
  52. $root = $single ? '' : pathinfo(pathinfo($status['filename'], PATHINFO_FILENAME), PATHINFO_FILENAME).'/';
  53. $entries = [];
  54. foreach ($works as $i => $work) {
  55. $tick = function (float $fraction) use ($progress, $i, $count, $work): void {
  56. $progress(0.9 * ($i + $fraction) / $count, ($i + 1)."/{$count} {$work['local_title']}");
  57. };
  58. $path = $single ? '' : $this->categoryFolder($work, $context['lang']).'/';
  59. $name = self::safeName("{$work['sn']}-{$work['local_title']}");
  60. match ($format) {
  61. 'offline' => $entries[''] = $this->offline($dir, $status, $work, $tick),
  62. 'html' => $entries[$single ? self::safeName($work['local_title']).'.html' : "{$root}works/{$name}.html"]
  63. = $this->writeFile($dir, "w{$i}.html", $this->htmlWork($context, $work, $this->paragraphs($context['uid'], $work, 'html', $tick), $single ? null : '../index.html')),
  64. 'markdown' => $entries += $this->markdownWork($dir, $i, $context, $work, $this->paragraphs($context['uid'], $work, 'markdown', $tick), $single ? self::safeName($work['local_title']).'/' : "{$root}{$path}{$name}/"),
  65. 'epub', 'docx' => $entries[$single ? '' : "{$root}{$path}{$name}.{$format}"]
  66. = $this->pandoc($dir, $i, $format, $context, $work, $this->paragraphs($context['uid'], $work, 'markdown', $tick)),
  67. };
  68. }
  69. $progress(0.92, 'packing');
  70. if ($format === 'offline' || ($single && in_array($format, ['epub', 'docx'], true))) {
  71. return (string) file_get_contents($entries['']);
  72. }
  73. if (! $single) {
  74. $entries += match ($format) {
  75. 'html' => ["{$root}index.html" => $this->writeFile($dir, 'index.html', $this->htmlIndex($context, $scope))],
  76. default => ["{$root}README.md" => $this->writeFile($dir, 'index.md', $this->markdownIndex($context, $scope, $format))],
  77. };
  78. }
  79. return $this->zip($dir, $entries);
  80. } finally {
  81. App::setLocale($previousLocale);
  82. File::deleteDirectory($dir);
  83. }
  84. }
  85. /**
  86. * channel 的语言(如 zh、zh-Hant、en-US)→ 受支持的界面语言,匹配不上用 en。
  87. */
  88. public static function locale(string $lang): string
  89. {
  90. $tag = strtolower($lang);
  91. if (str_starts_with($tag, 'zh')) {
  92. return preg_match('/hant|tw|hk|mo/', $tag) ? 'zh-Hant' : 'zh-Hans';
  93. }
  94. $primary = explode('-', $tag)[0];
  95. return array_key_exists($primary, (array) config('mint.languages')) ? $primary : 'en';
  96. }
  97. /**
  98. * 文件 / 目录名:去掉文件系统不允许的字符,限长。
  99. */
  100. public static function safeName(string $name): string
  101. {
  102. $name = trim((string) preg_replace('/[\\\\\/:*?"<>|\x00-\x1f]+/u', ' ', $name));
  103. $name = (string) preg_replace('/\s+/u', ' ', $name);
  104. return mb_substr($name === '' ? 'untitled' : $name, 0, 80);
  105. }
  106. /**
  107. * 一部作品的全部段落(按经文顺序),附上标题级别。没有译文的段落不在其中。
  108. *
  109. * @param array<string, mixed> $work
  110. * @param callable(float): void $tick
  111. * @return list<array{para: int, level: int, display?: string, sentences?: list<array{sid: string, html: string}>}>
  112. */
  113. private function paragraphs(string $channel, array $work, string $format, callable $tick): array
  114. {
  115. $levels = $this->headingLevels($work);
  116. $items = [];
  117. $after = null;
  118. do {
  119. $page = $this->reading->page($channel, array_filter([
  120. 'book' => $work['book'],
  121. 'para' => $work['para'],
  122. 'to' => $work['end'],
  123. 'unit' => 'para',
  124. 'page_size' => TipitakaReadingService::MAX_PARAGRAPHS_PER_PAGE,
  125. 'format' => $format,
  126. 'include' => $format === 'html' ? 'display' : 'sentences',
  127. 'after' => $after,
  128. ]));
  129. foreach ($page['items'] as $item) {
  130. unset($item['book']);
  131. $items[] = $item + ['level' => $levels[$item['para']] ?? 0];
  132. }
  133. $total = (int) ($page['meta']['total'] ?? 0);
  134. $tick($total > 0 ? 1 - ((int) ($page['meta']['remaining'] ?? 0)) / $total : 1.0);
  135. $after = $page['meta']['next_cursor'];
  136. } while ($after !== null);
  137. return $items;
  138. }
  139. /**
  140. * 作品区间里的标题段落:段落号 => 级别(1–7)。
  141. *
  142. * @param array<string, mixed> $work
  143. * @return array<int, int>
  144. */
  145. private function headingLevels(array $work): array
  146. {
  147. return array_map(fn (array $heading) => $heading['level'], $this->headingsIn($work));
  148. }
  149. /**
  150. * 作品区间里的标题:段落号 => [级别, 巴利标题]。译文没有译出标题时拿巴利标题顶上。
  151. *
  152. * @param array<string, mixed> $work
  153. * @return array<int, array{int, string}>
  154. */
  155. private function headings(array $work): array
  156. {
  157. return array_map(fn (array $heading) => [$heading['level'], $heading['toc']], $this->headingsIn($work));
  158. }
  159. /**
  160. * 作品区间里的标题段(缓存的经文静态数据),按段落号升序。
  161. *
  162. * @param array<string, mixed> $work
  163. * @return array<int, array{level: int, chapter_len: int, chapter_strlen: int, parent: int, toc: string}>
  164. */
  165. private function headingsIn(array $work): array
  166. {
  167. return array_filter(
  168. $this->paliTexts->headings((int) $work['book']),
  169. fn (int $para) => $para >= $work['para'] && $para <= $work['end'],
  170. ARRAY_FILTER_USE_KEY,
  171. );
  172. }
  173. /**
  174. * @return array{uid: string, name: string, lang: string, generated_at: string}
  175. */
  176. private function context(string $channel): array
  177. {
  178. $row = Channel::where('uid', $channel)->first(['uid', 'name', 'lang']);
  179. return [
  180. 'uid' => $channel,
  181. 'name' => (string) $row?->name,
  182. 'lang' => (string) ($row?->lang ?: 'en'),
  183. 'generated_at' => now()->toDateString(),
  184. ];
  185. }
  186. /**
  187. * 打包时作品所在的目录:分类路径(本地化名字),没有分类的放「其他」。
  188. *
  189. * @param array<string, mixed> $work
  190. */
  191. private function categoryFolder(array $work, string $lang): string
  192. {
  193. return implode('/', array_map(self::safeName(...), $this->categoryNames($work, $lang)));
  194. }
  195. /**
  196. * @param array<string, mixed> $work
  197. * @return list<string>
  198. */
  199. private function categoryNames(array $work, string $lang): array
  200. {
  201. if ($work['category_id'] === null) {
  202. return [__('library.export_uncategorized')];
  203. }
  204. $path = $this->catalog->categoryPath($work['category_id']);
  205. // 分类名查术语表要用界面语言(zh-Hans),channel 的语言常写成 zh
  206. $names = $this->catalog->localNames($this->catalog->categories(), self::locale($lang));
  207. return array_map(fn ($c) => $names[$c['name']] ?? $c['name'], $path);
  208. }
  209. // ── html ────────────────────────────────────────────────────────────
  210. /**
  211. * 一部作品的单个 HTML 文件(样式内联,离线可用)。
  212. *
  213. * @param array<string, mixed> $context
  214. * @param array<string, mixed> $work
  215. * @param list<array{para: int, level: int, display?: string}> $paragraphs
  216. */
  217. private function htmlWork(array $context, array $work, array $paragraphs, ?string $indexHref): string
  218. {
  219. $baseLevel = $paragraphs === [] ? 1 : min(array_map(fn ($p) => $p['level'] ?: 99, $paragraphs));
  220. $toc = [];
  221. $body = '';
  222. foreach ($paragraphs as $p) {
  223. // pali_texts 的级别到 7,html 只有 h1–h6
  224. $body .= preg_replace('#<(/?)h7>#', '<$1h6>', $p['display']);
  225. if ($p['level'] > 0 && $p['level'] <= $baseLevel + 2) {
  226. $toc[] = ['id' => "para-{$p['para']}", 'depth' => $p['level'] - $baseLevel, 'title' => $this->plainText($p['display'])];
  227. }
  228. }
  229. return view('exports.tipitaka.work', [
  230. 'context' => $context,
  231. 'work' => $work,
  232. 'toc' => $toc,
  233. 'body' => $body,
  234. 'indexHref' => $indexHref,
  235. 'sourceUrl' => route('library.tipitaka.channels.work', ['channel' => $context['uid'], 'sn' => $work['sn']]),
  236. ])->render();
  237. }
  238. /**
  239. * 打包时的 index.html:按藏 / 分类分组列出作品,可搜索。
  240. *
  241. * @param array<string, mixed> $context
  242. * @param array{kind: string, works: list<array<string, mixed>>, title: string} $scope
  243. */
  244. private function htmlIndex(array $context, array $scope): string
  245. {
  246. $groups = [];
  247. foreach ($scope['works'] as $work) {
  248. $names = $this->categoryNames($work, $context['lang']);
  249. $top = $names[0];
  250. $sub = implode(' · ', array_slice($names, 1)) ?: $top;
  251. $groups[$top][$sub][] = [
  252. 'title' => $work['local_title'],
  253. 'pali' => $work['title'],
  254. 'progress' => (int) round($work['progress'] * 100),
  255. 'href' => 'works/'.rawurlencode(self::safeName("{$work['sn']}-{$work['local_title']}")).'.html',
  256. ];
  257. }
  258. return view('exports.tipitaka.index', [
  259. 'context' => $context,
  260. 'scope' => $scope,
  261. 'groups' => $groups,
  262. 'averageProgress' => (int) round(100 * array_sum(array_column($scope['works'], 'progress')) / max(1, count($scope['works']))),
  263. 'sourceUrl' => route('library.tipitaka.channels.show', ['channel' => $context['uid']]),
  264. ])->render();
  265. }
  266. /**
  267. * HTML 片段的纯文字(目录用):去掉边注、脚注列表这些不属于标题的部分。
  268. */
  269. private function plainText(string $html): string
  270. {
  271. $doc = new DOMDocument;
  272. @$doc->loadHTML('<?xml encoding="UTF-8"><div>'.$html.'</div>', LIBXML_NOERROR);
  273. $xpath = new DOMXPath($doc);
  274. foreach ($xpath->query('//*[contains(@class,"sidenote") or contains(@class,"anno-footnotes") or contains(@class,"margin-toggle")]') ?: [] as $node) {
  275. $node->parentNode?->removeChild($node);
  276. }
  277. return trim((string) preg_replace('/\s+/u', ' ', $doc->textContent));
  278. }
  279. // ── markdown ────────────────────────────────────────────────────────
  280. /**
  281. * 一部作品的 markdown:README.md(目录)+ 每章一个文件。返回 zip 条目 => 临时文件。
  282. *
  283. * @param array<string, mixed> $context
  284. * @param array<string, mixed> $work
  285. * @param list<array{para: int, level: int, sentences?: list<array{sid: string, html: string}>}> $paragraphs
  286. * @return array<string, string>
  287. */
  288. private function markdownWork(string $dir, int $index, array $context, array $work, array $paragraphs, string $prefix): array
  289. {
  290. $chapters = $this->chapters($work, $paragraphs);
  291. $entries = [];
  292. $toc = [];
  293. // 00 只给序言(第一章之前的段落),正式的章从 01 起
  294. $offset = ($chapters[0]['start'] ?? null) === 0 ? 0 : 1;
  295. foreach ($chapters as $i => $chapter) {
  296. $file = sprintf('%02d-%s.md', $i + $offset, self::safeName($chapter['title']));
  297. $entries[$prefix.$file] = $this->writeFile($dir, "w{$index}-{$i}.md", $this->markdown($chapter['paragraphs'], $chapter['level']));
  298. $toc[] = '- ['.$this->escapeLink($chapter['title']).'](<'.$file.'>)';
  299. }
  300. $readme = "# {$work['local_title']}\n\n*{$work['title']}* · {$context['name']}\n\n"
  301. .__('library.export_generated_at', ['date' => $context['generated_at']])."\n\n"
  302. .implode("\n", $toc)."\n";
  303. $entries[$prefix.'README.md'] = $this->writeFile($dir, "w{$index}-readme.md", $readme);
  304. return $entries;
  305. }
  306. /**
  307. * 打包时的总目录 README.md:按分类列出各部作品(markdown 指向作品目录,epub / docx 指向文件)。
  308. *
  309. * @param array<string, mixed> $context
  310. * @param array{kind: string, works: list<array<string, mixed>>, title: string} $scope
  311. */
  312. private function markdownIndex(array $context, array $scope, string $format): string
  313. {
  314. $lines = ["# {$scope['title']}", '', "{$context['name']} · ".__('library.export_generated_at', ['date' => $context['generated_at']])];
  315. $current = null;
  316. foreach ($scope['works'] as $work) {
  317. $folder = $this->categoryFolder($work, $context['lang']);
  318. if ($folder !== $current) {
  319. $lines[] = '';
  320. $lines[] = '## '.str_replace('/', ' / ', $folder);
  321. $lines[] = '';
  322. $current = $folder;
  323. }
  324. $name = self::safeName("{$work['sn']}-{$work['local_title']}");
  325. $target = $format === 'markdown' ? "{$folder}/{$name}/README.md" : "{$folder}/{$name}.{$format}";
  326. $lines[] = '- ['.$this->escapeLink($work['local_title']).'](<'.$target.'>) · *'.$work['title'].'*';
  327. }
  328. return implode("\n", $lines)."\n";
  329. }
  330. /**
  331. * 按章切分:作品区间里比作品本身低一级的标题(实际出现的最高一级)各成一章;
  332. * 第一章之前的段落(作品标题、序言)归到第 0 章。没有译文的章不出现。
  333. *
  334. * @param array<string, mixed> $work
  335. * @param list<array{para: int, level: int, sentences?: list<array{sid: string, html: string}>}> $paragraphs
  336. * @return list<array{start: int, title: string, level: int, paragraphs: list<array<string, mixed>>}>
  337. */
  338. private function chapters(array $work, array $paragraphs): array
  339. {
  340. $headings = $this->headings($work);
  341. $inner = array_filter($headings, fn ($h, $para) => $para > $work['para'], ARRAY_FILTER_USE_BOTH);
  342. $splitLevel = $inner === [] ? 99 : min(array_column($inner, 0));
  343. $starts = array_keys(array_filter($inner, fn ($h) => $h[0] === $splitLevel));
  344. $chapters = [];
  345. foreach ($paragraphs as $p) {
  346. $start = 0;
  347. foreach ($starts as $s) {
  348. if ($s > $p['para']) {
  349. break;
  350. }
  351. $start = $s;
  352. }
  353. $chapters[$start] ??= ['start' => $start, 'title' => $start === 0 ? $work['local_title'] : $headings[$start][1], 'level' => $splitLevel, 'paragraphs' => []];
  354. if ($p['para'] === $start) {
  355. // 章标题段有译文就用译文作章名
  356. $chapters[$start]['title'] = $this->markdownPlain($p) ?: $chapters[$start]['title'];
  357. }
  358. if ($start === 0 && $p['para'] === $work['para']) {
  359. // 作品标题是 README 的标题,不在第 0 章里重复
  360. continue;
  361. }
  362. $chapters[$start]['paragraphs'][] = $p;
  363. }
  364. return array_values(array_filter($chapters, fn ($c) => $c['paragraphs'] !== []));
  365. }
  366. /**
  367. * 把段落拼成一篇 markdown:标题段加 #($baseLevel 那一级是 #),脚注整篇重新编号、正文放在文末。
  368. *
  369. * @param list<array{para: int, level: int, sentences?: list<array{sid: string, html: string}>}> $paragraphs
  370. */
  371. private function markdown(array $paragraphs, int $baseLevel): string
  372. {
  373. $number = 0;
  374. $notes = [];
  375. $blocks = [];
  376. foreach ($paragraphs as $p) {
  377. $parts = [];
  378. foreach ($p['sentences'] ?? [] as $sentence) {
  379. $pieces = preg_split('/\n\n(?=\[\^\d+\]: )/', $sentence['html']) ?: [$sentence['html']];
  380. $map = [];
  381. foreach (array_slice($pieces, 1) as $piece) {
  382. if (preg_match('/^\[\^(\d+)\]: (.*)$/s', $piece, $m)) {
  383. $map[$m[1]] = ++$number;
  384. // 脚注正文多行时后续行要缩进,否则 pandoc 只认第一行
  385. $notes[] = "[^{$number}]: ".str_replace("\n", "\n ", trim($m[2]));
  386. }
  387. }
  388. $parts[] = preg_replace_callback('/\[\^(\d+)\]/', fn ($m) => isset($map[$m[1]]) ? "[^{$map[$m[1]]}]" : '', $pieces[0]);
  389. }
  390. $text = trim(implode("\n", $parts));
  391. if ($text === '') {
  392. continue;
  393. }
  394. if ($p['level'] > 0) {
  395. $text = str_repeat('#', max(1, min(6, $p['level'] - $baseLevel + 1))).' '.str_replace("\n", ' ', $text);
  396. }
  397. $blocks[] = $text;
  398. }
  399. return implode("\n\n", $blocks)."\n".($notes === [] ? '' : "\n".implode("\n\n", $notes)."\n");
  400. }
  401. /**
  402. * 段落 markdown 的纯文字(章名用):去掉脚注标记与正文。
  403. *
  404. * @param array{sentences?: list<array{html: string}>} $paragraph
  405. */
  406. private function markdownPlain(array $paragraph): string
  407. {
  408. $text = implode(' ', array_map(
  409. fn ($s) => (string) preg_replace('/\[\^\d+\]/', '', (preg_split('/\n\n(?=\[\^\d+\]: )/', $s['html']) ?: [''])[0]),
  410. $paragraph['sentences'] ?? [],
  411. ));
  412. return trim((string) preg_replace('/[*_`#]+|\s+/u', ' ', $text));
  413. }
  414. private function escapeLink(string $text): string
  415. {
  416. return str_replace(['[', ']'], ['\\[', '\\]'], $text);
  417. }
  418. // ── pandoc ──────────────────────────────────────────────────────────
  419. /**
  420. * 整部作品拼成一篇 markdown,交给 pandoc 转 epub / docx,返回生成的临时文件路径。
  421. *
  422. * @param array<string, mixed> $context
  423. * @param array<string, mixed> $work
  424. * @param list<array<string, mixed>> $paragraphs
  425. */
  426. private function pandoc(string $dir, int $index, string $format, array $context, array $work, array $paragraphs): string
  427. {
  428. $chapters = $this->chapters($work, $paragraphs);
  429. $source = '';
  430. foreach ($chapters as $chapter) {
  431. // 第 0 章(序言)没有自己的标题段,补一个,epub 目录里才有它
  432. $first = $chapter['paragraphs'][0];
  433. $needsTitle = $first['level'] !== $chapter['level'] && $chapter['level'] !== 99;
  434. $source .= ($needsTitle ? '# '.$chapter['title']."\n\n" : '').$this->markdown($chapter['paragraphs'], $chapter['level'])."\n";
  435. }
  436. $input = $this->writeFile($dir, "w{$index}.md", $source === '' ? "\n" : $source);
  437. $output = "{$dir}/w{$index}.{$format}";
  438. $command = [
  439. (string) config('mint.tipitaka_export.pandoc'),
  440. $input,
  441. // 译文里的 $、~、^ 与 --- 不是数学公式 / 上下标 / 元数据块
  442. '--from=markdown+east_asian_line_breaks-tex_math_dollars-raw_tex-subscript-superscript-yaml_metadata_block',
  443. '--output='.$output,
  444. '--toc',
  445. '--toc-depth=2',
  446. '--metadata=title:'.$work['local_title'],
  447. '--metadata=subtitle:'.$work['title'],
  448. '--metadata=author:'.$context['name'],
  449. '--metadata=lang:'.$context['lang'],
  450. '--metadata=date:'.$context['generated_at'],
  451. ];
  452. if ($format === 'epub') {
  453. $command[] = '--css='.resource_path('template/epub/tipitaka.css');
  454. $command[] = '--split-level=1';
  455. } else {
  456. $command[] = '--reference-doc='.resource_path('template/docx/paper.docx');
  457. }
  458. $process = new Process($command, $dir, null, null, (float) config('mint.tipitaka_export.pandoc_timeout'));
  459. $process->run();
  460. if (! $process->isSuccessful()) {
  461. throw new RuntimeException('pandoc failed: '.mb_substr($process->getErrorOutput(), 0, 2000));
  462. }
  463. return $output;
  464. }
  465. // ── offline ─────────────────────────────────────────────────────────
  466. /**
  467. * mobile 离线包:NDJSON,首行头、每段一行、末行 end(客户端用 count 校验完整)。
  468. * 存的是 gzip 后的字节,下载接口以 `Content-Encoding: gzip` 发出。
  469. * `html` 与 `/v3/tipitaka-reading?format=html&include=display` 的 display 完全相同。
  470. *
  471. * @param array<string, mixed> $status
  472. * @param array<string, mixed> $work
  473. * @param callable(float): void $tick
  474. */
  475. private function offline(string $dir, array $status, array $work, callable $tick): string
  476. {
  477. $paragraphs = $this->paragraphs($status['channel'], $work, 'html', $tick);
  478. $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
  479. $lines = [json_encode([
  480. 'type' => 'header',
  481. 'format' => 1,
  482. 'id' => $status['id'],
  483. 'channel' => $status['channel'],
  484. 'sn' => $work['sn'],
  485. 'book' => $work['book'],
  486. 'para' => $work['para'],
  487. 'end' => $work['end'],
  488. 'paragraphs' => count($paragraphs),
  489. ], $flags)];
  490. foreach ($paragraphs as $p) {
  491. $lines[] = json_encode(['type' => 'para', 'book' => $work['book'], 'para' => $p['para'], 'html' => $p['display']], $flags);
  492. }
  493. $lines[] = json_encode(['type' => 'end', 'count' => count($paragraphs)], $flags);
  494. return $this->writeFile($dir, 'offline.ndjson.gz', (string) gzencode(implode("\n", $lines)."\n", 6));
  495. }
  496. // ── files ───────────────────────────────────────────────────────────
  497. private function writeFile(string $dir, string $name, string $content): string
  498. {
  499. $path = "{$dir}/{$name}";
  500. file_put_contents($path, $content);
  501. return $path;
  502. }
  503. /**
  504. * 把临时文件按条目名打成 zip,返回 zip 字节。条目名按 UTF-8 标记,中文文件名解压不乱码。
  505. *
  506. * @param array<string, string> $entries zip 里的路径 => 临时文件
  507. */
  508. private function zip(string $dir, array $entries): string
  509. {
  510. $path = "{$dir}/_bundle.zip";
  511. $zip = new ZipArchive;
  512. if ($zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
  513. throw new RuntimeException("cannot create zip {$path}");
  514. }
  515. ksort($entries, SORT_NATURAL);
  516. foreach ($entries as $name => $file) {
  517. $zip->addFile($file, $name, 0, 0, ZipArchive::FL_OVERWRITE | ZipArchive::FL_ENC_UTF_8);
  518. }
  519. $zip->close();
  520. return (string) file_get_contents($path);
  521. }
  522. }