UserTrafficAutoWarning.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. try {
  44. Mail::to($user->username)->send(new userTrafficWarning(self::$systemConfig['website_name'], $usedPercent));
  45. Helpers::addEmailLog($user->id, $title, $content);
  46. } catch (\Exception $e) {
  47. Helpers::addEmailLog($user->id, $title, $content, 0, $e->getMessage());
  48. }
  49. }
  50. }
  51. }
  52. }