editUser.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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\Foundation\Bus\Dispatchable;
  10. use Illuminate\Queue\InteractsWithQueue;
  11. use Illuminate\Queue\SerializesModels;
  12. use Log;
  13. use Throwable;
  14. class editUser 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(User $user, $nodes)
  23. {
  24. $this->nodes = $nodes;
  25. $this->data = [
  26. 'uid' => $user->id,
  27. 'port' => (int) $user->port,
  28. 'passwd' => $user->passwd,
  29. 'speed_limit' => $user->speed_limit,
  30. 'enable' => (int) $user->enable,
  31. ];
  32. }
  33. public function handle(): void
  34. {
  35. foreach ($this->nodes as $node) {
  36. $list = $this->list(($node->server ?: $node->ips()[0]).':'.$node->push_port, $node->auth->secret);
  37. if ($list && in_array($this->data['uid'], $list, true)) { // 如果用户已存在节点内,则执行修改;否则为添加
  38. if ($node->is_ddns) {
  39. $this->send($node->server.':'.$node->push_port, $node->auth->secret);
  40. } else { // 多IP支持
  41. foreach ($node->ips() as $ip) {
  42. $this->send($ip.':'.$node->push_port, $node->auth->secret);
  43. }
  44. }
  45. } else {
  46. addUser::dispatch($this->data['uid'], $node);
  47. }
  48. }
  49. }
  50. private function list(string $host, string $secret)
  51. {
  52. $response = Http::baseUrl($host)->timeout(20)->withHeaders(['secret' => $secret])->get('api/user/list');
  53. $message = $response->json();
  54. if ($message && $response->ok()) {
  55. return Arr::pluck($message, 'uid');
  56. }
  57. Log::warning('【用户列表】获取失败(推送地址:'.$host.')');
  58. return false;
  59. }
  60. private function send(string $host, string $secret): void
  61. {
  62. try {
  63. $response = Http::baseUrl($host)->timeout(20)->withHeaders(['secret' => $secret])->post('api/user/edit', $this->data);
  64. $message = $response->json();
  65. if ($message && Arr::has($message, ['success', 'content']) && $response->ok()) {
  66. if ($message['success'] === 'false') {
  67. Log::warning("【编辑用户】推送失败(推送地址:{$host},返回内容:".$message['content'].')');
  68. } else {
  69. Log::info("【编辑用户】推送成功(推送地址:{$host},内容:".json_encode($this->data, true).')');
  70. }
  71. }
  72. } catch (Exception $exception) {
  73. Log::alert('【编辑用户】推送异常:'.$exception->getMessage());
  74. }
  75. }
  76. // 队列失败处理
  77. public function failed(Throwable $exception)
  78. {
  79. Log::alert('【编辑用户】推送异常:'.$exception->getMessage());
  80. }
  81. }