RemoteFollowImportRecent.php 6.5 KB

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