VersionService.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using System.Threading.Tasks;
  8. namespace LJProxy.Services
  9. {
  10. public class VersionService:ServiceBase
  11. {
  12. private static object _updateJsonSyncRoot = new object();
  13. private static object _apkSyncRoot = new object();
  14. public string GetUpdateJson()
  15. {
  16. string updateJson = string.Empty;
  17. string key = "UpdateJson";
  18. lock (_updateJsonSyncRoot)
  19. {
  20. updateJson = Cache.DefaultCache.Get(key) as string;
  21. if (string.IsNullOrEmpty(updateJson))
  22. {
  23. string updateJsonPath = @$"{AppDomain.CurrentDomain.BaseDirectory}apk\update.json";
  24. updateJson = System.IO.File.ReadAllText(updateJsonPath, Encoding.UTF8);
  25. Cache.DefaultCache.Add(key, updateJson, Cache.CreateCacheItemPolicy(null, DateTime.Now.AddMinutes(30), new List<string>() { updateJsonPath }));
  26. }
  27. }
  28. return updateJson;
  29. }
  30. public byte[] GetAPK(string apkName)
  31. {
  32. if (string.IsNullOrEmpty(apkName)) return null;
  33. var updateJson = GetUpdateJson();
  34. var updateInfoObj = JObject.Parse(updateJson);
  35. string url = updateInfoObj["url"]?.ToString();
  36. if (string.IsNullOrEmpty(url))
  37. {
  38. return null;
  39. }
  40. Regex regx = new Regex(@"GetAppUpdate/(?<apkName>.*?\.apk)", RegexOptions.IgnoreCase);
  41. var matchResult = regx.Match(url);
  42. if (matchResult.Success)
  43. {
  44. var jsonApkName = matchResult.Groups["apkName"]?.Value;
  45. if (!apkName.Equals(jsonApkName, StringComparison.OrdinalIgnoreCase)) return null;
  46. string key = apkName.ToLower();
  47. byte[] result = null;
  48. lock (_apkSyncRoot)
  49. {
  50. result = Cache.DefaultCache.Get(key) as byte[];
  51. if (result == null)
  52. {
  53. string apkFilePath = @$"{AppDomain.CurrentDomain.BaseDirectory}apk\{apkName}";
  54. if (!System.IO.File.Exists(apkFilePath))
  55. {
  56. return null;
  57. }
  58. result = System.IO.File.ReadAllBytes(apkFilePath);
  59. Cache.DefaultCache.Add(key, result, Cache.CreateCacheItemPolicy(null, DateTime.Now.AddMinutes(30), new List<string>() { apkFilePath }));
  60. }
  61. }
  62. return result;
  63. }
  64. return null;
  65. }
  66. }
  67. }