AvatarOptimize.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Jobs\AvatarPipeline;
  3. use App\Avatar;
  4. use App\Profile;
  5. use Carbon\Carbon;
  6. use Illuminate\Bus\Queueable;
  7. use Illuminate\Contracts\Queue\ShouldQueue;
  8. use Illuminate\Foundation\Bus\Dispatchable;
  9. use Illuminate\Queue\InteractsWithQueue;
  10. use Illuminate\Queue\SerializesModels;
  11. use Image as Intervention;
  12. class AvatarOptimize implements ShouldQueue
  13. {
  14. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  15. protected $profile;
  16. protected $current;
  17. /**
  18. * Delete the job if its models no longer exist.
  19. *
  20. * @var bool
  21. */
  22. public $deleteWhenMissingModels = true;
  23. /**
  24. * Create a new job instance.
  25. *
  26. * @return void
  27. */
  28. public function __construct(Profile $profile, $current)
  29. {
  30. $this->profile = $profile;
  31. $this->current = $current;
  32. }
  33. /**
  34. * Execute the job.
  35. *
  36. * @return void
  37. */
  38. public function handle()
  39. {
  40. $avatar = $this->profile->avatar;
  41. $file = storage_path("app/$avatar->media_path");
  42. try {
  43. $img = Intervention::make($file)->orientate();
  44. $img->fit(200, 200, function ($constraint) {
  45. $constraint->upsize();
  46. });
  47. $quality = config('pixelfed.image_quality');
  48. $img->save($file, $quality);
  49. $avatar = Avatar::whereProfileId($this->profile->id)->firstOrFail();
  50. $avatar->thumb_path = $avatar->media_path;
  51. $avatar->change_count = ++$avatar->change_count;
  52. $avatar->last_processed_at = Carbon::now();
  53. $avatar->save();
  54. $this->deleteOldAvatar($avatar->media_path, $this->current);
  55. } catch (Exception $e) {
  56. }
  57. }
  58. protected function deleteOldAvatar($new, $current)
  59. {
  60. if (storage_path('app/'.$new) == $current) {
  61. return;
  62. }
  63. if (is_file($current)) {
  64. @unlink($current);
  65. }
  66. }
  67. }