示例#1
0
        public void Update_should_create_events()
        {
            var newTrigger = new ContentChangedTrigger
            {
                Schemas = new List <ContentChangedTriggerSchema>()
            };

            var newAction = new WebhookAction
            {
                Url = new Uri("https://squidex.io/v2")
            };

            CreateRule();

            var command = new UpdateRule {
                Trigger = newTrigger, Action = newAction
            };

            sut.Update(CreateRuleCommand(command));

            sut.GetUncomittedEvents()
            .ShouldHaveSameEvents(
                CreateRuleEvent(new RuleUpdated {
                Trigger = newTrigger, Action = newAction
            })
                );
        }
示例#2
0
        public void Update_should_create_events()
        {
            var newTrigger = new ContentChangedTrigger
            {
                Schemas = ImmutableList <ContentChangedTriggerSchema> .Empty
            };

            var newAction = new WebhookAction
            {
                Url = new Uri("https://squidex.io/v2")
            };

            CreateRule();

            var command = new UpdateRule {
                Trigger = newTrigger, Action = newAction
            };

            sut.Update(CreateRuleCommand(command));

            Assert.Same(newTrigger, sut.State.RuleDef.Trigger);
            Assert.Same(newAction, sut.State.RuleDef.Action);

            sut.GetUncomittedEvents()
            .ShouldHaveSameEvents(
                CreateRuleEvent(new RuleUpdated {
                Trigger = newTrigger, Action = newAction
            })
                );
        }
示例#3
0
文件: RuleTests.cs 项目: ifle/squidex
        public void Should_replace_action_when_updating()
        {
            var newAction = new WebhookAction();

            sut.Update(newAction);

            Assert.Same(newAction, sut.Action);
        }
示例#4
0
文件: RuleTests.cs 项目: zxbe/squidex
        public void Should_replace_action_when_updating()
        {
            var newAction = new WebhookAction();

            var rule_1 = rule_0.Update(newAction);

            Assert.NotSame(newAction, rule_0.Action);
            Assert.Same(newAction, rule_1.Action);
        }
示例#5
0
        public async Task Should_not_add_error_if_url_is_absolute()
        {
            var action = new WebhookAction {
                Url = new Uri("https://squidex.io", UriKind.Absolute)
            };

            var errors = await RuleActionValidator.ValidateAsync(action);

            Assert.Empty(errors);
        }
示例#6
0
        public async Task Should_add_error_if_url_is_relative()
        {
            var action = new WebhookAction {
                Url = new Uri("/invalid", UriKind.Relative)
            };

            var errors = await RuleActionValidator.ValidateAsync(action);

            Assert.NotEmpty(errors);
        }
示例#7
0
        public async Task Should_add_error_if_url_is_null()
        {
            var action = new WebhookAction {
                Url = null
            };

            var errors = await RuleActionValidator.ValidateAsync(action);

            Assert.NotEmpty(errors);
        }
示例#8
0
        public Task <IEnumerable <ValidationError> > Visit(WebhookAction action)
        {
            var errors = new List <ValidationError>();

            if (action.Url == null || !action.Url.IsAbsoluteUri)
            {
                errors.Add(new ValidationError("Url is required and must be an absolute URL.", nameof(action.Url)));
            }

            return(Task.FromResult <IEnumerable <ValidationError> >(errors));
        }
示例#9
0
文件: RuleTests.cs 项目: ifle/squidex
        public void Should_create_with_trigger_and_action()
        {
            var ruleTrigger = new ContentChangedTrigger();
            var ruleAction  = new WebhookAction();

            var newRule = new Rule(ruleTrigger, ruleAction);

            Assert.Equal(ruleTrigger, newRule.Trigger);
            Assert.Equal(ruleAction, newRule.Action);
            Assert.True(newRule.IsEnabled);
        }
示例#10
0
        public async Task Should_add_error_if_url_is_relative()
        {
            var action = new WebhookAction {
                Url = new Uri("/invalid", UriKind.Relative)
            };

            var errors = await RuleActionValidator.ValidateAsync(action);

            errors.Should().BeEquivalentTo(
                new List <ValidationError>
            {
                new ValidationError("URL is required and must be an absolute URL.", "Url")
            });
        }
示例#11
0
        public async Task Should_add_error_if_url_is_null()
        {
            var action = new WebhookAction {
                Url = null
            };

            var errors = await RuleActionValidator.ValidateAsync(action);

            errors.ShouldBeEquivalentTo(
                new List <ValidationError>
            {
                new ValidationError("URL is required and must be an absolute URL.", "Url")
            });
        }
示例#12
0
        private static UpdateRule MakeUpdateCommand()
        {
            var newTrigger = new ContentChangedTrigger
            {
                Schemas = ImmutableList <ContentChangedTriggerSchema> .Empty
            };

            var newAction = new WebhookAction
            {
                Url = new Uri("https://squidex.io/v2")
            };

            return(new UpdateRule {
                Trigger = newTrigger, Action = newAction
            });
        }
示例#13
0
        public static WebhookAction MapToWebhookAction(WebhookActionModel model)
        {
            var action = new WebhookAction(model.Name, model.Url, model.Request);

            action.SetCodename(model.Codename);
            if (model.Inactive)
            {
                action.Deactivate();
            }
            foreach (var header in model.Headers ?? new Dictionary <string, object>())
            {
                action.Headers[header.Key] = header.Value;
            }

            return(action);
        }
示例#14
0
 public RuleActionDto Visit(WebhookAction action)
 {
     return(SimpleMapper.Map(action, new WebhookActionDto()));
 }
示例#15
0
        private static async Task <IWorkflowMessage> GetWebhookMessage(int userId, int revisionId, long transactionId, WebhookAction webhookAction,
                                                                       IWebhooksRepository webhooksRepository, WebhookArtifactInfo webhookArtifactInfo)
        {
            List <int> webhookId = new List <int> {
                webhookAction.WebhookId
            };
            var webhookInfos = await webhooksRepository.GetWebhooks(webhookId);

            var webhookInfo = webhookInfos.FirstOrDefault();

            var securityInfo = SerializationHelper.FromXml <XmlWebhookSecurityInfo>(webhookInfo.SecurityInfo);

            var webhookMessage = new WebhookMessage
            {
                TransactionId = transactionId,
                UserId        = userId,
                RevisionId    = revisionId,
                // Authentication Information
                Url = webhookInfo.Url,
                IgnoreInvalidSSLCertificate = securityInfo.IgnoreInvalidSSLCertificate,
                HttpHeaders          = securityInfo.HttpHeaders,
                BasicAuthUsername    = securityInfo.BasicAuth?.Username,
                BasicAuthPassword    = securityInfo.BasicAuth?.Password,
                SignatureSecretToken = securityInfo.Signature?.SecretToken,
                SignatureAlgorithm   = securityInfo.Signature?.Algorithm,
                // Payload Information
                WebhookJsonPayload = webhookArtifactInfo.ToJSON()
            };

            return(webhookMessage);
        }
示例#16
0
        public IActionResult EventProcesor(
            [FromRoute(Name = "event")] string eventName,
            [FromRoute(Name = "access")] string accessKey,
            [FromQuery] string value1,
            [FromQuery] string value2,
            [FromQuery] string value3)
        {
            if (accessKey != _SITE_AccessKey)
            {
                _logger.LogError($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Invalid key: {accessKey}");
                return(BadRequest());
            }

            try
            {
                if (eventName == "xo")
                {
                    _logger.LogWarning($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Triggered event: xo (execute order), Value1: {value1}, Value2: {value2}, Value3: {value3}");

                    var recipients = new string[]
                    {
                        "*****@*****.**"
                    };
                    foreach (var recipient in recipients)
                    {
                        var emailAction = new EmailAction
                        {
                            Addresses = new string[] { recipient },
                            Subject   = "Execute Request: Result",
                            Body      = $"v1: {value1}\r\nv2: {value2}\r\nv2: {value3}\r\n"
                        };
                        _notify.EmailActions.Add(emailAction.Id, emailAction);
                        _logger.LogInformation($"EmailAction queued: {eventName} for {recipient}");
                    }

                    return(Ok("Accepted"));
                }

                if (eventName == "mdet1")
                {
                    _logger.LogWarning($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Triggered event: motion1 (motion detector test)");

                    var webhookEvent = new WebhookAction
                    {
                        Url           = string.Format(_IFTTT_BaseAddress, eventName + "_ack", _IFTTT_WebhookAccessKey),
                        Attempts      = 0,
                        PerishSeconds = 120,
                        Payload       = string.Empty
                    };
                    _notify.WebHookActions.Add(webhookEvent.Id, webhookEvent);
                    _logger.LogInformation($"Action queued: motion_detected ({webhookEvent.Id})");

                    var recipients = new string[]
                    {
                        "*****@*****.**",
                        "*****@*****.**"
                    };
                    foreach (var recipient in recipients)
                    {
                        var emailAction = new EmailAction
                        {
                            Addresses = new string[] { recipient },
                            Subject   = "Motion Detector Test: Result",
                            Body      = "A motion detector test was triggered by an incoming webhook"
                        };
                        _notify.EmailActions.Add(emailAction.Id, emailAction);
                        _logger.LogInformation($"EmailAction queued: {eventName} for {recipient}");
                    }
                    return(Ok("Accepted"));
                }

                if (eventName == "led_on")
                {
                    _flash.LightVisibility = Flash.LightState.On;
                    _logger.LogWarning($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Triggered event: led_on (LED on)");

#if USE_GPIO
                    GpioController controller = new GpioController(_flash.PinScheme);
                    controller.OpenPin(_flash.LedPin, PinMode.Output);
                    controller.Write(_flash.LedPin, PinValue.High);
#endif
                    return(Ok("Accepted"));
                }

                if (eventName == "led_off")
                {
                    _flash.LightVisibility = Flash.LightState.Off;
                    _logger.LogWarning($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Triggered event: led_off (LED off)");
                    return(Ok("Accepted"));
                }

                if (eventName == "led_toggle")
                {
                    _flash.LightVisibility = (
                        _flash.LightVisibility == Flash.LightState.Flashing ? Flash.LightState.Off :
                        (_flash.LightVisibility == Flash.LightState.On ? Flash.LightState.Off : Flash.LightState.On)
                        );
                    _logger.LogWarning($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Triggered event: led_toggle (LED toggle)");
                    return(Ok("Accepted"));
                }

                if (eventName == "led_flash")
                {
                    _flash.LightVisibility = Flash.LightState.Flashing;
                    _flash.FlashingMode    = Flash.FlashMode.Fast;
                    var phrase = value2.ToLower().Replace("\"", string.Empty).Trim();
                    if (_flash.FlashPhrases.ContainsKey(phrase))
                    {
                        _flash.FlashingMode = _flash.FlashPhrases[phrase];
                    }
                    _flash.FlashIndex = 0;
                    _logger.LogWarning($"Request from: {Request.HttpContext.Connection.RemoteIpAddress}: Triggered event: led_flash ({_flash.FlashingMode}) with phrase ({value2})");
                    return(Ok("Accepted"));
                }
                _logger.LogError($"Unknown event requested: {eventName}");
                return(NotFound("Unknown request"));
            }
            catch (Exception err)
            {
                _logger.LogCritical($"Unhandled exception: {err.Message}");
                return(StatusCode(500, err.Message));
            }
        }