示例#1
0
        /// <inheritdoc />
        public override async Task <IDocument> ExecuteAsync(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context)
        {
            IMetadataDictionary dictionary = args.ToDictionary(
                "Language",
                "Element",
                "HighlightJsFile");

            HtmlParser parser = new HtmlParser();

            using (IJavaScriptEnginePool enginePool = context.GetJavaScriptEnginePool(x =>
            {
                if (dictionary.ContainsKey("HighlightJsFile"))
                {
                    x.ExecuteFile(dictionary.GetString("HighlightJsFile"));
                }
                else
                {
                    x.ExecuteResource("highlight-all.js", typeof(Statiq.Highlight.HighlightCode));
                }
            }))
            {
                AngleSharp.Dom.IDocument htmlDocument = parser.Parse(string.Empty);
                AngleSharp.Dom.IElement  element      = htmlDocument.CreateElement(dictionary.GetString("Element", "code"));
                element.InnerHtml = content.Trim();
                if (dictionary.ContainsKey("Language"))
                {
                    element.SetAttribute("class", $"language-{dictionary.GetString("Language")}");
                }
                Statiq.Highlight.HighlightCode.HighlightElement(enginePool, element);
                return(context.CreateDocument(await context.GetContentProviderAsync(element.OuterHtml)));
            }
        }
        /// <inheritdoc />
        public override async Task <IDocument> ExecuteAsync(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context)
        {
            IMetadataDictionary arguments = args.ToDictionary(
                "Path",
                "IncludeHost",
                "Host",
                "Root",
                "Scheme",
                "UseHttps",
                "HideIndexPages",
                "HideExtensions",
                "Lowercase");

            arguments.RequireKeys("Path");

            string path = arguments.GetString("Path");

            if (LinkGenerator.TryGetAbsoluteHttpUri(path, out string absoluteUri))
            {
                return(context.CreateDocument(await context.GetContentProviderAsync(absoluteUri)));
            }
            FilePath filePath = new FilePath(path);

            // Use "Host" if it's provided, otherwise use Host setting if "IncludeHost" is true
            string host = arguments.GetString("Host", arguments.GetBool("IncludeHost") ? context.Settings.GetString(Keys.Host) : null);

            // Use "Root" if it's provided, otherwise LinkRoot setting
            DirectoryPath root = arguments.GetDirectoryPath("Root", context.Settings.GetDirectoryPath(Keys.LinkRoot));

            // Use "Scheme" if it's provided, otherwise if "UseHttps" is true use "https" or use LinksUseHttps setting
            string scheme = arguments.GetString("Scheme", arguments.ContainsKey("UseHttps")
                ? (arguments.GetBool("UseHttps") ? "https" : null)
                : (context.Settings.GetBool(Keys.LinksUseHttps) ? "https" : null));

            // If "HideIndexPages" is provided and true use default hide pages, otherwise use default hide pages if LinkHideIndexPages is true
            string[] hidePages = arguments.ContainsKey("HideIndexPages")
                ? (arguments.GetBool("HideIndexPages") ? LinkGenerator.DefaultHidePages : null)
                : (context.Settings.GetBool(Keys.LinkHideIndexPages) ? LinkGenerator.DefaultHidePages : null);

            // If "HideExtensions" is provided and true use default hide extensions, otherwise use default hide extensions if LinkHideExtensions is true
            string[] hideExtensions = arguments.ContainsKey("HideExtensions")
                ? (arguments.GetBool("HideExtensions") ? LinkGenerator.DefaultHideExtensions : null)
                : (context.Settings.GetBool(Keys.LinkHideExtensions) ? LinkGenerator.DefaultHideExtensions : null);

            // If "Lowercase" is provided use that, otherwise use LinkLowercase setting
            bool lowercase = arguments.ContainsKey("Lowercase")
                ? arguments.GetBool("Lowercase")
                : context.Settings.GetBool(Keys.LinkLowercase);

            return(context.CreateDocument(await context.GetContentProviderAsync(LinkGenerator.GetLink(filePath, host, root, scheme, hidePages, hideExtensions, lowercase))));
        }
示例#3
0
        /// <inheritdoc />
        public override ShortcodeResult Execute(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context)
        {
            IMetadataDictionary arguments = args.ToDictionary(
                Path,
                IncludeHost,
                Host,
                Root,
                Scheme,
                UseHttps,
                HideIndexPages,
                HideExtensions,
                Lowercase);

            arguments.RequireKeys(Path);

            string path = arguments.GetString(Path);

            if (LinkGenerator.TryGetAbsoluteHttpUri(path, out string absoluteUri))
            {
                return(absoluteUri);
            }
            NormalizedPath filePath = new NormalizedPath(path);

            // Use "Host" if it's provided, otherwise use Host setting if "IncludeHost" is true
            string host = arguments.GetString(Host, arguments.GetBool(IncludeHost) ? context.Settings.GetString(Keys.Host) : null);

            // Use "Root" if it's provided, otherwise LinkRoot setting
            NormalizedPath root = arguments.GetPath(Root, context.Settings.GetPath(Keys.LinkRoot));

            // Use "Scheme" if it's provided, otherwise if "UseHttps" is true use "https" or use LinksUseHttps setting
            string scheme = arguments.GetString(Scheme, arguments.ContainsKey(UseHttps)
                ? (arguments.GetBool(UseHttps) ? "https" : null)
                : (context.Settings.GetBool(Keys.LinksUseHttps) ? "https" : null));

            // If "HideIndexPages" is provided and true use default hide pages, otherwise use default hide pages if LinkHideIndexPages is true
            string[] hidePages = arguments.ContainsKey(HideIndexPages)
                ? (arguments.GetBool(HideIndexPages) ? LinkGenerator.DefaultHidePages : null)
                : (context.Settings.GetBool(Keys.LinkHideIndexPages) ? LinkGenerator.DefaultHidePages : null);

            // If "HideExtensions" is provided and true use default hide extensions, otherwise use default hide extensions if LinkHideExtensions is true
            string[] hideExtensions = arguments.ContainsKey(HideExtensions)
                ? (arguments.GetBool(HideExtensions) ? LinkGenerator.DefaultHideExtensions : null)
                : (context.Settings.GetBool(Keys.LinkHideExtensions) ? LinkGenerator.DefaultHideExtensions : null);

            // If "Lowercase" is provided use that, otherwise use LinkLowercase setting
            bool lowercase = arguments.ContainsKey(Lowercase)
                ? arguments.GetBool(Lowercase)
                : context.Settings.GetBool(Keys.LinkLowercase);

            return(LinkGenerator.GetLink(filePath, host, root, scheme, hidePages, hideExtensions, lowercase));
        }
        public override async Task <IDocument> ExecuteAsync(
            KeyValuePair <string, string>[] args,
            string content,
            IDocument document,
            IExecutionContext context)
        {
            IMetadataDictionary dictionary = args.ToDictionary(
                "Key",
                "Value");

            dictionary.RequireKeys("Key");

            object keyValue = document.Get(dictionary.GetString("Key"));

            if (dictionary.ContainsKey("Value"))
            {
                return(TypeHelper.TryConvert(dictionary.Get("Value"), keyValue.GetType(), out object value) &&
                       (keyValue?.Equals(value) ?? (keyValue == null && value == null))
                    ? await document.CloneAsync(content)
                    : null);
            }

            return(TypeHelper.TryConvert(keyValue, out bool result) && result
                ? await document.CloneAsync(content)
                : null);
        }
 private static DateTime?GetExpiry(IMetadataDictionary metadata)
 {
     if (metadata.ContainsKey(Constants.Documents.Metadata.Expires))
     {
         return(DateTime.Parse(metadata[Constants.Documents.Metadata.Expires].ToString()).ToUniversalTime());
     }
     else
     {
         return(null);
     }
 }
示例#6
0
        /// <summary>
        /// Shortcodes for specific oEmbed services should override this method and call one of the other execute helper methods.
        /// </summary>
        public virtual async Task <ShortcodeResult> ExecuteAsync(KeyValuePair <string, string>[] args, IDocument document, IExecutionContext context)
        {
            IMetadataDictionary arguments = args.ToDictionary(Endpoint, Url, Format);

            arguments.RequireKeys(Endpoint, Url);
            return(await GetEmbedResultAsync(
                       arguments.GetString(Endpoint),
                       arguments.GetString(Url),
                       arguments.ContainsKey(Format)
                       ?new string[] { $"format={arguments.GetString(Format)}" }
                       : null,
                       context));
        }
示例#7
0
        public static TocItem Create(IMetadataDictionary data)
        {
            var tocItem = new TocItem()
            {
                Title = data.Get <string>("title"),
                Link  = data.Get <string>("link"),
            };

            if (data.ContainsKey("children"))
            {
                tocItem.Children = Create(data.GetList <IMetadataDictionary>("children"));
            }

            return(tocItem);
        }
        /// <summary>
        /// Shortcodes for specific oEmbed services should override this method and call one of the other execute helper methods.
        /// </summary>
        public override async Task <IDocument> ExecuteAsync(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context)
        {
            IMetadataDictionary arguments = args.ToDictionary(
                "Endpoint",
                "Url",
                "Format");

            arguments.RequireKeys("Endpoint", "Url");
            return(await ExecuteAsync(
                       arguments.GetString("Endpoint"),
                       arguments.GetString("Url"),
                       arguments.ContainsKey("Format")
                       ?new string[] { $"format={arguments.GetString("Format")}" }
                       : null,
                       context));
        }
示例#9
0
        /// <inheritdoc />
        public override async Task <IDocument> ExecuteAsync(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context)
        {
            IMetadataDictionary arguments = args.ToDictionary(
                "Id",
                "HideMedia",
                "HideThread",
                "Theme",
                "OmitScript");

            arguments.RequireKeys("Id");

            // Create the url
            List <string> query = new List <string>();

            if (arguments.GetBool("HideMedia"))
            {
                query.Add("hide_media=true");
            }
            if (arguments.GetBool("HideThread"))
            {
                query.Add("hide_thread=true");
            }
            if (arguments.ContainsKey("Theme"))
            {
                query.Add($"theme={arguments.GetString("theme")}");
            }
            if (_omitScript || arguments.GetBool("OmitScript"))
            {
                query.Add("omit_script=true");
            }

            // Omit the script on the next Twitter embed
            _omitScript = true;

            return(await ExecuteAsync("https://publish.twitter.com/oembed", $"https://twitter.com/username/status/{arguments.GetString("Id")}", query, context));
        }
示例#10
0
        public override ShortcodeResult Execute(
            KeyValuePair <string, string>[] args,
            string content,
            IDocument document,
            IExecutionContext context)
        {
            IMetadataDictionary dictionary = args.ToDictionary(Key, Value);

            dictionary.RequireKeys(Key);

            object keyValue = document.Get(dictionary.GetString(Key));

            if (dictionary.ContainsKey(Value))
            {
                return(TypeHelper.TryConvert(dictionary.Get(Value), keyValue.GetType(), out object value) &&
                       (keyValue?.Equals(value) ?? (keyValue == null && value == null))
                    ? content
                    : null);
            }

            return(TypeHelper.TryConvert(keyValue, out bool result) && result
                ? content
                : null);
        }
示例#11
0
        /// <inheritdoc />
        public override async Task <ShortcodeResult> ExecuteAsync(KeyValuePair <string, string>[] args, IDocument document, IExecutionContext context)
        {
            IMetadataDictionary arguments = args.ToDictionary(
                Id,
                HideMedia,
                HideThread,
                Theme,
                OmitScript);

            arguments.RequireKeys(Id);

            // Create the url
            List <string> query = new List <string>();

            if (arguments.GetBool(HideMedia))
            {
                query.Add("hide_media=true");
            }
            if (arguments.GetBool(HideThread))
            {
                query.Add("hide_thread=true");
            }
            if (arguments.ContainsKey(Theme))
            {
                query.Add($"theme={arguments.GetString(Theme)}");
            }
            if (_omitScript || arguments.GetBool(OmitScript))
            {
                query.Add("omit_script=true");
            }

            // Omit the script on the next Twitter embed
            _omitScript = true;

            return(await GetEmbedResultAsync("https://publish.twitter.com/oembed", $"https://twitter.com/username/status/{arguments.GetString(Id)}", query, context));
        }
        public async Task MakeSureDeletionsRevisionsDontReplicate()
        {
            var certificates = Certificates.SetupServerAuthentication();
            var adminCert    = Certificates.RegisterClientCertificate(certificates.ServerCertificate.Value, certificates
                                                                      .ClientCertificate1.Value, new Dictionary <string, DatabaseAccess>(), SecurityClearance.ClusterAdmin);

            var hubDatabase  = GetDatabaseName("HUB");
            var sinkDatabase = GetDatabaseName("SINK");

            using var hubStore = GetDocumentStore(new RavenTestBase.Options
            {
                AdminCertificate   = adminCert,
                ClientCertificate  = adminCert,
                ModifyDatabaseName = x => hubDatabase
            });

            using var sinkStore = GetDocumentStore(new RavenTestBase.Options
            {
                AdminCertificate   = adminCert,
                ClientCertificate  = adminCert,
                ModifyDatabaseName = x => sinkDatabase
            });

            //setup expiration
            await SetupExpiration(sinkStore);

            var pullCert = new X509Certificate2(File.ReadAllBytes(certificates.ClientCertificate2Path), (string)null,
                                                X509KeyStorageFlags.Exportable);

            await hubStore.Maintenance.SendAsync(new PutPullReplicationAsHubOperation(new PullReplicationDefinition
            {
                Name = "pullRepHub",
                Mode = PullReplicationMode.SinkToHub | PullReplicationMode.HubToSink,
                PreventDeletionsMode = PreventDeletionsMode.PreventSinkToHubDeletions
            }));

            await hubStore.Maintenance.SendAsync(new RegisterReplicationHubAccessOperation("pullRepHub",
                                                                                           new ReplicationHubAccess {
                Name = "hubAccess", CertificateBase64 = Convert.ToBase64String(pullCert.Export(X509ContentType.Cert))
            }));

            await sinkStore.Maintenance.SendAsync(new PutConnectionStringOperation <RavenConnectionString>(new RavenConnectionString
            {
                Database = hubStore.Database,
                Name = hubStore.Database + "ConStr",
                TopologyDiscoveryUrls = hubStore.Urls
            }));

            await sinkStore.Maintenance.SendAsync(new UpdatePullReplicationAsSinkOperation(new PullReplicationAsSink
            {
                ConnectionStringName = hubStore.Database + "ConStr",
                Mode = PullReplicationMode.SinkToHub | PullReplicationMode.HubToSink,
                CertificateWithPrivateKey = Convert.ToBase64String(pullCert.Export(X509ContentType.Pfx)),
                HubName = "pullRepHub"
            }));

            //enable revisions
            await RevisionsHelper.SetupRevisions(Server.ServerStore, sinkStore.Database, r => r.Collections["Users"].PurgeOnDelete = false);

            //create doc in sink
            using (var s = sinkStore.OpenAsyncSession())
            {
                dynamic user1 = new User {
                    Source = "Sink"
                };
                await s.StoreAsync(user1, "users/insink/1");

                s.Advanced.GetMetadataFor(user1)[Constants.Documents.Metadata.Expires] = DateTime.UtcNow.AddMinutes(10);

                await s.SaveChangesAsync();
            }

            //create revision
            using (var s = sinkStore.OpenAsyncSession())
            {
                var user1 = await s.LoadAsync <User>("users/insink/1");

                user1.Source = "SinkAfterChange";
                await s.SaveChangesAsync();
            }

            //create doc in hub
            using (var s = hubStore.OpenAsyncSession())
            {
                await s.StoreAsync(new { Source = "Hub" }, "users/inhub/1");

                await s.SaveChangesAsync();
            }

            Assert.True(WaitForDocument(sinkStore, "users/inhub/1"));

            //make sure hub got both docs and expires gets deleted
            using (var h = hubStore.OpenAsyncSession())
            {
                //check hub got both docs
                var doc1 = await h.LoadAsync <dynamic>("users/insink/1");

                Assert.NotNull(doc1);

                //check expired does not exist in users/insink/1
                IMetadataDictionary metadata = h.Advanced.GetMetadataFor(doc1);
                Assert.False(metadata?.ContainsKey(Constants.Documents.Metadata.Expires));
            }

            //delete doc from sink
            using (var s = sinkStore.OpenAsyncSession())
            {
                s.Delete("users/insink/1");
                await s.SaveChangesAsync();
            }

            EnsureReplicating(hubStore, sinkStore);
            EnsureReplicating(sinkStore, hubStore);

            //make sure doc is deleted from sink
            Assert.True(WaitForDocumentDeletion(sinkStore, "users/insink/1"));

            //make sure doc not deleted from hub and still doesn't contain expires
            using (var h = hubStore.OpenAsyncSession())
            {
                //check hub got doc
                var doc1 = await h.LoadAsync <dynamic>("users/insink/1");

                Assert.NotNull(doc1);

                //check expires does not exist in users/insink/1
                IMetadataDictionary metadata = h.Advanced.GetMetadataFor(doc1);
                Assert.False(metadata?.ContainsKey(Constants.Documents.Metadata.Expires));
            }
        }