AvatarOptimize.php 2.1 KB

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