TipitakaExportV3Test.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. <?php
  2. use App\Facades\RedisCache;
  3. use App\Models\BookTitle;
  4. use App\Models\Channel;
  5. use App\Models\PaliText;
  6. use App\Models\ProgressChapter;
  7. use App\Models\Sentence;
  8. use App\Models\Tag;
  9. use App\Models\TagMap;
  10. use App\Services\V3\TipitakaExportQueue;
  11. use App\Services\V3\TipitakaExportService;
  12. use Illuminate\Foundation\Testing\RefreshDatabase;
  13. use Illuminate\Support\Facades\Storage;
  14. use Illuminate\Support\Str;
  15. /*
  16. | 三藏下载 /v3/tipitaka-exports。这里断言的是形状而非契约(spectator 未安装)。
  17. | 生成在测试里同步调 TipitakaExportService::run(),队列换成 mock,不连 RabbitMQ;
  18. | 文件进的是 Storage::fake() 的默认磁盘(本地磁盘的流式下载);S3 的跳转单独一条测。
  19. */
  20. uses(RefreshDatabase::class);
  21. beforeEach(fn () => Storage::fake());
  22. function exportPaliText(int $book, int $paragraph, int $level, int $chapterLen, string $toc = ''): PaliText
  23. {
  24. $row = new PaliText;
  25. $row->forceFill([
  26. 'book' => $book, 'paragraph' => $paragraph, 'level' => $level, 'class' => '', 'toc' => $toc,
  27. 'text' => '', 'html' => '', 'pcd_book_id' => 0, 'chapter_len' => $chapterLen, 'chapter_strlen' => 100,
  28. 'uid' => (string) Str::uuid(),
  29. ])->save();
  30. return $row;
  31. }
  32. function exportProgress(string $channel, int $book, int $para, float $progress, ?string $title = null): void
  33. {
  34. (new ProgressChapter)->forceFill([
  35. 'id' => random_int(1, PHP_INT_MAX), 'uid' => (string) Str::uuid(), 'book' => $book, 'para' => $para,
  36. 'lang' => 'zh-Hans', 'channel_id' => $channel, 'progress' => $progress, 'title' => $title,
  37. 'all_trans' => 0, 'public' => 0,
  38. ])->save();
  39. }
  40. /**
  41. * 一部作品 sn 9100 = book 9100 的 3–102 段(两章:4、50),归入长部 › 戒蕴品(分类 3)。
  42. * channel 收录了它,有作品标题、两个章标题和带脚注的正文。
  43. *
  44. * @return array{channel: string, owner: string, sn: int}
  45. */
  46. function exportFixture(): array
  47. {
  48. $root = exportPaliText(9100, 3, 1, 100, 'Sīlakkhandhavaggapāḷi');
  49. exportPaliText(9100, 4, 2, 46, '1. Brahmajālasuttaṃ');
  50. exportPaliText(9100, 50, 2, 53, '2. Sāmaññaphalasuttaṃ');
  51. foreach (['sutta', 'dīghanikāya', 'sīlakkhandhavagga', 'pāḷi'] as $name) {
  52. $tag = Tag::where('name', $name)->first();
  53. if (! $tag) {
  54. $tag = new Tag;
  55. $tag->forceFill(['id' => (string) Str::uuid(), 'name' => $name, 'color' => 0, 'owner_id' => (string) Str::uuid()])->save();
  56. }
  57. (new TagMap)->forceFill(['id' => (string) Str::uuid(), 'table_name' => 'pali_texts', 'anchor_id' => $root->uid, 'tag_id' => $tag->id])->save();
  58. }
  59. (new BookTitle)->forceFill(['sn' => 9100, 'book' => 9100, 'paragraph' => 3, 'title' => 'dīghanikāyapāḷi'])->save();
  60. $owner = makeStudio('export-owner');
  61. $channel = makeChannel($owner, 'export channel');
  62. exportProgress($channel, 9100, 3, 0.4, '戒蕴品');
  63. makeSentence($channel, 9100, 3, 1, '戒蕴品');
  64. makeSentence($channel, 9100, 4, 1, '梵网经');
  65. makeSentence($channel, 9100, 5, 1, '如是我闻{{note|第一条注}}。');
  66. makeSentence($channel, 9100, 5, 2, '一时佛住{{note|第二条注}}。');
  67. makeSentence($channel, 9100, 50, 1, '沙门果经');
  68. makeSentence($channel, 9100, 51, 1, '尔时国王{{note|第三条注}}。');
  69. return ['channel' => $channel, 'owner' => $owner, 'sn' => 9100];
  70. }
  71. /**
  72. * 换掉队列,返回收到的 [id, bulk] 列表。
  73. */
  74. function fakeExportQueue(): ArrayObject
  75. {
  76. $pushed = new ArrayObject;
  77. test()->mock(TipitakaExportQueue::class, function ($mock) use ($pushed) {
  78. $mock->shouldReceive('push')->andReturnUsing(function (string $id, bool $bulk) use ($pushed) {
  79. $pushed[] = [$id, $bulk];
  80. });
  81. });
  82. return $pushed;
  83. }
  84. /**
  85. * 发起并同步生成,返回就绪后的 data。
  86. *
  87. * @param array<string, mixed> $body
  88. * @return array<string, mixed>
  89. */
  90. function exportReady(array $body): array
  91. {
  92. $id = test()->postJson('/api/v3/tipitaka-exports', $body)->assertStatus(202)->json('data.id');
  93. app(TipitakaExportService::class)->run($id);
  94. return test()->postJson('/api/v3/tipitaka-exports', $body)->assertOk()->json('data');
  95. }
  96. /**
  97. * zip 字节 → [条目名 => 内容]
  98. *
  99. * @return array<string, string>
  100. */
  101. function unzipExport(string $bytes): array
  102. {
  103. $path = tempnam(sys_get_temp_dir(), 'export');
  104. file_put_contents($path, $bytes);
  105. $zip = new ZipArchive;
  106. $zip->open($path);
  107. $files = [];
  108. for ($i = 0; $i < $zip->numFiles; $i++) {
  109. $files[$zip->getNameIndex($i)] = $zip->getFromIndex($i);
  110. }
  111. $zip->close();
  112. unlink($path);
  113. return $files;
  114. }
  115. it('queues a work export and does not queue the same one twice', function () {
  116. $pushed = fakeExportQueue();
  117. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  118. $response = $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'])
  119. ->assertStatus(202)
  120. ->assertHeader('Retry-After', '2');
  121. expect($response->json('data'))->toMatchArray([
  122. 'status' => 'queued', 'format' => 'html', 'title' => '戒蕴品', 'works' => 1, 'size' => null, 'download_url' => null,
  123. ])->and($response->json('data.id'))->toMatch('/^[0-9a-f]{40}$/')
  124. ->and($response->json('data.filename'))->toBe('戒蕴品-export channel-html.zip');
  125. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'])->assertStatus(202);
  126. expect($pushed->getArrayCopy())->toBe([[$response->json('data.id'), false]]);
  127. });
  128. it('generates an html work export and serves it through the signed link', function () {
  129. fakeExportQueue();
  130. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  131. $data = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'html']);
  132. expect($data['status'])->toBe('ready')
  133. ->and($data['size'])->toBeInt()->toBeGreaterThan(0)
  134. ->and($data['download_url'])->toStartWith("/api/v3/tipitaka-exports/{$data['id']}/file?expires=");
  135. $this->getJson("/api/v3/tipitaka-exports/{$data['id']}")->assertOk()->assertJsonPath('data.status', 'ready');
  136. $file = $this->get($data['download_url'])
  137. ->assertOk()
  138. ->assertHeader('Content-Type', 'application/zip')
  139. ->assertHeader('Accept-Ranges', 'bytes');
  140. expect($file->headers->get('Content-Disposition'))->toContain("filename*=utf-8''");
  141. $bytes = $file->streamedContent();
  142. expect(strlen($bytes))->toBe($data['size']);
  143. $files = unzipExport($bytes);
  144. expect(array_keys($files))->toBe(['戒蕴品.html']);
  145. expect($files['戒蕴品.html'])
  146. ->toContain('<!doctype html>')
  147. ->toContain('梵网经')
  148. ->toContain('如是我闻')
  149. ->toContain('href="#para-4"');
  150. // 断点续传与条件请求
  151. $part = $this->get($data['download_url'], ['Range' => 'bytes=10-19'])->assertStatus(206)
  152. ->assertHeader('Content-Range', "bytes 10-19/{$data['size']}");
  153. expect($part->streamedContent())->toBe(substr($bytes, 10, 10));
  154. $this->get($data['download_url'], ['Range' => 'bytes=999999999-'])->assertStatus(416);
  155. $this->get($data['download_url'], ['If-None-Match' => $file->headers->get('ETag')])->assertStatus(304);
  156. });
  157. it('stores the file in the temporary area and redirects to a signed S3 link when the disk is S3', function () {
  158. config(['filesystems.default' => 's3']);
  159. Storage::fake('s3')->buildTemporaryUrlsUsing(
  160. fn (string $path, DateTimeInterface $expiration, array $options) => "https://s3.test/{$path}?".http_build_query($options)
  161. );
  162. fakeExportQueue();
  163. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  164. $data = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'html']);
  165. $path = config('mint.attachments.bucket_name.temporary')."/tipitaka-exports/{$channel}/html/work-{$sn}";
  166. Storage::disk('s3')->assertExists($path);
  167. expect(Storage::disk('s3')->size($path))->toBe($data['size']);
  168. $location = $this->get($data['download_url'])->assertRedirect()->headers->get('Location');
  169. expect($location)->toStartWith("https://s3.test/{$path}?")
  170. ->and(urldecode($location))->toContain('ResponseContentDisposition=attachment;')->toContain("filename*=utf-8''");
  171. // 文件被生命周期规则清掉了:状态还在也当作没有
  172. Storage::disk('s3')->delete($path);
  173. $this->get($data['download_url'])->assertNotFound();
  174. $this->getJson("/api/v3/tipitaka-exports/{$data['id']}")->assertNotFound();
  175. });
  176. it('regenerates into the same file once the status expires or the translation changes', function () {
  177. fakeExportQueue();
  178. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  179. $path = config('mint.attachments.bucket_name.temporary')."/tipitaka-exports/{$channel}/html/work-{$sn}";
  180. $first = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'html']);
  181. expect(Storage::files(dirname($path)))->toBe([$path]);
  182. // Redis 里的状态过期:重新生成,同一个 id、同一个文件
  183. RedisCache::forget("/tipitaka-export/status/{$first['id']}");
  184. $again = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'html']);
  185. expect($again['id'])->toBe($first['id'])
  186. ->and(Storage::files(dirname($path)))->toBe([$path]);
  187. // 译文改了:换了 id,仍覆盖同一个文件;旧 id 的链接拿到的是新文件
  188. $sentence = Sentence::where('channel_uid', $channel)->orderBy('paragraph')->first();
  189. // 范围统计(指纹的来源)缓存 5 分钟;指纹看 max(updated_at),改动要晚于建好的数据
  190. $this->travel(6)->minutes();
  191. $sentence->forceFill(['content' => '改过的译文', 'strlen' => 5])->save();
  192. $changed = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'html']);
  193. expect($changed['id'])->not->toBe($first['id'])
  194. ->and(Storage::files(dirname($path)))->toBe([$path]);
  195. $files = unzipExport($this->get($first['download_url'])->assertOk()->streamedContent());
  196. expect(array_values($files)[0])->toContain('改过的译文');
  197. });
  198. it('rejects the file link without a valid signature', function () {
  199. fakeExportQueue();
  200. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  201. $data = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'html']);
  202. $this->get("/api/v3/tipitaka-exports/{$data['id']}/file")->assertForbidden();
  203. $this->get($data['download_url'].'0')->assertForbidden();
  204. });
  205. it('splits markdown by chapter and renumbers footnotes per file', function () {
  206. fakeExportQueue();
  207. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  208. $data = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'markdown']);
  209. $files = unzipExport($this->get($data['download_url'])->streamedContent());
  210. expect(array_keys($files))->toEqualCanonicalizing(['戒蕴品/01-梵网经.md', '戒蕴品/02-沙门果经.md', '戒蕴品/README.md']);
  211. expect($files['戒蕴品/README.md'])->toContain('# 戒蕴品')->toContain('(<01-梵网经.md>)');
  212. // 两句各自从 [^1] 起编号,合进一章后是 1、2
  213. expect($files['戒蕴品/01-梵网经.md'])
  214. ->toStartWith("# 梵网经\n")
  215. ->toContain('如是我闻[^1]')
  216. ->toContain('一时佛住[^2]')
  217. ->toContain('[^1]: 第一条注')
  218. ->toContain('[^2]: 第二条注');
  219. expect($files['戒蕴品/02-沙门果经.md'])->toContain('尔时国王[^1]')->toContain('[^1]: 第三条注');
  220. });
  221. it('gives single-work epub and docx as the file itself', function (string $format, string $type, string $magic) {
  222. fakeExportQueue();
  223. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  224. $data = exportReady(['channel' => $channel, 'work' => $sn, 'format' => $format]);
  225. expect($data['filename'])->toBe("戒蕴品-export channel.{$format}")
  226. ->and($data['content_type'])->toBe($type);
  227. $bytes = $this->get($data['download_url'])->assertOk()->assertHeader('Content-Type', $type)->streamedContent();
  228. // epub 与 docx 本身都是 zip 容器
  229. expect(substr($bytes, 0, 2))->toBe($magic);
  230. })->with([
  231. 'epub' => ['epub', 'application/epub+zip', 'PK'],
  232. 'docx' => ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'PK'],
  233. ])->skip(fn () => trim((string) shell_exec('command -v pandoc')) === '', 'pandoc 不可用');
  234. it('builds the mobile offline package as gzip-encoded ndjson, only per work', function () {
  235. fakeExportQueue();
  236. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  237. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'format' => 'offline'])
  238. ->assertStatus(422)
  239. ->assertJsonValidationErrors('format');
  240. $data = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'offline']);
  241. expect($data['content_type'])->toBe('application/x-ndjson')
  242. ->and($data['filename'])->toBe('戒蕴品-export channel.ndjson');
  243. $file = $this->get($data['download_url'])
  244. ->assertHeader('Content-Type', 'application/x-ndjson')
  245. ->assertHeader('Content-Encoding', 'gzip');
  246. $lines = array_map(fn ($l) => json_decode($l, true), explode("\n", trim(gzdecode($file->streamedContent()))));
  247. expect($lines[0])->toMatchArray(['type' => 'header', 'format' => 1, 'id' => $data['id'], 'channel' => $channel, 'sn' => $sn, 'book' => 9100, 'para' => 3, 'paragraphs' => 5])
  248. ->and(end($lines))->toBe(['type' => 'end', 'count' => 5])
  249. ->and($lines[1])->toMatchArray(['type' => 'para', 'book' => 9100, 'para' => 3]);
  250. // 与阅读接口的 display 一字不差
  251. $display = $this->getJson("/api/v3/tipitaka-reading/{$channel}?book=9100&para=5")->json('data.0.display');
  252. expect(collect($lines)->firstWhere('para', 5)['html'])->toBe($display);
  253. });
  254. it('bundles the whole channel with an index page on the bulk queue', function () {
  255. $pushed = fakeExportQueue();
  256. ['channel' => $channel] = exportFixture();
  257. $data = exportReady(['channel' => $channel, 'format' => 'html']);
  258. expect($pushed[0][1])->toBeTrue()
  259. ->and($data['filename'])->toBe('export channel-html.zip');
  260. $files = unzipExport($this->get($data['download_url'])->streamedContent());
  261. expect(array_keys($files))->toEqualCanonicalizing(['export channel-html/index.html', 'export channel-html/works/9100-戒蕴品.html']);
  262. expect($files['export channel-html/index.html'])->toContain('href="works/9100-%E6%88%92%E8%95%B4%E5%93%81.html"')->toContain('data-q');
  263. expect($files['export channel-html/works/9100-戒蕴品.html'])->toContain('href="../index.html"');
  264. });
  265. it('keeps private channels to people who can read them', function () {
  266. $pushed = fakeExportQueue();
  267. ['channel' => $channel, 'owner' => $owner, 'sn' => $sn] = exportFixture();
  268. Channel::where('uid', $channel)->update(['status' => 10]);
  269. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'])->assertForbidden();
  270. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'], authHeader(makeStudio('stranger')))->assertForbidden();
  271. $id = $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'], authHeader($owner))
  272. ->assertStatus(202)->json('data.id');
  273. // 状态也只给看得见的人
  274. $this->getJson("/api/v3/tipitaka-exports/{$id}")->assertForbidden();
  275. $this->getJson("/api/v3/tipitaka-exports/{$id}", authHeader($owner))->assertOk();
  276. expect($pushed)->toHaveCount(1);
  277. });
  278. it('validates the request', function () {
  279. fakeExportQueue();
  280. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  281. $this->postJson('/api/v3/tipitaka-exports', [])->assertStatus(422)->assertJsonValidationErrors(['channel', 'format']);
  282. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'format' => 'pdf'])->assertStatus(422)->assertJsonValidationErrors('format');
  283. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'category' => 3, 'format' => 'html'])
  284. ->assertStatus(422)->assertJsonValidationErrors('work');
  285. // 没有收录的作品、不存在的 channel
  286. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => 1, 'format' => 'html'])->assertNotFound();
  287. $this->postJson('/api/v3/tipitaka-exports', ['channel' => (string) Str::uuid(), 'work' => $sn, 'format' => 'html'])->assertNotFound();
  288. $this->getJson('/api/v3/tipitaka-exports/'.str_repeat('a', 40))->assertNotFound();
  289. });
  290. it('refuses selections larger than the limit', function () {
  291. $pushed = fakeExportQueue();
  292. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  293. config(['mint.tipitaka_export.max_source_chars' => 5]);
  294. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'])
  295. ->assertStatus(422)
  296. ->assertJsonPath('type', fn ($type) => str_ends_with($type, 'export-too-large'));
  297. expect($pushed)->toHaveCount(0);
  298. });
  299. it('marks the export failed when the file is too big, and retries on the next request', function () {
  300. $pushed = fakeExportQueue();
  301. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  302. config(['mint.tipitaka_export.max_file_bytes' => 10]);
  303. $id = $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'])->json('data.id');
  304. app(TipitakaExportService::class)->run($id);
  305. $this->getJson("/api/v3/tipitaka-exports/{$id}")->assertOk()->assertJsonPath('data.status', 'failed');
  306. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'])
  307. ->assertStatus(202)->assertJsonPath('data.status', 'queued');
  308. expect($pushed)->toHaveCount(2);
  309. });
  310. it('shows the library download pages', function () {
  311. fakeExportQueue();
  312. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  313. exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'epub']);
  314. $this->get("/library/tipitaka/channels/{$channel}/work/{$sn}")
  315. ->assertOk()
  316. ->assertSee("/library/tipitaka/channels/{$channel}/work/{$sn}/download", false);
  317. $page = $this->get("/library/tipitaka/channels/{$channel}/work/{$sn}/download")->assertOk();
  318. $page->assertSee('data-format="epub"', false)
  319. ->assertSee('data-format="markdown"', false)
  320. ->assertDontSee('data-format="offline"', false)
  321. ->assertSee('/api/v3/tipitaka-exports/', false);
  322. expect(substr_count($page->getContent(), 'data-state="ready"'))->toBe(1);
  323. $this->get("/library/tipitaka/channels/{$channel}/download")->assertOk()->assertSee('戒蕴品');
  324. // 打包只有「全部」,没有按藏 / 分类的切换
  325. $this->get("/library/tipitaka/channels/{$channel}/download")->assertDontSee('tipitaka-pill', false);
  326. $this->get("/library/tipitaka/channels/{$channel}/work/1/download")->assertNotFound();
  327. })->skip(fn () => ! file_exists(public_path('build/manifest.json')), '需要先 npm run build');
  328. it('finds the work by book and paragraph for clients that only know coordinates', function () {
  329. fakeExportQueue();
  330. ['channel' => $channel, 'sn' => $sn] = exportFixture();
  331. $bySn = $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'offline'])->json('data.id');
  332. // 作品里的任一段都指向同一份(id 相同)
  333. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'book' => 9100, 'para' => 51, 'format' => 'offline'])
  334. ->assertStatus(202)
  335. ->assertJsonPath('data.id', $bySn);
  336. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'book' => 9100, 'format' => 'offline'])
  337. ->assertStatus(422)->assertJsonValidationErrors('para');
  338. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'book' => 9100, 'para' => 3, 'work' => $sn, 'format' => 'offline'])
  339. ->assertStatus(422)->assertJsonValidationErrors('work');
  340. // 不在任何作品里的段
  341. $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'book' => 9100, 'para' => 999, 'format' => 'offline'])->assertNotFound();
  342. });