editUser.php 2.9 KB

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