addUser.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Jobs\VNet;
  3. use App\Models\User;
  4. use GuzzleHttp\Client;
  5. use Illuminate\Bus\Queueable;
  6. use Illuminate\Contracts\Queue\ShouldQueue;
  7. use Illuminate\Foundation\Bus\Dispatchable;
  8. use Illuminate\Queue\InteractsWithQueue;
  9. use Illuminate\Queue\SerializesModels;
  10. class addUser implements ShouldQueue {
  11. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  12. private static $data;
  13. private static $url;
  14. private $nodes;
  15. public function __construct(User $users, $nodes) {
  16. $this->nodes = $nodes;
  17. if($users->count() > 1){
  18. self::$url = '/api/v2/user/add/list';
  19. }else{
  20. self::$url = '/api/user/add';
  21. }
  22. $data = [];
  23. foreach($users as $user){
  24. $data[] = [
  25. 'uid' => $user->id,
  26. 'port' => $user->port,
  27. 'passwd' => $user->passwd,
  28. 'speed_limit' => $user->speed_limit,
  29. 'enable' => $user->enable,
  30. ];
  31. }
  32. self::$data = $data;
  33. }
  34. public function handle(): void {
  35. foreach($this->nodes as $node){
  36. self::send(($node->server?: $node->ip).':'.$node->push_port, $node->auth->secret);
  37. }
  38. }
  39. private static function send($host, $secret): void {
  40. $client = new Client([
  41. 'base_uri' => $host,
  42. 'timeout' => 15,
  43. 'headers' => [
  44. 'secret' => $secret,
  45. 'content-type' => 'application/json'
  46. ]
  47. ]);
  48. $client->post(self::$url, ['body' => json_encode(self::$data)]);
  49. }
  50. }