/// <summary>
        /// Return stream for requested  asset file  (used for search current and base themes assets)
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task <Stream> GetAssetStreamAsync(string filePath)
        {
            Stream retVal = null;
            var    filePathWithoutExtension = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath));
            //file.ext => file.ext || file || file.liquid || file.ext.liquid
            var searchPatterns = new[] { filePath, filePathWithoutExtension, string.Format(_liquidTemplateFormat, filePathWithoutExtension), string.Format(_liquidTemplateFormat, filePath) };


            string currentThemeFilePath = null;

            //try to search in current store theme
            if (_themeBlobProvider.PathExists(Path.Combine(CurrentThemePath, "assets")))
            {
                currentThemeFilePath = searchPatterns.SelectMany(x => _themeBlobProvider.Search(Path.Combine(CurrentThemePath, "assets"), x, true)).FirstOrDefault();
            }
            //If not found by current theme path try find them by base path if it is defined
            if (currentThemeFilePath == null && BaseThemePath != null)
            {
                currentThemeFilePath = searchPatterns.SelectMany(x => _themeBlobProvider.Search(Path.Combine(BaseThemePath, "assets"), x, true)).FirstOrDefault();
            }

            if (currentThemeFilePath != null)
            {
                retVal   = _themeBlobProvider.OpenRead(currentThemeFilePath);
                filePath = currentThemeFilePath;
            }

            if (retVal != null && filePath.EndsWith(".liquid"))
            {
                var context = WorkContext.Clone() as WorkContext;
                context.Settings = GetSettings("''");
                var templateContent = retVal.ReadToString();
                retVal.Dispose();

                var template = await RenderTemplateAsync(templateContent, filePath, context.ToScriptObject());

                retVal = new MemoryStream(Encoding.UTF8.GetBytes(template));
            }

            if (retVal != null && (filePath.Contains(".scss.") && filePath.EndsWith(".liquid") || filePath.EndsWith(".scss")))
            {
                var content = retVal.ReadToString();
                retVal.Dispose();

                try
                {
                    //handle scss resources
                    var result = SassCompiler.Compile(content);
                    content = result.CompiledContent;

                    retVal = new MemoryStream(Encoding.UTF8.GetBytes(content));
                }
                catch (Exception ex)
                {
                    throw new SaasCompileException(filePath, content, ex);
                }
            }

            return(retVal);
        }
        /// <summary>
        /// Return stream for requested  asset file  (used for search current and base themes assets)
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public Stream GetAssetStream(string filePath, bool searchInGlobalThemeOnly = false)
        {
            Stream retVal = null;
            var    filePathWithoutExtension = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath)).Replace("\\", "/");
            //file.ext => file.ext || file || file.liquid || file.ext.liquid
            var searchPatterns = new[] { filePath, filePathWithoutExtension, string.Format(_liquidTemplateFormat, filePathWithoutExtension), string.Format(_liquidTemplateFormat, filePath) };

            string currentThemeFilePath = null;
            //search in global theme first
            var globalThemeFilePath = searchPatterns.SelectMany(x => _globalThemeBlobProvider.Search("assets", x, true)).FirstOrDefault();

            if (!searchInGlobalThemeOnly)
            {
                //try to search in current store theme
                if (_themeBlobProvider.PathExists(CurrentThemePath + "\\assets"))
                {
                    currentThemeFilePath = searchPatterns.SelectMany(x => _themeBlobProvider.Search(CurrentThemePath + "\\assets", x, true)).FirstOrDefault();
                }
            }

            if (currentThemeFilePath != null)
            {
                retVal   = _themeBlobProvider.OpenRead(currentThemeFilePath);
                filePath = currentThemeFilePath;
            }
            else if (globalThemeFilePath != null)
            {
                retVal   = _globalThemeBlobProvider.OpenRead(globalThemeFilePath);
                filePath = globalThemeFilePath;
            }

            if (retVal != null && filePath.EndsWith(".liquid"))
            {
                var shopifyContext = WorkContext.ToShopifyModel(UrlBuilder);
                var parameters     = shopifyContext.ToLiquid() as Dictionary <string, object>;
                var settings       = GetSettings("''");
                parameters.Add("settings", settings);
                var templateContent = retVal.ReadToString();
                var template        = RenderTemplate(templateContent, parameters);
                retVal = new MemoryStream(Encoding.UTF8.GetBytes(template));
            }

            if (retVal != null && (filePath.Contains(".scss.") || filePath.EndsWith(".scss")))
            {
                var content = retVal.ReadToString();
                try
                {
                    //handle scss resources
                    content = _saasCompiler.Compile(content);
                    retVal  = new MemoryStream(Encoding.UTF8.GetBytes(content));
                }
                catch (Exception ex)
                {
                    throw new SaasCompileException(filePath, content, ex);
                }
            }

            return(retVal);
        }
        public IEnumerable <ContentItem> LoadStoreStaticContent(Store store)
        {
            var baseStoreContentPath = string.Concat(_basePath, "/", store.Id);
            var cacheKey             = CacheKey.With(GetType(), "LoadStoreStaticContent", store.Id);

            return(_memoryCache.GetOrCreateExclusive(cacheKey, (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(new CompositeChangeToken(new[] { StaticContentCacheRegion.CreateChangeToken(), _contentBlobProvider.Watch(baseStoreContentPath + "/**/*") }));

                var retVal = new List <ContentItem>();
                const string searchPattern = "*.*";

                if (_contentBlobProvider.PathExists(baseStoreContentPath))
                {
                    // Search files by requested search pattern
                    var contentBlobs = _contentBlobProvider.Search(baseStoreContentPath, searchPattern, true)
                                       .Where(x => _extensions.Any(x.EndsWith))
                                       .Select(x => x.Replace("\\\\", "\\"));

                    foreach (var contentBlob in contentBlobs)
                    {
                        var blobRelativePath = "/" + contentBlob.TrimStart('/');

                        var contentItem = _builder.BuildFrom(baseStoreContentPath, blobRelativePath, GetContent(blobRelativePath));
                        if (contentItem != null)
                        {
                            retVal.Add(contentItem);
                        }
                    }
                }

                return retVal.ToArray();
            }));
        }
        private static JObject InnerReadLocalization(IContentBlobProvider themeBlobProvider, string themePath, Language language)
        {
            JObject retVal           = null;
            var     localeFolderPath = Path.Combine(themePath, "locales");

            if (themeBlobProvider.PathExists(localeFolderPath))
            {
                JObject localeJson  = null;
                JObject defaultJson = null;

                foreach (var languageName in new[] { language.CultureName, language.TwoLetterLanguageName })
                {
                    var currentLocalePath = Path.Combine(localeFolderPath, string.Concat(languageName, ".json"));

                    if (themeBlobProvider.PathExists(currentLocalePath))
                    {
                        using (var stream = themeBlobProvider.OpenRead(currentLocalePath))
                        {
                            localeJson = JsonConvert.DeserializeObject <dynamic>(stream.ReadToString());
                        }
                        break;
                    }
                }

                var localeDefaultPath = themeBlobProvider.Search(localeFolderPath, "*.default.json", false).FirstOrDefault();

                if (localeDefaultPath != null && themeBlobProvider.PathExists(localeDefaultPath))
                {
                    using (var stream = themeBlobProvider.OpenRead(localeDefaultPath))
                    {
                        defaultJson = JsonConvert.DeserializeObject <dynamic>(stream.ReadToString());
                    }
                }

                //Need merge default and requested localization json to resulting object
                retVal = defaultJson ?? localeJson;

                if (defaultJson != null && localeJson != null)
                {
                    retVal.Merge(localeJson, new JsonMergeSettings {
                        MergeArrayHandling = MergeArrayHandling.Merge
                    });
                }
            }
            return(retVal);
        }
Exemple #5
0
 public bool FileExists(string path)
 {
     // Workaround for directories
     if (string.IsNullOrEmpty(Path.GetExtension(path)))
     {
         return(false);
     }
     return(_contentBlobProvider.PathExists(path));
 }
        private static JObject InnerGetAllSettings(IContentBlobProvider themeBlobProvider, string themePath)
        {
            JObject retVal       = null;
            var     settingsPath = Path.Combine(themePath, "config\\settings_data.json");

            if (themeBlobProvider.PathExists(settingsPath))
            {
                using (var stream = themeBlobProvider.OpenRead(settingsPath))
                {
                    retVal = JsonConvert.DeserializeObject <JObject>(stream.ReadToString());
                }
            }
            return(retVal);
        }
        private static JObject InnerGetSettings(IContentBlobProvider themeBlobProvider, string themePath)
        {
            JObject retVal       = null;
            var     settingsPath = Path.Combine(themePath, "config\\settings_data.json");

            if (themeBlobProvider.PathExists(settingsPath))
            {
                using (var stream = themeBlobProvider.OpenRead(settingsPath))
                {
                    var settings = JsonConvert.DeserializeObject <JObject>(stream.ReadToString());
                    // now get settings for current theme and add it as a settings parameter
                    retVal = settings["current"] as JObject ?? settings["presets"][settings["current"].ToString()] as JObject;
                }
            }
            return(retVal);
        }
        private static JObject InnerGetAllSettings(IContentBlobProvider themeBlobProvider, string settingsPath)
        {
            if (settingsPath == null)
            {
                throw new ArgumentNullException(nameof(settingsPath));
            }

            var result = new JObject();

            if (themeBlobProvider.PathExists(settingsPath))
            {
                using (var stream = themeBlobProvider.OpenRead(settingsPath))
                {
                    result = JsonConvert.DeserializeObject <JObject>(stream.ReadToString());
                }
            }
            return(result);
        }
        /// <summary>
        /// resolve  template path by it name
        /// </summary>
        /// <param name="templateName"></param>
        /// <returns></returns>
        public string ResolveTemplatePath(string templateName, bool searchInGlobalThemeOnly = false)
        {
            if (WorkContext.CurrentStore == null)
            {
                return(null);
            }

            var liquidTemplateFileName    = String.Format(_liquidTemplateFormat, templateName);
            var curentThemediscoveryPaths = _templatesDiscoveryFolders.Select(x => Path.Combine(CurrentThemePath, x, liquidTemplateFileName));
            //First try to find template in current theme folder
            var retVal = curentThemediscoveryPaths.FirstOrDefault(x => _themeBlobProvider.PathExists(x));

            if (searchInGlobalThemeOnly || retVal == null)
            {
                //Then try to find in global theme
                var globalThemeDiscoveyPaths = _templatesDiscoveryFolders.Select(x => Path.Combine(x, liquidTemplateFileName));
                retVal = globalThemeDiscoveyPaths.FirstOrDefault(x => _globalThemeBlobProvider.PathExists(x));
            }
            return(retVal);
        }
        private string ReadTemplateByPath(string templatePath)
        {
            var retVal = _cacheManager.Get(GetCacheKey("ReadTemplateByName", templatePath), "LiquidThemeRegion", () =>
            {
                if (!String.IsNullOrEmpty(templatePath))
                {
                    //First try find content in current store themer
                    IContentBlobProvider blobProvider = _themeBlobProvider;
                    if (!blobProvider.PathExists(templatePath))
                    {
                        //Else search in global theme
                        blobProvider = _globalThemeBlobProvider;
                    }
                    using (var stream = blobProvider.OpenRead(templatePath))
                    {
                        return(stream.ReadToString());
                    }
                }
                throw new FileSystemException("Error - No such template {0}.", templatePath);
            });

            return(retVal);
        }
 private static JObject InnerGetSettings(IContentBlobProvider themeBlobProvider, string themePath)
 {
     JObject retVal = null;
     var settingsPath = Path.Combine(themePath, "config\\settings_data.json");
     if (themeBlobProvider.PathExists(settingsPath))
     {
         using (var stream = themeBlobProvider.OpenRead(settingsPath))
         {
             var settings = JsonConvert.DeserializeObject<JObject>(stream.ReadToString());
             // now get settings for current theme and add it as a settings parameter
             retVal = settings["current"] as JObject;
             if (retVal == null)
             {
                 //is setting preset name need return it as active
                 retVal = settings["presets"][settings["current"].ToString()] as JObject;
             }
         }
     }
     return retVal;
 }
        private static JObject InnerReadLocalization(IContentBlobProvider themeBlobProvider, string themePath, Language language)
        {
            JObject retVal = null;
            var localeFolderPath = Path.Combine(themePath, "locales");
            if (themeBlobProvider.PathExists(localeFolderPath))
            {
                var currentLocalePath = Path.Combine(localeFolderPath, string.Concat(language.TwoLetterLanguageName, ".json"));
                var localeDefaultPath = themeBlobProvider.Search(localeFolderPath, "*.default.json", false).FirstOrDefault();

                JObject localeJson = null;
                JObject defaultJson = null;

                if (themeBlobProvider.PathExists(currentLocalePath))
                {
                    using (var stream = themeBlobProvider.OpenRead(currentLocalePath))
                    {
                        localeJson = JsonConvert.DeserializeObject<dynamic>(stream.ReadToString());
                    }
                }

                if (localeDefaultPath != null && themeBlobProvider.PathExists(localeDefaultPath))
                {
                    using (var stream = themeBlobProvider.OpenRead(localeDefaultPath))
                    {
                        defaultJson = JsonConvert.DeserializeObject<dynamic>(stream.ReadToString());
                    }
                }

                //Need merge default and requested localization json to resulting object
                retVal = defaultJson ?? localeJson;
                if (defaultJson != null && localeJson != null)
                {
                    retVal.Merge(localeJson, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Merge });
                }
            }
            return retVal;
        }
        /// <summary>
        /// Return stream for requested  asset file  (used for search current and base themes assets)
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public Stream GetAssetStream(string fileName, bool searchInGlobalThemeOnly = false)
        {
            Stream retVal           = null;
            var    fileExtensions   = System.IO.Path.GetExtension(fileName);
            string currentThemePath = null;
            string globalThemePath  = _globalThemeBlobProvider.Search("assets", fileName, true).FirstOrDefault();

            if (!searchInGlobalThemeOnly)
            {
                //try to search in current store theme
                if (_themeBlobProvider.PathExists(CurrentThemePath + "\\assets"))
                {
                    currentThemePath = _themeBlobProvider.Search(CurrentThemePath + "\\assets", fileName, true).FirstOrDefault();
                }
            }

            //We find requested asset need return resulting stream
            if (currentThemePath != null)
            {
                retVal = _themeBlobProvider.OpenRead(currentThemePath);
            }
            else if (globalThemePath != null)
            {
                retVal = _globalThemeBlobProvider.OpenRead(globalThemePath);
            }
            else
            {
                //Otherwise it may be liquid template
                fileName = fileName.Replace(".scss.css", ".scss");
                var settings = GetSettings("''");
                //Try to parse liquid asset resource
                var themeAssetPath = ResolveTemplatePath(fileName, searchInGlobalThemeOnly);
                if (themeAssetPath != null)
                {
                    var templateContent = ReadTemplateByPath(themeAssetPath);
                    var content         = RenderTemplate(templateContent, new Dictionary <string, object>()
                    {
                        { "settings", settings }
                    });

                    if (fileName.EndsWith(".scss"))
                    {
                        try
                        {
                            //handle scss resources
                            content = _saasCompiler.Compile(content);
                        }
                        catch (Exception ex)
                        {
                            throw new SaasCompileException(fileName, content, ex);
                        }
                    }
                    if (content != null)
                    {
                        retVal = new MemoryStream(Encoding.UTF8.GetBytes(content));
                    }
                }
            }

            return(retVal);
        }