StoryGC.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\{
  5. DB,
  6. Storage
  7. };
  8. use App\{
  9. Story,
  10. StoryView
  11. };
  12. class StoryGC extends Command
  13. {
  14. /**
  15. * The name and signature of the console command.
  16. *
  17. * @var string
  18. */
  19. protected $signature = 'story:gc';
  20. /**
  21. * The console command description.
  22. *
  23. * @var string
  24. */
  25. protected $description = 'Clear expired Stories';
  26. /**
  27. * Create a new command instance.
  28. *
  29. * @return void
  30. */
  31. public function __construct()
  32. {
  33. parent::__construct();
  34. }
  35. /**
  36. * Execute the console command.
  37. *
  38. * @return mixed
  39. */
  40. public function handle()
  41. {
  42. $this->directoryScan();
  43. $this->deleteViews();
  44. $this->deleteStories();
  45. }
  46. protected function directoryScan()
  47. {
  48. $day = now()->day;
  49. if($day != 3) {
  50. return;
  51. }
  52. $monthHash = substr(hash('sha1', date('Y').date('m')), 0, 12);
  53. $t1 = Storage::directories('public/_esm.t1');
  54. $t2 = Storage::directories('public/_esm.t2');
  55. $dirs = array_merge($t1, $t2);
  56. foreach($dirs as $dir) {
  57. $hash = last(explode('/', $dir));
  58. if($hash != $monthHash) {
  59. $this->info('Found directory to delete: ' . $dir);
  60. $this->deleteDirectory($dir);
  61. }
  62. }
  63. }
  64. protected function deleteDirectory($path)
  65. {
  66. Storage::deleteDirectory($path);
  67. }
  68. protected function deleteViews()
  69. {
  70. StoryView::where('created_at', '<', now()->subMinutes(1441))->delete();
  71. }
  72. protected function deleteStories()
  73. {
  74. $stories = Story::where('created_at', '<', now()->subMinutes(1441))->take(50)->get();
  75. if($stories->count() == 0) {
  76. exit;
  77. }
  78. foreach($stories as $story) {
  79. if(Storage::exists($story->path) == true) {
  80. Storage::delete($story->path);
  81. }
  82. DB::transaction(function() use($story) {
  83. StoryView::whereStoryId($story->id)->delete();
  84. $story->delete();
  85. });
  86. }
  87. }
  88. }