private static int GetLastStoredEpisodeId(string siteTypeName) { using (var db = new AppDbContext()) { return db.Episodes?.Where(e => e.Show.SiteType.Name == siteTypeName).Max(e => (int?)e.SiteId) ?? LastStoredEpisodesId[siteTypeName]; } }
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; }
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; }
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(); } }
public override void Execute() { using (var db = new AppDbContext()) { User user = db.GetUserByTelegramId(Message.From.Id); if (user == null || !user.Subscriptions.Any()) { SendResponse("Вы не подписаны ни на один сериал"); Status = true; return; } if (ShowId != null) { var show = db.GetShowById(ShowId.Value); if (show == null) { SendResponse($"Сериал с идентификатором {ShowId} не найден"); } else { var response = Unsubscribe(user, show); SendResponse(response); } } else { SendSubscriptions(user, GetMessageSize()); } } Status = true; }
public override void Execute() { Program.Logger.Debug($"{GetType().Name}: Parsing message size. Arguments: {Arguments}"); int messageSize; int.TryParse(Arguments, out messageSize); if (messageSize == 0) { messageSize = MaxPageSize; } messageSize = Math.Min(messageSize, MaxPageSize); Program.Logger.Debug($"{GetType().Name}: Message size: {messageSize}"); List<string> shows; Program.Logger.Debug($"{GetType().Name}: Retrieving shows list"); using (var db = new AppDbContext()) { try { shows = db.Shows.Select(s => s.Title + " (" + s.OriginalTitle + ")").ToList(); } catch (Exception e) { throw new Exception($"{GetType().Name}: An error occurred while retrieving shows list", e); } } List<string> pages = GetPages(shows, messageSize); SendPages(pages); Status = true; }
public override void Execute() { User user; List<Show> userShows = null; using (var db = new AppDbContext()) { Program.Logger.Debug( $"{GetType().Name}: Searching user with TelegramId: {Message.From.Id} in database"); try { user = db.GetUserByTelegramId(Message.From.Id); } catch (Exception e) { throw new Exception($"{GetType().Name}: An error occurred while searching user in database", e); } if (user == null) { Program.Logger.Debug($"{GetType().Name}: User {Message.From} is not exists"); } else { Program.Logger.Debug($"{GetType().Name}: Retrieving user's subscriptions"); try { userShows = db.Subscriptions .Where(s => s.User.Id == user.Id) .Select(s => s.Show) .ToList(); } catch (Exception e) { throw new Exception($"{GetType().Name}: An error occurred while retrieving user's subscriptions", e); } } } if (userShows == null || userShows.Count == 0) { 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; return; } List<string> pages = GetPages(userShows.Select(s => $"- {s.Title} ({s.OriginalTitle})").ToList(), MaxPageSize); SendPages(pages); Status = true; }
public LostFilmScraper(long lastStoredEpisodeId) : base(lastStoredEpisodeId) { SiteTitle = "LostFilm.TV"; SiteEncoding = Encoding.GetEncoding(1251); using (var db = new AppDbContext()) { ShowsSiteType = db.GetSiteTypeByName("lostfilm"); } }
public NewStudioScraper(long lastStoredEpisodeId) : base(lastStoredEpisodeId) { SiteTitle = "NewStudio.TV"; SiteEncoding = Encoding.UTF8; using (var db = new AppDbContext()) { ShowsSiteType = db.GetSiteTypeByName("newstudio"); } }
public override void Execute() { string response = null; do { User user = GetUser(Message.From); if (user == null || !UserHasSubscriptions(user)) { response = "Вы не подписаны ни на один сериал"; break; } if (ShowId != null) { Show show; using (AppDbContext db = new AppDbContext()) { show = db.GetShowById(ShowId.Value); } if (show == null) { response = $"Сериал с идентификатором {ShowId} не найден"; break; } response = Unsubscribe(user, show); } else { int messageSize; int.TryParse(Arguments, out messageSize); if (messageSize == 0) { messageSize = MaxPageSize; } messageSize = Math.Min(messageSize, MaxPageSize); SendSubscriptions(user, messageSize); } } while (false); if (!string.IsNullOrEmpty(response)) { 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; }
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; }
public override async Task<List<Show>> LoadShows() { var doc = await DownloadDocument(ShowsListUrl); var showNodes = doc.DocumentNode.SelectNodes(@"//div[@id='serialist']//li//a"); var shows = showNodes.Select(n => new Show() { SiteId = int.Parse(IdRegex.Match(n.Attributes["href"].Value).Groups[1].Value), Title = WebUtility.HtmlDecode(n.InnerText), SiteTypeId = ShowsSiteType.Id }).ToList(); using (var db = new AppDbContext()) { foreach (var show in shows) { var dbShow = db.Shows.FirstOrDefault(s => s.Title == show.Title); show.OriginalTitle = dbShow?.OriginalTitle ?? GetOriginalTitle(show.SiteId); show.Description = dbShow?.Description ?? GetDescription(show.SiteId); } } return shows; }
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; }
public DetailsModel(DAL.AppDbContext context) { _context = context; }
public EditModel(DAL.AppDbContext context) { _context = context; }
private User GetUser(Telegram.User user) { using (AppDbContext db = new AppDbContext()) { Program.Logger.Debug($"{GetType().Name}: Searching user with TelegramId: {user.Id} in database"); try { return db.GetUserByTelegramId(user.Id); } catch (Exception e) { throw new Exception($"{GetType().Name}: An error occurred while searching user in database", e); } } }
public PlayGameModel(AppDbContext context) { _context = context; Game = new GameEngine.Game(_context); }
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"); } } }
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(); } }
private void SendShowList(string showTitle, int messageSize) { using (AppDbContext db = new AppDbContext()) { List<Show> shows; try { shows = db.GetShowsFuzzy(showTitle); } catch (Exception e) { throw new Exception($"{GetType().Name}: An error occurred while retrieving fuzzy shows list", e); } List<string> showsList = shows.Select(show => $"{string.Format(SubscribeCommandFormat, show.Id)} {show.Title} ({show.OriginalTitle})").ToList(); List<string> pages = GetPages(showsList, messageSize); SendPages(pages); } }
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; }
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)); } } }
public IndexModel(DAL.AppDbContext context) { _context = context; }
public Load(AppDbContext context) { _context = context; Engine = new Engine(_context); }
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"); } } }
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; }
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; }
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(); } }
public Ingredients(AppDbContext context) { _context = context; }
public DeleteModel(DAL.AppDbContext context) { _context = context; }
private void SendSubscriptions(User user, int messageSize) { List<string> showsList; using (AppDbContext db = new AppDbContext()) { List<Show> shows = db.Subscriptions .Where(s => s.User.Id == user.Id) .Select(s => s.Show) .ToList(); showsList = shows.Select(s => $"{string.Format(UnsubscribeCommandFormat, s.Id)} {s.Title} ({s.OriginalTitle})").ToList(); } List<string> pagesList = GetPages(showsList, messageSize); SendPages(pagesList); }
private int? RequestShow(out string showTitle) { if (string.IsNullOrEmpty(Arguments)) { Program.Logger.Debug($"{GetType().Name}: Sending 'Enter show title' prompt"); try { TelegramApi.SendMessage(Message.From, "Введите название сериала"); } catch (Exception e) { throw new Exception($"{GetType().Name}: An error occurred while sending prompt", e); } Program.Logger.Debug($"{GetType().Name}: Waiting for a message that contains show title"); try { showTitle = TelegramApi.WaitForMessage(Message.From).Text; } catch (Exception e) { throw new Exception($"{GetType().Name}: An error occurred while waiting for a message that contains show title", e); } } else { showTitle = Arguments; } Show show; using (AppDbContext db = new AppDbContext()) { Program.Logger.Debug($"{GetType().Name}: Searching show {showTitle} in database"); try { show = db.GetShowByTitle(showTitle); } catch (Exception e) { throw new Exception($"{GetType().Name}: An error occurred while searching show {showTitle} in database", e); } } return show?.Id; }
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; }
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; }
private bool UserHasSubscriptions(User user) { if (user == null) { Program.Logger.Debug($"{GetType().Name}: User {Message.From} is not exists"); return false; } bool userHasSubscriptions; using (AppDbContext db = new AppDbContext()) { Program.Logger.Debug($"{GetType().Name}: Checking if user has subscriptions"); try { userHasSubscriptions = db.Subscriptions.Any(s => s.User.Id == user.Id); } catch (Exception e) { throw new Exception($"{GetType().Name}: An error occurred while checking if user has subscriptions", e); } } return userHasSubscriptions; }
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); }
public CreateModel(DAL.AppDbContext context) { _context = context; }
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; } }
public IndexModel(ILogger <IndexModel> logger, AppDbContext context) { _logger = logger; _context = context; }