editUser.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. $host = ($node->server ?: $node->ip).':'.$node->push_port;
  36. $secret = $node->auth->secret;
  37. // 如果用户已存在节点内,则执行修改;否则为添加
  38. $list = $this->list($host, $secret);
  39. if ($list && in_array($this->data['uid'], $list)) {
  40. $this->send($host, $secret);
  41. } else {
  42. addUser::dispatch($this->data['uid'], $node->id);
  43. }
  44. }
  45. }
  46. private function list($host, $secret)
  47. {
  48. $response = Http::baseUrl($host)->timeout(20)->withHeaders(['secret' => $secret])->get('api/user/list');
  49. $message = $response->json();
  50. if ($message && $response->ok()) {
  51. return Arr::pluck($message, 'uid');
  52. }
  53. Log::warning('【用户列表】获取失败(推送地址:'.$host.')');
  54. return false;
  55. }
  56. private function send($host, $secret): void
  57. {
  58. $response = Http::baseUrl($host)->timeout(20)->withHeaders(['secret' => $secret])->post('api/user/edit', $this->data);
  59. $message = $response->json();
  60. if ($message && Arr::has($message, ['success', 'content']) && $response->ok()) {
  61. if ($message['success'] === 'false') {
  62. Log::warning('【编辑用户】推送失败(推送地址:'.$host.',返回内容:'.$message['content'].')');
  63. } else {
  64. Log::info('【编辑用户】推送成功(推送地址:'.$host.',内容:'.json_encode($this->data, true).')');
  65. }
  66. }
  67. }
  68. // 队列失败处理
  69. public function failed(Throwable $exception)
  70. {
  71. Log::warning('【编辑用户】推送异常:'.$exception->getMessage());
  72. }
  73. }