editUser.php 2.8 KB

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