editUser.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 = (new getUser())->list($node);
  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 send(string $host, string $secret): void
  51. {
  52. try {
  53. $response = Http::baseUrl($host)->timeout(20)->withHeaders(['secret' => $secret])->post('api/user/edit', $this->data);
  54. $message = $response->json();
  55. if ($message && Arr::has($message, ['success', 'content']) && $response->ok()) {
  56. if ($message['success'] === 'false') {
  57. Log::warning("【编辑用户】推送失败(推送地址:{$host},返回内容:".$message['content'].')');
  58. } else {
  59. Log::info("【编辑用户】推送成功(推送地址:{$host},内容:".json_encode($this->data, true).')');
  60. }
  61. }
  62. } catch (Exception $exception) {
  63. Log::alert('【编辑用户】推送异常:'.$exception->getMessage());
  64. }
  65. }
  66. // 队列失败处理
  67. public function failed(Throwable $exception)
  68. {
  69. Log::alert('【编辑用户】推送异常:'.$exception->getMessage());
  70. }
  71. }