Exemplo n.º 1
0
        protected override (string Description, WebhookJob Data) CreateJob(EnrichedEvent @event, WebhookAction action)
        {
            string requestBody;

            if (!string.IsNullOrEmpty(action.Payload))
            {
                requestBody = Format(action.Payload, @event);
            }
            else
            {
                requestBody = ToEnvelopeJson(@event);
            }

            var requestUrl = Format(action.Url, @event);

            var ruleDescription = $"Send event to webhook '{requestUrl}'";
            var ruleJob         = new WebhookJob
            {
                RequestUrl       = Format(action.Url.ToString(), @event),
                RequestSignature = $"{requestBody}{action.SharedSecret}".Sha256Base64(),
                RequestBody      = requestBody
            };

            return(ruleDescription, ruleJob);
        }
Exemplo n.º 2
0
        protected override (string Description, CommentJob Data) CreateJob(EnrichedEvent @event, CommentAction action)
        {
            if (@event is EnrichedContentEvent contentEvent)
            {
                var text = Format(action.Text, @event);

                var actor = contentEvent.Actor;

                if (!string.IsNullOrEmpty(action.Client))
                {
                    actor = new RefToken(RefTokenType.Client, action.Client);
                }

                var ruleJob = new CommentJob
                {
                    AppId      = contentEvent.AppId,
                    Actor      = actor,
                    CommentsId = contentEvent.Id.ToString(),
                    Text       = text
                };

                return(Description, ruleJob);
            }

            return("Ignore", new CommentJob());
        }
Exemplo n.º 3
0
        private List <TextPart> BuildParts(string text, EnrichedEvent @event)
        {
            var parts = new List <TextPart>();

            var span = text.AsSpan();

            var currentOffset = 0;

            for (var i = 0; i < text.Length; i++)
            {
                var c = text[i];

                if (c == '$')
                {
                    parts.Add(TextPart.Text(currentOffset, i - currentOffset));

                    var(length, part) = GetReplacement(span.Slice(i + 1).ToString(), @event);

                    if (length > 0)
                    {
                        parts.Add(part);

                        i += length + 1;
                    }

                    currentOffset = i;
                }
            }

            parts.Add(TextPart.Text(currentOffset, text.Length - currentOffset));

            return(parts);
        }
Exemplo n.º 4
0
        protected override (string Description, DiscourseJob Data) CreateJob(EnrichedEvent @event, DiscourseAction action)
        {
            var url = $"{action.Url.ToString().TrimEnd('/')}/posts.json?api_key={action.ApiKey}&api_username={action.ApiUsername}";

            var json =
                new JObject(
                    new JProperty("raw", Format(action.Text, @event)),
                    new JProperty("title", Format(action.Title, @event)));

            if (action.Topic.HasValue)
            {
                json.Add(new JProperty("topic_id", action.Topic.Value));
            }

            if (action.Category.HasValue)
            {
                json.Add(new JProperty("category", action.Category.Value));
            }

            var ruleJob = new DiscourseJob
            {
                RequestUrl  = url,
                RequestBody = json.ToString()
            };

            var description =
                action.Topic.HasValue ?
                DescriptionCreateTopic :
                DescriptionCreatePost;

            return(description, ruleJob);
        }
            public (bool Match, ValueTask <string?>) Format(EnrichedEvent @event, object value, string[] path)
            {
                if (path[0] == "data" && value is JsonArray _)
                {
                    return(true, GetValueAsync());
                }

                return(default);
Exemplo n.º 6
0
        bool IRuleTriggerHandler.Trigger(EnrichedEvent @event, RuleTrigger trigger)
        {
            if (@event is TEnrichedEvent typed)
            {
                return(Trigger(typed, (TTrigger)trigger));
            }

            return(false);
        }
Exemplo n.º 7
0
        protected override (string Description, KafkaJob Data) CreateJob(EnrichedEvent @event, KafkaAction action)
        {
            var ruleJob = new KafkaJob
            {
                TopicName    = action.TopicName,
                MessageKey   = @event.Name,
                MessageValue = ToEnvelopeJson(@event)
            };

            return(Description, ruleJob);
        }
Exemplo n.º 8
0
        bool IRuleTriggerHandler.Trigger(EnrichedEvent @event, RuleTrigger trigger)
        {
            var typed = @event as TEnrichedEvent;

            if (typed != null)
            {
                return(Trigger(typed, (TTrigger)trigger));
            }

            return(false);
        }
Exemplo n.º 9
0
        protected override (string Description, FastlyJob Data) CreateJob(EnrichedEvent @event, FastlyAction action)
        {
            var ruleJob = new FastlyJob
            {
                Key             = @event.AggregateId.ToString(),
                FastlyApiKey    = action.ApiKey,
                FastlyServiceID = action.ServiceId
            };

            return(Description, ruleJob);
        }
Exemplo n.º 10
0
        protected override (string Description, PrerenderJob Data) CreateJob(EnrichedEvent @event, PrerenderAction action)
        {
            var url = Format(action.Url, @event);

            var request     = new { prerenderToken = action.Token, url };
            var requestBody = ToJson(request);

            return($"Recache {url}", new PrerenderJob {
                RequestBody = requestBody
            });
        }
Exemplo n.º 11
0
        protected override (string Description, TweetJob Data) CreateJob(EnrichedEvent @event, TweetAction action)
        {
            var ruleJob = new TweetJob
            {
                Text         = Format(action.Text, @event),
                AccessToken  = action.AccessToken,
                AccessSecret = action.AccessSecret
            };

            return(Description, ruleJob);
        }
Exemplo n.º 12
0
        protected override (string Description, SlackJob Data) CreateJob(EnrichedEvent @event, SlackAction action)
        {
            var body = new { text = Format(action.Text, @event) };

            var ruleJob = new SlackJob
            {
                RequestUrl  = action.WebhookUrl.ToString(),
                RequestBody = ToJson(body)
            };

            return(Description, ruleJob);
        }
Exemplo n.º 13
0
        protected override (string Description, FastlyJob Data) CreateJob(EnrichedEvent @event, FastlyAction action)
        {
            var id = @event is IEnrichedEntityEvent entityEvent?entityEvent.Id.ToString() : string.Empty;

            var ruleJob = new FastlyJob
            {
                Key             = id,
                FastlyApiKey    = action.ApiKey,
                FastlyServiceID = action.ServiceId
            };

            return(Description, ruleJob);
        }
        protected override (string Description, PrerenderJob Data) CreateJob(EnrichedEvent @event, PrerenderAction action)
        {
            var url = Format(action.Url, @event);

            var request =
                new JObject(
                    new JProperty("prerenderToken", action.Token),
                    new JProperty("url", url));

            return($"Recache {url}", new PrerenderJob {
                RequestBody = request.ToString()
            });
        }
Exemplo n.º 15
0
        public static bool ShouldDelete(this EnrichedEvent @event, IScriptEngine scriptEngine, string expression)
        {
            if (!string.IsNullOrWhiteSpace(expression))
            {
                var vars = new ScriptVars
                {
                    ["event"] = @event
                };

                return(scriptEngine.Evaluate(vars, expression));
            }

            return(IsContentDeletion(@event) || IsAssetDeletion(@event));
        }
Exemplo n.º 16
0
        protected override (string Description, SlackJob Data) CreateJob(EnrichedEvent @event, SlackAction action)
        {
            var body =
                new JObject(
                    new JProperty("text", Format(action.Text, @event)));

            var ruleJob = new SlackJob
            {
                RequestUrl  = action.WebhookUrl.ToString(),
                RequestBody = body.ToString(Formatting.Indented)
            };

            return(Description, ruleJob);
        }
Exemplo n.º 17
0
        public static bool ShouldDelete(this EnrichedEvent @event, IScriptEngine scriptEngine, string expression)
        {
            if (!string.IsNullOrWhiteSpace(expression))
            {
                // Script vars are just wrappers over dictionaries for better performance.
                var vars = new EventScriptVars
                {
                    Event = @event
                };

                return(scriptEngine.Evaluate(vars, expression));
            }

            return(IsContentDeletion(@event) || IsAssetDeletion(@event));
        }
Exemplo n.º 18
0
        protected override (string Description, WebhookJob Data) CreateJob(EnrichedEvent @event, WebhookAction action)
        {
            var requestBody = formatter.ToEnvelope(@event).ToString(Formatting.Indented);
            var requestUrl  = formatter.Format(action.Url.ToString(), @event);

            var ruleDescription = $"Send event to webhook '{requestUrl}'";
            var ruleJob         = new WebhookJob
            {
                RequestUrl       = requestUrl,
                RequestSignature = $"{requestBody}{action.SharedSecret}".Sha256Base64(),
                RequestBodyV2    = requestBody
            };

            return(ruleDescription, ruleJob);
        }
Exemplo n.º 19
0
        protected override (string Description, SendGridJob Data) CreateJob(EnrichedEvent @event, SendGridAction action)
        {
            var ruleJob = new SendGridJob
            {
                APIKey         = action.APIKey,
                MessageFrom    = Format(action.MessageFrom, @event),
                MessageTo      = Format(action.MessageTo, @event),
                MessageSubject = Format(action.MessageSubject, @event),
                MessageBody    = Format(action.MessageBody, @event)
            };

            var description = $"Send an email to {action.MessageTo}";

            return(description, ruleJob);
        }
Exemplo n.º 20
0
        protected override (string Description, MediumJob Data) CreateJob(EnrichedEvent @event, MediumAction action)
        {
            var requestBody =
                new JObject(
                    new JProperty("title", Format(action.Title, @event)),
                    new JProperty("contentFormat", action.IsHtml ? "html" : "markdown"),
                    new JProperty("content", Format(action.Content, @event)),
                    new JProperty("canonicalUrl", Format(action.CanonicalUrl, @event)),
                    new JProperty("tags", ParseTags(@event, action)));

            var ruleJob = new MediumJob {
                AccessToken = action.AccessToken, RequestBody = requestBody.ToString(Formatting.Indented)
            };

            return(Description, ruleJob);
        }
Exemplo n.º 21
0
        private async Task EnrichDefaultAsync(EnrichedEvent result, Envelope <AppEvent> @event)
        {
            result.Timestamp = @event.Headers.Timestamp();

            if (@event.Payload is SquidexEvent squidexEvent)
            {
                result.Actor = squidexEvent.Actor;
            }

            if (@event.Payload is AppEvent appEvent)
            {
                result.AppId = appEvent.AppId;
            }

            result.User = await FindUserAsync(result.Actor);
        }
Exemplo n.º 22
0
        public bool Trigger(EnrichedEvent @event, RuleContext context)
        {
            var trigger = (SchemaChangedTrigger)context.Rule.Trigger;

            if (string.IsNullOrWhiteSpace(trigger.Condition))
            {
                return(true);
            }

            var vars = new ScriptVars
            {
                ["event"] = @event
            };

            return(scriptEngine.Evaluate(vars, trigger.Condition));
        }
Exemplo n.º 23
0
        public async Task EnrichAsync(EnrichedEvent enrichedEvent, Envelope <AppEvent> @event)
        {
            enrichedEvent.Timestamp = @event.Headers.Timestamp();

            if (enrichedEvent is EnrichedUserEventBase userEvent)
            {
                if (@event.Payload is SquidexEvent squidexEvent)
                {
                    userEvent.Actor = squidexEvent.Actor;
                }

                userEvent.User = await FindUserAsync(userEvent.Actor);
            }

            enrichedEvent.AppId = @event.Payload.AppId;
        }
Exemplo n.º 24
0
        public async ValueTask <string?> FormatAsync(string text, EnrichedEvent @event)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return(text);
            }

            if (TryGetTemplate(text.Trim(), out var template))
            {
                var vars = new TemplateVars
                {
                    ["event"] = @event
                };

                return(await templateEngine.RenderAsync(template, vars));
            }

            if (TryGetScript(text.Trim(), out var script))
            {
                // Script vars are just wrappers over dictionaries for better performance.
                var vars = new EventScriptVars
                {
                    Event   = @event,
                    AppId   = @event.AppId.Id,
                    AppName = @event.AppId.Name,
                    User    = Admin()
                };

                var result = (await scriptEngine.ExecuteAsync(vars, script)).ToString();

                if (result == "undefined")
                {
                    return(GlobalFallback);
                }

                return(result);
            }

            var parts = BuildParts(text, @event);

            if (parts.Any(x => !x.Var.IsCompleted))
            {
                await ValueTaskEx.WhenAll(parts.Select(x => x.Var));
            }

            return(CombineParts(text, parts));
        }
Exemplo n.º 25
0
        public bool Trigger(EnrichedEvent @event, RuleContext context)
        {
            var trigger = (CommentTrigger)context.Rule.Trigger;

            if (string.IsNullOrWhiteSpace(trigger.Condition))
            {
                return(true);
            }

            // Script vars are just wrappers over dictionaries for better performance.
            var vars = new EventScriptVars
            {
                Event = @event
            };

            return(scriptEngine.Evaluate(vars, trigger.Condition));
        }
Exemplo n.º 26
0
        private (int Length, TextPart Part) GetReplacement(string test, EnrichedEvent @event)
        {
            var(isNewRegex, match) = Match(test);

            if (match.Success)
            {
                var(length, replacement) = ResolveOldPatterns(match, isNewRegex, @event);

                if (length == 0)
                {
                    (length, replacement) = ResolveFromPath(match, @event);
                }

                return(length, TextPart.Variable(replacement, match.Groups["Fallback"].Value, match.Groups["Transform"].Value));
            }

            return(default);
Exemplo n.º 27
0
        private List <TextPart> BuildParts(string text, EnrichedEvent @event)
        {
            var parts = new List <TextPart>();

            var span = text.AsSpan();

            var currentOffset = 0;

            for (var i = 0; i < text.Length; i++)
            {
                var c = text[i];

                if (c == '$')
                {
                    parts.Add(TextPart.Text(currentOffset, i - currentOffset));

                    var(length, part) = GetReplacement(span[(i + 1)..].ToString(), @event);
Exemplo n.º 28
0
        public async ValueTask <string?> FormatAsync(string text, EnrichedEvent @event)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return(text);
            }

            if (TryGetTemplate(text.Trim(), out var template))
            {
                var vars = new TemplateVars
                {
                    ["event"] = @event
                };

                return(await templateEngine.RenderAsync(template, vars));
            }

            if (TryGetScript(text.Trim(), out var script))
            {
                var vars = new ScriptVars
                {
                    ["event"] = @event
                };

#pragma warning disable MA0042 // Do not use blocking calls in an async method
                var result = scriptEngine.Execute(vars, script).ToString();
#pragma warning restore MA0042 // Do not use blocking calls in an async method

                if (result == "undefined")
                {
                    return(GlobalFallback);
                }

                return(result);
            }

            var parts = BuildParts(text, @event);

            if (parts.Any(x => !x.Var.IsCompleted))
            {
                await ValueTaskEx.WhenAll(parts.Select(x => x.Var));
            }

            return(CombineParts(text, parts));
        }
Exemplo n.º 29
0
        protected override (string Description, FastlyJob Data) CreateJob(EnrichedEvent @event, FastlyAction action)
        {
            var id = string.Empty;

            if (@event is IEnrichedEntityEvent entityEvent)
            {
                id = DomainId.Combine(@event.AppId.Id, entityEvent.Id).ToString();
            }

            var ruleJob = new FastlyJob
            {
                Key             = id,
                FastlyApiKey    = action.ApiKey,
                FastlyServiceID = action.ServiceId
            };

            return(Description, ruleJob);
        }
Exemplo n.º 30
0
        private async Task <string[]> ParseTagsAsync(EnrichedEvent @event, MediumAction action)
        {
            if (string.IsNullOrWhiteSpace(action.Tags))
            {
                return(null);
            }

            try
            {
                var jsonTags = await FormatAsync(action.Tags, @event);

                return(serializer.Deserialize <string[]>(jsonTags));
            }
            catch
            {
                return(action.Tags.Split(','));
            }
        }