L1SvrFileInfo.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using LJLib.Net.SPI.Client;
  2. using LJProxy.Models;
  3. using Microsoft.Extensions.FileProviders;
  4. using Newtonsoft.Json;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Threading.Tasks;
  10. namespace LJProxy.Providers
  11. {
  12. public class L1SvrFileInfo : IFileInfo
  13. {
  14. private string _fullFilepath;
  15. private string _subpath;
  16. private FileInfo _file;
  17. private Stream _stream;
  18. private ILJClient _ljPool;
  19. private static object _syncRoot = new object();
  20. public L1SvrFileInfo(string fullFilepath, string subpath, ILJClient ljPool)
  21. {
  22. _fullFilepath = fullFilepath;
  23. _subpath = subpath;
  24. _ljPool = ljPool;
  25. if (File.Exists(_fullFilepath))
  26. {
  27. _file = new FileInfo(_fullFilepath);
  28. _stream = _file.OpenRead();
  29. }
  30. else
  31. {
  32. lock (_syncRoot)
  33. {
  34. if (File.Exists(_fullFilepath))
  35. {
  36. _file = new FileInfo(_fullFilepath);
  37. _stream = _file.OpenRead();
  38. }
  39. else
  40. {
  41. GetRemoteFile();
  42. if (File.Exists(_fullFilepath))
  43. {
  44. _file = new FileInfo(_fullFilepath);
  45. _stream = _file.OpenRead();
  46. }
  47. }
  48. }
  49. }
  50. }
  51. public bool Exists => _file!=null;
  52. public bool IsDirectory => false;
  53. public DateTimeOffset LastModified => _file.LastWriteTime;
  54. public long Length => _stream.Length;
  55. public string Name => _file.Name;
  56. public string PhysicalPath => _file.FullName;
  57. public Stream CreateReadStream()
  58. {
  59. return _stream;
  60. }
  61. public void GetRemoteFile()
  62. {
  63. var getFileReq = new GetFileRequest() {
  64. Filepath = _subpath
  65. };
  66. var responseStr = _ljPool.DoExcute(getFileReq.GetApiName(),JsonConvert.SerializeObject(getFileReq));
  67. var response = JsonConvert.DeserializeObject<GetFileResponse>(responseStr);
  68. if (string.IsNullOrEmpty(response.ErrMsg))
  69. {
  70. var fileDir = Path.GetDirectoryName(_fullFilepath);
  71. if (!Directory.Exists(fileDir)){
  72. Directory.CreateDirectory(fileDir);
  73. }
  74. File.WriteAllBytes(_fullFilepath, response.FileData);
  75. }
  76. }
  77. }
  78. }