addUser.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace App\Jobs\VNet;
  3. use App\Models\Node;
  4. use App\Models\User;
  5. use Arr;
  6. use Http;
  7. use Illuminate\Bus\Queueable;
  8. use Illuminate\Contracts\Queue\ShouldQueue;
  9. use Illuminate\Foundation\Bus\Dispatchable;
  10. use Illuminate\Queue\InteractsWithQueue;
  11. use Illuminate\Queue\SerializesModels;
  12. use Log;
  13. use Throwable;
  14. class addUser implements ShouldQueue
  15. {
  16. use Dispatchable;
  17. use InteractsWithQueue;
  18. use Queueable;
  19. use SerializesModels;
  20. private $data;
  21. private $nodes;
  22. public function __construct($userIds, $nodeIds)
  23. {
  24. $this->nodes = Node::findMany($nodeIds);
  25. $data = [];
  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. $this->send(($node->server ?: $node->ip).':'.$node->push_port, $node->auth->secret);
  41. }
  42. }
  43. private function send($host, $secret): void
  44. {
  45. $request = Http::baseUrl($host)->timeout(20)->withHeaders(['secret' => $secret]);
  46. $response = $request->post('api/v2/user/add/list', $this->data);
  47. $message = $response->json();
  48. if ($message && Arr::has($message, ['success', 'content']) && $response->ok()) {
  49. if ($message['success'] === 'false') {
  50. Log::warning('【新增用户】推送失败(推送地址:'.$host.',返回内容:'.$message['content'].')');
  51. } else {
  52. Log::info('【新增用户】推送成功(推送地址:'.$host.',内容:'.json_encode($this->data, true).')');
  53. }
  54. }
  55. }
  56. // 队列失败处理
  57. public function failed(Throwable $exception)
  58. {
  59. Log::error('【新增用户】推送异常:'.$exception->getMessage());
  60. }
  61. }