예제 #1
0
        public async Task DoOperationAsync(RequestTutorMessage message2, IBinder binder, CancellationToken token)
        {
            if (_configuration.Search.IsDevelop)
            //if (bool.Parse(_configuration["IsDevelop"]))
            {
                _email = "*****@*****.**";
            }
            var query  = new RequestTutorAdminEmailQuery(message2.LeadId);
            var result = await _queryBus.QueryAsync(query, token);

            if (result == null)
            {
                return;
            }

            foreach (var obj in result)
            {
                var code           = _dataProtectionService.ProtectData(obj.UserId.ToString(), DateTimeOffset.UtcNow.AddDays(5));
                var identifierChat = ShortId.Generate(true, false);

                var url         = _urlBuilder.BuildChatEndpoint(code, new { utm_source = "request-tutor-admin-email" });
                var commandChat = new CreateShortUrlCommand(identifierChat, url.PathAndQuery, DateTime.UtcNow.AddDays(5));
                await _commandBus.DispatchAsync(commandChat, token);

                var whatsAppLink = new UriBuilder($"https://wa.me/{obj.UserPhone.Replace("+", string.Empty)}")
                                   .AddQuery(new
                {
                    text = $"שובץ לך מורה ל{obj.CourseName} בשם {obj.TutorName}. לשוחח עם המורה לחץ {_urlBuilder.BuildShortUrlEndpoint(identifierChat)}"
                });

                string body = whatsAppLink.ToString();

                var message = new SendGridMessage()
                {
                    Subject     = "New Tutor request",
                    HtmlContent = $"<html><body>{body.Replace(Environment.NewLine, "<br><br>")}</body></html>"
                };

                message.AddTo(_email);
                var emailProvider =
                    await binder.BindAsync <IAsyncCollector <SendGridMessage> >(new SendGridAttribute()
                {
                    ApiKey = "SendgridKey", From = "Spitball <*****@*****.**>"
                }, token);

                await emailProvider.AddAsync(message, token);

                await emailProvider.FlushAsync(token);
            }
        }
예제 #2
0
        public static async Task SmsUnreadAsync([TimerTrigger("0 */10 * * * *")] TimerInfo myTimer,
                                                [Blob("spitball/chat/unread.txt")] CloudBlockBlob blob,
                                                [TwilioSms(AccountSidSetting = "TwilioSid", AuthTokenSetting = "TwilioToken", From = "+1 203-347-4577")] IAsyncCollector <CreateMessageOptions> options,
                                                [SendGrid(ApiKey = "SendgridKey")] IAsyncCollector <SendGridMessage> emailProvider,
                                                [Inject] IQueryBus queryBus,
                                                [Inject] ICommandBus commandBus,
                                                [Inject] IDataProtectionProvider dataProtectProvider,
                                                [Inject] IUrlBuilder urlBuilder,
                                                ILogger log,
                                                CancellationToken token)
        {
            byte[] version = null;
            if (await blob.ExistsAsync())
            {
                version = new byte[8];
                await blob.DownloadToByteArrayAsync(version, 0);
            }

            var query         = new UserUnreadMessageQuery(version);
            var result        = (await queryBus.QueryAsync(query, token)).ToList();
            var dataProtector = dataProtectProvider.CreateProtector("Spitball")
                                .ToTimeLimitedDataProtector();

            foreach (var unreadMessageDto in result.Distinct(UnreadMessageDto.UserIdComparer))
            {
                try
                {
                    if (unreadMessageDto.ChatMessagesCount == 0)
                    {
                        continue;
                    }

                    if (unreadMessageDto.Country is null)
                    {
                        continue;
                    }
                    log.LogInformation($"processing {unreadMessageDto}");
                    CultureInfo.DefaultThreadCurrentCulture = unreadMessageDto.CultureInfo.ChangeCultureBaseOnCountry(unreadMessageDto.Country);

                    var code       = dataProtector.Protect(unreadMessageDto.UserId.ToString(), DateTimeOffset.UtcNow.AddDays(5));
                    var identifier = ShortId.Generate(true, false);
                    var url        = urlBuilder.BuildChatEndpoint(code, new { utm_source = "SMS-auto" });
                    var command    = new CreateShortUrlCommand(identifier, url.PathAndQuery, DateTime.UtcNow.AddDays(5));
                    await commandBus.DispatchAsync(command, token);

                    var urlShort = urlBuilder.BuildShortUrlEndpoint(identifier, unreadMessageDto.Country);


                    if (!unreadMessageDto.Country.Equals(Country.India.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        var text           = GetText(unreadMessageDto.IsTutor, unreadMessageDto.ChatMessagesCount, false);
                        var generatedText  = text.Inject(new { link = urlShort });
                        var messageOptions = new CreateMessageOptions(new PhoneNumber(unreadMessageDto.PhoneNumber))
                        {
                            Body = generatedText
                        };
                        if (unreadMessageDto.PhoneNumber.StartsWith("+972"))
                        {
                            messageOptions.From = "Spitball";
                        }
                        try
                        {
                            await options.AddAsync(messageOptions, token);

                            await options.FlushAsync(token);
                        }
                        catch (Exception ex)
                        {
                            log.LogError(ex, $"Cant send sms to {unreadMessageDto}");
                        }
                    }

                    var htmlBodyDirection = CultureInfo.CurrentCulture.TextInfo.IsRightToLeft ? "rtl" : "ltr";

                    var message = new SendGridMessage();
                    message.AddTo(unreadMessageDto.Email);

                    var body = GetText(unreadMessageDto.IsTutor, unreadMessageDto.ChatMessagesCount, true).Inject(new { link = urlShort });


                    message.AddContent("text/html", $"<html>" +
                                       $"<body dir=\"{htmlBodyDirection}\">{body}</body></html>");
                    message.SetSubject(ResourceWrapper.GetString("you_have_unread_message"));
                    message.AddFromResource(CultureInfo.DefaultThreadCurrentCulture);
                    await emailProvider.AddAsync(message, token);

                    await emailProvider.FlushAsync(token);
                }
                catch (Exception ex)
                {
                    log.LogError(ex, $"Cant send sms/email to {unreadMessageDto}");
                }
            }
            if (result.Count > 0)
            {
                version = result.OrderByDescending(o => o.VersionAsLong).First().Version;
                await blob.UploadFromByteArrayAsync(version, 0, 8);
            }
        }
        public async Task DoOperationAsync(RequestTutorMessage message2, IBinder binder, CancellationToken token)
        {
            var query  = new RequestTutorEmailQuery(message2.LeadId);
            var result = await _queryBus.QueryAsync(query, token);

            foreach (var obj in result)
            {
                CultureInfo.DefaultThreadCurrentCulture = obj.TutorLanguage.ChangeCultureBaseOnCountry(obj.TutorCountry);
                var body = ResourceWrapper.GetString("unread_message_request_email_body");


                var code           = _dataProtectionService.ProtectData(obj.TutorId.ToString(), DateTimeOffset.UtcNow.AddDays(5));
                var identifierChat = ShortId.Generate(true, false);

                var url         = _urlBuilder.BuildChatEndpoint(code, new { utm_source = "request-tutor-email" });
                var commandChat = new CreateShortUrlCommand(identifierChat, url.PathAndQuery, DateTime.UtcNow.AddDays(5));
                await _commandBus.DispatchAsync(commandChat, token);

                var request = string.Empty;
                //TODO -  whatsapp link
                if (!string.IsNullOrEmpty(obj.Request))
                {
                    request = ResourceWrapper.GetString("unread_message_request_email_body_lead_request")
                              .InjectSingleValue("Request", obj.Request);
                }


                var whatsAppLink = new UriBuilder($"https://wa.me/{obj.StudentPhoneNumber.Replace("+", string.Empty)}")
                                   .AddQuery(new
                {
                    text = ResourceWrapper.GetString("unread_message_request_email_body_whatsapp_text").InjectSingleValue("CourseName", obj.CourseName),
                });

                var identifierWhatsApp = ShortId.Generate(true, false);
                var commandWhatsApp    = new CreateShortUrlCommand(identifierWhatsApp, whatsAppLink.ToString(), DateTime.UtcNow.AddDays(30));
                await _commandBus.DispatchAsync(commandWhatsApp, token);

                var urlShortWhatsApp = _urlBuilder.BuildShortUrlEndpoint(identifierWhatsApp, new
                {
                    eventCategory = "After tutor Submit",
                    eventAction   = "Whatsapp email",
                    eventLabel    = $"Tutor{obj.TutorId}, Student {obj.StudentId}"
                });
                body = body.InjectSingleValue("Request", request);

                body = body.InjectSingleValue("WhatsappLink", urlShortWhatsApp);

                var htmlBodyDirection = CultureInfo.CurrentCulture.TextInfo.IsRightToLeft ? "rtl" : "ltr";
                body = body.Inject(new
                {
                    Request       = request,
                    WhatsappLink  = whatsAppLink.ToString(),
                    UserFirstName = obj.TutorFirstName,
                    link          = _urlBuilder.BuildShortUrlEndpoint(identifierChat /*, obj.TutorCountry*/),
                    obj.StudentName,
                    obj.CourseName,
                    FirstMessageStudentName = obj.StudentName
                });
                var message = new SendGridMessage()
                {
                    Subject = ResourceWrapper.GetString("unread_message_request_email_subject").InjectSingleValue("FirstMessageStudentName", obj.StudentName)
                              .Inject(obj),
                    HtmlContent = $"<html><body dir=\"{htmlBodyDirection}\">{body.Replace(Environment.NewLine, "<br><br>")}</body></html>",
                };
                message.AddFromResource(CultureInfo.DefaultThreadCurrentCulture);
                message.AddTo(obj.TutorEmail);
                var emailProvider =
                    await binder.BindAsync <IAsyncCollector <SendGridMessage> >(new SendGridAttribute()
                {
                    ApiKey = "SendgridKey"
                }, token);

                await emailProvider.AddAsync(message, token);
            }
        }