WebfingerService.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Services;
  3. use Cache;
  4. use App\Profile;
  5. use App\Util\Webfinger\WebfingerUrl;
  6. use Illuminate\Support\Facades\Http;
  7. use App\Util\ActivityPub\Helpers;
  8. use App\Services\AccountService;
  9. class WebfingerService
  10. {
  11. public static function lookup($query, $mastodonMode = false)
  12. {
  13. return (new self)->run($query, $mastodonMode);
  14. }
  15. protected function run($query, $mastodonMode)
  16. {
  17. if($profile = Profile::whereUsername($query)->first()) {
  18. return $mastodonMode ?
  19. AccountService::getMastodon($profile->id, true) :
  20. AccountService::get($profile->id);
  21. }
  22. $url = WebfingerUrl::generateWebfingerUrl($query);
  23. if(!Helpers::validateUrl($url)) {
  24. return [];
  25. }
  26. try {
  27. $res = Http::retry(3, 100)
  28. ->acceptJson()
  29. ->withHeaders([
  30. 'User-Agent' => '(Pixelfed/' . config('pixelfed.version') . '; +' . config('app.url') . ')'
  31. ])
  32. ->timeout(20)
  33. ->get($url);
  34. } catch (\Illuminate\Http\Client\ConnectionException $e) {
  35. return [];
  36. }
  37. if(!$res->successful()) {
  38. return [];
  39. }
  40. $webfinger = $res->json();
  41. if(!isset($webfinger['links']) || !is_array($webfinger['links']) || empty($webfinger['links'])) {
  42. return [];
  43. }
  44. $link = collect($webfinger['links'])
  45. ->filter(function($link) {
  46. return $link &&
  47. isset($link['rel'], $link['type'], $link['href']) &&
  48. $link['rel'] === 'self' &&
  49. in_array($link['type'], ['application/activity+json','application/ld+json; profile="https://www.w3.org/ns/activitystreams"']);
  50. })
  51. ->pluck('href')
  52. ->first();
  53. $profile = Helpers::profileFetch($link);
  54. if(!$profile) {
  55. return;
  56. }
  57. return $mastodonMode ?
  58. AccountService::getMastodon($profile->id, true) :
  59. AccountService::get($profile->id);
  60. }
  61. }