GetUpdatePkgExcutor.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using LJLib;
  2. using LJLib.Net.SPI.Com;
  3. using LJLib.Tools.Encry;
  4. using LJProxy.LJLib.Net.SPI.Server;
  5. using LJProxy.Models;
  6. using Microsoft.AspNetCore.Mvc;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Threading.Tasks;
  12. namespace LJProxy.Excutor
  13. {
  14. public class GetUpdatePkgExcutor : ExcutorBase<GetUpdatePkgRequest>
  15. {
  16. private static object _syncRoot = new object();
  17. protected override IActionResult ExcuteInternal(GetUpdatePkgRequest request, object state)
  18. {
  19. GetUpdatePkgResponse rslt = new GetUpdatePkgResponse();
  20. rslt.ErrCode = "0";
  21. var apkDirs = @$"{AppDomain.CurrentDomain.BaseDirectory}apk\";
  22. if (!Directory.Exists(apkDirs))
  23. {
  24. rslt.ErrMsg = "apk file folder not exists";
  25. return new JsonResult(rslt);
  26. }
  27. //cache file version
  28. GetUpdatePkgResponse apkInfo = null;
  29. string cacheKey = "NewestApkData";
  30. lock (_syncRoot)
  31. {
  32. apkInfo = Cache.DefaultCache.Get(cacheKey) as GetUpdatePkgResponse;
  33. if (apkInfo == null)
  34. {
  35. var dirinfo = new DirectoryInfo(apkDirs);
  36. var file = dirinfo.GetFiles()
  37. .Where(x => x.Name.EndsWith(".apk", StringComparison.CurrentCultureIgnoreCase))
  38. .OrderByDescending(x => x.LastWriteTime).FirstOrDefault();
  39. if (file == null)
  40. {
  41. rslt.ErrMsg = "can not found apk";
  42. return new JsonResult(rslt);
  43. }
  44. byte[] apkData = null;
  45. using (var fs = file.OpenRead())
  46. using (var ms = new MemoryStream())
  47. {
  48. byte[] buff = new byte[10240];
  49. int read = 0;
  50. int total = 0;
  51. while ((read = fs.Read(buff, 0, buff.Length)) > 0)
  52. {
  53. ms.Write(buff, 0, read);
  54. ms.Flush();
  55. total += read;
  56. }
  57. apkData = ms.ToArray();
  58. }
  59. APKHelper apkHelper = new APKHelper();
  60. var md5Helper = new MD5();
  61. var clientVer = apkHelper.GetVersionName(apkData);
  62. apkInfo = new GetUpdatePkgResponse();
  63. apkInfo.Version = clientVer;
  64. apkInfo.ApkData = apkData;
  65. apkInfo.Checksum = md5Helper.GetMD5(apkData);
  66. //TODO:文件夹缓存依赖不生效,待扩展
  67. Cache.DefaultCache.Add(cacheKey, apkInfo, Cache.CreateCacheItemPolicy(null, DateTime.Now.AddMinutes(30), new List<string>() { file.FullName }));
  68. }
  69. }
  70. rslt.Version = apkInfo.Version;
  71. rslt.ApkData = apkInfo.ApkData;
  72. rslt.Checksum = apkInfo.Checksum;
  73. return new JsonResult(rslt);
  74. }
  75. }
  76. }