UserTrafficAutoWarning.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Components\Helpers;
  4. use Illuminate\Console\Command;
  5. use App\Http\Models\User;
  6. use App\Mail\userTrafficWarning;
  7. use Mail;
  8. use Log;
  9. class UserTrafficAutoWarning extends Command
  10. {
  11. protected $signature = 'userTrafficAutoWarning';
  12. protected $description = '用户流量超过警告阈值自动发邮件提醒';
  13. protected static $systemConfig;
  14. public function __construct()
  15. {
  16. parent::__construct();
  17. self::$systemConfig = Helpers::systemConfig();
  18. }
  19. public function handle()
  20. {
  21. $jobStartTime = microtime(true);
  22. // 用户流量超过警告阈值自动发邮件提醒
  23. if (self::$systemConfig['traffic_warning']) {
  24. $this->userTrafficWarning();
  25. }
  26. $jobEndTime = microtime(true);
  27. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  28. Log::info('执行定时任务【' . $this->description . '】,耗时' . $jobUsedTime . '秒');
  29. }
  30. // 用户流量超过警告阈值自动发邮件提醒
  31. private function userTrafficWarning()
  32. {
  33. $userList = User::query()->where('status', '>=', 0)->where('enable', 1)->where('transfer_enable', '>', 0)->get();
  34. foreach ($userList as $user) {
  35. // 用户名不是邮箱的跳过
  36. if (false === filter_var($user->username, FILTER_VALIDATE_EMAIL)) {
  37. continue;
  38. }
  39. $usedPercent = round(($user->d + $user->u) / $user->transfer_enable, 2) * 100; // 已使用流量百分比
  40. if ($usedPercent >= self::$systemConfig['traffic_warning_percent']) {
  41. $title = '流量提醒';
  42. $content = '流量已使用:' . $usedPercent . '%,请保持关注。';
  43. $logId = Helpers::addEmailLog($user->username, $title, $content);
  44. Mail::to($user->username)->send(new userTrafficWarning($logId, $usedPercent));
  45. }
  46. }
  47. }
  48. }