Helpers.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. <?php
  2. namespace App\Util\ActivityPub;
  3. use DB, Cache, Purify, Storage, Request, Validator;
  4. use App\{
  5. Activity,
  6. Follower,
  7. Instance,
  8. Like,
  9. Media,
  10. Notification,
  11. Profile,
  12. Status
  13. };
  14. use Zttp\Zttp;
  15. use Carbon\Carbon;
  16. use GuzzleHttp\Client;
  17. use Illuminate\Http\File;
  18. use Illuminate\Validation\Rule;
  19. use App\Jobs\AvatarPipeline\CreateAvatar;
  20. use App\Jobs\RemoteFollowPipeline\RemoteFollowImportRecent;
  21. use App\Jobs\ImageOptimizePipeline\{ImageOptimize,ImageThumbnail};
  22. use App\Jobs\StatusPipeline\NewStatusPipeline;
  23. use App\Jobs\StatusPipeline\StatusReplyPipeline;
  24. use App\Jobs\StatusPipeline\StatusTagsPipeline;
  25. use App\Util\ActivityPub\HttpSignature;
  26. use Illuminate\Support\Str;
  27. use App\Services\ActivityPubFetchService;
  28. use App\Services\ActivityPubDeliveryService;
  29. use App\Services\CustomEmojiService;
  30. use App\Services\InstanceService;
  31. use App\Services\MediaPathService;
  32. use App\Services\MediaStorageService;
  33. use App\Jobs\MediaPipeline\MediaStoragePipeline;
  34. use App\Jobs\AvatarPipeline\RemoteAvatarFetch;
  35. use App\Util\Media\License;
  36. use App\Models\Poll;
  37. class Helpers {
  38. public static function validateObject($data)
  39. {
  40. $verbs = ['Create', 'Announce', 'Like', 'Follow', 'Delete', 'Accept', 'Reject', 'Undo', 'Tombstone'];
  41. $valid = Validator::make($data, [
  42. 'type' => [
  43. 'required',
  44. 'string',
  45. Rule::in($verbs)
  46. ],
  47. 'id' => 'required|string',
  48. 'actor' => 'required|string|url',
  49. 'object' => 'required',
  50. 'object.type' => 'required_if:type,Create',
  51. 'object.attributedTo' => 'required_if:type,Create|url',
  52. 'published' => 'required_if:type,Create|date'
  53. ])->passes();
  54. return $valid;
  55. }
  56. public static function verifyAttachments($data)
  57. {
  58. if(!isset($data['object']) || empty($data['object'])) {
  59. $data = ['object'=>$data];
  60. }
  61. $activity = $data['object'];
  62. $mimeTypes = explode(',', config_cache('pixelfed.media_types'));
  63. $mediaTypes = in_array('video/mp4', $mimeTypes) ? ['Document', 'Image', 'Video'] : ['Document', 'Image'];
  64. // Peertube
  65. // $mediaTypes = in_array('video/mp4', $mimeTypes) ? ['Document', 'Image', 'Video', 'Link'] : ['Document', 'Image'];
  66. if(!isset($activity['attachment']) || empty($activity['attachment'])) {
  67. return false;
  68. }
  69. // peertube
  70. // $attachment = is_array($activity['url']) ?
  71. // collect($activity['url'])
  72. // ->filter(function($media) {
  73. // return $media['type'] == 'Link' && $media['mediaType'] == 'video/mp4';
  74. // })
  75. // ->take(1)
  76. // ->values()
  77. // ->toArray()[0] : $activity['attachment'];
  78. $attachment = $activity['attachment'];
  79. $valid = Validator::make($attachment, [
  80. '*.type' => [
  81. 'required',
  82. 'string',
  83. Rule::in($mediaTypes)
  84. ],
  85. '*.url' => 'required|url|max:255',
  86. '*.mediaType' => [
  87. 'required',
  88. 'string',
  89. Rule::in($mimeTypes)
  90. ],
  91. '*.name' => 'sometimes|nullable|string|max:255'
  92. ])->passes();
  93. return $valid;
  94. }
  95. public static function normalizeAudience($data, $localOnly = true)
  96. {
  97. if(!isset($data['to'])) {
  98. return;
  99. }
  100. $audience = [];
  101. $audience['to'] = [];
  102. $audience['cc'] = [];
  103. $scope = 'private';
  104. if(is_array($data['to']) && !empty($data['to'])) {
  105. foreach ($data['to'] as $to) {
  106. if($to == 'https://www.w3.org/ns/activitystreams#Public') {
  107. $scope = 'public';
  108. continue;
  109. }
  110. $url = $localOnly ? self::validateLocalUrl($to) : self::validateUrl($to);
  111. if($url != false) {
  112. array_push($audience['to'], $url);
  113. }
  114. }
  115. }
  116. if(is_array($data['cc']) && !empty($data['cc'])) {
  117. foreach ($data['cc'] as $cc) {
  118. if($cc == 'https://www.w3.org/ns/activitystreams#Public') {
  119. $scope = 'unlisted';
  120. continue;
  121. }
  122. $url = $localOnly ? self::validateLocalUrl($cc) : self::validateUrl($cc);
  123. if($url != false) {
  124. array_push($audience['cc'], $url);
  125. }
  126. }
  127. }
  128. $audience['scope'] = $scope;
  129. return $audience;
  130. }
  131. public static function userInAudience($profile, $data)
  132. {
  133. $audience = self::normalizeAudience($data);
  134. $url = $profile->permalink();
  135. return in_array($url, $audience['to']) || in_array($url, $audience['cc']);
  136. }
  137. public static function validateUrl($url)
  138. {
  139. if(is_array($url)) {
  140. $url = $url[0];
  141. }
  142. $hash = hash('sha256', $url);
  143. $key = "helpers:url:valid:sha256-{$hash}";
  144. $ttl = now()->addMinutes(5);
  145. $valid = Cache::remember($key, $ttl, function() use($url) {
  146. $localhosts = [
  147. '127.0.0.1', 'localhost', '::1'
  148. ];
  149. if(mb_substr($url, 0, 8) !== 'https://') {
  150. return false;
  151. }
  152. $valid = filter_var($url, FILTER_VALIDATE_URL);
  153. if(!$valid) {
  154. return false;
  155. }
  156. $host = parse_url($valid, PHP_URL_HOST);
  157. // if(count(dns_get_record($host, DNS_A | DNS_AAAA)) == 0) {
  158. // return false;
  159. // }
  160. if(config('costar.enabled') == true) {
  161. if(
  162. (config('costar.domain.block') != null && Str::contains($host, config('costar.domain.block')) == true) ||
  163. (config('costar.actor.block') != null && in_array($url, config('costar.actor.block')) == true)
  164. ) {
  165. return false;
  166. }
  167. }
  168. if(app()->environment() === 'production') {
  169. $bannedInstances = InstanceService::getBannedDomains();
  170. if(in_array($host, $bannedInstances)) {
  171. return false;
  172. }
  173. }
  174. if(in_array($host, $localhosts)) {
  175. return false;
  176. }
  177. return $url;
  178. });
  179. return $valid;
  180. }
  181. public static function validateLocalUrl($url)
  182. {
  183. $url = self::validateUrl($url);
  184. if($url == true) {
  185. $domain = config('pixelfed.domain.app');
  186. $host = parse_url($url, PHP_URL_HOST);
  187. $url = $domain === $host ? $url : false;
  188. return $url;
  189. }
  190. return false;
  191. }
  192. public static function zttpUserAgent()
  193. {
  194. $version = config('pixelfed.version');
  195. $url = config('app.url');
  196. return [
  197. 'Accept' => 'application/activity+json',
  198. 'User-Agent' => "(Pixelfed/{$version}; +{$url})",
  199. ];
  200. }
  201. public static function fetchFromUrl($url = false)
  202. {
  203. if(self::validateUrl($url) == false) {
  204. return;
  205. }
  206. $hash = hash('sha256', $url);
  207. $key = "helpers:url:fetcher:sha256-{$hash}";
  208. $ttl = now()->addMinutes(5);
  209. return Cache::remember($key, $ttl, function() use($url) {
  210. $res = ActivityPubFetchService::get($url);
  211. $res = json_decode($res, true, 8);
  212. if(json_last_error() == JSON_ERROR_NONE) {
  213. return $res;
  214. } else {
  215. return false;
  216. }
  217. });
  218. }
  219. public static function fetchProfileFromUrl($url)
  220. {
  221. return self::fetchFromUrl($url);
  222. }
  223. public static function pluckval($val)
  224. {
  225. if(is_string($val)) {
  226. return $val;
  227. }
  228. if(is_array($val)) {
  229. return !empty($val) ? $val[0] : null;
  230. }
  231. return null;
  232. }
  233. public static function statusFirstOrFetch($url, $replyTo = false)
  234. {
  235. $url = self::validateUrl($url);
  236. if($url == false) {
  237. return;
  238. }
  239. $host = parse_url($url, PHP_URL_HOST);
  240. $local = config('pixelfed.domain.app') == $host ? true : false;
  241. if($local) {
  242. $id = (int) last(explode('/', $url));
  243. return Status::whereNotIn('scope', ['draft','archived'])->findOrFail($id);
  244. }
  245. $cached = Status::whereNotIn('scope', ['draft','archived'])
  246. ->whereUri($url)
  247. ->orWhere('object_url', $url)
  248. ->first();
  249. if($cached) {
  250. return $cached;
  251. }
  252. $res = self::fetchFromUrl($url);
  253. if(!$res || empty($res) || isset($res['error']) || !isset($res['@context']) ) {
  254. return;
  255. }
  256. if(isset($res['object'])) {
  257. $activity = $res;
  258. } else {
  259. $activity = ['object' => $res];
  260. }
  261. $scope = 'private';
  262. $cw = isset($res['sensitive']) ? (bool) $res['sensitive'] : false;
  263. if(isset($res['to']) == true) {
  264. if(is_array($res['to']) && in_array('https://www.w3.org/ns/activitystreams#Public', $res['to'])) {
  265. $scope = 'public';
  266. }
  267. if(is_string($res['to']) && 'https://www.w3.org/ns/activitystreams#Public' == $res['to']) {
  268. $scope = 'public';
  269. }
  270. }
  271. if(isset($res['cc']) == true) {
  272. if(is_array($res['cc']) && in_array('https://www.w3.org/ns/activitystreams#Public', $res['cc'])) {
  273. $scope = 'unlisted';
  274. }
  275. if(is_string($res['cc']) && 'https://www.w3.org/ns/activitystreams#Public' == $res['cc']) {
  276. $scope = 'unlisted';
  277. }
  278. }
  279. if(config('costar.enabled') == true) {
  280. $blockedKeywords = config('costar.keyword.block');
  281. if($blockedKeywords !== null) {
  282. $keywords = config('costar.keyword.block');
  283. foreach($keywords as $kw) {
  284. if(Str::contains($res['content'], $kw) == true) {
  285. return;
  286. }
  287. }
  288. }
  289. $unlisted = config('costar.domain.unlisted');
  290. if(in_array(parse_url($url, PHP_URL_HOST), $unlisted) == true) {
  291. $unlisted = true;
  292. $scope = 'unlisted';
  293. } else {
  294. $unlisted = false;
  295. }
  296. $cwDomains = config('costar.domain.cw');
  297. if(in_array(parse_url($url, PHP_URL_HOST), $cwDomains) == true) {
  298. $cw = true;
  299. }
  300. }
  301. $id = isset($res['id']) ? self::pluckval($res['id']) : self::pluckval($url);
  302. $idDomain = parse_url($id, PHP_URL_HOST);
  303. $urlDomain = parse_url($url, PHP_URL_HOST);
  304. if(!self::validateUrl($id)) {
  305. return;
  306. }
  307. $attributedTo = is_string($activity['object']['attributedTo']) ?
  308. $activity['object']['attributedTo'] :
  309. (is_array($activity['object']['attributedTo']) ?
  310. collect($activity['object']['attributedTo'])
  311. ->filter(function($o) {
  312. return $o && isset($o['type']) && $o['type'] == 'Person';
  313. })
  314. ->pluck('id')
  315. ->first() : null
  316. );
  317. if($attributedTo) {
  318. $actorDomain = parse_url($attributedTo, PHP_URL_HOST);
  319. if(!self::validateUrl($attributedTo) ||
  320. $idDomain !== $actorDomain ||
  321. $actorDomain !== $urlDomain
  322. )
  323. {
  324. return;
  325. }
  326. }
  327. if($idDomain !== $urlDomain) {
  328. return;
  329. }
  330. $profile = self::profileFirstOrNew($attributedTo);
  331. if(isset($activity['object']['inReplyTo']) && !empty($activity['object']['inReplyTo']) || $replyTo == true) {
  332. $reply_to = self::statusFirstOrFetch(self::pluckval($activity['object']['inReplyTo']), false);
  333. $reply_to = optional($reply_to)->id;
  334. } else {
  335. $reply_to = null;
  336. }
  337. $ts = self::pluckval($res['published']);
  338. if($scope == 'public' && in_array($urlDomain, InstanceService::getUnlistedDomains())) {
  339. $scope = 'unlisted';
  340. }
  341. if(in_array($urlDomain, InstanceService::getNsfwDomains())) {
  342. $cw = true;
  343. }
  344. $statusLockKey = 'helpers:status-lock:' . hash('sha256', $res['id']);
  345. $status = Cache::lock($statusLockKey)
  346. ->get(function () use(
  347. $profile,
  348. $res,
  349. $url,
  350. $ts,
  351. $reply_to,
  352. $cw,
  353. $scope,
  354. $id
  355. ) {
  356. if($res['type'] === 'Question') {
  357. $status = self::storePoll(
  358. $profile,
  359. $res,
  360. $url,
  361. $ts,
  362. $reply_to,
  363. $cw,
  364. $scope,
  365. $id
  366. );
  367. return $status;
  368. }
  369. return self::storeStatus($url, $profile, $res);
  370. });
  371. return $status;
  372. }
  373. public static function storeStatus($url, $profile, $activity)
  374. {
  375. $id = isset($activity['id']) ? self::pluckval($activity['id']) : self::pluckval($activity['url']);
  376. $url = isset($activity['url']) && is_string($activity['url']) ? $activity['url'] : $id;
  377. $idDomain = parse_url($id, PHP_URL_HOST);
  378. $urlDomain = parse_url($url, PHP_URL_HOST);
  379. if(!self::validateUrl($id) || !self::validateUrl($url)) {
  380. return;
  381. }
  382. $reply_to = self::getReplyTo($activity);
  383. return DB::transaction(function() use($url, $profile, $activity, $reply_to, $id) {
  384. $ts = self::pluckval($activity['published']);
  385. $scope = self::getScope($activity);
  386. $cw = self::getSensitive($activity);
  387. $status = new Status;
  388. $status->profile_id = $profile->id;
  389. $status->url = $url;
  390. $status->uri = $url;
  391. $status->object_url = $id;
  392. $status->caption = strip_tags($activity['content']);
  393. $status->rendered = Purify::clean($activity['content']);
  394. $status->created_at = Carbon::parse($ts);
  395. $status->in_reply_to_id = $reply_to;
  396. $status->local = false;
  397. $status->is_nsfw = $cw;
  398. $status->scope = $scope;
  399. $status->visibility = $scope;
  400. $status->cw_summary = $cw == true && isset($activity['summary']) ?
  401. Purify::clean(strip_tags($activity['summary'])) : null;
  402. $status->save();
  403. if($reply_to == null) {
  404. self::importNoteAttachment($activity, $status);
  405. } else {
  406. StatusReplyPipeline::dispatch($status);
  407. }
  408. if(isset($activity['tag']) && is_array($activity['tag']) && !empty($activity['tag'])) {
  409. StatusTagsPipeline::dispatch($activity, $status);
  410. }
  411. return $status;
  412. });
  413. }
  414. public static function getSensitive($activity)
  415. {
  416. $id = isset($activity['id']) ? self::pluckval($activity['id']) : self::pluckval($url);
  417. $url = isset($activity['url']) ? self::pluckval($activity['url']) : $id;
  418. $urlDomain = parse_url($url, PHP_URL_HOST);
  419. $cw = isset($activity['sensitive']) ? (bool) $activity['sensitive'] : false;
  420. if(in_array($urlDomain, InstanceService::getNsfwDomains())) {
  421. $cw = true;
  422. }
  423. return $cw;
  424. }
  425. public static function getReplyTo($activity)
  426. {
  427. $reply_to = null;
  428. $inReplyTo = isset($activity['inReplyTo']) && !empty($activity['inReplyTo']) ?
  429. self::pluckval($activity['inReplyTo']) :
  430. false;
  431. if($inReplyTo) {
  432. $reply_to = self::statusFirstOrFetch($inReplyTo);
  433. if($reply_to) {
  434. $reply_to = optional($reply_to)->id;
  435. }
  436. } else {
  437. $reply_to = null;
  438. }
  439. return $reply_to;
  440. }
  441. public static function getScope($activity)
  442. {
  443. $id = isset($activity['id']) ? self::pluckval($activity['id']) : self::pluckval($url);
  444. $url = isset($activity['url']) ? self::pluckval($activity['url']) : $id;
  445. $urlDomain = parse_url($url, PHP_URL_HOST);
  446. $scope = 'private';
  447. if(isset($activity['to']) == true) {
  448. if(is_array($activity['to']) && in_array('https://www.w3.org/ns/activitystreams#Public', $activity['to'])) {
  449. $scope = 'public';
  450. }
  451. if(is_string($activity['to']) && 'https://www.w3.org/ns/activitystreams#Public' == $activity['to']) {
  452. $scope = 'public';
  453. }
  454. }
  455. if(isset($activity['cc']) == true) {
  456. if(is_array($activity['cc']) && in_array('https://www.w3.org/ns/activitystreams#Public', $activity['cc'])) {
  457. $scope = 'unlisted';
  458. }
  459. if(is_string($activity['cc']) && 'https://www.w3.org/ns/activitystreams#Public' == $activity['cc']) {
  460. $scope = 'unlisted';
  461. }
  462. }
  463. if($scope == 'public' && in_array($urlDomain, InstanceService::getUnlistedDomains())) {
  464. $scope = 'unlisted';
  465. }
  466. return $scope;
  467. }
  468. private static function storePoll($profile, $res, $url, $ts, $reply_to, $cw, $scope, $id)
  469. {
  470. if(!isset($res['endTime']) || !isset($res['oneOf']) || !is_array($res['oneOf']) || count($res['oneOf']) > 4) {
  471. return;
  472. }
  473. $options = collect($res['oneOf'])->map(function($option) {
  474. return $option['name'];
  475. })->toArray();
  476. $cachedTallies = collect($res['oneOf'])->map(function($option) {
  477. return $option['replies']['totalItems'] ?? 0;
  478. })->toArray();
  479. $status = new Status;
  480. $status->profile_id = $profile->id;
  481. $status->url = isset($res['url']) ? $res['url'] : $url;
  482. $status->uri = isset($res['url']) ? $res['url'] : $url;
  483. $status->object_url = $id;
  484. $status->caption = strip_tags($res['content']);
  485. $status->rendered = Purify::clean($res['content']);
  486. $status->created_at = Carbon::parse($ts);
  487. $status->in_reply_to_id = null;
  488. $status->local = false;
  489. $status->is_nsfw = $cw;
  490. $status->scope = 'draft';
  491. $status->visibility = 'draft';
  492. $status->cw_summary = $cw == true && isset($res['summary']) ?
  493. Purify::clean(strip_tags($res['summary'])) : null;
  494. $status->save();
  495. $poll = new Poll;
  496. $poll->status_id = $status->id;
  497. $poll->profile_id = $status->profile_id;
  498. $poll->poll_options = $options;
  499. $poll->cached_tallies = $cachedTallies;
  500. $poll->votes_count = array_sum($cachedTallies);
  501. $poll->expires_at = now()->parse($res['endTime']);
  502. $poll->last_fetched_at = now();
  503. $poll->save();
  504. $status->type = 'poll';
  505. $status->scope = $scope;
  506. $status->visibility = $scope;
  507. $status->save();
  508. return $status;
  509. }
  510. public static function statusFetch($url)
  511. {
  512. return self::statusFirstOrFetch($url);
  513. }
  514. public static function importNoteAttachment($data, Status $status)
  515. {
  516. if(self::verifyAttachments($data) == false) {
  517. // \Log::info('importNoteAttachment::failedVerification.', [$data['id']]);
  518. $status->viewType();
  519. return;
  520. }
  521. $attachments = isset($data['object']) ? $data['object']['attachment'] : $data['attachment'];
  522. // peertube
  523. // if(!$attachments) {
  524. // $obj = isset($data['object']) ? $data['object'] : $data;
  525. // $attachments = is_array($obj['url']) ? $obj['url'] : null;
  526. // }
  527. $user = $status->profile;
  528. $storagePath = MediaPathService::get($user, 2);
  529. $allowed = explode(',', config_cache('pixelfed.media_types'));
  530. foreach($attachments as $media) {
  531. $type = $media['mediaType'];
  532. $url = $media['url'];
  533. $blurhash = isset($media['blurhash']) ? $media['blurhash'] : null;
  534. $license = isset($media['license']) ? License::nameToId($media['license']) : null;
  535. $valid = self::validateUrl($url);
  536. if(in_array($type, $allowed) == false || $valid == false) {
  537. continue;
  538. }
  539. $media = new Media();
  540. $media->blurhash = $blurhash;
  541. $media->remote_media = true;
  542. $media->status_id = $status->id;
  543. $media->profile_id = $status->profile_id;
  544. $media->user_id = null;
  545. $media->media_path = $url;
  546. $media->remote_url = $url;
  547. if($license) {
  548. $media->license = $license;
  549. }
  550. $media->mime = $type;
  551. $media->version = 3;
  552. $media->save();
  553. if(config_cache('pixelfed.cloud_storage') == true) {
  554. MediaStoragePipeline::dispatch($media);
  555. }
  556. }
  557. $status->viewType();
  558. return;
  559. }
  560. public static function profileFirstOrNew($url, $runJobs = false)
  561. {
  562. $url = self::validateUrl($url);
  563. if($url == false || strlen($url) > 190) {
  564. return;
  565. }
  566. $hash = base64_encode($url);
  567. $key = 'ap:profile:by_url:' . $hash;
  568. $ttl = now()->addMinutes(5);
  569. $profile = Cache::remember($key, $ttl, function() use($url, $runJobs) {
  570. $host = parse_url($url, PHP_URL_HOST);
  571. $local = config('pixelfed.domain.app') == $host ? true : false;
  572. if($local == true) {
  573. $id = last(explode('/', $url));
  574. return Profile::whereNull('status')
  575. ->whereNull('domain')
  576. ->whereUsername($id)
  577. ->firstOrFail();
  578. }
  579. $res = self::fetchProfileFromUrl($url);
  580. if(isset($res['id']) == false) {
  581. return;
  582. }
  583. $domain = parse_url($res['id'], PHP_URL_HOST);
  584. if(!isset($res['preferredUsername']) && !isset($res['nickname'])) {
  585. return;
  586. }
  587. $username = (string) Purify::clean($res['preferredUsername'] ?? $res['nickname']);
  588. if(empty($username)) {
  589. return;
  590. }
  591. $remoteUsername = $username;
  592. $webfinger = "@{$username}@{$domain}";
  593. abort_if(!self::validateUrl($res['inbox']), 400);
  594. abort_if(!self::validateUrl($res['id']), 400);
  595. $profile = Profile::whereRemoteUrl($res['id'])->first();
  596. if(!$profile) {
  597. $instance = Instance::firstOrCreate([
  598. 'domain' => $domain
  599. ]);
  600. if($instance->wasRecentlyCreated == true) {
  601. \App\Jobs\InstancePipeline\FetchNodeinfoPipeline::dispatch($instance)->onQueue('low');
  602. }
  603. $profileLockKey = 'helpers:profile-lock:' . hash('sha256', $res['id']);
  604. $profile = Cache::lock($profileLockKey)->get(function () use($domain, $webfinger, $res, $runJobs) {
  605. return DB::transaction(function() use($domain, $webfinger, $res, $runJobs) {
  606. $profile = new Profile();
  607. $profile->domain = strtolower($domain);
  608. $profile->username = Purify::clean($webfinger);
  609. $profile->name = isset($res['name']) ? Purify::clean($res['name']) : 'user';
  610. $profile->bio = isset($res['summary']) ? Purify::clean($res['summary']) : null;
  611. $profile->sharedInbox = isset($res['endpoints']) && isset($res['endpoints']['sharedInbox']) ? $res['endpoints']['sharedInbox'] : null;
  612. $profile->inbox_url = $res['inbox'];
  613. $profile->outbox_url = isset($res['outbox']) ? $res['outbox'] : null;
  614. $profile->remote_url = $res['id'];
  615. $profile->public_key = $res['publicKey']['publicKeyPem'];
  616. $profile->key_id = $res['publicKey']['id'];
  617. $profile->webfinger = Purify::clean($webfinger);
  618. $profile->last_fetched_at = now();
  619. $profile->save();
  620. RemoteAvatarFetch::dispatch($profile);
  621. return $profile;
  622. });
  623. });
  624. } else {
  625. // Update info after 24 hours
  626. if($profile->last_fetched_at == null ||
  627. $profile->last_fetched_at->lt(now()->subHours(24)) == true
  628. ) {
  629. $profile->name = isset($res['name']) ? Purify::clean($res['name']) : 'user';
  630. $profile->bio = isset($res['summary']) ? Purify::clean($res['summary']) : null;
  631. $profile->last_fetched_at = now();
  632. $profile->sharedInbox = isset($res['endpoints']) && isset($res['endpoints']['sharedInbox']) && Helpers::validateUrl($res['endpoints']['sharedInbox']) ? $res['endpoints']['sharedInbox'] : null;
  633. $profile->save();
  634. }
  635. RemoteAvatarFetch::dispatch($profile);
  636. }
  637. return $profile;
  638. });
  639. return $profile;
  640. }
  641. public static function profileFetch($url)
  642. {
  643. return self::profileFirstOrNew($url);
  644. }
  645. public static function sendSignedObject($profile, $url, $body)
  646. {
  647. ActivityPubDeliveryService::queue()
  648. ->from($profile)
  649. ->to($url)
  650. ->payload($body)
  651. ->send();
  652. }
  653. }