TipitakaExportService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Exceptions\BusinessException;
  4. use App\Facades\RedisCache;
  5. use App\Models\Channel;
  6. use App\Models\Sentence;
  7. use App\Services\TipitakaCatalogService;
  8. use Illuminate\Database\Eloquent\Builder;
  9. use Illuminate\Support\Carbon;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Storage;
  12. use Illuminate\Support\Facades\URL;
  13. use Illuminate\Validation\ValidationException;
  14. use RuntimeException;
  15. use Throwable;
  16. /**
  17. * 三藏下载:把一个 channel 的一部作品、一个分类或整个 channel 导出成文件。
  18. *
  19. * 流程:请求方 request() → 已有同一份文件就直接给;没有就写一条 queued 状态、投递到 RabbitMQ
  20. * (TipitakaExportQueue:单部作品与打包分两个队列)→ worker `mq:export.tipitaka` 调 run() 生成(TipitakaExportBuilder)→
  21. * 文件存进默认磁盘的临时区(生产是 S3),状态存 Redis,保留 `mint.tipitaka_export.ttl`。
  22. *
  23. * **文件路径按范围固定,不跟 id 走**({@see self::filePath()}):同一 channel、同一范围、同一格式永远是同一个对象。
  24. * Redis 状态过期、或译文改了换了 id,重新生成时覆盖原来那份,临时区不会积累没人读的旧文件。
  25. * 旧 id 的下载链接(7 天内)拿到的是覆盖后的最新文件。
  26. *
  27. * **id 就是内容指纹**:channel + 范围 + 格式 + 模板版本 + 范围内句子的最后修改时间与条数。
  28. * 所以谁先生成谁就给后来的人用;译文一改,指纹就变,自然重新生成,不需要失效逻辑。
  29. *
  30. * 格式:html(单部作品一个文件,打包时加 index.html)、markdown(每章一个文件 + 目录)、
  31. * epub / docx(pandoc 生成;单部作品直接给文件,打包时一部一个)、offline(mobile 离线包,
  32. * gzip 的 NDJSON,一行一段,`html` 与 `tipitaka-reading` 的 display 一致;只按作品)。
  33. */
  34. class TipitakaExportService
  35. {
  36. public const FORMATS = ['html', 'markdown', 'epub', 'docx', 'offline'];
  37. /**
  38. * 模板 / 文件结构改了就加一,让已经生成好的旧文件不再命中。
  39. */
  40. public const TEMPLATE_VERSION = 2;
  41. /**
  42. * 范围统计(字数、最后修改时间)缓存多久。整个大 channel 求 max(updated_at) 要两秒,
  43. * 下载页每次打开都算不划算;代价是五分钟内的修改要等缓存过期才会触发重新生成。
  44. */
  45. private const STATS_TTL = 300;
  46. public function __construct(
  47. private readonly TipitakaCatalogService $catalog,
  48. private readonly ChannelAbilityService $abilities,
  49. private readonly TipitakaExportQueue $queue,
  50. private readonly TipitakaExportBuilder $builder,
  51. ) {}
  52. /**
  53. * 发起一次导出。已有可用的文件,或同一份正在生成,就直接返回它的状态,不重复排队。
  54. *
  55. * @param array{channel: string, work?: int, book?: int, para?: int, category?: int, format: string} $input
  56. * @return array<string, mixed> present() 的结果
  57. */
  58. public function request(array $input, ?string $userUid): array
  59. {
  60. $channel = $input['channel'];
  61. $this->abilities->assertReadable($channel, $userUid);
  62. $format = $input['format'];
  63. $work = $input['work'] ?? (isset($input['book']) ? $this->workAt((int) $input['book'], (int) $input['para']) : null);
  64. $scope = $this->scope($channel, $work, $input['category'] ?? null);
  65. if ($format === 'offline' && $scope['kind'] !== 'work') {
  66. throw ValidationException::withMessages(['format' => __('messages.export_offline_work_only')]);
  67. }
  68. $spec = $this->spec($channel, $scope, $format);
  69. $status = $this->find($spec['id']);
  70. if ($status !== null && $this->reusable($status)) {
  71. return $this->present($status);
  72. }
  73. $status = $spec + ['status' => 'queued', 'progress' => 0.0, 'message' => null, 'updated_at' => now()->toIso8601ZuluString()];
  74. $this->save($status);
  75. $this->queue->push($spec['id'], $scope['kind'] !== 'work');
  76. return $this->present($status);
  77. }
  78. /**
  79. * 下载页用:这个范围四种文件格式各自现在的状态,不排队。范围里没有作品时返回 null。
  80. *
  81. * @param array{kind: string, works: list<array<string, mixed>>, title: string, work?: int, category?: int|null} $scope
  82. * @return array<string, array<string, mixed>> 格式 => present()(可下载)或 {id, format, status: absent|stale, filename, too_large}
  83. */
  84. public function describe(string $channel, array $scope, ?string $userUid): array
  85. {
  86. $this->abilities->assertReadable($channel, $userUid);
  87. $formats = array_values(array_filter(self::FORMATS, fn ($f) => $f !== 'offline'));
  88. $result = [];
  89. foreach ($formats as $format) {
  90. $spec = $this->spec($channel, $scope, $format, false);
  91. $status = $this->find($spec['id']);
  92. $result[$format] = $status !== null && $this->reusable($status)
  93. ? $this->present($status)
  94. : [
  95. 'id' => $spec['id'],
  96. 'format' => $format,
  97. // 失败、失联的按「没有」给:页面上都是点一下重新生成
  98. 'status' => in_array($status['status'] ?? null, ['queued', 'running'], true) ? 'stale' : 'absent',
  99. 'filename' => $spec['filename'],
  100. 'too_large' => $spec['too_large'],
  101. ];
  102. }
  103. return $result;
  104. }
  105. /**
  106. * 查一次导出的状态。不存在(或已过期)404。看不见那个 channel 403。
  107. *
  108. * @return array<string, mixed> present() 的结果
  109. */
  110. public function show(string $id, ?string $userUid): array
  111. {
  112. $status = $this->find($id);
  113. if ($status === null) {
  114. abort(404, __('messages.export_not_found'));
  115. }
  116. $this->abilities->assertReadable($status['channel'], $userUid);
  117. if ($status['status'] === 'ready' && ! $this->fileExists($status)) {
  118. // 文件被清掉了,状态还在:当作没生成过,让客户端重新发起
  119. abort(404, __('messages.export_not_found'));
  120. }
  121. return $this->present($status);
  122. }
  123. /**
  124. * 按 work / category 解析导出范围:哪些作品、叫什么名字。
  125. *
  126. * - 给 work:那一部作品,该 channel 没有收录它就 404
  127. * - 给 category:分类(含后代)下该 channel 收录的作品
  128. * - 都不给:该 channel 收录的全部作品
  129. *
  130. * @return array{kind: string, works: list<array<string, mixed>>, title: string, work?: int, category?: int|null}
  131. */
  132. public function scope(string $channel, ?int $work, ?int $category): array
  133. {
  134. $progress = $this->catalog->channelProgress($channel);
  135. $withTitle = function (array $w) use ($progress): array {
  136. $row = $progress["{$w['book']}-{$w['para']}"] ?? null;
  137. return $w + [
  138. 'local_title' => ! empty($row['title']) ? $row['title'] : $w['title'],
  139. 'progress' => $row ? (float) $row['progress'] : 0.0,
  140. ];
  141. };
  142. $included = fn (array $w): bool => isset($progress["{$w['book']}-{$w['para']}"]);
  143. if ($work !== null) {
  144. $found = $this->catalog->work($work);
  145. if (! $found || ! $included($found)) {
  146. abort(404, __('site.not_found'));
  147. }
  148. $item = $withTitle($found);
  149. return ['kind' => 'work', 'work' => $work, 'works' => [$item], 'title' => $item['local_title']];
  150. }
  151. if ($category !== null) {
  152. $node = $this->catalog->category($category);
  153. if (! $node) {
  154. abort(404, __('site.not_found'));
  155. }
  156. $works = array_values(array_map($withTitle, array_filter($this->catalog->worksInCategory($category), $included)));
  157. $title = $this->catalog->localNames([$node], TipitakaExportBuilder::locale($this->channelLang($channel)))[$node['name']] ?? $node['name'];
  158. $kind = 'category';
  159. } else {
  160. $works = array_values(array_map($withTitle, array_filter($this->catalog->works(), $included)));
  161. $title = (string) Channel::where('uid', $channel)->value('name');
  162. $kind = 'channel';
  163. }
  164. if ($works === []) {
  165. abort(404, __('site.not_found'));
  166. }
  167. // 分类 id 是分类树深度优先的流水号:按它排,同一分类的作品挨在一起,律 → 经 → 论 → 藏外
  168. usort($works, fn ($a, $b) => [$a['category_id'] ?? PHP_INT_MAX, $a['sn']] <=> [$b['category_id'] ?? PHP_INT_MAX, $b['sn']]);
  169. return ['kind' => $kind, 'category' => $category, 'works' => $works, 'title' => $title];
  170. }
  171. /**
  172. * 段落所在作品的 sn。不在任何作品里 404。
  173. */
  174. private function workAt(int $book, int $para): int
  175. {
  176. $work = $this->catalog->workAt($book, $para);
  177. if ($work === null) {
  178. abort(404, __('site.not_found'));
  179. }
  180. return $work['sn'];
  181. }
  182. /**
  183. * worker 入口:生成一份导出,文件存进临时区、状态存 Redis。已经生成好、或状态已过期被清掉的直接跳过。
  184. */
  185. public function run(string $id): void
  186. {
  187. $status = $this->find($id);
  188. if ($status === null || ($status['status'] === 'ready' && $this->fileExists($status))) {
  189. return;
  190. }
  191. $status = $this->save(['status' => 'running', 'progress' => 0.0, 'message' => null] + $status);
  192. $started = microtime(true);
  193. try {
  194. $scope = $this->scope($status['channel'], $status['scope']['work'] ?? null, $status['scope']['category'] ?? null);
  195. $file = $this->builder->build($status, $scope, function (float $progress, string $message) use (&$status): void {
  196. $status = $this->save(['progress' => round($progress, 3), 'message' => $message] + $status);
  197. });
  198. $maxBytes = (int) config('mint.tipitaka_export.max_file_bytes');
  199. if (strlen($file) > $maxBytes) {
  200. throw new BusinessException(__('messages.export_too_large'), 422, 'export-too-large');
  201. }
  202. $ttl = (int) config('mint.tipitaka_export.ttl');
  203. // S3 上把类型与传输编码写进对象:下载时直接跳到 S3,离线包靠 Content-Encoding: gzip 让客户端自动解压
  204. $stored = Storage::put($this->filePath($status), $file, array_filter([
  205. 'ContentType' => $status['content_type'],
  206. 'ContentEncoding' => $status['format'] === 'offline' ? 'gzip' : null,
  207. ]));
  208. if (! $stored) {
  209. throw new RuntimeException('tipitaka-export: cannot store '.$this->filePath($status));
  210. }
  211. $this->save([
  212. 'status' => 'ready',
  213. 'progress' => 1.0,
  214. 'message' => null,
  215. 'size' => strlen($file),
  216. 'ready_at' => now()->toIso8601ZuluString(),
  217. 'expires_at' => now()->addSeconds($ttl)->toIso8601ZuluString(),
  218. ] + $status, $ttl);
  219. Log::info('tipitaka-export: ready', ['id' => $id, 'format' => $status['format'], 'scope' => $status['scope'], 'bytes' => strlen($file), 'seconds' => round(microtime(true) - $started, 1)]);
  220. } catch (Throwable $e) {
  221. $this->save(['status' => 'failed', 'message' => $e instanceof BusinessException ? $e->getMessage() : __('messages.export_failed')] + $status);
  222. Log::error('tipitaka-export: failed', ['id' => $id, 'exception' => $e]);
  223. }
  224. }
  225. /**
  226. * 文件在默认磁盘上的路径(临时区):`{temporary}/tipitaka-exports/{channel}/{format}/{work-sn | category-id | channel}`。
  227. * 只由 channel、范围、格式决定,与内容指纹(id)、模板版本无关,重新生成时覆盖同一个对象。
  228. *
  229. * @param array<string, mixed> $status 导出状态(spec() 的字段)
  230. */
  231. public function filePath(array $status): string
  232. {
  233. $scope = match ($status['scope']['kind']) {
  234. 'work' => 'work-'.$status['scope']['work'],
  235. 'category' => 'category-'.$status['scope']['category'],
  236. default => 'channel',
  237. };
  238. return config('mint.attachments.bucket_name.temporary')."/tipitaka-exports/{$status['channel']}/{$status['format']}/{$scope}";
  239. }
  240. /**
  241. * 已生成的文件的元数据;没有(或不可下载)返回 null。
  242. *
  243. * @return array{path: string, filename: string, content_type: string, content_encoding: string|null, size: int}|null
  244. */
  245. public function file(string $id): ?array
  246. {
  247. $status = $this->find($id);
  248. if ($status === null || $status['status'] !== 'ready' || ! $this->fileExists($status)) {
  249. return null;
  250. }
  251. $path = $this->filePath($status);
  252. return [
  253. 'path' => $path,
  254. 'filename' => $status['filename'],
  255. 'content_type' => $status['content_type'],
  256. 'content_encoding' => $status['format'] === 'offline' ? 'gzip' : null,
  257. // 按文件实际大小:这个范围后来又生成过的话,旧 id 的状态里记的是旧文件的大小
  258. 'size' => (int) Storage::size($path),
  259. ];
  260. }
  261. /**
  262. * 导出的不变部分:id(内容指纹)、范围、文件名。超过字数上限时 $strict 抛 422,否则标 too_large。
  263. *
  264. * @param array{kind: string, works: list<array<string, mixed>>, title: string, work?: int, category?: int|null} $scope
  265. * @return array<string, mixed>
  266. */
  267. private function spec(string $channel, array $scope, string $format, bool $strict = true): array
  268. {
  269. $stats = $this->stats($channel, $scope);
  270. $max = (int) config('mint.tipitaka_export.max_source_chars');
  271. $tooLarge = $stats['chars'] > $max;
  272. if ($tooLarge && $strict) {
  273. throw new BusinessException(__('messages.export_too_large'), 422, 'export-too-large', ['chars' => $stats['chars'], 'limit' => $max]);
  274. }
  275. $scopeKey = match ($scope['kind']) {
  276. 'work' => ['kind' => 'work', 'work' => $scope['work']],
  277. 'category' => ['kind' => 'category', 'category' => $scope['category']],
  278. default => ['kind' => 'channel'],
  279. };
  280. $id = sha1(json_encode([$channel, $scopeKey, $format, self::TEMPLATE_VERSION, $stats['updated_at'], $stats['count']]));
  281. $channelName = (string) Channel::where('uid', $channel)->value('name');
  282. [$filename, $contentType] = $this->filename($scope, $format, $channelName);
  283. return [
  284. 'id' => $id,
  285. 'channel' => $channel,
  286. 'scope' => $scopeKey,
  287. 'format' => $format,
  288. 'title' => $scope['title'],
  289. 'works' => count($scope['works']),
  290. 'filename' => $filename,
  291. 'content_type' => $contentType,
  292. 'too_large' => $tooLarge,
  293. ];
  294. }
  295. /**
  296. * 下载时的文件名与 MIME。单部作品的 epub / docx 直接给文件,其余打 zip;离线包是 gzip 的 NDJSON。
  297. *
  298. * @param array{kind: string, works: list<array<string, mixed>>, title: string} $scope
  299. * @return array{string, string}
  300. */
  301. private function filename(array $scope, string $format, string $channelName): array
  302. {
  303. $base = TipitakaExportBuilder::safeName($scope['kind'] === 'channel' ? $channelName : "{$scope['title']}-{$channelName}");
  304. if ($format === 'offline') {
  305. // 存的是 gzip 字节,下载时带 Content-Encoding: gzip:客户端的 HTTP 栈
  306. // (OkHttp / NSURLSession / 浏览器)自己解压,App 不用另装解压库
  307. return ["{$base}.ndjson", 'application/x-ndjson'];
  308. }
  309. if ($scope['kind'] === 'work' && $format === 'epub') {
  310. return ["{$base}.epub", 'application/epub+zip'];
  311. }
  312. if ($scope['kind'] === 'work' && $format === 'docx') {
  313. return ["{$base}.docx", 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
  314. }
  315. return ["{$base}-{$format}.zip", 'application/zip'];
  316. }
  317. /**
  318. * 范围内的句子:条数、字数(strlen 之和)、最后修改时间。指纹与大小上限都靠它。
  319. *
  320. * @param array{kind: string, works: list<array<string, mixed>>} $scope
  321. * @return array{count: int, chars: int, updated_at: string|null}
  322. */
  323. private function stats(string $channel, array $scope): array
  324. {
  325. $key = '/tipitaka-export/stats/'.sha1($channel.'|'.json_encode(array_map(fn ($w) => [$w['book'], $w['para'], $w['end']], $scope['works'])));
  326. return RedisCache::remember($key, self::STATS_TTL, function () use ($channel, $scope) {
  327. $query = Sentence::query()->where('channel_uid', $channel)->where('strlen', '>', 0);
  328. if ($scope['kind'] !== 'channel') {
  329. $query->where(function (Builder $q) use ($scope) {
  330. foreach ($scope['works'] as $work) {
  331. $q->orWhere(fn (Builder $w) => $w->where('book_id', $work['book'])
  332. ->whereBetween('paragraph', [$work['para'], $work['end']]));
  333. }
  334. });
  335. }
  336. $row = $query->selectRaw('count(*) as c, coalesce(sum(strlen), 0) as s, max(updated_at) as m')->first();
  337. return ['count' => (int) $row->c, 'chars' => (int) $row->s, 'updated_at' => $row->m ? (string) $row->m : null];
  338. });
  339. }
  340. /**
  341. * 已完成且文件还在的,或正在排队 / 生成且没有失联的,可以直接给请求方用。失败的允许重试。
  342. *
  343. * @param array<string, mixed> $status
  344. */
  345. private function reusable(array $status): bool
  346. {
  347. return match ($status['status']) {
  348. 'ready' => $this->fileExists($status),
  349. 'queued', 'running' => now()->diffInSeconds($status['updated_at'], true) < (int) config('mint.tipitaka_export.stale_after'),
  350. default => false,
  351. };
  352. }
  353. /**
  354. * 对外的状态:去掉内部字段,ready 时附带签名的下载链接(相对地址,反代下不拼错域名;7 天内有效)。
  355. *
  356. * @param array<string, mixed> $status
  357. * @return array<string, mixed>
  358. */
  359. private function present(array $status): array
  360. {
  361. $ready = $status['status'] === 'ready';
  362. return [
  363. 'id' => $status['id'],
  364. 'status' => $status['status'],
  365. 'format' => $status['format'],
  366. 'progress' => (float) $status['progress'],
  367. 'message' => $status['message'] ?? null,
  368. 'title' => $status['title'],
  369. 'works' => (int) $status['works'],
  370. 'filename' => $status['filename'],
  371. 'content_type' => $status['content_type'],
  372. 'size' => $ready ? (int) $status['size'] : null,
  373. 'ready_at' => $status['ready_at'] ?? null,
  374. 'expires_at' => $status['expires_at'] ?? null,
  375. 'download_url' => $ready ? URL::temporarySignedRoute(
  376. 'v3.tipitaka-exports.file',
  377. Carbon::parse($status['expires_at']),
  378. ['export' => $status['id']],
  379. absolute: false,
  380. ) : null,
  381. ];
  382. }
  383. /**
  384. * @return array<string, mixed>|null
  385. */
  386. private function find(string $id): ?array
  387. {
  388. return RedisCache::get($this->statusKey($id));
  389. }
  390. /**
  391. * 写状态,顺带刷新 updated_at(失联判断看它)。返回写入的值。
  392. *
  393. * @param array<string, mixed> $status
  394. * @return array<string, mixed>
  395. */
  396. private function save(array $status, ?int $ttl = null): array
  397. {
  398. $status['updated_at'] = now()->toIso8601ZuluString();
  399. RedisCache::put($this->statusKey($status['id']), $status, $ttl ?? (int) config('mint.tipitaka_export.ttl'));
  400. return $status;
  401. }
  402. /**
  403. * @param array<string, mixed> $status
  404. */
  405. private function fileExists(array $status): bool
  406. {
  407. return Storage::exists($this->filePath($status));
  408. }
  409. private function statusKey(string $id): string
  410. {
  411. return "/tipitaka-export/status/{$id}";
  412. }
  413. private function channelLang(string $channel): string
  414. {
  415. return (string) (Channel::where('uid', $channel)->value('lang') ?? 'en');
  416. }
  417. }