Example #1
0
        // no more than one alert per week
        public static async Task suppressDetection(EventItem eventItem, string type, string userId, string evidence)
        {
            var now = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();

            //we don't want to raise alert on old events
            if (eventItem.timestamp < now - TimeSpan.FromDays(7).TotalSeconds)
            {
                return;
            }

            var sqlQueryText = $"SELECT TOP 1 * FROM c WHERE c.device_id = '{eventItem.device_id}' AND " +
                               $"c.created_at >  {(now - TimeSpan.FromDays(7).TotalSeconds)} AND " +
                               $"c.type = '{type}' order by c.created_at";

            logger.LogInformation("Checking older alerts...");

            QueryDefinition          queryDefinition        = new QueryDefinition(sqlQueryText);
            FeedIterator <AlertItem> queryResultSetIterator = Resources.alert_container.GetItemQueryIterator <AlertItem>(queryDefinition);

            if (queryResultSetIterator.HasMoreResults)
            {
                FeedResponse <AlertItem> currentResultSet = await queryResultSetIterator.ReadNextAsync();

                AlertItem alert = currentResultSet.FirstOrDefault <AlertItem>();
                if (!Object.Equals(null, alert))
                {
                    logger.LogInformation("Detection was suppressed");
                    return;
                }
            }
            await createAlert(eventItem, type, userId, evidence);
        }
Example #2
0
        public static void sendMailNewAlert(AlertItem alertItem, string userId)
        {
            string subject  = $"Attention! We have just detected an abnormal values in your water system.";
            string mailBody = $"Dear WATERLY user,\n\n" +
                              $"We have just detected an abnormal values in your water system.\n" +
                              $"Issue detected: {alertItem.type}.\n" +
                              $"{alertItem.message}.\n" +
                              $"After finding out, we will be thankful if you could give us feedback " +
                              $"on this alert in the alerts section in your account.\n\n" +
                              $"Thanks!\n" +
                              $"WATERLY team.";
            string reciever = getEmailAddresByUserId(userId).Result;

            Console.WriteLine($"Sending mail - new alert to {reciever}");
            sendMail(subject, mailBody, reciever);
        }
        public static async Task <IActionResult> updateAlert(
            [HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "notifications/{notificationId}")] HttpRequest request, string notificationId,
            ILogger log)

        {
            string alert_id = notificationId;

            string    req_body           = await new StreamReader(request.Body).ReadToEndAsync();
            AlertItem current_alert_data = JsonConvert.DeserializeObject <AlertItem>(req_body);
            Container alerts_container   = Resources.alert_container;

            var option = new FeedOptions {
                EnableCrossPartitionQuery = true
            };

            AlertItem alert_to_update = Resources.docClient.CreateDocumentQuery <AlertItem>(
                UriFactory.CreateDocumentCollectionUri("waterly_db", "alerts_table"), option)
                                        .Where(alert_to_update => alert_to_update.id.Equals(alert_id))
                                        .AsEnumerable()
                                        .First();

            bool   status   = current_alert_data.status;
            string feedback = current_alert_data.feedback;

            if (alert_to_update.status != status)
            {
                alert_to_update.status = status;
            }

            if (alert_to_update.feedback != feedback)
            {
                alert_to_update.feedback = feedback;
            }


            ResourceResponse <Document> response = await Resources.docClient.ReplaceDocumentAsync(
                UriFactory.CreateDocumentUri("waterly_db", "alerts_table", alert_to_update.id),
                alert_to_update);

            var updated = response.Resource;

            return(new OkObjectResult(alert_to_update));
        }
Example #4
0
        public static async Task createAlert(EventItem eventItem, string type, string userId, string evidence)
        {
            logger.LogInformation("Creating alert...");

            var    sqlQueryText = $"SELECT * FROM c WHERE c.id = '{eventItem.device_id}'";
            string device_name  = null;

            QueryDefinition           queryDefinition        = new QueryDefinition(sqlQueryText);
            FeedIterator <DeviceItem> queryResultSetIterator = Resources.devices_container.GetItemQueryIterator <DeviceItem>(queryDefinition);
            FeedResponse <DeviceItem> currentResultSet;

            while (queryResultSetIterator.HasMoreResults)
            {
                currentResultSet = await queryResultSetIterator.ReadNextAsync();

                DeviceItem device = currentResultSet.FirstOrDefault <DeviceItem>();
                device_name = device.name;
            }

            AlertItem alert = new AlertItem
            {
                id          = Guid.NewGuid().ToString(),
                device_id   = eventItem.device_id,
                created_at  = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(),
                type        = type,
                user_id     = userId,
                status      = true,
                evidence    = evidence,
                device_name = device_name,
                message     = "Please contact with your local service center"
            };

            // Create an item in the container representing alert.
            ItemResponse <AlertItem> alertResponse = await Resources.alert_container.CreateItemAsync <AlertItem>(alert);

            // Note that after creating the item, we can access the body of the item with the Resource property off the ItemResponse.
            Console.WriteLine("Created alert in database with id: {0}\n", alertResponse.Resource.id);

            EmailSender.sendMailNewAlert(alert, userId);
        }