RemoteFollowImportRecent.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. namespace App\Jobs\RemoteFollowPipeline;
  3. use App\Jobs\ImageOptimizePipeline\ImageThumbnail;
  4. use App\Jobs\StatusPipeline\NewStatusPipeline;
  5. use App\Media;
  6. use App\Status;
  7. use Carbon\Carbon;
  8. use Illuminate\Bus\Queueable;
  9. use Illuminate\Contracts\Queue\ShouldQueue;
  10. use Illuminate\Foundation\Bus\Dispatchable;
  11. use Illuminate\Http\File;
  12. use Illuminate\Queue\InteractsWithQueue;
  13. use Illuminate\Queue\SerializesModels;
  14. use Log;
  15. use Storage;
  16. use Zttp\Zttp;
  17. use App\Util\ActivityPub\Helpers;
  18. class RemoteFollowImportRecent implements ShouldQueue
  19. {
  20. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  21. protected $actor;
  22. protected $profile;
  23. protected $outbox;
  24. protected $mediaCount;
  25. protected $cursor;
  26. protected $nextUrl;
  27. protected $supported;
  28. /**
  29. * Create a new job instance.
  30. *
  31. * @return void
  32. */
  33. public function __construct($actorObject, $profile)
  34. {
  35. $this->actor = $actorObject;
  36. $this->profile = $profile;
  37. $this->cursor = 1;
  38. $this->mediaCount = 0;
  39. $this->supported = [
  40. 'image/jpg',
  41. 'image/jpeg',
  42. 'image/png',
  43. 'image/gif',
  44. ];
  45. }
  46. /**
  47. * Execute the job.
  48. *
  49. * @return void
  50. */
  51. public function handle()
  52. {
  53. $outbox = $this->fetchOutbox();
  54. }
  55. public function fetchOutbox($url = false)
  56. {
  57. $url = ($url == false) ? $this->actor['outbox'] : $url;
  58. if(Helpers::validateUrl($url) == false) {
  59. return;
  60. }
  61. $response = Zttp::withHeaders([
  62. 'User-Agent' => 'PixelFedBot v0.1 - https://pixelfed.org',
  63. ])->get($url);
  64. $this->outbox = $response->json();
  65. $this->parseOutbox($this->outbox);
  66. }
  67. public function parseOutbox($outbox)
  68. {
  69. $types = ['OrderedCollection', 'OrderedCollectionPage'];
  70. if (isset($outbox['totalItems']) && $outbox['totalItems'] < 1) {
  71. // Skip remote fetch, not enough posts
  72. Log::info('not enough items');
  73. return;
  74. }
  75. if (isset($outbox['type']) && in_array($outbox['type'], $types)) {
  76. Log::info('handle ordered collection');
  77. $this->handleOrderedCollection();
  78. }
  79. }
  80. public function handleOrderedCollection()
  81. {
  82. $outbox = $this->outbox;
  83. if (!isset($outbox['next']) && !isset($outbox['first']['next']) && $this->cursor !== 1) {
  84. $this->cursor = 40;
  85. $outbox['next'] = false;
  86. }
  87. if ($outbox['type'] == 'OrderedCollectionPage') {
  88. $this->nextUrl = $outbox['next'];
  89. }
  90. if (isset($outbox['first']) && !is_array($outbox['first'])) {
  91. // Mastodon detected
  92. Log::info('Mastodon detected...');
  93. $this->nextUrl = $outbox['first'];
  94. return $this->fetchOutbox($this->nextUrl);
  95. } else {
  96. // Pleroma detected.
  97. $this->nextUrl = isset($outbox['next']) ? $outbox['next'] : (isset($outbox['first']['next']) ? $outbox['first']['next'] : $outbox['next']);
  98. Log::info('Checking ordered items...');
  99. $orderedItems = isset($outbox['orderedItems']) ? $outbox['orderedItems'] : $outbox['first']['orderedItems'];
  100. }
  101. foreach ($orderedItems as $item) {
  102. Log::info('Parsing items...');
  103. $parsed = $this->parseObject($item);
  104. if ($parsed !== 0) {
  105. Log::info('Found media!');
  106. $this->importActivity($item);
  107. }
  108. }
  109. if ($this->cursor < 40 && $this->mediaCount < 9) {
  110. $this->cursor++;
  111. $this->mediaCount++;
  112. $this->fetchOutbox($this->nextUrl);
  113. }
  114. }
  115. public function parseObject($parsed)
  116. {
  117. if ($parsed['type'] !== 'Create') {
  118. return 0;
  119. }
  120. $activity = $parsed['object'];
  121. if (isset($activity['attachment']) && !empty($activity['attachment'])) {
  122. return $this->detectSupportedMedia($activity['attachment']);
  123. }
  124. }
  125. public function detectSupportedMedia($attachments)
  126. {
  127. $supported = $this->supported;
  128. $count = 0;
  129. foreach ($attachments as $media) {
  130. $mime = $media['mediaType'];
  131. $count = in_array($mime, $supported) ? ($count + 1) : $count;
  132. }
  133. return $count;
  134. }
  135. public function importActivity($activity)
  136. {
  137. $profile = $this->profile;
  138. $supported = $this->supported;
  139. $attachments = $activity['object']['attachment'];
  140. $caption = str_limit($activity['object']['content'], 125);
  141. if (Status::whereUrl($activity['id'])->count() !== 0) {
  142. return true;
  143. }
  144. $status = new Status();
  145. $status->profile_id = $profile->id;
  146. $status->url = $activity['id'];
  147. $status->local = false;
  148. $status->caption = strip_tags($caption);
  149. $status->created_at = Carbon::parse($activity['published']);
  150. $count = 0;
  151. foreach ($attachments as $media) {
  152. Log::info($media['mediaType'].' - '.$media['url']);
  153. $url = $media['url'];
  154. $mime = $media['mediaType'];
  155. if (!in_array($mime, $supported)) {
  156. Log::info('Invalid media, skipping. '.$mime);
  157. continue;
  158. }
  159. if (Helpers::validateUrl($url) == false) {
  160. Log::info('Skipping invalid attachment URL: ' . $url);
  161. continue;
  162. }
  163. $count++;
  164. if ($count === 1) {
  165. $status->save();
  166. }
  167. $this->importMedia($url, $mime, $status);
  168. }
  169. Log::info(count($attachments).' media found...');
  170. if ($count !== 0) {
  171. NewStatusPipeline::dispatch($status, $status->media->first());
  172. }
  173. }
  174. public function importMedia($url, $mime, $status)
  175. {
  176. $user = $this->profile;
  177. $monthHash = hash('sha1', date('Y').date('m'));
  178. $userHash = hash('sha1', $user->id.(string) $user->created_at);
  179. $storagePath = "public/m/{$monthHash}/{$userHash}";
  180. try {
  181. $info = pathinfo($url);
  182. $url = str_replace(' ', '%20', $url);
  183. $img = file_get_contents($url);
  184. $file = '/tmp/'.str_random(12).$info['basename'];
  185. file_put_contents($file, $img);
  186. $path = Storage::putFile($storagePath, new File($file), 'public');
  187. $media = new Media();
  188. $media->status_id = $status->id;
  189. $media->profile_id = $status->profile_id;
  190. $media->user_id = null;
  191. $media->media_path = $path;
  192. $media->size = 0;
  193. $media->mime = $mime;
  194. $media->save();
  195. ImageThumbnail::dispatch($media);
  196. return true;
  197. } catch (Exception $e) {
  198. return false;
  199. }
  200. }
  201. }