public async Task <List <SegmentAdvanced> > GetSegmentsByUserAsync(string userId, CancellationToken cancellationToken = default)
        {
            var filter         = new StarredThreadFilter(x => x.UserReference.UserId.Equals(userId));
            var starredThreads = await ThreadsRepository
                                 .FetchAsync(filter, RequestWindow.All)
                                 .ConfigureAwait(continueOnCapturedContext: false);

            if (starredThreads.Count == 0)
            {
                return(new List <SegmentAdvanced>());
            }


            var segments = new List <SegmentAdvanced>(capacity: starredThreads.Count);

            for (var i = 0; i < starredThreads.Count; i++)
            {
                var starred = starredThreads[i];
                ScheduleThreadApi.From      = starred.FromCode;
                ScheduleThreadApi.To        = starred.ToCode;
                ScheduleThreadApi.ThreadKey = starred.ThreadKey;
                var request  = RequestApiFactory.RequestApiFactory.Create(ScheduleThreadApi);
                var response = await request.GetResponseAsync()
                               .ConfigureAwait(continueOnCapturedContext: false);

                var result = RequestApiFactory.RequestApiFactory.RequestJsonDesirialize <SegmentAdvanced>(response);
                if (result != null)
                {
                    segments.Add(result);
                }
            }

            return(segments);
        }
Пример #2
0
        public async Task <IActionResult> Index(string fromCode = null, string toCode = null)
        {
            if (!string.IsNullOrWhiteSpace(fromCode) && !string.IsNullOrWhiteSpace(toCode))
            {
                _scheduleApi.From = fromCode;
                _scheduleApi.To   = toCode;
                var request  = RequestApiFactory.Create(_scheduleApi);
                var response = await request.GetResponseAsync()
                               .ConfigureAwait(continueOnCapturedContext: false);

                var result = RequestApiFactory.RequestJsonDesirialize <ScheduleResponse>(response);
                if (result != null && result.Error == null)
                {
                    var filter = new StarredThreadFilter(x =>
                                                         User.FindFirstValue(Services.Identity.User.IdClaimType).Equals(x.UserReference.UserId));
                    var sttaredThreads = await ThreadsRepository
                                         .FetchAsync(filter, RequestWindow.All)
                                         .ConfigureAwait(continueOnCapturedContext: false);

                    var model = new SchedulesViewModel
                    {
                        Segments          = result.Segments,
                        SttaredThreadKeys = sttaredThreads.Select(x => x.ThreadKey).ToArray(),
                        FromCode          = fromCode,
                        ToCode            = toCode,
                    };
                    return(View(model));
                }
            }

            return(View(new SchedulesViewModel
            {
                From = string.Empty,
                To = string.Empty,
            }));
        }
Пример #3
0
        public async Task <IActionResult> Index(SchedulesViewModel model)
        {
            try
            {
                if (model == null)
                {
                    return(View(new SchedulesViewModel
                    {
                        From = string.Empty,
                        To = string.Empty,
                    }));
                }
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                if (model.FromCode == null || model.ToCode == null)
                {
                    var fromCityTask = _cities.GetCityKeyAsync(model.From);
                    var toCityTask   = _cities.GetCityKeyAsync(model.To);

                    await Task.WhenAll(fromCityTask, toCityTask)
                    .ConfigureAwait(continueOnCapturedContext: false);

                    if (fromCityTask.Result == null || toCityTask.Result == null)
                    {
                        return(View(model));
                    }

                    model.FromCode = fromCityTask.Result.Code;
                    model.ToCode   = toCityTask.Result.Code;
                }

                _scheduleApi.From = model.FromCode;
                _scheduleApi.To   = model.ToCode;
                var request  = RequestApiFactory.Create(_scheduleApi);
                var response = await request.GetResponseAsync()
                               .ConfigureAwait(continueOnCapturedContext: false);

                var result = RequestApiFactory.RequestJsonDesirialize <ScheduleResponse>(response);
                if (result != null && result.Error == null)
                {
                    var filter = new StarredThreadFilter(x =>
                                                         User.FindFirstValue(Services.Identity.User.IdClaimType).Equals(x.UserReference.UserId));
                    var sttaredThreads = await ThreadsRepository
                                         .FetchAsync(filter, RequestWindow.All)
                                         .ConfigureAwait(continueOnCapturedContext: false);

                    var filtredSegments = result.Segments.AsEnumerable();
                    if (model.StartDate.HasValue)
                    {
                        filtredSegments = filtredSegments.Where(x => x.StartDate >= model.StartDate.Value);
                    }
                    if (model.EndDate.HasValue)
                    {
                        filtredSegments = filtredSegments.Where(x => x.StartDate <= model.EndDate.Value);
                    }
                    model.Segments = filtredSegments.ToArray();

                    model.SttaredThreadKeys = sttaredThreads.Select(x => x.ThreadKey).ToArray();
                    return(View(model));
                }
            }
            catch (Exception exc)
            {
                return(RedirectToAction("Error", new ErrorViewModel {
                    Exception = exc
                }));
            }

            return(View(model));
        }
        public async void TimerCallBack(object state)
        {
            if (string.IsNullOrWhiteSpace(_email) || string.IsNullOrWhiteSpace(_password))
            {
                throw new ArgumentException("EmailDistributionSettings Not Found");
            }
            using (_syncRoot.Enter())
            {
                try
                {
                    var threads = await ThreadsRepository
                                  .FetchAsync(new StarredThreadFilter(x => x.TimeToMailling.HasValue), RequestWindow.All)
                                  .ConfigureAwait(continueOnCapturedContext: false);

                    if (threads.Count == 0)
                    {
                        return;
                    }
                    var usersLocked = await UserManager.Users
                                      .Where(x => x.LockoutEnd.HasValue)
                                      .ToListAsync()
                                      .ConfigureAwait(continueOnCapturedContext: false);

                    for (var i = 0; i < threads.Count; i++)
                    {
                        var thread = threads[i];
                        ScheduleThreadApi.From      = thread.FromCode;
                        ScheduleThreadApi.To        = thread.ToCode;
                        ScheduleThreadApi.ThreadKey = ScheduleThreadApi.ThreadKey;

                        var request  = RequestApiFactory.RequestApiFactory.Create(ScheduleThreadApi);
                        var response = await request.GetResponseAsync()
                                       .ConfigureAwait(continueOnCapturedContext: false);

                        var result = RequestApiFactory.RequestApiFactory.RequestJsonDesirialize <SegmentAdvanced>(response);
                        if (result == null)
                        {
                            continue;
                        }

                        var startDate = result.ArrivalDate.Add(result.ArrivalTime);
                        var now       = DateTime.Now;
                        var alertDate = startDate.Add(thread.TimeToMailling.Value);
                        if (alertDate <= now)
                        {
                            using (var context = await RepositoryFactory.DatabaseStorageService
                                                 .CreateContextAsync()
                                                 .ConfigureAwait(continueOnCapturedContext: false))
                            {
                                context.ConfigureAsFetchOnly();

                                if (usersLocked.Any(x => x.Id == thread.UserReference.UserId))
                                {
                                    continue;
                                }

                                var user = await context.Set <User>()
                                           .AsNoTracking()
                                           .FirstOrDefaultAsync(x => x.Id.Equals(thread.UserReference.UserId))
                                           .ConfigureAwait(continueOnCapturedContext: false);


                                var emailMessage = new MimeMessage();

                                emailMessage.From.Add(new MailboxAddress("Администрация сайта YandexScheduler", ""));
                                emailMessage.To.Add(new MailboxAddress(user.Email, user.Email));
                                emailMessage.Subject = $"Уведомление о поезде {result.Name}";
                                emailMessage.Body    = new TextPart(MimeKit.Text.TextFormat.Text)
                                {
                                    Text = $"Отправление в {startDate}",
                                };

                                using (var client = new SmtpClient())
                                {
                                    await client.ConnectAsync("smtp.yandex.ru", 465, true);

                                    await client.AuthenticateAsync(_email, _password);

                                    await client.SendAsync(emailMessage);

                                    await client.DisconnectAsync(true);
                                }
                            }
                        }
                    }
                }
                catch (MailKit.Security.AuthenticationException exc)
                {
                    throw exc;
                }
                catch (Exception exc)
                {
                }
            }
        }