FetchCacheService.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Services;
  3. use App\Util\ActivityPub\Helpers;
  4. use Illuminate\Http\Client\ConnectionException;
  5. use Illuminate\Http\Client\RequestException;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\Http;
  8. class FetchCacheService
  9. {
  10. const CACHE_KEY = 'pf:fetch_cache_service:getjson:';
  11. public static function getJson($url, $verifyCheck = true, $ttl = 3600, $allowRedirects = true)
  12. {
  13. $vc = $verifyCheck ? 'vc1:' : 'vc0:';
  14. $ar = $allowRedirects ? 'ar1:' : 'ar0';
  15. $key = self::CACHE_KEY.sha1($url).':'.$vc.$ar.$ttl;
  16. if (Cache::has($key)) {
  17. return false;
  18. }
  19. if ($verifyCheck) {
  20. if (! Helpers::validateUrl($url)) {
  21. Cache::put($key, 1, $ttl);
  22. return false;
  23. }
  24. }
  25. $headers = [
  26. 'User-Agent' => '(Pixelfed/'.config('pixelfed.version').'; +'.config('app.url').')',
  27. ];
  28. if ($allowRedirects) {
  29. $options = [
  30. 'allow_redirects' => [
  31. 'max' => 2,
  32. 'strict' => true,
  33. ],
  34. ];
  35. } else {
  36. $options = [
  37. 'allow_redirects' => false,
  38. ];
  39. }
  40. try {
  41. $res = Http::withOptions($options)
  42. ->retry(3, function (int $attempt, $exception) {
  43. return $attempt * 500;
  44. })
  45. ->acceptJson()
  46. ->withHeaders($headers)
  47. ->timeout(40)
  48. ->get($url);
  49. } catch (RequestException $e) {
  50. Cache::put($key, 1, $ttl);
  51. return false;
  52. } catch (ConnectionException $e) {
  53. Cache::put($key, 1, $ttl);
  54. return false;
  55. } catch (Exception $e) {
  56. Cache::put($key, 1, $ttl);
  57. return false;
  58. }
  59. if (! $res->ok()) {
  60. Cache::put($key, 1, $ttl);
  61. return false;
  62. }
  63. return $res->json();
  64. }
  65. }