UpgradeService.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using Microsoft.Extensions.Logging;
  2. using System;
  3. using System.Linq;
  4. using System.Net.Http;
  5. using System.Net.Http.Json;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace FastGithub.Upgrade
  9. {
  10. /// <summary>
  11. /// 升级服务
  12. /// </summary>
  13. sealed class UpgradeService
  14. {
  15. private readonly ILogger<UpgradeService> logger;
  16. private const string DownloadPage = "https://gitee.com/jiulang/fast-github/releases";
  17. private const string ReleasesUri = "https://gitee.com/api/v5/repos/jiulang/fast-github/releases?page=1&per_page=1&direction=desc";
  18. /// <summary>
  19. /// 升级服务
  20. /// </summary>
  21. /// <param name="logger"></param>
  22. public UpgradeService(ILogger<UpgradeService> logger)
  23. {
  24. this.logger = logger;
  25. }
  26. /// <summary>
  27. /// 进行升级
  28. /// </summary>
  29. /// <param name="cancellationToken"></param>
  30. /// <returns></returns>
  31. public async Task UpgradeAsync(CancellationToken cancellationToken)
  32. {
  33. var currentVersion = ProductionVersion.GetApplicationVersion();
  34. if (currentVersion == null)
  35. {
  36. return;
  37. }
  38. var lastRelease = await this.GetLastedReleaseAsync(cancellationToken);
  39. if (lastRelease == null)
  40. {
  41. return;
  42. }
  43. var lastedVersion = lastRelease.GetProductionVersion();
  44. if (lastedVersion.CompareTo(currentVersion) > 0)
  45. {
  46. this.logger.LogInformation($"您正在使用{currentVersion}版本{Environment.NewLine}请前往{DownloadPage}下载新版本");
  47. this.logger.LogInformation(lastRelease.ToString());
  48. }
  49. }
  50. /// <summary>
  51. /// 获取最新发布
  52. /// </summary>
  53. /// <returns></returns>
  54. public async Task<GiteeRelease?> GetLastedReleaseAsync(CancellationToken cancellationToken)
  55. {
  56. using var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5d) };
  57. var releases = await httpClient.GetFromJsonAsync<GiteeRelease[]>(ReleasesUri, cancellationToken);
  58. return releases?.FirstOrDefault();
  59. }
  60. }
  61. }