示例#1
0
 private static void LoadModuleLangPack(Dictionary <string, string> values, string langCode)
 {
     foreach (var item in VirtualResources.GetFiles(AppSettings.ModulePath, "*config.json", SearchOption.AllDirectories))
     {
         try
         {
             var json = VirtualResources.ReadAllText(item);
             var dic  = JsonHelper.DeserializeJObject(json)?["langs"]?[langCode]?.ToObject <Dictionary <string, string> >();
             if (dic == null)
             {
                 continue;
             }
             foreach (var kv in dic)
             {
                 if (!values.ContainsKey(kv.Key) && !string.IsNullOrEmpty(kv.Value))
                 {
                     values[kv.Key] = kv.Value;
                 }
             }
         }
         catch (Exception)
         {
         }
     }
 }
        public static void LoadZip(this VirtualResources virtualResources, string zipPath, bool cache = false)
        {
            if (!File.Exists(zipPath))
            {
                throw new FileNotFoundException();
            }
            zipPath = Helper.NormalizePath(zipPath);
            var file       = File.OpenRead(zipPath);
            var zipArchive = new ZipArchive(file);
            var fullPath   = Path.GetFullPath(zipPath);

            var dir = Path.Combine(Path.GetDirectoryName(fullPath), Path.GetFileNameWithoutExtension(fullPath));

            foreach (var item in zipArchive.Entries)
            {
                var path = Path.Combine(dir, item.FullName);
                path = Helper.NormalizePath(path);
                IEntry entry;

                if (item.Name == string.Empty)
                {
                    entry = new VirtualDirectory(path, "zip");
                }
                else
                {
                    entry = new ZipFile(item, path, zipPath, cache);
                }

                virtualResources._entries[path] = entry;
            }
        }
示例#3
0
        private static string AddModuleLangPack(string langjs, string lang)
        {
            var sb = new System.Text.StringBuilder();

            sb.AppendLine(langjs);

            foreach (var item in VirtualResources.GetFiles(AppSettings.ModulePath, "*config.json", SearchOption.AllDirectories))
            {
                try
                {
                    var moduleName = Path.GetDirectoryName(item);
                    moduleName = Path.GetFileName(moduleName).ToLower();
                    var json = VirtualResources.ReadAllText(item);
                    var dic  = JsonHelper.DeserializeJObject(json)["langs"][lang]
                               .ToObject <Dictionary <string, string> >()
                               .Where(w => !string.IsNullOrEmpty(w.Value));
                    if (dic == null || dic.Count() == 0)
                    {
                        continue;
                    }
                    var properties = string.Join(",", dic.Select(s => $"'{s.Key}':'{s.Value}'"));

                    sb.AppendLine($@"
(function(){{
    Kooboo.text[""{moduleName}""]={{{properties}}}
}})();
");
                }
                catch (Exception)
                {
                }
            }

            return(sb.ToString());
        }
 public void LoadZipTest()
 {
     VirtualResources.Setup(a =>
     {
         a.LoadZip("test.zip");
     });
 }
        private List <Assembly> LoadDlls()
        {
            var dlls = new List <Assembly>();

            foreach (var folder in extensionFolders)
            {
                if (!Directory.Exists(folder))
                {
                    continue;
                }

                var allsubdlls = VirtualResources.GetFiles(folder, "*.dll", SearchOption.AllDirectories);

                foreach (var filename in allsubdlls)
                {
                    try
                    {
                        var otherAssembly = Assembly.Load(VirtualResources.ReadAllBytes(filename));

                        if (otherAssembly != null)
                        {
                            dlls.Add(otherAssembly);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            return(dlls);
        }
示例#6
0
        private List <Assembly> LoadDlls()
        {
            var  dlls           = new List <Assembly>();
            bool isNetFramework = false;  // = RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework");

#if NET461
            {
                isNetFramework = true;
            }
#endif

            foreach (var folder in extensionFolders)
            {
                if (!Directory.Exists(folder))
                {
                    continue;
                }

                var allsubdlls = VirtualResources.GetFiles(folder, "*.dll", SearchOption.AllDirectories);

                foreach (var filename in allsubdlls)
                {
#if DEBUG
                    if (isNetFramework && File.Exists("ignoremodules.txt"))
                    {
                        var modules = File.ReadAllText("ignoremodules.txt")
                                      .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                                      .Select(s =>
                        {
                            var module = s.ToUpper().Trim();
                            if (module.EndsWith(".ZIP"))
                            {
                                module = module.Substring(0, module.Length - 4);
                            }
                            return(module);
                        });

                        if (modules.Any(a => filename.Contains(a)))
                        {
                            continue;
                        }
                    }
#endif

                    try
                    {
                        var otherAssembly = Assembly.Load(VirtualResources.ReadAllBytes(filename));

                        if (otherAssembly != null)
                        {
                            dlls.Add(otherAssembly);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            return(dlls);
        }
示例#7
0
        public static void LoadZip(this VirtualResources virtualResources, string zipPath, string rootPath, ZipOption zipOption)
        {
            if (!File.Exists(zipPath))
            {
                // throw new FileNotFoundException();
                return;
            }
            var zipArchive = new ICSharpCode.SharpZipLib.Zip.ZipFile(zipPath);

            zipPath = Helper.NormalizePath(zipPath);
            _zipArchives[zipPath] = zipArchive;

            var dir      = GetZipVirtualPath(zipPath);
            var fileMaps = GetFileMaps(zipArchive);

            foreach (ZipEntry item in zipArchive)
            {
                var path = Path.Combine(dir, item.Name);
                path = Helper.NormalizePath(path);

                if (item.IsDirectory)
                {
                    var virtualDirectory = new VirtualDirectory(path, "zip");
                    virtualResources._entries[path] = virtualDirectory;
                }
                else
                {
                    var fileMap = fileMaps.FirstOrDefault(f => f.To == item.Name);

                    if (fileMap != null)
                    {
                        fileMap.From = fileMap.From.Trim();
                        if (fileMap.From.StartsWith("/"))
                        {
                            fileMap.From = fileMap.From.Substring(1);
                        }
                        var fromPath    = Path.Combine(rootPath, fileMap.From);
                        var fileMapFrom = Helper.NormalizePath(fromPath);
                        var virtualFile = new ZipFile(item, zipArchive, fileMapFrom, zipPath, zipOption);
                        virtualResources._fileMaps[fileMapFrom] = virtualFile;
                    }

                    virtualResources._entries[path] = new ZipFile(item, zipArchive, path, zipPath, zipOption);

                    while (true)
                    {
                        if (path == dir)
                        {
                            break;
                        }
                        path = Path.GetDirectoryName(path);
                        if (virtualResources._entries.Where(w => w.Value is VirtualDirectory).All(a => a.Key != path))
                        {
                            virtualResources._entries[path] = new VirtualDirectory(path, "zip");
                        }
                    }
                }
            }
        }
示例#8
0
        private static async Task DownloadMonacoAsync()
        {
            var currentMonacoVersion = Data.AppSettings.MonacoVersion ?? "";
            var fileBakName          = MonacoZipPath + ".bak";

            if (currentMonacoVersion != _monacoVersion || !_zipExist)
            {
                try
                {
                    _isLoadding = true;
                    var client = new System.Net.WebClient();
                    var uri    = new Uri($"https://cdn.jsdelivr.net/gh/kooboo/monaco@master/vs{_monacoVersion}.zip");
                    var bytes  = await client.DownloadDataTaskAsync(uri);

                    if (bytes != null && bytes.Length > 0)
                    {
                        if (File.Exists(MonacoZipPath))
                        {
                            VirtualResources.Setup(s => s.UnloadZip(MonacoZipPath));
                            if (File.Exists(fileBakName))
                            {
                                File.Delete(fileBakName);
                            }
                            File.Move(MonacoZipPath, fileBakName);
                        }

                        File.WriteAllBytes(MonacoZipPath, bytes);

                        VirtualResources.Setup(s => s.LoadZip(
                                                   MonacoZipPath,
                                                   AppSettings.RootPath,
                                                   new Lib.VirtualFile.Zip.ZipOption
                        {
                            Cache = true
                        }));
                        _zipExist = true;
                    }

                    AppSettings.SetConfigValue("MonacoVersion", _monacoVersion);
                    if (File.Exists(fileBakName))
                    {
                        File.Delete(fileBakName);
                    }
                    _isLoadding = false;
                }
                catch (Exception e)
                {
                    _isLoadding = false;
                    if (File.Exists(fileBakName))
                    {
                        File.Move(fileBakName, MonacoZipPath);
                    }
                    AppSettings.SetConfigValue("MonacoVersion", currentMonacoVersion);
                    _zipExist = File.Exists(MonacoZipPath);
                    throw e;
                }
            }
        }
        private static string GetText(RenderContext context, RenderOption option, string RelativeUrl, string FullFileName)
        {
            Guid   key  = Lib.Security.Hash.ComputeGuidIgnoreCase(FullFileName);
            string text = null;

            if (option.StartPath != null)
            {
                if (option.StartPath.Contains("_admin"))
                {
#if DEBUG
                    {
                        text = VirtualResources.ReadAllText(FullFileName);
                        key  = Lib.Security.Hash.ComputeHashGuid(text);
                    }
#endif
                }
                else
                {
                    text = VirtualResources.ReadAllText(FullFileName);
                    key  = Lib.Security.Hash.ComputeHashGuid(text);
                }
            }
            else
            {
                text = VirtualResources.ReadAllText(FullFileName);
                key  = Lib.Security.Hash.ComputeHashGuid(text);
            }


            if (option.EnableMultilingual)
            {
                string htmlbody = Kooboo.Data.Cache.MultiLingualRender.GetHtml(context, key);
                if (htmlbody == null)
                {
                    if (text == null)
                    {
                        text = VirtualResources.ReadAllText(FullFileName);
                    }
                    htmlbody = Kooboo.Data.Cache.MultiLingualRender.SetGetHtml(context, key, text);
                }
                return(htmlbody);
            }
            else
            {
                if (text == null)
                {
                    text = Kooboo.Data.Cache.RenderCache.GetHtml(key);
                    if (text == null)
                    {
                        text = VirtualResources.ReadAllText(FullFileName);
                    }
                    Kooboo.Data.Cache.RenderCache.SetHtml(key, text);
                }
                return(text);
            }
        }
示例#10
0
        public void ReadAllTextTest()
        {
            VirtualResources.Setup(a =>
            {
                a.LoadZip("test.zip");
            });

            var result = VirtualResources.ReadAllText("test/TestPage.html");

            Assert.IsTrue(result.Length > 0);
        }
示例#11
0
 private static void AddModuleRoot(string path)
 {
     if (Directory.Exists(path))
     {
         ModuleRoots.Add(path);
     }
     foreach (var item in VirtualResources.GetDirectories(path))
     {
         ModuleRoots.Add(item);
     }
 }
示例#12
0
        public void GetDirectoriesTest()
        {
            VirtualResources.Setup(a =>
            {
                a.LoadZip("test.zip");
            });

            var dirs = VirtualResources.GetDirectories("test");

            Assert.AreEqual(dirs.Count(), 3);
        }
示例#13
0
        public void GetFilesTest()
        {
            VirtualResources.Setup(a =>
            {
                a.LoadZip("test.zip");
            });

            var files = VirtualResources.GetFiles("test/js");

            Assert.AreEqual(files.Count(), 1);
        }
示例#14
0
        public static string FindFile(string FullFilePath)
        {
            var root = Data.AppSettings.RootPath;

            if (FullFilePath.StartsWith(root))
            {
                string relative = FullFilePath.Substring(root.Length);
                if (string.IsNullOrWhiteSpace(relative))
                {
                    return(null);
                }

                if (relative.StartsWith("/") || relative.StartsWith("\\"))
                {
                    relative = relative.Substring(1);
                }

                if (string.IsNullOrWhiteSpace(relative))
                {
                    return(null);
                }

                if (relative.ToLower().StartsWith(AdminPath))
                {
                    relative = relative.Substring(AdminPath.Length);
                }

                if (string.IsNullOrWhiteSpace(relative))
                {
                    return(null);
                }

                var paths = relative.Split(seps, StringSplitOptions.RemoveEmptyEntries).ToList();
                foreach (var moduleRoot in ModuleRoots)
                {
                    paths.Insert(0, moduleRoot);

                    var fullpath = Path.Combine(paths.ToArray());

                    if (VirtualResources.FileExists(fullpath))
                    {
                        return(fullpath);
                    }
                    paths.RemoveAt(0);
                }
            }

            return(null);
        }
示例#15
0
        private static void LoadModuleZip()
        {
            var rootPath = PathUtility.TryRootPath();

            VirtualResources.Setup(v =>
            {
                foreach (var item in Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, "modules"), "*.zip"))
                {
                    v.LoadZip(item, rootPath, new Lib.VirtualFile.Zip.ZipOption
                    {
                        Cache = true
                    });
                }
            });
        }
        public static void UnloadZip(this VirtualResources virtualResources, string zipPath)
        {
            zipPath = Helper.NormalizePath(zipPath);
            var dir = GetZipVirtualPath(zipPath);

            dir = Helper.NormalizePath(dir);
            RemoveEntries(virtualResources, dir);
            RemoveFileMaps(virtualResources, zipPath);

            if (_zipArchives.TryGetValue(zipPath, out var zipArchive))
            {
                zipArchive.Close();
                _zipArchives.TryRemove(zipPath, out _);
            }
        }
示例#17
0
        public static RenderRespnose RenderJsLangFile(string FullFileName, RenderContext context)
        {
            var values = Kooboo.Data.Cache.MultiLingualRender.GetJs(context);

            if (values == null)
            {
                var bytes = VirtualResources.ReadAllBytes(FullFileName);

                values = Kooboo.Data.Cache.MultiLingualRender.SetGetJs(context, bytes);
            }

            return(new RenderRespnose()
            {
                BinaryBytes = values, ContentType = "application/javascript"
            });
        }
        private static byte[] GetBinary(RenderContext context, RenderOption option, string RelativeUrl, string FullFileName)
        {
            if (option.EnableMultilingual && RelativeUrl.ToLower().EndsWith(option.MultilingualJsFile))
            {
                Guid   key   = Lib.Security.Hash.ComputeGuidIgnoreCase(RelativeUrl);
                byte[] bytes = null;
#if DEBUG
                {
                    bytes = VirtualResources.ReadAllBytes(FullFileName);
                    key   = Lib.Security.Hash.ComputeGuid(bytes);
                }
#endif
                var values = Kooboo.Data.Cache.MultiLingualRender.GetJs(context);
                if (values == null)
                {
                    if (bytes == null)
                    {
                        bytes = VirtualResources.ReadAllBytes(FullFileName);
                    }
                    values = Kooboo.Data.Cache.MultiLingualRender.SetGetJs(context, bytes);
                }
                return(values);
            }
            else
            {
                byte[] result = null;
#if DEBUG
                {
                    result = VirtualResources.ReadAllBytes(FullFileName);
                }
#endif
                if (result == null)
                {
                    Guid key = Kooboo.Lib.Security.Hash.ComputeGuidIgnoreCase(RelativeUrl);
                    result = Kooboo.Data.Cache.RenderCache.GetBinary(key);
                    if (result == null)
                    {
                        result = VirtualResources.ReadAllBytes(FullFileName);
                        Kooboo.Data.Cache.RenderCache.SetBinary(key, result);
                    }
                }
                return(result);
            }
        }
示例#19
0
        public Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            var assemblyName = new AssemblyName(args.Name);
            var name         = assemblyName.Name;

            var assembly = Assemblies.Find(a =>
            {
                return(assemblyName.Name == a.GetName().Name);
            });

            if (assembly != null)
            {
                return(assembly);
            }

            var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            var path          = extensionFolders.Union(new[] { baseDirectory }).Select(folder =>
            {
                var dllpath = Path.Combine(folder, string.Format("{0}.dll", name));
                if (VirtualResources.FileExists(dllpath))
                {
                    return(dllpath);
                }

                return(string.Empty);
            }).FirstOrDefault(f => f.Length > 0);

            if (!string.IsNullOrEmpty(path))
            {
                assembly = Assembly.Load(VirtualResources.ReadAllBytes(path));
                lock (_lockObj)
                {
                    if (!Assemblies.Exists(a => a.FullName == assemblyName.FullName))
                    {
                        Assemblies.Add(assembly);
                    }
                }
                return(assembly);
            }

            return(null);
        }
示例#20
0
        private static byte[] GetBinary(RenderContext context, SpaRenderOption option, string RelativeUrl, string FullFileName)
        {
            byte[] result = null;
#if DEBUG
            {
                result = VirtualResources.ReadAllBytes(FullFileName);
            }
#endif
            if (result == null)
            {
                Guid key = Kooboo.Lib.Security.Hash.ComputeGuidIgnoreCase(RelativeUrl);
                result = Kooboo.Data.Cache.RenderCache.GetBinary(key);
                if (result == null)
                {
                    result = VirtualResources.ReadAllBytes(FullFileName);
                    Kooboo.Data.Cache.RenderCache.SetBinary(key, result);
                }
            }
            return(result);
        }
        private static void RemoveFileMaps(VirtualResources virtualResources, string zipPath)
        {
            var removed = new List <KeyValuePair <string, VirtualFile> >();

            foreach (var item in virtualResources._fileMaps)
            {
                if (!(item.Value is ZipFile))
                {
                    continue;
                }
                if ((item.Value as ZipFile).ZipPath == zipPath)
                {
                    removed.Add(item);
                }
            }

            foreach (var item in removed)
            {
                virtualResources._fileMaps.TryRemove(item.Key, out _);
            }
        }
        private static void RemoveEntries(VirtualResources virtualResources, string dir)
        {
            var removed = new List <KeyValuePair <string, IEntry> >();

            foreach (var item in virtualResources._entries)
            {
                if (item.Value.Source != "zip")
                {
                    continue;
                }
                if (item.Value.Path.StartsWith(dir))
                {
                    removed.Add(item);
                }
            }

            foreach (var item in removed)
            {
                virtualResources._entries.TryRemove(item.Key, out _);
            }
        }
示例#23
0
        private List <Assembly> LoadDlls()
        {
            var dlls           = new List <Assembly>();
            var isNetFramework = RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework");

            foreach (var folder in extensionFolders)
            {
                if (!Directory.Exists(folder))
                {
                    continue;
                }

                var allsubdlls = VirtualResources.GetFiles(folder, "*.dll", SearchOption.AllDirectories);

                foreach (var filename in allsubdlls)
                {
                    try
                    {
                        var otherAssembly            = Assembly.Load(VirtualResources.ReadAllBytes(filename));
                        var targetFrameworkAttribute = otherAssembly?.CustomAttributes?.FirstOrDefault(f => f.AttributeType == typeof(TargetFrameworkAttribute));
                        var netVersion = targetFrameworkAttribute?.ConstructorArguments?.FirstOrDefault().Value;

                        if (isNetFramework && netVersion != null && netVersion.ToString().StartsWith(".NETCoreApp"))
                        {
                            continue;
                        }

                        if (otherAssembly != null)
                        {
                            dlls.Add(otherAssembly);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            return(dlls);
        }
示例#24
0
        private string GetString(string url)
        {
            string root = Kooboo.Data.AppSettings.RootPath;

            string fullpath = Lib.Compatible.CompatibleManager.Instance.System.CombinePath(root, url);

            if (VirtualResources.FileExists(fullpath))
            {
                return(VirtualResources.ReadAllText(fullpath));
            }
            else
            {
                fullpath = Kooboo.Render.Controller.ModuleFile.FindFile(fullpath);

                if (!string.IsNullOrWhiteSpace(fullpath) && VirtualResources.FileExists(fullpath))
                {
                    return(VirtualResources.ReadAllText(fullpath));
                }
            }

            return(null);
        }
示例#25
0
        public static RenderRespnose RenderJs(CommandDiskSourceProvider sourceProvider, RenderOption option, RenderContext context, string RelativeUrl)
        {
            var fullname = sourceProvider.GetFullFileName(context, RelativeUrl);

            if (string.IsNullOrEmpty(fullname))
            {
                return(new RenderRespnose()
                {
                    Body = null
                });
            }

            if (option.EnableMultilingual && RelativeUrl.ToLower().EndsWith(option.MultilingualJsFile))
            {
                return(RenderJsLangFile(fullname, context));
            }

            System.IO.FileInfo info = new System.IO.FileInfo(fullname);

            if (info != null && info.LastWriteTime != null)
            {
                JsRenderPlan renderplan = null;

                Guid hash = Lib.Security.Hash.ComputeGuidIgnoreCase(info.LastWriteTime.ToLongTimeString());

                var cacheplan = GetJs(RelativeUrl);

                if (cacheplan != null && cacheplan.Hash == hash)
                {
                    renderplan = cacheplan;
                }

                //either not key found not hash not the same.
                if (renderplan == null)
                {
                    string fulltext = VirtualResources.ReadAllText(fullname);

                    renderplan       = new JsRenderPlan();
                    renderplan.Tasks = GetJsRenderPlan(fulltext);
                    renderplan.Hash  = hash;
                    SetJs(RelativeUrl, renderplan);
                }

                if (renderplan != null)
                {
                    string result = string.Empty;
                    foreach (var task in renderplan.Tasks)
                    {
                        result += task.Render(sourceProvider, option, context, RelativeUrl);
                    }
                    return(new RenderRespnose()
                    {
                        Body = result, ContentType = "application/javascript"
                    });
                }
            }
            else
            {
                return(new RenderRespnose()
                {
                    Body = null
                });
            }

            return(new RenderRespnose()
            {
                Body = null
            });
        }
示例#26
0
        public static List <IServerTask> GetJsRenderPlan(CommandDiskSourceProvider sourceProvider, RenderOption option, RenderContext context, string fullfilename, string relativeUrl)
        {
            List <IServerTask> result = new List <IServerTask>();

            List <preTask> pretask = new List <preTask>();

            string source = VirtualResources.ReadAllText(fullfilename);

            if (string.IsNullOrWhiteSpace(source))
            {
                result.Add(new StringTask()
                {
                    content = ""
                });
                return(result);
            }

            foreach (var item in TaskContainer.list)
            {
                var startEndList = GetStartEndList(source, item.Key);

                foreach (var one in startEndList)
                {
                    var line = source.Substring(one.Key, one.Value - one.Key + 1);

                    var paras = GetParas(line);

                    var taskInstance = Activator.CreateInstance(item.Value) as IServerTask;
                    taskInstance.paras = paras;

                    pretask.Add(new preTask()
                    {
                        start = one.Key, end = one.Value, Task = taskInstance
                    });
                }
            }

            if (pretask.Count() > 0)
            {
                int currentIndex = 0;
                foreach (var item in pretask.OrderBy(o => o.start))
                {
                    int len = item.start - currentIndex;

                    if (len > 0)
                    {
                        string before = source.Substring(currentIndex, len);
                        result.Add(new StringTask()
                        {
                            content = before
                        });
                    }

                    result.Add(item.Task);

                    currentIndex = item.end + 1;
                }
            }
            else
            {
                result.Add(new StringTask()
                {
                    content = source
                });
            }

            return(result);
        }