GetTrafficStats.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Jobs\Hysteria2;
  3. use App\Models\Node;
  4. use App\Models\User;
  5. use Exception;
  6. use Http;
  7. use Illuminate\Bus\Queueable;
  8. use Illuminate\Contracts\Queue\ShouldQueue;
  9. use Illuminate\Database\Eloquent\Collection;
  10. use Illuminate\Foundation\Bus\Dispatchable;
  11. use Illuminate\Queue\InteractsWithQueue;
  12. use Illuminate\Queue\SerializesModels;
  13. use Log;
  14. use Throwable;
  15. class GetTrafficStats implements ShouldQueue
  16. {
  17. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  18. public function __construct(private Collection|Node $nodes)
  19. {
  20. if (! $nodes instanceof Collection) {
  21. $this->nodes = new Collection([$nodes]);
  22. }
  23. }
  24. public function handle(): void
  25. {
  26. foreach ($this->nodes as $node) {
  27. if ($node->is_ddns) {
  28. $data = $this->send($node->server.':'.$node->push_port, $node->auth->secret);
  29. if ($data) {
  30. $this->syncTrafficData($node, $data);
  31. }
  32. } else { // 多IP支持
  33. foreach ($node->ips() as $ip) {
  34. $data = $this->send($ip.':'.$node->push_port, $node->auth->secret);
  35. if ($data) {
  36. $this->syncTrafficData($node, $data);
  37. }
  38. }
  39. }
  40. }
  41. }
  42. private function syncTrafficData(Node $node, array $data): void
  43. {
  44. $rate = $node->traffic_rate;
  45. foreach ($data as $userId => $stats) { // Hysteria2 API 返回的是用户ID
  46. $user = User::find($userId);
  47. if (! $user) {
  48. Log::warning("【Hysteria2流量统计】未找到ID为 {$userId} 的用户");
  49. continue;
  50. }
  51. $upload = (int) $stats['tx'] * $rate;
  52. $download = (int) $stats['rx'] * $rate;
  53. $user->update(['u' => $user->u + $upload, 'd' => $user->d + $download, 't' => time()]);
  54. $node->userDataFlowLogs()->create(['user_id' => $user->id, 'u' => $upload, 'd' => $download, 'traffic' => formatBytes($upload + $download), 'rate' => $rate, 'log_time' => time()]);
  55. }
  56. }
  57. private function send(string $host, string $secret): array
  58. {
  59. try {
  60. $request = Http::baseUrl($host)->timeout(15)->withHeader('Authorization', $secret);
  61. $response = $request->get('/traffic?clear=1');
  62. $data = $response->json();
  63. if ($data) {
  64. return $data;
  65. }
  66. } catch (Exception $exception) {
  67. Log::alert('【Hysteria2流量统计】获取异常:'.$exception->getMessage());
  68. }
  69. return [];
  70. }
  71. // 队列失败处理
  72. public function failed(Throwable $exception): void
  73. {
  74. Log::alert('【Hysteria2流量统计】获取异常:'.$exception->getMessage());
  75. }
  76. }