/
AutoGroup.php
106 lines (91 loc) · 3.3 KB
/
AutoGroup.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
/**
* NOTICE OF LICENSE.
*
* UNIT3D Community Edition is open-sourced software licensed under the GNU Affero General Public License v3.0
* The details is bundled with this project in the file LICENSE.txt.
*
* @project UNIT3D Community Edition
*
* @author HDVinnie <hdinnovations@protonmail.com>
* @license https://www.gnu.org/licenses/agpl-3.0.en.html/ GNU Affero General Public License v3.0
*/
namespace App\Console\Commands;
use App\Enums\UserGroup;
use App\Models\Group;
use App\Models\User;
use App\Services\Unit3dAnnounce;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
/**
* @see \Tests\Unit\Console\Commands\AutoGroupTest
*/
class AutoGroup extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'auto:group';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Automatically Change A Users Group Class If Requirements Met';
/**
* Execute the console command.
*/
public function handle(): void
{
$now = now();
$current = Carbon::now();
$groups = Group::query()
->where('autogroup', '=', 1)
->orderBy('position')
->get();
$users = User::query()
->whereIntegerInRaw('group_id', $groups->pluck('id'))
->get();
foreach ($users as $user) {
// memoize when necessary
$seedsize = null;
$seedtime = null;
foreach ($groups as $group) {
$seedtime ??= DB::table('history')
->where('user_id', '=', $user->id)
->avg('seedtime') ?? 0;
$seedsize ??= $user->seedingTorrents()->sum('size');
if (
//short circuit when the values are 0 or null
(!$group->min_uploaded || $group->min_uploaded <= $user->uploaded)
&& (!$group->min_ratio || $group->min_ratio <= $user->ratio)
&& (!$group->min_age || $user->created_at->addSeconds($group->min_age)->isBefore($current))
&& (!$group->min_avg_seedtime || $group->min_avg_seedtime <= ($seedtime))
&& (!$group->min_seedsize || $group->min_seedsize <= ($seedsize))
) {
$user->group_id = $group->id;
// Leech ratio dropped below sites minimum
if ($user->group_id === UserGroup::LEECH->value) {
$user->can_request = false;
$user->can_invite = false;
$user->can_download = false;
} else {
$user->can_request = true;
$user->can_invite = true;
$user->can_download = true;
}
$user->save();
if ($user->wasChanged()) {
cache()->forget('user:'.$user->passkey);
Unit3dAnnounce::addUser($user);
}
}
}
}
$elapsed = now()->diffInSeconds($now);
$this->comment('Automated User Group Command Complete ('.$elapsed.')');
}
}