Пример #1
0
        public async Task <bool> Email([FromBody] EmailNotificationSettings settings)
        {
            try
            {
                var message = new NotificationMessage
                {
                    Message = "This is just a test! Success!",
                    Subject = $"Ombi: Test",
                    To      = settings.AdminEmail,
                };

                message.Other.Add("PlainTextBody", "This is just a test! Success!");
                await EmailProvider.SendAdHoc(message, settings);
            }
            catch (Exception e)
            {
                Log.LogWarning(e, "Exception when testing Email Notifications");
                return(false);
            }

            return(true);
        }
Пример #2
0
        private async Task EmailNewRequest(NotificationModel model, EmailNotificationSettings settings)
        {
            var email = new EmailBasicTemplate();
            var html  = email.LoadTemplate(
                $"Ombi: New {model.RequestType.GetString()?.ToLower()} request for {model.Title}!",
                $"Hello! The user '{model.User}' has requested the {model.RequestType.GetString()?.ToLower()} '{model.Title}'! Please log in to approve this request. Request Date: {model.DateTime.ToString("f")}",
                model.ImgSrc);
            var body = new BodyBuilder {
                HtmlBody = html, TextBody = $"Hello! The user '{model.User}' has requested the {model.RequestType.GetString()?.ToLower()} '{model.Title}'! Please log in to approve this request. Request Date: {model.DateTime.ToString("f")}"
            };

            var message = new MimeMessage
            {
                Body    = body.ToMessageBody(),
                Subject = $"Ombi: New {model.RequestType.GetString()?.ToLower()} request for {model.Title}!"
            };

            message.From.Add(new MailboxAddress(settings.EmailSender, settings.EmailSender));
            message.To.Add(new MailboxAddress(settings.RecipientEmail, settings.RecipientEmail));


            await Send(message, settings);
        }
Пример #3
0
        private async Task EmailRequestApproved(NotificationModel model, EmailNotificationSettings settings)
        {
            var email = new EmailBasicTemplate();
            var html  = email.LoadTemplate(
                "Ombi: Your request has been approved!",
                $"Hello! Your request for {model.Title} has been approved!",
                model.ImgSrc);
            var body = new BodyBuilder {
                HtmlBody = html, TextBody = $"Hello! Your request for {model.Title} has been approved!",
            };

            var message = new MimeMessage
            {
                Body    = body.ToMessageBody(),
                Subject = $"Ombi: Your request has been approved!"
            };

            message.From.Add(new MailboxAddress(settings.EmailSender, settings.EmailSender));
            message.To.Add(new MailboxAddress(model.UserEmail, model.UserEmail));


            await Send(message, settings);
        }
Пример #4
0
        private async Task EmailIssue(NotificationModel model, EmailNotificationSettings settings)
        {
            var email = new EmailBasicTemplate();
            var html  = email.LoadTemplate(
                $"Ombi: New issue for {model.Title}!",
                $"Hello! The user '{model.User}' has reported a new issue {model.Body} for the title {model.Title}!",
                model.ImgSrc);
            var body = new BodyBuilder {
                HtmlBody = html, TextBody = $"Hello! The user '{model.User}' has reported a new issue {model.Body} for the title {model.Title}!"
            };

            var message = new MimeMessage
            {
                Body    = body.ToMessageBody(),
                Subject = $"Ombi: New issue for {model.Title}!"
            };

            message.From.Add(new MailboxAddress(settings.EmailSender, settings.EmailSender));
            message.To.Add(new MailboxAddress(settings.RecipientEmail, settings.RecipientEmail));


            await Send(message, settings);
        }
Пример #5
0
        private async Task EmailAddedToRequestQueue(NotificationModel model, EmailNotificationSettings settings)
        {
            var email = new EmailBasicTemplate();
            var html  = email.LoadTemplate(
                "Ombi: A request could not be added.",
                $"Hello! The user '{model.User}' has requested {model.Title} but it could not be added. This has been added into the requests queue and will keep retrying",
                model.ImgSrc);
            var body = new BodyBuilder {
                HtmlBody = html, TextBody = $"Hello! The user '{model.User}' has requested {model.Title} but it could not be added. This has been added into the requests queue and will keep retrying"
            };

            var message = new MimeMessage
            {
                Body    = body.ToMessageBody(),
                Subject = $"Ombi: A request could not be added"
            };

            message.From.Add(new MailboxAddress(settings.EmailSender, settings.EmailSender));
            message.To.Add(new MailboxAddress(settings.RecipientEmail, settings.RecipientEmail));


            await Send(message, settings);
        }
Пример #6
0
        private bool ValidateConfiguration(EmailNotificationSettings settings)
        {
            if (settings.Authentication)
            {
                if (string.IsNullOrEmpty(settings.EmailUsername) || string.IsNullOrEmpty(settings.EmailPassword))
                {
                    return(false);
                }
            }
            if (string.IsNullOrEmpty(settings.EmailHost) || string.IsNullOrEmpty(settings.RecipientEmail) || string.IsNullOrEmpty(settings.EmailPort.ToString()))
            {
                return(false);
            }

            if (!settings.EnableUserEmailNotifications)
            {
                if (!settings.Enabled)
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #7
0
        private async Task Send(MimeMessage message, EmailNotificationSettings settings)
        {
            try
            {
                using (var client = new SmtpClient())
                {
                    client.Connect(settings.EmailHost, settings.EmailPort, SecureSocketOptions.Auto); // Let MailKit figure out the correct SecureSocketOptions.

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    client.Authenticate(settings.EmailUsername, settings.EmailPassword);

                    await client.SendAsync(message);

                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
Пример #8
0
        /// <summary>
        /// This will load up the Email template and generate the HTML
        /// </summary>
        /// <param name="model"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public async Task SendAdHoc(NotificationMessage model, EmailNotificationSettings settings)
        {
            try
            {
                var email = new EmailBasicTemplate();

                var customization = await CustomizationSettings.GetSettingsAsync();

                var html = email.LoadTemplate(model.Subject, model.Message, null, customization.Logo);

                var textBody = string.Empty;

                model.Other.TryGetValue("PlainTextBody", out textBody);
                var body = new BodyBuilder
                {
                    HtmlBody = html,
                    TextBody = textBody
                };

                var message = new MimeMessage
                {
                    Body    = body.ToMessageBody(),
                    Subject = model.Subject
                };
                message.From.Add(new MailboxAddress(string.IsNullOrEmpty(settings.SenderName) ? settings.SenderAddress : settings.SenderName, settings.SenderAddress));
                message.To.Add(new MailboxAddress(model.To, model.To));

                using (var client = new SmtpClient())
                {
                    if (settings.DisableCertificateChecking)
                    {
                        // Disable validation of the certificate associated with the SMTP service
                        // Helpful when the TLS certificate is not in the certificate store of the server
                        // Does carry the risk of man in the middle snooping
                        client.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                    }

                    if (settings.DisableTLS)
                    {
                        // Does not attempt to use either TLS or SSL
                        // Helpful when MailKit finds a TLS certificate, but it unable to use it
                        client.Connect(settings.Host, settings.Port, MailKit.Security.SecureSocketOptions.None);
                    }
                    else
                    {
                        client.Connect(settings.Host, settings.Port); // Let MailKit figure out the correct SecureSocketOptions.
                    }

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    if (settings.Authentication)
                    {
                        client.Authenticate(settings.Username, settings.Password);
                    }
                    _log.LogDebug("sending message to {0} \r\n from: {1}\r\n Are we authenticated: {2}", message.To, message.From, client.IsAuthenticated);
                    await client.SendAsync(message);

                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception e)
            {
                _log.LogError(e, "Exception when attempting to send an email");
                throw;
            }
        }
Пример #9
0
 public EmailNotifier(EmailNotificationSettings settings)
 {
     _settings = settings;
 }
        private CreateJobApplicationResponse CreateJobApplication(
            SocialMediaProcessedResponse result,
            JobDetailsModel jobDetails,
            ApplicantInfo applicantInfo,
            string overrideEmail)
        {
            // Gather Attachments
            Guid identifier = Guid.NewGuid();
            JobApplicationAttachmentUploadItem uploadItem = new JobApplicationAttachmentUploadItem()
            {
                Id               = identifier.ToString(),
                AttachmentType   = JobApplicationAttachmentType.Resume,
                FileName         = result.FileName,
                FileStream       = result.FileStream,
                PathToAttachment = identifier.ToString() + "_" + result.FileName,
                Status           = "Ready"
            };



            // End code for fetch job details
            Log.Write("overrideEmail uploadItem object created", ConfigurationPolicy.ErrorLog);
            List <JobApplicationAttachmentUploadItem> attachments = new List <JobApplicationAttachmentUploadItem>();

            attachments.Add(uploadItem);
            Log.Write("overrideEmail uploadItem attachment added", ConfigurationPolicy.ErrorLog);
            string resumeAttachmentPath = JobApplicationAttachmentUploadItem.GetAttachmentPath(attachments, JobApplicationAttachmentType.Resume);

            Log.Write("After resume GetAttachmentPath", ConfigurationPolicy.ErrorLog);
            string coverletterAttachmentPath = JobApplicationAttachmentUploadItem.GetAttachmentPath(attachments, JobApplicationAttachmentType.Coverletter);

            Log.Write("After cover letter GetAttachmentPath", ConfigurationPolicy.ErrorLog);

            string htmlEmailContent           = this.GetEmailHtmlContent(this.EmailTemplateId);
            string htmlEmailSubject           = this.GetEmailSubject(this.EmailTemplateId);
            string htmlAdvertiserEmailContent = this.GetEmailHtmlContent(this.AdvertiserEmailTemplateId);
            string htmlAdvertiserEmailSubject = this.GetEmailSubject(this.AdvertiserEmailTemplateId);

            Log.Write("After GetHtmlEmailContent", ConfigurationPolicy.ErrorLog);
            // Email notification settings


            List <dynamic> emailAttachments = new List <dynamic>();

            foreach (var item in attachments)
            {
                dynamic emailAttachment = new ExpandoObject();
                emailAttachment.FileStream = item.FileStream;
                emailAttachment.FileName   = item.FileName;
                emailAttachments.Add(emailAttachment);
            }

            EmailNotificationSettings advertiserEmailNotificationSettings = (this.AdvertiserEmailTemplateId != null) ?
                                                                            _createAdvertiserEmailTemplate(
                new JobApplicationEmailTemplateModel()
            {
                FromFirstName = result.FirstName,
                FromLastName  = result.LastName,
                FromEmail     = overrideEmail,
                ToFirstName   = jobDetails.ContactDetails.GetFirstName(),
                ToLastName    = jobDetails.ContactDetails.GetLastName(),
                ToEmail       = jobDetails.ApplicationEmail,
                Subject       = SitefinityHelper.GetCurrentSiteEmailTemplateTitle(this.AdvertiserEmailTemplateId),
                HtmlContent   = SitefinityHelper.GetCurrentSiteEmailTemplateHtmlContent(this.AdvertiserEmailTemplateId),
                Attachments   = emailAttachments
            }) : null;



            EmailNotificationSettings emailNotificationSettings = (this.EmailTemplateId != null) ?
                                                                  _createApplicantEmailTemplate(
                new JobApplicationEmailTemplateModel()
            {
                FromFirstName = this.EmailTemplateSenderName,
                FromLastName  = null,
                FromEmail     = this.EmailTemplateSenderEmailAddress,
                ToFirstName   = SitefinityHelper.GetUserFirstNameById(SitefinityHelper.GetUserByEmail(overrideEmail).Id),
                ToLastName    = null,
                ToEmail       = overrideEmail,
                Subject       = SitefinityHelper.GetCurrentSiteEmailTemplateTitle(this.EmailTemplateId),
                HtmlContent   = SitefinityHelper.GetCurrentSiteEmailTemplateHtmlContent(this.EmailTemplateId),
                Attachments   = null
            }) : null;


            EmailNotificationSettings registrationNotificationsSettings = (applicantInfo.IsNewUser && this.RegistrationEmailTemplateId != null) ?
                                                                          _createRegistrationEmailTemplate(
                new JobApplicationEmailTemplateModel()
            {
                FromFirstName = this.EmailTemplateSenderName,
                FromLastName  = null,
                FromEmail     = this.EmailTemplateSenderEmailAddress,
                ToFirstName   = applicantInfo.FirstName,
                ToLastName    = null,
                ToEmail       = applicantInfo.Email,
                Subject       = SitefinityHelper.GetCurrentSiteEmailTemplateTitle(this.RegistrationEmailTemplateId),
                HtmlContent   = SitefinityHelper.GetCurrentSiteEmailTemplateHtmlContent(this.RegistrationEmailTemplateId),
                Attachments   = null
            }) : null;


            Log.Write("emailNotificationSettings after: ", ConfigurationPolicy.ErrorLog);

            Log.Write("BL response before: ", ConfigurationPolicy.ErrorLog);

            //Create Application
            var response = _blConnector.MemberCreateJobApplication(
                new JXTNext_MemberApplicationRequest
            {
                ApplyResourceID               = result.JobId.Value,
                MemberID                      = 2,
                ResumePath                    = resumeAttachmentPath,
                CoverletterPath               = coverletterAttachmentPath,
                EmailNotification             = emailNotificationSettings,
                AdvertiserEmailNotification   = advertiserEmailNotificationSettings,
                AdvertiserName                = jobDetails.ContactDetails,
                CompanyName                   = jobDetails.CompanyName,
                UrlReferral                   = result.UrlReferral,
                RegistrationEmailNotification = registrationNotificationsSettings
            },
                overrideEmail);

            Log.Write("BL response after: ", ConfigurationPolicy.ErrorLog);

            var createJobApplicationResponse = new CreateJobApplicationResponse {
                MemberApplicationResponse = response
            };

            if (response.Success && response.ApplicationID.HasValue)
            {
                Log.Write("BL response in: ", ConfigurationPolicy.ErrorLog);
                var hasFailedUpload = _jobApplicationService.UploadFiles(attachments);
                Log.Write("file upload is : " + hasFailedUpload, ConfigurationPolicy.ErrorLog);
                if (hasFailedUpload)
                {
                    createJobApplicationResponse.FilesUploaded = false;
                    createJobApplicationResponse.Status        = JobApplicationStatus.Technical_Issue; // Unable to attach files
                    createJobApplicationResponse.Message       = "Unable to attach files to application";
                }
                else
                {
                    createJobApplicationResponse.FilesUploaded = true;
                    createJobApplicationResponse.Status        = JobApplicationStatus.Applied_Successful;
                    createJobApplicationResponse.Message       = "Your application was successfully processed.";
                }
            }
            else
            {
                if (response.Errors.FirstOrDefault().ToLower().Contains("already exists"))
                {
                    createJobApplicationResponse.Status  = JobApplicationStatus.Already_Applied;
                    createJobApplicationResponse.Message = "You have already applied to this job.";
                }
                else
                {
                    createJobApplicationResponse.Status  = JobApplicationStatus.Technical_Issue;
                    createJobApplicationResponse.Message = response.Errors.FirstOrDefault();
                }
            }

            return(createJobApplicationResponse);
        }
Пример #11
0
        private async Task SendBccMails(MassEmailModel model, CustomizationSettings customization, EmailNotificationSettings email, List <Task> messagesSent)
        {
            var resolver = new NotificationMessageResolver();
            var curlys   = new NotificationMessageCurlys();

            var validUsers = new List <OmbiUser>();

            foreach (var user in model.Users)
            {
                var fullUser = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == user.Id);

                if (!fullUser.Email.HasValue())
                {
                    _log.LogInformation("User {0} has no email, cannot send mass email to this user", fullUser.UserName);
                    continue;
                }

                validUsers.Add(fullUser);
            }

            if (!validUsers.Any())
            {
                return;
            }

            var firstUser = validUsers.FirstOrDefault();

            var bccAddress = string.Join(',', validUsers.Select(x => x.Email));

            curlys.Setup(firstUser, customization);
            var template = new NotificationTemplates()
            {
                Message = model.Body, Subject = model.Subject
            };
            var content = resolver.ParseMessage(template, curlys);
            var msg     = new NotificationMessage
            {
                Message = content.Message,
                Subject = content.Subject,
                Other   = new Dictionary <string, string> {
                    { "bcc", bccAddress }
                }
            };

            messagesSent.Add(_email.SendAdHoc(msg, email));
        }
Пример #12
0
        /// <summary>
        /// This will add a 2 second delay, this is to help with concurrent connection limits
        /// <see href="https://github.com/Ombi-app/Ombi/issues/4377"/>
        /// </summary>
        private async Task DelayEmail(NotificationMessage msg, EmailNotificationSettings email)
        {
            await Task.Delay(2000);

            await _email.SendAdHoc(msg, email);
        }
Пример #13
0
        private async Task SendIndividualEmails(MassEmailModel model, CustomizationSettings customization, EmailNotificationSettings email, List <Task> messagesSent)
        {
            var resolver = new NotificationMessageResolver();
            var curlys   = new NotificationMessageCurlys();

            foreach (var user in model.Users)
            {
                var fullUser = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == user.Id);

                if (!fullUser.Email.HasValue())
                {
                    _log.LogInformation("User {0} has no email, cannot send mass email to this user", fullUser.UserName);
                    continue;
                }
                curlys.Setup(fullUser, customization);
                var template = new NotificationTemplates()
                {
                    Message = model.Body, Subject = model.Subject
                };
                var content = resolver.ParseMessage(template, curlys);
                var msg     = new NotificationMessage
                {
                    Message = content.Message,
                    To      = fullUser.Email,
                    Subject = content.Subject
                };
                messagesSent.Add(DelayEmail(msg, email));
                _log.LogInformation("Sent mass email to user {0} @ {1}", fullUser.UserName, fullUser.Email);
            }
        }
Пример #14
0
        public async Task <IActionResult> CreatePost(PostCreateDTO postCreateDTO)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(User.Identity.Name);

                var categories = await _categoryService.GetAllAsync();

                var languages = await _languageService.GetAllAsync();

                var category = categories.First();
                var language = languages.First();

                var post = _mapper.Map <Post>(postCreateDTO);

                post.UserId     = user.Id;
                post.Created    = DateTime.Now;
                post.CreatedBy  = user.UserName;
                post.PostStatus = PostStatus.Posted;
                post.CategoryId = category.Id;
                post.LanguageId = language.Id;

                var newPost = await _postService.CreateAsync(post);

                if (postCreateDTO.Files != null)
                {
                    List <Picture> pictures = AddFiles(postCreateDTO.Files, newPost.Id, user.UserName);

                    foreach (var picture in pictures)
                    {
                        await _pictureService.CreateAsync(picture);
                    }
                }

                var usersForNotification = await _userService.GetUsersForNitificationAsync();

                if (usersForNotification != null)
                {
                    var usersVoewDTO = _mapper.Map <List <UserViewDto> >(usersForNotification);
                    var postViewDTO  = _mapper.Map <PostViewDTO>(post);
                    var userViewDTO  = _mapper.Map <UserViewDto>(user);

                    postViewDTO.UserViewDto = userViewDTO;

                    var viewPostLink = Url.Action(
                        "PostDetails",
                        "Post",
                        new { id = postViewDTO.Id },
                        protocol: HttpContext.Request.Scheme);

                    var stringForm = await _razorViewToStringRenderer.RenderToStringAsync("Post/PostForEmailNotification", postViewDTO);

                    await _automaticEmailNotificationService.SentAutomaticNotificationAsync(EmailNotificationSettings.subject,
                                                                                            EmailNotificationSettings.CteateMessage(postViewDTO, stringForm, viewPostLink), usersVoewDTO);
                }

                return(RedirectToAction("Index", "Home"));
            }
            return(View(postCreateDTO));
        }
Пример #15
0
        public async Task Send(NotificationMessage model, EmailNotificationSettings settings)
        {
            try
            {
                EnsureArg.IsNotNullOrEmpty(settings.SenderAddress);
                EnsureArg.IsNotNullOrEmpty(model.To);
                EnsureArg.IsNotNullOrEmpty(model.Message);
                EnsureArg.IsNotNullOrEmpty(settings.Host);

                var body = new BodyBuilder
                {
                    HtmlBody = model.Message,
                };

                if (model.Other.ContainsKey("PlainTextBody"))
                {
                    body.TextBody = model.Other["PlainTextBody"];
                }

                var message = new MimeMessage
                {
                    Body    = body.ToMessageBody(),
                    Subject = model.Subject
                };

                message.From.Add(new MailboxAddress(string.IsNullOrEmpty(settings.SenderName) ? settings.SenderAddress : settings.SenderName, settings.SenderAddress));
                message.To.Add(new MailboxAddress(model.To, model.To));

                using (var client = new SmtpClient())
                {
                    if (settings.DisableCertificateChecking)
                    {
                        client.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                    }

                    if (settings.DisableTLS)
                    {
                        client.Connect(settings.Host, settings.Port, MailKit.Security.SecureSocketOptions.None);
                    }
                    else
                    {
                        client.Connect(settings.Host, settings.Port); // Let MailKit figure out the correct SecureSocketOptions.
                    }

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    if (settings.Authentication)
                    {
                        client.Authenticate(settings.Username, settings.Password);
                    }
                    //Log.Info("sending message to {0} \r\n from: {1}\r\n Are we authenticated: {2}", message.To, message.From, client.IsAuthenticated);
                    await client.SendAsync(message);

                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception e)
            {
                _log.LogError(e, "Exception when attempting to send email");
                throw;
            }
        }
Пример #16
0
        public ActionResult Create(JobAlertViewModel model)
        {
            List <JobAlertEditFilterRootItem> filtersVMList = GetJobFilterData();

            if (model.SalaryStringify != null)
            {
                model.Salary = JsonConvert.DeserializeObject <JobAlertSalaryFilterReceiver>(model.SalaryStringify);
            }

            if (String.IsNullOrEmpty(model.Email))
            {
                model.Email = SitefinityHelper.GetLoggedInUserEmail();
            }

            model.Data = JobAlertUtility.ConvertJobAlertViewModelToSearchModel(model, filtersVMList);
            // Create Email Notification
            EmailNotificationSettings jobAlertEmailNotificationSettings = null;

            if (this.JobAlertEmailTemplateId != null)
            {
                jobAlertEmailNotificationSettings = new EmailNotificationSettings(new EmailTarget(this.JobAlertEmailTemplateSenderName, this.JobAlertEmailTemplateSenderEmailAddress),
                                                                                  new EmailTarget(string.Empty, model.Email),
                                                                                  SitefinityHelper.GetCurrentSiteEmailTemplateTitle(this.JobAlertEmailTemplateId),
                                                                                  SitefinityHelper.GetCurrentSiteEmailTemplateHtmlContent(this.JobAlertEmailTemplateId), null);
                if (!this.JobAlertEmailTemplateCC.IsNullOrEmpty())
                {
                    foreach (var ccEmail in this.JobAlertEmailTemplateCC.Split(';'))
                    {
                        jobAlertEmailNotificationSettings?.AddCC(String.Empty, ccEmail);
                    }
                }

                if (!this.JobAlertEmailTemplateBCC.IsNullOrEmpty())
                {
                    foreach (var bccEmail in this.JobAlertEmailTemplateBCC.Split(';'))
                    {
                        jobAlertEmailNotificationSettings?.AddBCC(String.Empty, bccEmail);
                    }
                }
            }


            model.EmailNotifications = jobAlertEmailNotificationSettings;
            var response     = GetUpsertResponse(model);
            var stausMessage = "A Job Alert has been created successfully.";
            var alertStatus  = JobAlertStatus.SUCCESS;

            if (!response.Success)
            {
                stausMessage = response.Errors.First();
                alertStatus  = JobAlertStatus.CREATE_FAILED;
            }

            TempData["StatusCode"]    = alertStatus;
            TempData["StatusMessage"] = stausMessage;

            // Why action name is empty?
            // Here we need to call Index action, if we are providing action name as Index here
            // It is appending in the URL, but we dont want to show that in URL. So, sending it as empty
            // Will definity call defaut action i,.e Index
            return(RedirectToAction(""));
        }
Пример #17
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <GameService>()
            .As <IGameService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <GenreService>()
            .As <IGenreService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <PlatformService>()
            .As <IPlatformService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <PublisherService>()
            .As <IPublisherService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <CommentService>()
            .As <ICommentService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <BasketService>()
            .As <IBasketService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <OrderService>()
            .As <IOrderService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <PaymentTypeService>()
            .As <IPaymentTypeService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <InvoiceService>()
            .As <IInvoiceService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <ShipperService>()
            .As <IShipperService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <MostCommentedSortOption>()
            .Keyed <ISortOption <GameRoot> >(SortOptions.MostCommented)
            .InstancePerLifetimeScope();

            builder.RegisterType <NewSortOption>()
            .Keyed <ISortOption <GameRoot> >(SortOptions.New)
            .InstancePerLifetimeScope();

            builder.RegisterType <MostPopularSortOption>()
            .Keyed <ISortOption <GameRoot> >(SortOptions.MostPopular)
            .InstancePerLifetimeScope();

            builder.RegisterType <PriceAscSortOption>()
            .Keyed <ISortOption <GameRoot> >(SortOptions.PriceAsc)
            .InstancePerLifetimeScope();

            builder.RegisterType <PriceDescSortOption>()
            .Named <ISortOption <GameRoot> >(SortOptions.PriceDesc)
            .InstancePerLifetimeScope();

            builder.RegisterType <GameSortOptionFactory>()
            .As <ISortOptionFactory <GameRoot> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <OrderDetailsService>()
            .As <IOrderDetailsService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <UserService>()
            .As <IUserService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <RoleService>()
            .As <IRoleService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <PermissionService>()
            .As <IPermissionService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <RatingService>()
            .As <IRatingService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <GameImageService>()
            .As <IGameImageService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <OrderNotificationService>()
            .As <INotificationService <Order> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <MailSenderService>()
            .Keyed <INotificationSenderService <Order> >(NotificationMethod.Email)
            .InstancePerLifetimeScope();

            builder.RegisterGeneric(typeof(NotificationSenderServiceFactory <>))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            builder.Register(c =>
            {
                const string notificationConfigSegment = nameof(EmailNotificationSettings);
                var config   = c.Resolve <IConfiguration>();
                var host     = config.GetValue <string>($"{notificationConfigSegment}:Host");
                var email    = config.GetValue <string>($"{notificationConfigSegment}:Email");
                var password = config.GetValue <string>($"{notificationConfigSegment}:Password");
                var port     = config.GetValue <int>($"{notificationConfigSegment}:Port");

                var settings = new EmailNotificationSettings(host, email, password, port);

                return(settings);
            }).As <IEmailNotificationSettings>()
            .InstancePerLifetimeScope();
        }
Пример #18
0
        private Response NotifyUser(bool notify)
        {
            var auth  = Auth.GetSettings().UserAuthentication;
            var email = EmailNotificationSettings.GetSettings().EnableUserEmailNotifications;

            if (!auth)
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Sorry, but this functionality is currently only for users with Plex accounts"
                }));
            }
            if (!email)
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Sorry, but your administrator has not yet enabled this functionality."
                }));
            }
            var username     = Username;
            var originalList = UsersToNotifyRepo.GetAll();

            if (!notify)
            {
                if (originalList == null)
                {
                    return(Response.AsJson(new JsonResponseModel {
                        Result = false, Message = "We could not remove this notification because you never had it!"
                    }));
                }
                var userToRemove = originalList.FirstOrDefault(x => x.Username == username);
                if (userToRemove != null)
                {
                    UsersToNotifyRepo.Delete(userToRemove);
                }
                return(Response.AsJson(new JsonResponseModel {
                    Result = true
                }));
            }


            if (originalList == null)
            {
                var userModel = new UsersToNotify {
                    Username = username
                };
                var insertResult = UsersToNotifyRepo.Insert(userModel);
                return(Response.AsJson(insertResult != -1 ? new JsonResponseModel {
                    Result = true
                } : new JsonResponseModel {
                    Result = false, Message = "Could not save, please try again"
                }));
            }

            var existingUser = originalList.FirstOrDefault(x => x.Username == username);

            if (existingUser != null)
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = true
                }));                                                             // It's already enabled
            }
            else
            {
                var userModel = new UsersToNotify {
                    Username = username
                };
                var insertResult = UsersToNotifyRepo.Insert(userModel);
                return(Response.AsJson(insertResult != -1 ? new JsonResponseModel {
                    Result = true
                } : new JsonResponseModel {
                    Result = false, Message = "Could not save, please try again"
                }));
            }
        }
        public JsonResult CreateAnonymousJobAlert(JobSearchResultsFilterModel filterModel, string email)
        {
            string  alertName   = String.Empty;
            var     jsonData    = JsonConvert.SerializeObject(filterModel);
            dynamic searchModel = new ExpandoObject();
            var     jsonModel   = _mapToCronJobJsonModel(filterModel);

            searchModel.search = jsonModel.search;
            // Creating the job alert model
            JobAlertViewModel alertModel = new JobAlertViewModel()
            {
                Filters = new List <JobAlertFilters>(),
                Salary  = new JobAlertSalaryFilterReceiver(),
                Email   = email
            };



            if (filterModel != null)
            {
                // Keywords
                alertModel.Keywords = filterModel.Keywords;
                if (!alertModel.Keywords.IsNullOrEmpty())
                {
                    alertName = alertModel.Keywords;
                }

                // Filters
                if (filterModel.Filters != null && filterModel.Filters.Count() > 0)
                {
                    List <JobAlertFilters> alertFilters = new List <JobAlertFilters>();
                    bool flag = false;
                    for (int i = 0; i < filterModel.Filters.Count(); i++)
                    {
                        var filter = filterModel.Filters[i];
                        if (filter != null && filter.values != null && filter.values.Count > 0)
                        {
                            JobAlertFilters alertFilter = new JobAlertFilters
                            {
                                RootId = filter.rootId,
                                Values = new List <string>()
                            };

                            foreach (var filterItem in filter.values)
                            {
                                if (!flag && alertName.IsNullOrEmpty())
                                {
                                    flag      = true;
                                    alertName = filter.values.Count.ToString() + " " + filter.rootId;
                                }

                                JobSearchResultsFilterModel.ProcessFilterLevelsToFlat(filterItem, alertFilter.Values);
                            }

                            alertFilters.Add(alertFilter);
                        }
                    }

                    alertModel.Filters = alertFilters;
                }

                // Salary
                if (filterModel.Salary != null)
                {
                    alertModel.Salary.RootName    = filterModel.Salary.RootName;
                    alertModel.Salary.TargetValue = filterModel.Salary.TargetValue;
                    alertModel.Salary.LowerRange  = filterModel.Salary.LowerRange;
                    alertModel.Salary.UpperRange  = filterModel.Salary.UpperRange;

                    if (alertName.IsNullOrEmpty())
                    {
                        alertName = "Salary from" + alertModel.Salary.LowerRange.ToString() + " to " + alertModel.Salary.UpperRange.ToString();
                    }
                }
            }

            if (alertName.IsNullOrEmpty())
            {
                alertName = "All search";
            }

            alertModel.Name = alertName;
            searchModel.jobAlertViewModelData = alertModel;
            alertModel.Data = JsonConvert.SerializeObject(searchModel);

            // Code for sending email alerts
            EmailNotificationSettings jobAlertEmailNotificationSettings = null;

            if (JobAlertEmailTemplateId != null)
            {
                jobAlertEmailNotificationSettings = new EmailNotificationSettings(new EmailTarget(this.JobAlertEmailTemplateSenderName, this.JobAlertEmailTemplateSenderEmailAddress),
                                                                                  new EmailTarget(string.Empty, email),
                                                                                  this.GetJobAlertHtmlEmailTitle(),
                                                                                  this.GetJobAlertHtmlEmailContent(), null);
                if (!this.JobAlertEmailTemplateCC.IsNullOrEmpty())
                {
                    foreach (var ccEmail in this.JobAlertEmailTemplateCC.Split(';'))
                    {
                        jobAlertEmailNotificationSettings.AddCC(String.Empty, ccEmail);
                    }
                }

                if (!this.JobAlertEmailTemplateBCC.IsNullOrEmpty())
                {
                    foreach (var bccEmail in this.JobAlertEmailTemplateBCC.Split(';'))
                    {
                        jobAlertEmailNotificationSettings.AddBCC(String.Empty, bccEmail);
                    }
                }
            }


            alertModel.EmailNotifications = jobAlertEmailNotificationSettings;


            var response = _jobAlertService.MemberJobAlertUpsert(alertModel);

            return(new JsonResult {
                Data = response
            });
        }