AutoStatisticsUserDailyTrafficJob.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Http\Models\User;
  5. use App\Http\Models\SsNode;
  6. use App\Http\Models\UserTrafficDaily;
  7. use App\Http\Models\UserTrafficLog;
  8. use Log;
  9. class AutoStatisticsUserDailyTrafficJob extends Command
  10. {
  11. protected $signature = 'command:autoStatisticsUserDailyTrafficJob';
  12. protected $description = '自动统计用户每日流量';
  13. public function __construct()
  14. {
  15. parent::__construct();
  16. }
  17. public function handle()
  18. {
  19. $userList = User::query()->where('status', '>=', 0)->where('enable', 1)->get();
  20. foreach ($userList as $user) {
  21. // 统计一次所有节点的总和
  22. $this->statisticsByNode($user->id);
  23. // 统计每个节点产生的流量
  24. $nodeList = SsNode::query()->where('status', 1)->orderBy('id', 'asc')->get();
  25. foreach ($nodeList as $node) {
  26. $this->statisticsByNode($user->id, $node->id);
  27. }
  28. }
  29. Log::info('定时任务:' . $this->description);
  30. }
  31. private function statisticsByNode($user_id, $node_id = 0)
  32. {
  33. $start_time = strtotime(date('Y-m-d 00:00:00', strtotime("-1 day")));
  34. $end_time = strtotime(date('Y-m-d 23:59:59', strtotime("-1 day")));
  35. $query = UserTrafficLog::query()->where('user_id', $user_id)->whereBetween('log_time', [$start_time, $end_time]);
  36. if ($node_id) {
  37. $query->where('node_id', $node_id);
  38. }
  39. $u = $query->sum('u');
  40. $d = $query->sum('d');
  41. $total = $u + $d;
  42. $traffic = $this->flowAutoShow($total);
  43. $obj = new UserTrafficDaily();
  44. $obj->user_id = $user_id;
  45. $obj->node_id = $node_id;
  46. $obj->u = $u;
  47. $obj->d = $d;
  48. $obj->total = $total;
  49. $obj->traffic = $traffic;
  50. $obj->save();
  51. }
  52. // 根据流量值自动转换单位输出
  53. private function flowAutoShow($value = 0)
  54. {
  55. $kb = 1024;
  56. $mb = 1048576;
  57. $gb = 1073741824;
  58. $tb = $gb * 1024;
  59. $pb = $tb * 1024;
  60. if (abs($value) > $pb) {
  61. return round($value / $pb, 2) . "PB";
  62. } elseif (abs($value) > $tb) {
  63. return round($value / $tb, 2) . "TB";
  64. } elseif (abs($value) > $gb) {
  65. return round($value / $gb, 2) . "GB";
  66. } elseif (abs($value) > $mb) {
  67. return round($value / $mb, 2) . "MB";
  68. } elseif (abs($value) > $kb) {
  69. return round($value / $kb, 2) . "KB";
  70. } else {
  71. return round($value, 2) . "B";
  72. }
  73. }
  74. }