Пример #1
0
        public FilenameParser(string filename)
        {
            try
            {
                ////////////////////////////////////////////////////////////////////////////////////////////
                // Parsing filename for all recognized naming formats to extract episode information
                ////////////////////////////////////////////////////////////////////////////////////////////
                m_Filename = filename;
                if (sExpressions.Count == 0)
                {
                    reLoadExpressions();
                }

                int index = 0;

                // run Before replacements
                m_FileNameAfterReplacement = RunReplacements(replacementRegexBefore, m_Filename);

                foreach (Regex regularExpression in regularExpressions)
                {
                    Match matchResults;
                    matchResults = regularExpression.Match(m_FileNameAfterReplacement);

                    if (matchResults.Success)
                    {
                        for (int i = 1; i < matchResults.Groups.Count; i++)
                        {
                            string GroupName  = regularExpression.GroupNameFromNumber(i);
                            string GroupValue = matchResults.Groups[i].Value;

                            if (GroupValue.Length > 0 && GroupName != "unknown")
                            {
                                // ´run after replacements on captures
                                GroupValue = RunReplacements(replacementRegexAfter, GroupValue);

                                GroupValue = GroupValue.Trim();
                                m_Matches.Add(GroupName, GroupValue);
                            }
                        }
                        // stop on the first successful match
                        m_RegexpMatched    = sExpressions[index];
                        m_RegexpMatchedIdx = index;
                        return;
                    }
                    index++;
                }
            }
            catch (Exception ex)
            {
                MPTVSeriesLog.Write("And error occured in the 'FilenameParser' function (" + ex.ToString() + ")");
            }
        }
Пример #2
0
 public static void StartDiskWatcher()
 {
     lock (syncRoot) {
         if (!MonitorStarted)
         {
             MPTVSeriesLog.Write("Starting Disk Watcher...", MPTVSeriesLog.LogLevel.Normal);
             watcherThread      = new Thread(new ThreadStart(WatchDisks));
             watcherThread.Name = "DeviceManager.WatchDisks";
             watcherThread.Start();
             MPTVSeriesLog.Write("Successfully started Disk Watcher.", MPTVSeriesLog.LogLevel.Normal);
         }
     }
 }
Пример #3
0
        public List <DBSeries> getSeriesItems(int stepIndex, string[] currentStepSelection)
        {
            MPTVSeriesLog.Write("View: Get Series Items", MPTVSeriesLog.LogLevel.Debug);
            SQLCondition conditions = null;

            if (stepIndex >= m_steps.Count)
            {
                return(null);                            // wrong index specified!!
            }
            addHierarchyConditions(ref stepIndex, ref currentStepSelection, ref conditions);
            MPTVSeriesLog.Write("View: Get Series Items: Executing SQL", MPTVSeriesLog.LogLevel.Debug);
            return(DBSeries.Get(conditions));
        }
Пример #4
0
        private static void GetDefines(XmlDocument doc)
        {
            MPTVSeriesLog.Write("Loading Skin Defines", MPTVSeriesLog.LogLevel.Normal);

            // clear defines
            Defines.Clear();

            XmlNode node = null;

            node = doc.DocumentElement.SelectSingleNode(string.Format("/settings/defines//property[@key='{0}']", cfanartlistlayout));
            if (node != null)
            {
                Defines.Add(cfanartlistlayout, node.InnerText);
            }

            node = doc.DocumentElement.SelectSingleNode(string.Format("/settings/defines//property[@key='{0}']", cfanarticonslayout));
            if (node != null)
            {
                Defines.Add(cfanarticonslayout, node.InnerText.ToLowerInvariant());
            }

            node = doc.DocumentElement.SelectSingleNode(string.Format("/settings/defines//property[@key='{0}']", cfanartfilmstriplayout));
            if (node != null)
            {
                Defines.Add(cfanartfilmstriplayout, node.InnerText.ToLowerInvariant());
            }

            node = doc.DocumentElement.SelectSingleNode(string.Format("/settings/defines//property[@key='{0}']", cfanartcoverflowlayout));
            if (node != null)
            {
                Defines.Add(cfanartcoverflowlayout, node.InnerText.ToLowerInvariant());
            }

            node = doc.DocumentElement.SelectSingleNode(string.Format("/settings/defines//property[@key='{0}']", cfanartseriesview));
            if (node != null)
            {
                Defines.Add(cfanartseriesview, node.InnerText.ToLowerInvariant());
            }

            node = doc.DocumentElement.SelectSingleNode(string.Format("/settings/defines//property[@key='{0}']", cfanartseasonview));
            if (node != null)
            {
                Defines.Add(cfanartseasonview, node.InnerText.ToLowerInvariant());
            }

            node = doc.DocumentElement.SelectSingleNode(string.Format("/settings/defines//property[@key='{0}']", cfanartepisodeview));
            if (node != null)
            {
                Defines.Add(cfanartepisodeview, node.InnerText.ToLowerInvariant());
            }
        }
Пример #5
0
        public static void UpdateEpisodeCounts(DBSeries series)
        {
            if (series == null)
            {
                return;
            }

            int seriesEpsTotal     = 0;
            int seriesEpsUnWatched = 0;
            int epsTotal           = 0;
            int epsUnWatched       = 0;

            // Update for each season in series and add each to total series count
            SQLCondition condition = new SQLCondition();

            if (!DBOption.GetOptions(DBOption.cShowHiddenItems))
            {
                //don't include hidden seasons unless the ShowHiddenItems option is set
                condition.Add(new DBSeason(), DBSeason.cHidden, 0, SQLConditionType.Equal);
            }

            List <DBSeason> Seasons = DBSeason.Get(series[DBSeries.cID], condition);

            foreach (DBSeason season in Seasons)
            {
                epsTotal     = 0;
                epsUnWatched = 0;

                DBEpisode.GetSeasonEpisodeCounts(series, season, out epsTotal, out epsUnWatched);
                season[DBSeason.cEpisodeCount]      = epsTotal;
                season[DBSeason.cEpisodesUnWatched] = epsUnWatched;
                season[DBSeason.cUnwatchedItems]    = epsUnWatched > 0;
                season.Commit();

                seriesEpsTotal += epsTotal;
                // Count the Special (Season 0 (zero)) episodes as watched!
                if ((season[DBSeason.cIndex] != 0) || (season[DBSeason.cIndex] == 0 && !DBOption.GetOptions(DBOption.cCountSpecialEpisodesAsWatched)))
                {
                    seriesEpsUnWatched += epsUnWatched;
                }

                MPTVSeriesLog.Write(string.Format("Series \"{0} Season {1}\" has {2}/{3} unwatched episodes", series.ToString(), season[DBSeason.cIndex], epsUnWatched, epsTotal), MPTVSeriesLog.LogLevel.Debug);
            }

            MPTVSeriesLog.Write(string.Format("Series \"{0}\" has {1}/{2} unwatched episodes", series.ToString(), seriesEpsUnWatched, seriesEpsTotal), MPTVSeriesLog.LogLevel.Debug);

            series[DBOnlineSeries.cEpisodeCount]      = seriesEpsTotal;
            series[DBOnlineSeries.cEpisodesUnWatched] = seriesEpsUnWatched;
            series[DBOnlineSeries.cUnwatchedItems]    = seriesEpsUnWatched > 0;
            series.Commit();
        }
Пример #6
0
        /// <summary>
        /// Gets all properties used by this plugin
        /// </summary>
        /// <param name="skinfile"></param>
        static void GetSkinProperties(string filename)
        {
            string content = string.Empty;

            StreamReader r = new StreamReader(filename);

            content = r.ReadToEnd();

            Regex           reg     = new Regex(@"(#TVSeries\.\w+(?:\.\w+)*)");
            MatchCollection matches = reg.Matches(content);

            MPTVSeriesLog.Write("Skin uses " + matches.Count.ToString() + " fields", MPTVSeriesLog.LogLevel.Debug);

            for (int i = 0; i < matches.Count; i++)
            {
                string pre    = string.Empty;
                string remove = string.Empty;

                if (matches[i].Value.Contains((remove = "#TVSeries.Episode.")))
                {
                    pre = "Episode";
                }
                else if (matches[i].Value.Contains((remove = "#TVSeries.Season.")))
                {
                    pre = "Season";
                }
                else if (matches[i].Value.Contains((remove = "#TVSeries.Series.")))
                {
                    pre = "Series";
                }

                string value = matches[i].Value.Trim().Replace(remove, string.Empty);
                if (pre.Length > 0)
                {
                    if (SkinProperties.ContainsKey(pre))
                    {
                        if (!SkinProperties[pre].Contains(value))
                        {
                            SkinProperties[pre].Add(value);
                        }
                    }
                    else
                    {
                        List <string> v = new List <string>();
                        v.Add(value);
                        SkinProperties.Add(pre, v);
                    }
                }
            }
        }
Пример #7
0
        public static void DeleteXmlCache(int aSeriesID)
        {
            string lPath = Path.Combine(Settings.GetPath(Settings.Path.config), string.Format(@"Cache\{0}\", aSeriesID.ToString()));

            MPTVSeriesLog.Write($"Deleting series API cache. Path={lPath}");
            try
            {
                Directory.Delete(lPath, true);
            }
            catch (Exception e)
            {
                MPTVSeriesLog.Write($"Error deleting series API cache. Exception={e.Message}");
            }
        }
Пример #8
0
        private static void InitDB()
        {
            if (System.Diagnostics.Process.GetCurrentProcess().ProcessName.ToLower() == "devenv")
            {
                return;
            }

            string databaseFile = Settings.GetPath(Settings.Path.database);

            bool databaseExists = true;

            if (!File.Exists(databaseFile))
            {
                databaseExists = false;
            }

            try
            {
                m_db = new SQLiteClient(databaseFile);

                // check database integrity
                if (databaseExists)
                {
                    if (CheckIntegrity())
                    {
                        // backup volume if all is good
                        Backup();
                    }
                    else
                    {
                        // restore last known good volume if corrupt
                        Restore();
                    }
                }

                ExecutePragmas();

                MPTVSeriesLog.Write("Successfully opened database. Filename = '{0}'", databaseFile);

                return;
            }
            catch (Exception ex)
            {
                MPTVSeriesLog.Write("Failed to open database. Filename = '{0}', Reason = '{1}'", databaseFile, ex.Message);

                // restore last known good volume
                Restore();
                ExecutePragmas();
            }
        }
Пример #9
0
 internal static void LogOptions()
 {
     lock (thisLock)
     {
         foreach (string key in optionsCache.Keys)
         {
             // dont log private options
             if (!key.Equals(DBOption.cOnlineUserID))
             {
                 MPTVSeriesLog.Write(string.Format("Option {0}: {1}", key, optionsCache[key].ToString()), MPTVSeriesLog.LogLevel.Debug);
             }
         }
     }
 }
Пример #10
0
        public bool Load(PlayList incomingPlaylist, string playlistFileName)
        {
            if (playlistFileName == null)
            {
                return(false);
            }

            playlist = incomingPlaylist;
            playlist.Clear();

            XmlDocument doc = new XmlDocument();

            try
            {
                doc.Load(playlistFileName);
            }
            catch (XmlException e)
            {
                MPTVSeriesLog.Write(string.Format("Cannot Load Playlist file: {0}", playlistFileName));
                MPTVSeriesLog.Write(e.Message);
                return(false);
            }

            try
            {
                playlist.Name = Path.GetFileName(playlistFileName);
                basePath      = Path.GetDirectoryName(Path.GetFullPath(playlistFileName));

                XmlNodeList nodeList = doc.DocumentElement.SelectNodes("/Playlist/Episode");
                if (nodeList == null)
                {
                    return(false);
                }

                foreach (XmlNode node in nodeList)
                {
                    if (!AddItem(node.SelectSingleNode("ID").InnerText))
                    {
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                MPTVSeriesLog.Write(string.Format("exception loading playlist {0} err:{1} stack:{2}", playlistFileName, ex.Message, ex.StackTrace));
                return(false);
            }
            return(true);
        }
Пример #11
0
        public virtual bool AddColumn(String sName, DBField field)
        {
            // verify if we already have that field avail
            if (!m_fields.ContainsKey(sName))
            {
                if (m_fields.Count == 0 && !field.Primary)
                {
                    throw new Exception("First field added needs to be the index");
                }

                try
                {
                    // ok, we don't, add it
                    SQLiteResultSet results;
                    results = DBTVSeries.Execute("SELECT name FROM sqlite_master WHERE name='" + m_tableName + "'");
                    if (results != null && results.Rows.Count > 0)
                    {
                        // table already exists, alter it
                        String sQuery = "ALTER TABLE " + m_tableName + " ADD " + sName + " " + field.Type;
                        DBTVSeries.Execute(sQuery);
                    }
                    else
                    {
                        // new table, create it
                        // no tables, assume it's going to be created later (using AddColumn)
                        string type = field.Type.ToString();
                        if (field.Primary && field.Type == DBField.cType.Int && field.AutoIncrement)
                        {
                            //for the automatic creation of an auto incremental integer primary key you must use the full "Integer" not just "int"
                            type = "Integer";
                        }

                        String sQuery = "CREATE TABLE " + m_tableName + " (" + sName + " " + type + (field.Primary ? " primary key)" : ")");
                        DBTVSeries.Execute(sQuery);
                    }
                    // delete the s_fields cache so newed up objects get the right fields
                    lock (fields)
                        fields.Remove(m_tableName);
                    m_fields.Add(sName, field);
                    return(true);
                }
                catch (Exception ex)
                {
                    MPTVSeriesLog.Write(m_tableName + " table.AddColumn failed (" + ex.Message + ").");
                    return(false);
                }
            }
            return(false);
        }
Пример #12
0
        static cache()
        {
            if (!Settings.isConfig)
            {
                // for globalset and clear we dumb all objects in question
                DBTable.dbUpdateOccured += new DBTable.dbUpdateOccuredDelegate(DBTable_dbUpdateOccured);
                // for commits on single object we can update the specific object in question
                // (if commited ones are not yet in cache we don't add them though)
                DBSeries.dbSeriesUpdateOccured   += new DBSeries.dbSeriesUpdateOccuredDelegate(DBSeries_dbSeriesUpdateOccured);
                DBSeason.dbSeasonUpdateOccured   += new DBSeason.dbSeasonUpdateOccuredDelegate(DBSeason_dbSeasonUpdateOccured);
                DBEpisode.dbEpisodeUpdateOccured += new DBEpisode.dbEpisodeUpdateOccuredDelegate(DBEpisode_dbEpisodeUpdateOccured);

                MPTVSeriesLog.Write("Cache Initialized", MPTVSeriesLog.LogLevel.Debug);
            }
        }
Пример #13
0
        public Watcher(List <String> WatchedFolders, int nScanLapse)
        {
            MPTVSeriesLog.Write("File Watcher: Creating new File System Watcher", MPTVSeriesLog.LogLevel.Normal);

            m_nScanLapse = nScanLapse;

            foreach (String folder in WatchedFolders)
            {
                string sRoot = System.IO.Path.GetPathRoot(folder);
                try
                {
                    DriveInfo info = new DriveInfo(sRoot);

                    if (info.DriveType == DriveType.CDRom)
                    {
                        // do nothing as filesystemwatchers do nothing for cd or dvd drives
                        MPTVSeriesLog.Write(string.Format("File Watcher: Skipping CD/DVD drive: {0}", sRoot), MPTVSeriesLog.LogLevel.Normal);
                    }
                    else if (info.DriveType == DriveType.Network)
                    {
                        //string sUNCPath=MPR.GetUniversalName(folder);

                        MPTVSeriesLog.Write(string.Format("File Watcher: Adding watcher on folder: {0}", folder), MPTVSeriesLog.LogLevel.Normal);
                        m_ScannedFolders.Add(folder);
                    }
                    else
                    {
                        MPTVSeriesLog.Write(string.Format("File Watcher: Adding watcher on folder: {0}", folder), MPTVSeriesLog.LogLevel.Normal);
                        m_WatchedFolders.Add(folder);
                    }
                }
                catch (System.ArgumentException)
                {
                    // this has to be a UNC path
                    MPTVSeriesLog.Write(string.Format("File Watcher: Adding watcher on folder: {0}", folder), MPTVSeriesLog.LogLevel.Normal);
                    m_ScannedFolders.Add(folder);
                }
            }

            DeviceManager.OnVolumeInserted += OnVolumeInsertedRemoved;
            DeviceManager.OnVolumeRemoved  += OnVolumeInsertedRemoved;

            worker.WorkerReportsProgress      = true;
            worker.WorkerSupportsCancellation = true;
            worker.ProgressChanged           += new ProgressChangedEventHandler(worker_ProgressChanged);
            worker.RunWorkerCompleted        += new RunWorkerCompletedEventHandler(worker_Completed);
            worker.DoWork += new DoWorkEventHandler(workerWatcher_DoWork);
        }
Пример #14
0
        public static void AddWatchDrive(string path, bool localOnly)
        {
            try {
                // if the path does not point to logical volume do not add it to the drive watcher
                if (PathIsUnc(path))
                {
                    return;
                }

                if (localOnly)
                {
                    if (PathIsOnNetwork(path))
                    {
                        return;
                    }
                }

                // get the driveletter
                string driveLetter = GetDriveLetter(path);
                if (driveLetter == null)
                {
                    return;
                }

                // add the drive to the drive watcher
                lock (syncRoot) {
                    if (watchedDrives == null)
                    {
                        watchedDrives = new List <string>();
                    }

                    if (!watchedDrives.Contains(driveLetter))
                    {
                        watchedDrives.Add(driveLetter);
                        StartDiskWatcher();
                        MPTVSeriesLog.Write("Added " + driveLetter + " to Disk Watcher", MPTVSeriesLog.LogLevel.Normal);
                    }
                }
            }
            catch (Exception e) {
                if (e is ThreadAbortException)
                {
                    throw e;
                }

                MPTVSeriesLog.Write("Error adding \"" + path + "\" to Disk Watcher!!", MPTVSeriesLog.LogLevel.Debug);
            }
        }
Пример #15
0
        public static void Close()
        {
            string databaseFile = Settings.GetPath(Settings.Path.database);

            try
            {
                m_db.Close();
                m_db.Dispose();
                m_db = null;
                MPTVSeriesLog.Write("Successfully closed database. Filename = '{0}'", databaseFile);
            }
            catch (Exception)
            {
                MPTVSeriesLog.Write("Failed to close database. Filename = '{0}'", databaseFile);
            }
        }
Пример #16
0
 public static void cleanUP() // there is no static destructor in .NET, so this has to be called explicitally
 {
     // clean up all dynLogoFiles
     MPTVSeriesLog.Write("Cleaning up cached, generated Logos");
     foreach (string file in System.IO.Directory.GetFiles(pathfortmpfile, "TVSeriesDynLogo*"))
     {
         try
         {
             System.IO.File.Delete(file);
         }
         catch (Exception ex)
         {
             MPTVSeriesLog.Write("Error: Could not delete temporary Logo File " + file, ex.Message, MPTVSeriesLog.LogLevel.Normal);
         }
     }
 }
Пример #17
0
 private static void CreateTable()
 {
     try
     {
         SQLiteResultSet results = DBTVSeries.Execute("SELECT name FROM sqlite_master WHERE name='options' and type='table' UNION ALL SELECT name FROM sqlite_temp_master WHERE type='table' ORDER BY name");
         if (results == null || results.Rows.Count == 0)
         {
             // no table, create it
             DBTVSeries.Execute("CREATE TABLE options (option_id integer primary key, property text, value text)");
         }
     }
     catch (Exception ex)
     {
         MPTVSeriesLog.Write("DBOption.CreateTable failed (" + ex.Message + ").");
     }
 }
Пример #18
0
        void DoFileScan(List <String> scannedFolders, ref List <PathPair> previousScan)
        {
            MPTVSeriesLog.Write("File Watcher: Performing File Scan on Import Paths for changes", MPTVSeriesLog.LogLevel.Normal);

            // Check if Fullscreen Video is active as this can cause stuttering/dropped frames
            if (!DBOption.GetOptions(DBOption.cImportScanWhileFullscreenVideo) && Helper.IsFullscreenVideo)
            {
                MPTVSeriesLog.Write("File Watcher: Fullscreen Video has been detected, aborting file scan");
                return;
            }

            List <PathPair> newScan = Filelister.GetFiles(scannedFolders);

            List <PathPair> addedFiles = new List <PathPair>();

            addedFiles.AddRange(newScan);

            foreach (PathPair pair in previousScan)
            {
                addedFiles.RemoveAll(item => item.m_sFull_FileName == pair.m_sFull_FileName);
            }

            List <PathPair> removedFiles = new List <PathPair>();

            removedFiles.AddRange(previousScan);
            foreach (PathPair pair in newScan)
            {
                removedFiles.RemoveAll(item => item.m_sFull_FileName == pair.m_sFull_FileName);
            }

            lock (m_modifiedFilesList)
            {
                foreach (PathPair pair in addedFiles)
                {
                    m_modifiedFilesList.Add(new WatcherItem(pair, WatcherItemType.Added));
                }

                foreach (PathPair pair in removedFiles)
                {
                    m_modifiedFilesList.Add(new WatcherItem(pair, WatcherItemType.Deleted));
                }
            }

            previousScan = newScan;

            MPTVSeriesLog.Write("File Watcher: Finished File Scan on Import Paths", MPTVSeriesLog.LogLevel.Normal);
        }
Пример #19
0
        static void appendLogos(List <string> logosForBuilding, ref Graphics g, int totalHeight, int totalWidth)
        {
            int          noImgs     = logosForBuilding.Count;
            List <Image> imgs       = new List <Image>();
            List <Size>  imgSizes   = new List <Size>();
            int          spacer     = 5;
            int          checkWidth = 0;
            // step one: get all sizes (not all logos are obviously square) and scale them to fit vertically
            Image single = null;
            float scale = 0, totalHeightf = (float)totalHeight;
            Size  tmp   = default(Size);
            int   x_pos = 0;

            for (int i = 0; i < logosForBuilding.Count; i++)
            {
                try
                {
                    single = ImageAllocator.LoadImageFastFromFile(logosForBuilding[i]);
                }
                catch (Exception)
                {
                    MPTVSeriesLog.Write("Could not load Image file... " + logosForBuilding[i]);
                    return;
                }
                scale       = totalHeightf / (float)single.Size.Height;
                tmp         = new Size((int)(single.Width * scale), (int)(single.Height * scale));
                checkWidth += tmp.Width;
                imgSizes.Add(tmp);
                imgs.Add(single);
            }
            // step two: check if we are too big horizontally and if so scale again
            checkWidth += imgSizes.Count * spacer;
            if (checkWidth > totalWidth)
            {
                scale = (float)checkWidth / (float)totalWidth;
                for (int i = 0; i < imgSizes.Count; i++)
                {
                    imgSizes[i] = new Size((int)(imgSizes[i].Width / scale), (int)(imgSizes[i].Height / scale));
                }
            }
            // step three: finally draw them
            for (int i = 0; i < imgs.Count; i++)
            {
                g.DrawImage(imgs[i], x_pos, totalHeight - imgSizes[i].Height, imgSizes[i].Width, imgSizes[i].Height);
                x_pos += imgSizes[i].Width + spacer;
            }
        }
Пример #20
0
 public void Delete()
 {
     // first let's delete the physical file
     if (this.IsAvailableLocally)
     {
         try
         {
             System.IO.File.Delete(FullLocalPath);
             MPTVSeriesLog.Write("Fanart Deleted: " + FullLocalPath);
         }
         catch (Exception ex)
         {
             MPTVSeriesLog.Write("Failed to delete file: " + FullLocalPath + " (" + ex.Message + ")");
         }
     }
     Clear(this[cIndex]);
 }
Пример #21
0
        public static List <P> getPropertyListFromList <T, P>(string PropertyNameToGet, List <T> elements)
        {
            List <P> results = new List <P>();

            foreach (T elem in elements)
            {
                try
                {
                    results.Add((P)elem.GetType().InvokeMember(PropertyNameToGet, System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.GetField, null, elem, null));
                }
                catch (Exception)
                {
                    MPTVSeriesLog.Write("Wrong call of getPropertyListFromList<T,P>: Type " + elem.GetType().Name);
                }
            }
            return(results);
        }
Пример #22
0
        void signalModifiedFiles()
        {
            try
            {
                lock (m_modifiedFilesList)
                {
                    if (m_modifiedFilesList.Count > 0)
                    {
                        m_modifiedFilesList = removeDuplicates(m_modifiedFilesList);

                        MPTVSeriesLog.Write("File Watcher: Signaling " + m_modifiedFilesList.Count + " modified files");
                        List <WatcherItem> outList = new List <WatcherItem>();

                        // leave locked files in the m_modifiedFilesList
                        foreach (WatcherItem watcherItem in m_modifiedFilesList)
                        {
                            if (!watcherItem.IsLocked())
                            {
                                outList.Add(watcherItem);
                            }
                            else
                            {
                                MPTVSeriesLog.Write("File " + watcherItem.m_sParsedFileName + " is locked, leaving for later parsing!", MPTVSeriesLog.LogLevel.Debug);
                            }
                        }
                        // clear m_modifiedFilesList
                        foreach (WatcherItem watcherItem in outList)
                        {
                            m_modifiedFilesList.Remove(watcherItem);
                        }

                        // go over the modified files list once in a while & update
                        //outList.AddRange(m_modifiedFilesList);
                        //m_modifiedFilesList.Clear();
                        if (outList.Count > 0)
                        {
                            worker.ReportProgress(0, outList);
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                MPTVSeriesLog.Write("File Watcher: Exception happened in Signal Modified Files: " + exp.Message);
            }
        }
Пример #23
0
 public bool ReadPrimary(DBValue Value)
 {
     try
     {
         m_fields[PrimaryKey()].Value = Value;
         SQLCondition condition = new SQLCondition();
         condition.Add(this, PrimaryKey(), m_fields[PrimaryKey()].Value, SQLConditionType.Equal);
         String          sqlQuery = "select * from " + m_tableName + condition;
         SQLiteResultSet records  = DBTVSeries.Execute(sqlQuery);
         return(Read(ref records, 0));
     }
     catch (Exception ex)
     {
         MPTVSeriesLog.Write("An Error Occurred (" + ex.Message + ").");
     }
     return(false);
 }
Пример #24
0
        public static IEnumerable <DBFormatting> GetAll(bool includeDisabled)
        {
            if (cache == null || Settings.isConfig)
            {
                try
                {
                    // make sure the table is created - create a dummy object
                    DBFormatting dummy = new DBFormatting();

                    // retrieve all fields in the table
                    String sqlQuery = "select * from " + cTableName;
                    if (!includeDisabled)
                    {
                        sqlQuery += " where " + cEnabled + " = 1";
                    }
                    sqlQuery += " order by " + cIndex;

                    SQLiteResultSet results = DBTVSeries.Execute(sqlQuery);
                    if (results.Rows.Count > 0)
                    {
                        cache = new DBFormatting[results.Rows.Count];
                        for (int index = 0; index < results.Rows.Count; index++)
                        {
                            cache[index] = new DBFormatting();
                            cache[index].Read(ref results, index);
                        }
                    }
                    MPTVSeriesLog.Write("Found and loaded " + results.Rows.Count + " User Formatting Rules", MPTVSeriesLog.LogLevel.Debug);
                    if (results.Rows.Count == 0)
                    {
                        cache = new DBFormatting[0];
                    }
                }
                catch (Exception ex)
                {
                    MPTVSeriesLog.Write("Error in DBFormatting.Get (" + ex.Message + ").");
                }
            }
            if (cache != null)
            {
                for (int i = 0; i < cache.Length; i++)
                {
                    yield return(cache[i]);
                }
            }
        }
Пример #25
0
        public WatcherItem(FileSystemWatcher watcher, FileSystemEventArgs e)
        {
            m_sFullPathFileName = e.FullPath;
            m_sParsedFileName   = m_sFullPathFileName.Substring(watcher.Path.Length).TrimStart('\\');
            switch (e.ChangeType)
            {
            case WatcherChangeTypes.Deleted:
                m_type = WatcherItemType.Deleted;
                break;

            default:
                m_type   = WatcherItemType.Added;
                fileInfo = new FileInfo(m_sFullPathFileName);
                break;
            }
            MPTVSeriesLog.Write("File monitor: " + m_sParsedFileName + " " + m_type);
        }
Пример #26
0
 public WatcherItem(FileSystemWatcher watcher, RenamedEventArgs e, bool bOldName)
 {
     if (bOldName)
     {
         m_sFullPathFileName = e.OldFullPath;
         m_sParsedFileName   = m_sFullPathFileName.Substring(watcher.Path.Length).TrimStart('\\');
         m_type = WatcherItemType.Deleted;
         MPTVSeriesLog.Write("File monitor: " + m_sParsedFileName + " " + m_type);
     }
     else
     {
         m_sFullPathFileName = e.FullPath;
         m_sParsedFileName   = m_sFullPathFileName.Substring(watcher.Path.Length).TrimStart('\\');
         fileInfo            = new FileInfo(m_sFullPathFileName);
         m_type = WatcherItemType.Added;
         MPTVSeriesLog.Write("File monitor: " + m_sParsedFileName + " " + m_type);
     }
 }
Пример #27
0
 /// <summary>
 /// Removes non-existant files from a list of filenames
 /// </summary>
 /// <param name="filenames"></param>
 /// <returns></returns>
 public static List <string> filterExistingFiles(List <string> filenames)
 {
     for (int f = 0; f < filenames.Count; f++)
     {
         bool wasCached = false;
         if ((wasCached = nonExistingFiles.Contains(filenames[f])) || !System.IO.File.Exists(filenames[f]))
         {
             if (!wasCached)
             {
                 MPTVSeriesLog.Write("File does not exist: " + filenames[f], MPTVSeriesLog.LogLevel.Debug);
                 nonExistingFiles.Add(filenames[f]);
             }
             filenames.RemoveAt(f);
             f--;
         }
     }
     return(filenames);
 }
Пример #28
0
        public static List <string> getFieldNameListFromList <T>(string FieldNameToGet, List <T> elements) where T : DBTable
        {
            MPTVSeriesLog.Write("Elements found: " + elements.Count.ToString());
            List <string> results = new List <string>();

            foreach (T elem in elements)
            {
                try
                {
                    results.Add((string)elem[FieldNameToGet]);
                }
                catch (Exception)
                {
                    MPTVSeriesLog.Write("Wrong call of getPropertyListFromList<T,P>: Type " + elem.GetType().Name);
                }
            }
            return(results);
        }
Пример #29
0
        public static List <DBValue> GetSingleField(string field, SQLCondition conds, DBTable obj)
        {
            string         sql     = "select " + field + " from " + obj.m_tableName + conds + conds.orderString + conds.limitString;
            List <DBValue> results = new List <DBValue>();

            try
            {
                foreach (SQLiteResultSet.Row result in DBTVSeries.Execute(sql).Rows)
                {
                    results.Add(result.fields[0]);
                }
            }
            catch (Exception ex)
            {
                MPTVSeriesLog.Write("GetSingleField SQL method generated an error: " + ex.Message);
            }
            return(results);
        }
Пример #30
0
 public virtual DBValue this[String fieldName]
 {
     get
     {
         DBField result;
         if (!m_fields.TryGetValue(fieldName, out result))
         {
             return(string.Empty);
         }
         return(result.Value);
     }
     set
     {
         try
         {
             DBField result;
             if (m_fields.TryGetValue(fieldName, out result))
             {
                 if (result.Value != value)
                 {
                     if (result.Type == DBField.cTypeInt)
                     {
                         result.Value = (long)value;
                     }
                     else
                     {
                         result.Value = value;
                     }
                     result.WasChanged = true;
                     m_CommitNeeded    = true;
                 }
             }
             else
             {
                 AddColumn(fieldName, new DBField(DBField.cTypeString));
                 this[fieldName] = value;
             }
         }
         catch (SystemException)
         {
             MPTVSeriesLog.Write("Cast exception when trying to assign " + value + " to field " + fieldName + " in table " + m_tableName);
         }
     }
 }