editUser.php 2.6 KB

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