RemoteFollowImportRecent.php 6.5 KB

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