Exemplo n.º 1
0
        public void SendCommunication(Guid fromDefinedValue)
        {
            // Get the From value
            var fromValue = DefinedValueCache.Get(fromDefinedValue);


            // Get the recipients
            var recipients = this.GetRecipients();

            // Get the message
            string message = this.Message;

            // Send the message
            if (recipients.Any() && (!string.IsNullOrWhiteSpace(message)))
            {
                var smsMessage = new RockSMSMessage();
                smsMessage.FromNumber = fromValue;
                smsMessage.Message    = $"{( this.AlertNotification.Title != null ? this.AlertNotification.Title + ": " : "" )}{message}";
                smsMessage.CreateCommunicationRecord = true;
                smsMessage.communicationName         = this.AlertNotification?.Title ?? "Alert Notification Message";

                foreach (var person in recipients.ToList())
                {
                    var mergeObject = new Dictionary <string, object> {
                        { "Person", person }
                    };
                    smsMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeObject));
                }

                smsMessage.Send();
            }
        }
Exemplo n.º 2
0
        private void SendNotificationSms(List <TestResult> alarms, List <Person> people)
        {
            var fromNumber = dataMap.GetString("FromNumber").AsGuid();
            var smsMessage = new RockSMSMessage();

            smsMessage.FromNumber = DefinedValueCache.Get(fromNumber);

            var recipients = new List <RockMessageRecipient>();

            smsMessage.Message = "System Monitor Alert:\n";
            foreach (var alarm in alarms)
            {
                smsMessage.Message += alarm.Name + "\n";
            }
            smsMessage.CreateCommunicationRecord = true;
            smsMessage.communicationName         = "System Monitor Alert Notification Message";

            foreach (var person in people)
            {
                var mergeObject = new Dictionary <string, object> {
                    { "Person", person }
                };
                smsMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeObject));
            }

            smsMessage.Send();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Handles the Click event of the btnSend control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSend_Click(object sender, EventArgs e)
        {
            var definedValueGuid = GetAttributeValue(AttributeKey.SMSFrom).AsGuidOrNull();
            var message          = tbSmsMessage.Value.Trim();

            if (message.IsNullOrWhiteSpace() || !definedValueGuid.HasValue)
            {
                ResetSms();
                DisplayResult(NotificationBoxType.Danger, "Error sending message. Please try again or contact an administrator if the error continues.");
                if (!definedValueGuid.HasValue)
                {
                    LogException(new Exception(string.Format("While trying to send an SMS from the Check-in Manager, the following error occurred: There is a misconfiguration with the {0} setting.", AttributeKey.SMSFrom)));
                }

                return;
            }

            var smsFromNumber = DefinedValueCache.Get(definedValueGuid.Value);

            if (smsFromNumber == null)
            {
                ResetSms();
                DisplayResult(NotificationBoxType.Danger, "Could not find a valid phone number to send from.");
                return;
            }

            var rockContext = new RockContext();
            var person      = new PersonService(rockContext).Get(PageParameter(PERSON_GUID_PAGE_QUERY_KEY).AsGuid());
            var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.IsMessagingEnabled);

            if (phoneNumber == null)
            {
                ResetSms();
                DisplayResult(NotificationBoxType.Danger, "Could not find a valid number for this person.");
                return;
            }

            var smsMessage = new RockSMSMessage();

            // NumberFormatted and NumberFormattedWithCountryCode does NOT work (this pattern is repeated in Twilio.cs)
            smsMessage.AddRecipient(new RecipientData("+" + phoneNumber.CountryCode + phoneNumber.Number));
            smsMessage.FromNumber = smsFromNumber;
            smsMessage.Message    = tbSmsMessage.Value;
            var errorMessages = new List <string>();

            smsMessage.Send(out errorMessages);

            if (errorMessages.Any())
            {
                DisplayResult(NotificationBoxType.Danger, "Error sending message. Please try again or contact an administrator if the error continues.");
                LogException(new Exception(string.Format("While trying to send an SMS from the Check-in Manager, the following error(s) occurred: {0}", string.Join("; ", errorMessages))));
                return;
            }

            DisplayResult(NotificationBoxType.Success, "Message sent.");
            ResetSms();
        }
        protected void btnLookup_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            var ipLimit         = GetAttributeValue(AttributeKey.IpThrottleLimit).AsInteger();
            var messageTemplate = GetAttributeValue(AttributeKey.TextMessageTemplate);
            var fromNumber      = GetAttributeValue(AttributeKey.SmsNumber);
            var phoneNumber     = pbPhoneNumberLookup.Number;

            try
            {
                using (var rockContext = new RockContext())
                {
                    var identityVerificationService = new IdentityVerificationService(rockContext);

                    var identityVerification = identityVerificationService.CreateIdentityVerificationRecord(Request.UserHostAddress, ipLimit, phoneNumber);

                    var smsMessage = new RockSMSMessage
                    {
                        FromNumber = DefinedValueCache.Get(fromNumber),
                        Message    = messageTemplate,
                    };
                    var mergeObjects = LavaHelper.GetCommonMergeFields(this.RockPage);
                    mergeObjects.Add("ConfirmationCode", identityVerification.IdentityVerificationCode.Code);

                    smsMessage.SetRecipients(new List <RockSMSMessageRecipient> {
                        RockSMSMessageRecipient.CreateAnonymous(phoneNumber, mergeObjects)
                    });

                    var errorList = new List <string>();
                    if (smsMessage.Send(out errorList))
                    {
                        IdentityVerificationId = identityVerification.Id;
                        ShowVerificationPage();
                    }
                    else
                    {
                        ShowWarningMessage("Verification text message failed to send.");
                    }
                }
            }
            catch (Exception ex)
            {
                ShowWarningMessage(ex.Message);
                RockLogger.Log.Error(RockLogDomains.Core, ex);
                ExceptionLogService.LogException(ex);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Sends the SMS message so the user can be logged in
        /// </summary>
        /// <param name="smsMessage"></param>
        /// <param name="phoneNumber"></param>
        /// <param name="ipAddress"></param>
        /// <param name="delay"></param>
        public async void SendSMS(RockSMSMessage smsMessage, string phoneNumber, string ipAddress, double delay)
        {
            await Task.Delay(( int )delay);

            try
            {
                smsMessage.Send();
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex);
            }
            SMSRecords.ReleaseItems(ipAddress, phoneNumber);
        }
Exemplo n.º 6
0
        public async void SendSMS(RockSMSMessage smsMessage, string phoneNumber, string ipAddress, double delay)
        {
            await Task.Delay(( int )delay);

            try
            {
                smsMessage.Send();
            }
            catch
            {
                //Nom Nom Nom
            }
            SMSRecords.ReleaseItems(ipAddress, phoneNumber);
        }
Exemplo n.º 7
0
        public override void Send(Dictionary <string, string> mediumData, List <string> recipients, string appRoot, string themeRoot)
        {
            var message = new RockSMSMessage();

            message.FromNumber = DefinedValueCache.Get((mediumData.GetValueOrNull("FromValue") ?? string.Empty).AsInteger());
            message.SetRecipients(recipients);
            message.ThemeRoot = themeRoot;
            message.AppRoot   = appRoot;

            var errorMessages  = new List <string>();
            int mediumEntityId = EntityTypeCache.Get(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS.AsGuid())?.Id ?? 0;

            Send(message, mediumEntityId, null, out errorMessages);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Sends an RSVP reminder email to an individual attendee.
        /// </summary>
        /// <param name="person">The <see cref="Person"/>.</param>
        /// <param name="reminder">The <see cref="SystemCommunication"/> to be sent as a reminder.</param>
        /// <param name="lavaMergeFields">A dictionary containing Lava merge fields.</param>
        /// <param name="smsNumber">The correctly formatted SMS Number for SMS communications.</param>
        /// <returns>1 if the communication was successfully sent, otherwise 0.</returns>
        private int SendReminderSMS(Person person, SystemCommunication reminder, Dictionary <string, object> lavaMergeFields, string smsNumber)
        {
            var recipient = new RockSMSMessageRecipient(person, smsNumber, lavaMergeFields);
            var message   = new RockSMSMessage(reminder);

            message.SetRecipients(new List <RockSMSMessageRecipient>()
            {
                recipient
            });
            message.Send(out List <string> smsErrors);

            if (!smsErrors.Any())
            {
                return(1); // No error, this should be counted as a sent reminder.
            }

            return(0);
        }
Exemplo n.º 9
0
        public override void Send(List <string> recipients, string from, string subject, string body, string appRoot = null, string themeRoot = null)
        {
            var message = new RockSMSMessage();

            message.FromNumber = DefinedValueCache.Get(from.AsInteger());
            if (message.FromNumber == null)
            {
                message.FromNumber = DefinedTypeCache.Get(SystemGuid.DefinedType.COMMUNICATION_SMS_FROM.AsGuid())
                                     .DefinedValues
                                     .Where(v => v.Value == from)
                                     .FirstOrDefault();
            }
            message.SetRecipients(recipients);
            message.ThemeRoot = themeRoot;
            message.AppRoot   = appRoot;

            var errorMessages  = new List <string>();
            int mediumEntityId = EntityTypeCache.Get(SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS.AsGuid())?.Id ?? 0;

            Send(message, mediumEntityId, null, out errorMessages);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Handles the ItemCommand event of the rptrReceiptOptions control.
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="e">The <see cref="RepeaterCommandEventArgs"/> instance containing the event data.</param>
        protected void rptrReceiptOptions_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var destination = e.CommandArgument.ToStringSafe();
            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson);

            mergeFields.AddOrReplace("Person", Customer);
            mergeFields.AddOrReplace("Cart", Cart);

            if (destination.StartsWith("email:"))
            {
                var emailMessage = new RockEmailMessage(GetAttributeValue("ReceiptEmail").AsGuid())
                {
                    AppRoot = GlobalAttributesCache.Get().GetValue("InternalApplicationRoot"),
                    CreateCommunicationRecord = false
                };

                emailMessage.AddRecipient(new RecipientData(destination.Substring(6), mergeFields));

                emailMessage.Send();
            }
            else if (destination.StartsWith("sms:"))
            {
                var smsMessage = new RockSMSMessage
                {
                    FromNumber = DefinedValueCache.Get(GetAttributeValue("ReceiptSMSNumber").AsGuid()),
                    Message    = GetAttributeValue("SMSReceiptTemplate"),
                    AppRoot    = GlobalAttributesCache.Get().GetValue("InternalApplicationRoot")
                };

                smsMessage.AddRecipient(new RecipientData(destination.Substring(4), mergeFields));

                List <string> errorMessages;
                bool          result = smsMessage.Send(out errorMessages);
            }

            ResetTerminal();
        }
Exemplo n.º 11
0
        private async Task <SendMessageResult> SendToRecipientAsync(RockMessageRecipient recipient, Dictionary <string, object> mergeFields, RockSMSMessage smsMessage, List <Uri> attachmentMediaUrls, int mediumEntityTypeId, Dictionary <string, string> mediumAttributes)
        {
            var sendMessageResult = new SendMessageResult();

            try
            {
                foreach (var mergeField in mergeFields)
                {
                    recipient.MergeFields.AddOrIgnore(mergeField.Key, mergeField.Value);
                }

                CommunicationRecipient communicationRecipient = null;

                using (var rockContext = new RockContext())
                {
                    CommunicationRecipientService communicationRecipientService = new CommunicationRecipientService(rockContext);
                    int?recipientId = recipient.CommunicationRecipientId;
                    if (recipientId != null)
                    {
                        communicationRecipient = communicationRecipientService.Get(recipientId.Value);
                    }

                    string message         = ResolveText(smsMessage.Message, smsMessage.CurrentPerson, communicationRecipient, smsMessage.EnabledLavaCommands, recipient.MergeFields, smsMessage.AppRoot, smsMessage.ThemeRoot);
                    Person recipientPerson = ( Person )recipient.MergeFields.GetValueOrNull("Person");

                    // Create the communication record and send using that if we have a person since a communication record requires a valid person. Otherwise just send without creating a communication record.
                    if (smsMessage.CreateCommunicationRecord && recipientPerson != null)
                    {
                        var communicationService = new CommunicationService(rockContext);

                        var createSMSCommunicationArgs = new CommunicationService.CreateSMSCommunicationArgs
                        {
                            FromPerson            = smsMessage.CurrentPerson,
                            ToPersonAliasId       = recipientPerson?.PrimaryAliasId,
                            Message               = message,
                            FromPhone             = smsMessage.FromNumber,
                            CommunicationName     = smsMessage.CommunicationName,
                            ResponseCode          = string.Empty,
                            SystemCommunicationId = smsMessage.SystemCommunicationId
                        };

                        Rock.Model.Communication communication = communicationService.CreateSMSCommunication(createSMSCommunicationArgs);

                        if (smsMessage?.CurrentPerson != null)
                        {
                            communication.CreatedByPersonAliasId  = smsMessage.CurrentPerson.PrimaryAliasId;
                            communication.ModifiedByPersonAliasId = smsMessage.CurrentPerson.PrimaryAliasId;
                        }

                        // Since we just created a new communication record, we need to move any attachments from the rockMessage
                        // to the communication's attachments since the Send method below will be handling the delivery.
                        if (attachmentMediaUrls.Any())
                        {
                            foreach (var attachment in smsMessage.Attachments.AsQueryable())
                            {
                                communication.AddAttachment(new CommunicationAttachment {
                                    BinaryFileId = attachment.Id
                                }, CommunicationType.SMS);
                            }
                        }

                        rockContext.SaveChanges();
                        await SendAsync(communication, mediumEntityTypeId, mediumAttributes).ConfigureAwait(false);

                        communication.SendDateTime = RockDateTime.Now;
                        rockContext.SaveChanges();
                        sendMessageResult.MessagesSent += 1;
                    }
                    else
                    {
                        MessageResource response = await SendToTwilioAsync(smsMessage.FromNumber.Value, null, attachmentMediaUrls, message, recipient.To).ConfigureAwait(false);

                        if (response.ErrorMessage.IsNotNullOrWhiteSpace())
                        {
                            sendMessageResult.Errors.Add(response.ErrorMessage);
                        }
                        else
                        {
                            sendMessageResult.MessagesSent += 1;
                        }

                        if (communicationRecipient != null)
                        {
                            rockContext.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                sendMessageResult.Errors.Add(ex.Message);
                ExceptionLogService.LogException(ex);
            }

            return(sendMessageResult);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);

            // Get the From value
            int? fromId   = null;
            Guid?fromGuid = GetAttributeValue(action, "From").AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var fromValue = DefinedValueCache.Read(fromGuid.Value, rockContext);
                if (fromValue != null)
                {
                    fromId = fromValue.Id;
                }
            }

            // Get the recipients
            var    recipients = new List <RecipientData>();
            string toValue    = GetAttributeValue(action, "To");
            Guid   guid       = toValue.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read(guid, rockContext);
                if (attribute != null)
                {
                    string toAttributeValue = action.GetWorklowAttributeValue(guid);
                    if (!string.IsNullOrWhiteSpace(toAttributeValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        {
                            recipients.Add(new RecipientData(toAttributeValue, mergeFields));
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var phoneNumber = new PersonAliasService(rockContext).Queryable()
                                                  .Where(a => a.Guid.Equals(personAliasGuid))
                                                  .SelectMany(a => a.Person.PhoneNumbers)
                                                  .Where(p => p.IsMessagingEnabled)
                                                  .FirstOrDefault();

                                if (phoneNumber == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person or valid SMS phone number not found", true);
                                }
                                else
                                {
                                    string smsNumber = phoneNumber.Number;
                                    if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                    {
                                        smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                    }

                                    var recipient = new RecipientData(smsNumber, mergeFields);
                                    recipients.Add(recipient);

                                    var person = new PersonAliasService(rockContext).GetPerson(personAliasGuid);
                                    if (person != null)
                                    {
                                        recipient.MergeFields.Add("Person", person);
                                    }
                                }
                            }
                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toAttributeValue.AsIntegerOrNull();
                            Guid?groupGuid = toAttributeValue.AsGuidOrNull();
                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }

                            // Handle situations where the attribute value stored is the Guid
                            else if (groupGuid.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    var phoneNumber = person.PhoneNumbers
                                                      .Where(p => p.IsMessagingEnabled)
                                                      .FirstOrDefault();
                                    if (phoneNumber != null)
                                    {
                                        string smsNumber = phoneNumber.Number;
                                        if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                        {
                                            smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                        }

                                        var recipientMergeFields = new Dictionary <string, object>(mergeFields);
                                        var recipient            = new RecipientData(smsNumber, recipientMergeFields);
                                        recipients.Add(recipient);
                                        recipient.MergeFields.Add("Person", person);
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toValue))
                {
                    recipients.Add(new RecipientData(toValue.ResolveMergeFields(mergeFields), mergeFields));
                }
            }

            // Get the message
            string message     = GetAttributeValue(action, "Message");
            Guid?  messageGuid = message.AsGuidOrNull();

            if (messageGuid.HasValue)
            {
                var attribute = AttributeCache.Read(messageGuid.Value, rockContext);
                if (attribute != null)
                {
                    string messageAttributeValue = action.GetWorklowAttributeValue(messageGuid.Value);
                    if (!string.IsNullOrWhiteSpace(messageAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType" ||
                            attribute.FieldType.Class == "Rock.Field.Types.MemoFieldType")
                        {
                            message = messageAttributeValue;
                        }
                    }
                }
            }

            // Add the attachment (if one was specified)
            var binaryFile = new BinaryFileService(rockContext).Get(GetAttributeValue(action, "Attachment", true).AsGuid());

            // Send the message
            if (recipients.Any() && !string.IsNullOrWhiteSpace(message))
            {
                var smsMessage = new RockSMSMessage();
                smsMessage.SetRecipients(recipients);
                smsMessage.FromNumber = DefinedValueCache.Read(fromId.Value);
                smsMessage.Message    = message;
                if (binaryFile != null)
                {
                    smsMessage.Attachments.Add(binaryFile);
                }

                smsMessage.Send();
            }

            return(true);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);
            // Get the From value. Can be in the form of Text, Phone Number, Person or Defined type
            string fromValue = string.Empty;
            int?   fromId    = null;

            fromValue = GetAttributeValue(action, "From", true);


            if (!string.IsNullOrWhiteSpace(fromValue))
            {
                Guid?fromGuid = fromValue.AsGuidOrNull();

                DefinedTypeCache smsPhoneNumbers = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.COMMUNICATION_SMS_FROM);

                // If fromGuid is null but fromValue is not, then this is a phone number (match it up with the value from the DefinedType)
                if (fromGuid == null)
                {
                    try
                    {
                        fromValue = PhoneNumber.CleanNumber(fromValue);
                        fromGuid  = smsPhoneNumbers.DefinedValues.Where(dv => dv.Value.Right(10) == fromValue.Right(10)).Select(dv => dv.Guid).FirstOrDefault();
                        if (fromGuid == Guid.Empty)
                        {
                            action.AddLogEntry("Invalid sending number: Person or valid SMS phone number not found", true);
                        }
                    }
                    catch (Exception e)
                    {
                        action.AddLogEntry("Invalid sending number: Person or valid SMS phone number not found", true);
                    }
                }

                // At this point, fromGuid should either be a Person or a DefinedValue

                if (fromGuid.HasValue)
                {
                    fromId = smsPhoneNumbers.DefinedValues.Where(dv => dv.Guid == fromGuid || dv.GetAttributeValue("ResponseRecipient") == fromGuid.ToString()).Select(dv => dv.Id).FirstOrDefault();
                }
            }

            else
            {
                // The From number is required and was not entered
                action.AddLogEntry("Invalid sending number: Person or valid SMS phone number not found", true);
            }

            // Get the recipients, Can be in the form of Text, Phone Number, Person, Group or Security role
            var    recipients = new List <RockSMSMessageRecipient>();
            string toValue    = GetAttributeValue(action, "To");
            Guid   guid       = toValue.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Get(guid, rockContext);
                if (attribute != null)
                {
                    string toAttributeValue = action.GetWorklowAttributeValue(guid);
                    if (!string.IsNullOrWhiteSpace(toAttributeValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        case "Rock.Field.Types.PhoneNumberFieldType":
                        {
                            var smsNumber = toAttributeValue;
                            smsNumber = PhoneNumber.CleanNumber(smsNumber);
                            recipients.Add(RockSMSMessageRecipient.CreateAnonymous(smsNumber, mergeFields));
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var phoneNumber = new PersonAliasService(rockContext).Queryable()
                                                  .Where(a => a.Guid.Equals(personAliasGuid))
                                                  .SelectMany(a => a.Person.PhoneNumbers)
                                                  .Where(p => p.IsMessagingEnabled)
                                                  .FirstOrDefault();

                                if (phoneNumber == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person or valid SMS phone number not found", true);
                                }
                                else
                                {
                                    var person = new PersonAliasService(rockContext).GetPerson(personAliasGuid);

                                    var recipient = new RockSMSMessageRecipient(person, phoneNumber.ToSmsNumber(), mergeFields);
                                    recipients.Add(recipient);
                                    recipient.MergeFields.Add(recipient.PersonMergeFieldKey, person);
                                }
                            }
                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toAttributeValue.AsIntegerOrNull();
                            Guid?groupGuid = toAttributeValue.AsGuidOrNull();
                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }

                            // Handle situations where the attribute value stored is the Guid
                            else if (groupGuid.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    var phoneNumber = person.PhoneNumbers
                                                      .Where(p => p.IsMessagingEnabled)
                                                      .FirstOrDefault();
                                    if (phoneNumber != null)
                                    {
                                        var recipientMergeFields = new Dictionary <string, object>(mergeFields);
                                        var recipient            = new RockSMSMessageRecipient(person, phoneNumber.ToSmsNumber(), recipientMergeFields);
                                        recipients.Add(recipient);
                                        recipient.MergeFields.Add(recipient.PersonMergeFieldKey, person);
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toValue))
                {
                    recipients.Add(RockSMSMessageRecipient.CreateAnonymous(toValue.ResolveMergeFields(mergeFields), mergeFields));
                }
            }

            // Get the message from the Message attribute.
            // NOTE: Passing 'true' as the checkWorkflowAttributeValue will also check the workflow AttributeValue
            // which allows us to remove the unneeded code.
            string message = GetAttributeValue(action, "Message", checkWorkflowAttributeValue: true);

            // Add the attachment (if one was specified)
            var        attachmentBinaryFileGuid = GetAttributeValue(action, "Attachment", true).AsGuidOrNull();
            BinaryFile binaryFile = null;

            if (attachmentBinaryFileGuid.HasValue && attachmentBinaryFileGuid != Guid.Empty)
            {
                binaryFile = new BinaryFileService(rockContext).Get(attachmentBinaryFileGuid.Value);
            }

            // Send the message
            if (recipients.Any() && (!string.IsNullOrWhiteSpace(message) || binaryFile != null))
            {
                var smsMessage = new RockSMSMessage();
                smsMessage.SetRecipients(recipients);
                smsMessage.FromNumber = DefinedValueCache.Get(fromId.Value);
                smsMessage.Message    = message;
                smsMessage.CreateCommunicationRecord = GetAttributeValue(action, "SaveCommunicationHistory").AsBoolean();
                smsMessage.communicationName         = action.ActionTypeCache.Name;

                if (binaryFile != null)
                {
                    smsMessage.Attachments.Add(binaryFile);
                }

                smsMessage.Send();
            }
            else
            {
                action.AddLogEntry("Warning: No text or attachment was supplied so nothing was sent.", true);
            }

            return(true);
        }
Exemplo n.º 14
0
        private string GenerateCode(string resource)
        {
            if (resource == null || resource.Length != 10)
            {
                return("Please enter a 10 digit phone number.");
            }

            RockContext        rockContext        = new RockContext();
            PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);
            var numberOwners = phoneNumberService.Queryable()
                               .Where(pn => pn.Number == resource)
                               .Select(pn => pn.Person)
                               .DistinctBy(p => p.Id)
                               .ToList();

            if (numberOwners.Count == 0)
            {
                return("0|We are sorry, we could not find your phone number in our records.");
            }

            if (numberOwners.Count > 1)
            {
                return("2|We are sorry, we dected more than one person with your number in our records.");
            }

            var person = numberOwners.FirstOrDefault();

            UserLoginService userLoginService = new UserLoginService(rockContext);
            var userLogin = userLoginService.Queryable()
                            .Where(u => u.UserName == ("__PHONENUMBER__+1" + resource))
                            .FirstOrDefault();

            if (userLogin == null)
            {
                var entityTypeId = EntityTypeCache.Read("Avalanche.Security.Authentication.PhoneNumber").Id;

                userLogin = new UserLogin()
                {
                    UserName     = "******" + resource,
                    EntityTypeId = entityTypeId,
                };
                userLoginService.Add(userLogin);
            }

            userLogin.PersonId = person.Id;
            userLogin.LastPasswordChangedDateTime = Rock.RockDateTime.Now;
            userLogin.FailedPasswordAttemptWindowStartDateTime = Rock.RockDateTime.Now;
            userLogin.FailedPasswordAttemptCount = 0;
            userLogin.IsConfirmed = true;
            userLogin.Password    = new Random().Next(100000, 999999).ToString();

            rockContext.SaveChanges();

            var workflowName = string.Format("{0} ({1})", person.FullName, resource);
            var atts         = new Dictionary <string, string>
            {
                { "PhoneNumber", resource },
                { "Password", userLogin.Password }
            };

            var recipients = new List <RecipientData>();

            recipients.Add(new RecipientData(resource));

            var smsMessage = new RockSMSMessage();

            smsMessage.SetRecipients(recipients);

            // Get the From value
            Guid?fromGuid = GetAttributeValue("From").AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var fromValue = DefinedValueCache.Read(fromGuid.Value, rockContext);
                if (fromValue != null)
                {
                    smsMessage.FromNumber = DefinedValueCache.Read(fromValue.Id);
                }
            }

            var mergeObjects = new Dictionary <string, object> {
                { "password", userLogin.Password }
            };
            var message = AvalancheUtilities.ProcessLava(GetAttributeValue("Message"), CurrentPerson, mergeObjects: mergeObjects);

            smsMessage.Message = message;
            smsMessage.Send();

            return("1|Success!");
        }
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            var dataMap                 = context.JobDetail.JobDataMap;
            var JobStartDateTime        = RockDateTime.Now;
            var minimumCareTouches      = dataMap.GetIntegerFromString(AttributeKey.MinimumCareTouches);
            var minimumCareTouchesHours = dataMap.GetIntegerFromString(AttributeKey.MinimumCareTouches);
            var followUpDays            = dataMap.GetIntegerFromString(AttributeKey.FollowUpDays);

            using (var rockContext = new RockContext())
            {
                // get the last run date or yesterday
                DateTime?lastStartDateTime = null;

                // get job type id
                int jobId = context.JobDetail.Description.AsInteger();

                // load job
                var job = new ServiceJobService(rockContext)
                          .GetNoTracking(jobId);

                if (job != null && job.Guid != Rock.SystemGuid.ServiceJob.JOB_PULSE.AsGuid())
                {
                    lastStartDateTime = job.LastRunDateTime?.AddSeconds(0.0d - ( double )job.LastRunDurationSeconds);
                }
                var beginDateTime = lastStartDateTime ?? JobStartDateTime.AddDays(-1);
                //beginDateTime = JobStartDateTime.AddDays( -3 );

                var careNeedService       = new CareNeedService(rockContext);
                var assignedPersonService = new AssignedPersonService(rockContext);

                var noteType         = NoteTypeCache.GetByEntity(EntityTypeCache.Get(typeof(CareNeed)).Id, "", "", true).FirstOrDefault();
                var careNeedNotesQry = new NoteService(rockContext)
                                       .GetByNoteTypeId(noteType.Id).AsNoTracking();

                var closedValueId = DefinedValueCache.Get(SystemGuid.DefinedValue.CARE_NEED_STATUS_CLOSED.AsGuid()).Id;
                var followUpValue = DefinedValueCache.Get(SystemGuid.DefinedValue.CARE_NEED_STATUS_FOLLOWUP.AsGuid());
                var openValueId   = DefinedValueCache.Get(SystemGuid.DefinedValue.CARE_NEED_STATUS_OPEN.AsGuid()).Id;

                var careNeeds    = careNeedService.Queryable("PersonAlias,SubmitterPersonAlias").Where(n => n.StatusValueId != closedValueId);
                var careAssigned = assignedPersonService.Queryable().Where(ap => ap.PersonAliasId != null && ap.NeedId != null && ap.CareNeed.StatusValueId != closedValueId).DistinctBy(ap => ap.PersonAliasId);

                var careNeedFollowUp = careNeeds.Where(n => n.StatusValueId == openValueId && n.DateEntered <= DbFunctions.AddDays(RockDateTime.Now, -followUpDays));

                var careNeed24Hrs   = careNeeds.Where(n => n.StatusValueId == openValueId && DbFunctions.DiffHours(n.DateEntered.Value, RockDateTime.Now) >= minimumCareTouchesHours);
                var careNeedFlagged = careNeed24Hrs
                                      .SelectMany(cn => careNeedNotesQry.Where(n => n.EntityId == cn.Id && cn.AssignedPersons.Any(ap => ap.FollowUpWorker.HasValue && ap.FollowUpWorker.Value && ap.PersonAliasId == n.CreatedByPersonAliasId)).DefaultIfEmpty(),
                                                  (cn, n) => new
                {
                    CareNeed = cn,
                    HasFollowUpWorkerNote = n != null,
                    TouchCount            = careNeedNotesQry.Where(note => note.EntityId == cn.Id).Count()
                })
                                      .Where(f => !f.HasFollowUpWorkerNote || f.TouchCount <= minimumCareTouches)
                                      .ToList();

                var followUpSystemCommunicationGuid   = dataMap.GetString(AttributeKey.FollowUpSystemCommunication).AsGuid();
                var careTouchNeededCommunicationGuid  = dataMap.GetString(AttributeKey.CareTouchNeededCommunication).AsGuid();
                var outstandingNeedsCommunicationGuid = dataMap.GetString(AttributeKey.OutstandingNeedsCommunication).AsGuid();
                var followUpSystemCommunication       = new SystemCommunicationService(rockContext).Get(followUpSystemCommunicationGuid);
                var careTouchNeededCommunication      = new SystemCommunicationService(rockContext).Get(careTouchNeededCommunicationGuid);
                var outstandingNeedsCommunication     = new SystemCommunicationService(rockContext).Get(outstandingNeedsCommunicationGuid);

                var detailPage         = PageCache.Get(dataMap.GetString(AttributeKey.CareDetailPage));
                var detailPageRoute    = detailPage.PageRoutes.FirstOrDefault();
                var dashboardPage      = PageCache.Get(dataMap.GetString(AttributeKey.CareDashboardPage));
                var dashboardPageRoute = dashboardPage.PageRoutes.FirstOrDefault();
                Dictionary <string, object> linkedPages = new Dictionary <string, object>();
                linkedPages.Add("CareDetail", detailPageRoute != null ? "/" + detailPageRoute.Route : "/page/" + detailPage.Id);
                linkedPages.Add("CareDashboard", dashboardPageRoute != null ? "/" + dashboardPageRoute.Route : "/page/" + dashboardPage.Id);

                var errors    = new List <string>();
                var errorsSms = new List <string>();

                // Update status to follow up and email follow up messages
                foreach (var careNeed in careNeedFollowUp)
                {
                    careNeed.StatusValueId = followUpValue.Id;
                    careNeed.LoadAttributes();

                    if (!followUpSystemCommunicationGuid.IsEmpty())
                    {
                        var emailMessage = new RockEmailMessage(followUpSystemCommunication);
                        var smsMessage   = new RockSMSMessage(followUpSystemCommunication);

                        foreach (var assignee in careNeed.AssignedPersons.Where(ap => ap.FollowUpWorker.HasValue && ap.FollowUpWorker.Value))
                        {
                            assignee.PersonAlias.Person.LoadAttributes();

                            var smsNumber = assignee.PersonAlias.Person.PhoneNumbers.GetFirstSmsNumber();
                            if (!assignee.PersonAlias.Person.CanReceiveEmail(false) && smsNumber.IsNullOrWhiteSpace())
                            {
                                continue;
                            }
                            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, assignee.PersonAlias.Person);
                            mergeFields.Add("CareNeed", careNeed);
                            mergeFields.Add("LinkedPages", linkedPages);
                            mergeFields.Add("AssignedPerson", assignee);
                            mergeFields.Add("Person", assignee.PersonAlias.Person);

                            var recipients = new List <RockMessageRecipient>();
                            recipients.Add(new RockEmailMessageRecipient(assignee.PersonAlias.Person, mergeFields));

                            var notificationType = assignee.PersonAlias.Person.GetAttributeValue(SystemGuid.PersonAttribute.NOTIFICATION.AsGuid());

                            if (notificationType == null || notificationType == "Email" || notificationType == "Both")
                            {
                                if (!assignee.PersonAlias.Person.CanReceiveEmail(false))
                                {
                                    errorCount += 1;
                                    errorMessages.Add(string.Format("{0} does not have a valid email address.", assignee.PersonAlias.Person.FullName));
                                }
                                else
                                {
                                    emailMessage.AddRecipient(new RockEmailMessageRecipient(assignee.PersonAlias.Person, mergeFields));
                                }
                            }
                            if (notificationType == "SMS" || notificationType == "Both")
                            {
                                if (string.IsNullOrWhiteSpace(smsNumber))
                                {
                                    errorCount += 1;
                                    errorMessages.Add(string.Format("No SMS number could be found for {0}.", assignee.PersonAlias.Person.FullName));
                                }
                                smsMessage.AddRecipient(new RockSMSMessageRecipient(assignee.PersonAlias.Person, smsNumber, mergeFields));
                            }
                            //pushMessage.AddRecipient( new RockPushMessageRecipient( assignee.PersonAlias.Person, assignee.PersonAlias.Person.Devices, mergeFields ) );
                        }

                        if (emailMessage.GetRecipients().Count > 0)
                        {
                            emailMessage.Send(out errors);
                        }
                        if (smsMessage.GetRecipients().Count > 0)
                        {
                            smsMessage.Send(out errorsSms);
                        }

                        if (errors.Any())
                        {
                            errorCount += errors.Count;
                            errorMessages.AddRange(errors);
                        }
                        else
                        {
                            assignedPersonEmails++;
                        }
                        if (errorsSms.Any())
                        {
                            errorCount += errorsSms.Count;
                            errorMessages.AddRange(errorsSms);
                        }
                        else
                        {
                            assignedPersonSms++;
                        }
                    }
                }
                rockContext.SaveChanges();

                // Send notification about "Flagged" messages (any messages without a care touch by the follow up worker or minimum care touches within the set minimum Care Touches Hours.
                if (careTouchNeededCommunication != null && careTouchNeededCommunication.Id > 0)
                {
                    foreach (var flagNeed in careNeedFlagged)
                    {
                        var careNeed = flagNeed.CareNeed;
                        careNeed.LoadAttributes();
                        var emailMessage = new RockEmailMessage(careTouchNeededCommunication);
                        var smsMessage   = new RockSMSMessage(careTouchNeededCommunication);
                        //var pushMessage = new RockPushMessage( careTouchNeededCommunication );
                        var recipients = new List <RockMessageRecipient>();

                        foreach (var assignee in careNeed.AssignedPersons)
                        {
                            assignee.PersonAlias.Person.LoadAttributes();

                            var smsNumber = assignee.PersonAlias.Person.PhoneNumbers.GetFirstSmsNumber();
                            if (!assignee.PersonAlias.Person.CanReceiveEmail(false) && smsNumber.IsNullOrWhiteSpace())
                            {
                                continue;
                            }

                            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, assignee.PersonAlias.Person);
                            mergeFields.Add("CareNeed", careNeed);
                            mergeFields.Add("LinkedPages", linkedPages);
                            mergeFields.Add("AssignedPerson", assignee);
                            mergeFields.Add("Person", assignee.PersonAlias.Person);
                            mergeFields.Add("TouchCount", flagNeed.TouchCount);
                            mergeFields.Add("HasFollowUpWorkerNote", flagNeed.HasFollowUpWorkerNote);

                            var notificationType = assignee.PersonAlias.Person.GetAttributeValue(SystemGuid.PersonAttribute.NOTIFICATION.AsGuid());

                            if (notificationType == null || notificationType == "Email" || notificationType == "Both")
                            {
                                if (!assignee.PersonAlias.Person.CanReceiveEmail(false))
                                {
                                    errorCount += 1;
                                    errorMessages.Add(string.Format("{0} does not have a valid email address.", assignee.PersonAlias.Person.FullName));
                                }
                                else
                                {
                                    emailMessage.AddRecipient(new RockEmailMessageRecipient(assignee.PersonAlias.Person, mergeFields));
                                }
                            }
                            if (notificationType == "SMS" || notificationType == "Both")
                            {
                                if (string.IsNullOrWhiteSpace(smsNumber))
                                {
                                    errorCount += 1;
                                    errorMessages.Add(string.Format("No SMS number could be found for {0}.", assignee.PersonAlias.Person.FullName));
                                }
                                smsMessage.AddRecipient(new RockSMSMessageRecipient(assignee.PersonAlias.Person, smsNumber, mergeFields));
                            }
                            //pushMessage.AddRecipient( new RockPushMessageRecipient( assignee.PersonAlias.Person, assignee.PersonAlias.Person.Devices, mergeFields ) );
                        }
                        if (emailMessage.GetRecipients().Count > 0)
                        {
                            emailMessage.Send(out errors);
                        }
                        if (smsMessage.GetRecipients().Count > 0)
                        {
                            smsMessage.Send(out errorsSms);
                        }

                        if (errors.Any())
                        {
                            errorCount += errors.Count;
                            errorMessages.AddRange(errors);
                        }
                        else
                        {
                            assignedPersonEmails++;
                        }
                        if (errorsSms.Any())
                        {
                            errorCount += errorsSms.Count;
                            errorMessages.AddRange(errorsSms);
                        }
                        else
                        {
                            assignedPersonSms++;
                        }
                    }
                }

                // Send Outstanding needs daily notification
                if (outstandingNeedsCommunication != null && outstandingNeedsCommunication.Id > 0)
                {
                    foreach (var assigned in careAssigned)
                    {
                        var smsNumber = assigned.PersonAlias.Person.PhoneNumbers.GetFirstSmsNumber();

                        if (!assigned.PersonAlias.Person.CanReceiveEmail(false) && smsNumber.IsNullOrWhiteSpace())
                        {
                            continue;
                        }
                        var emailMessage = new RockEmailMessage(outstandingNeedsCommunication);
                        var smsMessage   = new RockSMSMessage(outstandingNeedsCommunication);
                        //var pushMessage = new RockPushMessage( outstandingNeedsCommunication );
                        var recipients = new List <RockMessageRecipient>();

                        var assignedNeeds = careNeeds.Where(cn => cn.AssignedPersons.Any(ap => ap.PersonAliasId == assigned.PersonAliasId));

                        assigned.PersonAlias.Person.LoadAttributes();

                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, assigned.PersonAlias.Person);
                        mergeFields.Add("CareNeeds", assignedNeeds);
                        mergeFields.Add("LinkedPages", linkedPages);
                        mergeFields.Add("AssignedPerson", assigned);
                        mergeFields.Add("Person", assigned.PersonAlias.Person);

                        var notificationType = assigned.PersonAlias.Person.GetAttributeValue(SystemGuid.PersonAttribute.NOTIFICATION.AsGuid());

                        if (notificationType == null || notificationType == "Email" || notificationType == "Both")
                        {
                            if (!assigned.PersonAlias.Person.CanReceiveEmail(false))
                            {
                                errorCount += 1;
                                errorMessages.Add(string.Format("{0} does not have a valid email address.", assigned.PersonAlias.Person.FullName));
                            }
                            else
                            {
                                emailMessage.AddRecipient(new RockEmailMessageRecipient(assigned.PersonAlias.Person, mergeFields));
                            }
                        }
                        if (notificationType == "SMS" || notificationType == "Both")
                        {
                            if (string.IsNullOrWhiteSpace(smsNumber))
                            {
                                errorCount += 1;
                                errorMessages.Add(string.Format("No SMS number could be found for {0}.", assigned.PersonAlias.Person.FullName));
                            }
                            smsMessage.AddRecipient(new RockSMSMessageRecipient(assigned.PersonAlias.Person, smsNumber, mergeFields));
                        }
                        //pushMessage.AddRecipient( new RockPushMessageRecipient( assignee.PersonAlias.Person, assignee.PersonAlias.Person.Devices, mergeFields ) );

                        if (emailMessage.GetRecipients().Count > 0)
                        {
                            emailMessage.Send(out errors);
                        }
                        if (smsMessage.GetRecipients().Count > 0)
                        {
                            smsMessage.Send(out errorsSms);
                        }

                        if (errors.Any())
                        {
                            errorCount += errors.Count;
                            errorMessages.AddRange(errors);
                        }
                        else
                        {
                            assignedPersonEmails++;
                        }
                        if (errorsSms.Any())
                        {
                            errorCount += errorsSms.Count;
                            errorMessages.AddRange(errorsSms);
                        }
                        else
                        {
                            assignedPersonSms++;
                        }
                    }
                }
            }
            context.Result = string.Format("{0} emails sent \n{1} SMS messages sent", assignedPersonEmails, assignedPersonSms);
            if (errorMessages.Any())
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.Append(string.Format("{0} Errors: ", errorCount));
                errorMessages.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                string errors = sb.ToString();
                context.Result += errors;
                var         exception = new Exception(errors);
                HttpContext context2  = HttpContext.Current;
                ExceptionLogService.LogException(exception, context2);
                throw exception;
            }
        }
Exemplo n.º 16
0
        protected void btnGenerate_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            pnlPhoneNumber.Visible = false;
            RockContext        rockContext        = new RockContext();
            PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);
            var numberOwners = phoneNumberService.Queryable()
                               .Where(pn => pn.Number == PhoneNumber)
                               .Select(pn => pn.Person)
                               .DistinctBy(p => p.Id)
                               .ToList();

            if (numberOwners.Count == 0)
            {
                lbNoNumber.Text     = GetAttributeValue("NoNumberMessage");
                pnlNoNumber.Visible = true;
                return;
            }

            if (numberOwners.Count > 1)
            {
                if (GetAttributeValue("DuplicateNumberPage").AsGuidOrNull() == null)
                {
                    btnResolution.Visible = false;
                }
                lbDuplicateNumber.Text     = GetAttributeValue("DuplicateMessage");
                pnlDuplicateNumber.Visible = true;
                return;
            }

            var person = numberOwners.FirstOrDefault();

            UserLoginService userLoginService = new UserLoginService(rockContext);
            var userLogin = userLoginService.Queryable()
                            .Where(u => u.UserName == ("__PHONENUMBER__" + PhoneNumber))
                            .FirstOrDefault();

            if (userLogin == null)
            {
                var entityTypeId = EntityTypeCache.Read("Avalanche.Security.Authentication.PhoneNumber").Id;

                userLogin = new UserLogin()
                {
                    UserName     = "******" + PhoneNumber,
                    EntityTypeId = entityTypeId,
                };
                userLoginService.Add(userLogin);
            }

            userLogin.PersonId = person.Id;
            userLogin.LastPasswordChangedDateTime = Rock.RockDateTime.Now;
            userLogin.FailedPasswordAttemptWindowStartDateTime = Rock.RockDateTime.Now;
            userLogin.FailedPasswordAttemptCount = 0;
            userLogin.IsConfirmed = true;
            userLogin.Password    = new Random().Next(100000, 999999).ToString();

            rockContext.SaveChanges();

            var recipients = new List <RecipientData>();

            recipients.Add(new RecipientData(PhoneNumber));

            var smsMessage = new RockSMSMessage();

            smsMessage.SetRecipients(recipients);

            // Get the From value
            Guid?fromGuid = GetAttributeValue("From").AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var fromValue = DefinedValueCache.Read(fromGuid.Value, rockContext);
                if (fromValue != null)
                {
                    smsMessage.FromNumber = DefinedValueCache.Read(fromValue.Id);
                }
            }

            var mergeObjects = new Dictionary <string, object> {
                { "password", userLogin.Password }
            };
            var message = GetAttributeValue("Message").ResolveMergeFields(mergeObjects, null);

            smsMessage.Message = message;

            var ipAddress = GetIpAddress();

            if (SMSRecords.ReserveItems(ipAddress, PhoneNumber))
            {
                pnlCode.Visible = true;
                var delay = SMSRecords.GetDelay(ipAddress, PhoneNumber);
                Task.Run(() => { SendSMS(smsMessage, ipAddress, PhoneNumber, delay); });
            }
            else
            {
                LogException(new Exception(string.Format("Unable to reserve for SMS message: IP: {0} PhoneNumber: {1}", ipAddress, PhoneNumber)));
                pnlRateLimited.Visible = true;
            }
        }
        /// <summary>
        /// Sends the meeting reminders.
        /// </summary>
        /// <param name="context">The overall job context.</param>
        /// <param name="rockContext">The rockContext.</param>
        /// <param name="occurrenceData">The occurrenceData to process.</param>
        /// <param name="systemCommunication">The system communication.</param>
        /// <param name="jobPreferredCommunicationType">Type of the job preferred communication.</param>
        /// <returns></returns>
        private SendMessageResult SendMeetingReminders(IJobExecutionContext context,
                                                       RockContext rockContext,
                                                       Dictionary <RoomOccurrence, Group> occurrenceData,
                                                       SystemCommunication systemCommunication,
                                                       CommunicationType jobPreferredCommunicationType,
                                                       bool isSmsEnabled,
                                                       bool isPushEnabled)
        {
            var result      = new SendMessageResult();
            var errorsEmail = new List <string>();
            var errorsSms   = new List <string>();
            var errorsPush  = new List <string>();

            // Loop through the room occurrence data
            foreach (var occurrence in occurrenceData)
            {
                var             emailMessage = new RockEmailMessage(systemCommunication);
                RockSMSMessage  smsMessage   = isSmsEnabled ? new RockSMSMessage(systemCommunication) : null;
                RockPushMessage pushMessage  = isPushEnabled ? new RockPushMessage(systemCommunication) : null;
                var             group        = occurrence.Value;
                foreach (var groupMember in group.ActiveMembers().ToList())
                {
                    groupMember.Person.LoadAttributes();
                    var           smsNumber   = groupMember.Person.PhoneNumbers.GetFirstSmsNumber();
                    var           personAlias = new PersonAliasService(rockContext).Get(groupMember.Person.PrimaryAliasId.Value);
                    List <string> pushDevices = new PersonalDeviceService(rockContext).Queryable()
                                                .Where(a => a.PersonAliasId.HasValue && a.PersonAliasId == personAlias.Id && a.NotificationsEnabled)
                                                .Select(a => a.DeviceRegistrationId)
                                                .ToList();
                    if (!groupMember.Person.CanReceiveEmail(false) && smsNumber.IsNullOrWhiteSpace() && pushDevices.Count == 0)
                    {
                        continue;
                    }
                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, groupMember.Person);
                    mergeFields.Add("Group", group);
                    mergeFields.Add("Occurrence", occurrence.Key);
                    mergeFields.Add("Person", groupMember.Person);

                    var notificationType = ( CommunicationType )Communication.DetermineMediumEntityTypeId(
                        ( int )CommunicationType.Email,
                        ( int )CommunicationType.SMS,
                        ( int )CommunicationType.PushNotification,
                        jobPreferredCommunicationType,
                        groupMember.CommunicationPreference,
                        groupMember.Person.CommunicationPreference);

                    switch (notificationType)
                    {
                    case CommunicationType.Email:
                        if (!groupMember.Person.CanReceiveEmail(false))
                        {
                            errorCount += 1;
                            errorMessages.Add(string.Format("{0} does not have a valid email address.", groupMember.Person.FullName));
                        }
                        else
                        {
                            emailMessage.AddRecipient(new RockEmailMessageRecipient(groupMember.Person, mergeFields));
                        }
                        break;

                    case CommunicationType.SMS:
                        if (string.IsNullOrWhiteSpace(smsNumber) || smsMessage == null)
                        {
                            errorCount += 1;
                            errorMessages.Add(string.Format("No SMS number could be found for {0}.", groupMember.Person.FullName));
                            goto case CommunicationType.Email;
                        }
                        else
                        {
                            smsMessage.AddRecipient(new RockSMSMessageRecipient(groupMember.Person, smsNumber, mergeFields));
                        }
                        break;

                    case CommunicationType.PushNotification:
                        if (pushDevices.Count == 0 || pushMessage == null)
                        {
                            errorCount += 1;
                            errorMessages.Add(string.Format("No devices that support notifications could be found for {0}.", groupMember.Person.FullName));
                            goto case CommunicationType.Email;
                        }
                        else
                        {
                            string deviceIds = String.Join(",", pushDevices);
                            pushMessage.AddRecipient(new RockPushMessageRecipient(groupMember.Person, deviceIds, mergeFields));
                        }
                        break;

                    default:
                        break;
                    }
                }

                if (emailMessage.GetRecipients().Count > 0)
                {
                    emailMessage.Send(out errorsEmail);
                    if (errorsEmail.Any())
                    {
                        result.Errors.AddRange(errorsEmail);
                    }
                    else
                    {
                        notificationEmails++;
                    }
                }
                if (smsMessage != null && smsMessage.GetRecipients().Count > 0)
                {
                    smsMessage.Send(out errorsSms);
                    if (errorsSms.Any())
                    {
                        result.Errors.AddRange(errorsSms);
                    }
                    else
                    {
                        notificationSms++;
                    }
                }
                if (pushMessage != null && pushMessage.GetRecipients().Count > 0)
                {
                    pushMessage.Send(out errorsPush);
                    if (errorsPush.Any())
                    {
                        result.Errors.AddRange(errorsPush);
                    }
                    else
                    {
                        notificationPush++;
                    }
                }
            }
            if (errorMessages.Any())
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.Append(string.Format("{0} Errors: ", errorCount));
                errorMessages.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                string errors = sb.ToString();
                context.Result += errors;
                var         exception = new Exception(errors);
                HttpContext context2  = HttpContext.Current;
                ExceptionLogService.LogException(exception, context2);
                throw exception;
            }

            return(result);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);

            // Get the From value
            int? fromId   = null;
            Guid?fromGuid = GetAttributeValue(action, AttributeKey.FromFromDropDown).AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var fromValue = DefinedValueCache.Get(fromGuid.Value, rockContext);
                if (fromValue != null)
                {
                    fromId = fromValue.Id;
                }
            }

            if (!fromId.HasValue)
            {
                Guid fromGuidFromAttribute = GetAttributeValue(action, AttributeKey.FromFromAttribute).AsGuid();

                fromGuid = action.GetWorkflowAttributeValue(fromGuidFromAttribute).AsGuidOrNull();

                var fromValue = DefinedValueCache.Get(fromGuid.Value, rockContext);
                if (fromValue != null)
                {
                    fromId = fromValue.Id;
                }
            }

            var smsFromDefinedValues = DefinedTypeCache.Get(SystemGuid.DefinedType.COMMUNICATION_SMS_FROM.AsGuid()).DefinedValues;

            // Now can we do our final check to ensure the guid is a valid SMS From Defined Value
            if (!fromId.HasValue || !smsFromDefinedValues.Any(a => a.Id == fromId))
            {
                var msg = string.Format($"'From' could not be found for selected value ('{fromGuid}')");
                errorMessages.Add(msg);
                action.AddLogEntry(msg, true);
                return(false);
            }

            // Get the recipients
            var    recipients = new List <RockSMSMessageRecipient>();
            string toValue    = GetAttributeValue(action, "To");
            Guid   guid       = toValue.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Get(guid, rockContext);
                if (attribute != null)
                {
                    string toAttributeValue = action.GetWorkflowAttributeValue(guid);
                    if (!string.IsNullOrWhiteSpace(toAttributeValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        {
                            var smsNumber = toAttributeValue;
                            recipients.Add(RockSMSMessageRecipient.CreateAnonymous(smsNumber, mergeFields));
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var phoneNumber = new PersonAliasService(rockContext).Queryable()
                                                  .Where(a => a.Guid.Equals(personAliasGuid))
                                                  .SelectMany(a => a.Person.PhoneNumbers)
                                                  .Where(p => p.IsMessagingEnabled)
                                                  .FirstOrDefault();

                                if (phoneNumber == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person or valid SMS phone number not found", true);
                                }
                                else
                                {
                                    var person = new PersonAliasService(rockContext).GetPerson(personAliasGuid);

                                    var recipient = new RockSMSMessageRecipient(person, phoneNumber.ToSmsNumber(), mergeFields);
                                    recipients.Add(recipient);
                                    recipient.MergeFields.Add(recipient.PersonMergeFieldKey, person);
                                }
                            }

                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toAttributeValue.AsIntegerOrNull();
                            Guid?groupGuid = toAttributeValue.AsGuidOrNull();
                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }
                            else if (groupGuid.HasValue)
                            {
                                // Handle situations where the attribute value stored is the Guid
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    var phoneNumber = person.PhoneNumbers
                                                      .Where(p => p.IsMessagingEnabled)
                                                      .FirstOrDefault();
                                    if (phoneNumber != null)
                                    {
                                        var recipientMergeFields = new Dictionary <string, object>(mergeFields);
                                        var recipient            = new RockSMSMessageRecipient(person, phoneNumber.ToSmsNumber(), recipientMergeFields);
                                        recipients.Add(recipient);
                                        recipient.MergeFields.Add(recipient.PersonMergeFieldKey, person);
                                    }
                                }
                            }

                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toValue))
                {
                    recipients.Add(RockSMSMessageRecipient.CreateAnonymous(toValue.ResolveMergeFields(mergeFields), mergeFields));
                }
            }

            // Get the message from the Message attribute.
            // NOTE: Passing 'true' as the checkWorkflowAttributeValue will also check the workflow AttributeValue
            // which allows us to remove the unneeded code.
            string message = GetAttributeValue(action, "Message", checkWorkflowAttributeValue: true);

            // Add the attachment (if one was specified)
            var        attachmentBinaryFileGuid = GetAttributeValue(action, "Attachment", true).AsGuidOrNull();
            BinaryFile binaryFile = null;

            if (attachmentBinaryFileGuid.HasValue && attachmentBinaryFileGuid != Guid.Empty)
            {
                binaryFile = new BinaryFileService(rockContext).Get(attachmentBinaryFileGuid.Value);
            }

            // Send the message
            if (recipients.Any() && (!string.IsNullOrWhiteSpace(message) || binaryFile != null))
            {
                var smsMessage = new RockSMSMessage();
                smsMessage.SetRecipients(recipients);
                smsMessage.FromNumber = DefinedValueCache.Get(fromId.Value);
                smsMessage.Message    = message;
                smsMessage.CreateCommunicationRecord = GetAttributeValue(action, "SaveCommunicationHistory").AsBoolean();
                smsMessage.CommunicationName         = action.ActionTypeCache.Name;

                if (binaryFile != null)
                {
                    smsMessage.Attachments.Add(binaryFile);
                }

                smsMessage.Send();
            }
            else
            {
                action.AddLogEntry("Warning: No text or attachment was supplied so nothing was sent.", true);
            }

            return(true);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Creates the user login for the SMS message and send the text message with the code
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public bool SendSMSAuthentication(string phoneNumber)
        {
            RockContext rockContext = new RockContext();

            string error;
            var    person = GetNumberOwner(phoneNumber, rockContext, out error);

            if (person == null)
            {
                return(false);
            }

            UserLoginService userLoginService = new UserLoginService(rockContext);
            var userLogin = userLoginService.Queryable()
                            .Where(u => u.UserName == ("SMS_" + person.Id.ToString()))
                            .FirstOrDefault();

            //Create user login if does not exist
            if (userLogin == null)
            {
                var entityTypeId = EntityTypeCache.Get("Rock.Security.ExternalAuthentication.SMSAuthentication").Id;

                userLogin = new UserLogin()
                {
                    UserName     = "******" + person.Id.ToString(),
                    EntityTypeId = entityTypeId,
                };
                userLoginService.Add(userLogin);
            }

            //Update user login
            userLogin.PersonId = person.Id;
            userLogin.LastPasswordChangedDateTime = Rock.RockDateTime.Now;
            userLogin.FailedPasswordAttemptWindowStartDateTime = Rock.RockDateTime.Now;
            userLogin.FailedPasswordAttemptCount = 0;
            userLogin.IsConfirmed = true;
            var password = new Random().Next(100000, 999999).ToString();

            userLogin.Password = EncodeBcrypt(password);
            rockContext.SaveChanges();

            var recipients = new List <RockSMSMessageRecipient>();

            recipients.Add(RockSMSMessageRecipient.CreateAnonymous(phoneNumber, null));

            var smsMessage = new RockSMSMessage
            {
                CreateCommunicationRecord = false
            };

            smsMessage.SetRecipients(recipients);

            // Get the From value
            Guid?fromGuid = GetAttributeValue("From").AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var fromValue = DefinedValueCache.Get(fromGuid.Value, rockContext);
                if (fromValue != null)
                {
                    smsMessage.FromNumber = DefinedValueCache.Get(fromValue.Id, rockContext);
                }
            }

            smsMessage.AdditionalMergeFields = new Dictionary <string, object> {
                { "password", password }
            };

            smsMessage.Message = GetAttributeValue("Message");

            var ipAddress = GetIpAddress();

            //Reserve items rate limits the text messages
            if (SMSRecords.ReserveItems(ipAddress, phoneNumber))
            {
                var delay = SMSRecords.GetDelay(ipAddress, phoneNumber);
                Task.Run(() => { SendSMS(smsMessage, ipAddress, phoneNumber, delay); });
            }
            else
            {
                ExceptionLogService.LogException(new Exception(string.Format("Rate limiting reached for SMS authentication: IP: {0} PhoneNumber: {1}", ipAddress, phoneNumber)));
            }


            return(true);
        }