ProxyService.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Node;
  4. use App\Models\User;
  5. use App\Utils\Clients\Formatters\Text;
  6. use App\Utils\Clients\Formatters\URLSchemes;
  7. use Arr;
  8. use Exception;
  9. use Illuminate\Database\Eloquent\Collection;
  10. use ReflectionClass;
  11. /**
  12. * 订阅代理服务
  13. * 提供代理配置的生成、管理和格式化功能.
  14. */
  15. class ProxyService
  16. {
  17. private static array $servers = [];
  18. private User $user;
  19. public function __construct(?User $user = null)
  20. {
  21. $this->user = $user ?? auth()->user();
  22. }
  23. public function buildClientConfig(?string $target = null, ?int $type = null): string
  24. { // 构建客户端配置
  25. $servers = $this->getServers($type);
  26. // 尝试匹配特定客户端
  27. $classes = glob(app_path('Utils/Clients').'/*.php');
  28. foreach ($classes as $file) {
  29. $className = 'App\\Utils\\Clients\\'.basename($file, '.php');
  30. if (! class_exists($className)) {
  31. continue;
  32. }
  33. $reflection = new ReflectionClass($className);
  34. if (! $reflection->hasConstant('AGENT')) {
  35. continue;
  36. }
  37. $agents = $reflection->getConstant('AGENT');
  38. if (! is_array($agents)) {
  39. continue;
  40. }
  41. foreach ($agents as $agent) {
  42. if (str_contains($target ?? '', $agent)) {
  43. return (new $className)->getConfig($servers, $this->user, $target);
  44. }
  45. }
  46. }
  47. // 默认返回 URL 方案
  48. return URLSchemes::build($servers);
  49. }
  50. private function getServers(?int $type): array
  51. {
  52. if (empty(self::$servers)) {
  53. $servers = $this->fetchAvailableNodes($type);
  54. if (empty($servers)) {
  55. $this->failedProxyReturn(trans('errors.subscribe.none'), $type);
  56. } else {
  57. self::$servers = $servers;
  58. }
  59. }
  60. return self::$servers;
  61. }
  62. public function fetchAvailableNodes(?int $type = null, bool $withConfigs = true): array|Collection
  63. { // 获取用户可用的节点列表
  64. $query = $this->user->nodes()
  65. ->whereIn('is_display', [2, 3]) // 获取这个账号可用节点
  66. ->with(['labels', 'country', 'relayNode']); // 预加载关联关系以避免N+1查询
  67. if ($type === 1 || $type === 4) {
  68. $query->whereIn('type', [1, 4]);
  69. } elseif ($type !== null) {
  70. $query->whereType($type);
  71. }
  72. // 根据配置决定是否随机排序,并应用数量限制
  73. if (sysConfig('rand_subscribe')) {
  74. $query->inRandomOrder();
  75. } else {
  76. $query->orderByDesc('node.sort')->orderBy('node.id');
  77. }
  78. // 限制最大订阅数量
  79. $max = (int) sysConfig('subscribe_max');
  80. if ($max) {
  81. $query->limit($max);
  82. }
  83. $nodes = $query->get();
  84. if ($withConfigs) {
  85. $configs = [];
  86. foreach ($nodes as $node) {
  87. $configs[] = $this->generateNodeConfig($node);
  88. }
  89. return $configs;
  90. }
  91. return $nodes;
  92. }
  93. public function generateNodeConfig(Node $node): array
  94. { // 生成节点的完整配置
  95. $config = [
  96. 'id' => $node->id,
  97. 'name' => $node->name,
  98. 'country' => $node->country_code,
  99. 'labels' => $node->labels->pluck('name')->toArray(),
  100. 'area' => $node->country->name,
  101. 'host' => $node->host,
  102. 'group' => sysConfig('website_name'),
  103. 'udp' => $node->is_udp,
  104. ];
  105. // 如果是中转节点,处理父节点配置
  106. if ($node->relay_node_id) {
  107. $parentConfig = $this->generateNodeConfig($node->relayNode);
  108. $config = array_merge($config, Arr::except($parentConfig, ['id', 'name', 'host', 'group', 'udp']));
  109. if ($parentConfig['type'] === 'trojan') {
  110. $config['sni'] = $parentConfig['host'];
  111. }
  112. $config['port'] = $node->port;
  113. return $config;
  114. }
  115. // 按节点类型生成特定配置
  116. return match ($node->type) {
  117. 0 => [ // Shadowsocks
  118. 'type' => 'shadowsocks',
  119. 'port' => $node->port ?: $this->user->port,
  120. 'passwd' => $this->user->passwd,
  121. ...$node->profile,
  122. ],
  123. 2 => [ // Vmess
  124. 'type' => 'vmess',
  125. 'port' => $node->port,
  126. 'uuid' => $this->user->vmess_id,
  127. ...$node->profile,
  128. ],
  129. 3 => [ // Trojan
  130. 'type' => 'trojan',
  131. 'port' => $node->port,
  132. 'passwd' => $this->user->passwd,
  133. ...$node->profile,
  134. ],
  135. 5 => [ // Hysteria2
  136. 'type' => 'hysteria2',
  137. 'port' => $node->port,
  138. 'passwd' => $this->user->port.':'.$this->user->passwd,
  139. ...$node->profile,
  140. ],
  141. default => array_merge(
  142. [ // 1, 4 => SSR
  143. 'type' => 'shadowsocksr',
  144. ...$node->profile,
  145. ],
  146. ($node->profile['passwd'] ?? false) && $node->port
  147. ? [ // 单端口使用中转的端口
  148. 'port' => $node->port,
  149. 'protocol_param' => $this->user->port.':'.$this->user->passwd,
  150. ]
  151. : [
  152. 'port' => $this->user->port,
  153. 'passwd' => $this->user->passwd,
  154. ],
  155. $node->type === 1
  156. ? [
  157. 'method' => $this->user->method,
  158. 'protocol' => $this->user->protocol,
  159. 'obfs' => $this->user->obfs,
  160. ]
  161. : []
  162. ),
  163. } + $config;
  164. }
  165. public function failedProxyReturn(string $message, int $type = 0): void
  166. { // 设置错误代理返回(用于兼容客户端)
  167. $types = ['shadowsocks', 'shadowsocksr', 'vmess', 'trojan', 'hysteria2'];
  168. $addition = match ($type) {
  169. 1 => ['method' => 'none', 'passwd' => 'error', 'obfs' => 'origin', 'obfs_param' => '', 'protocol' => 'plain', 'protocol_param' => ''],
  170. 2 => ['uuid' => '0', 'v2_alter_id' => 0, 'method' => 'auto'],
  171. 3 => ['passwd' => 'error'],
  172. 5 => ['passwd' => 'error', 'sni' => 'error', 'insecure' => false],
  173. default => ['method' => 'none', 'passwd' => 'error'],
  174. };
  175. // 确保$type在有效范围内
  176. $typeIndex = $type > 5 ? 0 : $type;
  177. self::$servers = [['id' => 0, 'name' => $message, 'type' => $types[$typeIndex], 'host' => sysConfig('website_url'), 'port' => 0, 'udp' => 0, ...$addition]];
  178. }
  179. public function getUserProxyConfig(Node $node, bool $isUrlFormat = false): string
  180. { // 获取用户显示用代理信息
  181. $server = $this->generateNodeConfig($node);
  182. $type = $isUrlFormat ? new URLSchemes : new Text;
  183. return match ($server['type']) {
  184. 'shadowsocks' => $type->buildShadowsocks($server),
  185. 'shadowsocksr' => $type->buildShadowsocksr($server),
  186. 'vmess' => $type->buildVmess($server),
  187. 'trojan' => $type->buildTrojan($server),
  188. 'hysteria2' => $type->buildHysteria2($server),
  189. default => throw new Exception('Unsupported proxy type: '.$server['type']),
  190. };
  191. }
  192. public function setUser(User $user): void
  193. { // 设置用户
  194. $this->user = $user;
  195. }
  196. }