FileService.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service;
  4. use Hyperf\Redis\Redis;
  5. class FileService
  6. {
  7. private Redis $redis;
  8. private string $cachePrefix = 'file_cache:';
  9. private int $cacheExpire = 3600; // 1小时缓存
  10. public function __construct(Redis $redis)
  11. {
  12. $this->redis = $redis;
  13. }
  14. public function getCachedFile(string $url): ?string
  15. {
  16. $cacheKey = $this->cachePrefix . md5($url);
  17. $result = $this->redis->get($cacheKey);
  18. return $result === false ? null : $result;
  19. }
  20. public function cacheFile(string $url, string $content): void
  21. {
  22. $cacheKey = $this->cachePrefix . md5($url);
  23. $this->redis->setex($cacheKey, $this->cacheExpire, $content);
  24. }
  25. public function downloadWithProgress(string $url, callable $progressCallback = null): string|false
  26. {
  27. $ch = curl_init();
  28. curl_setopt_array($ch, [
  29. CURLOPT_URL => $url,
  30. CURLOPT_RETURNTRANSFER => true,
  31. CURLOPT_TIMEOUT => 120,
  32. CURLOPT_CONNECTTIMEOUT => 30,
  33. CURLOPT_FOLLOWLOCATION => true,
  34. CURLOPT_MAXREDIRS => 5,
  35. CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
  36. CURLOPT_SSL_VERIFYPEER => false,
  37. CURLOPT_SSL_VERIFYHOST => false,
  38. CURLOPT_ENCODING => '',
  39. CURLOPT_NOPROGRESS => false,
  40. CURLOPT_PROGRESSFUNCTION => $progressCallback
  41. ]);
  42. $content = curl_exec($ch);
  43. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  44. curl_close($ch);
  45. if ($content === false || $httpCode !== 200) {
  46. return false;
  47. }
  48. return $content;
  49. }
  50. }