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