internal static string IdentifyMovieByVideoFingerprint(IMLItem item, ConnectionResult connectionresult, bool FileServerIsOnline, bool IsUNC, string location, string parent )
        {

            #region function variables

            string moviehash = Helpers.GetTagValueFromItem(item,"VideoHash");
            string imdbid = Helpers.GetTagValueFromItem(item,"ImdbID");
            #endregion


            if (!String.IsNullOrEmpty(imdbid))
                return imdbid;

            #region Compute Hash
            if (String.IsNullOrEmpty(moviehash))
            {
                //if ( Importer.EnableHashing)
                //{
                if (!IsUNC || FileServerIsOnline)
                {
                    if (File.Exists(location))
                    {
                        Debugger.LogMessageToFile("Computing video fingerprint for " + item.Name + "...");
                        MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress, "Computing video fingerprint for " + item.Name + "...");
                        Thread.Sleep(200);
                        moviehash = Hasher.ComputeHash(location, item);
                        item.Tags["VideoHash"] = moviehash;
                        item.SaveTags();
                    }
                    else
                    {
                        MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress, "The video file in location field was not found. MediaFairy cannot identify this film.");
                        Thread.Sleep(Settings.SleepValue);
                    }
                }
                //}
            }
            else moviehash = Helpers.GetTagValueFromItem(item,"VideoHash");

            item.SaveTags();
            #endregion


            MovieDescriptorReader.ReadMovieDescriptor(item, moviehash, parent, item.Name );


            if (Settings.PrimaryVideoFingerprintMatchingSource == "OSDb")
            {
                OSDbVideoFingeprintIdentifier.IdentifyMovieByHashOSDb(item, connectionresult);
                imdbid = TMDbVideoFingerprintIdentifier.IdentifyMovieByHashTMDb(item, connectionresult);
            }
            else
            {
                TMDbVideoFingerprintIdentifier.IdentifyMovieByHashTMDb(item, connectionresult);
                imdbid = OSDbVideoFingeprintIdentifier.IdentifyMovieByHashOSDb(item, connectionresult);
            }

            return imdbid;
        }
        public static void ImportMediaInfoforVideo
            (MediaInfoLib.MediaInfo mi, IMLItem item, string filesize, 
            string filecodec, int videoDuration)
        {

            if (!MeediFier.Settings.MediaInfoIsEnabled) 
                return;


          

            Debugger.LogMessageToFile("Setting item's Media Information tags...");

            try
            {
                    
                Debugger.LogMessageToFile("filesize: " + filesize);
                
                item.Tags["filesize"] = filesize;
                item.SaveTags();
                
                
                Debugger.LogMessageToFile("filecodec: " + filecodec);
                
                item.Tags["Format"] = filecodec;
                item.SaveTags();


                ImportVideoInfo(mi, item, videoDuration);

                ImportAudioInfo(mi, item);



                item.Tags["general_bitrate"] = mi.Get
                    (0, 0, "OverallBitRate");
                
                item.SaveTags();

            
            
            }
            catch (Exception e)
            {
                Debugger.LogMessageToFile("An unexpected error ocurred while importing media information. The error was:" + Environment.NewLine + e.ToString());
            }

            item.SaveTags();
        }
        //REFACTOR: 
        internal static void SetUpdateFlag(IMLItem item)
        {



            if (String.IsNullOrEmpty
                    (Helpers.GetTagValueFromItem
                         (item, "ImdbID")))
            {
                ClearProcessedFlag(item);
                return;
            }



            if (String.IsNullOrEmpty
                    (Helpers.GetTagValueFromItem
                         (item, "Year")))
            {
                ClearProcessedFlag(item);
                return;
            }



            if (String.IsNullOrEmpty
                    (Helpers.GetTagValueFromItem
                         (item, "Title")))
            {
                ClearProcessedFlag(item);
                return;
            }



            if (String.IsNullOrEmpty
                (Helpers.GetTagValueFromItem
                     (item, "OriginalTitle")))
            {
                ClearProcessedFlag(item);
                return;
            }
                

            if (String.IsNullOrEmpty
                (Helpers.GetTagValueFromItem
                     (item, "SortTitle")))
            {
                ClearProcessedFlag(item);
                return;
            }
                   


            item.Tags["E.F.I.-processed"]
                = "--processed--";
                
            item.SaveTags();
            
        }
        internal static bool CheckForExistingSubtitleSetHasSubtitleFlag
            (string itemName, IMLItem item, string parentPath,
             string subfilePathSrt, string subfilePathSub)
        {


            MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress,
                                                      "Determining if subtitle exists for " + item.Name);


            if (File.Exists(subfilePathSrt) || File.Exists(subfilePathSub))
            {
                item.Tags["HasSubtitle"] = "True";
                item.SaveTags();

                DeleteSubtitleZipFile(itemName, parentPath);

                return false; 
            
            }



            return true;
       
        }
Example #5
0
        internal static void CleanItemNameSetOriginalTitleTag(IMLItem item)
        {
            string itemName = item.Name;

            if (String.IsNullOrEmpty(itemName))
            {
                return;
            }

            itemName  = itemName.Replace('_', ' ');
            itemName  = itemName.Replace('.', ' ');
            item.Name = itemName;


            string originalTitleTmp = Helpers.GetTagValueFromItem
                                          (item, "OriginalTitle");


            if (!String.IsNullOrEmpty(originalTitleTmp))
            {
                return;
            }

            item.Tags["OriginalTitle"] = item.Name;
            item.SaveTags();


            Debugger.LogMessageToFile(String.Format(
                                          "The item's original name {0} was stored to OrginalTitle tag.",
                                          item.Name));
        }
        private static void ClearProcessedFlag(IMLItem item)
        {
            item.Tags["E.F.I.-processed"]
                = String.Empty;

            item.SaveTags();
        }
        internal static void AddFileToSection
            (out IMLItem item, IMLSection section,
            string itemName, string itemLocation,
            string externalID)
        {
            //TODO: Implement option to not update the Media Section on each imported item.

            if (Settings.UpdateMediaSectionOnEachImportedItem)
            {
                section.BeginUpdate();
            }


            item = section.AddNewItem
                       (itemName, itemLocation);

            item.ExternalID = externalID;
            item.SaveTags();



            if (Settings.UpdateMediaSectionOnEachImportedItem)
            {
                section.EndUpdate();
            }
        }
        internal static void LinkFilmItemChains
            (IMLSection moviesSection,
             IMLItemList allFilmItems,
             IMLItem Item)
        {

            if (!MeediFier.Settings
                .FilmItemChainLinkerIsEnabled)
                return;


            if (allFilmItems == null
                || allFilmItems.Count <= 0)
                return;


            MainImportingEngine.ThisProgress.Progress
                (MainImportingEngine.CurrentProgress,
                 "scanning for un-linked files...");


            Application.DoEvents();


            foreach (IMLItem item in allFilmItems)
            {


                string itemImdbID = Helpers
                    .GetTagValueFromItem
                    (item, "ImdbID");

                string itemToCompareImdbID = Helpers
                    .GetTagValueFromItem
                    (Item, "ImdbID");



                if (item.Location == Item.Location
                    || itemImdbID != itemToCompareImdbID)
                    continue;


                if (item.Location.StartsWith("|")
                    || Item.Location.StartsWith("|"))
                    continue;

                Item.Location =
                    "|" + Item.Location +
                    "|" + item.Location + "|";

                Item.SaveTags();

                moviesSection.DeleteItem(item);
            }


        }
        //REFACTOR:
        internal static void SetUpdateFlag(IMLItem item)
        {
            if (String.IsNullOrEmpty
                    (Helpers.GetTagValueFromItem
                        (item, "ImdbID")))
            {
                ClearProcessedFlag(item);
                return;
            }



            if (String.IsNullOrEmpty
                    (Helpers.GetTagValueFromItem
                        (item, "Year")))
            {
                ClearProcessedFlag(item);
                return;
            }



            if (String.IsNullOrEmpty
                    (Helpers.GetTagValueFromItem
                        (item, "Title")))
            {
                ClearProcessedFlag(item);
                return;
            }



            if (String.IsNullOrEmpty
                    (Helpers.GetTagValueFromItem
                        (item, "OriginalTitle")))
            {
                ClearProcessedFlag(item);
                return;
            }


            if (String.IsNullOrEmpty
                    (Helpers.GetTagValueFromItem
                        (item, "SortTitle")))
            {
                ClearProcessedFlag(item);
                return;
            }



            item.Tags["E.F.I.-processed"]
                = "--processed--";

            item.SaveTags();
        }
 internal static bool DescriptorAlreadyExists(IMLItem item, string xmlpath)
 {
     if (File.Exists(xmlpath))
     {
         item.Tags["HasDescriptor"] = "true";
         item.SaveTags();
         return true;
     }
     return false;
 }
        internal static void SetSortTitleTag
            (IMLItem item)
        {
            string title = Helpers
                           .GetTagValueFromItem
                               (item, "Title");


            string sortTitle = Helpers
                               .GetTagValueFromItem
                                   (item, "SortTitle");



            if (String.IsNullOrEmpty(title))
            {
                return;
            }


            if (!String.IsNullOrEmpty(sortTitle))
            {
                return;
            }



            if (title.StartsWith("The"))
            {
                sortTitle = title.Remove
                                (0, 4) + ", The ";


                Debugger.LogMessageToFile
                    (String.Format
                        ("Set item's SortTitle to:" +
                        " '{0}'.", sortTitle));
            }
            else
            {
                sortTitle = title;
            }


            item.Tags["SortTitle"]
                = sortTitle;

            item.SaveTags();
        }
        private static void CalculateAndSaveHashToLibrary(IMLItem item, string location)
        {
            Helpers.LogMessageToFile(String.Format
               ("Calculating video fingerprint for {0}...", item.Name));

            MainImportingEngine.ThisProgress.Progress
                (ImportProgress.CurrentProgress,
                 String.Format("Calculating video fingerprint for {0}...",
                 item.Name));

            Thread.Sleep(200);

            string videoHash = Hasher.CalculateFileHash(location, item);

            item.Tags["Hash"] = videoHash;
            item.SaveTags();
        }
        internal static void AddFileToSection(out IMLItem item, IMLSection section,
            string itemName, string itemLocation,
            string externalID)
        {
            //TODO: Implement option to not update the Media Section on each imported item.

             if (Settings.UpdateMediaSectionOnEachImportedItem)
                section.BeginUpdate();

            item = section.AddNewItem
                (itemName, itemLocation);

            item.ExternalID = externalID;
            item.SaveTags();

            if (Settings.UpdateMediaSectionOnEachImportedItem)
                section.EndUpdate();
        }
        public static bool ExtractMetadataFromEpisodeFilename(IMLItem item, string location,
            IMLSection Section, IMLSection TvSection, bool RanFromTvSection, 
            IEnumerable<string> combinedSceneTags)
        {
            if (!Settings.ExtractMetadataFromFilenames)
                return false;

            if (String.IsNullOrEmpty(item.Name))
                return false;

            try
            {
                //Importer.thisProgress.Progress(Importer.CurrentProgress, "Performing meta-information extraction...");
                Helpers.UpdateProgress("Performing diagnostic operations", "Performing meta-information extraction...", item);
                Debugger.LogMessageToFile("Performing meta-information extraction...");


                #region Clean Iten Name from common tags
                Debugger.LogMessageToFile("Cleaning Item Name...");
                string itemName = item.Name;
                itemName = VideoFilenameCleaner.CleanVideoFilename(itemName, combinedSceneTags ).Trim();
               

                item.Name = itemName;
                item.SaveTags();
                #endregion

                RecognizeSeries(TvSection, Section, RanFromTvSection, item, location);




            }
            catch (Exception e)
            {
                StatusForm.statusForm.TrayIcon.ShowBalloonTip(5000, "Error parsing filename", "An unexpected error ocurred in the filename parser. " + Environment.NewLine +
                                                                                              "Please see the Debug.log file for details.", ToolTipIcon.Warning);
                Debugger.LogMessageToFile("An unexpected error occured in the filename parsing method. The error was: " + e.ToString());
            }

            return false;
        }
        public static string SaveImage
            (byte[] imagedata, IMLItem item,
            bool isPoster, string specificImageTag,string ImageFile)
        {
            

            #region Save image file
            try
            {

                //MessageBox.Show("imagefile: " + ImageFile);

                _fileStream = File.Create(ImageFile);
                _fileStream.Write(imagedata, 0, imagedata.Length);
                _fileStream.Close();

                if (isPoster)
                {
                    item.ImageFile = ImageFile;
                    item.SaveTags();
                }
                else
                {
                    item.Tags[specificImageTag] = ImageFile;
                    item.SaveTags();

                }

                return ImageFile;
            }
            catch (Exception ex)
            {
                Debugger.LogMessageToFile("Error while saving Poster image for " + item.Name + ": " + ex.Message);
                return "";
            }

            #endregion



        }
        internal static bool ValidateDownloadedDataAndRetry(string language,  IMLItem item, string firstsub,
            WebClient client, string zipfilePath)
        {
            StreamReader sr
                = File.OpenText(zipfilePath);

            if (CheckFirstLineForHtmlToken(sr))
                return true;

            Sleep10SecsToRetry(sr);

            File.Delete(zipfilePath);

            client.DownloadFile(firstsub, zipfilePath);

            sr = File.OpenText(zipfilePath);

            if (!CheckFirstlineForHtmlTokenFinalTry
                (zipfilePath, sr))
                return false;

            MainImportingEngine.ThisProgress.Progress
                (ImportProgress.CurrentProgress,
                 "Subtitle for " + item.Name +
                 " was downloaded succesfully.");

            Thread.Sleep(1500);

            item.Tags
                ["Subtitle language"]
                = language;

            item.SaveTags();

            sr.Close();
            sr.Dispose();

            return true;
        }
        private static string GetIMDbIdByVideoHash(IMLItem item,
            ConnectionResult connectionresult, 
            string imdbid, string moviehash)
        {
            if (!connectionresult.OSDbIsOnline)
                return imdbid;

            if (String.IsNullOrEmpty(moviehash))
                return imdbid;

            if (!String.IsNullOrEmpty(imdbid))
                return imdbid;
            
            imdbid = OSoperations.FindImdbIDbyHash2
                (moviehash, item, connectionresult.OsDbLoginResult.token,
                 ref connectionresult.OSDbIsOnline);

            item.Tags["ImdbID"] = imdbid;
            item.SaveTags();

            return imdbid;
        }
        internal static bool SaveXmlDocument(IMLItem item, string filmFolder, XmlDocument doc, string xmlpath)
        {
            try
            {
                doc.Save(xmlpath);
                item.SaveTags();
                return true;
            }
            catch (Exception)
            {
                //MessageBox.Show(e.ToString());
                StatusForm.statusForm.TrayIcon.ShowBalloonTip(10000, "Access to a media directory was rectricted",
                                                              "MediaFairy could not write a film descriptor file in the directory " +
                                                              filmFolder +
                                                              " because Windows security privileges do not allow modification for this directory.",
                                                              ToolTipIcon.Warning);
                Thread.Sleep(2000);

                return false;
            }

        }
        internal static void CleanItemNameSetOriginalTitleTag(IMLItem item)
        {
            string itemName = item.Name;

                            if (String.IsNullOrEmpty(itemName))
                                return;

                            itemName = itemName.Replace('_', ' ');
                            itemName = itemName.Replace('.', ' ');
                            item.Name = itemName;

                            string originalTitleTmp = Helpers.GetTagValueFromItem
                                (item, "OriginalTitle");

                            if (!String.IsNullOrEmpty(originalTitleTmp))
                                return;

                            item.Tags["OriginalTitle"] = item.Name;
                            item.SaveTags();

                            Debugger.LogMessageToFile(String.Format(
                                "The item's original name {0} was stored to OrginalTitle tag.",
                                item.Name));
        }
        internal static string IdentifyMovieByHashTMDb
            (IMLItem item, ConnectionResult connectionresult)
        {

            //TmdbAPI api = new TmdbAPI(Importer.ApiKey); 

            

            #region function variables
            string name = item.Name;
            string moviehash = Helpers.GetTagValueFromItem(item, "Hash");
            string imdbid = Helpers.GetTagValueFromItem(item, "ImdbID");
            string location = item.Location;
            FileInfo fi = new FileInfo(location);
            long byteSize = fi.Length;
            #endregion


            if (!Settings.EnableVideoHasher)
                return imdbid;

            if (!connectionresult.InternetConnectionAvailable && Settings.ConnectionDiagnosticsEnabled)
                return imdbid;

            if (!String.IsNullOrEmpty(imdbid))
                return imdbid;

            if (String.IsNullOrEmpty(moviehash))
                return imdbid;


            #region Get ImdBID

            string TMDbUrl = "http://api.themoviedb.org/2.1/Media.getInfo/en/xml/" + Settings.TMDbApiKey + "/" + moviehash + "/" + byteSize;
            Debugger.LogMessageToFile("Trying to get IMDb ID from url " + TMDbUrl + "...");
       
            #region request and return Response stream
            WebResponse objResponse = Downloaders.TryDatabaseRequest(TMDbUrl, "Movies", "TheMovieDatabase", item);
            if (objResponse == null)
            {
                Debugger.LogMessageToFile("The web response from TMdb was not valid. The IMDb ID for this film cannot be retrieved.");
                return imdbid;
            }
            Debugger.LogMessageToFile("Getting Response stream...");
            Stream stream = objResponse.GetResponseStream();
            #endregion

            

            #region Load XML document
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(stream);
            }
            catch (Exception)
            {
                try
                {
                    doc.Load(stream);
                }
                catch (Exception e)
                {
                    StatusForm.statusForm.TrayIcon.ShowBalloonTip(5000, "Unable to parse online response.", "An unexpected error occurred while trying to read themoviedb.org response stream." + Environment.NewLine + "Please check the log file for more details on this error.", ToolTipIcon.Warning);
                    Debugger.LogMessageToFile("An unexpected error occurred while trying to read themoviedb.org response stream. The error was: " + e.ToString());
                    return imdbid;
                }
            }
            #endregion


            //string XmlText = doc.InnerText;
            //MessageBox.Show(XmlText);

            #region Parse XML nodes to get IMDb ID
            XmlNodeList nodelist = doc.ChildNodes;
            bool FoundFirst = false;
            foreach (XmlNode node in nodelist)
            {
                //MessageBox.Show("First level: " + node.Name);
                if (node.HasChildNodes)
                {
                    foreach (XmlNode childnode in node.ChildNodes)
                    {
                        //MessageBox.Show("Second level: " + node.Name);
                        foreach (XmlNode result in node.ChildNodes)
                        {
                            //MessageBox.Show("Third level: " + result.Name);

                            foreach (XmlNode movie in result.ChildNodes)
                            {
                                //MessageBox.Show("Fourth level: " + movie.Name);
                                if (movie.Name == "movie" && !FoundFirst)
                                {
                                    FoundFirst = true;
                                    //MessageBox.Show("Fifth level: " + movie.Name);
                                    XmlNode Tag = movie.SelectSingleNode("imdb_id");

                                    if (Tag == null)
                                        return imdbid;

                                    if (String.IsNullOrEmpty(Tag.InnerText))
                                        return imdbid;

                                    imdbid = Tag.InnerText;
                                    Debugger.LogMessageToFile("The film's IMDb ID " + imdbid + " was succesfully extracted from the TMDb response stream.");

                                }
                            }
                        }
                    }
                }
            }
            #endregion


            #region Save found IMDbID to item's tag
            if (!String.IsNullOrEmpty(imdbid))
            {


                Debugger.LogMessageToFile("Online identification by video fingerprint (using TMDb) was successful!");
                MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress, "Online identification by video fingerprint (using TMDb) was succesfull!");
                Thread.Sleep(2000);
                item.Tags["ImdbID"] = imdbid;
                item.SaveTags();
            }
            else
            {
                Debugger.LogMessageToFile("Online identification by video's fingerprint (using TMDb) was not possible.");
            }
            #endregion

            #endregion


            return imdbid;
        }
        internal static bool DownloadFilmInfoFromSevenVideoNet
            (IMLItem Item, string location)
        {

            if (!MediaFairy.Settings.SevenFilmDetailsEnabled)
                return false;

            if (!String.IsNullOrEmpty(Helpers.GetTagValueFromItem(Item, "SevenUpdated")))
                return true;

        
            #region Construct search URL
            string BaseUrl = "http://www.videoseven.gr/site.php?file=searchsimple.xml&searchstr=";
            string ItemName = Item.Name;
            string ItemTitle = Helpers.GetTagValueFromItem(Item, "Title");
            string filmPage = "";
            ItemTitle = StringFunctions.replaceIllegalCharacters(ItemTitle, "-");
            string SearchUrl = ItemTitle.Replace(' ', '+');
            string Suffix = "&imageField22.x=0&imageField22.y=0";
            SearchUrl = BaseUrl + SearchUrl + Suffix;
            #endregion

            try
            {

                #region Download film html page
                Helpers.UpdateProgress("Updating Movies Section...", "Searching Seven Video Net for film " + ItemTitle + "...", Item);
                string MovieID = Downloaders.MineWebDataReturnFirstMatch(SearchUrl, "showOneMovieImage.xml&id=(?<MovieID>.*?)\"");
                //MessageBox.Show("MovieID: " + MovieID);

                if (String.IsNullOrEmpty(MovieID))
                {
                    Debugger.LogMessageToFile("No results were found for this film. Unable to download aditiional film information from AMG.");
                    return false;
                }

                string filmUrl = "http://www.videoseven.gr/site.php?&file=moviedetails.xml&id=" + MovieID;

                Debugger.LogMessageToFile("filmUrl: " + filmUrl);

                Helpers.UpdateProgress("Updating Movies Section...", "Downloading film information from Seven Video Net...", Item);
                filmPage = HtmlDownloaders.DownloadHTMLfromURLUnicode(filmUrl);
                
                //Debugger.LogMessageToFile(filmPage);
                //MessageBox.Show("filmPage: " + filmPage);

                if (String.IsNullOrEmpty(filmPage))
                    return false;
                #endregion



                #region Download Details

                #region Synopsis


                string Synopsis = RegExMatchers.MatchExpressionReturnFirstMatchFirstGroup(filmPage, "<td align=\"justified\"><p>(?<Synopsis>[^$]*?)<br>");
                //Debugger.LogMessageToFile("Synopsis: " + Synopsis);
                string[] dirtyText = RegExMatchers.MatchExpressionReturnAllMatchesFirstGroup(Synopsis, "<.*?>");
                if (dirtyText != null)
                {
                    foreach (string dirtyTag in dirtyText)
                    {
                        Synopsis = Synopsis.Replace(dirtyTag, "");
                    }
                }

                //MessageBox.Show("Synopsis: " + Synopsis);
                if (!String.IsNullOrEmpty(Synopsis))
                {
                    Item.Tags["LongOverview"] = Synopsis;
                    Item.SaveTags();
                }

                string Tagline = RegExMatchers.MatchExpressionReturnFirstMatchFirstGroup(filmPage, "<span class=\"comment\">(?<Tagline>.*?)</span>");
                if (!String.IsNullOrEmpty(Tagline))
                {
                    Item.Tags["Tagline"] = Tagline;
                    Item.SaveTags();
                }

                string TitleGR = RegExMatchers.MatchExpressionReturnFirstMatchFirstGroup(filmPage, "<b>(?<TitleGR>.*?)</b><br/>");
                Item.Tags["TitleGR"] = TitleGR;
                Item.SaveTags();
                    
                
                #endregion


      

                #endregion


                Item.Tags["SevenUpdated"] = "true";
                Item.SaveTags();

            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            return true;
        }
        private static bool ImageFileExistsInItemLocatiohn
            (IMLItem item, bool fileServerIsOnline, bool isUNC)
        {

            if (String.IsNullOrEmpty(item.ImageFile))
                return false;


            if (!fileServerIsOnline && isUNC)
                return false;


            if (!File.Exists(item.ImageFile))
                return false;

            item.SaveTags();

            return true;
        }
        private static bool LookForPosterInItemLocation(IMLItem item, bool fileServerIsOnline, bool isUNC, string imageFile)
        {

            if (!fileServerIsOnline && isUNC)
                return false;

            if (!File.Exists(imageFile))
                return false;

            item.ImageFile = imageFile;
            item.SaveTags();

            return true;
        }
        internal static string IdentifyMovieByHashOSDb(IMLItem item, ConnectionResult connectionresult)
        {


            #region function variables

            string moviehash = Helpers.GetTagValueFromItem(item, "Hash");
            string imdbid = Helpers.GetTagValueFromItem(item, "ImdbID");
            #endregion


            if (!Settings.EnableVideoHasher)
                return imdbid;

            if (!connectionresult.InternetConnectionAvailable && Settings.ConnectionDiagnosticsEnabled)
                return imdbid;

            if (!connectionresult.OSDbIsOnline)
                return imdbid;

            if (!String.IsNullOrEmpty(imdbid))
                return imdbid;

            if (String.IsNullOrEmpty(moviehash))
                return imdbid;


            #region Get ImdBID


            imdbid = OSoperations.FindImdbIDbyHash2(moviehash, item, connectionresult.OsDbLoginResult.token, ref connectionresult.OSDbIsOnline);

            #region Construct correct IMDbID in case it was received wrong
            if (!String.IsNullOrEmpty(imdbid))
            {
                if (!imdbid.StartsWith("tt"))
                {
                    if (imdbid.Length == 6)
                        imdbid = "0" + imdbid;

                    imdbid = "tt" + imdbid;
                }
                else
                {
                    if (imdbid.Length == 8)
                    {
                        imdbid = imdbid.Remove(0, 2);
                        imdbid = "0" + imdbid;
                        imdbid = "tt" + imdbid;
                    }
                }
            }
            #endregion

            #region Save found IMDbID to item's tag
            if (!String.IsNullOrEmpty(imdbid))
            {

                Debugger.LogMessageToFile
                    ("Online identification by video fingerprint" +
                     " (using OSDb) was successful!");


                MainImportingEngine.ThisProgress.Progress
                    (MainImportingEngine.CurrentProgress,
                    "Online identification by" +
                    " video fingerprint (using OSDb)" +
                    " was succesfull!");


                //Thread.Sleep(200);

                item.Tags["ImdbID"] = imdbid;
                item.SaveTags();

            }
            else
            {

                Debugger.LogMessageToFile
                    ("Online identification by video's" +
                     " fingerprint (using OSDb)" +
                     " was not possible.");


            }
            #endregion

            #endregion


            return imdbid;
        }
 internal static void MarkSeriesAsNotListed(IMLItem Item, string SeriesName)
 {
     Debugger.LogMessageToFile("The Series named " + SeriesName + " was not found in TVdb.");
     Item.Tags["NotListed"] = "true";
     Item.SaveTags();
 }
        //REFACTOR:
        internal static void SetDetailsFlag(IMLItem item)
        {
            if (
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "Title")))
                &&
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "Year")))
                &&
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "Actors")))
                &&
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "ActorRoles")))
                &&
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "Director")))
                &&
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "Genre")))
                &&
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "LongOverview")))
                &&
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "Overview")))
                &&
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "Rating")))
                &&
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "ReleaseDate")))
                &&
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "Review")))
                &&
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "Runtime")))
                &&
                (!String.IsNullOrEmpty
                     (Helpers.GetTagValueFromItem
                         (item, "Studio")))
                )
            {
                item.Tags
                ["HasDetails"]
                    = "True";

                item.SaveTags();
            }
            else
            {
                item.Tags
                ["HasDetails"]
                    = String.Empty;

                item.SaveTags();
            }
        }
        //TODO: Test if the overloads for this function are working correctly.
        //Used fy the Film Updater
        public static bool ExtractMetadataFromMovieFilename
            ( IMLItem item, IEnumerable<string> combinedSceneTags)
        {


            if (!Settings.ExtractMetadataFromFilenames)
                return false;


            if (String.IsNullOrEmpty
                (item.Name))
                return false;


           

            Helpers.UpdateProgress
                ("Performing diagnostic operations",
                "Performing local metadata extraction...");
                
            Debugger.LogMessageToFile
                ("Performing local metadata extraction...");



            try
            {

                 ExtractImdbIdFromFilename
                    (item, combinedSceneTags);



                item.Name = VideoFilenameCleaner
                    .CleanVideoFilename
                    (item.Name, combinedSceneTags );

                item.SaveTags();

                //TODO: The change I made to the video filename cleaner should avoid the need of calling this function more than once.
            
                item.Name = VideoFilenameCleaner
                    .CleanVideoFilename
                    (item.Name, combinedSceneTags).Trim();

                item.SaveTags();

                item.Name = VideoFilenameCleaner
                    .CleanVideoFilename
                    (item.Name, combinedSceneTags).Trim();


                item.SaveTags(); 


                ExtractYearFromFilename(item);



            }
            catch (Exception e)
            {

                
                Debugger.LogMessageToFile
                    ("An unexpected error occured" +
                     " in the filename parsing method. " +
                     "The error was: " + e );

            }

            return false;
        }
        private static string SetItemTagsFromOutput(IMLItem item, IEnumerable<string> lines, string title, ref string artist, ref string album, ref string tracknumber, ref string genre, ref string year)
        {
            string puid;
            foreach (string line in lines)
            {
                //MessageBox.Show(line);
                #region Set library tags

                #region Set Title
                if (line.Contains("Title:"))
                {
                    //MessageBox.Show("line contains Title!");

                    title = line.Remove(0, 7);

                    if (!String.IsNullOrEmpty(title.Trim()))
                    {
                        //MessageBox.Show(Title);
                        item.Tags["Title"] = title;
                        item.Name = title;
                        item.SaveTags();


                    }

                }
                #endregion

                #region Set Artist
                if (line.Contains("Artist:"))
                {
                    artist = line.Remove(0, 8);
                    //MessageBox.Show(artist);

                    if (!String.IsNullOrEmpty(artist))
                    {
                        item.Tags["Artist"] = artist;
                        item.SaveTags();

 
                    }
                    MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress, item.Name + " was succesfully identified!");
                    Thread.Sleep(1000);
                }
                #endregion

                #region Set Album
                if (line.Contains("Album:"))
                {
                    album = line.Remove(0, 7);

                    if (!String.IsNullOrEmpty(album))
                    {
                        //MessageBox.Show(Album);
                        item.Tags["Album"] = album;
                        item.SaveTags();
                    }

                }
                #endregion

                #region Set track number
                if (line.Contains("Track number:"))
                {
                    tracknumber = line.Remove(0, 14);

                    if (tracknumber.Trim() != "(null)")
                    {
                        //MessageBox.Show(tracknumber);
                        item.Tags["Track No."] = tracknumber;
                        item.SaveTags();
                    }

                }
                #endregion

                #region Set Genre
                if (line.Contains("Genre:"))
                {
                    genre = line.Remove(0, 7);

                    if (!String.IsNullOrEmpty(genre.Trim()))
                    {
                        //MessageBox.Show(Title);
                        item.Tags["Genre"] = genre;
                        item.SaveTags();
                    }

                }
                #endregion

                #region Set Year
                if (line.Contains("Year:"))
                {
                    year = line.Remove(0, 6);

                    if (!String.IsNullOrEmpty(year.Trim()))
                    {
                        //MessageBox.Show(Title);
                        item.Tags["Year"] = year;
                        item.SaveTags();
                    }

                }
                #endregion

                #region Set PUID

                if (!line.Contains("PUID:")) continue;

                puid = line.Remove(0, 8);

                if (String.IsNullOrEmpty(puid.Trim())) continue;

                //MessageBox.Show(PUID);
                item.Tags["PUID"] = puid;
                item.SaveTags();

                #endregion

                #endregion

            }
            return title;
        }
        internal static void PopulateAudioTags
            (string album, string title, File audiofile, string artist, IMLItem item)
        {


            if (String.IsNullOrEmpty(artist) || Settings.OverwriteExistingMusicTags)
                item.Tags["Artist"] = audiofile.Tag.FirstAlbumArtist;

            if (String.IsNullOrEmpty(album) || Settings.OverwriteExistingMusicTags)
                item.Tags["Album"] = audiofile.Tag.Album;

            if (String.IsNullOrEmpty(title) || Settings.OverwriteExistingMusicTags)
                item.Tags["Title"] = audiofile.Tag.Title;

            if (!String.IsNullOrEmpty(audiofile.Tag.Title))
                item.Name = audiofile.Tag.Title;


            string genre = Helpers.GetTagValueFromItem(item, "Genre");
            if (String.IsNullOrEmpty(genre) || Settings.OverwriteExistingMusicTags)
                item.Tags["Genre"] = audiofile.Tag.JoinedGenres;


            string track = Helpers.GetTagValueFromItem(item, "Track");
            if (String.IsNullOrEmpty(track) || Settings.OverwriteExistingMusicTags)
            {
                if (audiofile.Tag.Track != 0)
                    item.Tags["Track"] = audiofile.Tag.Track;
            }


            string year = Helpers.GetTagValueFromItem(item, "Year");
            if (String.IsNullOrEmpty(year) || Settings.OverwriteExistingMusicTags)
            {
                if (audiofile.Tag.Year != 0)
                    item.Tags["Year"] = audiofile.Tag.Year;
            }


            string lyrics = Helpers.GetTagValueFromItem(item, "Lyrics");
            if (String.IsNullOrEmpty(lyrics) || Settings.OverwriteExistingMusicTags)
            {
                if (!String.IsNullOrEmpty(audiofile.Tag.Lyrics))
                    item.Tags["Lyrics"] = audiofile.Tag.Lyrics;
            }


            string beatsPerMinute = Helpers.GetTagValueFromItem(item, "BeatsPerMinute");
            if (String.IsNullOrEmpty(beatsPerMinute) ||
                Settings.OverwriteExistingMusicTags)
            {
                if (audiofile.Tag.BeatsPerMinute != 0)
                    item.Tags["BeatsPerMinute"] = audiofile.Tag.BeatsPerMinute;
            }


            string comment = Helpers.GetTagValueFromItem(item, "Comment");
            if (String.IsNullOrEmpty(comment) || Settings.OverwriteExistingMusicTags)
            {
                if (!String.IsNullOrEmpty(audiofile.Tag.Comment))
                    item.Tags["Comment"] = audiofile.Tag.Comment;
            }


            string copyright = Helpers.GetTagValueFromItem(item, "Copyright");
            if (String.IsNullOrEmpty(copyright) || Settings.OverwriteExistingMusicTags)
            {
                if (!String.IsNullOrEmpty(audiofile.Tag.Copyright))
                    item.Tags["Copyright"] = audiofile.Tag.Copyright;
            }


            string disc = Helpers.GetTagValueFromItem(item, "Disc");
            if (String.IsNullOrEmpty(disc) || Settings.OverwriteExistingMusicTags)
            {
                if (audiofile.Tag.Disc != 0)
                    item.Tags["Disc"] = audiofile.Tag.Disc;
            }


            string discCount = Helpers.GetTagValueFromItem(item, "DiscCount");
            if (String.IsNullOrEmpty(discCount) || Settings.OverwriteExistingMusicTags)
            {
                if (audiofile.Tag.DiscCount != 0)
                    item.Tags["DiscCount"] = audiofile.Tag.DiscCount;
            }


            string composer = Helpers.GetTagValueFromItem(item, "Composer");
            if (String.IsNullOrEmpty(composer) || Settings.OverwriteExistingMusicTags)
            {
                if (!String.IsNullOrEmpty(audiofile.Tag.FirstComposer))
                    item.Tags["Composer"] = audiofile.Tag.FirstComposer;
            }


            string performer = Helpers.GetTagValueFromItem(item, "Performer");
            if (String.IsNullOrEmpty(performer) || Settings.OverwriteExistingMusicTags)
            {
                if (!String.IsNullOrEmpty(audiofile.Tag.FirstPerformer))
                    item.Tags["Performer"] = audiofile.Tag.FirstPerformer;
            }


            string albumArtists = Helpers.GetTagValueFromItem(item, "AlbumArtists");

            if (String.IsNullOrEmpty(albumArtists) ||
                Settings.OverwriteExistingMusicTags)
            {
                if (!String.IsNullOrEmpty(audiofile.Tag.JoinedAlbumArtists))
                    item.Tags["AlbumArtists"] = audiofile.Tag.JoinedAlbumArtists;
            }


            item.SaveTags();

        }
        private static void GetMainDetails(IMLItem item, ITVDBSeries series)
        {

            if (!String.IsNullOrEmpty(series.ID))
            {

                MediaSectionsAllocator.TvSeriesSection.BeginUpdate();

                IMLItem seriesItem = MediaSectionsAllocator.TvSeriesSection.AddNewItem(series.SeriesName, series.ID);
                seriesItem.ExternalID = series.ID;
                seriesItem.SaveTags();

                MediaSectionsAllocator.TvSeriesSection.EndUpdate();

                item.Tags["SeriesID"] = series.ID;


            }


            if (!String.IsNullOrEmpty(series.Actors))
                item.Tags["SeriesActors"] = series.Actors;

            if (!String.IsNullOrEmpty(series.Airs_DayOfWeek) && !String.IsNullOrEmpty(series.Airs_TimeOfDay))
                item.Tags["SeriesAirs"] = series.Airs_DayOfWeek + " @ " + series.Airs_TimeOfDay;

            if (!String.IsNullOrEmpty(series.FirstAired.ToShortDateString()))
                item.Tags["SeriesFirstAired"] = series.FirstAired;

            if (!String.IsNullOrEmpty(series.Genre))
                item.Tags["SeriesGenre"] = series.Genre;

            if (!String.IsNullOrEmpty(series.IMDb_ID))
                item.Tags["SeriesIMDbID"] = series.IMDb_ID;

            if (!String.IsNullOrEmpty(series.Language))
            item.Tags["SeriesLanguage"] = series.Language;

            if (series.LastUpdated != 0)
            item.Tags["SeriesLastUpdated"] = series.LastUpdated;

            if (!String.IsNullOrEmpty(series.Network))
            item.Tags["SeriesNetwork"] = series.Network;

            if (!String.IsNullOrEmpty(series.Overview))
            item.Tags["SeriesOverview"] = series.Overview;

            if (series.Rating > 0)
                item.Tags["SeriesRating"] = series.Rating;


            if (!String.IsNullOrEmpty(series.Runtime))
                item.Tags["SeriesRuntime"] = series.Runtime;

            if (!String.IsNullOrEmpty(series.SeriesName))
            item.Tags["SeriesName"] = series.SeriesName;

            if (!String.IsNullOrEmpty(series.Status))
            item.Tags["SeriesStatus"] = series.Status;

            if (!String.IsNullOrEmpty(series.Zap2It_ID))
            item.Tags["Zap2ItID"] = series.Zap2It_ID;

            if (!String.IsNullOrEmpty(series.ID))
            item.Tags["SeriesID"] = series.ID;
            


            item.SaveTags();
        

        }
        private static string GetImdbidFromXmlRpcStruct(IMLItem Item, XmlRpcStruct mystruct)
        {
            string token = String.Empty;
            string imdbid = String.Empty;

            Debugger.LogMessageToFile("Parsing the XMLRPC structure returned by OSdb...");
            try
            {
                #region scan entries and get imdbid
                foreach (DictionaryEntry d in mystruct)
                {
                    token = Convert.ToString(d.Key);
                    if (token == "data")
                    {
                        Debugger.LogMessageToFile("data structure found.");
                        object value = d.Value;
                        XmlRpcStruct s = (XmlRpcStruct)value; //unboxing 
                        foreach (DictionaryEntry e in s)
                        {
                            object objb = e.Value;

                            Type type = objb.GetType();
                            string typename = type.Name;

                            if (typename == "Object[]")
                            {
                                //Importer.thisProgress.Progress(Item.Name + " could not be identified by fingerpint. Will search by film's title...");
                                //Thread.Sleep(Importer.Importer.SleepValue);
                                Debugger.LogMessageToFile("OSdb returned multiple XMLRPC structures. " + Item.Name + " could not be identified by video fingerprint.");
                                Item.Tags["OSdbMatched"] = "false";
                                Item.SaveTags();
                                return "";
                            }



                            XmlRpcStruct movie = (XmlRpcStruct)objb; //unboxing
                            foreach (DictionaryEntry f in movie)
                            {
                                token = Convert.ToString(f.Key);

                                if (token == "MovieImdbID")
                                {
                                    object g = f.Value;
                                    imdbid = (string)g;
                                    Item.Tags["OSdbMatched"] = "true";
                                    Item.SaveTags();
                                    Debugger.LogMessageToFile("The film's IMDbID was successfully extracted from OSdb response.");
                                }

                            }//foreach d in dictionary
                        }//foreach e in dictionary
                    }
                }
                #endregion
            }
            catch (Exception e)
            {
                StatusForm.statusForm.TrayIcon.ShowBalloonTip(5000, "Online video identification was unsuccesfull", "An error occured while reading the response from OSdb. The error was logged to the plugin's debug.log file.", ToolTipIcon.Error);
                Debugger.LogMessageToFile("An error occured on the XMLRPC structure parser. The error was: " + e.ToString() );
            }

            return imdbid;
        }
        internal static void GetEpisodeThumbnail(IMLItem item, bool fileServerIsOnline, bool isUNC, string mdfSettingsb,
                                                 IBaseSystem iBaseSystem, ITVDBEpisode episode, WebClient client)
        {

            string imageFile = TVShows.CreateEpisodeThumbsFilePath
                (item, mdfSettingsb, ".jpg", iBaseSystem);


            string imagelocation = imageFile;

            if (File.Exists(imagelocation))
            {
                item.ImageFile = imagelocation;
                item.SaveTags();
                return;
            }

            if (!Settings.WantEpisodeThumbnails)
                return;

            if (String.IsNullOrEmpty(episode.ImageFile))
                return;

            if (!fileServerIsOnline && isUNC)
                return;


            MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress,
                                                      "Downloading episode thumbnail...");

            try
            {
                client.DownloadFile(episode.ImageFile, imagelocation);
                item.ImageFile = imagelocation;
                item.SaveTags();
            }
            catch
            {
                try
                {
                    client.DownloadFile(episode.ImageFile, imagelocation);
                    item.ImageFile = imagelocation;
                    item.SaveTags();
                }
                catch
                {
                }

            }

        }
        public static Movie GetDetailsFromOSdb(string imdbid, IMLItem Item)
        {
            Movie m;
            m = new Movie();

            Debugger.LogMessageToFile("Attempting to download film details for item " + Item.Name + " from OSdb ..."); 
            mystruct = Proxy.GetIMDBMovieDetails("token", imdbid);

            Debugger.LogMessageToFile("Retrieving data from OSdb response...");
            #region parse rsults and return details

            foreach (DictionaryEntry d in mystruct)
            {
                token = Convert.ToString(d.Key);
                if (token == "data")
                {
                    object value = d.Value;
                    Console.WriteLine(value.GetType());
                    XmlRpcStruct s = (XmlRpcStruct)value;
                    foreach (DictionaryEntry e in s)
                    {
                        token = Convert.ToString(e.Key);

                        if (token == "title")
                        {
                            string str = (string)e.Value;
                            m.Name = str;
                        }

                        if (token == "tagline")
                        {
                            string str = (string)e.Value;
                            m.Tagline = str;
                        }

                        if (token == "year")
                        {
                            string str = (string)e.Value;
                            m.Year = str;
                        }

                        if (token == "duration")
                        {
                            string str = (string)e.Value;
                            m.Duration = str;
                        }

                        if (token == "plot")
                        {
                            string str = (string)e.Value;
                            m.Plot = str;
                        }

                        if (token == "trivia")
                        {
                            string str = (string)e.Value;
                            m.Trivia = str;
                        }

                        if (token == "goofs")
                        {
                            string str = (string)e.Value;
                            m.Goofs = str;
                        }


                        token = Convert.ToString(e.Key);
                        if (token == "directors")
                        {
                            value = e.Value;
                            s = (XmlRpcStruct)value;
                            string str = "";
                            int i = 1;

                            foreach (DictionaryEntry f in s)
                            {
                                if (i == s.Count) str = (string)f.Value;
                                else str = f.Value + "|";
                                i++;
                            }
                            m.Directors = str;
                        }



                        token = Convert.ToString(e.Key);
                        if (token == "cast")
                        {
                            value = e.Value;
                            s = (XmlRpcStruct)value;
                            string str = "";
                            int i = 1;

                            foreach (DictionaryEntry f in s)
                            {
                                if (i == s.Count) str += (string)f.Value;
                                else str += f.Value + "|";
                                i++;
                            }
                            m.Cast = str;
                        }




                        token = Convert.ToString(e.Key);
                        if (token == "writers")
                        {
                            value = e.Value;
                            s = (XmlRpcStruct)value;
                            string str = "";
                            int i = 1;

                            foreach (DictionaryEntry f in s)
                            {
                                if (i == s.Count) str += (string)f.Value;
                                else str += f.Value + "|";
                                i++;
                            }
                            m.Writers = str;
                        }




                        token = Convert.ToString(e.Key);
                        if (token == "genres")
                        {
                            value = e.Value;
                            string[] genres = (string[])value;
                            string str = "";
                            int i = 1;

                            foreach (string genre in genres)
                            {
                                if (i == genres.Length)
                                    str += genre;
                                else
                                    str += genre + "|";
                                i++;
                            }
                            m.Genres = str;
                        }



                        token = Convert.ToString(e.Key);
                        if (token == "cover")
                        {
                            string str = (string)e.Value;
                            m.Cover = str;
                        }




                    }
                }
            }
            #endregion


            Debugger.LogMessageToFile("Saving results from item's tags...");
            #region save results to item's tags

            if (!String.IsNullOrEmpty(m.Name))
            {
                Item.Name = m.Name;
                Item.Tags["Title"] = m.Name;
            }
            //Item.Tags["Poster URL"] = m.Cover;

            if (Settings.WantOSdbDetails)
            {
                if (!String.IsNullOrEmpty(m.Tagline))
                {
                    string TaglineTag;
                    if (Settings.MovieNightCompatibility)
                        TaglineTag = "Subtitle";
                    else TaglineTag = "Tagline";

                    Item.Tags[TaglineTag] = m.Tagline;
                }

                if (!String.IsNullOrEmpty(m.Year))
                Item.Tags["Year"] = m.Year;

                if (!String.IsNullOrEmpty(m.Duration))
                Item.Tags["Runtime"] = m.Duration;

                if (!String.IsNullOrEmpty(m.Plot))
                Item.Tags["Overview"] = m.Plot;

                if (!String.IsNullOrEmpty(m.Directors))
                Item.Tags["Director"] = m.Directors;

                if (!String.IsNullOrEmpty(m.Cast))
                Item.Tags["Actors"] = m.Cast;

                if (!String.IsNullOrEmpty(m.Genres))
                Item.Tags["Genre"] = m.Genres;

                if (!String.IsNullOrEmpty(m.Writers))
                Item.Tags["Writer"] = m.Writers;

                if (!String.IsNullOrEmpty(m.Trivia))
                Item.Tags["Trivia"] = m.Trivia;

                if (!String.IsNullOrEmpty(m.Goofs))
                Item.Tags["Mistakes"] = m.Goofs;

                Item.Tags["HasDetails"] = "True";
            }


            Item.SaveTags();
            #endregion


            return m;
        }
        internal static bool ValidateDownloadedDataAndRetry(string language, 
                                                           IMLItem item, string firstsub, WebClient client, string zipfilePath)
        {

            StreamReader sr = File.OpenText(zipfilePath);
            string zipfileLine = sr.ReadLine();

            if (zipfileLine != null && zipfileLine.Contains("DOCTYPE html"))
            {
                MainImportingEngine.ThisProgress.Progress
                    (MainImportingEngine.CurrentProgress,
                     "The subtitle archive was corrupt." +
                     " Retrying in 10 seconds...");

                sr.Close();
                Thread.Sleep(10000);

                File.Delete(zipfilePath);

                client.DownloadFile(firstsub, zipfilePath);


                sr = File.OpenText(zipfilePath);

                zipfileLine = sr.ReadLine();

                if (zipfileLine != null && zipfileLine.Contains("DOCTYPE html"))
                {
                    MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress,
                                                              "Unable to extract subtitle. The downloaded archive was corrupt.");

                    sr.Close();
                    Thread.Sleep(1500);
                    File.Delete(zipfilePath);

                    return false;
                }

                MainImportingEngine.ThisProgress.Progress
                    (MainImportingEngine.CurrentProgress,
                     "Subtitle for " + item.Name + " was downloaded succesfully.");

                Thread.Sleep(1500);

                item.Tags["HasSubtitle"] = "True";
                item.Tags["Subtitle language"] = language;
                item.SaveTags();

                sr.Close();
                sr.Dispose();

            }

            return true;

        }
        internal static bool SearchForAndDownloadFilmCoverArtFromMultipleSources
            (IMLItem item, string location,
             string videoFilename, 
             string mdfSettingsa,
             IBaseSystem ibs,
             string imageFile)
        {


            #region initialize variables


            string movieName = Helpers.GetTagValueFromItem(item, "Title");
            string releaseYear = Helpers.GetTagValueFromItem(item, "Year");
            #endregion

            string title = Helpers.GetTagValueFromItem(item, "Title");


            var imageUrls = new List<string>();
            var previewImages = new List<string>();
            //PreviewImages = ImageUrls;





            //TODO: Skip searching secondary sources if cover art is found from the first source.

            #region Add the image URLs from all sources



            if (MeediFier.Settings.PosterPrimarySource == "TheMovieDatabase")
            {

                if (MeediFier.Settings.TMDbPostersEnabled)
                {

                    if (imageUrls.Count == 0 || MeediFier.Settings.AlwaysPromptForImages)
                    {

                        //imageUrls.AddRange(TMDbFilmCoverArtScraper.GetFilmPostersFromTMDb(item, ref previewImages));
                        
                        //tmp = "";
                        //tmp = GetFilmPosterFromTMDb(Item);
                        //if (!String.IsNullOrEmpty(tmp))
                        //    ImageUrls.Add(tmp);
                    
                    }
                
                }


                if (MeediFier.Settings.ImpAwardsPostersEnabled)
                {
                    if (imageUrls.Count == 0 || MeediFier.Settings.AlwaysPromptForImages)
                    {
                        List<string> tmpList = ImpAwardsFilmCoverArtDownloader.GetPoster(item, movieName, releaseYear, "Both");
                        imageUrls.AddRange(tmpList);
                        previewImages.AddRange(tmpList);
                    }
                }

            }
            else
            {


                if (MeediFier.Settings.ImpAwardsPostersEnabled)
                {
                    if (imageUrls.Count == 0 || MeediFier.Settings.AlwaysPromptForImages)
                    {
                        List<string> tmpList = ImpAwardsFilmCoverArtDownloader.GetPoster(item, movieName, releaseYear, "Both");
                        imageUrls.AddRange(tmpList);
                        previewImages.AddRange(tmpList);
                    }
                }

                if (MeediFier.Settings.TMDbPostersEnabled)
                {
                    if (imageUrls.Count == 0 || MeediFier.Settings.AlwaysPromptForImages)
                    {

                        //imageUrls.AddRange(TMDbFilmCoverArtScraper.GetFilmPostersFromTMDb(item, ref previewImages));
                        //tmp = "";
                        //tmp = GetFilmPosterFromTMDb(Item);
                        //if (!String.IsNullOrEmpty(tmp))
                        //    ImageUrls.Add(tmp);
                    }
                }

            }

            if (MeediFier.Settings.IMDbPostersEnabled)
            {
                if (imageUrls.Count == 0 || MeediFier.Settings.AlwaysPromptForImages)
                {
                    string tmp = IMDbCoverArtScraper.GetFilmPosterFromIMDb
                        (item);


                    if (!String.IsNullOrEmpty(tmp))
                    {
                        imageUrls.Add(tmp);
                        previewImages.Add(tmp);
                    }
                }
            }

            #endregion



            if (imageUrls.Count == 0 || previewImages.Count == 0)
            {
                Debugger.LogMessageToFile("The image URLs list is empty. No online posters were found for this film.");
                return false;
            }



            string posterUrl 
                = ImageSelectionEngine
                .UserSelectsImage
                (item, imageUrls,
                previewImages,
                "poster");



            #region Download Image

            Helpers.UpdateProgress
                ("Updating Films Section...", 
                "Downloading film poster for "
                + title + "...", item);


            byte[] imageData = MeediFier.Downloaders
                .TrytoDownloadData(posterUrl, "Movies", "", item);



            if (imageData == null)
                return false;

            #endregion



            #region Save Image
            //if (SaveImage(imageData, Item, Importer.PosterNamingMethod, Importer.WhereToSavePoster, Importer.PosterFolder, true, VideoFilename, filepath, "", "") != "")
            if (ImageFileConstructor.SaveImage(imageData, item,true,"",imageFile) != "")
            {
                if (MeediFier.Settings.ResizeFilmPosters)
                {

                    Helpers.UpdateProgress
                        ("Updating Movies Section", 
                         "Resizing image...", item);
                    
                    ImageResizer.ResizeImage
                        (imageFile, imageFile, MeediFier.Settings.FilmPosterWidth, 
                         MeediFier.Settings.FilmPosterHeight, false);
                
                }

                item.SaveTags();
                return true;
            }


            return false;

            #endregion


        }
        internal static void ExtractAndRenameSubtitle(string language, IMLItem item,
            string parentPath, string videoFilename, string zipfilePath, FastZip fz)
        {

            MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress,
                                                      "Subtitle for " + item.Name + " was downloaded succesfully.");

            Thread.Sleep(1500);

            item.Tags["HasSubtitle"] = "True";
            item.Tags["Subtitle language"] = language;
            item.SaveTags();


            string subtitleFilename;
            string subtitleExtension;


            videoFilename = ConstructSubtitleFilenameAndExtractSubtitle
                (item, parentPath, videoFilename, fz, zipfilePath,
                 out subtitleFilename, out subtitleExtension);


            RenameSubtitleAccordingToVideoFilename
                (item, parentPath, videoFilename, subtitleFilename, subtitleExtension);


        }
        //TODO: This function should be changed to use regural expressions. 
        private static string ExtractImdbIdFromFilename
            (IMLItem item, IEnumerable<string> combinedSceneTags)
        {


            string imdbid = String.Empty;

            if (combinedSceneTags == null)
                return imdbid;

            
            if (!item.Name.Contains("tt"))
                return imdbid;


            int imdbidIndex
                = item.Name.IndexOf
                ("tt", StringComparison.Ordinal);


            if ((item.Name.Length - imdbidIndex) <= 2)
                return imdbid;


            Char firstDigit = item.Name[imdbidIndex + 2];
            if (imdbidIndex >= 0 && Char.IsNumber(firstDigit))
            {
                int imdbIndexStart = imdbidIndex;
                int imdbIndexEnd = 0;
                imdbidIndex = imdbidIndex + 2;
                //string substring = item.Name.Substring(imdbid_index, item.Name.Length - imdbid_index - 1);


                for (int i = imdbidIndex; i <= item.Name.Length; i++)
                {
                    if (Char.IsNumber(item.Name[i]))
                    {
                        imdbIndexEnd = i;
                    }
                    else break;
                }

                int imdbidLength = imdbIndexEnd - imdbidIndex + 1;
                imdbid = item.Name.Substring(imdbidIndex, imdbidLength);
                imdbid = "tt" + imdbid;


                item.Tags["ImdbID"] = imdbid;

                string leftNamepart = item.Name.Substring(0, imdbIndexStart);

                string rightNamepart = item.Name.Substring(imdbIndexEnd + 1,
                                                           item.Name.Length - imdbIndexEnd - 1);

                item.Name = leftNamepart + rightNamepart;
                item.SaveTags();
            }


            Debugger.LogMessageToFile
                (String.Format
                ("ImdbID {0} was extracted" +
                 " from item's name...", imdbid));



            return imdbid;
        }
        public static void OrganizeMediaFiles(IMLItem Item, string ItemTitle,
            string[] multipart, ref string location, string SortingDestination, 
            string directoryTagMask, itemUpdateParams updateParams,
            string MediaType)
        {


            if (!updateParams.FileServerIsOnline)
                return;

            if (Settings.OnlyTaggedForMoving &&
                (!Settings.OnlyTaggedForMoving || Helpers.GetTagValueFromItem(Item, "ReadyToSort") != "true"))
                return;


            if (Helpers.GetTagValueFromItem(Item, "FileSorted") == "true") 
                return;

            if (String.IsNullOrEmpty(ItemTitle))
                return;

            #region local varibales
            bool assignedLocationtoFirstItem = false;
            string fileTitle = ItemTitle;
            fileTitle = ToolBox.Utils.StringProcessors.StringBuilderProcessing.NormalizePath(fileTitle);
            string filmTitle = ItemTitle;
            filmTitle = ToolBox.Utils.StringProcessors.StringBuilderProcessing.NormalizePath(filmTitle);
            string multipaTlocation = "";
            bool CancelMoving = false;
            #endregion


            if (!SortingDestination.EndsWith(@"\"))
                SortingDestination = SortingDestination + @"\";


            #region loop files in item's location
            int i = 1;


            foreach (string partLocation in multipart)
            {

                if (File.Exists(partLocation))
                {
                    #region partfile variables

                    FileInfo partfileInfo = new FileInfo(partLocation);

                    string videoextension = partfileInfo.Extension;
                    long filesize = partfileInfo.Length;
                    long secstocopy = filesize / 10000000;
                    string folderToMove = "";

                    #endregion

                    #region synthesise full directory path

                    #region Synthesize folder
                    if (Settings.DirectoryStructure == "Simple- Default directory structures")
                    {
                        #region default structure

                        if (MediaType == "Film")
                        {
                            folderToMove = SortingDestination + filmTitle + @"\";
                        }
                        if (MediaType == "TvShow")
                        {
                            if (String.IsNullOrEmpty(Helpers.GetTagValueFromItem(Item, "SeriesName")) || Item.Tags["SeriesName"] == null)
                                CancelMoving = true;
                            if (String.IsNullOrEmpty(Helpers.GetTagValueFromItem(Item, "SeasonNumber")) || Item.Tags["SeasonNumber"] == null)
                                CancelMoving = true;

                            string seriesNameNorm = Helpers.GetTagValueFromItem(Item, "SeriesName");
                            seriesNameNorm = ToolBox.Utils.StringProcessors.StringBuilderProcessing.NormalizePath(seriesNameNorm);

                            folderToMove = SortingDestination + seriesNameNorm + @"\" + "Season " + Helpers.GetTagValueFromItem(Item, "SeasonNumber") + @"\";

                        }
                        if (MediaType == "Music")
                        {
                            if (String.IsNullOrEmpty(Helpers.GetTagValueFromItem(Item, "Album")))
                                CancelMoving = true;

                            folderToMove = SortingDestination + @"\" + Helpers.GetTagValueFromItem(Item, "Artist") + @"\" + Helpers.GetTagValueFromItem(Item, "Album") + @"\";
                        }


                        if (!Directory.Exists(folderToMove))
                            Directory.CreateDirectory(folderToMove);
                        #endregion
                    }
                    else
                    {
                        #region advanced structure
                        string[] FolderStructure = directoryTagMask.Split('\\');
                        string tagname = "";
                        string tagvalue = "";

                        folderToMove = SortingDestination;

                        #region Loop folder tag mask and construct new path
                        foreach (string folder in FolderStructure)
                        {
                            tagname = folder.Trim('<', '>');
                            tagvalue = Helpers.GetTagValueFromItem(Item, tagname);


                            if (String.IsNullOrEmpty(tagvalue))
                            {
                                CancelMoving = true;
                                MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress, "The item's tag '" + tagname + "' contains an empty value. Sorting operation was cancelled.");
                                Thread.Sleep(2500);
                            }
                            else
                            {
                                tagvalue = ToolBox.Utils.StringProcessors.StringBuilderProcessing.NormalizePath(tagvalue);
                                folderToMove += tagvalue + @"\";

                                //FolderToMove = Helpers.NormalizePath(FolderToMove);

                                //MessageBox.Show(FolderToMove);

                                if (!Directory.Exists(folderToMove))
                                    Directory.CreateDirectory(folderToMove);
                            }
                        }
                        #endregion


                        #endregion
                    }


                    #endregion

                    if (MediaType == "Film")
                    {
                        #region standrand filename synthesizer

                        if (String.IsNullOrEmpty(Helpers.GetTagValueFromItem(Item, "ImdbID")))
                            CancelMoving = true;

                        if (String.IsNullOrEmpty(Helpers.GetTagValueFromItem(Item, "Title")))
                            CancelMoving = true;

                        if (String.IsNullOrEmpty(Helpers.GetTagValueFromItem(Item, "Year") ) )
                            CancelMoving = true;

                        string canonicalTitle = Helpers.GetTagValueFromItem(Item, "Title");
                        canonicalTitle = ToolBox.Utils.StringProcessors.StringBuilderProcessing.NormalizePath(canonicalTitle);

                        fileTitle = Helpers.GetTagValueFromItem(Item, "ImdbID") + " - " + canonicalTitle + "(" + Helpers.GetTagValueFromItem(Item, "Year") + ")";

                        #endregion
                    }
                    if (MediaType == "TvShow")
                    {
                        #region standrand filename synthesizer

                        if (String.IsNullOrEmpty(Helpers.GetTagValueFromItem(Item, "EpisodeNumber") ) )
                            CancelMoving = true;

                        if (String.IsNullOrEmpty(Helpers.GetTagValueFromItem(Item, "EpisodeName") ) )
                            CancelMoving = true;


                        string seriesNameNorm = Helpers.GetTagValueFromItem(Item, "SeriesName");
                        seriesNameNorm = ToolBox.Utils.StringProcessors.StringBuilderProcessing.NormalizePath(seriesNameNorm);

                        string EpisodeNameNorm = Helpers.GetTagValueFromItem(Item, "EpisodeName");
                        EpisodeNameNorm = ToolBox.Utils.StringProcessors.StringBuilderProcessing.NormalizePath(EpisodeNameNorm);

                        string SeasonNumberNorm = Helpers.GetTagValueFromItem(Item, "SeasonNumber");
                        if (SeasonNumberNorm.Length == 1)
                            SeasonNumberNorm = "0" + SeasonNumberNorm;

                        string EpisodeNumberNorm = Helpers.GetTagValueFromItem(Item, "EpisodeNumber");
                        if (EpisodeNumberNorm.Length == 1)
                            EpisodeNumberNorm = "0" + EpisodeNumberNorm;

                        fileTitle = seriesNameNorm + " S" + SeasonNumberNorm + "E" + EpisodeNumberNorm + " - " + EpisodeNameNorm;
                        #endregion
                    }
                    if (MediaType == "Music")
                    {

                    }


                    if (!folderToMove.EndsWith(@"\"))
                        folderToMove = folderToMove + @"\";

                    if (multipart.Length > 1)
                        fileTitle = fileTitle + "[" + i + "]";


                    string locationToMove = folderToMove + fileTitle + videoextension;


                    
                    #endregion




                    #region decide if a file is going to be moved
                    DialogResult result;
                    bool DecideMoving = false;

                    if (locationToMove == partLocation)
                    {
                        DecideMoving = false;
                    }
                    else if (Settings.PromptBeforeMoving)
                    {
                        result = MessageBox.Show(null, "I'm going to move video file to: " + locationToMove + "     Is this ok?", "", MessageBoxButtons.YesNo);
                        if (result == DialogResult.Yes)
                            DecideMoving = true;
                    }
                    else DecideMoving = true;
                    #endregion

                    if (DecideMoving)
                    {


                        if (!CancelMoving)
                        {

                            if (locationToMove != partLocation)
                            {

                                #region move the file and update library

                                if (!updateParams.FileInUse)
                                {
                                                


                                    MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress, "Moving " + ItemTitle + "... " + secstocopy + " seconds remaining.");
                                    Thread.Sleep(500);


                                    try
                                    {

                                        File.Move(partLocation, locationToMove);

                                        #region Move the associated SRT subtitle
                                        string subtitleOldLocation = partLocation.Remove(partLocation.Length - 3, 3);
                                        subtitleOldLocation = subtitleOldLocation + "srt";
                                        string subtitleNewLocation = locationToMove.Remove(locationToMove.Length - 3, 3);
                                        subtitleNewLocation = subtitleNewLocation + "srt";

                                        if (File.Exists(subtitleOldLocation))
                                            File.Move(subtitleOldLocation, subtitleNewLocation);
                                        #endregion

                                        #region Move the associated SUB subtitle
                                        subtitleOldLocation = partLocation.Remove(partLocation.Length - 3, 3);
                                        subtitleOldLocation = subtitleOldLocation + "sub";
                                        subtitleNewLocation = locationToMove.Remove(locationToMove.Length - 3, 3);
                                        subtitleNewLocation = subtitleNewLocation + "sub";

                                        if (File.Exists(subtitleOldLocation))
                                            File.Move(subtitleOldLocation, subtitleNewLocation);
                                        #endregion


                                        #region update item tags
                                        if (updateParams.IsMultipart)
                                        {
                                            multipaTlocation += "|" + locationToMove;

                                            if (partLocation == multipart[multipart.Length - 1])
                                                multipaTlocation += "|";

                                            Item.Location = multipaTlocation;
                                        }
                                        else Item.Location = locationToMove;

                                        Item.Tags["FileSorted"] = "true";
                                        Item.SaveTags();
                                        #endregion

                                        #region Prevent the updating of item's location for the remaining parts
                                        if (!assignedLocationtoFirstItem)
                                        {
                                            location = locationToMove;
                                            assignedLocationtoFirstItem = true;
                                        }
                                        #endregion

                                    }
                                    catch (Exception e)
                                    {
                                        Debugger.LogMessageToFile("An error occurred while trying to move the file " + location + 
                                                                  " to destination " + locationToMove + ". The error was: " + e);

                                        
                                        StatusForm.statusForm.TrayIcon.ShowBalloonTip(10000, "file moving error", 
                                                                                      "An unexpected error occured while MediaFairy was trying to move the media file " + location + 
                                                                                      " to " + locationToMove + ". The error was: " + e.Message, ToolTipIcon.Error);

                                        continue;
                                    }



                                }

                                #endregion

                            }

                        }
                    }

                }

                i++;
            } //endof PartLocation loop
            #endregion


        }
        //TODO: This function should be changed to use regural expressions. 
        private static void ExtractYearFromFilename(IMLItem item)
        {


            #region First Try: Year in parenthesis
            int tempIndex = item.Name.IndexOf("[19");

            int yearIndex = tempIndex >= 0
                ? tempIndex + 1
                : 0;

            tempIndex = item.Name.IndexOf("(19");
            if (tempIndex >= 0) yearIndex = tempIndex + 1;

            tempIndex = item.Name.IndexOf(".19");
            if (tempIndex >= 0) yearIndex = tempIndex + 1;

            tempIndex = item.Name.IndexOf("[20");
            if (tempIndex >= 0) yearIndex = tempIndex + 1;

            tempIndex = item.Name.IndexOf("(20");
            if (tempIndex >= 0) yearIndex = tempIndex + 1;

            tempIndex = item.Name.IndexOf(".20");
            if (tempIndex >= 0) yearIndex = tempIndex + 1;
            #endregion

            #region Second Try: Year without parenthesis
            if (yearIndex == 0)
            {
                int lastChar = item.Name.Length - 1;
                int firstYearChar = lastChar - 3;
                string numberWord = item.Name.Substring(firstYearChar, 4);

                if (!numberWord.Contains("x") && !numberWord.Contains("E") 
                    && !numberWord.Contains("S") )
                    //the number extracted must Not belong to episode numbers
                {
                    if (item.Name.Length >= 8)
                    {
                        if (Char.IsDigit(item.Name[lastChar]))
                        {
                            if (Char.IsDigit(item.Name[firstYearChar]))
                            {
                                #region Second Try: Year without parenthesis
                                tempIndex = item.Name.IndexOf("19");
                                if (tempIndex >= 0) yearIndex = tempIndex;

                                tempIndex = item.Name.IndexOf("20");
                                if (tempIndex >= 0) yearIndex = tempIndex;
                                #endregion
                            }
                        }
                    }
                }
            }
            #endregion




            #region Extract Year and store it in item's tag

            if (yearIndex <= 0)
                return;

            string year = item
                .Name.Substring
                (yearIndex, 4);


            item.Tags["Year"] = year;
            item.SaveTags();


            item.Name = item.Name.Trim();
                       
            Char yearPrevChar = item.Name[yearIndex -1];



            if (String.CompareOrdinal(yearPrevChar.ToString
                (CultureInfo.InvariantCulture),
                '('.ToString(CultureInfo.InvariantCulture)) == 0 
                || String.CompareOrdinal(yearPrevChar.ToString
                (CultureInfo.InvariantCulture),
                '['.ToString(CultureInfo.InvariantCulture)) == 0 
                || String.CompareOrdinal(yearPrevChar.ToString
                (CultureInfo.InvariantCulture),
                '.'.ToString(CultureInfo.InvariantCulture)) == 0)
                yearIndex = yearIndex - 1;


            item.Name = item.Name.Substring(0, yearIndex);
            item.Name = item.Name.Trim();
            item.SaveTags();



            Debugger.LogMessageToFile
                (String.Format
                ("The film's Year ({0})" +
                 " was extracted from" +
                 " item's name.", year));


            #endregion

        }