|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Console\Commands; |
| 4 | + |
| 5 | +use App\Models\Comment; |
| 6 | +use App\Models\CommentReply; |
| 7 | +use App\Models\Follower; |
| 8 | +use App\Models\Instance; |
| 9 | +use App\Models\Profile; |
| 10 | +use App\Models\Report; |
| 11 | +use App\Models\Video; |
| 12 | +use Illuminate\Console\Command; |
| 13 | + |
| 14 | +class InstanceStatsCollectorCommand extends Command |
| 15 | +{ |
| 16 | + protected $signature = 'app:instance-stats-collector-command'; |
| 17 | + |
| 18 | + protected $description = 'Collect statistics for instances that need updating'; |
| 19 | + |
| 20 | + public function handle() |
| 21 | + { |
| 22 | + $count = 0; |
| 23 | + $now = now(); |
| 24 | + |
| 25 | + Instance::query() |
| 26 | + ->where(function ($query) { |
| 27 | + $query->whereNull('stats_last_collected_at') |
| 28 | + ->orWhere('stats_last_collected_at', '<', now()->subDay()); |
| 29 | + }) |
| 30 | + ->limit(250) |
| 31 | + ->lazyById() |
| 32 | + ->each(function ($instance) use (&$count, $now) { |
| 33 | + $instance->user_count = Profile::whereDomain($instance->domain)->count(); |
| 34 | + $instance->video_count = Video::join('profiles', 'videos.profile_id', '=', 'profiles.id') |
| 35 | + ->where('profiles.domain', $instance->domain) |
| 36 | + ->count(); |
| 37 | + $instance->comment_count = Comment::join('profiles', 'comments.profile_id', '=', 'profiles.id') |
| 38 | + ->where('profiles.domain', $instance->domain) |
| 39 | + ->count(); |
| 40 | + $instance->reply_count = CommentReply::join('profiles', 'comment_replies.profile_id', '=', 'profiles.id') |
| 41 | + ->where('profiles.domain', $instance->domain) |
| 42 | + ->count(); |
| 43 | + $instance->follower_count = Follower::join('profiles', 'followers.following_id', '=', 'profiles.id') |
| 44 | + ->where('profiles.domain', $instance->domain) |
| 45 | + ->count(); |
| 46 | + $instance->following_count = Follower::join('profiles', 'followers.profile_id', '=', 'profiles.id') |
| 47 | + ->where('profiles.domain', $instance->domain) |
| 48 | + ->count(); |
| 49 | + $instance->report_count = Report::join('profiles', 'reports.reported_profile_id', '=', 'profiles.id') |
| 50 | + ->where('profiles.domain', $instance->domain) |
| 51 | + ->count(); |
| 52 | + $instance->stats_last_collected_at = $now; |
| 53 | + $instance->save(); |
| 54 | + |
| 55 | + $count++; |
| 56 | + }); |
| 57 | + |
| 58 | + $this->info("Collected stats for {$count} instances"); |
| 59 | + } |
| 60 | +} |
0 commit comments