editUser.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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)->withHeader('secret', $secret)->post('api/user/edit', $this->data);
  60. $message = $response->json();
  61. if ($message && Arr::has($message, ['success', 'content']) && $message['success'] === 'false') {
  62. Log::warning("【编辑用户】推送失败(推送地址:{$host},返回内容:".$message['content'].')');
  63. }
  64. } catch (Exception $exception) {
  65. Log::alert('【编辑用户】推送异常:'.$exception->getMessage());
  66. }
  67. }
  68. // 队列失败处理
  69. public function failed(Throwable $exception): void
  70. {
  71. Log::alert('【编辑用户】推送异常:'.$exception->getMessage());
  72. }
  73. }