TipitakaExportDownload.php 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. namespace App\Services\V3;
  3. use Illuminate\Support\Facades\Storage;
  4. use Symfony\Component\HttpFoundation\HeaderUtils;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpFoundation\StreamedResponse;
  7. /**
  8. * 把临时区里的导出文件交给客户端。
  9. *
  10. * - 默认磁盘是 S3(生产):302 跳到 S3 的临时签名链接,流量不经 PHP;文件名由链接参数给,
  11. * 类型与离线包的 `Content-Encoding: gzip` 已写在对象上,`Range` / `If-None-Match` 由 S3 处理。
  12. * - 其他磁盘(本地开发):自己流式读,按 1MB 分块,不把整个文件读进内存;
  13. * 支持单段 `Range`(mobile 断点续传)与 `If-None-Match`。ETag 按文件的大小与修改时间算,不用导出 id:
  14. * 同一范围重新生成会覆盖同一个文件,旧 id 的链接拿到的是新文件。
  15. */
  16. class TipitakaExportDownload
  17. {
  18. private const CHUNK = 1024 * 1024;
  19. /** 跳去 S3 的签名链接有效多久(秒)。每次下载现签;给慢速网络下的大文件留足时间。 */
  20. private const REDIRECT_TTL = 3600;
  21. public function __construct(private readonly TipitakaExportService $exports) {}
  22. public function respond(string $id, ?string $range, ?string $ifNoneMatch): Response
  23. {
  24. $file = $this->exports->file($id);
  25. if ($file === null) {
  26. abort(404, __('messages.export_not_found'));
  27. }
  28. $disposition = HeaderUtils::makeDisposition(
  29. HeaderUtils::DISPOSITION_ATTACHMENT,
  30. $file['filename'],
  31. $this->asciiFallback($file['filename']),
  32. );
  33. if (config('filesystems.disks.'.config('filesystems.default').'.driver') === 's3') {
  34. return redirect()->away(Storage::temporaryUrl($file['path'], now()->addSeconds(self::REDIRECT_TTL), [
  35. 'ResponseContentDisposition' => $disposition,
  36. ]));
  37. }
  38. $etag = '"'.$file['size'].'-'.Storage::lastModified($file['path']).'"';
  39. $headers = [
  40. 'Content-Type' => $file['content_type'],
  41. 'Content-Disposition' => $disposition,
  42. 'Accept-Ranges' => 'bytes',
  43. 'ETag' => $etag,
  44. 'Cache-Control' => 'private, max-age=0, must-revalidate',
  45. ];
  46. if ($file['content_encoding'] !== null) {
  47. // 离线包:表示是 NDJSON,传输编码 gzip。Range / Content-Length 都按 gzip 后的字节算
  48. $headers['Content-Encoding'] = $file['content_encoding'];
  49. $headers['Vary'] = 'Accept-Encoding';
  50. }
  51. if ($ifNoneMatch !== null && in_array($etag, array_map('trim', explode(',', $ifNoneMatch)), true)) {
  52. return new Response('', 304, $headers);
  53. }
  54. $size = $file['size'];
  55. [$start, $end] = [0, $size - 1];
  56. $status = 200;
  57. if ($range !== null && preg_match('/^bytes=(\d*)-(\d*)$/', trim($range), $m) && ($m[1] !== '' || $m[2] !== '')) {
  58. if ($m[1] === '') {
  59. // bytes=-500:最后 500 字节
  60. $start = max(0, $size - (int) $m[2]);
  61. } else {
  62. $start = (int) $m[1];
  63. $end = $m[2] === '' ? $size - 1 : min($size - 1, (int) $m[2]);
  64. }
  65. if ($start > $end || $start >= $size) {
  66. return new Response('', 416, $headers + ['Content-Range' => "bytes */{$size}"]);
  67. }
  68. $status = 206;
  69. $headers['Content-Range'] = "bytes {$start}-{$end}/{$size}";
  70. }
  71. $headers['Content-Length'] = (string) ($end - $start + 1);
  72. $path = $file['path'];
  73. return new StreamedResponse(function () use ($path, $start, $end) {
  74. $stream = Storage::readStream($path);
  75. if ($stream === null) {
  76. return;
  77. }
  78. fseek($stream, $start);
  79. $remaining = $end - $start + 1;
  80. while ($remaining > 0 && ! feof($stream)) {
  81. $chunk = fread($stream, min(self::CHUNK, $remaining));
  82. if ($chunk === false || $chunk === '') {
  83. break;
  84. }
  85. echo $chunk;
  86. flush();
  87. $remaining -= strlen($chunk);
  88. }
  89. fclose($stream);
  90. }, $status, $headers);
  91. }
  92. /**
  93. * Content-Disposition 的 filename= 只能是 ASCII,中文名放在 filename*= 里。
  94. */
  95. private function asciiFallback(string $filename): string
  96. {
  97. $ascii = (string) preg_replace('/[^\x20-\x7e]+/', '_', $filename);
  98. $ascii = str_replace(['"', '\\', '/', '%'], '_', $ascii);
  99. return trim($ascii, '_ ') === '' || str_starts_with($ascii, '_.') ? 'tipitaka'.strrchr($filename, '.') : $ascii;
  100. }
  101. }