SysUpdateService.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using System.IO.Compression;
  7. namespace Admin.NET.Core.Service;
  8. /// <summary>
  9. /// 系统更新管理服务 🧩
  10. /// </summary>
  11. [ApiDescriptionSettings(Order = 390)]
  12. public class SysUpdateService : IDynamicApiController, ITransient
  13. {
  14. private readonly SqlSugarRepository<SysUser> _sysUserRep;
  15. private readonly SysOnlineUserService _onlineUserService;
  16. private readonly SysCacheService _sysCacheService;
  17. private readonly GiteeOptions _giteeOptions;
  18. private readonly UserManager _userManager;
  19. public SysUpdateService(
  20. SqlSugarRepository<SysUser> sysUserRep,
  21. SysOnlineUserService onlineUserService,
  22. IOptions<GiteeOptions> giteeOptions,
  23. SysCacheService sysCacheService,
  24. UserManager userManager)
  25. {
  26. _sysUserRep = sysUserRep;
  27. _userManager = userManager;
  28. _giteeOptions = giteeOptions.Value;
  29. _sysCacheService = sysCacheService;
  30. _onlineUserService = onlineUserService;
  31. }
  32. /// <summary>
  33. /// 从远端更新项目
  34. /// </summary>
  35. /// <returns></returns>
  36. public async Task Update()
  37. {
  38. var originColor = Console.ForegroundColor;
  39. Console.ForegroundColor = ConsoleColor.Yellow;
  40. Console.WriteLine($"【{DateTime.Now}】从远端仓库部署项目");
  41. try
  42. {
  43. await SendMessage("----------------------------从远端仓库部署项目-开始----------------------------");
  44. await SendMessage($"仓库地址:https://gitee.com/{_giteeOptions.Owner}/{_giteeOptions.Repo}.git");
  45. await SendMessage($"仓库分支:{_giteeOptions.Branch}");
  46. await SendMessage("项目备份...");
  47. // TODO 备份项目
  48. // 获取解压后的根目录
  49. var rootPath = Path.GetFullPath(Path.Combine(_giteeOptions.OutputDir.BackEnd, ".."));
  50. var tempDir = Path.Combine(rootPath, $"{_giteeOptions.Repo}-{_giteeOptions.Branch}");
  51. await SendMessage("清理旧文件...");
  52. TryDeleteFileOrDir(tempDir);
  53. await SendMessage("拉取远端代码...");
  54. var stream = await GiteeHelper.DownloadRepoZip(_giteeOptions.Owner, _giteeOptions.Repo,
  55. _giteeOptions.AccessToken, _giteeOptions.Branch);
  56. await SendMessage("文件包解压...");
  57. using ZipArchive archive = new(stream, ZipArchiveMode.Read, leaveOpen: false);
  58. archive.ExtractToDirectory(rootPath);
  59. // 项目目录
  60. var backendDir = "Admin.NET";
  61. var entryProjectName = "Admin.NET.Web.Entry";
  62. await SendMessage("编译项目...");
  63. await SendMessage($"发布版本:{_giteeOptions.Publish.Configuration}");
  64. await SendMessage($"目标框架:{_giteeOptions.Publish.TargetFramework}");
  65. await SendMessage($"运行环境:{_giteeOptions.Publish.RuntimeIdentifier}");
  66. var option = _giteeOptions.Publish;
  67. var adminNetDir = Path.Combine(tempDir, backendDir);
  68. var args =
  69. $"publish \"{entryProjectName}\" -c {option.Configuration} -f {option.TargetFramework} -r {option.RuntimeIdentifier} --output \"{_giteeOptions.OutputDir.BackEnd}\"";
  70. await RunCommandAsync("dotnet", args, adminNetDir);
  71. await SendMessage("清理文件...");
  72. TryDeleteFileOrDir(tempDir);
  73. await SendMessage("----------------------------从远端仓库部署项目-结束----------------------------");
  74. }
  75. catch (Exception ex)
  76. {
  77. await SendMessage("发生异常:" + ex.Message);
  78. throw;
  79. }
  80. finally
  81. {
  82. Console.ForegroundColor = originColor;
  83. }
  84. }
  85. /// <summary>
  86. /// 推送消息
  87. /// </summary>
  88. /// <param name="message"></param>
  89. public Task SendMessage(string message)
  90. {
  91. var logList = _sysCacheService.Get<List<string>>(CacheConst.KeySysUpdateLog) ?? new();
  92. var content = $"【{DateTime.Now}】 {message}";
  93. Console.WriteLine(content);
  94. logList.Add(content);
  95. _sysCacheService.Set(CacheConst.KeySysUpdateLog, logList);
  96. return Task.CompletedTask;
  97. }
  98. /// <summary>
  99. /// 执行命令
  100. /// </summary>
  101. /// <param name="command">命令</param>
  102. /// <param name="arguments">参数</param>
  103. /// <param name="workingDirectory">工作目录</param>
  104. private async Task RunCommandAsync(string command, string arguments, string workingDirectory)
  105. {
  106. var processStartInfo = new ProcessStartInfo
  107. {
  108. FileName = command,
  109. Arguments = arguments,
  110. WorkingDirectory = workingDirectory,
  111. RedirectStandardOutput = true,
  112. RedirectStandardError = true,
  113. StandardOutputEncoding = Encoding.UTF8,
  114. StandardErrorEncoding = Encoding.UTF8,
  115. UseShellExecute = false,
  116. CreateNoWindow = true
  117. };
  118. using var process = new Process();
  119. process.StartInfo = processStartInfo;
  120. process.Start();
  121. while (!process.StandardOutput.EndOfStream)
  122. {
  123. string line = await process.StandardOutput.ReadLineAsync();
  124. if (string.IsNullOrEmpty(line)) continue;
  125. await SendMessage(line.Trim());
  126. }
  127. await process.WaitForExitAsync();
  128. }
  129. /// <summary>
  130. /// 尝试删除文件/目录
  131. /// </summary>
  132. /// <param name="path"></param>
  133. /// <returns></returns>
  134. private void TryDeleteFileOrDir(string path)
  135. {
  136. try
  137. {
  138. if (string.IsNullOrEmpty(path)) return;
  139. if (Directory.Exists(path)) Directory.Delete(path, recursive: true);
  140. else File.Delete(path);
  141. }
  142. catch (Exception)
  143. {
  144. // ignored
  145. }
  146. }
  147. }