addUser.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Jobs\VNet;
  3. use App\Models\Node;
  4. use App\Models\User;
  5. use Arr;
  6. use Exception;
  7. use Http;
  8. use Illuminate\Bus\Queueable;
  9. use Illuminate\Contracts\Queue\ShouldQueue;
  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 $data;
  22. private $nodes;
  23. public function __construct($userIds, $nodes)
  24. {
  25. $this->nodes = $nodes;
  26. foreach (User::findMany($userIds) as $user) {
  27. $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. $this->data = $data ?? [];
  36. }
  37. public function handle(): void
  38. {
  39. foreach ($this->nodes as $node) {
  40. if ($node->is_ddns) {
  41. $this->send($node->server.':'.$node->push_port, $node->auth->secret);
  42. } else { // 多IP支持
  43. foreach ($node->ips() as $ip) {
  44. $this->send($ip.':'.$node->push_port, $node->auth->secret);
  45. }
  46. }
  47. }
  48. }
  49. private function send(string $host, string $secret): void
  50. {
  51. try {
  52. $response = Http::baseUrl($host)->timeout(20)->withHeaders(['secret' => $secret])->post('api/v2/user/add/list', $this->data);
  53. $message = $response->json();
  54. if ($message && Arr::has($message, ['success', 'content']) && $response->ok()) {
  55. if ($message['success'] === 'false') {
  56. Log::alert("【新增用户】推送失败(推送地址:{$host},返回内容:".$message['content'].')');
  57. } else {
  58. Log::notice("【新增用户】推送成功(推送地址:{$host},内容:".json_encode($this->data, true).')');
  59. }
  60. }
  61. } catch (Exception $exception) {
  62. Log::alert('【新增用户】推送异常:'.$exception->getMessage());
  63. }
  64. }
  65. // 队列失败处理
  66. public function failed(Throwable $exception)
  67. {
  68. Log::alert('【新增用户】推送异常:'.$exception->getMessage());
  69. }
  70. }