using LJLib.Net.SPI.Client; using LJProxy.Models; using Microsoft.Extensions.FileProviders; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace LJProxy.Providers { public class L1SvrFileInfo : IFileInfo { private string _fullFilepath; private string _subpath; private FileInfo _file; private FileInfo _tempFile; private MemoryStream _stream; private ILJClient _ljPool; private static object _syncRoot = new object(); private string _token; public L1SvrFileInfo(string fullFilepath, string subpath, ILJClient ljPool,string token) { _fullFilepath = fullFilepath; _subpath = subpath; _ljPool = ljPool; _token = token; _stream = new MemoryStream(); ; if (File.Exists(_fullFilepath)) { _tempFile = new FileInfo(_fullFilepath); CheckAuthorizationOrGetRemoteFile(_tempFile.LastWriteTime, true); } else { lock (_syncRoot) { if (File.Exists(_fullFilepath)) { _tempFile = new FileInfo(_fullFilepath); CheckAuthorizationOrGetRemoteFile(_tempFile.LastWriteTime,true); } else { CheckAuthorizationOrGetRemoteFile(null); } } } } public bool Exists => _file!=null; public bool IsDirectory => false; public DateTimeOffset LastModified => _file.LastWriteTime; public long Length => _stream.Length; public string Name => _file.Name; public string PhysicalPath => _file.FullName; public Stream CreateReadStream() { return _stream; } public void CheckAuthorizationOrGetRemoteFile(DateTime? lastWriteTime, bool checkAuthorization=false) { var getFileReq = new GetFileRequest() { Filepath = _subpath, token = _token, checkAuthorization = checkAuthorization, lastWriteTime = lastWriteTime }; var responseStr = _ljPool.DoExcute(getFileReq.GetApiName(),JsonConvert.SerializeObject(getFileReq)); var response = JsonConvert.DeserializeObject(responseStr); if (response.AppErrCode == "900") { if (!checkAuthorization) { var fileDir = Path.GetDirectoryName(_fullFilepath); if (!Directory.Exists(fileDir)) { Directory.CreateDirectory(fileDir); } File.WriteAllBytes(_fullFilepath, response.FileData); } else { if(response.FileData!=null && response.FileData.Length > 0) { var fileDir = Path.GetDirectoryName(_fullFilepath); if (!Directory.Exists(fileDir)) { Directory.CreateDirectory(fileDir); } File.WriteAllBytes(_fullFilepath, response.FileData); } } _file = new FileInfo(_fullFilepath); byte[] buff = new byte[1024]; using(var fs = _file.OpenRead()) { int readCount = fs.Read(buff, 0, buff.Length); while (readCount > 0) { _stream.Write(buff, 0, readCount); readCount = fs.Read(buff, 0, buff.Length); } } } } } }