Ejemplo n.º 1
0
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                ViewData["LanguageId"]  = new SelectList(_context.Languages, "LanguageId", "LanguageName");
                ViewData["PublisherId"] = new SelectList(_context.Publishers, "PublisherId", "PublisherName");
                AuthorsSelectList       = new SelectList(_context.Authors, nameof(Author.AuthorId), nameof(Author.FirstLastName));
                return(Page());
            }

            _context.Books.Add(Book);
            _context.SaveChanges();

            foreach (var bookAuthorId in BookAuthorIds)
            {
                _context.BookAuthors.Add(new BookAuthor()
                {
                    BookId   = _context.Books.Find(this.Book.BookId).BookId,
                    AuthorId = bookAuthorId
                });
            }

            if (_context.UnfinishedForms.Find(UserId) != null)
            {
                _context.UnfinishedForms.Remove(_context.UnfinishedForms.Find(UserId));
            }
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
Ejemplo n.º 2
0
        public async Task <ActionResult> OnGet(int gameId, int col)
        {
            GameId = gameId;
            var state = _context.GameStates
                        .FirstOrDefault(b => b.GameStateId == GameId);

            Engine.RestoreGameStateFromDb(GameId);
            if (Win)
            {
                if (state != null)
                {
                    _context.GameStates.Remove(state);
                    await _context.SaveChangesAsync();

                    Win = true;
                    return(RedirectToPage("./Winner", new { state.Player1Name, state.Player2Name, state.MoveByB }));;
                }

                _context.SaveChanges();
            }
            else
            {
                var result = Engine.Move(col, state != null && state.MoveByB);
                var board  = Engine.GetSerializedGameState();
                if (state != null)
                {
                    state.BoardStateJson = board;
                }
                if (state != null)
                {
                    state.MoveByB = !state.MoveByB;
                }
                if (state != null && state.HumanPlayerCount == 1)
                {
                    result = Engine.Move(Engine.RandomNumber(0, state.Width - 1), state.MoveByB);
                    board  = Engine.GetSerializedGameState();
                    state.BoardStateJson = board;
                    state.MoveByB        = !state.MoveByB;
                    _context.SaveChanges();
                }
                _context.SaveChanges();
                if (result == MoveResult.Won)
                {
                    Win = true;
                }
            }

            return(Page());
        }
Ejemplo n.º 3
0
        public override void Execute()
        {
            using (AppDbContext db = new AppDbContext())
            {
                Program.Logger.Debug($"{GetType().Name}: Searching user with TelegramId: {Message.From.Id} in database");
                var user = db.GetUserByTelegramId(Message.From.Id);
                if (user == null)
                {
                    user = new User
                    {
                        TelegramUserId = Message.From.Id,
                        FirstName = Message.From.FirstName,
                        LastName = Message.From.LastName,
                        Username = Message.From.Username
                    };

                    Program.Logger.Info($"{GetType().Name}: {user} is new User");
                    Program.Logger.Debug($"{GetType().Name}: Adding user {user} to database");
                    db.Users.Add(user);
                }
                else
                {
                    Program.Logger.Debug($"{GetType().Name}: User {user} is already exist");
                }

                Program.Logger.Debug($"{GetType().Name}: Subscribing {user} to all shows");
                var subscriptions = user.Subscriptions.ToList();
                foreach (Show show in db.Shows)
                {
                    Subscription subscription = new Subscription
                    {
                        User = user,
                        Show = show,
                        SubscriptionDate = DateTime.Now
                    };

                    if (subscriptions.Any(s => Equals(s.Show, show)))
                    {
                        continue;
                    }

                    db.Subscriptions.Add(subscription);
                }

                Program.Logger.Debug($"{GetType().Name}: Saving changes to database");
                db.SaveChanges();
            }

            Program.Logger.Debug($"{GetType().Name}: Sending response to {Message.From}");
            try
            {
                TelegramApi.SendMessage(Message.From, "Вы, братишка, подписаны на все сериалы");
            }
            catch (Exception e)
            {
                throw new Exception($"{GetType().Name}: An error occurred while sending response to {Message.From}", e);
            }

            Status = true;
        }
Ejemplo n.º 4
0
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            OrganisedEvent.FestivalEvents = new List <FestivalEvent>();
            if (string.IsNullOrEmpty(OrganisedEvent.EventName) ||
                string.IsNullOrEmpty(OrganisedEvent.StartTime) ||
                string.IsNullOrEmpty(OrganisedEvent.StartDate) ||
                string.IsNullOrEmpty(OrganisedEvent.EndTime) ||
                string.IsNullOrEmpty(OrganisedEvent.EndDate) ||
                string.IsNullOrEmpty(OrganisedEvent.PreparationTime) ||
                string.IsNullOrEmpty(OrganisedEvent.CleanUpTime))
            {
                return(Page());
            }

            _context.Events.Add(OrganisedEvent);
            _context.SaveChanges();
            var festivalEvent = new FestivalEvent()
            {
                FestivalId       = FestivalId,
                OrganisedEventId = OrganisedEvent.OrganisedEventId
            };

            OrganisedEvent.FestivalEvents.Add(festivalEvent);
            await _context.SaveChangesAsync();

            return(RedirectToPage("/Festivals/Details", new { id = Request.Query["id"] }));
        }
Ejemplo n.º 5
0
        public override void Execute()
        {
            using (AppDbContext db = new AppDbContext())
            {
                Program.Logger.Debug($"{GetType().Name}: Searching user's settings in database");
                var settings = db.GetSettingsByUser(db.GetUserByTelegramId(Message.From.Id));
                var text = GetMessageContent(settings);
                Program.Logger.Debug($"{GetType().Name}: Sending commands list");
                try
                {
                    TelegramApi.SendMessage(Message.From, text);
                }
                catch (Exception e)
                {
                    throw new Exception($"{GetType().Name}: An error occurred while sending commands list", e);
                }

                bool newSettings = false;
                if (settings == null)
                {
                    Program.Logger.Debug($"{GetType().Name}: Creating new settings for {Message.From}");
                    newSettings = true;
                    settings = new Settings { User = db.GetUserByTelegramId(Message.From.Id) };
                }

                Message msg;
                do
                {
                    Program.Logger.Debug($"{GetType().Name}: Waiting for a command");
                    try
                    {
                        msg = TelegramApi.WaitForMessage(Message.From);
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while waiting for a command", e);
                    }

                    SetSetting(settings, msg);
                }
                while (msg.Text != SaveSettingsCommand && msg.Text != CancelCommand);

                if (msg.Text == SaveSettingsCommand)
                {
                    Program.Logger.Debug($"{GetType().Name}: Saving changes to database");
                    if (newSettings)
                    {
                        db.Settings.Add(settings);
                    }

                    db.SaveChanges();
                }
                else
                {
                    Program.Logger.Debug($"{GetType().Name}: Exiting without saving changes to database");
                }
            }

            Status = true;
        }
Ejemplo n.º 6
0
        public override List<Show> LoadShows()
        {
            HtmlDocument doc = DownloadDocument(ShowsListUrl);
            var showNodes = doc.DocumentNode.SelectNodes(@"//div[@class='mid']//div[@class='bb']//a[@class='bb_a']");

            Regex ruTitleRegex = new Regex(@"(.*)<br>");
            Regex engTitleRegex = new Regex(@"\((.*)\)");
            List<Show> shows = showNodes.Select(n =>
                new Show()
                {
                    SiteId = int.Parse(ShowUrlRegex.Match(n.Attributes["href"].Value).Groups[1].Value),
                    Title = ruTitleRegex.Match(n.InnerHtml).Groups[1].Value,
                    OriginalTitle = engTitleRegex.Match(n.Element("span").InnerText).Groups[1].Value
                }
                ).ToList();

            using (AppDbContext db = new AppDbContext())
            {
                foreach (var show in db.Shows.Where(s => s.SiteId == 0 || string.IsNullOrEmpty(s.OriginalTitle)))
                {
                    try
                    {
                        show.SiteId = shows.First(s => s.Title == show.Title).SiteId;
                        show.OriginalTitle = shows.First(s => s.Title == show.Title).OriginalTitle;
                    }
                    catch (Exception e)
                    {
                        Program.Logger.Error(e, "An error occurred while updating SiteId or OriginalTitle");

                    }
                }
                db.SaveChanges();
            }

            using (AppDbContext db = new AppDbContext())
            {
                foreach (var show in db.Shows.Where(s => string.IsNullOrEmpty(s.Description)))
                {
                    try
                    {
                        show.Description = LoadShowDescription(show);
                    }
                    catch (Exception e)
                    {
                        Program.Logger.Error(e, "An error occurred while loading show description");
                    }
                }
                db.SaveChanges();
            }
            return shows;
        }
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            if (BookAuthorIds.Count != 0)
            {
                _context.BookAuthors.RemoveRange(_context.BookAuthors.Where(b => b.BookId == Book.BookId));
                _context.SaveChanges();

                foreach (var bookAuthorId in BookAuthorIds)
                {
                    _context.BookAuthors.Add(new BookAuthor()
                    {
                        BookId   = Book.BookId,
                        AuthorId = bookAuthorId
                    });
                }
            }

            // a real hack i am sorry :(
            try
            {
                _context.Books.Update(Book);
            }
            catch (InvalidOperationException)
            {
                return(NotFound());
            }

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BookExists(Book.BookId))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("./Index"));
        }
Ejemplo n.º 8
0
        public IActionResult OnPost(int?id, int?submitbutton)
        {
            if (submitbutton.HasValue)
            {
                Console.WriteLine(EventSet.EventSetId);
                var track = _context.Tracks.Find(submitbutton);
                _context.SetTracks.Add(new SetTrack()
                {
                    ActualPlayTimeInSeconds = track.LengthInSeconds,
                    EventSetId = EventSet.EventSetId,
                    TrackId    = track.TrackId
                });
                _context.SaveChanges();
            }

            return(RedirectToPage("/EventSets/Details", new
            {
                id = EventSet.EventSetId
            }));
        }
Ejemplo n.º 9
0
        public override async Task<List<Show>> LoadShows()
        {
            var doc = await DownloadDocument(ShowsListUrl);
            var showNodes = doc.DocumentNode.SelectNodes(@"//div[@class='mid']//div[@class='bb']//a[@class='bb_a']");

            var rusTitleRegex = new Regex(@"(.*)<br>");
            var engTitleRegex = new Regex(@"\((.*)\)");
            var shows = showNodes.Select(n =>
                new Show()
                {
                    SiteId = int.Parse(ShowUrlRegex.Match(n.Attributes["href"].Value).Groups[1].Value),
                    Title = WebUtility.HtmlDecode(rusTitleRegex.Match(n.InnerHtml).Groups[1].Value),
                    OriginalTitle = WebUtility.HtmlDecode(engTitleRegex.Match(n.Element("span").InnerText).Groups[1].Value),
                    SiteTypeId = ShowsSiteType.Id
                })
                .ToList();

            using (var db = new AppDbContext())
            {
                foreach (var show in shows.Except(db.Shows.Where(s => !string.IsNullOrEmpty(s.Description))))
                {
                    try
                    {
                        show.Description = LoadShowDescription(show);
                        shows.First(s => s.SiteId == show.SiteId).Description = show.Description;
                    }
                    catch (Exception e)
                    {
                        Program.Logger.Error(e, "An error occurred while loading show description");
                    }
                }

                db.SaveChanges();
            }

            return shows;
        }
Ejemplo n.º 10
0
        public void SendEpisodesNotifications()
        {
            using (AppDbContext db = new AppDbContext())
            {
                var notifications = db.Notifications
                    .Where(n => !n.Notified)
                    .ToList();
                if (notifications.Count == 0)
                {
                    return;
                }

                var notificationDictionary =
                    notifications.Aggregate(
                        new Dictionary<User, List<Notification>>(),
                        (d, notification) =>
                        {
                            if (d.ContainsKey(notification.Subscription.User))
                            {
                                d[notification.Subscription.User].Add(notification);
                            }
                            else
                            {
                                d.Add(notification.Subscription.User, new List<Notification>() { notification });
                            }

                            return d;
                        });

                Logger.Debug("SendEpisodesNotifications: Sending new notifications");
                foreach (var userNotifications in notificationDictionary)
                {
                    string text = string.Empty;
                    foreach (Notification notification in userNotifications.Value)
                    {
                        text += notification.Subscription.Show.Title + " - " + notification.Episode.Title;
                        var settings = db.GetSettingsByUser(userNotifications.Key);
                        if (settings != null)
                        {
                            text += GetTorrents(notification, settings);
                        }
                    }

                    try
                    {
                        telegramApi.SendMessage(userNotifications.Key.TelegramUserId, text);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "SendEpisodesNotifications: An error occurred while sending new notifications");
                    }
                }

                Logger.Info($"SendEpisodesNotifications: {notificationDictionary.Count} new " +
                            $"{((notificationDictionary.Count == 1) ? "notification was sent" : "notifications were sent")}");
                notifications.ForEach(notification => { db.Notifications.First(n => n.Id == notification.Id).Notified = true; });
                Logger.Trace("SendEpisodesNotifications: Saving changes to database");
                db.SaveChanges();
            }
        }
Ejemplo n.º 11
0
        private static void UpdateShows(Scraper scraper)
        {
            using (var db = new AppDbContext())
            {
                List<Show> showsList;
                Logger.Debug($"Retrieving shows from {scraper.SiteTitle}");
                try
                {
                    showsList = scraper.LoadShows().Result;
                }
                catch (Exception e)
                {
                    Logger.Error(e, $"An error occurred while retrieving shows from {scraper.SiteTitle}");
                    return;
                }

                foreach (var show in showsList)
                {
                    var dbShow = db.SiteTypes.First(st => st.Id == scraper.ShowsSiteType.Id).Shows.FirstOrDefault(s => s.SiteId == show.SiteId);
                    if (dbShow != null)
                    {
                        dbShow.OriginalTitle = show.OriginalTitle;
                        dbShow.Description = show.Description ?? dbShow.Description;
                        dbShow.SiteId = show.SiteId;
                    }
                    else
                    {
                        db.Shows.Add(show);
                    }
                }

                db.SaveChanges();
            }
        }
Ejemplo n.º 12
0
        public void SendShowsNotifications()
        {
            using (AppDbContext db = new AppDbContext())
            {
                var showNotifications = db.ShowNotifications
                    .Where(n => !n.Notified)
                    .ToList();
                if (showNotifications.Count == 0)
                {
                    return;
                }

                Logger.Debug("SendShowsNotifications: Sending new notifications");
                foreach (var notification in showNotifications)
                {
                    string text = $"{notification.Show.Title} ({notification.Show.SiteType.Title}) {string.Format(SubscribeCommand.SubscribeCommandFormat, notification.ShowId)}\n{notification.Show.Description}";
                    try
                    {
                        telegramApi.SendMessage(notification.User.TelegramUserId, text);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "SendShowsNotifications: An error occurred while sending new notifications");
                    }

                    notification.Notified = true;
                }

                Logger.Trace("SendShowsNotifications: Saving changes to database");
                db.SaveChanges();
            }
        }
Ejemplo n.º 13
0
        private string Unsubscribe(User user, Show show)
        {
            string response;
            using (AppDbContext db = new AppDbContext())
            {
                Subscription subscription;
                Program.Logger.Debug($"{GetType().Name}: Checking for subscription existence");
                try
                {
                    subscription = db.Subscriptions.FirstOrDefault(s => s.User.Id == user.Id && s.Show.Id == show.Id);
                }
                catch (Exception e)
                {
                    throw new Exception($"{GetType().Name}: An error occurred while checking for subscription existence", e);
                }
                if (subscription != null)
                {
                    Program.Logger.Debug($"{GetType().Name}: Deleting notifications for subscription");
                    try
                    {
                        db.Notifications.RemoveRange(db.Notifications.Where(n => n.Subscription.Id == subscription.Id));
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while deleting notifications for subscription", e);
                    }

                    Program.Logger.Debug($"{GetType().Name}: Deleting subscription");
                    try
                    {
                        db.Subscriptions.Remove(subscription);
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while deleting subscription", e);
                    }

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while saving changes to database", e);
                    }
                    response = $"Вы отписались от сериала \"{show.Title}\"";
                }
                else
                {
                    response = $"Вы, братишка, не подписаны на сериал \"{show.Title}\"";
                }
            }
            return response;
        }
Ejemplo n.º 14
0
        public void SendShowsNotifications()
        {
            using (AppDbContext db = new AppDbContext())
            {
                Logger.Trace("SendShowsNotifications: Retrieving new notifications");
                List<ShowNotification> showNotifications;
                try
                {
                    showNotifications = db.ShowNotifications
                        .Where(n => !n.Notified)
                        .ToList();
                }
                catch (Exception e)
                {
                    Logger.Error(e, "SendShowsNotifications: An error occurred while retrieving new notifications");
                    return;
                }

                if (showNotifications.Count == 0)
                {
                    return;
                }

                Logger.Debug("SendShowsNotifications: Sending new notifications");
                foreach (var notification in showNotifications)
                {
                    string text = $"{notification.Show.Title} ({string.Format(SubscribeCommand.SubscribeCommandFormat, notification.Show.Id)})\n{notification.Show.Description}";
                    try
                    {
                        TelegramApi.SendMessage(notification.User.TelegramUserId, text);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "SendShowsNotifications: An error occurred while sending new notifications");
                    }

                    notification.Notified = true;
                }

                //Logger.Info($"SendShowsNotifications: {notificationDictionary.Count} new " +
                //           $"{((notificationDictionary.Count == 1) ? "notification was sent" : "notifications were sent")}");

                Logger.Trace("SendShowsNotifications: Saving changes to database");
                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    Logger.Error(e, "SendShowsNotifications: An error occurred while saving changes to database");
                }
            }
        }
Ejemplo n.º 15
0
        public override void Execute()
        {
            Show show;
            string showTitle = string.Empty;
            bool subscribeById = ShowId != null;
            if (ShowId == null)
            {
                bool showFound = RequestShow(out showTitle);
                if (!showFound)
                {
                    SendShowList(showTitle, GetMessageSize());
                }

                Status = true;
                return;
            }

            string response;
            Program.Logger.Info($"{GetType().Name}: {Message.From} is trying to subscribe to '{(subscribeById ? $"Id = {ShowId}" : showTitle)}'");
            using (AppDbContext db = new AppDbContext())
            {
                show = db.GetShowById(ShowId.Value);
                if (show == null)
                {
                    Program.Logger.Info($"{GetType().Name}: Show '{(subscribeById ? $"Id = {ShowId}" : showTitle)}' was not found");
                    response = $"Сериал '{(subscribeById ? $"Id = {ShowId}" : showTitle)}' не найден";
                    Program.Logger.Debug($"{GetType().Name}: Sending response to {Message.From}");
                    try
                    {
                        TelegramApi.SendMessage(Message.From, response);
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while sending response to {Message.From}", e);
                    }

                    Status = true;
                    return;
                }

                Program.Logger.Debug($"{GetType().Name}: Searching user with TelegramId: {Message.From.Id} in database");
                var user = db.GetUserByTelegramId(Message.From.Id);
                bool newUser = false;
                if (user == null)
                {
                    user = new User
                    {
                        TelegramUserId = Message.From.Id,
                        FirstName = Message.From.FirstName,
                        LastName = Message.From.LastName,
                        Username = Message.From.Username
                    };

                    newUser = true;
                }

                Program.Logger.Debug($"{GetType().Name}: Checking for subscription existence");
                var subscriptionExists = user.Subscriptions.Any(s => s.Show.Id == show.Id);
                if (subscriptionExists)
                {
                    Program.Logger.Info($"{GetType().Name}: User {Message.From} is already subscribed to {show.OriginalTitle}");
                    response = $"Вы уже подписаны на сериал \"{show.Title}\" ({show.SiteType.Title})";
                }
                else
                {
                    Subscribe(db, user, show, newUser);
                    response = $"Вы подписались на сериал \"{show.Title}\" ({show.SiteType.Title})";
                }

                Program.Logger.Debug($"{GetType().Name}: Saving changes to database");
                db.SaveChanges();
            }

            Program.Logger.Debug($"{GetType().Name}: Sending response to {Message.From}");
            try
            {
                TelegramApi.SendMessage(Message.From, response);
            }
            catch (Exception e)
            {
                throw new Exception($"{GetType().Name}: An error occurred while sending response to {Message.From}", e);
            }

            Status = true;
        }
Ejemplo n.º 16
0
        public override void Execute()
        {
            using (AppDbContext db = new AppDbContext())
            {
                Program.Logger.Debug($"{GetType().Name}: Retrieving notification with id: {NotificationId}");
                Notification notification = null;
                try
                {
                    notification = db.GetNotificationById(NotificationId);
                }
                catch (Exception e)
                {
                    Program.Logger.Error(e, $"{GetType().Name}: An error occurred while retrieving notification");
                }

                if (notification == null)
                {
                    Program.Logger.Debug($"{GetType().Name}: Notification with specified Id was not found");
                    Status = false;
                    return;
                }

                Program.Logger.Debug($"{GetType().Name}: Retrieving settings of {notification.Subscription.User}");
                Settings settings = null;
                try
                {
                    settings = db.GetSettingsByUser(notification.Subscription.User);
                }
                catch (Exception e)
                {
                    Program.Logger.Error(e, "An error occurred while retrieving user's settings");
                }

                if (settings == null)
                {
                    Program.Logger.Debug($"{GetType().Name}: User's settings were not found");
                    Status = false;
                    return;
                }

                ITorrentGetter torrentGetter = new LostFilmTorrentGetter();

                List<TorrentDescription> torrents = null;
                Program.Logger.Debug($"{GetType().Name}: Retrieving torrents for {notification.Episode.Show} - {notification.Episode.Title}");
                try
                {
                    torrents = torrentGetter.GetEpisodeTorrents(notification.Episode, settings.SiteLogin, settings.SitePassword);
                }
                catch (Exception e)
                {
                    Program.Logger.Error(e, $"An error occured while retrieving torrents for {notification.Episode.Show.Title} - {notification.Episode.Title}");
                    TelegramApi.SendMessage(Message.From, "(Не удалось получить список торрентов. Возможно указан неверный логин/пароль)");
                    Status = false;
                    return;
                }
                Program.Logger.Debug($"{GetType().Name}: Number of torrents: {torrents?.Count() ?? 0}");

                TorrentDescription torrent = null;
                if (torrents != null && torrents.Count() != 0)
                {
                    Program.Logger.Debug($"{GetType().Name}: Retrieving torrent with required quality ({Quality})");
                    torrent = torrents.FirstOrDefault(t => t.Quality == Quality);
                }

                if (torrent == null)
                {
                    Program.Logger.Debug($"{GetType().Name}: Torrent with required quality was not found");
                    Status = false;
                    return;
                }

                Program.Logger.Debug($"{GetType().Name}: Creating new download task");
                db.DownloadTasks.Add(new DownloadTask()
                {
                    Episode = notification.Episode,
                    User = notification.Subscription.User,
                    TorrentUrl = torrent.TorrentUri.ToString()
                });

                Program.Logger.Debug($"{GetType().Name}: Saving changes to database");
                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    throw new Exception($"{GetType().Name}: An error occurred while saving changes to database", e);
                }
                Status = true;
            }
        }
Ejemplo n.º 17
0
        private static int CreateShowNotifications()
        {
            int newNotificationsCount = 0;
            using (AppDbContext db = new AppDbContext())
            {
                Logger.Trace("UpdateNotifications: Retrieving new shows for users");
                foreach (var user in db.Users.ToList())
                {
                    var shows = db.Shows
                        .Where(show => show.DateCreated > user.DateCreated).ToList()
                        .Where(show => !db.ShowNotifications.Any(notification => notification.UserId == user.Id && notification.ShowId == show.Id))
                        .ToList();
                    if (shows.Count == 0)
                    {
                        continue;
                    }

                    var newNotifications = shows.Aggregate(
                        new List<ShowNotification>(),
                        (list, show) =>
                        {
                            list.Add(new ShowNotification() { Show = show, User = user });
                            return list;
                        });
                    db.ShowNotifications.AddRange(newNotifications);
                    newNotificationsCount += newNotifications.Count;
                }

                Logger.Trace("UpdateNotifications: Saving changes to database");
                db.SaveChanges();
            }

            return newNotificationsCount;
        }
Ejemplo n.º 18
0
        private static int CreateEpisodeNotifications()
        {
            int newNotificationsCount = 0;
            using (AppDbContext db = new AppDbContext())
            {
                Logger.Trace("UpdateNotifications: Retrieving new episodes for subscriptions");
                foreach (Subscription subscription in db.Subscriptions.ToList())
                {
                    var episodes = db.Episodes
                        .Where(episode =>
                                episode.ShowId == subscription.ShowId && episode.Date >= subscription.SubscriptionDate &&
                                episode.Notifications.Count == 0).ToList();
                    if (episodes.Count == 0)
                    {
                        continue;
                    }

                    Logger.Debug("UpdateNotifications: Creating notifications for subcription: " +
                                 $" {subscription.User} -" +
                                 $" {subscription.Show.OriginalTitle}");

                    List<Notification> newNotifications = episodes.Aggregate(
                        new List<Notification>(),
                        (list, episode) =>
                        {
                            list.Add(new Notification
                            {
                                Episode = episode,
                                Subscription = subscription
                            });
                            return list;
                        });

                    db.Notifications.AddRange(newNotifications);
                    newNotificationsCount += newNotifications.Count;
                }

                Logger.Trace("UpdateNotifications: Saving changes to database");
                db.SaveChanges();
            }

            return newNotificationsCount;
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            Logger.Info($"TorrentDownloader started: {Assembly.GetEntryAssembly().Location}");
            ITorrentDownloader downloader = new TransmissionDownloader();
            int updateInterval;
            try
            {
                updateInterval = int.Parse(ConfigurationManager.AppSettings["UpdateInterval"]) * 1000;
            }
            catch (Exception e)
            {
                Logger.Fatal(e, "An error occurred while loading update interval");
                return;
            }

            do
            {
                using (AppDbContext db = new AppDbContext())
                {
                    var downloadTasks = db.DownloadTasks
                        .Where(d => !d.DownloadStarted)
                        .ToList();

                    if (downloadTasks.Count != 0)
                    {
                        Logger.Debug($"Awaiting download tasks number: {downloadTasks.Count}");
                    }

                    foreach (var downloadTask in downloadTasks)
                    {
                        Settings setting;
                        try
                        {
                            setting = db.GetSettingsByUser(downloadTask.User);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e, $"An error occurred while loading settings of {downloadTask.User}");
                            continue;
                        }
                        if (setting == null)
                        {
                            Logger.Debug($"Settings of {downloadTask.User} was not found");
                            continue;
                        }

                        bool downloadStarted;
                        Logger.Debug($"Downloading torrent {downloadTask.TorrentUrl}");
                        try
                        {
                            downloadStarted = downloader.Download(new Uri(downloadTask.TorrentUrl), new Uri(setting.WebUiUrl), setting.WebUiPassword);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e, "An error occurred while downloading torrent");
                            downloadStarted = false;
                        }

                        downloadTask.DownloadStarted = downloadStarted;
                        db.SaveChanges();
                    }
                }
                Thread.Sleep(updateInterval);
            } while (true);
        }
Ejemplo n.º 20
0
        public void SendEpisodesNotifications()
        {
            using (AppDbContext db = new AppDbContext())
            {
                Logger.Trace("SendEpisodesNotifications: Retrieving new notifications");
                List<Notification> notifications;
                try
                {
                    notifications = db.Notifications
                        .Where(n => !n.Notified)
                        .ToList();
                }
                catch (Exception e)
                {
                    Logger.Error(e, "SendEpisodesNotifications: An error occurred while retrieving new notifications");
                    return;
                }

                if (notifications.Count == 0)
                {
                    return;
                }

                Dictionary<User, List<Notification>> notificationDictionary =
                    notifications.Aggregate(
                        new Dictionary<User, List<Notification>>(),
                        (d, notification) =>
                        {
                            if (d.ContainsKey(notification.Subscription.User))
                            {
                                d[notification.Subscription.User].Add(notification);
                            }
                            else
                            {
                                d.Add(notification.Subscription.User, new List<Notification>() {notification});
                            }
                            return d;
                        }
                        );

                Logger.Debug("SendEpisodesNotifications: Sending new notifications");
                foreach (var userNotifications in notificationDictionary)
                {
                    string text = string.Empty;
                    foreach (Notification notification in userNotifications.Value)
                    {
                        text += notification.Subscription.Show.Title + " - " + notification.Episode.Title;
                        Settings settings = db.GetSettingsByUser(userNotifications.Key);
                        if (settings != null)
                        {
                            ITorrentGetter torrentGetter = new LostFilmTorrentGetter();

                            try
                            {
                                List<TorrentDescription> torrents = torrentGetter.GetEpisodeTorrents(notification.Episode, settings.SiteLogin, settings.SitePassword);
                                if (torrents.Count != 0)
                                {
                                    text += " (" +
                                            torrents.Select(t => t.Quality)
                                                .Aggregate(string.Empty,
                                                    (s, s1) =>
                                                        s + " " +
                                                        string.Format(DownloadCommand.DownloadCommandFormat, notification.Id, s1))
                                            + ")";
                                }
                            }
                            catch (Exception e)
                            {
                                Logger.Error(e, $"SendEpisodesNotifications: An error occured while retrieving torrents for {notification.Episode.Show.Title} - {notification.Episode.Title}");
                                text += "(Не удалось получить список торрентов. Возможно указан неверный логин/пароль)";
                            }

                            text += "\n";
                        }
                    }

                    try
                    {
                        TelegramApi.SendMessage(userNotifications.Key.TelegramUserId, text);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "SendEpisodesNotifications: An error occurred while sending new notifications");
                    }
                }

                Logger.Info($"SendEpisodesNotifications: {notificationDictionary.Count} new " +
                            $"{((notificationDictionary.Count == 1) ? "notification was sent" : "notifications were sent")}");

                Logger.Debug("SendEpisodesNotifications: Marking new notifications as notified");
                try
                {
                    notifications.ForEach(
                        notification => { db.Notifications.First(n => n.Id == notification.Id).Notified = true; }
                        );
                }
                catch (Exception e)
                {
                    Logger.Error(e, "SendEpisodesNotifications: An error occurred while marking new notifications as notified");
                }

                Logger.Trace("SendEpisodesNotifications: Saving changes to database");
                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    Logger.Error(e, "SendEpisodesNotifications: An error occurred while saving changes to database");
                }
            }
        }
Ejemplo n.º 21
0
        private static int CreateShowNotifications()
        {
            int newNotificationsCount = 0;
            using (AppDbContext db = new AppDbContext())
            {
                Logger.Trace("UpdateNotifications: Retrieving users");

                List<User> users;
                try
                {
                    users = db.Users.ToList();
                }
                catch (Exception e)
                {
                    Logger.Error(e, "UpdateNotifications: An error occurred while retrieving users");
                    return 0;
                }

                Logger.Trace("UpdateNotifications: Retrieving new shows for users");
                foreach (var user in users)
                {
                    List<Show> shows;
                    try
                    {
                        shows = db.Shows
                            .Where(s => s.DateCreated > user.DateCreated &&
                                        !db.ShowNotifications.Any(n => n.User.Id == user.Id && n.Show.Id == s.Id))
                            .ToList();
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, $"UpdateNotifications: An error occurred while retrieving new shows for user: {user}");
                        continue;
                    }

                    if (shows.Count == 0)
                    {
                        continue;
                    }

                    List<ShowNotification> newNotifications;
                    try
                    {
                        newNotifications = shows.Aggregate(
                            new List<ShowNotification>(), (list, show) =>
                            {
                                list.Add(new ShowNotification() { Show = show, User = user });
                                return list;
                            });
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, $"UpdateNotifications: An error occurred while creating new notifications for user: {user}");
                        continue;
                    }

                    db.ShowNotifications.AddRange(newNotifications);
                    newNotificationsCount += newNotifications.Count;
                }
                Logger.Trace("UpdateNotifications: Saving changes to database");
                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    Logger.Error(e, "UpdateNotifications: An error occurred while saving changes to database");
                }
            }
            return newNotificationsCount;
        }
Ejemplo n.º 22
0
        private static int CreateEpisodeNotifications()
        {
            int newNotificationsCount = 0;
            using (AppDbContext db = new AppDbContext())
            {
                Logger.Trace("UpdateNotifications: Retrieving subscriptions");
                List<Subscription> subscriptions;
                try
                {
                    subscriptions = db.Subscriptions.ToList();
                }
                catch (Exception e)
                {
                    Logger.Error(e, "UpdateNotifications: An error occurred while retrieving subscriptions");
                    return 0;
                }

                Logger.Trace("UpdateNotifications: Retrieving new episodes for subscriptions");
                foreach (Subscription subscription in subscriptions)
                {
                    if (subscription.User == null || subscription.Show == null)
                    {
                        continue;
                    }

                    IQueryable<Notification> notifications;
                    try
                    {
                        notifications = db.Notifications
                            .Where(n => n.Subscription.Id == subscription.Id);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e,
                            "UpdateNotifications: An error occurred while retrieving notifications for subscription: " +
                            $" {subscription.User} -" +
                            $" {subscription.Show.OriginalTitle}");
                        continue;
                    }

                    List<Episode> episodes;
                    try
                    {
                        episodes = db.Episodes
                            .Where(s => s.Show.Id == subscription.Show.Id && s.Date >= subscription.SubscriptionDate &&
                                        !notifications.Any(n => n.Episode.Id == s.Id))
                            .Select(s => s).ToList();
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "UpdateNotifications: An error occurred while retrieving episodes");
                        continue;
                    }

                    if (episodes.Count == 0)
                    {
                        continue;
                    }

                    Logger.Debug("UpdateNotifications: Creating notifications for subcription: " +
                                 $" {subscription.User} -" +
                                 $" {subscription.Show.OriginalTitle}");

                    List<Notification> newNotifications = episodes.Aggregate(
                        new List<Notification>(),
                        (list, episode) =>
                        {
                            list.Add(new Notification
                            {
                                Episode = episode,
                                Subscription = subscription
                            });
                            return list;
                        }
                        );

                    try
                    {
                        db.Notifications.AddRange(newNotifications);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "UpdateNotifications: An error occurred while creating notifications");
                    }

                    newNotificationsCount += newNotifications.Count;
                }

                Logger.Trace("UpdateNotifications: Saving changes to database");
                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    Logger.Error(e, "UpdateNotifications: An error occurred while saving changes to database");
                }
            }
            return newNotificationsCount;
        }
Ejemplo n.º 23
0
        private static void UpdateEpisodes(List<Show> shows)
        {
            using (var db = new AppDbContext())
            {
                foreach (var show in shows)
                {
                    var dbShow = db.GetShowByTitle(show.SiteTypeId, show.Title);
                    if (dbShow != null)
                    {
                        foreach (var episode in show.Episodes)
                        {
                            dbShow.Episodes.Add(episode);
                        }
                    }
                    else
                    {
                        db.Shows.Add(show);
                    }

                    Logger.Info($"{show.Title} - {string.Join(", ", show.Episodes.Select(e => e.Title))}");
                }

                db.SaveChanges();
            }
        }
Ejemplo n.º 24
0
        public override void Execute()
        {
            string response;
            using (var db = new AppDbContext())
            {
                do
                {
                    Program.Logger.Debug($"{GetType().Name}: Searching user with TelegramId: {Message.From.Id} in database");
                    var user = db.GetUserByTelegramId(Message.From.Id);
                    if (user == null)
                    {
                        Program.Logger.Debug($"{GetType().Name}: User with TelegramId: {Message.From.Id} is not found");
                        response = "Вы не подписаны ни на один сериал";
                        break;
                    }

                    var subscriptions = user.Subscriptions;
                    if (!subscriptions.Any())
                    {
                        Program.Logger.Debug($"{GetType().Name}: {user} has no subscriptions");
                        response = "Вы не подписаны ни на один сериал";
                        break;
                    }

                    Program.Logger.Debug($"{GetType().Name}: Sending the confirmation message to {user}");
                    try
                    {
                        TelegramApi.SendMessage(Message.From, "Вы действительно хотите отписаться от всех сериалов?\n/yes /no");
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while sending the confirmation message to {user}", e);
                    }

                    Program.Logger.Debug($"{GetType().Name}: Waiting for a message that contains confirmation");
                    Message msg;
                    try
                    {
                        msg = TelegramApi.WaitForMessage(Message.From);
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while waiting for a message that contains confirmation", e);
                    }

                    if (msg.Text.ToLower() != "/yes")
                    {
                        Program.Logger.Debug($"{GetType().Name}: {user} cancel command");
                        Status = true;
                    }

                    Program.Logger.Debug($"{GetType().Name}: Deleting notifications for all subscriptions");
                    foreach (var subscription in subscriptions)
                    {
                        db.Notifications.RemoveRange(db.Notifications.Where(n => n.Subscription.Id == subscription.Id));
                    }

                    Program.Logger.Debug($"{GetType().Name}: Deleting all subscriptions");
                    db.Subscriptions.RemoveRange(subscriptions);
                    response = "Вы отписались от всех сериалов";
                }
                while (false);

                Program.Logger.Debug($"{GetType().Name}: Saving changes to database");
                db.SaveChanges();
            }

            Program.Logger.Debug($"{GetType().Name}: Sending response to {Message.From}");
            try
            {
                TelegramApi.SendMessage(Message.From, response);
            }
            catch (Exception e)
            {
                throw new Exception($"{GetType().Name}: An error occurred while sending response to {Message.From}", e);
            }

            Status = true;
        }
Ejemplo n.º 25
0
        public override void Execute()
        {
            Show show;
            string showTitle = string.Empty;
            bool subscribeById = ShowId != null;
            if (ShowId == null)
            {
                int messageSize;
                int.TryParse(Arguments, out messageSize);
                if (messageSize == 0)
                {
                    messageSize = MaxPageSize;
                }
                messageSize = Math.Min(messageSize, MaxPageSize);

                ShowId = RequestShow(out showTitle);
                if (ShowId == null)
                {
                    SendShowList(showTitle, messageSize);
                    Status = true;
                    return;
                }
            }

            string response;
            Program.Logger.Info($"{GetType().Name}: {Message.From} is trying to subscribe to '{(subscribeById ? $"Id = {ShowId}" : showTitle)}'");
            using (AppDbContext db = new AppDbContext())
            {
                show = db.GetShowById(ShowId.Value);
                if (show == null)
                {
                    Program.Logger.Info($"{GetType().Name}: Show '{(subscribeById ? $"Id = {ShowId}" : showTitle)}' was not found");
                    response = $"Сериал '{(subscribeById ? $"Id = {ShowId}" : showTitle)}' не найден";
                    Program.Logger.Debug($"{GetType().Name}: Sending response to {Message.From}");
                    try
                    {
                        TelegramApi.SendMessage(Message.From, response);
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while sending response to {Message.From}", e);
                    }
                    Status = true;
                    return;
                }

                Program.Logger.Debug($"{GetType().Name}: Searching user with TelegramId: {Message.From.Id} in database");
                User user;
                try
                {
                    user = db.GetUserByTelegramId(Message.From.Id);
                }
                catch (Exception e)
                {
                    throw new Exception($"{GetType().Name}: An error occurred while searching user in database", e);
                }
                bool newUser = false;
                if (user == null)
                {
                    user = new User
                    {
                        TelegramUserId = Message.From.Id,
                        FirstName = Message.From.FirstName,
                        LastName = Message.From.LastName,
                        Username = Message.From.Username
                    };
                    newUser = true;
                }

                if (newUser)
                {
                    Program.Logger.Info($"{GetType().Name}: {user} is new User");
                }
                else
                {
                    Program.Logger.Debug($"{GetType().Name}: User {user} is already exist");
                }

                bool subscriptionExists;
                Program.Logger.Debug($"{GetType().Name}: Checking for subscription existence");
                try
                {
                    subscriptionExists = user.Subscriptions.Any(s => s.Show.Id == show.Id);
                }
                catch (Exception e)
                {
                    throw new Exception($"{GetType().Name}: An error occurred while checking for subscription existence", e);
                }
                if (subscriptionExists)
                {
                    Program.Logger.Info($"{GetType().Name}: User {Message.From} is already subscribed to {show.OriginalTitle}");
                    response = $"Вы уже подписаны на сериал '{show.Title}'";
                }
                else
                {
                    Subscription subscription = new Subscription
                    {
                        User = user,
                        Show = show,
                        SubscriptionDate = DateTimeOffset.Now
                    };

                    if (newUser)
                    {
                        user.Subscriptions.Add(subscription);
                        db.Users.Add(user);
                    }
                    else
                    {
                        db.Subscriptions.Add(subscription);
                    }
                    response = $"Вы подписались на сериал '{show.Title}'";
                }

                Program.Logger.Debug($"{GetType().Name}: Saving changes to database");
                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    throw new Exception($"{GetType().Name}: An error occurred while saving changes to database", e);
                }
            }

            Program.Logger.Debug($"{GetType().Name}: Sending response to {Message.From}");
            try
            {
                TelegramApi.SendMessage(Message.From, response);
            }
            catch (Exception e)
            {
                throw new Exception($"{GetType().Name}: An error occurred while sending response to {Message.From}", e);
            }

            Status = true;
        }
Ejemplo n.º 26
0
        static void Main()
        {
            Logger.Info($"Scraper started: {Assembly.GetEntryAssembly().Location}");

            if (!LoadSettings())
            {
                return;
            }

            using (var db = new AppDbContext())
            {
                int lastId;
                Logger.Debug("Retrieving last episode Id from database");
                try
                {
                    lastId = db.Episodes?.OrderByDescending(s => s.SiteId).FirstOrDefault()?.SiteId ?? 14468;
                }
                catch (Exception e)
                {
                    Logger.Error(e, "An error occurred while retrieving last episode Id");
                    return;
                }

                Scraper scraper = new LostFilmScraper(@"https://www.lostfilm.tv/browse.php",
                    @"http://www.lostfilm.tv/serials.php", lastId);

                List<Show> showsList;
                Logger.Debug($"Retrieving shows from {scraper.SiteTitle}");
                try
                {
                    showsList = scraper.LoadShows();
                }
                catch (Exception e)
                {
                    Logger.Error(e, $"An error occurred while retrieving shows from {scraper.SiteTitle}");
                    return;
                }

                int newShowsCount = 0;
                try
                {
                    foreach (var showTuple in showsList)
                    {
                        if (db.Shows.Any(s => s.Title == showTuple.Title))
                        {
                            db.Shows.First(s => s.Title == showTuple.Title).OriginalTitle = showTuple.OriginalTitle;
                        }
                        else
                        {
                            db.Shows.Add(new Show
                            {
                                Title = showTuple.Title,
                                OriginalTitle = showTuple.OriginalTitle
                            });
                            newShowsCount++;
                        }
                    }
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    Logger.Error(e, "An error occurred while adding new shows to database");
                }

                if (newShowsCount > 0)
                {
                    Logger.Info($"{newShowsCount} new {(newShowsCount == 1 ? "show" : "shows")} added");
                }

                while (true)
                {
                    List<Show> shows;
                    Logger.Trace($"Retrieving new episodes from {scraper.SiteTitle}");
                    try
                    {
                        shows = scraper.Load();
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, $"An error occurred while retrieving new episodes from {scraper.SiteTitle}");
                        shows = new List<Show>();
                    }

                    newShowsCount = 0;
                    int newEpisodesCount = 0;
                    foreach (var show in shows)
                    {
                        if (db.Shows.Any(s => s.Title == show.Title))
                        {
                            db.Shows.First(s => s.Title == show.Title)
                                .Episodes.AddRange(show.Episodes);
                        }
                        else
                        {
                            db.Shows.Add(show);
                            newShowsCount++;
                        }
                        newEpisodesCount += show.Episodes.Count;

                        Logger.Info($"{show.Title} - {string.Join(", ", show.Episodes.Select(e => e.Title))}");
                    }

                    if (newShowsCount > 0)
                    {
                        Logger.Info($"{newShowsCount} new {(newShowsCount == 1 ? "show" : "shows")} added");
                    }
                    if (newEpisodesCount > 0)
                    {
                        Logger.Info($"{newEpisodesCount} new {(newEpisodesCount == 1 ? "episode" : "episodes")} added");
                    }

                    Logger.Trace("Saving changes to database");
                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "An error occurred while saving changes to database");
                    }

                    Thread.Sleep(TimeSpan.FromMinutes(_updateInterval));
                }
            }
        }
Ejemplo n.º 27
0
        public async Task <ActionResult> OnGetAsync(int?foodItemId, int?personId, int?removeItemId, string?search, string?toDoActionReset)
        {
            if (toDoActionReset == "Reset")
            {
                Search = "";
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(search))
                {
                    Search = search.Trim();
                }
            }
            var itemsQuery = _context.FoodItems.Include(o => o.Category).AsQueryable();

            if (!string.IsNullOrWhiteSpace(Search))
            {
                if (Search.Contains("%21"))
                {
                    itemsQuery = itemsQuery.Where(b =>
                                                  !b.FoodItemName.Contains(Search) ||
                                                  !b.Category.CategoryName.Contains(Search));
                }
                else
                {
                    itemsQuery = itemsQuery.Where(b =>
                                                  b.FoodItemName.Contains(Search) ||
                                                  b.Category.CategoryName.Contains(Search));
                }
            }

            SavedPersonId = personId.Value;
            if (removeItemId.HasValue)
            {
                var dOrderItems = _context.OrderItems.First(n => n.OrderItemId == removeItemId && n.PersonId == personId);
                _context.Attach(dOrderItems);
                _context.Remove(dOrderItems);
                _context.SaveChanges();
            }
            if (!foodItemId.Equals(null) && personId.HasValue)
            {
                var newFoodItem  = _context.FoodItems.First(n => n.FoodItemId == foodItemId);
                var newOrderItem = new OrderItem()
                {
                    PersonId   = personId.Value,
                    FoodItem   = newFoodItem,
                    FoodItemId = newFoodItem.FoodItemId,
                    Sum        = newFoodItem.Price
                };
                _context.OrderItems.Add(newOrderItem);
                await _context.SaveChangesAsync();
            }

            itemsQuery = itemsQuery.OrderBy((b => b.Category.CategoryId));
            Items      = await itemsQuery.ToListAsync();

            //var orderedItem = _context.OrderItems.First(n => n.OrderItemId == orderItemId);
            //var personId = orderedItem.PersonId;

            var orderedItemsQuery =
                _context.OrderItems
                .Where(n => n.PersonId == personId)
                .AsQueryable()
                .Include(o => o.FoodItem)
                .Include(o => o.FoodItem.Category);

            OrderedItems = await orderedItemsQuery.ToListAsync();

            return(Page());
        }
Ejemplo n.º 28
0
        public override void Execute()
        {
            using (AppDbContext db = new AppDbContext())
            {
                Settings settings = null;
                Program.Logger.Debug($"{GetType().Name}: Searching user's settings in database");
                try
                {
                    settings = db.GetSettingsByUser(db.GetUserByTelegramId(Message.From.Id));
                }
                catch (Exception e)
                {
                    Program.Logger.Error(e, $"{GetType().Name}: An error occurred while searching user's settings in database");
                }

                string text =
                    $"{(String.IsNullOrEmpty(settings?.WebUiUrl) ? "*" : String.Empty)}Адрес web-интерфейса uTorrent: {WebUiUrlSetCommand}\n" +
                    $"{(String.IsNullOrEmpty(settings?._WebUiPassword) ? "*" : String.Empty)}Пароль web-интерфейса uTorrent: {WebUiPasswordSetCommand}\n" +
                    $"{(String.IsNullOrEmpty(settings?.SiteLogin) ? "*" : String.Empty)}Имя учетной записи LostFilm.tv: {SiteLoginSetCommand}\n" +
                    $"{(String.IsNullOrEmpty(settings?._SitePassword) ? "*" : String.Empty)}Пароль учетной записи LostFilm.tv: {SitePasswordSetCommand}\n" +
                    $"Сохранить настройки: {SaveSettingsCommand}\n" +
                    $"Выйти без сохранения изменений: {CancelCommand}";

                Program.Logger.Debug($"{GetType().Name}: Sending commands list");
                try
                {
                    TelegramApi.SendMessage(Message.From, text);
                }
                catch (Exception e)
                {
                    throw new Exception($"{GetType().Name}: An error occurred while sending commands list", e);
                }

                bool newSettings = false;
                if (settings == null)
                {
                    Program.Logger.Debug($"{GetType().Name}: Creating new settings for {Message.From}");
                    newSettings = true;
                    settings = new Settings {User = db.GetUserByTelegramId(Message.From.Id)};
                }

                Message msg;
                do
                {
                    Program.Logger.Debug($"{GetType().Name}: Waiting for a command");
                    try
                    {
                        msg = TelegramApi.WaitForMessage(Message.From);
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while waiting for a command", e);
                    }

                    switch (msg.Text)
                    {
                        case WebUiUrlSetCommand:
                            Program.Logger.Debug($"{GetType().Name}: {WebUiUrlSetCommand} command received");
                            settings.WebUiUrl = TelegramApi.WaitForMessage(Message.From).Text;
                            break;
                        case WebUiPasswordSetCommand:
                            Program.Logger.Debug($"{GetType().Name}: {WebUiPasswordSetCommand} command received");
                            settings.WebUiPassword = TelegramApi.WaitForMessage(Message.From).Text;
                            break;
                        case SiteLoginSetCommand:
                            Program.Logger.Debug($"{GetType().Name}: {SiteLoginSetCommand} command received");
                            settings.SiteLogin = TelegramApi.WaitForMessage(Message.From).Text;
                            break;
                        case SitePasswordSetCommand:
                            Program.Logger.Debug($"{GetType().Name}: {SitePasswordSetCommand} command received");
                            settings.SitePassword = TelegramApi.WaitForMessage(Message.From).Text;
                            break;
                        case SaveSettingsCommand:
                            Program.Logger.Debug($"{GetType().Name}: {SaveSettingsCommand} command received");
                            break;
                        case CancelCommand:
                            Program.Logger.Debug($"{GetType().Name}: {CancelCommand} command received");
                            break;
                        default:
                            Program.Logger.Debug($"{GetType().Name}: Unknown command received");
                            TelegramApi.SendMessage(Message.From, "Пощади, братишка");
                            break;
                    }
                } while (msg.Text != SaveSettingsCommand && msg.Text != CancelCommand);

                if (msg.Text == SaveSettingsCommand)
                {
                    Program.Logger.Debug($"{GetType().Name}: Saving changes to database");
                    try
                    {
                        if (newSettings)
                        {
                            db.Settings.Add(settings);
                        }
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while saving changes to database", e);
                    }
                }
                else
                {
                    Program.Logger.Debug($"{GetType().Name}: Exiting without saving changes to database");
                }
            }
            Status = true;
        }