1
0

Clash.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /*
  3. * Developed based on
  4. * https://clash.wiki/configuration/configuration-reference.html
  5. * https://docs.gtk.pw/contents/urlscheme.html#%E4%B8%8B%E8%BD%BD%E9%85%8D%E7%BD%AE
  6. * https://opensource.clash.wiki/Dreamacro/clash/
  7. * https://stash.wiki/get-started
  8. */
  9. namespace App\Utils\Clients;
  10. use App\Models\User;
  11. use App\Utils\Library\Templates\Client;
  12. use File;
  13. use Symfony\Component\Yaml\Yaml;
  14. class Clash implements Client
  15. {
  16. public const AGENT = ['clash', 'stash', 'bob_vpn'];
  17. public function getConfig(array $servers, User $user, string $target): array|string
  18. {
  19. $custom_path = '/resources/rules/custom.clash.yaml';
  20. if (str_contains($target, 'bob_vpn')) {
  21. $file_path = '/resources/rules/bob.clash.yaml';
  22. } elseif (File::exists(base_path().$custom_path)) {
  23. $file_path = $custom_path;
  24. } else {
  25. $file_path = '/resources/rules/default.clash.yaml';
  26. }
  27. $appName = sysConfig('website_name');
  28. header("content-disposition:attachment;filename*=UTF-8''".rawurlencode($appName).'.yaml');
  29. header('profile-update-interval: 24');
  30. header('profile-web-page-url:'.sysConfig('website_url'));
  31. if (sysConfig('is_custom_subscribe')) {
  32. // display remaining traffic and expire date
  33. header("subscription-userinfo: upload=$user->u; download=$user->d; total=$user->transfer_enable; expire=".strtotime($user->expired_at));
  34. }
  35. $config = Yaml::parseFile(base_path().$file_path);
  36. $proxyProfiles = Protocols\Clash::build($servers);
  37. $config['proxies'] = array_merge($config['proxies'] ?: [], $proxyProfiles['proxies']);
  38. foreach ($config['proxy-groups'] as $k => $v) {
  39. if (! is_array($config['proxy-groups'][$k]['proxies'])) {
  40. continue;
  41. }
  42. $config['proxy-groups'][$k]['proxies'] = array_merge($config['proxy-groups'][$k]['proxies'], $proxyProfiles['name']);
  43. }
  44. array_unshift($config['rules'], 'DOMAIN,'.$_SERVER['HTTP_HOST'].',DIRECT'); // Set current sub-domain to be direct
  45. return str_replace('$app_name', $appName, Yaml::dump($config, 2, 4, Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE));
  46. }
  47. }