Beispiel #1
0
        public TheTVDB(FileInfo loadFrom, FileInfo cacheFile, CommandLineArgs args)
        {
            Args = args;

            System.Diagnostics.Debug.Assert(cacheFile != null);
            this.CacheFile = cacheFile;

            this.LastError = "";
            // this.WhoHasLock = new List<String>();
            this.Connected = false;
            this.ExtraEpisodes = new System.Collections.Generic.List<ExtraEp>();

            this.LanguageList = new System.Collections.Generic.Dictionary<string, string>();
            this.LanguageList["en"] = "English";

            this.XMLMirror = "http://thetvdb.com";
            this.BannerMirror = "http://thetvdb.com";
            this.ZIPMirror = "http://thetvdb.com";

            this.Series = new System.Collections.Generic.Dictionary<int, SeriesInfo>();
            this.New_Srv_Time = this.Srv_Time = 0;

            this.LoadOK = (loadFrom == null) || this.LoadCache(loadFrom);

            this.ForceReloadOn = new System.Collections.Generic.List<int>();
        }
Beispiel #2
0
                                         }; // TODO: move into settings, and allow user to edit these

        #endregion Fields

        #region Constructors

        public TVDoc(FileInfo settingsFile, TheTVDB tvdb, CommandLineArgs args)
        {
            this.mTVDB = tvdb;
            this.Args = args;

            this.Ignore = new List<IgnoreItem>();

            this.Workers = null;
            this.WorkerSemaphore = null;

            this.mStats = new TVRenameStats();
            this.mDirty = false;
            this.TheActionList = new ItemList();

            this.Settings = new TVSettings();

            this.MonitorFolders = new List<String>();
            this.IgnoreFolders = new List<String>();
            this.SearchFolders = new List<String>();

            ShowItems = new List<ShowItem>();
            this.AddItems = new FolderMonitorEntryList();

            this.DownloadDone = true;
            this.DownloadOK = true;

            this.ActionCancel = false;
            this.ScanProgDlg = null;

            this.LoadOK = ((settingsFile == null) || this.LoadXMLSettings(settingsFile)) && this.mTVDB.LoadOK;

            UpdateTVDBLanguage();

            //    StartServer();
        }
Beispiel #3
0
                                       }; // TODO: move into settings, and allow user to edit these

        public TVDoc(FileInfo settingsFile, CommandLineArgs args)
        {
            this.Args = args;

            this.Ignore = new List<IgnoreItem>();

            this.Workers = null;
            this.WorkerSemaphore = null;

            this.mStats = new TVRenameStats();
            this.mDirty = false;
            this.TheActionList = new ItemList();

            this.MonitorFolders = new List<String>();
            this.IgnoreFolders = new List<String>();
            this.SearchFolders = new List<String>();

            ShowItems = new List<ShowItem>();
            this.AddItems = new FolderMonitorEntryList();

            this.DownloadDone = true;
            this.DownloadOK = true;

            this.ActionCancel = false;
            this.ScanProgDlg = null;

            this.Finders = new List<Finder> ();
            this.Finders.Add(new FileFinder(this));
            this.Finders.Add(new RSSFinder(this));
            this.Finders.Add(new uTorrentFinder(this));
            this.Finders.Add(new SABnzbdFinder(this));


            this.LoadOK = ((settingsFile == null) || this.LoadXMLSettings(settingsFile)) && TheTVDB.Instance.LoadOK;

            this.DownloadIdentifiers = new DownloadIdentifiersController();
            UpdateTVDBLanguage();

            //    StartServer();
        }
Beispiel #4
0
        public bool ProcessTorrentFile(string torrentFile, TreeView tvTree, CommandLineArgs args)
        {
            // ----------------------------------------
            // read in torrent file

            if (tvTree != null)
                tvTree.Nodes.Clear();

            BEncodeLoader bel = new BEncodeLoader();
            BTFile btFile = bel.Load(torrentFile);

            if (btFile == null)
                return false;

            BTItem bti = btFile.GetItem("info");
            if ((bti == null) || (bti.Type != BTChunk.kDictionary))
                return false;

            BTDictionary infoDict = (BTDictionary) (bti);

            bti = infoDict.GetItem("piece length");
            if ((bti == null) || (bti.Type != BTChunk.kInteger))
                return false;

            Int64 pieceSize = ((BTInteger) bti).Value;

            bti = infoDict.GetItem("pieces");
            if ((bti == null) || (bti.Type != BTChunk.kString))
                return false;

            BTString torrentPieces = (BTString) (bti);

            bti = infoDict.GetItem("files");

            if (bti == null) // single file torrent
            {
                bti = infoDict.GetItem("name");
                if ((bti == null) || (bti.Type != BTChunk.kString))
                    return false;

                BTString di = (BTString) (bti);
                string nameInTorrent = di.AsString();

                BTItem fileSizeI = infoDict.GetItem("length");
                Int64 fileSize = ((BTInteger) fileSizeI).Value;

                this.NewTorrentEntry(torrentFile, -1);
                if (this.DoHashChecking)
                {
                    byte[] torrentPieceHash = torrentPieces.StringTwentyBytePiece(0);

                    FileInfo fi = this.FindLocalFileWithHashAt(torrentPieceHash, 0, pieceSize, fileSize);
                    if (fi != null)
                        this.FoundFileOnDiskForFileInTorrent(torrentFile, fi, -1, nameInTorrent);
                    else
                        this.DidNotFindFileOnDiskForFileInTorrent(torrentFile, -1, nameInTorrent);
                }
                this.FinishedTorrentEntry(torrentFile, -1, nameInTorrent);

                // don't worry about updating overallPosition as this is the only file in the torrent
            }
            else
            {
                Int64 overallPosition = 0;
                Int64 lastPieceLeftover = 0;

                if (bti.Type != BTChunk.kList)
                    return false;

                BTList fileList = (BTList) (bti);

                // list of dictionaries
                for (int i = 0; i < fileList.Items.Count; i++)
                {
                    this.Prog(100 * i / fileList.Items.Count);
                    if (fileList.Items[i].Type != BTChunk.kDictionary)
                        return false;

                    BTDictionary file = (BTDictionary) (fileList.Items[i]);
                    BTItem thePath = file.GetItem("path");
                    if (thePath.Type != BTChunk.kList)
                        return false;
                    BTList pathList = (BTList) (thePath);
                    // want the last of the items in the list, which is the filename itself
                    int n = pathList.Items.Count - 1;
                    if (n < 0)
                        return false;
                    BTString fileName = (BTString) (pathList.Items[n]);

                    BTItem fileSizeI = file.GetItem("length");
                    Int64 fileSize = ((BTInteger) fileSizeI).Value;

                    int pieceNum = (int) (overallPosition / pieceSize);
                    if (overallPosition % pieceSize != 0)
                        pieceNum++;

                    this.NewTorrentEntry(torrentFile, i);

                    if (this.DoHashChecking)
                    {
                        byte[] torrentPieceHash = torrentPieces.StringTwentyBytePiece(pieceNum);

                        FileInfo fi = this.FindLocalFileWithHashAt(torrentPieceHash, lastPieceLeftover, pieceSize, fileSize);
                        if (fi != null)
                            this.FoundFileOnDiskForFileInTorrent(torrentFile, fi, i, fileName.AsString());
                        else
                            this.DidNotFindFileOnDiskForFileInTorrent(torrentFile, i, fileName.AsString());
                    }

                    this.FinishedTorrentEntry(torrentFile, i, fileName.AsString());

                    int sizeInPieces = (int) (fileSize / pieceSize);
                    if (fileSize % pieceSize != 0)
                        sizeInPieces++; // another partial piece

                    lastPieceLeftover = (lastPieceLeftover + (Int32) ((sizeInPieces * pieceSize) - fileSize)) % pieceSize;
                    overallPosition += fileSize;
                } // for each file in the torrent
            }

            if (tvTree != null)
            {
                tvTree.BeginUpdate();
                btFile.Tree(tvTree.Nodes);
                tvTree.ExpandAll();
                tvTree.EndUpdate();
                tvTree.Update();
            }

            this.Prog(0);

            return true;
        }
Beispiel #5
0
 public bool LoadResumeDat(CommandLineArgs args)
 {
     BEncodeLoader bel = new BEncodeLoader();
     this.ResumeDat = bel.Load(this.ResumeDatPath);
     return (this.ResumeDat != null);
 }
Beispiel #6
0
        public bool DoWork(List<string> Torrents, string searchFolder, ListView results, bool hashSearch, bool matchMissing, bool setPrios, bool testMode, 
                           bool searchSubFolders, ItemList missingList, List<FilenameProcessorRE> rexps, CommandLineArgs args)
        {
            this.Rexps = rexps;

            if (!matchMissing && !hashSearch)
                return true; // nothing to do

            if (hashSearch && string.IsNullOrEmpty(searchFolder))
                return false;

            if (matchMissing && ((missingList == null) || (rexps == null)))
                return false;

            this.MissingList = missingList;
            this.DoMatchMissing = matchMissing;
            this.DoHashChecking = hashSearch;
            this.SetPrios = setPrios;
            this.Results = results;

            this.Prog(0);

            if (!this.LoadResumeDat(args))
                return false;

            bool r = true;

            this.Prog(0);

            if (hashSearch)
                this.BuildFileCache(searchFolder, searchSubFolders);

            foreach (string tf in Torrents)
            {
                r = this.ProcessTorrentFile(tf, null, args);
                if (!r) // stop on the first failure
                    break;
            }

            if (this.Altered && !testMode)
                this.WriteResumeDat();

            this.Prog(0);

            return r;
        }
Beispiel #7
0
        public System.Collections.Generic.List<TorrentEntry> AllFilesBeingDownloaded(TVSettings settings, CommandLineArgs args)
        {
            System.Collections.Generic.List<TorrentEntry> r = new System.Collections.Generic.List<TorrentEntry>();

            BEncodeLoader bel = new BEncodeLoader();
            foreach (BTDictionaryItem it in this.ResumeDat.GetDict().Items)
            {
                if ((it.Type != BTChunk.kDictionaryItem))
                    continue;

                BTDictionaryItem dictitem = (BTDictionaryItem) (it);

                if ((dictitem.Key == ".fileguard") || (dictitem.Data.Type != BTChunk.kDictionary))
                    continue;

                string torrentFile = dictitem.Key;
                BTDictionary d2 = (BTDictionary) (dictitem.Data);

                BTItem p = d2.GetItem("prio");
                if ((p == null) || (p.Type != BTChunk.kString))
                    continue;

                BTString prioString = (BTString) (p);
                string directoryName = Path.GetDirectoryName(this.ResumeDatPath) + System.IO.Path.DirectorySeparatorChar;

                if (!File.Exists(torrentFile)) // if the torrent file doesn't exist
                    torrentFile = directoryName + torrentFile; // ..try prepending the resume.dat folder's path to it.

                if (!File.Exists(torrentFile))
                    continue; // can't find it.  give up!

                BTFile tor = bel.Load(torrentFile);
                if (tor == null)
                    continue;

                List<string> a = tor.AllFilesInTorrent();
                if (a != null)
                {
                    int c = 0;

                    p = d2.GetItem("path");
                    if ((p == null) || (p.Type != BTChunk.kString))
                        continue;
                    string defaultFolder = ((BTString) p).AsString();

                    BTItem targets = d2.GetItem("targets");
                    bool hasTargets = ((targets != null) && (targets.Type == BTChunk.kList));
                    BTList targetList = (BTList) (targets);

                    foreach (string s in a)
                    {
                        if ((c < prioString.Data.Length) && (prioString.Data[c] != BTPrio.Skip))
                        {
                            string saveTo = Helpers.FileInFolder(defaultFolder, settings.FilenameFriendly(s)).Name;
                            if (hasTargets)
                            {
                                // see if there is a target for this (the c'th) file
                                for (int i = 0; i < targetList.Items.Count; i++)
                                {
                                    BTList l = (BTList) (targetList.Items[i]);
                                    BTInteger n = (BTInteger) (l.Items[0]);
                                    BTString dest = (BTString) (l.Items[1]);
                                    if (n.Value == c)
                                    {
                                        saveTo = dest.AsString();
                                        break;
                                    }
                                }
                            }
                            int percent = (a.Count == 1) ? PercentBitsOn((BTString) (d2.GetItem("have"))) : -1;
                            TorrentEntry te = new TorrentEntry(torrentFile, saveTo, percent);
                            r.Add(te);
                        }
                        c++;
                    }
                }
            }

            return r;
        }
Beispiel #8
0
    private static int Main(string[] args)
    {
        // Enabling Windows XP visual effects before any controls are created
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        
        // Sort out the command line arguments
        CommandLineArgs clargs = new CommandLineArgs(args);

        // see if we're already running
        bool createdNew = false;
        System.Threading.Mutex mutex = new System.Threading.Mutex(true, "TVRenameMutex", out createdNew);

        if (!createdNew)
        {
            // we're already running

            // tell the already running copy to come to the foreground
            IpcClientChannel clientChannel = new IpcClientChannel();
            ChannelServices.RegisterChannel(clientChannel, true);

            RemotingConfiguration.RegisterWellKnownClientType(typeof (IPCMethods), "ipc://TVRenameChannel/IPCMethods");

            IPCMethods ipc = new IPCMethods();

            // if we were already running, and no command line arguments, then bring application to the foreground
            // and we're done.
            if (args.Length == 0)
            {
                ipc.BringToForeground();
                return 0;
            }

            // Send command-line arguments to already running TVRename via IPC

            CommandLineArgs.MissingFolderBehaviour before = ipc.MissingBehaviour;
            bool renameBefore = ipc.RenameBehaviour;

            if (clargs.RenameCheck == false)
             {
              // Temporarily override behaviour for missing folders
              ipc.RenameBehaviour = false;
            }

            if (clargs.MissingFolder != CommandLineArgs.MissingFolderBehaviour.Ask)
            {
                // Temporarily override behaviour for missing folders
                ipc.MissingBehaviour = clargs.MissingFolder;
            }

            // TODO: Unify command line handling between here and in UI.cs (ProcessArgs).  Just send in clargs via IPC?

            if (clargs.Scan || clargs.DoAll) // doall implies scan
                ipc.Scan();

            if (clargs.DoAll)
                ipc.DoAll();

            if (clargs.Quit)
            {
                ipc.Quit();
                return 0;
            }

            ipc.RenameBehaviour = renameBefore;
            ipc.MissingBehaviour = before;

        return 0;
        }

#if !DEBUG
		try
		{
#endif

        // Starting TVRename...

        // Check arguments for forced recover
        bool ok = true;
        string recoverText = "";

        if (clargs.ForceRecover)
        {
            ok = false; // force recover dialog
            recoverText = "Recover manually requested.";
        }

        // Load settings files
        TVDoc doc = null;
        try
        {
            if (!string.IsNullOrEmpty(clargs.UserFilePath))
                PathManager.SetUserDefinedBasePath(clargs.UserFilePath);
        }
        catch (System.Exception ex)
        {
            MessageBox.Show("Error while setting the User-Defined File Path:" + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Environment.Exit(1);
        }

        FileInfo tvdbFile = PathManager.TVDBFile;
        FileInfo settingsFile = PathManager.TVDocSettingsFile;

        do // loop until no problems loading settings & tvdb cache files
        {
            if (!ok) // something went wrong last time around, ask the user what to do
            {
                RecoverXML rec = new RecoverXML(recoverText);
                if (rec.ShowDialog() == DialogResult.OK)
                {
                    tvdbFile = rec.DBFile;
                    settingsFile = rec.SettingsFile;
                }
                else
                    return 1;
            }

            // try loading using current settings files, and set up the main
            // classes
            TheTVDB.Instance.setup(tvdbFile, PathManager.TVDBFile, clargs);

            doc = new TVDoc(settingsFile, clargs);

            if (!ok)
                doc.SetDirty();

            ok = doc.LoadOK;

            if (!ok)
            {
                recoverText = "";
                if (!doc.LoadOK && !String.IsNullOrEmpty(doc.LoadErr))
                    recoverText += doc.LoadErr;
                if (!TheTVDB.Instance.LoadOK && !String.IsNullOrEmpty(TheTVDB.Instance.LoadErr))
                    recoverText += "\r\n" + TheTVDB.Instance.LoadErr;
            }
        } while (!ok);

        // Show user interface
        UI theUI = new UI(doc);
        Application.Run(theUI);
        GC.KeepAlive(mutex);

#if !DEBUG
		}
		catch (Exception e)
		{
		  ShowException se = new ShowException(e);
		  se.ShowDialog();
		}
#endif

        return 0;
    }
Beispiel #9
0
        public Banner(SeriesInfo ser, Season seas, int?codeHint, XmlReader r, CommandLineArgs args)
        {
            // <Banner>
            //        <id>708811</id>
            //        <BannerPath>seasonswide/79488-5.jpg</BannerPath>
            //        <BannerType>season</BannerType>
            //        <BannerType2>seasonwide</BannerType2>
            //        <Language>en</Language>
            //        <Rating/>
            //        <RatingCount>0</RatingCount>
            //        <Season>5</Season>
            //  blah blah
            // </Banner>



            try
            {
                this.SetDefaults(ser, seas);

                this.SeriesID = (int)codeHint;

                r.Read();
                if (r.Name != "Banner")
                {
                    return;
                }

                r.Read();
                while (!r.EOF)
                {
                    if ((r.Name == "Banner") && (!r.IsStartElement()))
                    {
                        break;
                    }

                    if (r.Name == "id")
                    {
                        this.BannerId = r.ReadElementContentAsInt();
                    }
                    else if (r.Name == "seriesid")
                    {
                        this.SeriesID = r.ReadElementContentAsInt(); // thetvdb series id
                    }
                    else if (r.Name == "seasonid")
                    {
                        this.SeasonID = r.ReadElementContentAsInt();
                    }
                    else if (r.Name == "BannerPath")
                    {
                        this.BannerPath = XMLHelper.ReadStringFixQuotesAndSpaces(r);
                    }
                    else if (r.Name == "BannerType")
                    {
                        this.BannerType = r.ReadElementContentAsString();
                    }
                    else if (r.Name == "LanguageId")
                    {
                        this.LanguageId = r.ReadElementContentAsInt();
                    }
                    else if (r.Name == "Resolution")
                    {
                        this.Resolution = r.ReadElementContentAsString();
                    }
                    else if (r.Name == "Rating")
                    {
                        String sn = r.ReadElementContentAsString();
                        double.TryParse(sn, out this.Rating);
                    }
                    else if (r.Name == "RatingCount")
                    {
                        this.RatingCount = r.ReadElementContentAsInt();
                    }
                    else if (r.Name == "Season")
                    {
                        this.SeasonID = r.ReadElementContentAsInt();
                    }
                    else if (r.Name == "ThumbnailPath")
                    {
                        this.ThumbnailPath = r.ReadElementContentAsString();
                    }
                    else
                    {
                        if ((r.IsEmptyElement) || !r.IsStartElement())
                        {
                            r.ReadOuterXml();
                        }
                        else
                        {
                            r.Read();
                        }
                    }
                }
            }
            catch (XmlException e)
            {
                string message = "Error processing data from TheTVDB for a banner.";
                if (this.SeriesID != -1)
                {
                    message += "\r\nSeries ID: " + this.SeriesID;
                }
                if (this.BannerId != -1)
                {
                    message += "\r\nBanner ID: " + this.BannerId;
                }
                if (!string.IsNullOrEmpty(this.BannerPath))
                {
                    message += "\r\nBanner Path: " + this.BannerPath;
                }

                logger.Error(e, message);

                throw new TheTVDB.TVDBException(e.Message);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Defines the entry point of the application.
        /// Checks if the application is already running and if so, performs actions via IPC and exits.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            Logger.Info($"TV Rename {Helpers.DisplayVersion} started with args: {string.Join(" ", e.Args)}");
            Logger.Info($"Copyright (C) {DateTime.Now.Year} TV Rename");
            Logger.Info(
                "This program comes with ABSOLUTELY NO WARRANTY; This is free software, and you are welcome to redistribute it under certain conditions");

            // Parse command line arguments
            CommandLineArgs clargs = new CommandLineArgs(new ReadOnlyCollection <string>(e.Args));

            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);

            AppDomain.CurrentDomain.UnhandledException += GlobalExceptionHandler;

            if (e.Args.Contains("/?", StringComparer.OrdinalIgnoreCase))
            {
                Logger.Info(CommandLineArgs.Helptext());

                //redirect console output to parent process
                //must be before any calls to Console.WriteLine()
                //MS: Never got this to work quite right - seems there is no simple way to output
                //to the command line console if you are a winforms app
                if (NativeMethods.AttachParentConsole())
                {
                    Console.WriteLine(CommandLineArgs.Helptext());
                }
                else
                {
                    Logger.Info("Could not attach to console");
                }

                return;
            }

            // Check if an application instance is already running
            Mutex mutex = new Mutex(true, "TVRename", out bool newInstance);

            if (!newInstance)
            {
                // Already running
                Logger.Warn("An instance is already running");

                // Create an IPC channel to the existing instance
                RemoteClient.Proxy();

                // Transparent proxy to the existing instance
                RemoteClient ipc = new RemoteClient();

                // If already running and no command line arguments then bring instance to the foreground and quit
                if (e.Args.Length == 0)
                {
                    ipc.FocusWindow();

                    return;
                }

                // Send command-line arguments to already running instance
                CommandLineArgs.MissingFolderBehavior previousMissingFolderBehavior = ipc.MissingFolderBehavior;
                bool previousRenameBehavior = ipc.RenameBehavior;

                if (clargs.RenameCheck == false)
                {
                    // Temporarily override behavior for renaming folders
                    ipc.RenameBehavior = false;
                }

                if (clargs.MissingFolder != CommandLineArgs.MissingFolderBehavior.ask)
                {
                    // Temporarily override behavior for missing folders
                    ipc.MissingFolderBehavior = clargs.MissingFolder;
                }

                // TODO: Unify command line handling between here and in UI.cs (ProcessArgs). Just send in clargs via IPC?

                if (clargs.Scan)
                {
                    ipc.Scan();
                }

                if (clargs.QuickScan)
                {
                    ipc.QuickScan();
                }

                if (clargs.RecentScan)
                {
                    ipc.RecentScan();
                }

                if (clargs.DoAll)
                {
                    ipc.ProcessAll();
                }

                if (clargs.Quit)
                {
                    ipc.Quit();
                }

                // TODO: Necessary?
                ipc.RenameBehavior        = previousRenameBehavior;
                ipc.MissingFolderBehavior = previousMissingFolderBehavior;

                return;
            }

            try
            {
                Logger.Info("Starting new instance");

                LetsGo(clargs, string.Join(" ", e.Args));

                GC.KeepAlive(mutex);
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex, "Application exiting with error");

                //new ShowException(ex).ShowDialog();

                Environment.Exit(1);
            }

            Logger.Info("Application exiting");
        }
Beispiel #11
0
        private static TVDoc LoadSettings([NotNull] CommandLineArgs clargs)
        {
            bool   recover     = false;
            string recoverText = string.Empty;

            // Check arguments for forced recover
            if (clargs.ForceRecover)
            {
                recover     = true;
                recoverText = "Recover manually requested.";
            }

            SetupCustomSettings(clargs);

            FileInfo tvdbFile     = PathManager.TVDBFile;
            FileInfo settingsFile = PathManager.TVDocSettingsFile;
            TVDoc    doc;

            do               // Loop until files correctly load
            {
                if (recover) // Recovery required, prompt user
                {
/*                    RecoverXml recoveryForm = new RecoverXml(recoverText);
 *
 *                  if (recoveryForm.ShowDialog() == DialogResult.OK)
 *                  {
 *                      tvdbFile = recoveryForm.DbFile;
 *                      settingsFile = recoveryForm.SettingsFile;
 *                  }
 *                  else
 *                  {
 *                      Logger.Error("User requested no recovery");
 *                      throw new TVRenameOperationInterruptedException();
 *                  }*/
                }

                // Try loading settings file
                doc = new TVDoc(settingsFile, clargs);

                // Try loading TheTVDB cache file
                TheTVDB.Instance.Setup(doc.Library, tvdbFile, PathManager.TVDBFile, clargs);

                if (recover)
                {
                    doc.SetDirty();
                }

                recover = !doc.LoadOk;

                // Continue if correctly loaded
                if (!recover)
                {
                    continue;
                }

                // Set recover message
                recoverText = string.Empty;
                if (!doc.LoadOk && !string.IsNullOrEmpty(doc.LoadErr))
                {
                    recoverText = doc.LoadErr;
                }

                if (!TheTVDB.Instance.LoadOk && !string.IsNullOrEmpty(TheTVDB.Instance.LoadErr))
                {
                    recoverText += $"{Environment.NewLine}{TheTVDB.Instance.LoadErr}";
                }
            } while (recover);

            return(doc);
        }
Beispiel #12
0
        private void LetsGo(CommandLineArgs clargs, string commandLine)
        {
            //initialize the splash screen and set it as the application main window
            TvRenameSplash  splashScreen = new TvRenameSplash();
            SplashViewModel vm           = new SplashViewModel {
                Version = Helpers.DisplayVersion
            };

            this.MainWindow          = splashScreen;
            splashScreen.DataContext = vm;

            if (clargs.Hide || !Environment.UserInteractive)
            {
                splashScreen.Visibility = Visibility.Hidden;
            }
            else
            {
                splashScreen.Show();
            }

            // Update splash screen
            vm.Status = "Initializing";

            //because we're not on the UI thread, we need to use the Dispatcher
            //associated with the splash screen to update the progress bar
            vm.Progress = 5;


            //in order to ensure the UI stays responsive, we need to
            //do the work on a different thread
            Task.Factory.StartNew(() =>
            {
                splashScreen.Dispatcher.Invoke(() => vm.Status = "Loading Settings...");
                TVDoc doc = LoadSettings(clargs);

                splashScreen.Dispatcher.Invoke(() => vm.Status = "Setup Logging...");
                if (TVSettings.Instance.mode == TVSettings.BetaMode.BetaToo || TVSettings.Instance.ShareLogs)
                {
                    SetupLogging(commandLine);
                }

                splashScreen.Dispatcher.Invoke(() => vm.Status = "Configuring...");
                ConvertSeriesTimeZones(doc, TheTVDB.Instance);
                // Update RegVersion to bring the WebBrowser up to speed
                RegistryHelper.UpdateBrowserEmulationVersion();

                splashScreen.Dispatcher.Invoke(() => vm.Status = "Create Main Window...");

                //once we're done we need to use the Dispatcher
                //to create and show the main window

                Dispatcher.Invoke(() =>
                {
                    // Show user interface

                    MainWindow ui = new MainWindow(doc, vm, splashScreen.Dispatcher, !clargs.Unattended && !clargs.Hide && Environment.UserInteractive);
                    ui.Title      = ui.Title + " " + Helpers.DisplayVersion;

                    // Bind IPC actions to the form, this allows another instance to trigger form actions
                    RemoteClient.Bind(ui, doc);


                    //initialize the main window, set it as the application main window
                    //and close the splash screen
                    this.MainWindow = ui;


                    MainWindow.Show();
                    splashScreen.Close();
                });
            });
        }
Beispiel #13
0
        public bool ProcessTorrentFile(string torrentFile, TreeView tvTree, CommandLineArgs args)
        {
            // ----------------------------------------
            // read in torrent file

            if (tvTree != null)
            {
                tvTree.Nodes.Clear();
            }

            BEncodeLoader bel    = new BEncodeLoader();
            BTFile        btFile = bel.Load(torrentFile);

            if (btFile is null)
            {
                return(false);
            }

            BTItem bti = btFile.GetItem("info");

            if ((bti is null) || (bti.Type != BTChunk.kDictionary))
            {
                return(false);
            }

            BTDictionary infoDict = (BTDictionary)(bti);

            bti = infoDict.GetItem("piece length");
            if ((bti is null) || (bti.Type != BTChunk.kInteger))
            {
                return(false);
            }

            long pieceSize = ((BTInteger)bti).Value;

            bti = infoDict.GetItem("pieces");
            if ((bti is null) || (bti.Type != BTChunk.kString))
            {
                return(false);
            }

            BTString torrentPieces = (BTString)(bti);

            bti = infoDict.GetItem("files");

            if (bti is null) // single file torrent
            {
                bti = infoDict.GetItem("name");
                if ((bti is null) || (bti.Type != BTChunk.kString))
                {
                    return(false);
                }

                BTString di            = (BTString)(bti);
                string   nameInTorrent = di.AsString();

                BTItem fileSizeI = infoDict.GetItem("length");
                long   fileSize  = ((BTInteger)fileSizeI).Value;

                NewTorrentEntry(torrentFile, -1);
                if (DoHashChecking)
                {
                    byte[] torrentPieceHash = torrentPieces.StringTwentyBytePiece(0);

                    FileInfo fi = FindLocalFileWithHashAt(torrentPieceHash, 0, pieceSize, fileSize);
                    if (fi != null)
                    {
                        FoundFileOnDiskForFileInTorrent(torrentFile, fi, -1, nameInTorrent);
                    }
                    else
                    {
                        DidNotFindFileOnDiskForFileInTorrent(torrentFile, -1, nameInTorrent);
                    }
                }

                FinishedTorrentEntry(torrentFile, -1, nameInTorrent);

                // don't worry about updating overallPosition as this is the only file in the torrent
            }
            else
            {
                long overallPosition   = 0;
                long lastPieceLeftover = 0;

                if (bti.Type != BTChunk.kList)
                {
                    return(false);
                }

                BTList fileList = (BTList)(bti);

                // list of dictionaries
                for (int i = 0; i < fileList.Items.Count; i++)
                {
                    Prog(100 * i / fileList.Items.Count, i.ToString());
                    if (fileList.Items[i].Type != BTChunk.kDictionary)
                    {
                        return(false);
                    }

                    BTDictionary file    = (BTDictionary)(fileList.Items[i]);
                    BTItem       thePath = file.GetItem("path");
                    if (thePath.Type != BTChunk.kList)
                    {
                        return(false);
                    }

                    BTList pathList = (BTList)(thePath);
                    // want the last of the items in the list, which is the filename itself
                    int n = pathList.Items.Count - 1;
                    if (n < 0)
                    {
                        return(false);
                    }

                    BTString fileName = (BTString)(pathList.Items[n]);

                    BTItem fileSizeI = file.GetItem("length");
                    long   fileSize  = ((BTInteger)fileSizeI).Value;

                    int pieceNum = (int)(overallPosition / pieceSize);
                    if (overallPosition % pieceSize != 0)
                    {
                        pieceNum++;
                    }

                    NewTorrentEntry(torrentFile, i);

                    if (DoHashChecking)
                    {
                        byte[] torrentPieceHash = torrentPieces.StringTwentyBytePiece(pieceNum);

                        FileInfo fi = FindLocalFileWithHashAt(torrentPieceHash, lastPieceLeftover, pieceSize, fileSize);
                        if (fi != null)
                        {
                            FoundFileOnDiskForFileInTorrent(torrentFile, fi, i, fileName.AsString());
                        }
                        else
                        {
                            DidNotFindFileOnDiskForFileInTorrent(torrentFile, i, fileName.AsString());
                        }
                    }

                    FinishedTorrentEntry(torrentFile, i, fileName.AsString());

                    int sizeInPieces = (int)(fileSize / pieceSize);
                    if (fileSize % pieceSize != 0)
                    {
                        sizeInPieces++; // another partial piece
                    }
                    lastPieceLeftover = (lastPieceLeftover + (int)((sizeInPieces * pieceSize) - fileSize)) % pieceSize;
                    overallPosition  += fileSize;
                } // for each file in the torrent
            }

            if (tvTree != null)
            {
                tvTree.BeginUpdate();
                btFile.Tree(tvTree.Nodes);
                tvTree.ExpandAll();
                tvTree.EndUpdate();
                tvTree.Update();
            }

            Prog(0, string.Empty);

            return(true);
        }
Beispiel #14
0
        public bool DoWork(List <string> Torrents, string searchFolder, ListView results, bool hashSearch,
                           bool matchMissing, bool setPrios, bool testMode,
                           bool searchSubFolders, ItemList missingList, List <TVSettings.FilenameProcessorRE> rexps, CommandLineArgs args)
        {
            Rexps = rexps;

            if (!matchMissing && !hashSearch)
            {
                return(true); // nothing to do
            }
            if (hashSearch && string.IsNullOrEmpty(searchFolder))
            {
                return(false);
            }

            if (matchMissing && ((missingList is null) || (rexps is null)))
            {
                return(false);
            }

            MissingList    = missingList;
            DoMatchMissing = matchMissing;
            DoHashChecking = hashSearch;
            SetPrios       = setPrios;
            Results        = results;

            Prog(0, string.Empty);

            if (!LoadResumeDat())
            {
                return(false);
            }

            bool r = true;

            Prog(0, string.Empty);

            if (hashSearch)
            {
                BuildFileCache(searchFolder, searchSubFolders);
            }

            foreach (string tf in Torrents)
            {
                r = ProcessTorrentFile(tf, null, args);
                if (!r) // stop on the first failure
                {
                    break;
                }
            }

            if (Altered && !testMode)
            {
                WriteResumeDat();
            }

            Prog(0, string.Empty);

            return(r);
        }
Beispiel #15
0
        public bool RenameFilesOnDiskToMatchTorrent(string torrentFile, string folder, TreeView tvTree,
            ItemList renameListOut,
            bool copyNotMove, string copyDest, CommandLineArgs args)
        {
            if ((string.IsNullOrEmpty(folder) || !Directory.Exists(folder)))
                return false;

            if (string.IsNullOrEmpty(torrentFile))
                return false;

            if (renameListOut == null)
                return false;

            if (copyNotMove && (string.IsNullOrEmpty(copyDest) || !Directory.Exists(copyDest)))
                return false;

            this.CopyNotMove = copyNotMove;
            this.CopyToFolder = copyDest;
            this.DoHashChecking = true;
            this.RenameListOut = renameListOut;

            this.Prog(0);

            this.BuildFileCache(folder, false); // don't do subfolders

            this.RenameListOut.Clear();

            bool r = this.ProcessTorrentFile(torrentFile, tvTree, args);

            return r;
        }
Beispiel #16
0
        public bool RenameFilesToMatchTorrent(string torrent, string folder, TreeView tvTree, SetProgressDelegate prog, bool copyNotMove, string copyDest, CommandLineArgs args)
        {
            if (string.IsNullOrEmpty(folder))
                return false;
            if (string.IsNullOrEmpty(torrent))
                return false;

            if (copyNotMove)
            {
                if (string.IsNullOrEmpty(copyDest))
                    return false;
                if (!Directory.Exists(copyDest))
                    return false;
            }

            this.Stats().TorrentsMatched++;

            BTFileRenamer btp = new BTFileRenamer(prog);
            ItemList newList = new ItemList();
            bool r = btp.RenameFilesOnDiskToMatchTorrent(torrent, folder, tvTree, newList, copyNotMove, copyDest, args);

            foreach (Item i in newList)
                this.TheActionList.Add(i);

            return r;
        }
Beispiel #17
0
        public Episode(SeriesInfo ser, Season seas, XmlReader r, CommandLineArgs args)
        {
            // <Episode>
            //  <id>...</id>
            //  blah blah
            // </Episode>

            try
            {
                this.SetDefaults(ser, seas);

                r.Read();
                if (r.Name != "Episode")
                {
                    return;
                }

                r.Read();
                while (!r.EOF)
                {
                    if ((r.Name == "Episode") && (!r.IsStartElement()))
                    {
                        break;
                    }
                    if (r.Name == "id")
                    {
                        this.EpisodeID = r.ReadElementContentAsInt();
                    }
                    else if (r.Name == "seriesid")
                    {
                        this.SeriesID = r.ReadElementContentAsInt(); // thetvdb series id
                    }
                    else if (r.Name == "seasonid")
                    {
                        this.SeasonID = r.ReadElementContentAsInt();
                    }
                    else if (r.Name == "EpisodeNumber")
                    {
                        this.EpNum = r.ReadElementContentAsInt();
                    }
                    else if (r.Name == "SeasonNumber")
                    {
                        String sn = r.ReadElementContentAsString();
                        int.TryParse(sn, out this.ReadSeasonNum);
                    }
                    else if (r.Name == "lastupdated")
                    {
                        this.Srv_LastUpdated = r.ReadElementContentAsInt();
                    }
                    else if (r.Name == "Overview")
                    {
                        this.Overview = XMLHelper.ReadStringFixQuotesAndSpaces(r);
                    }
                    else if (r.Name == "Rating")
                    {
                        this.EpisodeRating = XMLHelper.ReadStringFixQuotesAndSpaces(r);
                    }
                    else if (r.Name == "GuestStars")
                    {
                        this.EpisodeGuestStars = XMLHelper.ReadStringFixQuotesAndSpaces(r);
                    }
                    else if (r.Name == "EpisodeDirector")
                    {
                        this.EpisodeDirector = XMLHelper.ReadStringFixQuotesAndSpaces(r);
                    }
                    else if (r.Name == "Writer")
                    {
                        this.Writer = XMLHelper.ReadStringFixQuotesAndSpaces(r);
                    }
                    else if (r.Name == "EpisodeName")
                    {
                        this.Name = XMLHelper.ReadStringFixQuotesAndSpaces(r);
                    }
                    else if (r.Name == "FirstAired")
                    {
                        try
                        {
                            String contents = r.ReadElementContentAsString();
                            if (contents == "")
                            {
                                logger.Info("Please confirm, but we are assuming that " + this.Name + "(episode Id =" + this.EpisodeID + ") has no airdate");
                                this.FirstAired = null;
                            }
                            else
                            {
                                this.FirstAired = DateTime.ParseExact(contents, "yyyy-MM-dd", new System.Globalization.CultureInfo(""));
                            }
                        }
                        catch
                        {
                            this.FirstAired = null;
                        }
                    }
                    else
                    {
                        if ((r.IsEmptyElement) || !r.IsStartElement())
                        {
                            r.ReadOuterXml();
                        }
                        else
                        {
                            XmlReader r2 = r.ReadSubtree();
                            r2.Read();
                            string name = r2.Name;
                            this.Items[name] = r2.ReadElementContentAsString();
                            r.Read();
                        }
                    }
                }
            }
            catch (XmlException e)
            {
                string message = "Error processing data from TheTVDB for an episode.";
                if (this.SeriesID != -1)
                {
                    message += "\r\nSeries ID: " + this.SeriesID;
                }
                if (this.EpisodeID != -1)
                {
                    message += "\r\nEpisode ID: " + this.EpisodeID;
                }
                if (this.EpNum != -1)
                {
                    message += "\r\nEpisode Number: " + this.EpNum;
                }
                if (!string.IsNullOrEmpty(this.Name))
                {
                    message += "\r\nName: " + this.Name;
                }


                logger.Error(e, message);

                throw new TVDBException(e.Message);
            }
        }
Beispiel #18
0
        public Banner(SeriesInfo ser, Season seas, int? codeHint, XmlReader r, CommandLineArgs args)
        {
            // <Banner>
            //        <id>708811</id>
            //        <BannerPath>seasonswide/79488-5.jpg</BannerPath>
            //        <BannerType>season</BannerType>
            //        <BannerType2>seasonwide</BannerType2>
            //        <Language>en</Language>
            //        <Rating/>
            //        <RatingCount>0</RatingCount>
            //        <Season>5</Season>
            //  blah blah
            // </Banner>



            try
            {
                this.SetDefaults(ser, seas);

                this.SeriesID = (int) codeHint;

                r.Read();
                if (r.Name != "Banner")
                    return;

                r.Read();
                while (!r.EOF)
                {
                    if ((r.Name == "Banner") && (!r.IsStartElement()))
                        break;

                    if (r.Name == "id")
                        this.BannerId = r.ReadElementContentAsInt();
                    else if (r.Name == "seriesid")
                        this.SeriesID = r.ReadElementContentAsInt(); // thetvdb series id
                    else if (r.Name == "seasonid")
                        this.SeasonID = r.ReadElementContentAsInt();
                    else if (r.Name == "BannerPath")
                        this.BannerPath = XMLHelper.ReadStringFixQuotesAndSpaces(r);
                    else if (r.Name == "BannerType")
                        this.BannerType = r.ReadElementContentAsString();
                    else if (r.Name == "BannerType2")
                        this.BannerType2 = r.ReadElementContentAsString();
                    else if (r.Name == "Language")
                        this.Language = r.ReadElementContentAsString();
                    else if (r.Name == "Rating")
                        {
                        String sn = r.ReadElementContentAsString();
                        double.TryParse(sn, out this.Rating);
                        }
                    else if (r.Name == "RatingCount")
                        this.RatingCount  = r.ReadElementContentAsInt();
                    else if (r.Name == "Season")
                        this.SeasonID = r.ReadElementContentAsInt();
                    else if (r.Name == "Colors") this.Colors = r.ReadElementContentAsString();
                    else if (r.Name == "ThumbnailPath") this.ThumbnailPath = r.ReadElementContentAsString();
                    else if (r.Name == "VignettePath") this.VignettePath = r.ReadElementContentAsString();
                    else if (r.Name == "SeriesName") this.SeriesName = r.ReadElementContentAsString();
                    else
                    {
                        if ((r.IsEmptyElement) || !r.IsStartElement())
                            r.ReadOuterXml();
                        else
                            r.Read();
                    }
                }
            }
            catch (XmlException e)
            {
                string message = "Error processing data from TheTVDB for a banner.";
                if (this.SeriesID != -1)
                    message += "\r\nSeries ID: " + this.SeriesID;
                if (this.BannerId != -1)
                    message += "\r\nBanner ID: " + this.BannerId;
                if (!string.IsNullOrEmpty(this.BannerPath))
                    message += "\r\nBanner Path: " + this.BannerPath;
                if (!string.IsNullOrEmpty(this.Name))
                    message += "\r\nName: " + this.Name;

                message += "\r\n" + e.Message;

                if (!args.Unattended) 
                    MessageBox.Show(message, "TVRename", MessageBoxButtons.OK, MessageBoxIcon.Error);

                throw new TVDBException(e.Message);
            }
        }
Beispiel #19
0
        public Episode(SeriesInfo ser, Season seas, XmlReader r, CommandLineArgs args)
        {
            // <Episode>
            //  <id>...</id>
            //  blah blah
            // </Episode>

            try
            {
                this.SetDefaults(ser, seas);

                r.Read();
                if (r.Name != "Episode")
                    return;

                r.Read();
                while (!r.EOF)
                {
                    if ((r.Name == "Episode") && (!r.IsStartElement()))
                        break;
                    if (r.Name == "id")
                        this.EpisodeID = r.ReadElementContentAsInt();
                    else if (r.Name == "seriesid")
                        this.SeriesID = r.ReadElementContentAsInt(); // thetvdb series id
                    else if (r.Name == "seasonid")
                        this.SeasonID = r.ReadElementContentAsInt();
                    else if (r.Name == "EpisodeNumber")
                        this.EpNum = r.ReadElementContentAsInt();
                    else if (r.Name == "SeasonNumber")
                    {
                        String sn = r.ReadElementContentAsString();
                        int.TryParse(sn, out this.ReadSeasonNum);
                    }
                    else if (r.Name == "lastupdated")
                        this.Srv_LastUpdated = r.ReadElementContentAsInt();
                    else if (r.Name == "Overview")
                        this.Overview = Helpers.ReadStringFixQuotesAndSpaces(r);
                    else if (r.Name == "Rating")        
                        this.EpisodeRating = Helpers.ReadStringFixQuotesAndSpaces(r);  
                    else if (r.Name == "GuestStars")
                        this.EpisodeGuestStars = Helpers.ReadStringFixQuotesAndSpaces(r);      
                    else if (r.Name == "Director")
                        this.EpisodeDirector = Helpers.ReadStringFixQuotesAndSpaces(r);      
                    else if (r.Name == "Writer")
                        this.Writer = Helpers.ReadStringFixQuotesAndSpaces(r);      
                    else if (r.Name == "EpisodeName")
                        this.Name = Helpers.ReadStringFixQuotesAndSpaces(r);
                    else if (r.Name == "FirstAired")
                    {
                        try
                        {
                            this.FirstAired = DateTime.ParseExact(r.ReadElementContentAsString(), "yyyy-MM-dd", new System.Globalization.CultureInfo(""));
                        }
                        catch
                        {
                            this.FirstAired = null;
                        }
                    }
                    else
                    {
                        if ((r.IsEmptyElement) || !r.IsStartElement())
                            r.ReadOuterXml();
                        else
                        {
                            XmlReader r2 = r.ReadSubtree();
                            r2.Read();
                            string name = r2.Name;
                            this.Items[name] = r2.ReadElementContentAsString();
                            r.Read();
                        }
                    }
                }
            }
            catch (XmlException e)
            {
                string message = "Error processing data from TheTVDB for an episode.";
                if (this.SeriesID != -1)
                    message += "\r\nSeries ID: " + this.SeriesID;
                if (this.EpisodeID != -1)
                    message += "\r\nEpisode ID: " + this.EpisodeID;
                if (this.EpNum != -1)
                    message += "\r\nEpisode Number: " + this.EpNum;
                if (!string.IsNullOrEmpty(this.Name))
                    message += "\r\nName: " + this.Name;

                message += "\r\n" + e.Message;

                if (!args.Unattended) 
                    MessageBox.Show(message, "TVRename", MessageBoxButtons.OK, MessageBoxIcon.Error);

                throw new TVDBException(e.Message);
            }
        }