addUser.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Jobs\VNet;
  3. use App\Models\User;
  4. use Arr;
  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 addUser implements ShouldQueue
  16. {
  17. use Dispatchable;
  18. use InteractsWithQueue;
  19. use Queueable;
  20. use SerializesModels;
  21. private array $data;
  22. private Collection $nodes;
  23. public function __construct(array $userIds, Collection $nodes)
  24. {
  25. $this->nodes = $nodes;
  26. foreach (User::findMany($userIds) as $user) {
  27. $this->data[] = [
  28. 'uid' => $user->id,
  29. 'port' => $user->port,
  30. 'passwd' => $user->passwd,
  31. 'speed_limit' => $user->speed_limit,
  32. 'enable' => $user->enable,
  33. ];
  34. }
  35. }
  36. public function handle(): void
  37. {
  38. foreach ($this->nodes as $node) {
  39. if (isset($node->is_ddns) && $node->is_ddns) {
  40. $this->send($node->server.':'.$node->push_port, $node->auth->secret);
  41. } else { // 多IP支持
  42. foreach ($node->ips() as $ip) {
  43. $this->send($ip.':'.$node->push_port, $node->auth->secret);
  44. }
  45. }
  46. }
  47. }
  48. private function send(string $host, string $secret): void
  49. {
  50. try {
  51. $response = Http::baseUrl($host)->timeout(20)->withHeaders(['secret' => $secret])->post('api/v2/user/add/list', $this->data);
  52. $message = $response->json();
  53. if ($message && Arr::has($message, ['success', 'content']) && $response->ok()) {
  54. if ($message['success'] === 'false') {
  55. Log::alert("【新增用户】推送失败(推送地址:{$host},返回内容:".$message['content'].')');
  56. } else {
  57. Log::notice("【新增用户】推送成功(推送地址:{$host},内容:".json_encode($this->data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT).')');
  58. }
  59. }
  60. } catch (Exception $exception) {
  61. Log::alert('【新增用户】推送异常:'.$exception->getMessage());
  62. }
  63. }
  64. // 队列失败处理
  65. public function failed(Throwable $exception): void
  66. {
  67. Log::alert('【新增用户】推送异常:'.$exception->getMessage());
  68. }
  69. }