public void AddBooking(string client, string phone, int numTickets, Trip trip, Account account)
        {
            LOGGER.InfoFormat("adding booking for client {0}  fo trip {1} tickets {2}", client, trip, numTickets);
            EnsureConnected();
            TripDto    t = new TripDto(trip.Id, trip.Landmark, trip.CompanyName, trip.DepartureTime, trip.Price, trip.AvailablePlaces);
            AccountDto a = new AccountDto(account.Id, account.Name, account.Password);
            Request    r = new Request()
            {
                Type = RequestType.ADD_BOOKING,
                Data = new BookingDto(client, phone, numTickets, t, a)
            };

            SendRequest(r);
            Response response = ReadResponse();

            LOGGER.InfoFormat("response for add booking {0}", response);
            if (response.Type == ResponseType.OK)
            {
                LOGGER.Info("booking added");
                return;
            }
            if (response.Type == ResponseType.ERROR)
            {
                String err = response.Data.ToString();
                LOGGER.Info("received ERROR response " + err);
                throw new ServiceException(err);
            }
        }
        private void CopyOrMove(string fromDirectpry, string toDirectory)
        {
            DirectoryInfo target = new DirectoryInfo(toDirectory);

            if (target.Exists)
            {
                if (target.GetFiles().Any(x => x.IsMovieFile()))
                {
                    throw new FixCheckException("Target location has movie files - not copying just in case");
                }

                //Copy files
                foreach (var file in Directory.EnumerateFiles(fromDirectpry))
                {
                    string destFile = Path.Combine(toDirectory, Path.GetFileName(file));
                    if (!File.Exists(destFile))
                    {
                        File.Move(file, destFile);
                    }
                    LOGGER.Info($"Moved {file} to {destFile}");
                }

                if (Directory.IsEmpty(fromDirectpry))
                {
                    Directory.Delete(fromDirectpry, true);
                    LOGGER.Info($"Deleted empty directory {fromDirectpry}");
                }
                return;
            }

            Directory.Move(fromDirectpry, toDirectory);
            LOGGER.Info($"Moved whole directory {fromDirectpry} to {toDirectory}");
        }
Example #3
0
        public override bool Go(TVRenameStats stats)
        {
            //if the directory is the root download folder do not delete
            if (TVSettings.Instance.MonitorFolders &&
                TVSettings.Instance.DownloadFolders.Contains(toRemove.FullName))
            {
                Error     = true;
                ErrorText = $@"Not removing {toRemove.FullName} as it is a Search Folder";
                return(false);
            }

            try
            {
                if (toRemove.Exists)
                {
                    DeleteOrRecycleFolder(toRemove);
                    if (Tidyup != null && Tidyup.DeleteEmpty)
                    {
                        LOGGER.Info($"Testing {toRemove.Parent.FullName } to see whether it should be tidied up");
                        DoTidyup(toRemove.Parent);
                    }
                }
            }
            catch (Exception e)
            {
                Error     = true;
                ErrorText = e.Message;
                LastError = e;
            }
            Done = true;
            return(!Error);
        }
Example #4
0
 private static void AddFile(string torrentName, string url)
 {
     try
     {
         using (HttpClient client = new HttpClient())
         {
             MultipartFormDataContent m = new MultipartFormDataContent();
             m.AddFile("torrents", torrentName, "application/x-bittorrent");
             HttpResponseMessage response = client.PostAsync(url, m).Result;
             if (!response.IsSuccessStatusCode)
             {
                 LOGGER.Warn(
                     $"Tried to download {torrentName} from file to qBitTorrent via {url}. Got following response {response.StatusCode}");
             }
             else
             {
                 LOGGER.Info(
                     $"Started download of {torrentName} via file to qBitTorrent using {url}. Got following response {response.StatusCode}");
             }
         }
     }
     catch (WebException wex)
     {
         LOGGER.Warn(
             $"Could not connect to {wex.Response.ResponseUri} to download {torrentName}, Please check qBitTorrent Settings and ensure qBitTorrent is running with no password required for local connections : {wex.Message}");
     }
 }
Example #5
0
            public List <string> CreateSpectograms(string audioFilePath)
            {
                LOGGER.Info("Reading audio file.");
                List <string> result = new List <string>();

                using (AudioFileReader audioFile = new AudioFileReader(audioFilePath)) {
                    List <double> audioData      = new List <double>();
                    int           percentageDone = 0;
                    float[]       buffer         = new float[BUFFER_SIZE];
                    int           samplesRead    = -1;
                    do
                    {
                        LOGGER.Debug("Reading samples to buffer (size: {buffersize})", BUFFER_SIZE);
                        samplesRead = audioFile.Read(buffer, 0, BUFFER_SIZE);
                        audioData.AddRange(buffer.Take(samplesRead).Select(x => (double)x));

                        // another percent done
                        int percentage = (int)(audioFile.Position * 100 / audioFile.Length);
                        if (percentage != percentageDone)
                        {
                            percentageDone = percentage;
                            LOGGER.Info("Creating spectrograms .. completed {per,3}% .. saving image.", percentageDone);

                            // make sure the spectrogram ends during a pause (except at 100%)
                            int splitIndex = (percentageDone == 100) ? audioData.Count : DetermineSplitIndex(audioData);

                            result.Add(SaveIndexedSpectogram(audioData, audioFile.WaveFormat.SampleRate, splitIndex, percentageDone));

                            // save post-split data and make it the start of the new block
                            audioData = audioData.TakeLast(audioData.Count - splitIndex).ToList();
                        }
                    } while ((samplesRead > 0) && (percentageDone < RUN_X_PERCENT));
                }
                return(result);
            }
Example #6
0
        private bool?AskUserAboutFileReplacement([NotNull] FileInfo newFile, [NotNull] FileInfo existingFile, [NotNull] ProcessedEpisode pep)
        {
            try
            {
                ChooseFile question = new ChooseFile(existingFile, newFile);
                question.ShowDialog();

                switch (question.Answer)
                {
                case ChooseFile.ChooseFileDialogResult.ignore:
                    LOGGER.Info(
                        $"Keeping {newFile.FullName} as it might be better quality than {existingFile.FullName}");
                    return(false);

                case ChooseFile.ChooseFileDialogResult.left:
                    LOGGER.Info(
                        $"User has elected to remove {newFile.FullName} as it is not as good quality than {existingFile.FullName}");

                    break;

                case ChooseFile.ChooseFileDialogResult.right:
                    UpgradeFile(newFile, pep, existingFile);
                    return(false);

                default:
                    throw new ArgumentOutOfRangeException();
                }

                return(null);
            }
            catch (System.IO.FileNotFoundException)
            {
                return(false);
            }
        }
        public override ActionOutcome Go(TVRenameStats stats)
        {
            //if the directory is the root download folder do not delete
            if (TVSettings.Instance.MonitorFolders &&
                TVSettings.Instance.DownloadFolders.Contains(toRemove.FullName))
            {
                return(new ActionOutcome($@"Not removing {toRemove.FullName} as it is a Search Folder"));
            }

            try
            {
                if (toRemove.Exists)
                {
                    DeleteOrRecycleFolder(toRemove);
                    if (Tidyup != null && Tidyup.DeleteEmpty)
                    {
                        LOGGER.Info($"Testing {toRemove.Parent.FullName } to see whether it should be tidied up");
                        DoTidyUp(toRemove.Parent);
                    }
                }
                return(ActionOutcome.Success());
            }
            catch (Exception e)
            {
                return(new ActionOutcome(e));
            }
        }
Example #8
0
        private static void FindMissingEpisode([NotNull] MovieItemMissing action, ItemList toRemove, ItemList newItems)
        {
            string url = TVSettings.Instance.UseJackettTextSearch ? TextJackettUrl(action.MovieConfig) : NormalJackettUrl(action.MovieConfig);

            RssItemList rssList = new RssItemList();

            rssList.DownloadRSS(url, false, "Jackett");
            ItemList newItemsForThisMissingEpisode = new ItemList();

            foreach (RSSItem rss in rssList.Where(rss => RssMatch(rss, action.MovieConfig)))
            {
                if (TVSettings.Instance.DetailedRSSJSONLogging)
                {
                    LOGGER.Info(
                        $"Adding {rss.URL} from RSS feed as it appears to be match for {action.MovieConfig.ShowName}");
                }
                ItemDownloading becomes = new ItemDownloading(new FutureTorrentEntry(rss.URL, action.TheFileNoExt), action.MovieConfig, action.TheFileNoExt, DownloadingFinder.DownloadApp.qBitTorrent, action);
                newItemsForThisMissingEpisode.Add(new ActionTDownload(rss, action, becomes));
                toRemove.Add(action);
            }

            foreach (ActionTDownload x in FindDuplicates(newItemsForThisMissingEpisode))
            {
                newItemsForThisMissingEpisode.Remove(x);
            }

            newItems.AddNullableRange(newItemsForThisMissingEpisode);
        }
Example #9
0
        public new void Remove(Process item)
        {
            LOGGER.Info($"Process with id: {item.Id} and name: '{item.ProcessName}' removed");

            item.Exited -= ProcessExited;
            base.Remove(item);
        }
Example #10
0
        internal override void Run()
        {
            LOGGER.Info($"Changing video details for video '{Video.Title}'");

            progress = 0;

            var request = HttpWebRequestCreator.CreateWithAuthHeader("https://www.googleapis.com/youtube/v3/videos?part=snippet,status", "PUT", Account.GetActiveToken());

            request.ContentType = "application/json";

            SerializableYoutubeVideo resource = SerializableYoutubeVideo.Create(Video);
            var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(resource));

            var response = WebService.Communicate(request, bytes);

            Status.QuotaReached = QuotaProblemHandler.IsQuotaLimitReached(response);

            if (!Status.QuotaReached)
            {
                LOGGER.Info($"Video details for video '{Video.Title}' were successfully changed");

                FinishedSuccessful = true;
                progress           = 100;
            }

            OnStepFinished();
        }
        private static IEnumerable <Item> ReviewFileInDownloadDirectory(bool unattended, DirFilesCache dfc, ICollection <FileInfo> filesThatMayBeNeeded, FileInfo fi, [NotNull] List <ShowItem> matchingShows)
        {
            bool             fileCanBeDeleted = TVSettings.Instance.RemoveDownloadDirectoriesFiles;
            List <Item>      returnActions    = new List <Item>();
            ProcessedEpisode firstMatchingPep = null;

            foreach (ShowItem si in matchingShows)
            {
                FinderHelper.FindSeasEp(fi, out int seasF, out int epF, out int _, si,
                                        out TVSettings.FilenameProcessorRE re);

                SeriesInfo s = si.TheSeries();

                if (s is null)
                {
                    continue;
                }

                (firstMatchingPep, fileCanBeDeleted) = FirstMatchingPep(unattended, dfc, fi, matchingShows, s, seasF, epF, si, firstMatchingPep, returnActions, re, fileCanBeDeleted);
            }

            if (fileCanBeDeleted)
            {
                LOGGER.Info(
                    $"Removing {fi.FullName} as it matches {string.Join(", ", matchingShows.Select(s => s.ShowName))} and no episodes are needed");

                returnActions.Add(new ActionDeleteFile(fi, firstMatchingPep, TVSettings.Instance.Tidyup));
            }
            else
            {
                filesThatMayBeNeeded.Add(fi);
            }

            return(returnActions);
        }
Example #12
0
 public RetryingUploadStep(IYoutubeJob job, int waitInterval = 90000)
     : base(job)
 {
     Step = (T)Activator.CreateInstance(typeof(T), job);
     LOGGER.Info($"Creating retrying upload step for step '{Step.GetType().Name}'");
     WaitInterval = waitInterval;
 }
        public List <Trip> GetAllTrips()
        {
            LOGGER.InfoFormat("getting all trips");
            EnsureConnected();
            Request r = new Request()
            {
                Type = RequestType.GET_ALL_TRIPS
            };

            SendRequest(r);
            Response response = ReadResponse();

            LOGGER.InfoFormat("response for get all trips received is {0}", response);
            if (response.Type == ResponseType.OK)
            {
                List <TripDto> tripDtos = (List <TripDto>)response.Data;
                List <Trip>    trips    = tripDtos
                                          .Select(t => new Trip(t.id, t.landmark, t.companyName, t.departure, t.price, t.places))
                                          .ToList();
                LOGGER.Info("found all trips");
                return(trips);
            }
            if (response.Type == ResponseType.ERROR)
            {
                String err = response.Data.ToString();
                LOGGER.Info("getting all trips failed ERROR response " + err);
                throw new ServiceException(err);
            }
            return(null);
        }
        public Account FindAccountByNameAndPassword(string name, string password)
        {
            LOGGER.InfoFormat("finding account with name {0} password {1}", name, password);
            EnsureConnected();
            Request r = new Request()
            {
                Type = RequestType.LOGIN,
                Data = new AccountDto(name, password)
            };

            SendRequest(r);
            Response response = ReadResponse();

            LOGGER.InfoFormat("response for find account received is {0}", response);
            if (response.Type == ResponseType.OK)
            {
                AccountDto accountDto = (AccountDto)response.Data;
                if (accountDto == null)
                {
                    LOGGER.Info("No account found");
                    return(null);
                }
                Account account = new Account(accountDto.id, accountDto.name, accountDto.password);
                LOGGER.InfoFormat("found account {0}", account);
                return(account);
            }
            if (response.Type == ResponseType.ERROR)
            {
                String err = response.Data.ToString();
                LOGGER.Info("finding account failed received ERROR response " + err);
                throw new ServiceException(err);
            }
            return(null);
        }
Example #15
0
 private List <MemberInfo> GetMembersUnderDirectRange(MemberInfo from)
 {
     LOGGER.Debug("GetMembersUnderDirectRange " + GetId(from));
     // All member under range antenna from farthest to nearest
     return(members.Values.Where(m => from.Id != m.Id)
            .Where(m =>
     {
         double d = MinRange(m, from);
         bool isInFromRange = d <= from.AntennaRange;
         bool isInMRange = d <= m.AntennaRange;
         bool isInBothRange = isInFromRange && isInMRange;
         if (!isInBothRange)
         {
             LOGGER.Info("-- " + GetId(m));
             if (!isInFromRange)
             {
                 LOGGER.Info("--> from : " + d + " <= " + from.AntennaRange);
             }
             if (!isInMRange)
             {
                 LOGGER.Info("--> m : " + d + " <= " + m.AntennaRange);
             }
         }
         else
         {
             LOGGER.Info("++ " + GetId(m));
         }
         return isInBothRange;
     })
            .OrderByDescending(m => m.NextPos.Distance(from.NextPos))
            .ToList());
 }
Example #16
0
        public new void RemoveAt(int index)
        {
            LOGGER.Info($"Process with id: {this[index].Id} and name: '{this[index].ProcessName}' removed from index {index}");

            this[index].Exited -= ProcessExited;
            base.RemoveAt(index);
        }
Example #17
0
        public override void Run()
        {
            if (Active())
            {
                try
                {
                    //Create the directory if needed
                    Directory.CreateDirectory(Path.GetDirectoryName(Location()) ?? "");
                    string contents = Produce();

                    //Write Contents to file
                    using (StreamWriter file = new StreamWriter(Location()))
                    {
                        file.Write(contents);
                    }

                    LOGGER.Info("Output File to: {0}", Location());
                    LOGGER.Trace("contents of File are: {0}", contents);
                }
                catch (Exception e)
                {
                    LOGGER.Error(e, "Failed to Output File to: {0}", Location());
                }
            }
            else
            {
                LOGGER.Trace("Skipped (Disabled) Output File to: {0}", Location());
            }
        }
        protected override void DoCheck(SetProgressDelegate prog, TVDoc.ScanSettings settings)
        {
            BulkAddSeriesManager bam = new BulkAddSeriesManager(MDoc);

            bam.CheckFolders(settings.Token, prog, false, !settings.Unattended);
            AskUserAboutShows(settings, bam);

            if (!bam.AddItems.Any(s => s.CodeKnown))
            {
                return;
            }

            var idsToAdd = bam.AddItems.Where(s => s.CodeKnown).Select(folder => new { Code = folder.ProviderCode, folder.Provider }).ToList();

            bam.AddAllToMyShows();
            List <ShowConfiguration> addedShows = idsToAdd.Select(s => MDoc.TvLibrary.GetShowItem(s.Code, s.Provider)).ToList();

            //add each new show into the shows being scanned
            foreach (ShowConfiguration si in addedShows)
            {
                settings.Shows.Add(si);
            }
            LOGGER.Info("Added new shows called: {0}", addedShows.Select(si => si.ShowName).ToCsv());

            MDoc.TvAddedOrEdited(true, settings.Unattended, settings.Hidden, settings.Owner, addedShows);
        }
Example #19
0
        internal override void Run()
        {
            if (File.Exists(Video.ThumbnailPath))
            {
                LOGGER.Info($"Uploading thumbnail of path '{Video.ThumbnailPath}'");

                HttpWebRequest request = CreateThumbnailUploadRequest();

                LOGGER.Info($"Uploading thumbnail to '{request.Method} {request.RequestUri}'");

                Upload(Video.ThumbnailPath, request);

                if (FinishedSuccessful)
                {
                    LOGGER.Info($"Finishing thumbnail upload request");

                    request.Headers.Set("Authorization", $"Bearer {Account.GetActiveToken()}");
                    var thumbnailResource = WebService.Communicate(request);

                    LOGGER.Info($"Thumbnail upload of file '{Video.ThumbnailPath}' finished successfully");

                    Status.QuotaReached = QuotaProblemHandler.IsQuotaLimitReached(thumbnailResource);
                }
            }
            else
            {
                LOGGER.Warn($"Skipping thumbnail upload since a thumbnail did not exist or maybe should not be uploaded. Thumbnail path: '{Video.ThumbnailPath}'");

                // Keine Datei -> Upload war erfolgreich
                FinishedSuccessful = true;
            }

            OnStepFinished();
        }
Example #20
0
        private static void FindMissingEpisode([NotNull] ShowItemMissing action, ItemList toRemove, ItemList newItems)
        {
            ProcessedEpisode processedEpisode = action.MissingEpisode;
            string           url = TVSettings.Instance.UseJackettTextSearch ? TextJackettUrl(processedEpisode) : NormalJackettUrl(processedEpisode);

            RssItemList rssList = new RssItemList();

            rssList.DownloadRSS(url, false, "Jackett");
            ItemList newItemsForThisMissingEpisode = new ItemList();

            foreach (RSSItem rss in rssList.Where(rss => RssMatch(rss, processedEpisode)))
            {
                if (TVSettings.Instance.DetailedRSSJSONLogging)
                {
                    LOGGER.Info(
                        $"Adding {rss.URL} from RSS feed as it appears to be match for {processedEpisode.Show.ShowName} S{processedEpisode.AppropriateSeasonNumber}E{processedEpisode.AppropriateEpNum}");
                }
                newItemsForThisMissingEpisode.Add(new ActionTDownload(rss, action.TheFileNoExt, action));
                toRemove.Add(action);
            }

            foreach (ActionTDownload x in FindDuplicates(newItemsForThisMissingEpisode))
            {
                newItemsForThisMissingEpisode.Remove(x);
            }

            newItems.AddNullableRange(newItemsForThisMissingEpisode);
        }
Example #21
0
        private FileInfo?CheckFile([NotNull] string folder, FileInfo fi, [NotNull] FileInfo actualFile, string newName, ProcessedEpisode ep, IEnumerable <FileInfo> files)
        {
            if (TVSettings.Instance.RetainLanguageSpecificSubtitles)
            {
                (bool isSubtitleFile, string subtitleExtension) = fi.IsLanguageSpecificSubtitle();

                if (isSubtitleFile && actualFile.Name != newName)
                {
                    newName = TVSettings.Instance.FilenameFriendly(
                        TVSettings.Instance.NamingStyle.NameFor(ep, subtitleExtension, folder.Length));
                }
            }

            FileInfo newFile = FileHelper.FileInFolder(folder, newName); // rename updates the filename

            //**** TODO *** Parameterise case insensitive search
            if (!string.Equals(newFile.FullName, actualFile.FullName, StringComparison.CurrentCultureIgnoreCase))
            {
                //Check that the file does not already exist
                //if (FileHelper.FileExistsCaseSensitive(newFile.FullName))
                if (FileHelper.FileExistsCaseSensitive(files, newFile))
                {
                    LOGGER.Warn(
                        $"Identified that {actualFile.FullName} should be renamed to {newName}, but it already exists.");
                }
                else
                {
                    LOGGER.Info($"Identified that {actualFile.FullName} should be renamed to {newName}.");
                    Doc.TheActionList.Add(new ActionCopyMoveRename(ActionCopyMoveRename.Op.rename, fi,
                                                                   newFile, ep, false, null, Doc));

                    //The following section informs the DownloadIdentifers that we already plan to
                    //copy a file in the appropriate place and they do not need to worry about downloading
                    //one for that purpose
                    downloadIdentifiers.NotifyComplete(newFile);

                    if (newFile.IsMovieFile())
                    {
                        return(newFile);
                    }
                }
            }
            else
            {
                if (actualFile.IsMovieFile())
                {
                    //File is correct name
                    LOGGER.Debug($"Identified that {actualFile.FullName} is in the right place. Marking it as 'seen'.");
                    //Record this episode as seen

                    TVSettings.Instance.PreviouslySeenEpisodes.EnsureAdded(ep);
                    if (TVSettings.Instance.IgnorePreviouslySeen)
                    {
                        Doc.SetDirty();
                    }
                }
            }

            return(null);
        }
        private bool?ReviewFile(bool unattended, [NotNull] FileInfo newFile, [NotNull] List <ShowItem> matchingShows, [NotNull] FileInfo existingFile, [NotNull] ProcessedEpisode pep)
        {
            FileHelper.VideoComparison result = FileHelper.BetterQualityFile(existingFile, newFile);
            switch (result)
            {
            case FileHelper.VideoComparison.secondFileBetter:
                if (TVSettings.Instance.ReplaceWithBetterQuality)
                {
                    if (matchingShows.Count > 1)
                    {
                        LOGGER.Warn(
                            $"Keeping {newFile.FullName}. Although it is better quality than {existingFile.FullName}, there are other shows ({string.Join(", ", matchingShows.Select(item => item.ShowName))}) that match.");
                    }
                    else
                    {
                        UpgradeFile(newFile, pep, existingFile);
                    }
                }
                else
                {
                    LOGGER.Warn(
                        $"Keeping {newFile.FullName} as it is better quality than some of the current files for that show (Auto Replace with better quality files is turned off)");
                }
                return(false);

            case FileHelper.VideoComparison.cantTell:
            case FileHelper.VideoComparison.similar:
                if (unattended)
                {
                    LOGGER.Info(
                        $"Keeping {newFile.FullName} as it might be better quality than {existingFile.FullName}");

                    return(false);
                }
                else
                {
                    if (matchingShows.Count <= 1)
                    {
                        return(AskUserAboutFileReplacement(newFile, existingFile, pep));
                    }

                    LOGGER.Warn(
                        $"Keeping {newFile.FullName}. Although it is better quality than {existingFile.FullName}, there are other shows ({string.Join(", ", matchingShows.Select(item => item.ShowName))}) that match.");

                    return(false);
                }

            //the other cases of the files being the same or the existing file being better are not enough to save the file
            case FileHelper.VideoComparison.firstFileBetter:
                break;

            case FileHelper.VideoComparison.same:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(null);
        }
Example #23
0
 private static void DownloadUrl(string torrentUrl, string url)
 {
     try
     {
         using (HttpClient client = new HttpClient())
         {
             Dictionary <string, string> values = new Dictionary <string, string> {
                 { "urls", torrentUrl }
             };
             FormUrlEncodedContent content  = new FormUrlEncodedContent(values);
             HttpResponseMessage   response = client.PostAsync(url, content).Result;
             if (!response.IsSuccessStatusCode)
             {
                 LOGGER.Warn(
                     $"Tried to download {torrentUrl} from qBitTorrent via {url}. Got following response {response.StatusCode}");
             }
             else
             {
                 LOGGER.Info(
                     $"Started download of {torrentUrl} via qBitTorrent using {url}. Got following response {response.StatusCode}");
             }
         }
     }
     catch (WebException wex)
     {
         LOGGER.Warn(
             $"Could not connect to {wex.Response.ResponseUri} to download {torrentUrl}, Please check qBitTorrent Settings and ensure qBitTorrent is running with no password required for local connections : {wex.LoggableDetails()}");
     }
 }
        protected override void DoCheck([NotNull] SetProgressDelegate prog, ICollection <ShowItem> showList, TVDoc.ScanSettings settings)
        {
            BulkAddManager bam = new BulkAddManager(MDoc);

            bam.CheckFolders(settings.Token, prog, false, !settings.Unattended);
            AskUserAboutShows(settings, bam);

            if (!bam.AddItems.Any(s => s.CodeKnown))
            {
                return;
            }

            List <int> idsToAdd = bam.AddItems.Where(s => s.CodeKnown).Select(folder => folder.TVDBCode).ToList();

            bam.AddAllToMyShows();

            MDoc.SetDirty();
            MDoc.DoDownloadsFG(settings.Unattended, settings.Hidden);

            List <ShowItem> addedShows = idsToAdd.Select(s => MDoc.Library.ShowItem(s)).ToList();

            //add each new show into the shows being scanned
            foreach (ShowItem si in addedShows)
            {
                showList.Add(si);
            }
            LOGGER.Info("Added new shows called: {0}", addedShows.Select(si => si?.ShowName).ToCsv());

            MDoc.DoWhenToWatch(true, settings.Unattended, settings.Hidden);

            MDoc.WriteUpcoming();
            MDoc.WriteRecent();
        }
Example #25
0
        public CachedMovieInfo?LookupMovieByImdb(string imdbToTest, bool showErrorMsgBox)
        {
            var results = Client.FindAsync(FindExternalSource.Imdb, imdbToTest).Result;

            LOGGER.Info($"Got {results.MovieResults.Count:N0} results searching for {imdbToTest}");
            foreach (SearchMovie result in results.MovieResults)
            {
                DownloadMovieNow(result.Id, showErrorMsgBox);
            }

            if (results.MovieResults.Count == 0)
            {
                return(null);
            }

            if (results.MovieResults.Count == 1)
            {
                lock (MOVIE_LOCK)
                {
                    return(Movies[results.MovieResults.First().Id]);
                }
            }

            return(null);
        }
Example #26
0
        private void RunBackup()
        {
            IsBackingUp         = true;
            LastBackupStartTime = DateTime.Now;

            MaxBackupProgressValue     = BackupServices.Sum(x => x.TotalReposCount);
            CurrentBackupProgressValue = 0;

            List <IBackupService> successfulServices = new List <IBackupService>();

            foreach (IBackupService service in BackupServices)
            {
                m_currentBackupService = service;
                if (!m_currentBackupService.IsAuthorized)
                {
                    LOGGER.Info($"{service.ServiceId} isn't authorized to backup");
                    continue;
                }

                bool result = service.Backup(BackupPath);
                if (result)
                {
                    successfulServices.Add(service);
                }
            }

            EVENT_AGGREGATOR.PublishOnCurrentThread(new OnBackupFinished(true)
            {
                SuccessfulBackupServices = successfulServices
            });
        }
Example #27
0
        internal override void Run()
        {
            progress = 0;

            if (Video.AddToPlaylist && !string.IsNullOrWhiteSpace(Video.PlaylistId))
            {
                LOGGER.Info($"Adding video '{Video.Title}' to playlist with id '{Video.PlaylistId}'");

                var request = HttpWebRequestCreator.CreateWithAuthHeader("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet", "POST", Account.GetActiveToken());
                request.ContentType = "application/json";

                YoutubePlaylistItem resource = new YoutubePlaylistItem(Video.PlaylistId, Video.Id);
                var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(resource));

                var response = WebService.Communicate(request, bytes);
                Status.QuotaReached = QuotaProblemHandler.IsQuotaLimitReached(response);

                if (!Status.QuotaReached)
                {
                    LOGGER.Info($"Video '{Video.Title}' was successfully added to playlist with id '{Video.PlaylistId}'");

                    FinishedSuccessful = true;
                    progress           = 100;
                }
            }
            else
            {
                LOGGER.Info($"Skipping playlist add since it is either not wanted or there is no playlist id");

                FinishedSuccessful = true;
                progress           = 100;
            }

            OnStepFinished();
        }
Example #28
0
        private static ShowItemMissing UpdateMissingItem([NotNull] ShowItemMissing me, [NotNull] FileInfo dce, int epF, int maxEp, int seasF)
        {
            ShowRule sr = new ShowRule
            {
                DoWhatNow = RuleAction.kMerge,
                First     = epF,
                Second    = maxEp
            };

            me.MissingEpisode.Show.AddSeasonRule(seasF, sr);

            LOGGER.Info(
                $"Looking at {me.MissingEpisode.Show.ShowName} and have identified that episode {epF} and {maxEp} of season {seasF} have been merged into one file {dce.FullName}");

            LOGGER.Info($"Added new rule automatically for {sr}");

            //Regenerate the episodes with the new rule added
            ShowLibrary.GenerateEpisodeDict(me.MissingEpisode.Show);

            //Get the newly created processed episode we are after
            // ReSharper disable once InconsistentNaming
            ProcessedEpisode newPE = me.MissingEpisode;

            foreach (ProcessedEpisode pe in me.MissingEpisode.Show.SeasonEpisodes[seasF])
            {
                if (pe.AppropriateEpNum == epF && pe.EpNum2 == maxEp)
                {
                    newPE = pe;
                }
            }

            return(new ShowItemMissing(newPE, me.TargetFolder));
        }
        private void ProcessFolder(TVDoc.ScanSettings settings, [NotNull] ItemMissing me, [NotNull] string folderName, [NotNull] DirFilesCache dfc,
                                   ItemList thisRound, [NotNull] List <FileInfo> matchedFiles)
        {
            LOGGER.Info($"Starting to look for {me.Filename} in the library folder: {folderName}");
            FileInfo[] files = dfc.GetFiles(folderName);
            if (files is null)
            {
                return;
            }

            foreach (FileInfo testFile in files)
            {
                if (!ReviewFile(me, thisRound, testFile, settings, false, false, false,
                                TVSettings.Instance.UseFullPathNameToMatchLibraryFolders))
                {
                    continue;
                }

                if (!matchedFiles.Contains(testFile))
                {
                    matchedFiles.Add(testFile);
                    LOGGER.Info($"Found {me.Filename} at: {testFile}");
                }
            }
        }
        public List <Trip> GetTripsByLandmarkDepartureHour(string landmark, int start, int end)
        {
            LOGGER.InfoFormat("getting trips by landmark {0} departure hours {1} {2}", landmark, start, end);
            EnsureConnected();
            Request r = new Request()
            {
                Type = RequestType.SEARCH_TRIPS,
                Data = new TripDto(landmark, start, end)
            };

            SendRequest(r);
            Response response = ReadResponse();

            LOGGER.InfoFormat("response for search trips received is {0}", response);
            if (response.Type == ResponseType.OK)
            {
                List <TripDto> tripDtos = (List <TripDto>)response.Data;
                List <Trip>    trips    = tripDtos
                                          .Select(t => new Trip(t.id, t.landmark, t.companyName, t.departure, t.price, t.places))
                                          .ToList();
                LOGGER.Info("found all trips");
                return(trips);
            }
            if (response.Type == ResponseType.ERROR)
            {
                String err = response.Data.ToString();
                LOGGER.Info("searching trips failed ERROR response " + err);
                throw new ServiceException(err);
            }
            return(null);
        }