Exemplo n.º 1
0
        public void Save(int hashCode, CombinatorResource resource)
        {
            var scliceCount = _fileRepository.Count(file => file.HashCode == hashCode);

            var fileRecord = new CombinedFileRecord()
            {
                HashCode = hashCode,
                Slice = ++scliceCount,
                Type = resource.Type,
                LastUpdatedUtc = _clock.UtcNow,
                Settings = _combinatorResourceManager.SerializeResourceSettings(resource)
            };

            if (!String.IsNullOrEmpty(resource.Content))
            {
                var path = MakePath(fileRecord);

                using (var stream = _storageProvider.CreateFile(path).OpenWrite())
                {
                    var bytes = Encoding.UTF8.GetBytes(resource.Content);
                    stream.Write(bytes, 0, bytes.Length);
                }
            }

            _fileRepository.Create(fileRecord);
        }
Exemplo n.º 2
0
        private void EmbedImages(CombinatorResource resource, int maxSizeKB)
        {
            ProcessUrlSettings(resource,
                (match) =>
                {
                    var url = match.Groups[1].Value;
                    var extension = Path.GetExtension(url).ToLowerInvariant();

                    // This is a dumb check but otherwise we'd have to inspect the file thoroughly
                    if (!String.IsNullOrEmpty(extension) && ".jpg .jpeg .png .gif .tiff .bmp".Contains(extension))
                    {
                        var imageData = _resourceFileService.GetImageBase64Data(MakeInlineUri(resource, url), maxSizeKB);

                        if (!String.IsNullOrEmpty(imageData))
                        {
                            var dataUrl =
                            "data:image/"
                                + Path.GetExtension(url).Replace(".", "")
                                + ";base64,"
                                + imageData;

                            return "url(\"" + dataUrl + "\")";
                        }
                    }

                    return match.Groups[0].Value;
                });
        }
Exemplo n.º 3
0
        public void OnContentLoaded(CombinatorResource resource)
        {
            var extension = Path.GetExtension(resource.AbsoluteUrl.ToString()).ToLowerInvariant();
            if (extension != ".sass" && extension != ".scss") return;

            using (var compiler = new SassCompiler())
            {
                resource.Content = compiler.Compile(_virtualPathProvider.MapPath(resource.RelativeVirtualPath).Replace("\\", @"\"), false, new List<string>());
            }
        }
Exemplo n.º 4
0
 public void LoadResourceContent(CombinatorResource resource)
 {
     if (resource.IsCdnResource || resource.IsRemoteStorageResource)
     {
         resource.Content = FetchRemoteResourceContent(resource);
     }
     else
     {
         resource.Content = FetchLocalResourceContent(resource);
     }
 }
 public string GetRemoteResourceContent(CombinatorResource resource)
 {
     using (var wc = new WebClient())
     {
         var byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
         var content = new UTF8Encoding(false).GetString(wc.DownloadData(resource.AbsoluteUrl));
         if (content.StartsWith(byteOrderMarkUtf8)) // Stripping "?"s from the beginning of css commments "/*"
         {
             content = content.Remove(0, byteOrderMarkUtf8.Length);
         }
         return content;
     }
 }
        public string SerializeResourceSettings(CombinatorResource resource)
        {
            var settings = resource.RequiredContext.Settings;
            if (settings == null) return "";

            return _serializer.XmlSerialize(
                new SerializableSettings()
                {
                    Url = resource.IsOriginal ? resource.IsCdnResource ? resource.AbsoluteUrl : resource.RelativeUrl : null,
                    Culture = settings.Culture,
                    Condition = settings.Condition,
                    Attributes = settings.Attributes
                });
        }
        public string GetLocalResourceContent(CombinatorResource resource)
        {
            var relativeVirtualPath = resource.RelativeVirtualPath;

            // Maybe TryFileExists would be better?
            if (!_virtualPathProvider.FileExists(relativeVirtualPath)) throw new OrchardException(T("Local resource file not found under {0}", relativeVirtualPath));

            string content;
            using (var stream = _virtualPathProvider.OpenFile(relativeVirtualPath))
            {
                content = new StreamReader(stream).ReadToEnd();
            }

            return content;
        }
        public string SerializeResourceSettings(CombinatorResource resource)
        {
            var settings = resource.RequiredContext.Settings;
            if (settings == null) return "";

            return _jsonConverter.Serialize(
                new SerializableSettings()
                {
                    Url = resource.IsOriginal ? !resource.IsCdnResource && !resource.IsRemoteStorageResource ? resource.RelativeUrl : resource.AbsoluteUrl : null,
                    IsRemoteStorageResource = resource.IsRemoteStorageResource,
                    Culture = settings.Culture,
                    Condition = settings.Condition,
                    Attributes = settings.Attributes,
                    TagAttributes = resource.RequiredContext.Resource.TagBuilder.Attributes
                });
        }
        public static void ConvertRelativeUrlsToAbsolute(CombinatorResource resource, Uri baseUrl)
        {
            if (String.IsNullOrEmpty(resource.Content)) return;

            var stylesheet = new StylesheetParser().Parse(resource.Content);

            // Modifying relative urls (because when saved, local urls were converted to unified relative ones) to point to the original domain
            ProcessUrls(
                resource,
                stylesheet,
                (ruleSet, urlTerm) =>
                {
                    if (Uri.IsWellFormedUriString(urlTerm.Value, UriKind.Absolute)) return;

                    urlTerm.Value = new Uri(baseUrl, urlTerm.Value).ToProtocolRelative();
                });
        }
        private static void AdjustRelativePaths(CombinatorResource resource)
        {
            ProcessUrlSettings(resource,
                (match) =>
                {
                    var url = match.Groups[1].ToString();

                    var uri = MakeInlineUri(resource, url);

                    // Remote paths are preserved as full urls, local paths become uniformed relative ones.
                    string uriString = "";
                    if (resource.IsCdnResource || resource.AbsoluteUrl.Host != uri.Host) uriString = uri.ToStringWithoutScheme();
                    else uriString = uri.PathAndQuery;

                    return "url(\"" + uriString + "\")";
                });
        }
        public void DeserializeSettings(string serialization, CombinatorResource resource)
        {
            if (String.IsNullOrEmpty(serialization)) return;

            var settings = _serializer.XmlDeserialize<SerializableSettings>(serialization);

            if (settings.Url != null)
            {
                resource.RequiredContext.Resource.SetUrlProtocolRelative(settings.Url);
                resource.IsOriginal = true;
            }

            if (resource.RequiredContext.Settings == null) resource.RequiredContext.Settings = new RequireSettings();
            var resourceSettings = resource.RequiredContext.Settings;
            resourceSettings.Culture = settings.Culture;
            resourceSettings.Condition = settings.Condition;
            resourceSettings.Attributes = settings.Attributes;
        }
Exemplo n.º 12
0
        public void DeserializeSettings(string serialization, CombinatorResource resource)
        {
            if (String.IsNullOrEmpty(serialization)) return;

            var settings = _serializer.XmlDeserialize<SerializableSettings>(serialization);

            if (settings.Url != null)
            {
                var resourceManifest = new ResourceManifest();
                resource.RequiredContext.Resource = resourceManifest.DefineResource(resource.Type.ToStringType(), settings.Url.ToString());
                resource.RequiredContext.Resource.SetUrlWithoutScheme(settings.Url);
                resource.IsOriginal = true;
            }

            if (resource.RequiredContext.Settings == null) resource.RequiredContext.Settings = new RequireSettings();
            var resourceSettings = resource.RequiredContext.Settings;
            resourceSettings.Culture = settings.Culture;
            resourceSettings.Condition = settings.Condition;
            resourceSettings.Attributes = settings.Attributes;
        }
Exemplo n.º 13
0
        public void ProcessResource(CombinatorResource resource, StringBuilder combinedContent, ICombinatorSettings settings)
        {
            if (!resource.IsCdnResource || settings.CombineCDNResources)
            {
                var absoluteUrlString = resource.AbsoluteUrl.ToString();

                if (!resource.IsCdnResource)
                {
                    resource.Content = _resourceFileService.GetLocalResourceContent(resource);
                }
                else if (settings.CombineCDNResources)
                {
                    resource.Content = _resourceFileService.GetRemoteResourceContent(resource);
                }

                if (String.IsNullOrEmpty(resource.Content)) return;

                if (settings.MinifyResources && (settings.MinificationExcludeFilter == null || !settings.MinificationExcludeFilter.IsMatch(absoluteUrlString)))
                {
                    MinifyResourceContent(resource);
                    if (String.IsNullOrEmpty(resource.Content)) return;
                }

                // Better to do after minification, as then urls commented out are removed
                if (resource.Type == ResourceType.Style)
                {
                    AdjustRelativePaths(resource);

                    if (settings.EmbedCssImages && (settings.EmbedCssImagesStylesheetExcludeFilter == null || !settings.EmbedCssImagesStylesheetExcludeFilter.IsMatch(absoluteUrlString)))
                    {
                        EmbedImages(resource, settings.EmbeddedImagesMaxSizeKB);
                    }
                }

                combinedContent.Append(resource.Content);
            }
            else
            {
                resource.IsOriginal = true;
            }
        }
Exemplo n.º 14
0
        public bool SettingsEqual(CombinatorResource other)
        {
            // If one's RequiredContext is null, their settings are not identical...
            if (RequiredContext == null ^ other.RequiredContext == null)
            {
                return(false);
            }

            // However if both of them are null, we say the settings are identical
            if (RequiredContext == null && other.RequiredContext == null)
            {
                return(true);
            }

            var settings      = RequiredContext.Settings;
            var otherSettings = other.RequiredContext.Settings;

            return
                (settings.Culture == otherSettings.Culture &&
                 settings.Condition == otherSettings.Condition &&
                 settings.AttributesEqual(otherSettings));
        }
        public void DeserializeSettings(string serialization, CombinatorResource resource)
        {
            if (string.IsNullOrEmpty(serialization)) return;

            var settings = _jsonConverter.Deserialize<SerializableSettings>(serialization);

            if (settings.Url != null)
            {
                resource.RequiredContext.Resource.SetUrlProtocolRelative(settings.Url);
                resource.IsOriginal = true;
            }

            resource.IsRemoteStorageResource = settings.IsRemoteStorageResource;

            if (resource.RequiredContext.Settings == null) resource.RequiredContext.Settings = new RequireSettings();
            var resourceSettings = resource.RequiredContext.Settings;
            resourceSettings.Culture = settings.Culture;
            resourceSettings.Condition = settings.Condition;
            resourceSettings.Attributes = settings.Attributes;

            resource.RequiredContext.Resource.TagBuilder.MergeAttributes(settings.TagAttributes, true);
        }
        public void ProcessResource(CombinatorResource resource, StringBuilder combinedContent, ICombinatorSettings settings)
        {
            if (resource.IsCdnResource && !settings.CombineCDNResources)
            {
                resource.IsOriginal = true;
                return;
            }

            var absoluteUrlString = resource.AbsoluteUrl.ToString();

            _resourceFileService.LoadResourceContent(resource);

            _eventHandler.OnContentLoaded(resource);

            if (String.IsNullOrEmpty(resource.Content)) return;

            if (resource.Type == ResourceType.Style)
            {
                var stylesheet = new StylesheetParser().Parse(resource.Content);
                AdjustRelativePaths(resource, stylesheet);

                if (settings.EmbedCssImages && (settings.EmbedCssImagesStylesheetExcludeFilter == null || !settings.EmbedCssImagesStylesheetExcludeFilter.IsMatch(absoluteUrlString)))
                {
                    EmbedImages(resource, stylesheet, settings.EmbeddedImagesMaxSizeKB);
                }

                resource.Content = stylesheet.ToString();
            }

            if (settings.MinifyResources && (settings.MinificationExcludeFilter == null || !settings.MinificationExcludeFilter.IsMatch(absoluteUrlString)))
            {
                MinifyResourceContent(resource);
                if (String.IsNullOrEmpty(resource.Content)) return;
            }

            _eventHandler.OnContentProcessed(resource);

            combinedContent.Append(resource.Content);
        }
Exemplo n.º 17
0
        private static void AddTimestampToUrlIfNecessary(CombinatorResource resource)
        {
            var uriBuilder = new UriBuilder(resource.AbsoluteUrl);

            if (uriBuilder.Query.Contains("timestamp=")) return;

            uriBuilder.Query = "timestamp=" + resource.LastUpdatedUtc.ToFileTimeUtc(); // Using UriBuilder for this is maybe an overkill
            var urlString = resource.IsCdnResource || resource.IsRemoteStorageResource ? uriBuilder.Uri.ToStringWithoutScheme() : uriBuilder.Uri.PathAndQuery.ToString();
            resource.RequiredContext.Resource.SetUrl(urlString);
        }
Exemplo n.º 18
0
 public void ReplaceCssImagesWithSprite(CombinatorResource resource)
 {
     resource.Content += "ImageSprite";
 }
Exemplo n.º 19
0
        private static void ProcessUrlSettings(CombinatorResource resource, MatchEvaluator evaluator)
        {
            string content = resource.Content;

            content = Regex.Replace(
                                    content,
                                    "url\\(['|\"]?(.+?)['|\"]?\\)",
                                    evaluator,
                                    RegexOptions.IgnoreCase);

            resource.Content = content;
        }
Exemplo n.º 20
0
 public void OnContentProcessed(CombinatorResource resource)
 {
 }
Exemplo n.º 21
0
 public void SaveResource(string key, CombinatorResource resource)
 {
     Resources[key] = resource;
 }
Exemplo n.º 22
0
 public void SaveResource(CombinatorResource resource)
 {
     Resources[resource.RequiredContext.Resource.Name] = resource;
 }
Exemplo n.º 23
0
 private void MinifyResourceContent(CombinatorResource resource)
 {
     if (resource.Type == ResourceType.Style)
     {
         resource.Content = _minificationService.MinifyCss(resource.Content);
     }
     else if (resource.Type == ResourceType.JavaScript)
     {
         resource.Content = _minificationService.MinifyJavaScript(resource.Content);
     }
 }
Exemplo n.º 24
0
 private static Uri MakeInlineUri(CombinatorResource resource, string url)
 {
     return Uri.IsWellFormedUriString(url, UriKind.Absolute) ? new Uri(url) : new Uri(resource.AbsoluteUrl, url);
 }
Exemplo n.º 25
0
 private static bool IsOwnedResource(CombinatorResource resource)
 {
     return (!resource.IsCdnResource && !resource.IsOriginal) || resource.IsRemoteStorageResource;
 }
Exemplo n.º 26
0
        public void OnContentLoaded(CombinatorResource resource)
        {
            if (Path.GetExtension(resource.AbsoluteUrl.ToString()).ToLowerInvariant() != ".less") return;

            resource.Content = Less.Parse(resource.Content);
        }
        private void EmbedImages(CombinatorResource resource, Stylesheet stylesheet, int maxSizeKB)
        {
            ProcessImageUrls(
                resource,
                stylesheet,
                (ruleSet, urlTerm) =>
                {
                    var url = urlTerm.Value;
                    var imageData = _resourceFileService.GetImageContent(InlineUriFactory(resource, url), maxSizeKB);

                    if (imageData != null)
                    {
                        var dataUrl =
                        "data:image/"
                            + Path.GetExtension(url).Replace(".", "")
                            + ";base64,"
                            + Convert.ToBase64String(imageData);

                        urlTerm.Value = dataUrl;
                    }
                });
        }
Exemplo n.º 28
0
        public bool SettingsEqual(CombinatorResource other)
        {
            // If one's RequiredContext is null, their settings are not identical...
            if (RequiredContext == null ^ other.RequiredContext == null) return false;

            // However if both of them are null, we say the settings are identical
            if (RequiredContext == null && other.RequiredContext == null) return true;

            var settings = RequiredContext.Settings;
            var otherSettings = other.RequiredContext.Settings;
            return
                settings.Culture == otherSettings.Culture
                && settings.Condition == otherSettings.Condition
                && settings.AttributesEqual(otherSettings);
        }
Exemplo n.º 29
0
            public void Save(string fingerprint, CombinatorResource resource, ICombinatorSettings settings)
            {
                int count;
                sliceCounts.TryGetValue(fingerprint, out count);
                sliceCounts[fingerprint] = ++count;

                var sliceName = fingerprint + "-" + count;

                var savedResource = _resourceRepository.NewResource(resource.Type);

                var requiredContext = resource.RequiredContext;

                savedResource.IsOriginal = resource.IsOriginal;
                savedResource.LastUpdatedUtc = DateTime.UtcNow;
                savedResource.FillRequiredContext(
                    requiredContext.Resource.Name,
                    requiredContext.Resource.Url,
                    requiredContext.Settings.Culture,
                    requiredContext.Settings.Condition,
                    requiredContext.Settings.Attributes);
                savedResource.Content = resource.Content;

                if (!resource.IsOriginal)
                {
                    var url = "/Media/Default/_PiedoneModules/Combinator/";
                    if (resource.Type == ResourceType.Style) url += "Styles/" + sliceName + ".css";
                    else if (resource.Type == ResourceType.JavaScript) url += "Scripts/" + sliceName + ".js";

                    savedResource.RequiredContext.Resource.SetUrl(url);
                }

                _resourceRepository.SaveResource(sliceName, savedResource);
            }
Exemplo n.º 30
0
 public CombinatorResource GetResource(CombinatorResource resource)
 {
     return GetResource(resource.RequiredContext.Resource.Name);
 }
Exemplo n.º 31
0
            public void ProcessResource(CombinatorResource resource, StringBuilder combinedContent, ICombinatorSettings settings)
            {
                if (resource.IsCdnResource && !settings.CombineCdnResources)
                {
                    resource.IsOriginal = true;
                    return;
                }

                resource.Content = "processed: " + resource.Content;
                combinedContent.Append(resource.Content);
            }