Beispiel #1
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;
        }
Beispiel #2
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();
            }
        }
        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;
            }
        }
Beispiel #4
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);
        }
Beispiel #5
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");
                }
            }
        }
        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;
        }