You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ShadowsocksController.cs 25 kB

7 years ago
11 years ago
7 years ago
11 years ago
11 years ago
11 years ago
7 years ago
11 years ago
11 years ago
11 years ago
7 years ago
7 years ago
7 years ago
11 years ago
7 years ago
11 years ago
7 years ago
7 years ago
11 years ago
11 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
10 years ago
10 years ago
7 years ago
10 years ago
7 years ago
11 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Net.Sockets;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using System.Web;
  13. using System.Windows.Forms;
  14. using NLog;
  15. using Shadowsocks.Controller.Service;
  16. using Shadowsocks.Controller.Strategy;
  17. using Shadowsocks.Model;
  18. using Shadowsocks.Util;
  19. namespace Shadowsocks.Controller
  20. {
  21. public class ShadowsocksController
  22. {
  23. private readonly Logger logger;
  24. private readonly HttpClient httpClient;
  25. // controller:
  26. // handle user actions
  27. // manipulates UI
  28. // interacts with low level logic
  29. #region Members definition
  30. private Thread _trafficThread;
  31. private Listener _listener;
  32. private PACDaemon _pacDaemon;
  33. private PACServer _pacServer;
  34. private Configuration _config;
  35. private StrategyManager _strategyManager;
  36. private PrivoxyRunner privoxyRunner;
  37. private readonly ConcurrentDictionary<Server, Sip003Plugin> _pluginsByServer;
  38. public AvailabilityStatistics availabilityStatistics = AvailabilityStatistics.Instance;
  39. public StatisticsStrategyConfiguration StatisticsConfiguration { get; private set; }
  40. private long _inboundCounter = 0;
  41. private long _outboundCounter = 0;
  42. public long InboundCounter => Interlocked.Read(ref _inboundCounter);
  43. public long OutboundCounter => Interlocked.Read(ref _outboundCounter);
  44. public Queue<TrafficPerSecond> trafficPerSecondQueue;
  45. private bool stopped = false;
  46. public class PathEventArgs : EventArgs
  47. {
  48. public string Path;
  49. }
  50. public class UpdatedEventArgs : EventArgs
  51. {
  52. public string OldVersion;
  53. public string NewVersion;
  54. }
  55. public class TrafficPerSecond
  56. {
  57. public long inboundCounter;
  58. public long outboundCounter;
  59. public long inboundIncreasement;
  60. public long outboundIncreasement;
  61. }
  62. public event EventHandler ConfigChanged;
  63. public event EventHandler EnableStatusChanged;
  64. public event EventHandler EnableGlobalChanged;
  65. public event EventHandler ShareOverLANStatusChanged;
  66. public event EventHandler VerboseLoggingStatusChanged;
  67. public event EventHandler ShowPluginOutputChanged;
  68. public event EventHandler TrafficChanged;
  69. // when user clicked Edit PAC, and PAC file has already created
  70. public event EventHandler<PathEventArgs> PACFileReadyToOpen;
  71. public event EventHandler<PathEventArgs> UserRuleFileReadyToOpen;
  72. public event EventHandler<GeositeResultEventArgs> UpdatePACFromGeositeCompleted;
  73. public event ErrorEventHandler UpdatePACFromGeositeError;
  74. public event ErrorEventHandler Errored;
  75. // Invoked when controller.Start();
  76. public event EventHandler<UpdatedEventArgs> ProgramUpdated;
  77. #endregion
  78. public ShadowsocksController()
  79. {
  80. logger = LogManager.GetCurrentClassLogger();
  81. httpClient = new HttpClient();
  82. _config = Configuration.Load();
  83. Configuration.Process(ref _config);
  84. StatisticsConfiguration = StatisticsStrategyConfiguration.Load();
  85. _strategyManager = new StrategyManager(this);
  86. _pluginsByServer = new ConcurrentDictionary<Server, Sip003Plugin>();
  87. StartTrafficStatistics(61);
  88. ProgramUpdated += (o, e) =>
  89. {
  90. logger.Info($"Updated from {e.OldVersion} to {e.NewVersion}");
  91. };
  92. }
  93. #region Basic
  94. public void Start(bool systemWakeUp = false)
  95. {
  96. if (_config.firstRunOnNewVersion && !systemWakeUp)
  97. {
  98. ProgramUpdated.Invoke(this, new UpdatedEventArgs()
  99. {
  100. OldVersion = _config.version,
  101. NewVersion = UpdateChecker.Version,
  102. });
  103. // delete pac.txt when regeneratePacOnUpdate is true
  104. if (_config.regeneratePacOnUpdate)
  105. try
  106. {
  107. File.Delete(PACDaemon.PAC_FILE);
  108. logger.Info("Deleted pac.txt from previous version.");
  109. }
  110. catch (Exception e)
  111. {
  112. logger.LogUsefulException(e);
  113. }
  114. // finish up first run of new version
  115. _config.firstRunOnNewVersion = false;
  116. _config.version = UpdateChecker.Version;
  117. Configuration.Save(_config);
  118. }
  119. Reload();
  120. if (!systemWakeUp)
  121. HotkeyReg.RegAllHotkeys();
  122. }
  123. public void Stop()
  124. {
  125. if (stopped)
  126. {
  127. return;
  128. }
  129. stopped = true;
  130. if (_listener != null)
  131. {
  132. _listener.Stop();
  133. }
  134. StopPlugins();
  135. if (privoxyRunner != null)
  136. {
  137. privoxyRunner.Stop();
  138. }
  139. if (_config.enabled)
  140. {
  141. SystemProxy.Update(_config, true, null);
  142. }
  143. Encryption.RNG.Close();
  144. }
  145. protected void Reload()
  146. {
  147. Encryption.RNG.Reload();
  148. // some logic in configuration updated the config when saving, we need to read it again
  149. _config = Configuration.Load();
  150. Configuration.Process(ref _config);
  151. NLogConfig.LoadConfiguration();
  152. // set User-Agent for httpClient
  153. try
  154. {
  155. if (!string.IsNullOrWhiteSpace(_config.userAgentString))
  156. httpClient.DefaultRequestHeaders.Add("User-Agent", _config.userAgentString);
  157. }
  158. catch
  159. {
  160. // reset userAgent to default and reapply
  161. Configuration.ResetUserAgent(_config);
  162. httpClient.DefaultRequestHeaders.Add("User-Agent", _config.userAgentString);
  163. }
  164. StatisticsConfiguration = StatisticsStrategyConfiguration.Load();
  165. privoxyRunner = privoxyRunner ?? new PrivoxyRunner();
  166. _pacDaemon = _pacDaemon ?? new PACDaemon(_config);
  167. _pacDaemon.PACFileChanged += PacDaemon_PACFileChanged;
  168. _pacDaemon.UserRuleFileChanged += PacDaemon_UserRuleFileChanged;
  169. _pacServer = _pacServer ?? new PACServer(_pacDaemon);
  170. _pacServer.UpdatePACURL(_config); // So PACServer works when system proxy disabled.
  171. GeositeUpdater.ResetEvent();
  172. GeositeUpdater.UpdateCompleted += PacServer_PACUpdateCompleted;
  173. GeositeUpdater.Error += PacServer_PACUpdateError;
  174. availabilityStatistics.UpdateConfiguration(this);
  175. _listener?.Stop();
  176. StopPlugins();
  177. // don't put PrivoxyRunner.Start() before pacServer.Stop()
  178. // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1
  179. // though UseShellExecute is set to true now
  180. // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open
  181. privoxyRunner.Stop();
  182. try
  183. {
  184. var strategy = GetCurrentStrategy();
  185. strategy?.ReloadServers();
  186. StartPlugin();
  187. privoxyRunner.Start(_config);
  188. TCPRelay tcpRelay = new TCPRelay(this, _config);
  189. tcpRelay.OnConnected += UpdateLatency;
  190. tcpRelay.OnInbound += UpdateInboundCounter;
  191. tcpRelay.OnOutbound += UpdateOutboundCounter;
  192. tcpRelay.OnFailed += (o, e) => GetCurrentStrategy()?.SetFailure(e.server);
  193. UDPRelay udpRelay = new UDPRelay(this);
  194. List<Listener.IService> services = new List<Listener.IService>
  195. {
  196. tcpRelay,
  197. udpRelay,
  198. _pacServer,
  199. new PortForwarder(privoxyRunner.RunningPort)
  200. };
  201. _listener = new Listener(services);
  202. _listener.Start(_config);
  203. }
  204. catch (Exception e)
  205. {
  206. // translate Microsoft language into human language
  207. // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use
  208. if (e is SocketException se)
  209. {
  210. if (se.SocketErrorCode == SocketError.AddressAlreadyInUse)
  211. {
  212. e = new Exception(I18N.GetString("Port {0} already in use", _config.localPort), e);
  213. }
  214. else if (se.SocketErrorCode == SocketError.AccessDenied)
  215. {
  216. e = new Exception(I18N.GetString("Port {0} is reserved by system", _config.localPort), e);
  217. }
  218. }
  219. logger.LogUsefulException(e);
  220. ReportError(e);
  221. }
  222. ConfigChanged?.Invoke(this, new EventArgs());
  223. UpdateSystemProxy();
  224. }
  225. protected void SaveConfig(Configuration newConfig)
  226. {
  227. Configuration.Save(newConfig);
  228. Reload();
  229. }
  230. protected void ReportError(Exception e)
  231. {
  232. Errored?.Invoke(this, new ErrorEventArgs(e));
  233. }
  234. public HttpClient GetHttpClient() => httpClient;
  235. public Server GetCurrentServer() => _config.GetCurrentServer();
  236. public Configuration GetCurrentConfiguration() => _config;
  237. public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint)
  238. {
  239. IStrategy strategy = GetCurrentStrategy();
  240. if (strategy != null)
  241. {
  242. return strategy.GetAServer(type, localIPEndPoint, destEndPoint);
  243. }
  244. if (_config.index < 0)
  245. {
  246. _config.index = 0;
  247. }
  248. return GetCurrentServer();
  249. }
  250. public void SaveServers(List<Server> servers, int localPort, bool portableMode)
  251. {
  252. _config.configs = servers;
  253. _config.localPort = localPort;
  254. _config.portableMode = portableMode;
  255. Configuration.Save(_config);
  256. }
  257. public void SelectServerIndex(int index)
  258. {
  259. _config.index = index;
  260. _config.strategy = null;
  261. SaveConfig(_config);
  262. }
  263. public void ToggleShareOverLAN(bool enabled)
  264. {
  265. _config.shareOverLan = enabled;
  266. SaveConfig(_config);
  267. ShareOverLANStatusChanged?.Invoke(this, new EventArgs());
  268. }
  269. #endregion
  270. #region OS Proxy
  271. public void ToggleEnable(bool enabled)
  272. {
  273. _config.enabled = enabled;
  274. SaveConfig(_config);
  275. EnableStatusChanged?.Invoke(this, new EventArgs());
  276. }
  277. public void ToggleGlobal(bool global)
  278. {
  279. _config.global = global;
  280. SaveConfig(_config);
  281. EnableGlobalChanged?.Invoke(this, new EventArgs());
  282. }
  283. public void SaveProxy(ForwardProxyConfig proxyConfig)
  284. {
  285. _config.proxy = proxyConfig;
  286. SaveConfig(_config);
  287. }
  288. private void UpdateSystemProxy()
  289. {
  290. SystemProxy.Update(_config, false, _pacServer);
  291. }
  292. #endregion
  293. #region PAC
  294. private void PacDaemon_PACFileChanged(object sender, EventArgs e)
  295. {
  296. UpdateSystemProxy();
  297. }
  298. private void PacServer_PACUpdateCompleted(object sender, GeositeResultEventArgs e)
  299. {
  300. UpdatePACFromGeositeCompleted?.Invoke(this, e);
  301. }
  302. private void PacServer_PACUpdateError(object sender, ErrorEventArgs e)
  303. {
  304. UpdatePACFromGeositeError?.Invoke(this, e);
  305. }
  306. private static readonly IEnumerable<char> IgnoredLineBegins = new[] { '!', '[' };
  307. private void PacDaemon_UserRuleFileChanged(object sender, EventArgs e)
  308. {
  309. GeositeUpdater.MergeAndWritePACFile(_config.geositeDirectGroups, _config.geositeProxiedGroups, _config.geositePreferDirect);
  310. UpdateSystemProxy();
  311. }
  312. public void CopyPacUrl()
  313. {
  314. Clipboard.SetDataObject(_pacServer.PacUrl);
  315. }
  316. public void SavePACUrl(string pacUrl)
  317. {
  318. _config.pacUrl = pacUrl;
  319. SaveConfig(_config);
  320. ConfigChanged?.Invoke(this, new EventArgs());
  321. }
  322. public void UseOnlinePAC(bool useOnlinePac)
  323. {
  324. _config.useOnlinePac = useOnlinePac;
  325. SaveConfig(_config);
  326. ConfigChanged?.Invoke(this, new EventArgs());
  327. }
  328. public void TouchPACFile()
  329. {
  330. string pacFilename = _pacDaemon.TouchPACFile();
  331. PACFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = pacFilename });
  332. }
  333. public void TouchUserRuleFile()
  334. {
  335. string userRuleFilename = _pacDaemon.TouchUserRuleFile();
  336. UserRuleFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = userRuleFilename });
  337. }
  338. public void ToggleSecureLocalPac(bool enabled)
  339. {
  340. _config.secureLocalPac = enabled;
  341. SaveConfig(_config);
  342. ConfigChanged?.Invoke(this, new EventArgs());
  343. }
  344. public void ToggleRegeneratePacOnUpdate(bool enabled)
  345. {
  346. _config.regeneratePacOnUpdate = enabled;
  347. SaveConfig(_config);
  348. ConfigChanged?.Invoke(this, new EventArgs());
  349. }
  350. #endregion
  351. #region SIP002
  352. public bool AskAddServerBySSURL(string ssURL)
  353. {
  354. var dr = MessageBox.Show(I18N.GetString("Import from URL: {0} ?", ssURL), I18N.GetString("Shadowsocks"), MessageBoxButtons.YesNo);
  355. if (dr == DialogResult.Yes)
  356. {
  357. if (AddServerBySSURL(ssURL))
  358. {
  359. MessageBox.Show(I18N.GetString("Successfully imported from {0}", ssURL));
  360. return true;
  361. }
  362. else
  363. {
  364. MessageBox.Show(I18N.GetString("Failed to import. Please check if the link is valid."));
  365. }
  366. }
  367. return false;
  368. }
  369. public bool AddServerBySSURL(string ssURL)
  370. {
  371. try
  372. {
  373. if (string.IsNullOrWhiteSpace(ssURL))
  374. return false;
  375. var servers = Server.GetServers(ssURL);
  376. if (servers == null || servers.Count == 0)
  377. return false;
  378. foreach (var server in servers)
  379. {
  380. _config.configs.Add(server);
  381. }
  382. _config.index = _config.configs.Count - 1;
  383. SaveConfig(_config);
  384. return true;
  385. }
  386. catch (Exception e)
  387. {
  388. logger.LogUsefulException(e);
  389. return false;
  390. }
  391. }
  392. public string GetServerURLForCurrentServer()
  393. {
  394. return GetCurrentServer().GetURL(_config.generateLegacyUrl);
  395. }
  396. #endregion
  397. #region Misc
  398. public void ToggleVerboseLogging(bool enabled)
  399. {
  400. _config.isVerboseLogging = enabled;
  401. SaveConfig(_config);
  402. NLogConfig.LoadConfiguration(); // reload nlog
  403. VerboseLoggingStatusChanged?.Invoke(this, new EventArgs());
  404. }
  405. public void ToggleCheckingUpdate(bool enabled)
  406. {
  407. _config.autoCheckUpdate = enabled;
  408. Configuration.Save(_config);
  409. ConfigChanged?.Invoke(this, new EventArgs());
  410. }
  411. public void ToggleCheckingPreRelease(bool enabled)
  412. {
  413. _config.checkPreRelease = enabled;
  414. Configuration.Save(_config);
  415. ConfigChanged?.Invoke(this, new EventArgs());
  416. }
  417. public void SaveSkippedUpdateVerion(string version)
  418. {
  419. _config.skippedUpdateVersion = version;
  420. Configuration.Save(_config);
  421. }
  422. public void SaveLogViewerConfig(LogViewerConfig newConfig)
  423. {
  424. _config.logViewer = newConfig;
  425. newConfig.SaveSize();
  426. Configuration.Save(_config);
  427. ConfigChanged?.Invoke(this, new EventArgs());
  428. }
  429. public void SaveHotkeyConfig(HotkeyConfig newConfig)
  430. {
  431. _config.hotkey = newConfig;
  432. SaveConfig(_config);
  433. ConfigChanged?.Invoke(this, new EventArgs());
  434. }
  435. #endregion
  436. #region Statistics
  437. public void SelectStrategy(string strategyID)
  438. {
  439. _config.index = -1;
  440. _config.strategy = strategyID;
  441. SaveConfig(_config);
  442. }
  443. public void SaveStrategyConfigurations(StatisticsStrategyConfiguration configuration)
  444. {
  445. StatisticsConfiguration = configuration;
  446. StatisticsStrategyConfiguration.Save(configuration);
  447. }
  448. public IList<IStrategy> GetStrategies()
  449. {
  450. return _strategyManager.GetStrategies();
  451. }
  452. public IStrategy GetCurrentStrategy()
  453. {
  454. foreach (var strategy in _strategyManager.GetStrategies())
  455. {
  456. if (strategy.ID == _config.strategy)
  457. {
  458. return strategy;
  459. }
  460. }
  461. return null;
  462. }
  463. public void UpdateStatisticsConfiguration(bool enabled)
  464. {
  465. if (availabilityStatistics != null)
  466. {
  467. availabilityStatistics.UpdateConfiguration(this);
  468. _config.availabilityStatistics = enabled;
  469. SaveConfig(_config);
  470. }
  471. }
  472. public void UpdateLatency(object sender, SSTCPConnectedEventArgs args)
  473. {
  474. GetCurrentStrategy()?.UpdateLatency(args.server, args.latency);
  475. if (_config.availabilityStatistics)
  476. {
  477. availabilityStatistics.UpdateLatency(args.server, (int)args.latency.TotalMilliseconds);
  478. }
  479. }
  480. public void UpdateInboundCounter(object sender, SSTransmitEventArgs args)
  481. {
  482. GetCurrentStrategy()?.UpdateLastRead(args.server);
  483. Interlocked.Add(ref _inboundCounter, args.length);
  484. if (_config.availabilityStatistics)
  485. {
  486. availabilityStatistics.UpdateInboundCounter(args.server, args.length);
  487. }
  488. }
  489. public void UpdateOutboundCounter(object sender, SSTransmitEventArgs args)
  490. {
  491. GetCurrentStrategy()?.UpdateLastWrite(args.server);
  492. Interlocked.Add(ref _outboundCounter, args.length);
  493. if (_config.availabilityStatistics)
  494. {
  495. availabilityStatistics.UpdateOutboundCounter(args.server, args.length);
  496. }
  497. }
  498. #endregion
  499. #region SIP003
  500. private void StartPlugin()
  501. {
  502. var server = _config.GetCurrentServer();
  503. GetPluginLocalEndPointIfConfigured(server);
  504. }
  505. private void StopPlugins()
  506. {
  507. foreach (var serverAndPlugin in _pluginsByServer)
  508. {
  509. serverAndPlugin.Value?.Dispose();
  510. }
  511. _pluginsByServer.Clear();
  512. }
  513. public EndPoint GetPluginLocalEndPointIfConfigured(Server server)
  514. {
  515. var plugin = _pluginsByServer.GetOrAdd(
  516. server,
  517. x => Sip003Plugin.CreateIfConfigured(x, _config.showPluginOutput));
  518. if (plugin == null)
  519. {
  520. return null;
  521. }
  522. try
  523. {
  524. if (plugin.StartIfNeeded())
  525. {
  526. logger.Info(
  527. $"Started SIP003 plugin for {server.Identifier()} on {plugin.LocalEndPoint} - PID: {plugin.ProcessId}");
  528. }
  529. }
  530. catch (Exception ex)
  531. {
  532. logger.Error("Failed to start SIP003 plugin: " + ex.Message);
  533. throw;
  534. }
  535. return plugin.LocalEndPoint;
  536. }
  537. public void ToggleShowPluginOutput(bool enabled)
  538. {
  539. _config.showPluginOutput = enabled;
  540. SaveConfig(_config);
  541. ShowPluginOutputChanged?.Invoke(this, new EventArgs());
  542. }
  543. #endregion
  544. #region Traffic Statistics
  545. private void StartTrafficStatistics(int queueMaxSize)
  546. {
  547. trafficPerSecondQueue = new Queue<TrafficPerSecond>();
  548. for (int i = 0; i < queueMaxSize; i++)
  549. {
  550. trafficPerSecondQueue.Enqueue(new TrafficPerSecond());
  551. }
  552. _trafficThread = new Thread(new ThreadStart(() => TrafficStatistics(queueMaxSize)))
  553. {
  554. IsBackground = true
  555. };
  556. _trafficThread.Start();
  557. }
  558. private void TrafficStatistics(int queueMaxSize)
  559. {
  560. TrafficPerSecond previous, current;
  561. while (true)
  562. {
  563. previous = trafficPerSecondQueue.Last();
  564. current = new TrafficPerSecond
  565. {
  566. inboundCounter = InboundCounter,
  567. outboundCounter = OutboundCounter
  568. };
  569. current.inboundIncreasement = current.inboundCounter - previous.inboundCounter;
  570. current.outboundIncreasement = current.outboundCounter - previous.outboundCounter;
  571. trafficPerSecondQueue.Enqueue(current);
  572. if (trafficPerSecondQueue.Count > queueMaxSize)
  573. trafficPerSecondQueue.Dequeue();
  574. TrafficChanged?.Invoke(this, new EventArgs());
  575. Thread.Sleep(1000);
  576. }
  577. }
  578. #endregion
  579. #region SIP008
  580. public async Task<int> UpdateOnlineConfigInternal(string url)
  581. {
  582. var onlineServer = await OnlineConfigResolver.GetOnline(url);
  583. _config.configs = Configuration.SortByOnlineConfig(
  584. _config.configs
  585. .Where(c => c.group != url)
  586. .Concat(onlineServer)
  587. );
  588. logger.Info($"updated {onlineServer.Count} server from {url}");
  589. return onlineServer.Count;
  590. }
  591. public async Task<bool> UpdateOnlineConfig(string url)
  592. {
  593. var selected = GetCurrentServer();
  594. try
  595. {
  596. int count = await UpdateOnlineConfigInternal(url);
  597. }
  598. catch (Exception e)
  599. {
  600. logger.LogUsefulException(e);
  601. return false;
  602. }
  603. _config.index = _config.configs.IndexOf(selected);
  604. SaveConfig(_config);
  605. return true;
  606. }
  607. public async Task<List<string>> UpdateAllOnlineConfig()
  608. {
  609. var selected = GetCurrentServer();
  610. var failedUrls = new List<string>();
  611. foreach (var url in _config.onlineConfigSource)
  612. {
  613. try
  614. {
  615. await UpdateOnlineConfigInternal(url);
  616. }
  617. catch (Exception e)
  618. {
  619. logger.LogUsefulException(e);
  620. failedUrls.Add(url);
  621. }
  622. }
  623. _config.index = _config.configs.IndexOf(selected);
  624. SaveConfig(_config);
  625. return failedUrls;
  626. }
  627. public void SaveOnlineConfigSource(List<string> sources)
  628. {
  629. _config.onlineConfigSource = sources;
  630. SaveConfig(_config);
  631. }
  632. public void RemoveOnlineConfig(string url)
  633. {
  634. _config.onlineConfigSource.RemoveAll(v => v == url);
  635. _config.configs = Configuration.SortByOnlineConfig(
  636. _config.configs.Where(c => c.group != url)
  637. );
  638. SaveConfig(_config);
  639. }
  640. #endregion
  641. }
  642. }