Beispiel #1
0
        static public XmlNode GetSeries(String sSeriesName, string aLanguageCode = "en")
        {
            string lEncodedSeriesName;

            try
            {
                lEncodedSeriesName = Uri.EscapeDataString(sSeriesName);
            }
            catch (UriFormatException ex)
            {
                MPTVSeriesLog.Write($"Failed to get encoded series name of '{sSeriesName}'. Error={ex.Message}");
                lEncodedSeriesName = HttpUtility.UrlEncode(sSeriesName);
            }

            return(Generic(string.Format(apiURIs.GetSeries, lEncodedSeriesName, aLanguageCode), true, false, Format.NoExtension));
        }
        private IList <parseResult> IdentifyChanges(bool includeDisabled)
        {
            List <parseResult> changes = new List <parseResult>();

            Dictionary <string, parseResult> origParseResults = origResults.ToDictionary(pr => pr.full_filename, pr => pr);

            foreach (DataGridViewRow row in dataGridViewReview.Rows)
            {
                if (includeDisabled || (bool)row.Cells[0].Value == true)
                {
                    // check if every editable col still equals to the original parseresult
                    for (int i = 0; i < uniqueCols.Count; i++)
                    {
                        if (row.Tag is parseResult)
                        {
                            //var origPR = origResults.SingleOrDefault(pr => pr.full_filename == (row.Tag as parseResult).full_filename);

                            parseResult origPR;
                            if (origParseResults.TryGetValue((row.Tag as parseResult).full_filename, out origPR))
                            //if (origPR != null)
                            {
                                origPR.success = (bool)row.Cells[0].Value == true;
                                var    colname = uniqueCols[i].Name;
                                string origValue;
                                string newValue = row.Cells[colname].Value as string;

                                if ((!origPR.parser.Matches.TryGetValue(colname, out origValue) && !string.IsNullOrEmpty(newValue)) || // manually added
                                    (newValue != origValue))    // or changed
                                {
                                    MPTVSeriesLog.Write(string.Format("User Change Detected for: \"{0}\" Column: \"{1}\" - From: \"{2}\" to \"{3}\"",
                                                                      origPR.match_filename, colname, origValue, newValue));
                                    // this one was changed
                                    // update the parsingResult
                                    origPR.parser.Matches[colname] = newValue;
                                }
                            }
                        }
                    }
                    if (row.Tag is parseResult)
                    {
                        changes.Add(row.Tag as parseResult);
                    }
                }
            }
            return(changes);
        }
Beispiel #3
0
        static public bool SubmitRating(RatingType type, string itemId, int rating)
        {
            string account = DBOption.GetOptions(DBOption.cOnlineUserID);

            if (String.IsNullOrEmpty(account))
            {
                string[] lines = new string[] { Translation.TVDB_INFO_ACCOUNTID_1, Translation.TVDB_INFO_ACCOUNTID_2 };
                //TVSeriesPlugin.ShowDialogOk(Translation.TVDB_INFO_TITLE, lines); //trakt.tv also listens to this, also can store ratings locally.
                MPTVSeriesLog.Write("Cannot submit rating to thetvdb.com, this requires your Account Identifier to be set.");
                return(false);
            }

            if (itemId == "0" || rating < 0 || rating > 10)
            {
                MPTVSeriesLog.Write("Cannot submit rating, invalid values...this is most likely a programming error");
                return(false);
            }

            if (!DBOnlineMirror.IsMirrorsAvailable)
            {
                // Server maybe available now.
                DBOnlineMirror.Init();
                if (!DBOnlineMirror.IsMirrorsAvailable)
                {
                    GUIDialogOK dlgOK = ( GUIDialogOK )GUIWindowManager.GetWindow(( int )GUIWindow.Window.WINDOW_DIALOG_OK);
                    dlgOK.SetHeading(Translation.TVDB_ERROR_TITLE);
                    if (!TVSeriesPlugin.IsNetworkAvailable)
                    {
                        string[] lines = new string[] { Translation.NETWORK_ERROR_UNAVAILABLE_1, Translation.NETWORK_ERROR_UNAVAILABLE_2 };
                        TVSeriesPlugin.ShowDialogOk(Translation.TVDB_ERROR_TITLE, lines);
                    }
                    else
                    {
                        string[] lines = new string[] { Translation.TVDB_ERROR_UNAVAILABLE_1, Translation.TVDB_ERROR_UNAVAILABLE_2 };
                        TVSeriesPlugin.ShowDialogOk(Translation.TVDB_ERROR_TITLE, lines);
                    }

                    MPTVSeriesLog.Write("Cannot submit rating, the online database is unavailable");
                    return(false);
                }
            }
            // ok we're good
            MPTVSeriesLog.Write(string.Format("Submitting Rating of {2} for {0} {1}", type.ToString(), itemId, rating), MPTVSeriesLog.LogLevel.Debug);
            Generic(string.Format(apiURIs.SubmitRating, account, type.ToString(), itemId, rating), true, false, Format.NoExtension);
            return(true);
        }
Beispiel #4
0
        private void bgTraktSync_DoWork(object sender, DoWorkEventArgs e)
        {
            MPTVSeriesLog.Write("Trakt: Synchronize Start");

            buttonManualSync.Text = cButtonCancelSync;
            ConfigurationForm.GetInstance().EnableImportButtonState(false);

            List <DBSeries> seriesList = DBSeries.Get(new SQLCondition());

            int progress = 0;

            foreach (DBSeries series in seriesList)
            {
                if (bgTraktSync.CancellationPending)
                {
                    return;
                }

                if (series[DBSeries.cID] <= 0)
                {
                    continue;
                }

                List <DBEpisode> episodesUnSeen  = TraktHandler.GetEpisodesToSync(series, TraktSyncModes.unseen);
                List <DBEpisode> episodesLibrary = TraktHandler.GetEpisodesToSync(series, TraktSyncModes.library);
                List <DBEpisode> episodesSeen    = TraktHandler.GetEpisodesToSync(series, TraktSyncModes.seen);

                // remove any seen episodes from library episode list as 'seen' counts as being part of the library
                // dont want to hit the server unnecessarily
                episodesLibrary.RemoveAll(eps => episodesSeen.Contains(eps));

                // sync UnSeen
                TraktHandler.SynchronizeLibrary(episodesUnSeen, TraktSyncModes.unseen);

                // sync library
                TraktHandler.SynchronizeLibrary(episodesLibrary, TraktSyncModes.library);

                // sync Seen
                TraktHandler.SynchronizeLibrary(episodesSeen, TraktSyncModes.seen);

                int percentage = Convert.ToInt32((double)(100 * progress++) / seriesList.Count());
                bgTraktSync.ReportProgress(percentage);
            }

            MPTVSeriesLog.Write("Trakt: Synchronize Complete");
        }
        private void lnkImport_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.IO.StreamReader w = null;
            try
            {
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    w = new System.IO.StreamReader(openFileDialog1.FileName);
                    List <DBFormatting> imports = new List <DBFormatting>();
                    string   line;
                    string[] splits = new string[] { "<Enabled>", "<Format>", "<FormatAs>" };
                    while ((line = w.ReadLine()) != null)
                    {
                        string[] properties = line.Split(splits, StringSplitOptions.RemoveEmptyEntries);
                        if (properties.Length == 3)
                        {
                            DBFormatting dbf = new DBFormatting();
                            dbf[DBFormatting.cEnabled] = properties[0];
                            dbf[DBFormatting.cReplace] = properties[1];
                            dbf[DBFormatting.cWith]    = properties[2];
                            imports.Add(dbf);
                            // now for add each one to the list
                            saveToDBAndReload(dbf, true);
                        }
                        else
                        {
                            MessageBox.Show("Unable to Import: " + line);
                        }
                    }

                    MPTVSeriesLog.Write(imports.Count.ToString() + " Formatting Rules Imported", MPTVSeriesLog.LogLevel.Normal);
                }
            }
            catch (Exception ex)
            {
                MPTVSeriesLog.Write("Error in trying to Export User Formatting Rules: " + ex.Message);
            }
            finally
            {
                if (w != null)
                {
                    w.Close();
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// Parses a given mathematical expression and evaluates it
        /// </summary>
        /// <param name="expression">The expression to parse</param>
        /// <returns>returns the result of the mathematical expression, or null if it cannot be evaluated</returns>
        public static double?Parse(string expression, out string stringResult)
        {
            //MPTVSeriesLog.Write("Mathparser: Trying ", expression, MPTVSeriesLog.LogLevel.Debug);
            double?result = null;

            stringResult = null;
            if (cache.TryGetValue(expression, out stringResult))
            {
                return(null);
            }
            try
            {
                StringBuilder builder = new StringBuilder(expression);
                //StringBuilder builder = new StringBuilder(expression.Replace(" ", ""));
                foreach (mathConstant c in constants)
                {
                    builder.Replace(c.form, c.Value.ToString(provider));
                }
                result = breakdDown(builder.ToString(), out stringResult);
            }
            catch (Exception e)
            {
                MPTVSeriesLog.Write("Mathparser: Critical Error ", e.Message, MPTVSeriesLog.LogLevel.Normal);
            }
            if (null != result)
            {
                //MPTVSeriesLog.Write(String.Format("Mathparser: Total Result: {0} = {1}", expression, result.ToString()), MPTVSeriesLog.LogLevel.Debug);
                lock (cache)
                    if (!cache.ContainsKey(expression)) // another thread might have added it in the meantime
                    {
                        cache.Add(expression, result.ToString());
                    }
            }
            else if (stringResult != null)
            {
                //MPTVSeriesLog.Write(String.Format("Mathparser: Total Result as String: {0} = {1}", expression, stringResult), MPTVSeriesLog.LogLevel.Debug);
                lock (cache)
                    if (!cache.ContainsKey(expression)) // another thread might have added it in the meantime
                    {
                        cache.Add(expression, stringResult);
                    }
            }
            return(result);
        }
Beispiel #7
0
        static decimal?atomicOperation(string expression)
        {
            decimal no1, no2;
            Match   m = singleOp.Match(expression);

            if (m == null)
            {
                return(null);
            }
            if (!decimal.TryParse(m.Groups["no1"].Value, NumberStyles.Number, provider, out no1))
            {
                return(null);
            }
            if (!decimal.TryParse(m.Groups["no2"].Value, NumberStyles.Number, provider, out no2))
            {
                return(null);
            }

            switch (MatchAtomOperation(m.Groups["type"].Value))
            {
            case atomicOperationType.addition:
                return(no1 + no2);

            case atomicOperationType.substraction:
                return(no1 - no2);

            case atomicOperationType.multiplication:
                return(no1 * no2);

            case atomicOperationType.division:
                return(no1 / no2);

            case atomicOperationType.mod:
                return(no1 % no2);

            case atomicOperationType.pow:
            //return Math.Pow((double)no1, no2);
            default: MPTVSeriesLog.Write("MathParser: Unknown operand: " + m.Groups["type"].Value, MPTVSeriesLog.LogLevel.Debug);
                break;
            }

            return(null);
        }
        void autoChangeAll(int column, string orig, string newval)
        {
            dataGridViewReview.SuspendLayout();

            foreach (DataGridViewRow row in dataGridViewReview.Rows)
            {
                if (row.Visible) // only filtered (currently displayed)
                {
                    if (row.Cells[column].Value as string == orig)
                    {
                        MPTVSeriesLog.Write(row.Cells[column].Value + "->" + newval);
                        row.Cells[column].Value = newval;
                    }
                }
            }

            RefreshGrid();
            dataGridViewReview.ResumeLayout();
        }
Beispiel #9
0
        static Stream RetrieveData(String aUrl)
        {
            MPTVSeriesLog.Write($"Retrieving Data from '{aUrl}'", MPTVSeriesLog.LogLevel.Debug);
            if (aUrl == null || aUrl.Length < 1 || aUrl[0] == '/')
            {
                // this happens if no active mirror is set
                return(null);
            }

            HttpWebRequest  lRequest;
            HttpWebResponse lResponse;

            try
            {
                // .NET 4.0: Use TLS v1.2. Many download sources no longer support the older and now insecure TLS v1.0/1.1 and SSL v3.
                ServicePointManager.SecurityProtocol = ( SecurityProtocolType )0xc00;

                // force secure http
                lRequest = ( HttpWebRequest )WebRequest.Create(aUrl);
                // Note: some network proxies require the useragent string to be set or they will deny the http request
                // this is true for instance for EVERY thailand internet connection (also needs to be set for banners/episodethumbs and any other http request we send)
                lRequest.UserAgent = Settings.UserAgent;
                lRequest.Timeout   = 60000;

                lResponse = ( HttpWebResponse )lRequest.GetResponse();

                if (lResponse != null)   // Get the stream associated with the response.
                {
                    return(lResponse.GetResponseStream());
                }
            }
            catch (Exception e)
            {
                MPTVSeriesLog.Write($"Unable to connect to '{aUrl}'. Error = '{e.Message}'");
            }
            finally
            {
                //if (response != null) response.Close(); // screws up the decompression
            }

            return(null);
        }
Beispiel #10
0
        static public XmlNode ConfigureFavourites(bool bAdd, String sAccountID, String sSeriesID)
        {
            if (sAccountID.Length == 0)
            {
                MPTVSeriesLog.Write("Cannot submit online favourite, make sure you have your Account identifier is set!");
                return(null);
            }

            if (bAdd)
            {
                MPTVSeriesLog.Write(string.Format("Adding favourite series \"{0}\" to online database (theTVDB.com)", Helper.getCorrespondingSeries(int.Parse(sSeriesID))));
            }
            else
            {
                MPTVSeriesLog.Write(string.Format("Removing favourite series \"{0}\" from online database (theTVDB.com)", Helper.getCorrespondingSeries(int.Parse(sSeriesID))));
            }

            string url = String.Format(apiURIs.ConfigureFavourites, sAccountID, (bAdd ? "add" : "remove"), sSeriesID);

            return(Generic(url, true, false, Format.NoExtension));
        }
        private void DoLocalParsing()
        {
            LocalParse runner = new LocalParse();

            runner.LocalParseCompleted += new LocalParse.LocalParseCompletedHandler(//runner_LocalParseCompleted);
                results =>
            {
                allFoundFiles = results.Select(r => r.PathPair).ToList();
                OnlineParsing.RemoveFilesInDB(ref results);
                this.labelWaitParse.Text = "Local File Parsing is done, displaying Results...";
                MPTVSeriesLog.Write(this.labelWaitParse.Text);
                origResults = results.ToList <parseResult>();
                FillGrid(results);
                this.labelWaitParse.Text = "Please make changes to the Results below, and/or add files. Click Next to continue.";
                // fire off event so user can click Next in wizard
                if (ParsingGridPopulated != null)
                {
                    ParsingGridPopulated();
                }
            });
            runner.AsyncFullParse();
        }
Beispiel #12
0
        private void DeleteActorThumbs()
        {
            GetActors actors = new GetActors(SeriesId);

            foreach (DBActor actor in actors.Actors)
            {
                string fileName = actor.Image;
                if (string.IsNullOrEmpty(fileName))
                {
                    continue;
                }

                try
                {
                    File.Delete(actor.Image);
                }
                catch (Exception e)
                {
                    MPTVSeriesLog.Write("Unable to delete actor image '{0}', {1}", fileName, e.Message);
                }
            }
        }
Beispiel #13
0
        static string stringOption(string input)
        {
            string[] parameters = input.Split(new string[] { "->" }, StringSplitOptions.RemoveEmptyEntries);
            string[] options    = parameters[1].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            MPTVSeriesLog.Write("MathParser: StringOptions -> prev Result was set to ", prevResult.ToString(), MPTVSeriesLog.LogLevel.Debug);

            if (options.Length >= prevResult)
            {
                double result;
                if (double.TryParse(parameters[0], NumberStyles.Number, provider, out result))
                {
                    return(result.ToString() + options[prevResult]);
                }
                else
                {
                    return(string.Empty);
                }
            }

            return(string.Empty);
        }
        private Dictionary <string, UserInputResultSeriesActionPair> getApprovedResults()
        {
            var pageResult = new Dictionary <string, UserInputResultSeriesActionPair>();

            foreach (DataGridViewRow row in dataGridViewIdentifySeries.Rows)
            {
                string         inputSeriesName = row.Cells[ColIndexOf(colSeries)].Value as string;
                var            requestedAction = getActionFromRow(row);
                DBOnlineSeries chosenSeries    = null;

                // else we dont even care
                if (requestedAction == UserInputResults.SeriesAction.Approve)
                {
                    chosenSeries = getSeriesFromSelected(row);
                }

                MPTVSeriesLog.Write(string.Format("Series \"{0}\" {1} {2}", inputSeriesName, requestedAction.ToString(), chosenSeries == null ? string.Empty : this.getDisplayStringForSeries(chosenSeries)));

                pageResult.Add(inputSeriesName, new UserInputResultSeriesActionPair(requestedAction, chosenSeries));
            }

            return(pageResult);
        }
Beispiel #15
0
        static Dictionary <string, XmlDocument> DecompressZipToXmls(Stream aStream)
        {
            MPTVSeriesLog.Write("Decompressing Stream...", MPTVSeriesLog.LogLevel.Debug);

            var lDocsInZip = new Dictionary <string, XmlDocument>();

            ZipConstants.DefaultCodePage = 850;
            var      lZipStream = new ZipInputStream(aStream);
            ZipEntry currEntry  = lZipStream.GetNextEntry();

            while (currEntry != null)
            {
                MPTVSeriesLog.Write("Decompressing Entry: ", currEntry.Name, MPTVSeriesLog.LogLevel.Debug);
                byte[] buffer = new byte[4096];

                var doc    = new XmlDocument();
                var stream = new MemoryStream();
                try
                {
                    StreamUtils.Copy(lZipStream, stream, buffer);
                    stream.Position = 0;
                    MPTVSeriesLog.Write("Decompression done, now loading as XML...", MPTVSeriesLog.LogLevel.Debug);
                    doc.Load(stream);
                    MPTVSeriesLog.Write("Loaded as valid XML", MPTVSeriesLog.LogLevel.Debug);
                    // check if .zip in filename and remove for backwards compatibility
                    lDocsInZip.Add(currEntry.Name.Replace(".zip", string.Empty), doc);
                }
                catch (XmlException e)
                {
                    MPTVSeriesLog.Write("Failed to load XML: " + e.Message.ToString());
                }

                stream.Close();
                currEntry = lZipStream.GetNextEntry();
            }
            return(lDocsInZip);
        }
Beispiel #16
0
        // Loads an Image from a File by invoking GDI Plus instead of using build-in
        // .NET methods, or falls back to Image.FromFile. GDI Plus should be faster.
        public static Image LoadImageFastFromFile(string filename)
        {
            IntPtr imagePtr = IntPtr.Zero;
            Image  image    = null;

            try {
                if (GdipLoadImageFromFile(filename, out imagePtr) != 0)
                {
                    MPTVSeriesLog.Write("AsyncImageResource: gdiplus.dll method failed. Will degrade performance.");
                    image = Image.FromFile(filename);
                }

                else
                {
                    image = (Image)typeof(Bitmap).InvokeMember("FromGDIplus", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[] { imagePtr });
                }
            }
            catch (Exception) {
                MPTVSeriesLog.Write("AsyncImageResource: Failed to load image from {0}", filename);
                image = null;
            }

            return(image);
        }
Beispiel #17
0
 /// <summary>
 /// Translates an expression e.g. Trans(FirstAired) => "First Aired"
 /// </summary>
 /// <param name="expression">An Expression which may contain one or more translated strings</param>
 /// <returns>Translated expression</returns>
 public static string TranslateExpression(string expression)
 {
     try {
         string replace, with;
         while (parenthesisFinder(expression, translateFormat, out replace, out with))
         {
             if (Translation.Strings.ContainsKey(with))
             {
                 expression = expression.Replace(replace, Translation.Strings[with]);
             }
             else
             {
                 MPTVSeriesLog.Write("Translation not Found: " + replace);
                 expression = expression.Replace(replace, string.Empty);
             }
         }
         return
             (expression);
     }
     catch (Exception e) {
         MPTVSeriesLog.Write("Error translating expression: " + expression + " [" + e.Message + "]");
         return("Translation Error!");
     }
 }
Beispiel #18
0
        static XmlNode Generic(String sUrl, bool appendBaseUrl, bool appendAPIKey, Format format, string aLanguageId, int seriesIDIfZip)
        {
            if (format == Format.Zip)
            {
                if (appendBaseUrl)
                {
                    sUrl = DBOnlineMirror.ZipInterface + sUrl;
                }
            }
            else
            {
                if (appendBaseUrl && appendAPIKey)
                {
                    sUrl = DBOnlineMirror.Interface + sUrl;
                }
                else if (appendBaseUrl)
                {
                    sUrl = DBOnlineMirror.InterfaceWithoutKey + sUrl;
                }
            }
            switch (format)
            {
            case Format.Xml:
                sUrl += ".xml";
                break;

            case Format.Zip:
                sUrl += ".zip";
                break;
            }
            Stream lStreamData = RetrieveData(sUrl);

            if (lStreamData != null)
            {
                if (format == Format.Zip)
                {
                    if (!String.IsNullOrEmpty(aLanguageId) && seriesIDIfZip != 0)
                    {
                        // save the zip file downloaded to disk
                        //string lFilename = Path.Combine(Settings.GetPath(Settings.Path.config), string.Format(@"Cache\{0}\{1}.zip", seriesIDIfZip, aLanguageId));
                        //Helper.SaveZipCache(lFilename, lStreamData);

                        Dictionary <string, XmlDocument> lZip = DecompressZipToXmls(lStreamData);
                        string  lFilenameInZip = aLanguageId + ".xml";
                        XmlNode lRoot;

                        // save all xmls in zip to cache
                        foreach (string key in lZip.Keys)
                        {
                            string lFilename = Path.Combine(Settings.GetPath(Settings.Path.config), string.Format(@"Cache\{0}\{1}\{2}", seriesIDIfZip, aLanguageId, key));
                            Helper.SaveXmlCache(lFilename, lZip[key].FirstChild.NextSibling ?? lZip[key].FirstChild);
                        }

                        // get what we are looking for
                        if (lZip.ContainsKey(lFilenameInZip))
                        {
                            lRoot = lZip[lFilenameInZip].FirstChild.NextSibling;
                            return(lRoot);
                        }
                        else
                        {
                            MPTVSeriesLog.Write("Decompression returned null or not the requested entry");
                        }
                    }
                }
                else
                {
                    var    reader   = new StreamReader(lStreamData);
                    String sXmlData = string.Empty;
                    try
                    {
                        sXmlData = reader.ReadToEnd().Replace('\0', ' ');
                    }
                    catch (Exception e)
                    {
                        MPTVSeriesLog.Write("Error reading stream: {0}", e.Message);
                    }

                    lStreamData.Close();
                    reader.Close();
                    if (!string.IsNullOrEmpty(sXmlData))
                    {
                        MPTVSeriesLog.Write("*************************************", MPTVSeriesLog.LogLevel.Debug);
                        MPTVSeriesLog.Write(sXmlData, MPTVSeriesLog.LogLevel.Debug);
                        MPTVSeriesLog.Write("*************************************", MPTVSeriesLog.LogLevel.Debug);
                        try
                        {
                            var doc = new XmlDocument();
                            doc.LoadXml(sXmlData);
                            XmlNode root = doc.FirstChild.NextSibling;
                            return(root);
                        }
                        catch (XmlException e)
                        {
                            // Most likely bad xml formatting, tvdb does not use CDATA structures so good luck.
                            MPTVSeriesLog.Write("Xml parsing of " + sUrl + " failed (line " + e.LineNumber + " - " + e.Message + ")");
                        }
                    }
                }
            }
            return(null);
        }
Beispiel #19
0
        public GetUpdates(OnlineAPI.UpdateType type)
        {
            if (type != OnlineAPI.UpdateType.all)
            {
                MPTVSeriesLog.Write(string.Format("Downloading updates from the last {0}", type.ToString()));
            }
            else
            {
                MPTVSeriesLog.Write("Downloading all updates");
            }

            XmlNode updates = OnlineAPI.Updates(type);

            series   = new Dictionary <DBValue, long>();
            episodes = new Dictionary <DBValue, long>();
            banners  = new Dictionary <DBValue, long>();
            fanart   = new Dictionary <DBValue, long>();

            // if updates via zip fails, try xml
            if (updates == null)
            {
                MPTVSeriesLog.Write("Failed to get updates from 'zip' file, trying 'xml'...");
                updates = OnlineAPI.Updates(type, OnlineAPI.Format.Xml);

                // if we're still failing to get updates...
                if (updates == null)
                {
                    // manually define what series need updating basis whether the series is continuing and has local episodes
                    SQLCondition condition = new SQLCondition();
                    condition.Add(new DBOnlineSeries(), DBOnlineSeries.cID, 0, SQLConditionType.GreaterThan);
                    condition.Add(new DBOnlineSeries(), DBOnlineSeries.cHasLocalFiles, 1, SQLConditionType.Equal);
                    condition.Add(new DBOnlineSeries(), DBOnlineSeries.cStatus, "Ended", SQLConditionType.NotEqual);
                    condition.Add(new DBSeries(), DBSeries.cScanIgnore, 0, SQLConditionType.Equal);
                    condition.Add(new DBSeries(), DBSeries.cDuplicateLocalName, 0, SQLConditionType.Equal);

                    var lContinuingSeries = DBSeries.Get(condition, false, false);
                    MPTVSeriesLog.Write($"Failed to get updates from online, manually defining series and images for updates. Database contains '{lContinuingSeries.Count}' continuing series with local files");

                    // force our local download cache to expire after a 12hrs
                    timestamp = DateTime.UtcNow.Subtract(new TimeSpan(0, 12, 0, 0)).ToEpoch();
                    foreach (var lSeries in lContinuingSeries)
                    {
                        string lSeriesId = lSeries[DBOnlineSeries.cID];

                        series.Add(lSeriesId, timestamp);
                        banners.Add(lSeriesId, timestamp);
                        fanart.Add(lSeriesId, timestamp);

                        // get the most recent season as that is the one that is most likely recently updated
                        // NB: specials could also be recently updated
                        var lSeasons = DBSeason.Get(int.Parse(lSeriesId));
                        if (lSeasons != null && lSeasons.Count > 0)
                        {
                            int lSeasonIndex = lSeasons.Max(s => ( int )s[DBSeason.cIndex]);

                            var lEpisodes = DBEpisode.Get(int.Parse(lSeriesId), lSeasonIndex);
                            lEpisodes.AddRange(DBEpisode.Get(int.Parse(lSeriesId), 0));

                            foreach (var episode in lEpisodes)
                            {
                                episodes.Add(episode[DBOnlineEpisode.cID], timestamp);
                            }
                        }
                    }
                }
                else
                {
                    long.TryParse(updates.Attributes["time"].Value, out timestamp);

                    // get all available series in database, there is not point processing updates from online if not needed
                    var lAvailableSeriesInDb = DBSeries.Get(new SQLCondition()).Select(field => (string)field[DBOnlineSeries.cID]).ToList();

                    // NB: updates from xml only includes series (no episodes or artwork!)
                    foreach (XmlNode node in updates.SelectNodes("/Data/Series"))
                    {
                        long.TryParse(node.SelectSingleNode("time").InnerText, out long lTime);
                        string lSeriesId = node.SelectSingleNode("id").InnerText;

                        // check if we're interested in this series
                        if (!lAvailableSeriesInDb.Contains(lSeriesId))
                        {
                            continue;
                        }

                        series.Add(lSeriesId, lTime);
                        banners.Add(lSeriesId, lTime);
                        fanart.Add(lSeriesId, lTime);

                        // get the most recent season as that is the one that is most likely recently updated
                        // NB: specials could also be recently updated
                        if (Helper.getCorrespondingSeries(int.Parse(lSeriesId)) != null)
                        {
                            var lSeasons = DBSeason.Get(int.Parse(lSeriesId));
                            if (lSeasons != null && lSeasons.Count > 0)
                            {
                                int lSeasonIndex = lSeasons.Max(s => ( int )s[DBSeason.cIndex]);

                                var lEpisodes = DBEpisode.Get(int.Parse(lSeriesId), lSeasonIndex);
                                lEpisodes.AddRange(DBEpisode.Get(int.Parse(lSeriesId), 0));

                                foreach (var episode in lEpisodes)
                                {
                                    episodes.Add(episode[DBOnlineEpisode.cID], lTime);
                                }
                            }
                        }
                    }
                }
                return;
            }

            // process zip file update...
            long.TryParse(updates.Attributes["time"].Value, out this.timestamp);

            // get all the series ids
            foreach (XmlNode node in updates.SelectNodes("/Data/Series"))
            {
                long time;
                long.TryParse(node.SelectSingleNode("time").InnerText, out time);
                this.series.Add(node.SelectSingleNode("id").InnerText, time);
            }

            // get all the episode ids
            foreach (XmlNode node in updates.SelectNodes("/Data/Episode"))
            {
                long time;
                long.TryParse(node.SelectSingleNode("time").InnerText, out time);
                this.episodes.Add(node.SelectSingleNode("id").InnerText, time);
            }

            // get all the season banners
            string id = string.Empty;
            long   value;

            foreach (XmlNode node in updates.SelectNodes("/Data/Banner[type='season']"))
            {
                long time;
                long.TryParse(node.SelectSingleNode("time").InnerText, out time);
                id = node.SelectSingleNode("Series").InnerText;
                if (!this.banners.TryGetValue(id, out value))
                {
                    this.banners.Add(id, time);
                }
            }

            //get all the series banners
            foreach (XmlNode node in updates.SelectNodes("/Data/Banner[type='series']"))
            {
                long time;
                long.TryParse(node.SelectSingleNode("time").InnerText, out time);
                id = node.SelectSingleNode("Series").InnerText;
                if (!this.banners.TryGetValue(id, out value))
                {
                    this.banners.Add(id, time);
                }
            }

            //get all the poster banners
            foreach (XmlNode node in updates.SelectNodes("/Data/Banner[type='poster']"))
            {
                long time;
                long.TryParse(node.SelectSingleNode("time").InnerText, out time);
                id = node.SelectSingleNode("Series").InnerText;
                if (!this.banners.TryGetValue(id, out value))
                {
                    this.banners.Add(id, time);
                }
            }

            //get all the fanart banners
            id = string.Empty;
            foreach (XmlNode node in updates.SelectNodes("/Data/Banner[type='fanart']"))
            {
                long time;
                long.TryParse(node.SelectSingleNode("time").InnerText, out time);
                id = node.SelectSingleNode("Series").InnerText;
                if (!this.fanart.TryGetValue(id, out value))
                {
                    this.fanart.Add(id, time);
                }
            }
        }
        private void ReceiveUpdates(int nprogress, ParsingProgress progress)
        {
            if (progress != null)
            {
                if (progress.CurrentItem != -1)
                {
                    MPTVSeriesLog.Write(string.Format("progress received: {0} [{1}/{2}] {3}", progress.CurrentAction, progress.CurrentItem, progress.TotalItems, progress.CurrentProgress));
                }

                switch (progress.CurrentAction)
                {
                case ParsingAction.NoExactMatch:
                    break;

                case ParsingAction.LocalScan:
                    SetProgressLabel(this.labelFilenameProcessingProgress, progress);
                    break;

                case ParsingAction.List_Add:
                    break;

                case ParsingAction.List_Remove:
                    break;

                case ParsingAction.MediaInfo:
                    SetProgressLabel(this.labelMediaInfoProgress, progress);
                    break;

                case ParsingAction.IdentifyNewSeries:
                    SetProgressLabel(this.labelMatchingSeriesProgress, progress);
                    break;

                case ParsingAction.IdentifyNewEpisodes:
                    SetProgressLabel(this.labelIdentifyEpisodesProgress, progress);
                    break;

                case ParsingAction.GetOnlineUpdates:
                    break;

                case ParsingAction.UpdateSeries:
                    SetProgressLabel(this.labelRetrievingSeriesMetaDataProgress, progress);
                    break;

                case ParsingAction.UpdateEpisodes:
                    SetProgressLabel(this.labelUpdatingEpisodeMetaDataProgress, progress);
                    break;

                case ParsingAction.UpdateEpisodeCounts:
                    SetProgressLabel(this.labelRetrievingEpisodeCounts, progress);
                    break;

                case ParsingAction.UpdateUserRatings:
                    SetProgressLabel(this.labelRetrievingUserRatings, progress);
                    break;

                case ParsingAction.UpdateCommunityRatings:
                    SetProgressLabel(this.labelRetrievingCommunityRatings, progress);
                    break;

                case ParsingAction.UpdateBanners:
                    SetProgressLabel(this.labelRetrievingSeriesArtworkProgress, progress);
                    break;

                case ParsingAction.UpdateFanart:
                    SetProgressLabel(this.labelRetrievingFanartProgress, progress);
                    break;

                case ParsingAction.GetNewBanners:
                    goto case ParsingAction.UpdateBanners;

                case ParsingAction.GetNewFanArt:
                    break;

                case ParsingAction.GetNewActors:
                    SetProgressLabel(this.labelRetrievingActorThumbProgress, progress);
                    break;

                case ParsingAction.UpdateEpisodeThumbNails:
                    SetProgressLabel(this.labelRetrievingEpisodeThumbsProgress, progress);
                    break;

                case ParsingAction.UpdateUserFavourites:
                    SetProgressLabel(this.labelRetrievingFavourites, progress);
                    break;

                case ParsingAction.CleanupEpisodes:
                    SetProgressLabel(this.labelCleaningEpisodes, progress);
                    break;

                default:
                    break;
                }
            }
        }
Beispiel #21
0
        public GetUpdates(OnlineAPI.UpdateType type)
        {
            if (type != OnlineAPI.UpdateType.all)
            {
                MPTVSeriesLog.Write(string.Format("Downloading updates from the last {0}", type.ToString()));
            }
            else
            {
                MPTVSeriesLog.Write("Downloading all updates");
            }

            XmlNode updates = OnlineAPI.Updates(type);

            if (updates == null)
            {
                return;
            }

            long.TryParse(updates.Attributes["time"].Value, out this.timestamp);

            // get all the series ids
            series = new Dictionary <DBValue, long>();
            foreach (XmlNode node in updates.SelectNodes("/Data/Series"))
            {
                long time;
                long.TryParse(node.SelectSingleNode("time").InnerText, out time);
                this.series.Add(node.SelectSingleNode("id").InnerText, time);
            }

            // get all the episode ids
            episodes = new Dictionary <DBValue, long>();
            foreach (XmlNode node in updates.SelectNodes("/Data/Episode"))
            {
                long time;
                long.TryParse(node.SelectSingleNode("time").InnerText, out time);
                this.episodes.Add(node.SelectSingleNode("id").InnerText, time);
            }

            // get all the season banners
            banners = new Dictionary <DBValue, long>();
            string id = string.Empty;
            long   value;

            foreach (XmlNode node in updates.SelectNodes("/Data/Banner[type='season']"))
            {
                long time;
                long.TryParse(node.SelectSingleNode("time").InnerText, out time);
                id = node.SelectSingleNode("Series").InnerText;
                if (!this.banners.TryGetValue(id, out value))
                {
                    this.banners.Add(id, time);
                }
            }

            //get all the series banners
            foreach (XmlNode node in updates.SelectNodes("/Data/Banner[type='series']"))
            {
                long time;
                long.TryParse(node.SelectSingleNode("time").InnerText, out time);
                id = node.SelectSingleNode("Series").InnerText;
                if (!this.banners.TryGetValue(id, out value))
                {
                    this.banners.Add(id, time);
                }
            }

            //get all the poster banners
            foreach (XmlNode node in updates.SelectNodes("/Data/Banner[type='poster']"))
            {
                long time;
                long.TryParse(node.SelectSingleNode("time").InnerText, out time);
                id = node.SelectSingleNode("Series").InnerText;
                if (!this.banners.TryGetValue(id, out value))
                {
                    this.banners.Add(id, time);
                }
            }

            //get all the fanart banners
            fanart = new Dictionary <DBValue, long>();
            id     = string.Empty;
            foreach (XmlNode node in updates.SelectNodes("/Data/Banner[type='fanart']"))
            {
                long time;
                long.TryParse(node.SelectSingleNode("time").InnerText, out time);
                id = node.SelectSingleNode("Series").InnerText;
                if (!this.fanart.TryGetValue(id, out value))
                {
                    this.fanart.Add(id, time);
                }
            }
        }