diff --git a/mediaportal/Databases/Video/IVideoDatabase.cs b/mediaportal/Databases/Video/IVideoDatabase.cs index 5b34ce33637..f5c1ea9ee16 100644 --- a/mediaportal/Databases/Video/IVideoDatabase.cs +++ b/mediaportal/Databases/Video/IVideoDatabase.cs @@ -27,7 +27,7 @@ namespace MediaPortal.Video.Database public interface IVideoDatabase { void Dispose(); - + // Files & Path int AddFile(int lMovieId, int lPathId, string strFileName); int GetFile(string strFilenameAndPath, out int lPathId, out int lMovieId, bool bExact); @@ -38,7 +38,7 @@ public interface IVideoDatabase void RemoveFilesForMovie(int lMovieId); int GetFileId(string strFilenameAndPath); void GetFilesForMovie(int lMovieId, ref ArrayList movies); - + // Genre int AddGenre(string strGenre1); void GetGenres(ArrayList genres); @@ -48,7 +48,7 @@ public interface IVideoDatabase void RemoveGenresForMovie(int lMovieId); string GetGenresForMovie(int lMovieId); void GetMovieGenres(int lMovieId, ArrayList movieGenres); - + // Movie Collection int AddCollection(string strCollection1); int GetCollectionId(string movieCollection); @@ -65,7 +65,7 @@ public interface IVideoDatabase void GetMovieCollections(int lMovieId, ArrayList movieCollections); bool GetMovieCollectionWatchedStatus(string collection, out int percent); bool GetMovieCollectionWatchedStatus(int collection, out int percent); - + // User groups int AddUserGroup(string userGroup); void AddUserGroupDescription(string userGroup, string description); @@ -87,7 +87,7 @@ public interface IVideoDatabase bool GetUserGroupWatchedStatus(int group, out int percent); void UpdateUserGroupWithRule(int ID); void UpdateUserGroupWithRule(int ID, string suffix); - + // Actors int AddActor(string strActorImdbId, string strActorName); void GetActors(ArrayList actors); @@ -99,18 +99,18 @@ public interface IVideoDatabase void DeleteActorFromMovie(int movieId, int actorId); void DeleteActor(string actorImdbId); void RemoveActorsForMovie(int lMovieId); - + // Actor info void SetActorInfo(int idActor, IMDBActor actor); void AddActorInfoMovie(int idActor, IMDBActor.IMDBActorMovie movie); IMDBActor GetActorInfo(int idActor); string GetActorImdbId(int idActor); - + // Bookmarks void ClearBookMarksOfMovie(string strFilenameAndPath); void AddBookMarkToMovie(string strFilenameAndPath, float fTime); void GetBookMarksForMovie(string strFilenameAndPath, ref ArrayList bookmarks); - + // Movie info void SetMovieInfo(string strFilenameAndPath, ref IMDBMovie details); void SetMovieInfoById(int lMovieId, ref IMDBMovie details); @@ -126,7 +126,7 @@ public interface IVideoDatabase void SetMovieTitleById(int lMovieId, string lmovieTitle, out bool error, out string errorMessage); void SetMovieSortTitleById(int lMovieId, string lmovieTitle); void SetMovieSortTitleById(int lMovieId, string lmovieTitle, out bool error, out string errorMessage); - + // Stop time & duration void DeleteMovieStopTime(int iFileId); int GetMovieStopTime(int iFileId); @@ -137,14 +137,16 @@ public interface IVideoDatabase int GetMovieDuration(int iMovieId); void SetVideoDuration(int iFileId, int duration); void SetMovieDuration(int iMovieId, int duration); - + // Watched status void SetMovieWatchedStatus(int iFileId, bool watched, int percent); void MovieWatchedCountIncrease(int idMovie); void SetMovieWatchedCount(int movieId, int watchedCount); bool GetMovieWatchedStatus(int iFileId, out int percent, out int timesWatched); + void ResetWatchedForAllMoviesInFolder(string folderName); + void DeleteMovie(string strFilenameAndPath); - + // User Rating void SetUserRatingForMovie(int lMovieId, int lUserRating); int GetUserRatingForMovie(int lMovieId); @@ -157,10 +159,10 @@ public interface IVideoDatabase int GetTitleBDId(int iFileId, out byte[] resumeData); bool HasSubtitle(string strFilenameAndPath); void SetThumbURL(int lMovieId, string thumbURL); - + // Fanart void SetFanartURL(int lMovieId, string fanartURL); - + // Movies by filters void GetYears(ArrayList years); void GetMoviesByGenre(string strGenre1, ref ArrayList movies); @@ -205,7 +207,7 @@ public interface IVideoDatabase void SetDVDLabel(int lMovieId, string strDVDLabel1); void UpdateCDLabel(IMDBMovie movieDetails, string CDlabel); string GetDVDLabel(string strFile); - + // Blacklisted thumbs bool IsVideoThumbBlacklisted(string path); int VideoThumbBlacklist(string path, DateTime expiresOn); @@ -216,10 +218,10 @@ public interface IVideoDatabase // Search void SearchMoviesByView(string dbField, string dbValue, out ArrayList movies); void SearchActorsByView(string dbActor, out ArrayList movies, bool director); - + // Other SQLiteResultSet GetResults(string sql); - void ExecuteSQL (string sql, out bool error, out string errorMessage); + void ExecuteSQL(string sql, out bool error, out string errorMessage); ArrayList ExecuteRuleSQL(string sql, string fieldName, out bool error, out string errorMessage); string DatabaseName { get; } void GetVideoFilesMediaInfo(string strFilenameAndPath, ref VideoFilesMediaInfo mediaInfo, bool refresh); @@ -233,6 +235,6 @@ public interface IVideoDatabase void FlushTransactionsToDisk(); void RevertFlushTransactionsToDisk(); bool DbHealth { get; } - string DefaultVideoViewFields {get; } + string DefaultVideoViewFields { get; } } } \ No newline at end of file diff --git a/mediaportal/Databases/Video/SqlLite/VideoDatabaseSqlLite.cs b/mediaportal/Databases/Video/SqlLite/VideoDatabaseSqlLite.cs index b3c60bb60e3..c4d4c5e4494 100644 --- a/mediaportal/Databases/Video/SqlLite/VideoDatabaseSqlLite.cs +++ b/mediaportal/Databases/Video/SqlLite/VideoDatabaseSqlLite.cs @@ -1071,7 +1071,7 @@ private void CheckMediaInfo(string file, string fullPathFilename, int pathID, in path = DatabaseUtility.Get(results, 0, "strPath"); } - if (path.Contains("remote:")|| path.Contains("http:")) + if (path.Contains("remote:") || path.Contains("http:")) { return; } @@ -1306,7 +1306,7 @@ private VideoFilesMediaInfo GetVideoFilesMediaInfo(int movieId) int fileID = GetFileId(movieId); - if (fileID < 1 ) + if (fileID < 1) { return mediaInfo; } @@ -1429,12 +1429,12 @@ public void GetGenres(ArrayList genres) { genres.Clear(); SQLiteResultSet results = m_db.Execute("SELECT * FROM genre ORDER BY strGenre"); - + if (results.Rows.Count == 0) { return; } - + for (int iRow = 0; iRow < results.Rows.Count; iRow++) { genres.Add(DatabaseUtility.Get(results, iRow, "strGenre")); @@ -1460,7 +1460,7 @@ public string GetGenreById(int genreId) { string sql = string.Format("SELECT * FROM genre WHERE idGenre = {0}", genreId); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return string.Empty; @@ -1483,11 +1483,11 @@ public void AddGenreToMovie(int lMovieId, int lGenreId) { return; } - + string strSQL = String.Format("SELECT * FROM genrelinkmovie WHERE idGenre={0} AND idMovie={1}", lGenreId, lMovieId); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { // doesnt exists, add it @@ -1510,7 +1510,7 @@ public void DeleteGenre(string genre) DatabaseUtility.RemoveInvalidChars(ref genreFiltered); string sql = String.Format("SELECT * FROM genre WHERE strGenre LIKE '{0}'", genreFiltered); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return; @@ -1547,7 +1547,7 @@ public void RemoveGenresForMovie(int lMovieId) } } - public string GetGenresForMovie(int lMovieId) + public string GetGenresForMovie(int lMovieId) { if (m_db == null) { @@ -1564,7 +1564,7 @@ public string GetGenresForMovie(int lMovieId) return strGenre; } - public void GetMovieGenres(int lMovieId, ArrayList movieGenres) + public void GetMovieGenres(int lMovieId, ArrayList movieGenres) { if (m_db == null) { @@ -1576,7 +1576,7 @@ public void GetMovieGenres(int lMovieId, ArrayList movieGenres) movieGenres.Clear(); string sql = string.Format("SELECT * FROM genre WHERE idGenre IN (SELECT idGenre FROM genrelinkmovie WHERE idMovie={0})", lMovieId); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return; @@ -1761,12 +1761,12 @@ public void GetCollections(ArrayList collections) { collections.Clear(); SQLiteResultSet results = m_db.Execute("SELECT * FROM moviecollection ORDER BY strCollection"); - + if (results.Rows.Count == 0) { return; } - + for (int iRow = 0; iRow < results.Rows.Count; iRow++) { collections.Add(DatabaseUtility.Get(results, iRow, "strCollection")); @@ -1792,7 +1792,7 @@ public string GetCollectionById(int collectionId) { string sql = string.Format("SELECT * FROM moviecollection WHERE idCollection = {0}", collectionId); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return string.Empty; @@ -1809,16 +1809,16 @@ public string GetCollectionById(int collectionId) public void AddCollectionToMovie(int lMovieId, int lCollectionId) { - if (null == m_db) - { - return; - } - + if (null == m_db) + { + return; + } + try { string strSQL = String.Format("SELECT * FROM moviecollectionlinkmovie WHERE idCollection={0} AND idMovie={1}", lCollectionId, lMovieId); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { // doesnt exists, add it @@ -1846,7 +1846,7 @@ public void DeleteCollection(string collection) DatabaseUtility.RemoveInvalidChars(ref collectionFiltered); string sql = String.Format("SELECT * FROM moviecollection WHERE strCollection LIKE '{0}'", collectionFiltered); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return; @@ -1897,10 +1897,10 @@ public void DeleteEmptyCollections() public void RemoveCollectionFromMovie(int lMovieId, int lCollectionId) { - if (null == m_db) - { - return; - } + if (null == m_db) + { + return; + } try { @@ -1918,10 +1918,10 @@ public void RemoveCollectionFromMovie(int lMovieId, int lCollectionId) public void RemoveCollectionsForMovie(int lMovieId) { - if (null == m_db) - { - return; - } + if (null == m_db) + { + return; + } try { @@ -1935,7 +1935,7 @@ public void RemoveCollectionsForMovie(int lMovieId) } } - public string GetCollectionsForMovie(int lMovieId) + public string GetCollectionsForMovie(int lMovieId) { if (m_db == null) { @@ -1952,7 +1952,7 @@ public string GetCollectionsForMovie(int lMovieId) return strCollection; } - public void GetMovieCollections(int lMovieId, ArrayList movieCollections) + public void GetMovieCollections(int lMovieId, ArrayList movieCollections) { if (m_db == null) { @@ -1964,7 +1964,7 @@ public void GetMovieCollections(int lMovieId, ArrayList movieCollections) movieCollections.Clear(); string sql = string.Format("SELECT * FROM moviecollection WHERE idCollection IN (SELECT idCollection FROM moviecollectionlinkmovie WHERE idMovie={0})", lMovieId); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return; @@ -2013,13 +2013,13 @@ public bool GetMovieCollectionWatchedStatus(int collection, out int percent) string strSQL = String.Format("SELECT * FROM movieinfo WHERE idMovie IN (SELECT idMovie FROM moviecollectionlinkmovie WHERE idCollection={0}) AND iswatched>0", collection); SQLiteResultSet results = m_db.Execute(strSQL); int watched = results.Rows.Count; - + strSQL = String.Format("SELECT * FROM movieinfo WHERE idMovie IN (SELECT idMovie FROM moviecollectionlinkmovie WHERE idCollection={0})", collection); results = m_db.Execute(strSQL); int total = results.Rows.Count; - percent = (total > 0) ? Convert.ToInt32((watched*100)/total) : 0; - + percent = (total > 0) ? Convert.ToInt32((watched * 100) / total) : 0; + return (watched != 0); } catch (ThreadAbortException) @@ -2044,7 +2044,7 @@ public int AddUserGroup(string userGroup) { string strUserGroup = userGroup.Trim(); DatabaseUtility.RemoveInvalidChars(ref strUserGroup); - + if (null == m_db) { return -1; @@ -2052,11 +2052,11 @@ public int AddUserGroup(string userGroup) string strSQL = string.Format("SELECT * FROM usergroup WHERE strGroup like '{0}'", strUserGroup); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { // doesnt exists, add it - strSQL = string.Format("INSERT INTO usergroup (idGroup, strGroup, strRule, strGroupDescription) VALUES( NULL, '{0}', '', '')", strUserGroup); + strSQL = string.Format("INSERT INTO usergroup (idGroup, strGroup, strRule, strGroupDescription) VALUES( NULL, '{0}', '', '')", strUserGroup); m_db.Execute(strSQL); int groupId = m_db.LastInsertID(); return groupId; @@ -2191,7 +2191,7 @@ public void GetUserGroups(ArrayList userGroups) { userGroups.Clear(); SQLiteResultSet results = m_db.Execute("SELECT * FROM usergroup ORDER BY strGroup"); - + if (results.Rows.Count == 0) { return; @@ -2266,7 +2266,7 @@ public string GetUserGroupDescriptionById(int groupId) } return strGroup; } - + public string GetUserGroupsForMovie(int lMovieId) { if (m_db == null) @@ -2296,18 +2296,18 @@ public void GetMovieUserGroups(int movieId, ArrayList userGroups) userGroups.Clear(); string strSQL = String.Format("SELECT idGroup FROM usergrouplinkmovie WHERE idMovie={0}", movieId); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { return; } - + for (int iRow = 0; iRow < results.Rows.Count; iRow++) { int groupId = DatabaseUtility.GetAsInt(results, iRow, "idGroup"); strSQL = String.Format("SELECT strGroup FROM usergroup WHERE idGroup = {0}", groupId); SQLiteResultSet resultsGroup = m_db.Execute(strSQL); - + if (resultsGroup.Rows.Count > 0) { userGroups.Add(DatabaseUtility.Get(resultsGroup, 0, "strGroup")); @@ -2332,7 +2332,7 @@ public string GetUserGroupRule(string group) string strSQL = String.Format("SELECT strRule FROM usergroup WHERE strGroup like '{0}'", group); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count != 0) { return DatabaseUtility.Get(results, 0, "strRule"); @@ -2400,7 +2400,7 @@ public void DeleteUserGroup(string userGroup) DatabaseUtility.RemoveInvalidChars(ref userGroupFiltered); string sql = String.Format("SELECT * FROM usergroup WHERE strGroup like '{0}'", userGroupFiltered); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return; @@ -2492,8 +2492,8 @@ public bool GetUserGroupWatchedStatus(int group, out int percent) results = m_db.Execute(strSQL); int total = results.Rows.Count; - percent = (total > 0) ? Convert.ToInt32((watched*100)/total) : 0; - + percent = (total > 0) ? Convert.ToInt32((watched * 100) / total) : 0; + return (watched != 0); } catch (ThreadAbortException) @@ -2521,11 +2521,11 @@ public void UpdateUserGroupWithRule(int ID, string suffix) } if (suffix == null) - { + { suffix = string.Empty; } if (!string.IsNullOrEmpty(suffix)) - { + { suffix = " " + suffix; } @@ -2579,7 +2579,7 @@ public int AddActor(string strActorImdbId, string strActorName) { DatabaseUtility.RemoveInvalidChars(ref strActorImdbId); DatabaseUtility.RemoveInvalidChars(ref strActorName); - + if (null == m_db) { return -1; @@ -2601,12 +2601,12 @@ public int AddActor(string strActorImdbId, string strActorName) } SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { // doesnt exists, add it but check first if it exists without ImdbId int idActor = CheckActorByName(strActorName); - + if (idActor != -1) { strSQL = string.Format("UPDATE actors SET IMDBActorID='{0}', strActor = '{1}' WHERE idActor ={2}", @@ -2651,7 +2651,7 @@ public void GetActors(ArrayList actors) { actors.Clear(); SQLiteResultSet results = m_db.Execute("SELECT * FROM actors"); - + if (results.Rows.Count == 0) { return; @@ -2684,13 +2684,13 @@ public string GetActorNameById(int actorId) { string sql = string.Format("SELECT strActor FROM actors WHERE idActor = {0}", actorId); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return string.Empty; } - - strActor = DatabaseUtility.Get(results, 0, "strActor"); + + strActor = DatabaseUtility.Get(results, 0, "strActor"); } catch (Exception ex) { @@ -2712,16 +2712,16 @@ public void GetActorByName(string strActorName, ArrayList actors) { actors.Clear(); SQLiteResultSet results = m_db.Execute("SELECT * FROM actors WHERE strActor LIKE '%" + strActorName + "%'"); - + if (results.Rows.Count == 0) { return; } - + for (int iRow = 0; iRow < results.Rows.Count; iRow++) { actors.Add(DatabaseUtility.Get(results, iRow, "idActor") + "|" + - DatabaseUtility.Get(results, iRow, "strActor") + "|" + + DatabaseUtility.Get(results, iRow, "strActor") + "|" + DatabaseUtility.Get(results, iRow, "IMDBActorID")); } } @@ -2742,7 +2742,7 @@ private int CheckActorByName(string strActorName) try { SQLiteResultSet results = m_db.Execute("SELECT * FROM actors WHERE strActor LIKE '%" + strActorName + "%'"); - + if (results.Rows.Count == 0) { return -1; @@ -2770,19 +2770,19 @@ public void GetActorsByMovieID(int idMovie, ref ArrayList actorsByMovieID) { return; } - + string strSQL = String.Format( "SELECT actors.idActor, actors.strActor, actors.IMDBActorID, actorlinkmovie.strRole FROM actors INNER JOIN actorlinkmovie ON actors.idActor = actorlinkmovie.idActor WHERE actorlinkmovie.idMovie={0}", idMovie); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count != 0) { for (int i = 0; i < results.Rows.Count; ++i) { actorsByMovieID.Add(DatabaseUtility.Get(results, i, "actors.idActor") + "|" + - DatabaseUtility.Get(results, i, "actors.strActor") + "|" + + DatabaseUtility.Get(results, i, "actors.strActor") + "|" + DatabaseUtility.Get(results, i, "actors.IMDBActorID") + "|" + DatabaseUtility.Get(results, i, "actorlinkmovie.strRole")); } @@ -2809,7 +2809,7 @@ public void AddActorToMovie(int lMovieId, int lActorId, string role) string strSQL = String.Format("SELECT * FROM actorlinkmovie WHERE idActor={0} AND idMovie={1}", lActorId, lMovieId); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { // doesnt exists, add it @@ -2819,7 +2819,7 @@ public void AddActorToMovie(int lMovieId, int lActorId, string role) else { // exists, update it (role only) - strSQL = String.Format("UPDATE actorlinkmovie SET strRole = '{0}' WHERE idActor={1} AND idMovie={2}", role,lActorId, lMovieId); + strSQL = String.Format("UPDATE actorlinkmovie SET strRole = '{0}' WHERE idActor={1} AND idMovie={2}", role, lActorId, lMovieId); m_db.Execute(strSQL); } } @@ -2851,7 +2851,7 @@ public void DeleteActor(string actorImdbId) DatabaseUtility.RemoveInvalidChars(ref actorFiltered); string sql = String.Format("SELECT * FROM actors WHERE IMDBActorID='{0}'", actorFiltered); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return; @@ -2888,7 +2888,7 @@ public void RemoveActorsForMovie(int lMovieId) } } - public string GetRoleByMovieAndActorId (int lMovieId, int lActorId) + public string GetRoleByMovieAndActorId(int lMovieId, int lActorId) { try { @@ -2901,7 +2901,7 @@ public string GetRoleByMovieAndActorId (int lMovieId, int lActorId) String.Format( "SELECT strRole from actorlinkmovie WHERE idMovie={0} AND idActor={1}", lMovieId, lActorId); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count != 0) { return DatabaseUtility.Get(results, 0, "actorlinkmovie.strRole"); @@ -2915,7 +2915,7 @@ public string GetRoleByMovieAndActorId (int lMovieId, int lActorId) return string.Empty; } - #endregion + #endregion #region bookmarks @@ -2930,12 +2930,12 @@ public void ClearBookMarksOfMovie(string strFilenameAndPath) int lPathId, lMovieId; int lFileId = GetFile(strFilenameAndPath, out lPathId, out lMovieId, true); - + if (lFileId < 0) { return; } - + string strSQL = String.Format("DELETE FROM bookmark WHERE idFile={0}", lFileId); m_db.Execute(strSQL); } @@ -2952,20 +2952,20 @@ public void AddBookMarkToMovie(string strFilenameAndPath, float fTime) { int lPathId, lMovieId; int lFileId = GetFile(strFilenameAndPath, out lPathId, out lMovieId, true); - + if (lFileId < 0) { return; } - + if (null == m_db) { return; } - + string strSQL = String.Format("SELECT * FROM bookmark WHERE idFile={0} AND fPercentage='{1}'", lFileId, fTime); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count != 0) { return; @@ -2985,19 +2985,19 @@ public void AddBookMarkToMovie(string strFilenameAndPath, float fTime) public void GetBookMarksForMovie(string strFilenameAndPath, ref ArrayList bookmarks) { bookmarks.Clear(); - + try { int lPathId, lMovieId; int lFileId = GetFile(strFilenameAndPath, out lPathId, out lMovieId, true); - + if (lFileId < 0) { return; } - + bookmarks.Clear(); - + if (null == m_db) { return; @@ -3005,12 +3005,12 @@ public void GetBookMarksForMovie(string strFilenameAndPath, ref ArrayList bookma string strSQL = String.Format("SELECT * FROM bookmark WHERE idFile={0} ORDER BY fPercentage", lFileId); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { return; } - + for (int iRow = 0; iRow < results.Rows.Count; iRow++) { double fTime = Convert.ToDouble(DatabaseUtility.Get(results, iRow, "fPercentage")); @@ -3034,14 +3034,14 @@ public void SetMovieInfo(string strFilenameAndPath, ref IMDBMovie details) { return; } - + int lMovieId = GetMovie(strFilenameAndPath, true); - + if (lMovieId < 0) { return; } - + details.ID = lMovieId; SetMovieInfoById(lMovieId, ref details); string strPath, strFileName; @@ -3054,7 +3054,7 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details) { SetMovieInfoById(lMovieId, ref details, false); } - + public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTimeStamp) { try @@ -3073,19 +3073,19 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTim DatabaseUtility.RemoveInvalidChars(ref strLine); details1.Director = strLine; // add director Id - int lDirector = - 1; - + int lDirector = -1; + if (details1.DirectorID < 1 && !string.IsNullOrEmpty(details1.Director)) { lDirector = AddActor("", details1.Director); AddActorToMovie(details1.ID, lDirector, GUILocalizeStrings.Get(199).Replace(":", string.Empty)); - + if (!CheckMovieImdbId(details1.IMDBNumber)) { // Add actors from cast ArrayList vecActors = new ArrayList(); ArrayList vecRoles = new ArrayList(); - + if (details1.Cast != Strings.Unknown) { string castFix = details1.Cast.Replace("''", "'"); @@ -3097,7 +3097,7 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTim int pos = actors[i].IndexOf(" as "); string actor = actors[i]; string role = string.Empty; - + if (pos >= 0) { if (actor.Length >= pos + 4) @@ -3106,7 +3106,7 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTim } actor = actors[i].Substring(0, pos); } - + actor = actor.Trim(); role = role.Trim(); int lActorId = AddActor(string.Empty, actor); @@ -3114,7 +3114,7 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTim vecRoles.Add(role); } } - + for (int i = 0; i < vecActors.Count; i++) { AddActorToMovie(lMovieId, (int)vecActors[i], (string)vecRoles[i]); @@ -3239,12 +3239,12 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTim // add all genres string szGenres = details.Genre; ArrayList vecGenres = new ArrayList(); - + if (szGenres != Strings.Unknown) { if (szGenres.IndexOf("/") >= 0 || szGenres.IndexOf("|") >= 0) { - Tokens f = new Tokens(szGenres, new[] {'/', '|'}); + Tokens f = new Tokens(szGenres, new[] { '/', '|' }); foreach (string strGenre in f) { if (!string.IsNullOrEmpty(strGenre.Trim())) @@ -3262,7 +3262,7 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTim vecGenres.Add(lGenreId); } } - + for (int i = 0; i < vecGenres.Count; ++i) { AddGenreToMovie(lMovieId, (int)vecGenres[i]); @@ -3284,7 +3284,7 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTim // add all Collection string szCollections = details.MovieCollection; ArrayList vecCollections = new ArrayList(); - + if (szCollections != Strings.Unknown) { string[] f = szCollections.Split(new string[] { "/", "|" }, StringSplitOptions.RemoveEmptyEntries); @@ -3304,7 +3304,7 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTim DeleteEmptyCollections(); string strRating = String.Format("{0}", details1.Rating); - + if (strRating == "") { strRating = "0.0"; @@ -3313,7 +3313,7 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTim string strSQL = String.Format("SELECT * FROM movieinfo WHERE idmovie={0}", lMovieId); // Log.Error("dbs:{0}", strSQL); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { // Insert new movie info - no date watched update @@ -3326,16 +3326,16 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTim details1.Cast, details1.WritingCredits, details1.Year, details1.Genre, details1.ThumbURL, details1.Title, - details1.IMDBNumber, details1.MPARating, - details1.RunTime, details1.Watched, - details1.UserReview, details1.FanartURL, - details1.Director, details1.DateAdded, - details1.Studios, details1.Country, - details1.Language, details1.LastUpdate, - details1.SortTitle, - details1.TMDBNumber, details1.LocalDBNumber, - details1.UserRating, - details1.MPAAText, + details1.IMDBNumber, details1.MPARating, + details1.RunTime, details1.Watched, + details1.UserReview, details1.FanartURL, + details1.Director, details1.DateAdded, + details1.Studios, details1.Country, + details1.Language, details1.LastUpdate, + details1.SortTitle, + details1.TMDBNumber, details1.LocalDBNumber, + details1.UserRating, + details1.MPAAText, details1.MovieAwards); // Log.Error("dbs:{0}", strSQL); @@ -3357,21 +3357,21 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTim details1.ThumbURL, details1.Title, details1.IMDBNumber, details1.MPARating, details1.RunTime, - details1.Watched, details1.UserReview, - details1.FanartURL, details1.Director, - details1.DateWatched ,details1.Studios, - details1.Country, details1.Language, + details1.Watched, details1.UserReview, + details1.FanartURL, details1.Director, + details1.DateWatched, details1.Studios, + details1.Country, details1.Language, details1.LastUpdate, details1.SortTitle, details1.TMDBNumber, details1.LocalDBNumber, - details1.UserRating, - details1.MPAAText, - details1.MovieAwards, + details1.UserRating, + details1.MPAAText, + details1.MovieAwards, lMovieId); // Log.Error("dbs:{0}", strSQL); m_db.Execute(strSQL); } - + VideoDatabase.GetMovieInfoById(details1.ID, ref details1); } catch (Exception ex) @@ -3384,7 +3384,7 @@ public void SetMovieInfoById(int lMovieId, ref IMDBMovie details, bool updateTim public void DeleteMovieInfo(string strFileNameAndPath) { int lMovieId = GetMovie(strFileNameAndPath, false); - + if (lMovieId < 0) { return; @@ -3401,12 +3401,12 @@ public void DeleteMovieInfoById(long lMovieId) { return; } - + if (lMovieId == -1) { return; } - + Log.Info("Removing movie:{0}", lMovieId); // Delete movie file stop time data ArrayList files = new ArrayList(); @@ -3419,14 +3419,14 @@ public void DeleteMovieInfoById(long lMovieId) } IMDBMovie movie = new IMDBMovie(); - GetMovieInfoById((int) lMovieId, ref movie); + GetMovieInfoById((int)lMovieId, ref movie); // Delete movie cover - FanArt.DeleteCovers(movie.Title, (int) lMovieId); + FanArt.DeleteCovers(movie.Title, (int)lMovieId); // Delete movie fanart - FanArt.DeleteFanarts((int) lMovieId); + FanArt.DeleteFanarts((int)lMovieId); // Delete user groups for movie - RemoveUserGroupsForMovie((int) lMovieId); + RemoveUserGroupsForMovie((int)lMovieId); string strSQL = String.Format("DELETE FROM genrelinkmovie WHERE idmovie={0}", lMovieId); m_db.Execute(strSQL); @@ -3454,7 +3454,7 @@ public void DeleteMovieInfoById(long lMovieId) Log.Error("videodatabase exception err:{0} stack:{1}", ex.Message, ex.StackTrace); Open(); } - + DeleteEmptyCollections(); } @@ -3470,22 +3470,22 @@ public bool HasMovieInfo(string strFilenameAndPath) { return false; } - + int lMovieId = GetMovie(strFilenameAndPath, false); - + if (lMovieId < 0) { return false; } - + string strSQL = String.Format("SELECT * FROM movieinfo WHERE movieinfo.idmovie={0}", lMovieId); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { return false; } - + return true; } catch (ThreadAbortException) @@ -3503,7 +3503,7 @@ public bool HasMovieInfo(string strFilenameAndPath) public int GetMovieInfo(string strFilenameAndPath, ref IMDBMovie details) { int lMovieId = GetMovie(strFilenameAndPath, false); - + if (lMovieId < 0) { return -1; @@ -3513,7 +3513,7 @@ public int GetMovieInfo(string strFilenameAndPath, ref IMDBMovie details) { return -1; } - + GetMovieInfoById(lMovieId, ref details); return lMovieId; } @@ -3527,12 +3527,12 @@ public void GetMovieInfoById(int lMovieId, ref IMDBMovie details) "SELECT * FROM movieinfo,movie,path WHERE path.idpath=movie.idpath AND movie.idMovie=movieinfo.idMovie AND movieinfo.idmovie={0}", lMovieId); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { return; } - + SetMovieDetails(ref details, 0, results); } catch (ThreadAbortException) @@ -3554,13 +3554,13 @@ public void SetWatched(IMDBMovie details) { return; } - + if (details.ID < 0) { return; } - - string strSQL = String.Format("UPDATE movieinfo SET iswatched={0}, datewatched = '{1}' WHERE idMovie={2}", + + string strSQL = String.Format("UPDATE movieinfo SET iswatched={0}, datewatched = '{1}' WHERE idMovie={2}", details.Watched, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), details.ID); @@ -3581,7 +3581,7 @@ public void SetDateWatched(IMDBMovie details) { return; } - + if (details.ID < 0) { return; @@ -3592,7 +3592,7 @@ public void SetDateWatched(IMDBMovie details) details.DateWatched = "0001-01-01 00:00:00"; } - string strSQL = String.Format("UPDATE movieinfo SET dateWatched='{0}' WHERE idMovie={1}", + string strSQL = String.Format("UPDATE movieinfo SET dateWatched='{0}' WHERE idMovie={1}", details.DateWatched, details.ID); m_db.Execute(strSQL); @@ -3643,7 +3643,7 @@ public void SetMovieSortTitleById(int lMovieId, string lmovieTitle, out bool err { return; } - + string strSQL = string.Format("UPDATE movieinfo SET strSortTitle = '{0}' WHERE idMovie = {1}", lmovieTitle, lMovieId); VideoDatabase.ExecuteSql(strSQL, out error, out errorMessage); } @@ -3672,12 +3672,12 @@ public int GetMovieStopTime(int iFileId) { string sql = string.Format("SELECT * FROM resume WHERE idFile={0}", iFileId); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return 0; } - + return DatabaseUtility.GetAsInt(results, 0, "stoptime"); } catch (Exception ex) @@ -3694,7 +3694,7 @@ public void SetMovieStopTime(int iFileId, int stoptime) { string sql = String.Format("SELECT * FROM resume WHERE idFile={0}", iFileId); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { sql = String.Format("INSERT INTO resume (idResume,idFile,stoptime) VALUES(NULL,{0},{1})", @@ -3718,7 +3718,7 @@ public void SetMovieStopTime(int iFileId, int stoptime) private byte[] FromHexString(string s) { byte[] bytes = new byte[s.Length / 2]; - + for (int i = 0; i < bytes.Length; i++) { bytes[i] = byte.Parse(s.Substring(i * 2, 2), NumberStyles.HexNumber); @@ -3729,9 +3729,9 @@ private byte[] FromHexString(string s) private string ToHexString(byte[] bytes) { - char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] chars = new char[bytes.Length * 2]; - + for (int i = 0; i < bytes.Length; i++) { int b = bytes[i]; @@ -3763,7 +3763,7 @@ public int GetMovieStopTimeAndResumeData(int iFileId, out byte[] resumeData, int { int stoptime = DatabaseUtility.GetAsInt(results, 0, "stoptime"); string resumeString = DatabaseUtility.Get(results, 0, "resumeData"); - resumeData = new byte[resumeString.Length/2]; + resumeData = new byte[resumeString.Length / 2]; FromHexString(resumeString).CopyTo(resumeData, 0); return stoptime; } @@ -3865,12 +3865,12 @@ public int GetVideoDuration(int iFileId) { string sql = string.Format("SELECT * FROM duration WHERE idFile={0}", iFileId); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return 0; } - + return DatabaseUtility.GetAsInt(results, 0, "duration"); } catch (ThreadAbortException) @@ -3938,16 +3938,16 @@ public void SetMovieWatchedStatus(int idMovie, bool watched, int percent) { string sql = String.Format("SELECT * FROM movie WHERE idMovie={0}", idMovie); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count != 0) { int iWatched = 0; - + if (watched) { iWatched = 1; } - + sql = String.Format("UPDATE movie SET watched={0}, iwatchedPercent = {1} WHERE idMovie={2}", iWatched, percent, idMovie); } @@ -3987,13 +3987,13 @@ public void MovieWatchedCountIncrease(int idMovie) } } - public void SetMovieWatchedCount(int movieId , int watchedCount) + public void SetMovieWatchedCount(int movieId, int watchedCount) { try { string sql = String.Format("SELECT * FROM movie WHERE idMovie={0}", movieId); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count != 0) { sql = String.Format("UPDATE movie SET timeswatched = {0} WHERE idMovie={1}", @@ -4012,12 +4012,12 @@ public bool GetMovieWatchedStatus(int idMovie, out int percent, out int timesWat { percent = 0; timesWatched = 0; - + try { string sql = String.Format("SELECT * FROM movie WHERE idMovie={0}", idMovie); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return false; @@ -4026,7 +4026,7 @@ public bool GetMovieWatchedStatus(int idMovie, out int percent, out int timesWat int watched = DatabaseUtility.GetAsInt(results, 0, "watched"); percent = DatabaseUtility.GetAsInt(results, 0, "iwatchedPercent"); timesWatched = DatabaseUtility.GetAsInt(results, 0, "timeswatched"); - + if (watched != 0) { return true; @@ -4045,6 +4045,24 @@ public bool GetMovieWatchedStatus(int idMovie, out int percent, out int timesWat return false; } + public void ResetWatchedForAllMoviesInFolder(string folderName) + { + try + { + string sql = String.Format("UPDATE movie SET watched = 0 WHERE movie.idPath IN (SELECT idPath FROM path WHERE strPath='{0}' OR strPath LIKE '{0}\\%')", folderName); + m_db.Execute(sql); + } + catch (ThreadAbortException) + { + // Will be logged in thread main code + } + catch (Exception ex) + { + Log.Error("videodatabase exception err:{0} stack:{1}", ex.Message, ex.StackTrace); + Open(); + } + } + #endregion #region User Rating @@ -4057,12 +4075,12 @@ public void SetUserRatingForMovie(int lMovieId, int lUserRating) { return; } - + if (lMovieId < 0) { return; } - + string strSQL = String.Format("UPDATE movieinfo SET iUserRating={0} WHERE idMovie={1}", lUserRating, lMovieId); m_db.Execute(strSQL); } @@ -4082,15 +4100,15 @@ public int GetUserRatingForMovie(int lMovieId) { return userRating; } - + if (lMovieId < 0) { return userRating; } - + string sql = string.Format("SELECT iUserRating FROM movieinfo WHERE idMovie={0}", lMovieId); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return userRating; @@ -4106,7 +4124,7 @@ public int GetUserRatingForMovie(int lMovieId) return 0; } - public int GetUserRatingForMovie(string lIMDBNumber) + public int GetUserRatingForMovie(string lIMDBNumber) { int userRating = 0; try @@ -4115,7 +4133,7 @@ public int GetUserRatingForMovie(string lIMDBNumber) { return userRating; } - + if (string.IsNullOrEmpty(lIMDBNumber)) { return userRating; @@ -4125,10 +4143,10 @@ public int GetUserRatingForMovie(string lIMDBNumber) { return userRating; } - + string sql = string.Format("SELECT iUserRating FROM movieinfo WHERE IMDBID='{0}'", lIMDBNumber.Trim()); SQLiteResultSet results = m_db.Execute(sql); - + if (results.Rows.Count == 0) { return userRating; @@ -4160,7 +4178,7 @@ private void DeleteMoviesInFolder(string strPath) { SQLiteResultSet results = m_db.Execute("SELECT idPath,strPath FROM path WHERE strPath LIKE '" + strPath + "%'"); SortedDictionary pathList = new SortedDictionary(); - + for (int i = 0; i < results.Rows.Count; ++i) { pathList.Add(DatabaseUtility.Get(results, i, 0), DatabaseUtility.Get(results, i, 1)); @@ -4169,7 +4187,7 @@ private void DeleteMoviesInFolder(string strPath) foreach (KeyValuePair kvp in pathList) { results = m_db.Execute("SELECT strFilename FROM files WHERE idPath=" + kvp.Key); - + for (int j = 0; j < results.Rows.Count; ++j) { DeleteSingleMovie(kvp.Value + DatabaseUtility.Get(results, j, 0)); @@ -4199,13 +4217,13 @@ private void DeleteSingleMovie(string strFilenameAndPath) "SELECT * FROM path,files WHERE path.idPath=files.idPath AND files.idmovie={0} ORDER BY strFilename", lMovieId); SQLiteResultSet results = m_db.Execute(strSQL); - + for (int i = 0; i < results.Rows.Count; ++i) { int iFileId = DatabaseUtility.GetAsInt(results, i, "files.idFile"); DeleteFile(iFileId); } - + // Delete covers IMDBMovie movieDetails = new IMDBMovie(); GetMovieInfoById(lMovieId, ref movieDetails); @@ -4302,7 +4320,7 @@ private int GetMovie(string strFilenameAndPath, bool bExact) { return -1; } - + return lMovieId; } @@ -4311,7 +4329,7 @@ public void GetMovies(ref ArrayList movies) try { movies.Clear(); - + if (null == m_db) { return; @@ -4320,7 +4338,7 @@ public void GetMovies(ref ArrayList movies) string strSQL = String.Format( "SELECT * FROM movie,movieinfo,path WHERE movieinfo.idmovie=movie.idmovie AND movie.idpath=path.idpath"); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { return; @@ -4452,22 +4470,22 @@ public void GetYears(ArrayList years) { return; } - + try { years.Clear(); SQLiteResultSet results = m_db.Execute("SELECT * FROM movieinfo"); - + if (results.Rows.Count == 0) { return; } - + for (int iRow = 0; iRow < results.Rows.Count; iRow++) { string strYear = DatabaseUtility.Get(results, iRow, "iYear"); bool bAdd = true; - + for (int i = 0; i < years.Count; ++i) { if (strYear == (string)years[i]) @@ -4475,7 +4493,7 @@ public void GetYears(ArrayList years) bAdd = false; } } - + if (bAdd) { years.Add(strYear); @@ -4497,22 +4515,22 @@ public void GetMoviesByGenre(string strGenre1, ref ArrayList movies) string strGenre = strGenre1; DatabaseUtility.RemoveInvalidChars(ref strGenre); movies.Clear(); - + if (null == m_db) { return; } - + string strSQL = String.Format( "SELECT * FROM genrelinkmovie,genre,movie,movieinfo,path WHERE path.idpath=movie.idpath AND genrelinkmovie.idGenre=genre.idGenre AND genrelinkmovie.idmovie=movie.idmovie AND movieinfo.idmovie=movie.idmovie AND genre.strGenre='{0}' ORDER BY movieinfo.strTitle", strGenre); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { return; } - + for (int iRow = 0; iRow < results.Rows.Count; iRow++) { IMDBMovie details = new IMDBMovie(); @@ -4545,7 +4563,7 @@ public void GetRandomMoviesByGenre(string strGenre1, ref ArrayList movies, int l return; } - string strSQL = string.Format("SELECT DISTINCT {0} FROM movieView WHERE strSingleGenre = '{1}' {2} ORDER BY RANDOM() LIMIT {3}", + string strSQL = string.Format("SELECT DISTINCT {0} FROM movieView WHERE strSingleGenre = '{1}' {2} ORDER BY RANDOM() LIMIT {3}", _defaultVideoViewFields, strGenre, (!string.IsNullOrEmpty(whereClause) ? "AND " + whereClause : ""), limit); SQLiteResultSet results = m_db.Execute(strSQL); @@ -4587,7 +4605,7 @@ public string GetMovieTitlesByGenre(string strGenre, string whereClause) string strSQLGenre = strGenre; DatabaseUtility.RemoveInvalidChars(ref strSQLGenre); - string strSQL = string.Format("SELECT DISTINCT strTitle FROM movieView WHERE strSingleGenre = '{0}' {1} ORDER BY strTitle ASC", + string strSQL = string.Format("SELECT DISTINCT strTitle FROM movieView WHERE strSingleGenre = '{0}' {1} ORDER BY strTitle ASC", strSQLGenre, (!string.IsNullOrEmpty(whereClause) ? "AND " + whereClause : "")); SQLiteResultSet results = m_db.Execute(strSQL); @@ -4608,15 +4626,15 @@ public string GetMovieTitlesByGenre(string strGenre, string whereClause) } return titles; } - + public void GetMoviesByCollection(string strMovieCollection, ref ArrayList movies) + { + movies.Clear(); + + if (null == m_db) { - movies.Clear(); - - if (null == m_db) - { - return; - } + return; + } if (string.IsNullOrWhiteSpace(strMovieCollection)) { return; @@ -4626,17 +4644,17 @@ public void GetMoviesByCollection(string strMovieCollection, ref ArrayList movie { string strCollection = strMovieCollection.Trim(); DatabaseUtility.RemoveInvalidChars(ref strCollection); - + string strSQL = String.Format( "SELECT * FROM moviecollectionlinkmovie,moviecollection,movie,movieinfo,path WHERE path.idpath=movie.idpath AND moviecollectionlinkmovie.idCollection=moviecollection.idCollection AND moviecollectionlinkmovie.idmovie=movie.idmovie AND movieinfo.idmovie=movie.idmovie AND moviecollection.strCollection='{0}' ORDER BY movieinfo.strTitle", strCollection); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { return; } - + for (int iRow = 0; iRow < results.Rows.Count; iRow++) { IMDBMovie details = new IMDBMovie(); @@ -4657,13 +4675,13 @@ public void GetRandomMoviesByCollection(string strMovieCollection, ref ArrayList } public void GetRandomMoviesByCollection(string strMovieCollection, ref ArrayList movies, int limit, string whereClause) - { - movies.Clear(); + { + movies.Clear(); - if (null == m_db) - { - return; - } + if (null == m_db) + { + return; + } if (string.IsNullOrWhiteSpace(strMovieCollection)) { return; @@ -4752,7 +4770,7 @@ public string GetMovieTitlesByCollection(int idCollection, string whereClause) { return titles; } - if (idCollection < 0) + if (idCollection < 0) { return titles; } @@ -4785,22 +4803,22 @@ public void GetMoviesByUserGroup(string strUserGroup, ref ArrayList movies) { DatabaseUtility.RemoveInvalidChars(ref strUserGroup); movies.Clear(); - + if (null == m_db) { return; } - + string strSQL = String.Format( "SELECT * FROM usergrouplinkmovie,usergroup,movie,movieinfo,path WHERE path.idpath=movie.idpath AND usergrouplinkmovie.idGroup=usergroup.idGroup AND usergrouplinkmovie.idmovie=movie.idmovie AND movieinfo.idmovie=movie.idmovie AND usergroup.strGroup='{0}' ORDER BY movieinfo.strTitle ASC", strUserGroup); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { return; } - + for (int iRow = 0; iRow < results.Rows.Count; iRow++) { IMDBMovie details = new IMDBMovie(); @@ -4830,7 +4848,7 @@ public string GetMovieTitlesByUserGroup(int idGroup, string whereClause) { return titles; } - if (idGroup < 0) + if (idGroup < 0) { return titles; } @@ -4906,22 +4924,22 @@ public void GetMoviesByActor(string strActor1, ref ArrayList movies) string strActor = strActor1; DatabaseUtility.RemoveInvalidChars(ref strActor); movies.Clear(); - + if (null == m_db) { return; } - + string strSQL = String.Format( "SELECT * FROM actorlinkmovie,actors,movie,movieinfo,path WHERE path.idpath=movie.idpath AND actors.idActor=actorlinkmovie.idActor AND actorlinkmovie.idmovie=movie.idmovie AND movieinfo.idmovie=movie.idmovie AND actors.stractor='{0}' ORDER BY movieinfo.strTitle ASC", strActor); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { return; } - + for (int iRow = 0; iRow < results.Rows.Count; iRow++) { IMDBMovie details = new IMDBMovie(); @@ -5105,7 +5123,7 @@ public void GetMoviesByYear(string strYear, ref ArrayList movies) int iYear; Int32.TryParse(strYear, out iYear); movies.Clear(); - + if (null == m_db) { return; @@ -5115,12 +5133,12 @@ public void GetMoviesByYear(string strYear, ref ArrayList movies) iYear); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { return; } - + for (int iRow = 0; iRow < results.Rows.Count; iRow++) { IMDBMovie details = new IMDBMovie(); @@ -5380,7 +5398,7 @@ public void GetRandomMoviesByIndex(string strDBField, string strIndexValue, ref } string strSQL = string.Format("SELECT DISTINCT {0} FROM movieView WHERE {1} {2} ORDER BY RANDOM() LIMIT {3}", - _defaultVideoViewFields, where, (!string.IsNullOrEmpty(whereClause) ? "AND " + whereClause : ""), limit); + _defaultVideoViewFields, where, (!string.IsNullOrEmpty(whereClause) ? "AND " + whereClause : ""), limit); SQLiteResultSet results = m_db.Execute(strSQL); if (results.Rows.Count == 0) @@ -5472,7 +5490,7 @@ public void GetMoviesByFilter(string sql, out ArrayList movies, bool actorTable, bool genreTable, bool usergroupTable, bool collectionTable) { movies = new ArrayList(); - + try { if (null == m_db) @@ -5487,19 +5505,19 @@ public void GetMoviesByFilter(string sql, out ArrayList movies, bool actorTable, { movie = new IMDBMovie(); SQLiteResultSet.Row fields = results.Rows[i]; - + if (actorTable && !movieinfoTable) { movie.Actor = fields.fields[1]; movie.ActorID = (int)Math.Floor(0.5d + Double.Parse(fields.fields[0])); } - + if (genreTable && !movieinfoTable) { movie.SingleGenre = fields.fields[1]; movie.GenreID = (int)Math.Floor(0.5d + Double.Parse(fields.fields[0])); } - + if (collectionTable && !movieinfoTable) { int percent = 0; @@ -5508,7 +5526,7 @@ public void GetMoviesByFilter(string sql, out ArrayList movies, bool actorTable, movie.Watched = (GetMovieCollectionWatchedStatus(movie.SingleMovieCollection, out percent) ? 1 : 0); movie.WatchedPercent = percent; } - + if (usergroupTable && !movieinfoTable) { int percent = 0; @@ -5517,7 +5535,7 @@ public void GetMoviesByFilter(string sql, out ArrayList movies, bool actorTable, movie.Watched = (GetUserGroupWatchedStatus(movie.SingleUserGroup, out percent) ? 1 : 0); movie.WatchedPercent = percent; } - + if (movieinfoTable) { SetMovieDetails(ref movie, i, results); @@ -5607,7 +5625,7 @@ public string GetMovieTitlesByIndex(string sql) } SQLiteResultSet results = GetResults(sql); - + for (int i = 0; i < results.Rows.Count; i++) { SQLiteResultSet.Row fields = results.Rows[i]; @@ -5630,7 +5648,7 @@ public void UpdateCDLabel(IMDBMovie movieDetails, string CDlabel) { return; } - + try { string sql = String.Format("SELECT idPath FROM path WHERE cdlabel = '{0}'", movieDetails.CDLabel); @@ -5653,12 +5671,12 @@ public void UpdateCDLabel(IMDBMovie movieDetails, string CDlabel) public string GetDVDLabel(string strFile) { string cdlabel = string.Empty; - + if (Util.Utils.IsDVD(strFile)) { cdlabel = Util.Utils.GetDriveSerial(strFile); } - + return cdlabel; } @@ -5670,7 +5688,7 @@ public SQLiteResultSet GetResults(string sql) { return null; } - + SQLiteResultSet results = m_db.Execute(sql); return results; } @@ -5682,7 +5700,7 @@ public SQLiteResultSet GetResults(string sql) return null; } - + #endregion #region ActorInfo @@ -5695,17 +5713,17 @@ public void SetActorInfo(int idActor, IMDBActor actor) { return; } - + string strSQL = String.Format("SELECT * FROM actorinfo WHERE idActor ={0}", idActor); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { // doesnt exists, add it strSQL = String.Format( "INSERT INTO actorinfo (idActor , dateofbirth , placeofbirth , minibio , biography, thumbURL, IMDBActorID, dateofdeath , placeofdeath, lastupdate ) VALUES( {0},'{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')", - idActor, + idActor, DatabaseUtility.RemoveInvalidChars(actor.DateOfBirth), DatabaseUtility.RemoveInvalidChars(actor.PlaceOfBirth), DatabaseUtility.RemoveInvalidChars(actor.MiniBiography), @@ -5723,7 +5741,7 @@ public void SetActorInfo(int idActor, IMDBActor actor) strSQL = String.Format( "UPDATE actorinfo SET dateofbirth='{1}', placeofbirth='{2}', minibio='{3}', biography='{4}', thumbURL='{5}', IMDBActorID='{6}', dateofdeath='{7}', placeofdeath='{8}', lastupdate ='{9}' WHERE idActor={0}", - idActor, + idActor, DatabaseUtility.RemoveInvalidChars(actor.DateOfBirth), DatabaseUtility.RemoveInvalidChars(actor.PlaceOfBirth), DatabaseUtility.RemoveInvalidChars(actor.MiniBiography), @@ -5736,12 +5754,12 @@ public void SetActorInfo(int idActor, IMDBActor actor) m_db.Execute(strSQL); RemoveActorInfoMovie(idActor); } - + for (int i = 0; i < actor.Count; ++i) { AddActorInfoMovie(idActor, actor[i]); } - + return; } catch (Exception ex) @@ -5756,44 +5774,44 @@ public void AddActorInfoMovie(int idActor, IMDBActor.IMDBActorMovie movie) { string movieTitle = DatabaseUtility.RemoveInvalidChars(movie.MovieTitle); string movieRole = DatabaseUtility.RemoveInvalidChars(movie.Role); - + try { if (null == m_db) { return; } - + string strSQL = String.Format( "INSERT INTO actorinfomovies (idActor, idDirector , strPlotOutline , strPlot , strTagLine , strVotes , fRating ,strCast ,strCredits , iYear , strGenre , strPictureURL , strTitle , IMDBID , mpaa ,runtime , iswatched , role , iUserRating ) VALUES( {0}, {1}, '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', {9}, '{10}', '{11}', '{12}', '{13}', '{14}', {15}, {16}, '{17}', {18})", - idActor, - -1, + idActor, + -1, + "", + "", + "", + "", "", - "", - "", - "", "", "", - "", 1900, "", "", - "", - movie.MovieImdbID, - "", - -1, + "", + movie.MovieImdbID, + "", + -1, 0, - movieRole, + movieRole, 0); m_db.Execute(strSQL); - + // populate IMDB Movies if (CheckMovieImdbId(movie.MovieImdbID)) { strSQL = String.Format("SELECT * FROM IMDBMovies WHERE idIMDB='{0}'", movie.MovieImdbID); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { strSQL = String.Format("INSERT INTO IMDBMovies ( idIMDB, idTmdb, strPlot, strCast, strCredits, iYear, strGenre, strPictureURL, strTitle, mpaa) VALUES( '{0}' ,'{1}' ,'{2}' , '{3}' , '{4}' , {5} , '{6}' ,'{7}' ,'{8}' , '{9}')", @@ -5836,7 +5854,7 @@ public void RemoveActorInfoMovie(int actorId) { return; } - + string strSQL = String.Format("DELETE FROM actorinfomovies WHERE idActor={0}", actorId); m_db.Execute(strSQL); } @@ -5858,7 +5876,7 @@ public IMDBActor GetActorInfo(int idActor) string strSql = String.Format( "SELECT actorinfo.biography, actorinfo.dateofbirth, actorinfo.dateofdeath, actorinfo.minibio, actors.strActor, actorinfo.placeofbirth, actorinfo.placeofdeath, actorinfo.thumbURL, actorinfo.lastupdate, actors.IMDBActorID, actorinfo.idActor FROM actors,actorinfo WHERE actors.idActor=actorinfo.idActor AND actors.idActor ={0}", idActor); SQLiteResultSet results = m_db.Execute(strSql); - + if (results.Rows.Count != 0) { IMDBActor actor = new IMDBActor(); @@ -5876,7 +5894,7 @@ public IMDBActor GetActorInfo(int idActor) strSql = String.Format("SELECT * FROM actorinfomovies WHERE idActor ={0}", idActor); results = m_db.Execute(strSql); - + for (int i = 0; i < results.Rows.Count; ++i) { string imdbId = DatabaseUtility.Get(results, i, "IMDBID"); @@ -5886,7 +5904,7 @@ public IMDBActor GetActorInfo(int idActor) IMDBActor.IMDBActorMovie movie = new IMDBActor.IMDBActorMovie(); movie.ActorID = DatabaseUtility.GetAsInt(results, i, "idActor"); movie.Role = DatabaseUtility.Get(results, i, "role"); - + if (resultsImdb.Rows.Count != 0) { // Added IMDBid @@ -5924,7 +5942,7 @@ public string GetActorImdbId(int idActor) } string strSql = String.Format("SELECT actors.IMDBActorID FROM actors WHERE actors.idActor ={0}", idActor); SQLiteResultSet results = m_db.Execute(strSql); - + if (results.Rows.Count != 0) { return DatabaseUtility.Get(results, 0, "actors.IMDBActorID"); @@ -5950,9 +5968,9 @@ public bool IsVideoThumbBlacklisted(string path) { return false; } - + FileInfo fileInfo = null; - + try { fileInfo = new FileInfo(path); @@ -5974,7 +5992,7 @@ public bool IsVideoThumbBlacklisted(string path) "SELECT idVideoThumbBList FROM VideoThumbBList WHERE strPath = '{0}' AND strExpires > '{1:yyyyMMdd}' AND strFileDate = '{2:s}' AND strFileSize = '{3}'", path, DateTime.Now, fileInfo.LastWriteTimeUtc, fileInfo.Length); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count != 0) { return true; @@ -6016,7 +6034,7 @@ public int VideoThumbBlacklist(string path, DateTime expiresOn) DatabaseUtility.RemoveInvalidChars(ref path); string strSQL = String.Format("SELECT idVideoThumbBList FROM VideoThumbBList WHERE strPath = '{0}'", path); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count == 0) { // doesnt exists, add it @@ -6032,7 +6050,7 @@ public int VideoThumbBlacklist(string path, DateTime expiresOn) else { int id = DatabaseUtility.GetAsInt(results, 0, "idVideoThumbBList"); - + if (id != 0) { strSQL = @@ -6065,11 +6083,11 @@ public bool VideoThumbRemoveFromBlacklist(string path) DatabaseUtility.RemoveInvalidChars(ref path); string strSQL = String.Format("SELECT idVideoThumbBList FROM VideoThumbBList WHERE strPath = '{0}'", path); SQLiteResultSet results = m_db.Execute(strSQL); - + if (results.Rows.Count != 0) { int id = DatabaseUtility.GetAsInt(results, 0, "idVideoThumbBList"); - + if (id != 0) { strSQL = String.Format("DELETE FROM VideoThumbBList WHERE idVideoThumbBList={0}", id); @@ -6125,7 +6143,7 @@ public void RemoveAllVideoThumbBlacklistEntries() #endregion - public void ExecuteSQL (string strSql, out bool error, out string errorMessage) + public void ExecuteSQL(string strSql, out bool error, out string errorMessage) { error = false; errorMessage = string.Empty; @@ -6136,7 +6154,7 @@ public void ExecuteSQL (string strSql, out bool error, out string errorMessage) { return; } - + m_db.Execute(strSql); } catch (ThreadAbortException) @@ -6195,15 +6213,15 @@ public bool CheckMovieImdbId(string id) { return false; } - + // Final IMDBtt check Match ttNo = Regex.Match(id, @"tt[\d]{7,8}?", RegexOptions.IgnoreCase); - + if (!ttNo.Success) { return false; } - + return true; } @@ -6214,15 +6232,15 @@ public bool CheckActorImdbId(string id) { return false; } - + // Final IMDBtt check Match ttNo = Regex.Match(id, @"nm[\d]{7,8}?", RegexOptions.IgnoreCase); - + if (!ttNo.Success) { return false; } - + return true; } @@ -6282,7 +6300,7 @@ public void ImportNfoUsingVideoFile(string videoFile, bool skipExisting, bool re IMDBMovie movie = new IMDBMovie(); int id = GetMovieInfo(videoFile, ref movie); - + if (skipExisting && id > 0) { movie = null; @@ -6303,7 +6321,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) IMDBMovie movie = new IMDBMovie(); bool isMovieFolder = Util.Utils.IsFolderDedicatedMovieFolder(Path.GetFullPath(nfoFile)); bool useInternalNfoScraper = false; - + using (Profile.Settings xmlreader = new Profile.MPSettings()) { // Use only nfo scrapper @@ -6321,7 +6339,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) int id = -1; XmlNodeList movieList = doc.DocumentElement.SelectNodes("/movie"); - + if (movieList == null) { Log.Debug("Movie tag for nfo file:{0} not exist. Nfo skipped.", nfoFile); @@ -6334,7 +6352,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) string cast = string.Empty; string path = string.Empty; string nfofileName = string.Empty; - + #region nodes XmlNode nodeTitle = nodeMovie.SelectSingleNode("title"); @@ -6367,7 +6385,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) XmlNode nodeTMDBNumber = nodeMovie.SelectSingleNode("tmdb"); XmlNode nodeLocalDBNumber = nodeMovie.SelectSingleNode("localdb"); XmlNode nodeAwards = nodeMovie.SelectSingleNode("awards"); - + #endregion #region Moviefiles @@ -6431,7 +6449,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) VideoDatabase.AddFile(movieId, pathId, filename); return; } - catch(Exception ex) + catch (Exception ex) { Log.Error("Import nfo error-stack check for path {0} Error: {1}", path, ex.Message); return; @@ -6446,7 +6464,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) { string tmpFile = string.Empty; string tmpPath = string.Empty; - + // Read filename Util.Utils.Split(file, out tmpPath, out tmpFile); // Remove extension @@ -6454,7 +6472,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) // Remove stack endings (CD1...) Util.Utils.RemoveStackEndings(ref tmpFile); Util.Utils.RemoveStackEndings(ref nfofileName); - + // Check and add to vdb and get movieId if (tmpFile.Equals(nfofileName, StringComparison.InvariantCultureIgnoreCase)) { @@ -6494,7 +6512,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) #endregion #region Check for existing movie or refresh database only - + GetMovieInfoById(id, ref movie); if (skipExisting && !movie.IsEmpty || refreshdbOnly && movie.IsEmpty || id < 1) @@ -6511,7 +6529,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) #region Genre XmlNodeList genres = nodeMovie.SelectNodes("genre"); - + foreach (XmlNode nodeGenre in genres) { if (nodeGenre.InnerText != null) @@ -6542,7 +6560,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) } movie.Genre = genre; - + #endregion #region Credits (Writers) @@ -6557,7 +6575,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) #region DateAdded movie.DateAdded = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); - + #endregion #region Title @@ -6693,7 +6711,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) if (nodeDirectorImdb != null) { dirImdb = nodeDirectorImdb.InnerText; - + if (!CheckActorImdbId(dirImdb)) { dirImdb = string.Empty; @@ -6727,7 +6745,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) { movie.MPARating = "NR"; } - + // MPAA Text if (nodeMpaaText != null) { @@ -6737,9 +6755,9 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) { movie.MPAAText = string.Empty; } - + #endregion - + #region Plot/Short plot // Plot @@ -6781,8 +6799,8 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) double rating = 0; if (double.TryParse(nodeRating.InnerText.Replace(",", "."), NumberStyles.Float, CultureInfo.InvariantCulture, out rating)) { - movie.Rating = (float) rating; - + movie.Rating = (float)rating; + if (movie.Rating > 10.0f) { movie.Rating /= 10.0f; @@ -6806,7 +6824,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) if (nodeRatings != null) { - foreach(XmlNode singleRating in nodeRatings) + foreach (XmlNode singleRating in nodeRatings) { XmlAttribute attrName = singleRating.Attributes["name"]; XmlAttribute attrMax = singleRating.Attributes["max"]; @@ -6819,7 +6837,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) { name = attrName.Value; } - if (attrDefault != null && attrDefault.Value != null) + if (attrDefault != null && attrDefault.Value != null) { def = singleRating.Attributes["default"].Value == "true"; } @@ -6838,10 +6856,10 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) if (nValue != null && nValue.InnerText != null) { - if (double.TryParse(nValue.InnerText.Replace(",","."), NumberStyles.Float, CultureInfo.InvariantCulture, out rating)) + if (double.TryParse(nValue.InnerText.Replace(",", "."), NumberStyles.Float, CultureInfo.InvariantCulture, out rating)) { - movie.Rating = (float) rating; - + movie.Rating = (float)rating; + if (movie.Rating > 10.0f) { movie.Rating /= 10.0f; @@ -6870,7 +6888,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) int userrating = 0; if (int.TryParse(nodeUserRating.InnerText, out userrating)) { - movie.UserRating = (int) userrating; + movie.UserRating = (int)userrating; } } @@ -6898,7 +6916,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) Int32.TryParse(m.Groups["h"].Value, out hours); int minutes = 0; Int32.TryParse(m.Groups["m"].Value, out minutes); - hours = hours*60; + hours = hours * 60; minutes = hours + minutes; movie.RunTime = minutes; } @@ -6922,7 +6940,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) } #endregion - + #region Tagline // Tagline @@ -6978,7 +6996,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) watchedCount = 0; Int32.TryParse(nodePlayCount.InnerText, out watchedCount); SetMovieWatchedCount(movie.ID, watchedCount); - + if (watchedCount > 0 && movie.Watched == 0) { movie.Watched = 1; @@ -7104,7 +7122,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) temporaryFilename = Path.Combine(Path.GetTempPath(), temporaryFilename); Util.Utils.FileDelete(temporaryFilename); Util.Utils.DownLoadAndOverwriteCachedImage(imageUrl, temporaryFilename); - + if (File.Exists(temporaryFilename)) { if (Util.Picture.CreateThumbnail(temporaryFilename, largeCoverArtImage, (int)Thumbs.ThumbLargeResolution, @@ -7182,7 +7200,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) Util.Utils.FileDelete(largeCoverArt); Util.Utils.FileDelete(coverArt); } - + // Save cover thumbs if (!string.IsNullOrEmpty(movie.ThumbURL)) { @@ -7251,7 +7269,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) movie.ThumbURL = imdbSearch[0]; } } - + string largeCoverArt = Util.Utils.GetLargeCoverArtName(Thumbs.MovieTitle, titleExt); string coverArt = Util.Utils.GetCoverArtName(Thumbs.MovieTitle, titleExt); @@ -7289,14 +7307,14 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) if (fanartNode != null && fanartNode.InnerText != null) { faFile = path + @"\" + fanartNode.InnerText; - + if (File.Exists(faFile)) { fa.GetLocalFanart(id, "file://" + faFile, faIndex); movie.FanartURL = faFile; faFound = true; } - faIndex ++; + faIndex++; } if (faIndex == 5) @@ -7307,13 +7325,13 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) if (!faFound) { - List localFanart = new List(); + List localFanart = new List(); faIndex = 0; faFile = path + @"\" + nfofileName + "-fanart.jpg"; localFanart.Add(faFile); faFile = path + @"\" + nfofileName + "-backdrop.jpg"; localFanart.Add(faFile); - faFile= path + @"\" + "backdrop.jpg"; + faFile = path + @"\" + "backdrop.jpg"; localFanart.Add(faFile); faFile = path + @"\" + "fanart.jpg"; localFanart.Add(faFile); @@ -7328,7 +7346,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) break; } } - + if (!faFound && !useInternalNfoScraper) { fa.GetTmdbFanartByApi(movie.ID, movie.IMDBNumber, string.Empty, false, 1, string.Empty); @@ -7341,7 +7359,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) // Cast parse XmlNodeList actorsList = nodeMovie.SelectNodes("actor"); - + foreach (XmlNode nodeActor in actorsList) { string name = string.Empty; @@ -7357,7 +7375,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) XmlNode nodeActorDeathDate = nodeActor.SelectSingleNode("deathdate"); XmlNode nodeActorDeathPlace = nodeActor.SelectSingleNode("deathplace"); XmlNode nodeActorMiniBio = nodeActor.SelectSingleNode("minibiography"); - XmlNode nodeActorBiography= nodeActor.SelectSingleNode("biography"); + XmlNode nodeActorBiography = nodeActor.SelectSingleNode("biography"); XmlNode nodeActorThumbnail = nodeActor.SelectSingleNode("thumb"); if (nodeActorName != null && nodeActorName.InnerText != null) @@ -7388,14 +7406,14 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) cast += line; int actId = VideoDatabase.AddActor(actorImdbId, name); - + VideoDatabase.AddActorToMovie(id, actId, role); if (CheckActorImdbId(actorImdbId)) { IMDBActor info = new IMDBActor(); info.IMDBActorID = actorImdbId; - + if (nodeActorBirthDate != null) { info.DateOfBirth = nodeActorBirthDate.InnerText; @@ -7420,9 +7438,9 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) { info.Biography = nodeActorBiography.InnerText; } - - if (info.DateOfBirth != string.Empty || - info.PlaceOfBirth != string.Empty|| + + if (info.DateOfBirth != string.Empty || + info.PlaceOfBirth != string.Empty || info.DateOfDeath != string.Empty || info.PlaceOfBirth != string.Empty || info.MiniBiography != string.Empty || @@ -7439,7 +7457,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) #endregion #region UserGroups / Movie Collections / Sets - + movie.MovieCollection = string.Empty; XmlNode movieCollection = nodeMovie.SelectSingleNode("set"); if (movieCollection != null) @@ -7456,7 +7474,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) else // Kodi 19 - -> Movie Collections { XmlNodeList movieCollectionList = nodeMovie.SelectNodes("set"); - + foreach (XmlNode nodeCollection in movieCollectionList) { string name = string.Empty; @@ -7488,12 +7506,12 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) } } } - + XmlNodeList userGroups = nodeMovie.SelectNodes("usergroup"); if (userGroups != null) { - foreach (XmlNode nodeUserGroup in userGroups) - { + foreach (XmlNode nodeUserGroup in userGroups) + { string name = string.Empty; string description = string.Empty; string rule = string.Empty; @@ -7524,7 +7542,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) image = nodeSetImage.InnerText; image = string.Format("{0}/{1}", path, image); } - + if (!string.IsNullOrEmpty(name)) { int iUserGroup = AddUserGroup(name); @@ -7560,9 +7578,9 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) Util.Utils.FileDelete(smallThumb); Util.Utils.FileDelete(largeThumb); - if (Util.Picture.CreateThumbnail(image, smallThumb, (int) Thumbs.ThumbResolution, (int) Thumbs.ThumbResolution, 0, Thumbs.SpeedThumbsSmall)) + if (Util.Picture.CreateThumbnail(image, smallThumb, (int)Thumbs.ThumbResolution, (int)Thumbs.ThumbResolution, 0, Thumbs.SpeedThumbsSmall)) { - Util.Picture.CreateThumbnail(image, largeThumb, (int) Thumbs.ThumbLargeResolution, (int) Thumbs.ThumbLargeResolution, 0, Thumbs.SpeedThumbsLarge); + Util.Picture.CreateThumbnail(image, largeThumb, (int)Thumbs.ThumbLargeResolution, (int)Thumbs.ThumbLargeResolution, 0, Thumbs.SpeedThumbsLarge); } } } @@ -7584,7 +7602,7 @@ public void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOnly) } } - public bool MakeNfo (int movieId) + public bool MakeNfo(int movieId) { string moviePath = string.Empty; string movieFile = string.Empty; @@ -7730,20 +7748,20 @@ public bool MakeNfo (int movieId) // Ratings / Kodi 19 subNode = doc.CreateElement("ratings"); - CreateXmlNode(subNode, doc, "rating", - new Dictionary() {{"name", "imdb"}, {"default","true"}}, - new Dictionary() {{"value", movieDetails.Rating.ToString().Replace(",", ".")}, {"votes", movieDetails.Votes}}); + CreateXmlNode(subNode, doc, "rating", + new Dictionary() { { "name", "imdb" }, { "default", "true" } }, + new Dictionary() { { "value", movieDetails.Rating.ToString().Replace(",", ".") }, { "votes", movieDetails.Votes } }); mainNode.AppendChild(subNode); // Unique ID / Kodi 19 - CreateXmlNode(mainNode, doc, "uniquid", movieDetails.IMDBNumber, new Dictionary() {{"type", "imdb"}}); - if (!string.IsNullOrEmpty(movieDetails.TMDBNumber)) - { - CreateXmlNode(mainNode, doc, "uniquid", movieDetails.TMDBNumber, new Dictionary() {{"type", "tmdb"}}); - } - if (!string.IsNullOrEmpty(movieDetails.LocalDBNumber)) - { - CreateXmlNode(mainNode, doc, "uniquid", movieDetails.LocalDBNumber, new Dictionary() {{"type", "local"}}); + CreateXmlNode(mainNode, doc, "uniquid", movieDetails.IMDBNumber, new Dictionary() { { "type", "imdb" } }); + if (!string.IsNullOrEmpty(movieDetails.TMDBNumber)) + { + CreateXmlNode(mainNode, doc, "uniquid", movieDetails.TMDBNumber, new Dictionary() { { "type", "tmdb" } }); + } + if (!string.IsNullOrEmpty(movieDetails.LocalDBNumber)) + { + CreateXmlNode(mainNode, doc, "uniquid", movieDetails.LocalDBNumber, new Dictionary() { { "type", "local" } }); } // Poster @@ -7757,7 +7775,7 @@ public bool MakeNfo (int movieId) { File.Copy(largeCoverArtImage, coverFilename, true); File.SetAttributes(coverFilename, FileAttributes.Normal); - CreateXmlNode(mainNode, doc, "thumb", movieFile + ".jpg", new Dictionary() {{"aspect", "poster"}}); + CreateXmlNode(mainNode, doc, "thumb", movieFile + ".jpg", new Dictionary() { { "aspect", "poster" } }); } catch (Exception ex) { @@ -7802,7 +7820,7 @@ public bool MakeNfo (int movieId) if (szGenres.IndexOf("/") >= 0 || szGenres.IndexOf("|") >= 0) { - Tokens f = new Tokens(szGenres, new[] {'/', '|'}); + Tokens f = new Tokens(szGenres, new[] { '/', '|' }); foreach (string strGenre in f) { @@ -7826,7 +7844,7 @@ public bool MakeNfo (int movieId) IMDBActor actorInfo = new IMDBActor(); subNode = doc.CreateElement("actor"); - char[] splitter = {'|'}; + char[] splitter = { '|' }; string[] temp = actor.Split(splitter); actorInfo = GetActorInfo(Convert.ToInt32(temp[0])); @@ -7851,7 +7869,7 @@ public bool MakeNfo (int movieId) // Movie Collections ArrayList movieCollections = new ArrayList(); GetMovieCollections(movieId, movieCollections); - + if (movieCollections.Count > 0) { foreach (string movieCollection in movieCollections) @@ -7873,7 +7891,7 @@ public bool MakeNfo (int movieId) // User groups ArrayList userGroups = new ArrayList(); GetMovieUserGroups(movieId, userGroups); - + if (userGroups.Count > 0) { foreach (string userGroup in userGroups) @@ -7913,9 +7931,9 @@ public bool MakeNfo (int movieId) fileCounter++; } } - catch(Exception ex) + catch (Exception ex) { - Log.Info("VideoDatabase: Error in creating nfo file:{0} Error:{1}", nfoFile ,ex.Message); + Log.Info("VideoDatabase: Error in creating nfo file:{0} Error:{1}", nfoFile, ex.Message); return false; } @@ -7929,33 +7947,33 @@ private void CreateXmlNode(XmlNode mainNode, XmlDocument doc, string element, st mainNode.AppendChild(subNode); } - private void CreateXmlNode(XmlNode mainNode, XmlDocument doc, string element, Dictionary attributes, Dictionary nodes) + private void CreateXmlNode(XmlNode mainNode, XmlDocument doc, string element, Dictionary attributes, Dictionary nodes) { XmlNode subNode = doc.CreateElement(element); - foreach(var pair in attributes) - { + foreach (var pair in attributes) + { XmlAttribute attr = doc.CreateAttribute(pair.Key); attr.Value = pair.Value; subNode.Attributes.Append(attr); } - foreach(var pair in nodes) - { - CreateXmlNode(subNode, doc, pair.Key, pair.Value); + foreach (var pair in nodes) + { + CreateXmlNode(subNode, doc, pair.Key, pair.Value); } - mainNode.AppendChild(subNode); + mainNode.AppendChild(subNode); } - private void CreateXmlNode(XmlNode mainNode, XmlDocument doc, string element, string innerTxt, Dictionary attributes) + private void CreateXmlNode(XmlNode mainNode, XmlDocument doc, string element, string innerTxt, Dictionary attributes) { XmlNode subNode = doc.CreateElement(element); subNode.InnerText = innerTxt; - foreach(var pair in attributes) - { + foreach (var pair in attributes) + { XmlAttribute attr = doc.CreateAttribute(pair.Key); attr.Value = pair.Value; subNode.Attributes.Append(attr); } - mainNode.AppendChild(subNode); + mainNode.AppendChild(subNode); } private void CreateCovers(string titleExt, string coverImage, IMDBMovie movie) @@ -7984,7 +8002,7 @@ public void GetVideoFiles(string path, ref ArrayList availableFiles) VirtualDirectory dir = new VirtualDirectory(); dir.SetExtensions(Util.Utils.VideoExtensions); ArrayList imagePath = new ArrayList(); - + // Thumbs creation spam no1 causing this call // // Temporary disable thumbcreation @@ -7996,7 +8014,7 @@ public void GetVideoFiles(string path, ref ArrayList availableFiles) } List items = dir.GetDirectoryUnProtectedExt(path, true, false); - + foreach (GUIListItem item in items) { if (item.IsFolder) @@ -8067,7 +8085,7 @@ private void SetLatestMovieProperties() string strSQL = "SELECT * FROM movieinfo ORDER BY dateAdded DESC LIMIT 3"; ArrayList movies = new ArrayList(); GetMoviesByFilter(strSQL, out movies, false, true, false, false, false); - + IMDBMovie movie1 = new IMDBMovie(); IMDBMovie movie2 = new IMDBMovie(); IMDBMovie movie3 = new IMDBMovie(); @@ -8078,7 +8096,7 @@ private void SetLatestMovieProperties() if (movies.Count > 0) { - movie1 = (IMDBMovie) movies[0]; + movie1 = (IMDBMovie)movies[0]; // Movie 1 GUIPropertyManager.SetProperty("#myvideos.latest1.genre", movie1.Genre.Replace(" /", ",")); // @@ -8102,7 +8120,7 @@ private void SetLatestMovieProperties() if (movies.Count > 1) { - movie2 = (IMDBMovie) movies[1]; + movie2 = (IMDBMovie)movies[1]; // Movie 2 GUIPropertyManager.SetProperty("#myvideos.latest2.genre", movie2.Genre.Replace(" /", ",")); // @@ -8126,7 +8144,7 @@ private void SetLatestMovieProperties() if (movies.Count > 2) { - movie3 = (IMDBMovie) movies[2]; + movie3 = (IMDBMovie)movies[2]; // Movie 3 GUIPropertyManager.SetProperty("#myvideos.latest3.genre", movie3.Genre.Replace(" /", ",")); // @@ -8190,7 +8208,7 @@ private void SetMovieDetails(ref IMDBMovie details, int iRow, SQLiteResultSet re Log.Error("VideoDatabaseSqLite:SetMovieDetails: {0}", ex.Message); details.DirectorID = -1; } - + details.WritingCredits = DatabaseUtility.Get(results, iRow, "movieinfo.strCredits").Replace("''", "'"); details.TagLine = DatabaseUtility.Get(results, iRow, "movieinfo.strTagLine").Replace("''", "'"); details.PlotOutline = DatabaseUtility.Get(results, iRow, "movieinfo.strPlotOutline").Replace("''", "'"); @@ -8265,7 +8283,7 @@ private void SetMovieDetails(ref IMDBMovie details, int iRow, SQLiteResultSet re if (files.Count > 0) { - movieFilename = (string) files[0]; + movieFilename = (string)files[0]; } details.VideoFileName = movieFilename; diff --git a/mediaportal/Databases/Video/VideoDatabase.cs b/mediaportal/Databases/Video/VideoDatabase.cs index 0c2d146ee3b..e0ddcb8e86b 100644 --- a/mediaportal/Databases/Video/VideoDatabase.cs +++ b/mediaportal/Databases/Video/VideoDatabase.cs @@ -170,12 +170,12 @@ public static void RemoveGenresForMovie(int lMovieId) _database.RemoveGenresForMovie(lMovieId); } - public static string GetGenresForMovie(int lMovieId) + public static string GetGenresForMovie(int lMovieId) { return _database.GetGenresForMovie(lMovieId); } - public static void GetMovieGenres(int lMovieId, ArrayList movieGenres) + public static void GetMovieGenres(int lMovieId, ArrayList movieGenres) { _database.GetMovieGenres(lMovieId, movieGenres); } @@ -189,15 +189,15 @@ public static int AddCollection(string strCollection1) } public static int GetCollectionId(string movieCollection) - { + { return _database.GetCollectionId(movieCollection); } public static void AddCollectionDescription(string movieCollection, string description) { _database.AddCollectionDescription(movieCollection, description); - } - + } + public static string GetCollectionDescriptionById(int collectionId) { return _database.GetCollectionDescriptionById(collectionId); @@ -238,12 +238,12 @@ public static void RemoveCollectionsForMovie(int lMovieId) _database.RemoveCollectionsForMovie(lMovieId); } - public static string GetCollectionsForMovie(int lMovieId) + public static string GetCollectionsForMovie(int lMovieId) { return _database.GetCollectionsForMovie(lMovieId); } - public static void GetMovieCollections(int lMovieId, ArrayList movieCollections) + public static void GetMovieCollections(int lMovieId, ArrayList movieCollections) { _database.GetMovieCollections(lMovieId, movieCollections); } @@ -275,7 +275,7 @@ public static void AddUserGroupDescription(string userGroup, string description) { _database.AddUserGroupDescription(userGroup, description); } - + public static void GetUserGroups(ArrayList userGroups) { _database.GetUserGroups(userGroups); @@ -290,7 +290,7 @@ public static string GetUserGroupDescriptionById(int groupId) { return _database.GetUserGroupDescriptionById(groupId); } - + public static string GetUserGroupsForMovie(int lMovieId) { return _database.GetUserGroupsForMovie(lMovieId); @@ -300,7 +300,7 @@ public static void GetMovieUserGroups(int movieId, ArrayList userGroups) { _database.GetMovieUserGroups(movieId, userGroups); } - + public static void AddUserGroupToMovie(int lMovieId, int lUserGroupId) { _database.AddUserGroupToMovie(lMovieId, lUserGroupId); @@ -400,7 +400,7 @@ public static void DeleteActorFromMovie(int movieId, int actorId) _database.DeleteActorFromMovie(movieId, actorId); } - public static string GetRoleByMovieAndActorId (int lMovieId, int lActorId) + public static string GetRoleByMovieAndActorId(int lMovieId, int lActorId) { return _database.GetRoleByMovieAndActorId(lMovieId, lActorId); } @@ -573,6 +573,11 @@ public static bool GetmovieWatchedStatus(int iMovieId, out int percent, out int return _database.GetMovieWatchedStatus(iMovieId, out percent, out timesWatched); } + public static void ResetWatchedForAllMoviesInFolder(string folderName) + { + _database.ResetWatchedForAllMoviesInFolder(folderName); + } + #endregion #region User Rating @@ -944,7 +949,7 @@ public static void ImportNfo(string nfoFile, bool skipExisting, bool refreshdbOn _database.ImportNfo(nfoFile, skipExisting, refreshdbOnly); } - public static bool MakeNfo (int movieId) + public static bool MakeNfo(int movieId) { return _database.MakeNfo(movieId); } @@ -1004,7 +1009,7 @@ public static bool CheckActorImdbId(string id) { return _database.CheckActorImdbId(id); } - + /// /// Returns all video files from path (for files with videoextension defined in MP) /// diff --git a/mediaportal/WindowPlugins/GUIVideos/GUIVideoFiles.cs b/mediaportal/WindowPlugins/GUIVideos/GUIVideoFiles.cs index 57ec55e7a47..446469a84ec 100644 --- a/mediaportal/WindowPlugins/GUIVideos/GUIVideoFiles.cs +++ b/mediaportal/WindowPlugins/GUIVideos/GUIVideoFiles.cs @@ -1,5793 +1,5808 @@ -#region Copyright (C) 2005-2023 Team MediaPortal - -// Copyright (C) 2005-2023 Team MediaPortal -// http://www.team-mediaportal.com -// -// MediaPortal is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 2 of the License, or -// (at your option) any later version. -// -// MediaPortal is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with MediaPortal. If not, see . - -#endregion - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Xml; -using System.Xml.Serialization; -using CSScriptLibrary; -using Common.GUIPlugins; -using MediaPortal.Configuration; -using MediaPortal.Database; -using MediaPortal.Dialogs; -using MediaPortal.GUI.Library; -using MediaPortal.GUI.View; -using MediaPortal.Player; -using MediaPortal.Playlists; -using MediaPortal.Services; -using MediaPortal.Util; -using MediaPortal.Video.Database; -using MediaPortal.Player.Subtitles; -using MediaPortal.Profile; -using Action = MediaPortal.GUI.Library.Action; -using Layout = MediaPortal.GUI.Library.GUIFacadeControl.Layout; - -#pragma warning disable 108 - -namespace MediaPortal.GUI.Video -{ - internal class ComboBoxItemDatabase - { - public string Database; - public string Name; - public string Language; - public string Limit; - - public override string ToString() - { - return String.Format("{0}: {1} [{2}]", Language, Name, Database); - } - } - - /// - /// MyVideo GUI class when not using DB driven views. - /// - [PluginIcons("GUIVideos.Video.gif", "GUIVideos.VideoDisabled.gif")] - public class GUIVideoFiles : GUIVideoBaseWindow, ISetupForm, IShowPlugin, IMDB.IProgress - { - #region map settings - - [Serializable] - public class MapSettings - { - protected int _SortBy; - protected int _ViewAs; - protected bool _Stack; - protected bool _SortAscending; - - public MapSettings() - { - _SortBy = 0; //name - _ViewAs = 0; //list - _Stack = true; - _SortAscending = true; - } - - [XmlElement("SortBy")] - public int SortBy - { - get { return _SortBy; } - set { _SortBy = value; } - } - - [XmlElement("ViewAs")] - public int ViewAs - { - get { return _ViewAs; } - set { _ViewAs = value; } - } - - [XmlElement("Stack")] - public bool Stack - { - get { return _Stack; } - set { _Stack = value; } - } - - [XmlElement("SortAscending")] - public bool SortAscending - { - get { return _SortAscending; } - set { _SortAscending = value; } - } - } - - #endregion - - #region variables - - public static int _getMediaInfoThreadNumber = 0; - public static Thread _getMediaInfoThread; - private static bool _getMediaInfoThreadAbort = false; - private Thread _refreshMediaInfoThread; - private static bool _refreshMediaInfoThreadAbort = false; - private static bool _askBeforePlayingDVDImage; - private static VirtualDirectory _virtualDirectory; - private static string _currentFolder = string.Empty; - private static PlayListPlayer _playlistPlayer; - private static PlayListType _currentPlaylistType; - private static int _currentPlaylistIndex = -1; - private static Thread _removableDrivesHandlerThread; - private VideoFolderWatcherHelper _videoFolderWatcher; - private MapSettings _mapSettings = new MapSettings(); - private DirectoryHistory _history = new DirectoryHistory(); - private string _virtualStartDirectory = string.Empty; - private int _currentSelectedItem = -1; - - // File menu - private string _fileMenuDestinationDir = string.Empty; - private bool _fileMenuEnabled; - private string _fileMenuPinCode = string.Empty; - - private bool _addVideoFilesToDb; // add automatically video files to database for show video duration in list view - private bool _scanning; - private int _scanningFileNumber = 1; - private int _scanningFileTotal = 1; - private bool _isFuzzyMatching; - private bool _scanSkipExisting; - private bool _getActors = true; - private bool _markWatchedFiles = true; - private bool _hideWatchedFiles = false; - private ArrayList _conflictFiles = new ArrayList(); - private bool _switchRemovableDrives; - // Stacked files duration - for watched status/also used in GUIVideoTitle - public static int TotalMovieDuration; - public static ArrayList StackedMovieFiles = new ArrayList(); - public static bool IsStacked; - - private List _cachedItems = new List(); - private string _cachedDir; - - private bool _resetSMSsearch; - private bool _oldStateSMSsearch; - private DateTime _resetSMSsearchDelay; - - private int _howToPlayAll = 3; - //Video info in share view before play - private bool _videoInfoInShare; - private bool _playClicked; - - // external player - private static bool _useInternalVideoPlayer = true; - private static bool _useInternalDVDVideoPlayer = true; - private static string _externalPlayerExtensions = string.Empty; - - private int _watchedPercentage = 95; - public static GUIListItem CurrentSelectedGUIItem; - - private Thread _setThumbs; - private List _threadGUIItems = new List(); - private ISelectDVDHandler _threadISelectDVDHandler; - private bool _setThumbsThreadAborted; - - // grabber index holds information/urls of available grabbers to download - private static string _grabberIndexFile = Config.GetFile(Config.Dir.Config, "MovieInfoGrabber.xml"); - private static string _grabberIndexUrl = @"http://install.team-mediaportal.com/MP1/MovieInfoGrabber_V16.xml"; - private static Dictionary _grabberList; - - private int _resetCount; - private string _selectedFilename = string.Empty; - - //Internal BDInternalMenu - private static bool _BDInternalMenu = true; - private static bool _BDDetect = false; - - private bool _useSortTitle = false; - private bool _useOnlyNfoScraper = false; - private bool _doNotUseDatabase = false; - - private static string _prevServerName = string.Empty; - private static DateTime _prevWolTime; - private static int _wolTimeout; - private static int _wolResendTime; - private GUIDialogProgress _progressDialogForUpdateMediaInfo; - - #endregion - - #region constructors - - static GUIVideoFiles() - { - _playlistPlayer = PlayListPlayer.SingletonPlayer; - } - - public GUIVideoFiles() - { - GetID = (int)Window.WINDOW_VIDEOS; - } - - #endregion - - #region Overrides - - protected override bool CurrentSortAsc - { - get { return _mapSettings.SortAscending; } - set { _mapSettings.SortAscending = value; } - } - - protected override VideoSort.SortMethod CurrentSortMethod - { - get { return (VideoSort.SortMethod) _mapSettings.SortBy; } - set { _mapSettings.SortBy = (int) value; } - } - - protected override Layout CurrentLayout - { - get { return (Layout) _mapSettings.ViewAs; } - set { _mapSettings.ViewAs = (int) value; } - } - - public override bool Init() - { - return Load(GUIGraphicsContext.GetThemedSkinFile(@"\myVideo.xml")); - } - - public override void OnAdded() - { - base.OnAdded(); - new IMDB(this); - g_Player.PlayBackStopped += OnPlayBackStopped; - g_Player.PlayBackEnded += OnPlayBackEnded; - g_Player.PlayBackStarted += OnPlayBackStarted; - g_Player.PlayBackChanged += OnPlayBackChanged; - GUIWindowManager.Receivers += GUIWindowManager_OnNewMessage; - LoadSettings(); - - _removableDrivesHandlerThread = new Thread(ListRemovableDrives); - _removableDrivesHandlerThread.IsBackground = true; - _removableDrivesHandlerThread.Name = "VideoRemovableDrivesHandlerThread"; - _removableDrivesHandlerThread.Start(); - } - - private void ListRemovableDrives() - { - RemovableDrivesHandler.ListRemovableDrives(_virtualDirectory.GetDirectoryExt(string.Empty)); - } - - protected override void OnSearchNew() - { - if (_doNotUseDatabase) - { - GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK); - dlgOk.SetHeading(string.Empty); - dlgOk.SetLine(1, GUILocalizeStrings.Get(416)); // Not available - dlgOk.DoModal(GUIWindowManager.ActiveWindow); - return; - } - - int maximumShares = 128; - ArrayList availablePaths = new ArrayList(); - - using (Profile.Settings xmlreader = new MPSettings()) - { - for (int index = 0; index < maximumShares; index++) - { - string sharePath = String.Format("sharepath{0}", index); - string shareDir = xmlreader.GetValueAsString("movies", sharePath, ""); - string shareScan = String.Format("sharescan{0}", index); - bool shareScanData = xmlreader.GetValueAsBool("movies", shareScan, true); - - if (shareScanData && shareDir != string.Empty) - { - availablePaths.Add(shareDir); - } - } - - ArrayList nfoFiles = new ArrayList(); - - foreach (string availablePath in availablePaths) - { - GetNfoFiles(availablePath, ref nfoFiles); - } - - if (!_useOnlyNfoScraper) // Normal scraper - { - // First try nfo files - IMDBFetcher fetcher = new IMDBFetcher(this); - fetcher.FetchNfo(nfoFiles, true, false); - // Then video files without nfo - IMDBFetcher.ScanIMDB(this, availablePaths, true, true, true, false); - } - else - { - // Only nfo files - IMDBFetcher fetcher = new IMDBFetcher(this); - fetcher.FetchNfo(nfoFiles, true, false); - } - - // Send global message that movie is refreshed/scanned - GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VIDEOINFO_REFRESH, 0, 0, 0, 0, 0, null); - GUIWindowManager.SendMessage(msg); - - _currentSelectedItem = facadeLayout.SelectedListItemIndex; - - if (_currentSelectedItem > 0) - { - _currentSelectedItem--; - } - - LoadDirectory(_currentFolder); - - if (_currentSelectedItem >= 0) - { - GUIControl.SelectItemControl(GetID, facadeLayout.GetID, _currentSelectedItem); - } - } - } - - #region Serialisation - - protected override void LoadSettings() - { - base.LoadSettings(); - using (Profile.Settings xmlreader = new Profile.MPSettings()) - { - currentLayout = (Layout) xmlreader.GetValueAsInt(SerializeName, "layout", (int) Layout.List); - m_bSortAscending = xmlreader.GetValueAsBool(SerializeName, "sortasc", true); - VideoState.StartWindow = xmlreader.GetValueAsInt("movies", "startWindow", GetID); - VideoState.View = xmlreader.GetValueAsString("movies", "startview", "369"); - - // Prevent unaccesible My Videos from corrupted config - if (!IsVideoWindow(VideoState.StartWindow)) - { - VideoState.StartWindow = GetID; - VideoState.View = "369"; - } - - _addVideoFilesToDb = xmlreader.GetValueAsBool("gui", "addVideoFilesToDb", false); - _isFuzzyMatching = xmlreader.GetValueAsBool("movies", "fuzzyMatching", false); - _scanSkipExisting = xmlreader.GetValueAsBool("moviedatabase", "scanskipexisting", false); - _getActors = xmlreader.GetValueAsBool("moviedatabase", "getactors", true); - _markWatchedFiles = xmlreader.GetValueAsBool("movies", "markwatched", true); - //_eachFolderIsMovie = xmlreader.GetValueAsBool("movies", "eachFolderIsMovie", false); - _fileMenuEnabled = xmlreader.GetValueAsBool("filemenu", "enabled", true); - _fileMenuPinCode = Util.Utils.DecryptPassword(xmlreader.GetValueAsString("filemenu", "pincode", string.Empty)); - _howToPlayAll = xmlreader.GetValueAsInt("movies", "playallinfolder", 3); - _watchedPercentage = xmlreader.GetValueAsInt("movies", "playedpercentagewatched", 95); - _videoInfoInShare = xmlreader.GetValueAsBool("moviedatabase", "movieinfoshareview", false); - _BDInternalMenu = xmlreader.GetValueAsBool("bdplayer", "useInternalBDPlayer", true); - - _virtualDirectory = VirtualDirectories.Instance.Movies; - // External player - _useInternalVideoPlayer = xmlreader.GetValueAsBool("movieplayer", "internal", true); - _useInternalDVDVideoPlayer = xmlreader.GetValueAsBool("dvdplayer", "internal", true); - _externalPlayerExtensions = xmlreader.GetValueAsString("movieplayer", "extensions", ""); - - _wolTimeout = xmlreader.GetValueAsInt("WOL", "WolTimeout", 10); - _wolResendTime = xmlreader.GetValueAsInt("WOL", "WolResendTime", 1); - - if (_virtualStartDirectory == string.Empty) - { - if (_virtualDirectory.DefaultShare != null) - { - if (_virtualDirectory.DefaultShare.IsFtpShare) - { - //remote:hostname?port?login?password?folder - _currentFolder = _virtualDirectory.GetShareRemoteURL(_virtualDirectory.DefaultShare); - _virtualStartDirectory = _currentFolder; - } - else - { - _currentFolder = _virtualDirectory.DefaultShare.Path; - _virtualStartDirectory = _virtualDirectory.DefaultShare.Path; - } - } - } - - _askBeforePlayingDVDImage = xmlreader.GetValueAsBool("daemon", "askbeforeplaying", false); - - if (xmlreader.GetValueAsBool("movies", "rememberlastfolder", false)) - { - string lastFolder = xmlreader.GetValueAsString("movies", "lastfolder", _currentFolder); - if (VirtualDirectory.IsImageFile(Path.GetExtension(lastFolder))) - { - lastFolder = "root"; - } - if (lastFolder != "root") - { - _currentFolder = lastFolder; - } - } - - _switchRemovableDrives = xmlreader.GetValueAsBool("movies", "SwitchRemovableDrives", true); - _useOnlyNfoScraper = xmlreader.GetValueAsBool("moviedatabase", "useonlynfoscraper", false); - _doNotUseDatabase = xmlreader.GetValueAsBool("moviedatabase", "donotusedatabase", false); - - } - - if (_currentFolder.Length > 0 && _currentFolder == _virtualStartDirectory) - { - VirtualDirectory vDir = new VirtualDirectory(); - vDir.LoadSettings("movies"); - } - } - - protected override void SaveSettings() - { - base.SaveSettings(); - - using (Profile.Settings xmlwriter = new MPSettings()) - { - xmlwriter.SetValue(SerializeName, "layout", (int)currentLayout); - xmlwriter.SetValueAsBool(SerializeName, "sortasc", m_bSortAscending); - } - } - - #endregion - - protected override string SerializeName - { - get { return "myvideo"; } - } - - public override void OnAction(Action action) - { - if ((action.wID == Action.ActionType.ACTION_PREVIOUS_MENU) && (facadeLayout.Focus)) - { - GUIListItem item = facadeLayout[0]; - if ((item != null) && item.IsFolder && (item.Label == "..")) - { - _history.Set("0", _currentFolder); - LoadDirectory(item.Path); - return; - } - } - - if (action.wID == Action.ActionType.ACTION_PARENT_DIR) - { - GUIListItem item = facadeLayout[0]; - if ((item != null) && item.IsFolder && (item.Label == "..")) - { - _history.Set("0", _currentFolder); - LoadDirectory(item.Path); - } - return; - } - - if (action.wID == Action.ActionType.ACTION_DELETE_ITEM && _fileMenuEnabled) - { - ShowFileMenu(true); - } - - if (action.wID == Action.ActionType.ACTION_PLAY || action.wID == Action.ActionType.ACTION_MUSIC_PLAY) - { - _playClicked = true; - } - - if (action.wID == Action.ActionType.ACTION_EJECTCD) - { - GUIListItem item = facadeLayout.SelectedListItem; - if (item == null || item.Path == null || Util.Utils.getDriveType(item.Path) != 5) - { - Util.Utils.EjectCDROM(); - } - else - { - Util.Utils.EjectCDROM(Path.GetPathRoot(item.Path)); - } - - LoadDirectory(string.Empty); - } - - base.OnAction(action); - } - - protected override void OnPageLoad() - { - base.OnPageLoad(); - - if (!VideoDatabase.DbHealth) - { - GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); - pDlgOK.SetHeading(315); - pDlgOK.SetLine(1, string.Empty); - pDlgOK.SetLine(2, GUILocalizeStrings.Get(190010, new object[] { GUILocalizeStrings.Get(3) })); - pDlgOK.DoModal(GUIWindowManager.ActiveWindow); ; - } - if (!FolderSettings.DbHealth) - { - GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); - pDlgOK.SetHeading(315); - pDlgOK.SetLine(1, string.Empty); - pDlgOK.SetLine(2, GUILocalizeStrings.Get(190010, new object[] { GUILocalizeStrings.Get(190011) })); - pDlgOK.DoModal(GUIWindowManager.ActiveWindow); - } - - base.LoadSettings(); - bool result = false; - - if (_loadParameter != null && _loadParameter != string.Empty) - { - foreach (GUIListItem item in VirtualDirectories.Instance.Movies.GetRootExt()) - { - if (item.Label.ToUpper() == _loadParameter.ToUpper()) - { - _currentFolder = item.Path; - result = true; - base.SetView(0); - } - } - if (!result) - { - if (_loadParameter == "134") - { - base.SetView(0); - Log.Debug("GUIVideoFiles.OnPageLoad: selectedView.Name = share"); - } - else - { - try - { - string selectedView; - - try - { - selectedView = GUILocalizeStrings.Get(Convert.ToInt32(_loadParameter)); - } - catch - { - selectedView = _loadParameter; - } - - for (int i = 0; i < handler.Views.Count; i++) - { - if (handler.Views[i].LocalizedName == selectedView) - { - Log.Debug("GUIVideoFiles.OnPageLoad: selectedView.Name = {0}", handler.Views[i].LocalizedName); - - base.SetView(i + 1); - - break; - } - } - } - catch (Exception ex) - { - Log.Error("GUIVideoFiles.OnPageLoad: Exception {0}", ex); - } - } - } - } - - // This can't be in LoadSettings beacuse settings are loaded on MP start and it will disable SortTitle setting always - using (Profile.Settings xmlreader = new Profile.MPSettings()) - { - // Don't sort by sorttitle - _useSortTitle = xmlreader.GetValueAsBool("moviedatabase", "usesorttitle", false); - xmlreader.SetValueAsBool("moviedatabase", "usesorttitle", false); - } - - if (!KeepVirtualDirectory(PreviousWindowId)) - { - Reset(); - } - - if (!IsVideoWindow(PreviousWindowId) && IsFolderPinProtected(_cachedDir)) - { - //when the user left MyVideos completely make sure that we don't use the cache - //if folder is pin protected and reload the dir completly including PIN request etc. - _cachedItems.Clear(); - _cachedDir = null; - } - - if (VideoState.StartWindow != GetID) - { - GUIWindowManager.ReplaceWindow(VideoState.StartWindow); - return; - } - - _resetCount = 0; - - // Go to default share from main MP menu - if (_currentFolder == string.Empty) - { - _currentFolder = _virtualStartDirectory; - } - - LoadFolderSettings(_currentFolder); - - //OnPageLoad is sometimes called when stopping playback. - //So we use the cached version of the function here. - LoadDirectory(_currentFolder, true); - } - - protected override void OnPageDestroy(int newWindowId) - { - // set back Sort by sorttitle - using (Profile.Settings xmlwriter = new Profile.MPSettings()) - { - xmlwriter.SetValueAsBool("moviedatabase", "usesorttitle", _useSortTitle); - } - - if (_videoFolderWatcher != null) - { - _videoFolderWatcher.PauseMonitoring(true); - } - - if (_setThumbs != null && _setThumbs.IsAlive) - { - _setThumbs.Abort(); - _setThumbs = null; - } - - // Set folder history when video window is not actually left (ie.: play movie, video info..) - if (IsVideoWindow(newWindowId)) - { - if (facadeLayout != null) - { - _history.Set(facadeLayout.SelectedListItemIndex.ToString(), _currentFolder); - } - } - else // For real exit (ie.: to home, reset folder history) - { - _history.Set("0", _currentFolder); - } - - SaveFolderSettings(_currentFolder); - ReleaseResources(); - base.OnPageDestroy(newWindowId); - } - - public override bool OnMessage(GUIMessage message) - { - switch (message.Message) - { - case GUIMessage.MessageType.GUI_MSG_CD_REMOVED: - if (g_Player.Playing && g_Player.IsDVD && - message.Label.Equals(g_Player.CurrentFile.Substring(0, 2), StringComparison.InvariantCultureIgnoreCase)) - // test if it is our drive - { - Log.Info("GUIVideoFiles: Stop dvd since DVD is ejected"); - g_Player.Stop(); - } - - if (GUIWindowManager.ActiveWindow == GetID) - { - if (Util.Utils.IsDVD(_currentFolder)) - { - _currentFolder = string.Empty; - LoadDirectory(_currentFolder); - } - } - break; - - case GUIMessage.MessageType.GUI_MSG_FILE_DOWNLOADING: - facadeLayout.OnMessage(message); - break; - - case GUIMessage.MessageType.GUI_MSG_FILE_DOWNLOADED: - - facadeLayout.OnMessage(message); - break; - - case GUIMessage.MessageType.GUI_MSG_VIDEOFILE_CREATED: - AddItem(message.Label, -1); - break; - - case GUIMessage.MessageType.GUI_MSG_VIDEOFILE_DELETED: - DeleteItem(message.Label); - SelectCurrentItem(); - break; - - case GUIMessage.MessageType.GUI_MSG_VIDEOFILE_RENAMED: - ReplaceItem(message.Label2, message.Label); - SelectCurrentItem(); - break; - - case GUIMessage.MessageType.GUI_MSG_VIDEODIRECTORY_CREATED: - AddItem(message.Label, -1); - break; - - case GUIMessage.MessageType.GUI_MSG_VIDEODIRECTORY_DELETED: - DeleteItem(message.Label); - SelectCurrentItem(); - break; - - case GUIMessage.MessageType.GUI_MSG_VIDEODIRECTORY_RENAMED: - ReplaceItem(message.Label2, message.Label); - SelectCurrentItem(); - break; - - case GUIMessage.MessageType.GUI_MSG_SHOW_DIRECTORY: - // Make sure file view is the current window - if (VideoState.StartWindow != GetID) - { - VideoState.StartWindow = GetID; - Reset(); - GUIWindowManager.ReplaceWindow(GetID); - } - _currentFolder = message.Label; - LoadDirectory(_currentFolder); - break; - - case GUIMessage.MessageType.GUI_MSG_ADD_REMOVABLE_DRIVE: - if (_switchRemovableDrives) - { - _currentFolder = message.Label; - if (!Util.Utils.IsRemovable(message.Label)) - { - _virtualDirectory.AddRemovableDrive(message.Label, message.Label2); - } - } - if (_removableDrivesHandlerThread != null) - { - _removableDrivesHandlerThread.Join(); - } - - RemovableDrivesHandler.ListRemovableDrives(_virtualDirectory.GetDirectoryExt(string.Empty)); - LoadDirectory(_currentFolder); - break; - - case GUIMessage.MessageType.GUI_MSG_REMOVE_REMOVABLE_DRIVE: - if (!Util.Utils.IsRemovable(message.Label)) - { - _virtualDirectory.Remove(message.Label); - } - if (_currentFolder.Contains(message.Label)) - { - _currentFolder = string.Empty; - } - LoadDirectory(_currentFolder); - break; - - case GUIMessage.MessageType.GUI_MSG_VOLUME_INSERTED: - case GUIMessage.MessageType.GUI_MSG_VOLUME_REMOVED: - if (_currentFolder == string.Empty || _currentFolder.Substring(0, 2) == message.Label) - { - _currentFolder = string.Empty; - LoadDirectory(_currentFolder); - } - break; - - case GUIMessage.MessageType.GUI_MSG_PLAY_DVD: - OnPlayDVD(message.Label, GetID); - break; - - case GUIMessage.MessageType.GUI_MSG_LAYOUT_CHANGED: - FolderSetting folderSetting = new FolderSetting(); - folderSetting.UpdateFolders(-1, CurrentSortAsc, (int)CurrentLayout); - break; - - case GUIMessage.MessageType.GUI_MSG_REFRESH_MEDIAINFO: - SelectCurrentItem(); - break; - } - return base.OnMessage(message); - } - - protected override void LoadDirectory(string newFolderName) - { - this.LoadDirectory(newFolderName, false); - } - - protected override void OnClick(int iItem) - { - GUIListItem item = facadeLayout.SelectedListItem; - TotalMovieDuration = 0; - IsStacked = false; - StackedMovieFiles.Clear(); - - if (item == null) - { - _playClicked = false; - return; - } - - if (!WakeUpSrv(item.Path)) - { - return; - } - - string path = item.Path; - - if (item.IsBdDvdFolder) - { - // Check if folder is actually a DVD. If so don't browse this folder, but play the DVD! - if (File.Exists(path + @"\VIDEO_TS\VIDEO_TS.IFO")) - { - path = item.Path + @"\VIDEO_TS\VIDEO_TS.IFO"; - } - // Then it's a Blu-Ray. Play the Blu-Ray! - else - { - path = item.Path + @"\BDMV\index.bdmv"; - } - } - - if ((item.IsFolder && !item.IsBdDvdFolder)) - { - // Play all in folder - if (_playClicked) - { - if (!item.IsRemote && item.Label != ".." && !VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) - { - if (!_virtualDirectory.RequestPin(item.Path)) - { - _playClicked = false; - return; - } - - OnPlayAll(item.Path); - _playClicked = false; - } - } - else - { - _currentSelectedItem = -1; - - if (facadeLayout != null) - { - _history.Set(facadeLayout.SelectedListItemIndex.ToString(), _currentFolder); - } - - LoadDirectory(path, true); - } - } - else - { - if (!_virtualDirectory.RequestPin(path)) - { - _playClicked = false; - return; - } - - if (_virtualDirectory.IsRemote(path)) - { - if (!_virtualDirectory.IsRemoteFileDownloaded(path, item.FileInfo.Length)) - { - if (!_virtualDirectory.ShouldWeDownloadFile(path)) - { - _playClicked = false; - return; - } - - if (!_virtualDirectory.DownloadRemoteFile(path, item.FileInfo.Length)) - { - //show message that we are unable to download the file - GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SHOW_WARNING, 0, 0, 0, 0, 0, 0); - msg.Param1 = 916; - msg.Param2 = 920; - msg.Param3 = 0; - msg.Param4 = 0; - GUIWindowManager.SendMessage(msg); - _playClicked = false; - return; - } - //download subtitle files - Thread subLoaderThread = new Thread(DownloadSubtitles); - subLoaderThread.IsBackground = true; - subLoaderThread.Name = "SubtitleLoader"; - subLoaderThread.Start(); - } - } - - if (item.FileInfo != null) - { - if (!_virtualDirectory.IsRemoteFileDownloaded(path, item.FileInfo.Length)) - { - _playClicked = false; - return; - } - } - - string movieFileName = path; - movieFileName = _virtualDirectory.GetLocalFilename(movieFileName); - - if (PlayListFactory.IsPlayList(movieFileName)) - { - LoadPlayList(movieFileName); - _playClicked = false; - return; - } - - if (!CheckMovie(movieFileName)) - { - _playClicked = false; - return; - } - - if (_videoInfoInShare && VideoDatabase.HasMovieInfo(movieFileName) && !_playClicked) - { - OnInfo(facadeLayout.SelectedListItemIndex); - return; - } - - bool askForResumeMovie = true; - _playClicked = false; - - #region StackEnabled and file is stackable - - // Proceed to file stack check if file is stackable - if (_mapSettings.Stack && IsFileStackable(movieFileName)) - { - IsStacked = true; - int selectedFileIndex = 0; - int movieDuration = 0; - ArrayList movies = new ArrayList(); - List items = new List(); - IMDBMovie movie = item.AlbumInfoTag as IMDBMovie; - - // This will return all stackable files for current clicked item - // Also will add all stackable files to videodatabase if they are not exist - StackedMovieFiles = AddFileToDatabase(movieFileName); - - // Add movie files to list - foreach (string file in StackedMovieFiles) - { - FileInformation fi = new FileInformation(); - GUIListItem itemMovie = new GUIListItem(Util.Utils.GetFilename(file), "", file, false, fi); - items.Add(itemMovie); - } - - // In the list must be at least 2 files so we check stackable movie for resume - // (which file have a stop time) - bool asked = false; - string title = item.Label; // Dlg title - - if (movie != null && !movie.IsEmpty) - { - title = movie.Title; - } - - for (int i = 0; i < items.Count; ++i) - { - IMDBMovie.SetMovieData(items[i]); // This will set IMDBMovie object and it will never be null - movie = items[i].AlbumInfoTag as IMDBMovie; - - if (!asked) - { - selectedFileIndex++; - } - - int idFile = VideoDatabase.GetFileId(movie.VideoFileName); - - if (idFile != -1) - { - int timeMovieStopped = VideoDatabase.GetMovieStopTime(idFile); - - if (timeMovieStopped > 0) - { - if (!asked) - { - asked = true; - GUIResumeDialog.Result result = - GUIResumeDialog.ShowResumeDialog(title, movieDuration + timeMovieStopped, - GUIResumeDialog.MediaType.Video); - - if (result == GUIResumeDialog.Result.Abort) - { - _playlistPlayer.Reset(); - _playlistPlayer.CurrentPlaylistType = _currentPlaylistType; - _playlistPlayer.CurrentSong = _currentPlaylistIndex; - return; - } - - if (result == GUIResumeDialog.Result.PlayFromBeginning) - { - VideoDatabase.DeleteMovieStopTime(idFile); - } - else - { - askForResumeMovie = false; - } - } - } - - // Total movie duration - movieDuration += VideoDatabase.GetVideoDuration(idFile); - TotalMovieDuration = movieDuration; - } - } - - for (int i = 0; i < items.Count; ++i) - { - GUIListItem temporaryListItem = (GUIListItem)items[i]; - movie = (IMDBMovie)temporaryListItem.AlbumInfoTag; - - if (Util.Utils.IsVideo(movie.VideoFileName) && !PlayListFactory.IsPlayList(movie.VideoFileName)) - { - movies.Add(movie.VideoFileName); - } - } - - if (movies.Count == 0) - { - movies.Add(movieFileName); - } - - if (movies.Count > 1) - { - movies.Sort(); - - // Stacked movies duration - if (TotalMovieDuration == 0) - { - MovieDuration(movies, false); - StackedMovieFiles = movies; - } - - // Ask for resume - if (askForResumeMovie) - { - GUIDialogFileStacking dlg = - (GUIDialogFileStacking) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_FILESTACKING); - - if (null != dlg) - { - dlg.SetFiles(movies); - dlg.DoModal(GetID); - selectedFileIndex = dlg.SelectedFile; - - if (selectedFileIndex < 1) - { - return; - } - } - } - } - // This can happen if user have one file and it is stackable (filename ends with CDx...) - else - { - MovieDuration(movies, false); - } - - // Get current playlist - _currentPlaylistType = new PlayListType(); - _currentPlaylistType = _playlistPlayer.CurrentPlaylistType; - _currentPlaylistIndex = _playlistPlayer.CurrentSong; - - _playlistPlayer.Reset(); - _playlistPlayer.CurrentPlaylistType = PlayListType.PLAYLIST_VIDEO_TEMP; - PlayList playlist = _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO_TEMP); - playlist.Clear(); - - for (int i = 0; i < (int) movies.Count; ++i) - { - movieFileName = (string) movies[i]; - PlayListItem itemNew = new PlayListItem(); - itemNew.FileName = movieFileName; - itemNew.Type = PlayListItem.PlayListItemType.Video; - playlist.Add(itemNew); - } - - // play movie...(2 or more files) - PlayMovieFromPlayList(askForResumeMovie, selectedFileIndex - 1, true); - return; - } - - #endregion - - #region StackDisabled or file not stackable - - // play movie...(only 1 file) - AddFileToDatabase(movieFileName); - - // Get current playlist - _currentPlaylistType = new PlayListType(); - _currentPlaylistType = _playlistPlayer.CurrentPlaylistType; - _currentPlaylistIndex = _playlistPlayer.CurrentSong; - - _playlistPlayer.Reset(); - _playlistPlayer.CurrentPlaylistType = PlayListType.PLAYLIST_VIDEO_TEMP; - PlayList newPlayList = _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO_TEMP); - newPlayList.Clear(); - PlayListItem NewItem = new PlayListItem(); - NewItem.FileName = movieFileName; - NewItem.Type = PlayListItem.PlayListItemType.Video; - newPlayList.Add(NewItem); - PlayMovieFromPlayList(true, true); - - #endregion - } - } - - protected override void OnQueueItem(int itemIndex) - { - // add item 2 playlist - GUIListItem listItem = facadeLayout[itemIndex]; - - if (listItem == null) - { - return; - } - - if (listItem.IsRemote) - { - return; - } - - if (!_virtualDirectory.RequestPin(listItem.Path)) - { - return; - } - - if (PlayListFactory.IsPlayList(listItem.Path)) - { - LoadPlayList(listItem.Path); - return; - } - - AddItemToPlayList(listItem); - - //move to next item - GUIControl.SelectItemControl(GetID, facadeLayout.GetID, itemIndex + 1); - } - - protected override void AddItemToPlayList(GUIListItem listItem) - { - if (listItem.IsFolder) - { - // recursive - if (listItem.Label == "..") - { - return; - } - - List itemlist = _virtualDirectory.GetDirectoryUnProtectedExt(listItem.Path, true); - - foreach (GUIListItem item in itemlist) - { - AddItemToPlayList(item); - } - } - else - { - if (Util.Utils.IsVideo(listItem.Path) && !PlayListFactory.IsPlayList(listItem.Path)) - { - PlayListItem playlistItem = new PlayListItem(); - playlistItem.FileName = listItem.Path; - playlistItem.Description = listItem.Label; - playlistItem.Duration = listItem.Duration; - playlistItem.Type = PlayListItem.PlayListItemType.Video; - _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO).Add(playlistItem); - } - } - } - - protected override void OnInfo(int iItem) - { - GUIListItem pItem = facadeLayout.SelectedListItem; - CurrentSelectedGUIItem = pItem; - - if (pItem == null || pItem.IsRemote || - !_virtualDirectory.RequestPin(pItem.Path) || - pItem.IsFolder && (!pItem.IsBdDvdFolder || pItem.Label == "..")) - { - return; - } - - IMDBMovie movieDetails = pItem.AlbumInfoTag as IMDBMovie; - - if (movieDetails == null) - { - return; - } - - if (_doNotUseDatabase && movieDetails.ID < 1) - { - if (string.IsNullOrEmpty(movieDetails.MovieNfoFile)) - { - return; - } - } - - if (movieDetails.ID < 1 && !_doNotUseDatabase) - { - - // Check for nfo file - if (_useOnlyNfoScraper && File.Exists(movieDetails.MovieNfoFile)) - { - // Import nfo into database - VideoDatabase.ImportNfo(movieDetails.MovieNfoFile, false, false); - // Refresh movie info - VideoDatabase.GetMovieInfo(movieDetails.VideoFileName, ref movieDetails); - } - else if (!Win32API.IsConnectedToInternet()) - { - if(File.Exists(movieDetails.MovieNfoFile)) - { - // Try nfo file - VideoDatabase.ImportNfo(movieDetails.MovieNfoFile, false, false); - // Refresh movie info - VideoDatabase.GetMovieInfo(movieDetails.VideoFileName, ref movieDetails); - // Send global message that movie is refreshed/scanned - GUIMessage msgNfo = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VIDEOINFO_REFRESH, 0, 0, 0, 0, 0, null); - GUIWindowManager.SendMessage(msgNfo); - return; - } - - GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); - dlgOk.SetHeading(257); - dlgOk.SetLine(1, GUILocalizeStrings.Get(703)); - dlgOk.DoModal(GUIWindowManager.ActiveWindow); - return; - } - else - { - if (File.Exists(movieDetails.MovieNfoFile)) - { - // Try nfo file - VideoDatabase.ImportNfo(movieDetails.MovieNfoFile, false, false); - // Refresh movie info - VideoDatabase.GetMovieInfo(movieDetails.VideoFileName, ref movieDetails); - } - else - { - bool isDedicatedMovieFolder = Util.Utils.IsFolderDedicatedMovieFolder(pItem.Path); - - if (isDedicatedMovieFolder) - { - if (pItem.IsBdDvdFolder) - { - movieDetails.SearchString = pItem.Label; - } - else - { - movieDetails.SearchString = Path.GetFileName(movieDetails.VideoFilePath); - } - } - else - { - // Remove extension from label if exist (when "Do not show file extesnion setting" is inactive) - movieDetails.SearchString = Util.Utils.GetFilename(pItem.Label, true); - } - - movieDetails.File = Path.GetFileName(movieDetails.VideoFileName); - Log.Info("GUIVideoFiles: IMDB search: {0}, file:{1}, path:{2}", movieDetails.SearchString, movieDetails.File, - movieDetails.Path); - - if (!IMDBFetcher.GetInfoFromIMDB(this, ref movieDetails, _isFuzzyMatching, false)) - { - return; - } - } - } - // Send global message that movie is refreshed/scanned - GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VIDEOINFO_REFRESH, 0, 0, 0, 0, 0, null); - GUIWindowManager.SendMessage(msg); - } - - // Open video info screen - GUIVideoInfo videoInfo = (GUIVideoInfo) GUIWindowManager.GetWindow((int) Window.WINDOW_VIDEO_INFO); - videoInfo.Movie = movieDetails; - - if (pItem.IsFolder) - { - videoInfo.FolderForThumbs = pItem.Path; - } - else - { - videoInfo.FolderForThumbs = string.Empty; - } - - GUIWindowManager.ActivateWindow((int) Window.WINDOW_VIDEO_INFO); - } - - protected override void SelectCurrentItem() - { - if (_currentSelectedItem >= 0) - { - GUIControl.SelectItemControl(GetID, facadeLayout.GetID, _currentSelectedItem); - } - else - { - GUIPropertyManager.SetProperty("#watchedcount", "-1"); - GUIPropertyManager.SetProperty("#videoruntime", string.Empty); - } - } - - protected override void OnShowContextMenu() - { - GUIListItem item = facadeLayout.SelectedListItem; - int itemNo = facadeLayout.SelectedListItemIndex; - GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_MENU); - - if (dlg == null) - { - return; - } - - dlg.Reset(); - dlg.SetHeading(498); // menu - - if (item == null) - { - dlg.AddLocalizedString(868); // Reset virtual directory - } - else if (item.IsRemote || (item.IsFolder) && (item.Label == "..") && _virtualDirectory.IsShareOfflineDetected()) - { - dlg.AddLocalizedString(868); // Force reset virtual directory if user want to refresh offline share - } - else if (item.IsRemote || (item.IsFolder) && (item.Label == "..")) - { - return; - } - else - { - IMDBMovie movie = item.AlbumInfoTag as IMDBMovie; - - if (!facadeLayout.Focus) - { - // Menu button context menuu - if (!_virtualDirectory.IsRemote(_currentFolder)) - { - dlg.AddLocalizedString(102); //Scan - dlg.AddLocalizedString(368); //IMDB - } - } - else - { - // DVD & files - if ((Path.GetFileName(item.Path) != string.Empty) || Util.Utils.IsDVD(item.Path)) - { - // DVD disc drive - if (Util.Utils.IsDVD(item.Path)) - { - if (File.Exists(item.Path + @"\VIDEO_TS\VIDEO_TS.IFO") || - File.Exists(item.Path + @"\BDMV\index.bdmv")) - { - dlg.AddLocalizedString(341); //play - } - else - { - dlg.AddLocalizedString(926); //Queue - dlg.AddLocalizedString(102); //Scan - } - - dlg.AddLocalizedString(368); //IMDB - } - // Folder - else if (item.IsFolder) - { - bool useMediaInfo = false; - - if (VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) - { - dlg.AddLocalizedString(208); //play - useMediaInfo = true; - } - - if (!VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) - { - // Simple folder - if (!item.IsBdDvdFolder) - { - dlg.AddLocalizedString(1204); // Play All in selected folder - dlg.AddLocalizedString(926); //Queue - dlg.AddLocalizedString(102); //Scan - dlg.AddLocalizedString(1280); // Scan using nfo files - } - // DVD folder - else if (item.IsBdDvdFolder) - { - useMediaInfo = true; - dlg.AddLocalizedString(208); //play - dlg.AddLocalizedString(926); //Queue - dlg.AddLocalizedString(368); //IMDB - - if (movie != null && !movie.IsEmpty) - { - if (item.IsPlayed) - { - { - dlg.AddLocalizedString(830); //Reset watched status for DVD folder - } - } - else - { - dlg.AddLocalizedString(1260); // Set watched status - } - } - } - } - - if (!IsFolderPinProtected(item.Path) && _fileMenuEnabled) - { - dlg.AddLocalizedString(500); // FileMenu - } - - if (useMediaInfo) - { - dlg.AddLocalizedString(1264); //Media info - } - } - else - { - dlg.AddLocalizedString(208); //Play - dlg.AddLocalizedString(926); //Queue - dlg.AddLocalizedString(368); //IMDB - - if (item.IsPlayed) - { - dlg.AddLocalizedString(830); //Reset watched status - } - else - { - dlg.AddLocalizedString(1260); // Set watched status - } - - if (!IsFolderPinProtected(item.Path) && !item.IsRemote && _fileMenuEnabled) - { - dlg.AddLocalizedString(500); // FileMenu - } - dlg.AddLocalizedString(1264); //Media info - } - } - else if (Util.Utils.IsNetwork(item.Path)) // Process network root with drive letter - { - dlg.AddLocalizedString(1204); // Play All in selected folder - } - } - if (!_mapSettings.Stack) - { - dlg.AddLocalizedString(346); //Stack - } - else - { - dlg.AddLocalizedString(347); //Unstack - } - - #region Eject/Load - - // CD/DVD/BD - if (Util.Utils.getDriveType(item.Path) == 5) - { - if (item.Path != null) - { - var driveInfo = new DriveInfo(Path.GetPathRoot(item.Path)); - - // There is no easy way in NET to detect open tray so we will check - // if media is inside (load will be visible also in case that tray is closed but - // media is not loaded) - if (!driveInfo.IsReady) - { - dlg.AddLocalizedString(607); //Load - } - - dlg.AddLocalizedString(654); //Eject - } - } - - // Removable/USB HDD - if (Util.Utils.IsRemovable(item.Path) || Util.Utils.IsUsbHdd(item.Path)) - { - dlg.AddLocalizedString(831); - } - - #endregion - - dlg.AddLocalizedString(1299); // Refresh current directory - - if (_virtualDirectory.IsRootShare(item.Path) || _virtualDirectory.IsShareOfflineDetected()) - { - dlg.AddLocalizedString(868); // Force reset virtual directory if user want to refresh offline share - } - } - - dlg.AddLocalizedString(1262); // Update grabber scripts - dlg.AddLocalizedString(1307); // Update internal grabber scripts - dlg.AddLocalizedString(1263); // Set default grabber - - if (item != null && !item.IsFolder) - { - dlg.AddLocalizedString(1984); // Refresh thumb - if (!_hideWatchedFiles) - { - dlg.AddLocalizedString(2498); // Hide watched movies - } - else - { - dlg.AddLocalizedString(2499); // Unhide watched movies - } - } - - if (item != null && (item.IsFolder && item.Label != "..")) - { - dlg.AddLocalizedString(1995); // Create 4x4 folder.jpg - if (_refreshMediaInfoThread != null && _refreshMediaInfoThread.IsAlive) - { - dlg.AddLocalizedString(2161); // Abort Update MediaInfo thread in the folder - } - else - { - dlg.AddLocalizedString(2160); // Update MediaInfo in the folder - } - } - - dlg.DoModal(GetID); - - if (dlg.SelectedId == -1) - { - return; - } - switch (dlg.SelectedId) - { - case 368: // IMDB - OnInfo(itemNo); - break; - - case 208: // play - _playClicked = true; - OnClick(itemNo); - break; - - case 926: // add to playlist - OnQueueItem(itemNo); - break; - - case 136: // show playlist - GUIWindowManager.ActivateWindow((int)Window.WINDOW_VIDEO_PLAYLIST); - break; - - case 607: // Load (only CDROM) - Util.Utils.CloseCDROM(Path.GetPathRoot(item.Path)); - break; - - case 654: // Eject - if (item == null || item.Path == null || Util.Utils.getDriveType(item.Path) != 5) - { - Util.Utils.EjectCDROM(); - } - else - { - Util.Utils.EjectCDROM(Path.GetPathRoot(item.Path)); - } - - LoadDirectory(string.Empty); - break; - - case 341: //Play dvd - OnPlayDVD(item.Path, GetID); - break; - - case 346: //Stack - _mapSettings.Stack = true; - LoadDirectory(_currentFolder); - UpdateButtonStates(); - SaveFolderSettings(_currentFolder); - break; - - case 347: //Unstack - _mapSettings.Stack = false; - LoadDirectory(_currentFolder); - UpdateButtonStates(); - SaveFolderSettings(_currentFolder); - break; - - case 102: //Scan - if (_doNotUseDatabase) - { - GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK); - dlgOk.SetHeading(string.Empty); - dlgOk.SetLine(1, GUILocalizeStrings.Get(416)); // Not available - dlgOk.DoModal(GUIWindowManager.ActiveWindow); - return; - } - - if (facadeLayout.Focus) - { - if (item.IsFolder) - { - if (item.Label == "..") - { - return; - } - if (item.IsRemote) - { - return; - } - } - } - - if (!_virtualDirectory.RequestPin(item.Path)) - { - return; - } - - int currentIndex = facadeLayout.SelectedListItemIndex; - ArrayList scanNfoFiles = new ArrayList(); - GetNfoFiles(item.Path, ref scanNfoFiles); - - if (_useOnlyNfoScraper) - { - IMDBFetcher scanFetcher = new IMDBFetcher(this); - scanFetcher.FetchNfo(scanNfoFiles, true, false); - // Send global message that movie is refreshed/scanned - GUIMessage scanNfoMsg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VIDEOINFO_REFRESH, 0, 0, 0, 0, 0, null); - GUIWindowManager.SendMessage(scanNfoMsg); - LoadDirectory(_currentFolder); - facadeLayout.SelectedListItemIndex = currentIndex; - } - else - { - // Try nfo files first - IMDBFetcher scanFetcher = new IMDBFetcher(this); - scanFetcher.FetchNfo(scanNfoFiles, true, false); - // Then the rest - ArrayList availablePaths = new ArrayList(); - availablePaths.Add(item.Path); - IMDBFetcher.ScanIMDB(this, availablePaths, _isFuzzyMatching, true, _getActors, false); - // Send global message that movie is refreshed/scanned - GUIMessage scanMsg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VIDEOINFO_REFRESH, 0, 0, 0, 0, 0, null); - GUIWindowManager.SendMessage(scanMsg); - LoadDirectory(_currentFolder); - facadeLayout.SelectedListItemIndex = currentIndex; - } - break; - - case 1280: //Scan using nfo files - if (_doNotUseDatabase) - { - GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK); - dlgOk.SetHeading(string.Empty); - dlgOk.SetLine(1, GUILocalizeStrings.Get(416)); // Not available - dlgOk.DoModal(GUIWindowManager.ActiveWindow); - return; - } - - if (facadeLayout.Focus) - { - if (item.IsFolder) - { - if (item.Label == "..") - { - return; - } - if (item.IsRemote) - { - return; - } - } - } - - if (!_virtualDirectory.RequestPin(item.Path)) - { - return; - } - - currentIndex = facadeLayout.SelectedListItemIndex; - ArrayList nfoFiles = new ArrayList(); - GetNfoFiles(item.Path, ref nfoFiles); - IMDBFetcher fetcher = new IMDBFetcher(this); - fetcher.FetchNfo(nfoFiles, true, false); - // Send global message that movie is refreshed/scanned - GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VIDEOINFO_REFRESH, 0, 0, 0, 0, 0, null); - GUIWindowManager.SendMessage(msg); - LoadDirectory(_currentFolder); - facadeLayout.SelectedListItemIndex = currentIndex; - break; - - case 830: // Reset watched status - SetMovieWatchStatus(item.Path, item.IsFolder, false); - int selectedIndex = facadeLayout.SelectedListItemIndex; - LoadDirectory(_currentFolder, false); - UpdateButtonStates(); - facadeLayout.SelectedListItemIndex = selectedIndex; - break; - - case 1260: // Set watched status - SetMovieWatchStatus(item.Path, item.IsFolder, true); - selectedIndex = facadeLayout.SelectedListItemIndex; - LoadDirectory(_currentFolder, false); - UpdateButtonStates(); - facadeLayout.SelectedListItemIndex = selectedIndex; - break; - - case 500: // File menu - { - ShowFileMenu(false); - } - break; - - case 831: - string message = string.Empty; - - if (Util.Utils.IsUsbHdd(item.Path) || Util.Utils.IsRemovableUsbDisk(item.Path)) - { - if (!RemovableDriveHelper.EjectDrive(item.Path, out message)) - { - GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); - pDlgOK.SetHeading(831); - pDlgOK.SetLine(1, GUILocalizeStrings.Get(832)); - pDlgOK.SetLine(2, string.Empty); - pDlgOK.SetLine(3, message); - pDlgOK.DoModal(GUIWindowManager.ActiveWindow); - } - else - { - GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); - pDlgOK.SetHeading(831); - pDlgOK.SetLine(1, GUILocalizeStrings.Get(833)); - pDlgOK.DoModal(GUIWindowManager.ActiveWindow); - } - } - else if (!RemovableDriveHelper.EjectMedia(item.Path, out message)) - { - GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); - pDlgOK.SetHeading(831); - pDlgOK.SetLine(1, GUILocalizeStrings.Get(832)); - pDlgOK.SetLine(2, string.Empty); - pDlgOK.SetLine(3, message); - pDlgOK.DoModal(GUIWindowManager.ActiveWindow); - } - else - { - GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); - pDlgOK.SetHeading(831); - pDlgOK.SetLine(1, GUILocalizeStrings.Get(833)); - pDlgOK.DoModal(GUIWindowManager.ActiveWindow); - } - break; - - case 1204: // Play all - { - if (!_virtualDirectory.RequestPin(item.Path)) - { - return; - } - OnPlayAll(item.Path); - } - break; - - case 1299: // Refresh current directory - { - if (facadeLayout.ListLayout.ListItems.Count > 0 && !string.IsNullOrEmpty(_currentFolder)) - { - facadeLayout.SelectedListItemIndex = 0; - LoadDirectory(_currentFolder, false); - } - } - break; - - case 868: // Reset V.directory - { - ResetShares(); - - if (_virtualDirectory.DefaultShare != null && _virtualDirectory.DefaultShare.Path != string.Empty) - { - LoadDirectory(_virtualDirectory.DefaultShare.Path, false); - } - else - { - LoadDirectory(string.Empty, false); - } - } - break; - - case 1262: // Update grabber scripts - UpdateGrabberScripts(false); - break; - case 1307: // Update internal grabber scripts - UpdateGrabberScripts(true); - break; - case 1263: // Set deault grabber script - SetDefaultGrabber(); - break; - case 1984: // Refresh video thumb - Log.Debug("Thumb refresh from context menu: {0}", item.Path); - if (Util.Utils.FileExistsInCache(item.Path)) - { - string strThumbPath = Util.Utils.GetVideosThumbPathname(item.Path); - - bool success = Util.VideoThumbCreator.CreateVideoThumb(item.Path, strThumbPath, true, true); - if (success) - { - Log.Debug("Refresh success!"); - if (facadeLayout.ListLayout.ListItems.Count > 0 && !string.IsNullOrEmpty(_currentFolder)) - { - selectedIndex = facadeLayout.SelectedListItemIndex; - LoadDirectory(_currentFolder, false); - facadeLayout.SelectedListItemIndex = selectedIndex; - } - } - } - - break; - case 2498: // Hide watched movies - Log.Debug("GUIVideoFiles: Hide watched movies"); - _hideWatchedFiles = true; - LoadDirectory(_currentFolder); - UpdateButtonStates(); - break; - case 2499: // Unhide watched movies - Log.Debug("GUIVideoFiles: Unhide watched movies"); - _hideWatchedFiles = false; - LoadDirectory(_currentFolder); - UpdateButtonStates(); - break; - case 1995: // Create 4x4 folder.jpg - Log.Debug("Create folder.jpg from context menu: {0}", item.Path); - CreateFolderThumb(item, true); - break; - case 1264: // Get media info (refresh mediainfo and duration) - RefreshMediaInfo(item); - break; - - case 2160: // Update mediainfo in all files in the folder - UpdateMediaInfoInFolder(item); - break; - - case 2161: // Abort update mediainfo thread in all files in the folder - if (_refreshMediaInfoThread.IsAlive) - { - _refreshMediaInfoThreadAbort = true; - } - break; - } - } - - public override void Process() - { - if ((_resetSMSsearch == true) && (_resetSMSsearchDelay.Subtract(DateTime.Now).Seconds < -2)) - { - _resetSMSsearchDelay = DateTime.Now; - _resetSMSsearch = true; - facadeLayout.EnableSMSsearch = _oldStateSMSsearch; - } - - base.Process(); - } - - #endregion - - #region Public methods - - /// - /// Total video duration in seconds (single or multiple -> stacked file(s)) - /// Also sets duration into videodatabase (movie table) -> full lenght with stacked parts - /// Parameter refresh force duration update even if data is in the videodatabase - /// - /// - /// - /// - public static int MovieDuration(ArrayList files, bool refresh) - { - TotalMovieDuration = 0; - - if (files == null || files.Count == 0) - { - return TotalMovieDuration; - } - - try - { - foreach (string file in files) - { - int fileID = VideoDatabase.GetFileId(file); - int tempDuration = VideoDatabase.GetVideoDuration(fileID); - - if (tempDuration > 0 && !refresh) - { - TotalMovieDuration += tempDuration; - } - else - { - VideoFilesMediaInfo mInfo = new VideoFilesMediaInfo(); - - if (fileID > -1) - { - // Set/update video file duration and media info - VideoDatabase.GetVideoFilesMediaInfo(file, ref mInfo, refresh); - TotalMovieDuration += (int) mInfo.Duration; - } - } - } - // Set movie duration - VideoDatabase.SetMovieDuration(VideoDatabase.GetMovieId(files[0].ToString()), TotalMovieDuration); - } - catch (Exception ex) - { - Log.Error("GUIVideoFiles: Movie duration exception: {0}", ex.Message); - } - - return TotalMovieDuration; - } - - public bool CheckMovie(string movieFileName) - { - if (!VideoDatabase.HasMovieInfo(movieFileName)) - { - return true; - } - - IMDBMovie movieDetails = new IMDBMovie(); - int idMovie = VideoDatabase.GetMovieInfo(movieFileName, ref movieDetails); - - if (idMovie < 0) - { - return true; - } - - return CheckMovie(idMovie); - } - - public static bool CheckMovie(int idMovie) - { - IMDBMovie movieDetails = new IMDBMovie(); - VideoDatabase.GetMovieInfoById(idMovie, ref movieDetails); - - if (!Util.Utils.IsDVD(movieDetails.Path)) - { - return true; - } - - string cdlabel = string.Empty; - cdlabel = Util.Utils.GetDriveSerial(movieDetails.Path); - - if (cdlabel.Equals(movieDetails.CDLabel)) - { - return true; - } - - GUIDialogYesNo dlg = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_YES_NO); - if (dlg == null) - { - return true; - } - - while (true) - { - dlg.SetHeading(428); - dlg.SetLine(1, 429); - dlg.SetLine(2, movieDetails.DVDLabel); - dlg.SetLine(3, movieDetails.Title); - dlg.SetYesLabel(GUILocalizeStrings.Get(186)); //OK - dlg.SetNoLabel(GUILocalizeStrings.Get(222)); //Cancel - dlg.SetDefaultToYes(true); - dlg.DoModal(GUIWindowManager.ActiveWindow); - - if (dlg.IsConfirmed) - { - if (movieDetails.CDLabel.StartsWith("nolabel")) - { - ArrayList movies = new ArrayList(); - VideoDatabase.GetFilesForMovie(idMovie, ref movies); - if (File.Exists( /*movieDetails.Path+movieDetails.File*/(string)movies[0])) - { - cdlabel = Util.Utils.GetDriveSerial(movieDetails.Path); - VideoDatabase.UpdateCDLabel(movieDetails, cdlabel); - movieDetails.CDLabel = cdlabel; - return true; - } - } - else - { - cdlabel = Util.Utils.GetDriveSerial(movieDetails.Path); - - if (cdlabel.Equals(movieDetails.CDLabel)) - { - return true; - } - } - } - else - { - break; - } - } - return false; - } - - public static void GetStringFromKeyboard(ref string strLine) - { - VirtualKeyboard keyboard = (VirtualKeyboard)GUIWindowManager.GetWindow((int)Window.WINDOW_VIRTUAL_KEYBOARD); - - if (null == keyboard) - { - return; - } - keyboard.IsSearchKeyboard = true; - keyboard.Reset(); - keyboard.Text = strLine; - keyboard.DoModal(GUIWindowManager.ActiveWindow); - strLine = string.Empty; - - if (keyboard.IsConfirmed) - { - strLine = keyboard.Text; - } - } - - [Obsolete("This method is obsolete; use method PlayMovieFromPlayList(bool askForResumeMovie, bool requestPin) instead.")] - public static void PlayMovieFromPlayList(bool askForResumeMovie) - { - PlayMovieFromPlayList(askForResumeMovie, -1, false); - } - - public static void PlayMovieFromPlayList(bool askForResumeMovie, bool requestPin) - { - PlayMovieFromPlayList(askForResumeMovie, -1, requestPin); - } - - public static void PlayMovieFromPlayList(bool askForResumeMovie, int iMovieIndex, bool requestPin) - { - bool BDInternalMenu = false; - bool NoBDResume = false; - _BDDetect = false; - g_Player.ForcePlay = false; - g_Player.SetResumeBDTitleState = g_Player.BdDefaultTitle; - string filename; - if (iMovieIndex == -1) - { - filename = _playlistPlayer.GetNext(); - } - else - { - filename = _playlistPlayer.Get(iMovieIndex); - } - - _playlistPlayer.Reset(); - - // If the file is an image file, it should be mounted before playing - bool isImage = false; - if (VirtualDirectory.IsImageFile(System.IO.Path.GetExtension(filename))) - { - if (!MountImageFile(GUIWindowManager.ActiveWindow, filename, requestPin)) - return; - isImage = true; - } - - // Convert BD ISO filenames for to BD index file (...BDMV\index.bdmv) - if (isImage) - { - // Covert filename - if (Util.Utils.IsBDImage(filename, ref filename)) - { - // Change also playlist filename - int index = iMovieIndex; - - if (iMovieIndex == -1) - index = 0; - - _playlistPlayer.GetPlaylist(_playlistPlayer.CurrentPlaylistType)[index].FileName = filename; - isImage = false; - } - } - - //Resume BD only for Title mode - if (filename.EndsWith(@"\BDMV\index.bdmv")) - { - _BDDetect = true; - } - - using (Profile.Settings xmlreader = new MPSettings()) - { - BDInternalMenu = xmlreader.GetValueAsBool("bdplayer", "useInternalBDPlayer", true); - } - - int timeMovieStopped = 0; - byte[] resumeData = null; - - { - // Skip resume for external player and BluRays (not implemented yet in BDLIB) - if (!CheckExternalPlayer(filename, isImage)) - { - // Check if we play image file to search db with the proper filename - if (Util.Utils.IsISOImage(filename)) - { - filename = DaemonTools.MountedIsoFile; - } - IMDBMovie movieDetails = new IMDBMovie(); - VideoDatabase.GetMovieInfo(filename, ref movieDetails); - int idFile = VideoDatabase.GetFileId(filename); - int idMovie = VideoDatabase.GetMovieId(filename); - - if (_BDDetect) - { - g_Player.SetResumeBDTitleState = VideoDatabase.GetTitleBDId(idFile, out resumeData); - if ((BDInternalMenu && g_Player.SetResumeBDTitleState >= g_Player.BdDefaultTitle) || (!BDInternalMenu && g_Player.SetResumeBDTitleState < g_Player.BdRemuxTitle)) - { - NoBDResume = true; - } - } - - if ((idMovie >= 0) && (idFile >= 0) && !NoBDResume) - { - timeMovieStopped = VideoDatabase.GetMovieStopTimeAndResumeData(idFile, out resumeData, - g_Player.SetResumeBDTitleState); - if (timeMovieStopped > 0) - { - string title = Path.GetFileName(filename); - VideoDatabase.GetMovieInfoById(idMovie, ref movieDetails); - if (movieDetails.Title != string.Empty) - { - title = movieDetails.Title; - } - - if (askForResumeMovie && g_Player.SetResumeBDTitleState >= 0) - { - if (_BDDetect) - g_Player.ForcePlay = true; - - GUIResumeDialog.Result result = - GUIResumeDialog.ShowResumeDialog(title, timeMovieStopped, - GUIResumeDialog.MediaType.Video); - - if (result == GUIResumeDialog.Result.Abort) - { - g_Player.ForcePlay = false; - timeMovieStopped = 0; - if (!_BDDetect) - { - _playlistPlayer.Reset(); - _playlistPlayer.CurrentPlaylistType = _currentPlaylistType; - _playlistPlayer.CurrentSong = _currentPlaylistIndex; - return; - } - // Return to list if we cancel resume dialog (needed when BD is remuxed) - else if (g_Player.SetResumeBDTitleState == g_Player.BdDefaultTitle || g_Player.SetResumeBDTitleState == g_Player.BdRemuxTitle) - { - return; - } - } - - if (result == GUIResumeDialog.Result.PlayFromBeginning) - timeMovieStopped = 0; - } - } - } - } - } - - // TODO Handle STOP when it comes from MyMusic otherwise Video Playlist will not work - //if (g_Player.Playing && !g_Player.IsDVD) - // g_Player.Stop(); - - string currentFile = g_Player.CurrentFile; - if (Util.Utils.IsISOImage(currentFile)) - { - if (!String.IsNullOrEmpty(Util.DaemonTools.GetVirtualDrive()) && - g_Player.IsDvdDirectory(Util.DaemonTools.GetVirtualDrive())) - Util.DaemonTools.UnMount(); - } - - if (iMovieIndex == -1) - { - _playlistPlayer.PlayNext(); - } - else - { - _playlistPlayer.Play(iMovieIndex); - } - - if (g_Player.Playing && timeMovieStopped > 0) - { - if (g_Player.IsDVD && !_BDDetect) - { - // send resume thread async - var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SET_RESUME_STATE, 0, 0, 0, 0, 0, resumeData); - GUIWindowManager.SendThreadMessage(msg); - } - else - { - GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SEEK_POSITION, 0, 0, 0, 0, 0, null); - msg.Param1 = timeMovieStopped; - GUIGraphicsContext.SendMessage(msg); - } - } - } - - public static void PlayMovieFromBDPlayList(bool askForResumeMovie, int iMovieIndex, bool requestPin) - { - //Resume BD only for Title mode - _BDDetect = false; - string filename = g_Player.currentFileName; - - // If the file is an image file, it should be mounted before playing - bool isImage = false; - if (VirtualDirectory.IsImageFile(System.IO.Path.GetExtension(filename))) - { - if (!MountImageFile(GUIWindowManager.ActiveWindow, filename, requestPin)) - return; - isImage = true; - } - - // Convert BD ISO filenames for to BD index file (...BDMV\index.bdmv) - if (isImage) - { - // Covert filename - if (Util.Utils.IsBDImage(filename, ref filename)) - { - // Change also playlist filename - int index = iMovieIndex; - - if (iMovieIndex == -1) - index = 0; - - _playlistPlayer.GetPlaylist(_playlistPlayer.CurrentPlaylistType)[index].FileName = filename; - isImage = false; - } - } - - int timeMovieStopped = 0; - byte[] resumeData = null; - - // Skip resume for external player and BluRays (not implemented yet in BDLIB) - if (!CheckExternalPlayer(filename, isImage)) - { - // Check if we play image file to search db with the proper filename - if (Util.Utils.IsISOImage(filename)) - { - filename = DaemonTools.MountedIsoFile; - } - IMDBMovie movieDetails = new IMDBMovie(); - VideoDatabase.GetMovieInfo(filename, ref movieDetails); - int idFile = VideoDatabase.GetFileId(filename); - int idMovie = VideoDatabase.GetMovieId(filename); - - if ((idMovie >= 0) && (idFile >= 0)) - { - timeMovieStopped = VideoDatabase.GetMovieStopTimeAndResumeData(idFile, out resumeData, g_Player.SetResumeBDTitleState); - if (timeMovieStopped > 0) - { - string title = Path.GetFileName(filename); - VideoDatabase.GetMovieInfoById(idMovie, ref movieDetails); - if (movieDetails.Title != string.Empty) - { - title = movieDetails.Title; - } - if (askForResumeMovie) - { - GUIResumeDialog.Result result = - GUIResumeDialog.ShowResumeDialog(title, timeMovieStopped, - GUIResumeDialog.MediaType.Video); - - if (result == GUIResumeDialog.Result.Abort) - { - g_Player.SetResumeBDTitleState = -1; - return; - } - - if (result == GUIResumeDialog.Result.PlayFromBeginning) - timeMovieStopped = 0; - } - } - } - GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SEEK_POSITION, 0, 0, 0, 0, 0, null); - msg.Param1 = timeMovieStopped; - GUIWindowManager.SendThreadMessage(msg); - } - } - - [Obsolete("This method is obsolete; use method MountImageFile(int WindowID, string file) instead.")] - public static bool MountImageFile(int windowID, string file) - { - return MountImageFile(windowID, file, false); - } - - public static bool MountImageFile(int windowID, string file, bool requestPin) - { - Log.Debug("GUIVideoFiles: MountImageFile"); - if (!DaemonTools.IsMounted(file)) - { - if (_askBeforePlayingDVDImage) - { - GUIDialogYesNo dlgYesNo = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_YES_NO); - - if (dlgYesNo != null) - { - dlgYesNo.SetHeading(713); - dlgYesNo.SetLine(1, 531); - dlgYesNo.DoModal(windowID); - if (!dlgYesNo.IsConfirmed) - { - return false; - } - } - } - - List items = new List(); - - if (requestPin) - { - items = _virtualDirectory.GetDirectoryExt(file); - } - else - { - items = _virtualDirectory.GetDirectoryUnProtectedExt(file, true); - } - - if (items.Count == 1 && file != string.Empty) - { - return false; // protected share, with wrong pincode - } - } - return DaemonTools.IsMounted(file); - } - - /// - /// Returns true if the specified window belongs to the my videos plugin - /// - /// id of window - /// - /// true: belongs to the my videos plugin - /// false: does not belong to the my videos plugin - public static bool IsVideoWindow(int windowId) - { - if (windowId == (int)Window.WINDOW_DVD) - { - return true; - } - - if (windowId == (int)Window.WINDOW_FULLSCREEN_VIDEO) - { - return true; - } - - if (windowId == (int)Window.WINDOW_VIDEO_ARTIST_INFO) - { - return true; - } - - if (windowId == (int)Window.WINDOW_VIDEO_INFO) - { - return true; - } - - if (windowId == (int)Window.WINDOW_VIDEO_PLAYLIST) - { - return true; - } - - if (windowId == (int)Window.WINDOW_VIDEO_TITLE) - { - return true; - } - - if (windowId == (int)Window.WINDOW_VIDEOS) - { - return true; - } - - return false; - } - - /// - /// Returns true if the specified window should maintain virtual directory - /// - /// id of window - /// - /// true: if the specified window should maintain virtual directory - /// false: if the specified window should not maintain virtual directory - public static bool KeepVirtualDirectory(int windowId) - { - if (windowId == (int)Window.WINDOW_DVD) - { - return true; - } - - if (windowId == (int)Window.WINDOW_FULLSCREEN_VIDEO) - { - return true; - } - - if (windowId == (int)Window.WINDOW_VIDEO_ARTIST_INFO) - { - return true; - } - - if (windowId == (int)Window.WINDOW_VIDEO_INFO) - { - return true; - } - - if (windowId == (int)Window.WINDOW_VIDEO_PLAYLIST) - { - return true; - } - - if (windowId == (int)Window.WINDOW_VIDEOS) - { - return true; - } - - return false; - } - - public static void Reset() - { - Log.Debug("GUIVideoFiles: Resetting virtual directory"); - _virtualDirectory.Reset(); - } - - [Obsolete("This method is obsolete; use method PlayMovie(int idMovie, bool requestPin) instead.")] - public static void PlayMovie(int idMovie) - { - PlayMovie(idMovie, false); - } - - public static void PlayMovie(int idMovie, bool requestPin) - { - - int selectedFileIndex = 1; - - if (IsStacked) - { - selectedFileIndex = 0; - } - - ArrayList movieFiles = new ArrayList(); - VideoDatabase.GetFilesForMovie(idMovie, ref movieFiles); - - if (movieFiles.Count <= 0 || !CheckMovie(idMovie)) - { - return; - } - - bool askForResumeMovie = true; - int movieDuration = 0; - - List items = new List(); - - foreach (string file in movieFiles) - { - FileInformation fi = new FileInformation(); - GUIListItem item = new GUIListItem(Util.Utils.GetFilename(file), "", file, false, fi); - items.Add(item); - - if (!WakeUpSrv(item.Path)) - { - return; - } - } - - if (items.Count <= 0) - { - return; - } - - if (requestPin) - { - string strDir = Path.GetDirectoryName(items[0].Path); - - if (strDir != null && strDir.EndsWith(@"\")) - { - strDir = strDir.Substring(0, strDir.Length - 1); - } - - if (strDir == null || strDir.Length > 254) - { - Log.Warn("GUIVideoFiles.PlayTitleMovie: Received a path which contains too many chars"); - return; - } - - string iPincodeCorrect; - if (_virtualDirectory.IsProtectedShare(strDir, out iPincodeCorrect)) - { - #region Pin protected - - bool retry = true; - { - while (retry) - { - //no, then ask user to enter the pincode - GUIMessage msgGetPassword = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GET_PASSWORD, 0, 0, 0, 0, 0, 0); - GUIWindowManager.SendMessage(msgGetPassword); - - if (msgGetPassword.Label != iPincodeCorrect) - { - GUIMessage msgWrongPassword = new GUIMessage(GUIMessage.MessageType.GUI_MSG_WRONG_PASSWORD, 0, 0, 0, 0, 0, - 0); - GUIWindowManager.SendMessage(msgWrongPassword); - - if (!(bool)msgWrongPassword.Object) - { - return; - } - } - else - { - retry = false; - } - } - } - - #endregion - } - } - - //check if we can resume 1 of those movies - if (items.Count > 1) - { - bool asked = false; - - for (int i = 0; i < items.Count; ++i) - { - GUIListItem temporaryListItem = (GUIListItem)items[i]; - - if (!asked) - { - selectedFileIndex++; - } - - IMDBMovie movieDetails = new IMDBMovie(); - int idFile = VideoDatabase.GetFileId(temporaryListItem.Path); - - if ((idMovie >= 0) && (idFile >= 0)) - { - VideoDatabase.GetMovieInfo((string)movieFiles[0], ref movieDetails); - string title = Path.GetFileName((string)movieFiles[0]); - - if ((VirtualDirectory.IsValidExtension((string)movieFiles[0], Util.Utils.VideoExtensions, false))) - { - Util.Utils.RemoveStackEndings(ref title); - } - - if (movieDetails.Title != string.Empty) - { - title = movieDetails.Title; - } - - int timeMovieStopped = VideoDatabase.GetMovieStopTime(idFile); - - if (timeMovieStopped > 0) - { - if (!asked) - { - asked = true; - - GUIResumeDialog.Result result = - GUIResumeDialog.ShowResumeDialog(title, movieDuration + timeMovieStopped, - GUIResumeDialog.MediaType.Video); - - if (result == GUIResumeDialog.Result.Abort) - { - _playlistPlayer.Reset(); - _playlistPlayer.CurrentPlaylistType = _currentPlaylistType; - _playlistPlayer.CurrentSong = _currentPlaylistIndex; - return; - } - - if (result == GUIResumeDialog.Result.PlayFromBeginning) - { - VideoDatabase.DeleteMovieStopTime(idFile); - } - else - { - askForResumeMovie = false; - } - } - } - // Total movie duration - movieDuration += VideoDatabase.GetVideoDuration(idFile); - } - } - - if (askForResumeMovie) - { - GUIDialogFileStacking dlg = - (GUIDialogFileStacking)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_FILESTACKING); - - if (null != dlg) - { - dlg.SetFiles(movieFiles); - dlg.DoModal(GUIWindowManager.ActiveWindow); - selectedFileIndex = dlg.SelectedFile; - if (selectedFileIndex < 1) - { - return; - } - } - } - } - - // Get current playlist - _currentPlaylistType = new PlayListType(); - _currentPlaylistType = _playlistPlayer.CurrentPlaylistType; - _currentPlaylistIndex = _playlistPlayer.CurrentSong; - - _playlistPlayer.Reset(); - _playlistPlayer.CurrentPlaylistType = PlayListType.PLAYLIST_VIDEO_TEMP; - PlayList playlist = _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO_TEMP); - playlist.Clear(); - - for (int i = selectedFileIndex - 1; i < movieFiles.Count; ++i) - { - string movieFileName = (string)movieFiles[i]; - PlayListItem newitem = new PlayListItem(); - newitem.FileName = movieFileName; - newitem.Type = PlayListItem.PlayListItemType.Video; - playlist.Add(newitem); - } - - // play movie... - PlayMovieFromPlayList(askForResumeMovie, requestPin); - } - - public static bool IsMovieFolder(string path) - { - ISelectDVDHandler selectDvdHandler = GetSelectDvdHandler(); - ISelectBDHandler selectBdHandler = GetSelectBDHandler(); - - if (selectBdHandler.IsBDDirectory(path) || selectDvdHandler.IsDvdDirectory(path)) - { - return true; - } - - return false; - } - - /// - /// Get/Set BDHandler interface from/to registered services. - /// - /// BDHandler interface - public static ISelectBDHandler GetSelectBDHandler() - { - ISelectBDHandler selectBDHandler; - if (GlobalServiceProvider.IsRegistered()) - { - selectBDHandler = GlobalServiceProvider.Get(); - } - else - { - selectBDHandler = new SelectBDHandler(); - GlobalServiceProvider.Add(selectBDHandler); - } - return selectBDHandler; - } - - /// - /// Get/Set DVDHandler interface from/to registered services. - /// - /// DVDHandler interface - public static ISelectDVDHandler GetSelectDvdHandler() - { - ISelectDVDHandler selectDVDHandler; - - if (GlobalServiceProvider.IsRegistered()) - { - selectDVDHandler = GlobalServiceProvider.Get(); - } - else - { - selectDVDHandler = new SelectDVDHandler(); - GlobalServiceProvider.Add(selectDVDHandler); - } - - return selectDVDHandler; - } - - public static void UpdateGrabberScripts(bool internalScript) - { - // Check Internet connection - - if (!Win32API.IsConnectedToInternet()) - { - GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); - dlgOk.SetHeading(257); - dlgOk.SetLine(1, GUILocalizeStrings.Get(703)); - dlgOk.DoModal(GUIWindowManager.ActiveWindow); - return; - } - - // Initialize progress bar - GUIDialogProgress progressDialog = - (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); - progressDialog.Reset(); - progressDialog.SetHeading(GUILocalizeStrings.Get(300030)); - progressDialog.ShowProgressBar(true); - progressDialog.SetLine(1, GUILocalizeStrings.Get(300031)); - progressDialog.SetLine(2, GUILocalizeStrings.Get(300032)); //Downloading - progressDialog.SetPercentage(25); - progressDialog.StartModal(GUIWindowManager.ActiveWindow); - - if (internalScript) - { - string parserIndexFile = Config.GetFile(Config.Dir.Config, "scripts\\VDBParserStrings.xml"); - string parserIndexUrl = @"http://install.team-mediaportal.com/MP1/VDBParserStrings.xml"; - string internalGrabberScriptFile = Config.GetFile(Config.Dir.Config, "scripts\\InternalActorMoviesGrabber.csscript"); - string internalGrabberScriptUrl = @"http://install.team-mediaportal.com/MP1/InternalGrabber/InternalActorMoviesGrabber.csscript"; - string internalMovieImagesGrabberScriptFile = Config.GetFile(Config.Dir.Config, "scripts\\InternalMovieImagesGrabber.csscript"); - string internalMovieImagesGrabberScriptUrl = @"http://install.team-mediaportal.com/MP1/InternalGrabber/InternalMovieImagesGrabber.csscript"; - - // VDB parser update - progressDialog.SetHeading(GUILocalizeStrings.Get(1316)); // Updating internal scripts... - progressDialog.ShowProgressBar(true); - progressDialog.SetLine(1, GUILocalizeStrings.Get(1317));// Downloading internal scripts... - progressDialog.SetLine(2, GUILocalizeStrings.Get(300032)); //Downloading - progressDialog.SetPercentage(50); - progressDialog.StartModal(GUIWindowManager.ActiveWindow); - - if (DownloadFile(parserIndexFile, parserIndexUrl, Encoding.UTF8) == false) - { - progressDialog.Close(); - return; - } - - // Internal actors grabber script update - progressDialog.SetHeading(GUILocalizeStrings.Get(1316)); - progressDialog.ShowProgressBar(true); - progressDialog.SetLine(1, GUILocalizeStrings.Get(1317)); - progressDialog.SetLine(2, GUILocalizeStrings.Get(300032)); - progressDialog.SetPercentage(75); - progressDialog.StartModal(GUIWindowManager.ActiveWindow); - - if (DownloadFile(internalGrabberScriptFile, internalGrabberScriptUrl, Encoding.Default) == false) - { - progressDialog.Close(); - return; - } - - // Internal images grabber script update - progressDialog.SetHeading(GUILocalizeStrings.Get(1316)); - progressDialog.ShowProgressBar(true); - progressDialog.SetLine(1, GUILocalizeStrings.Get(1317)); - progressDialog.SetLine(2, GUILocalizeStrings.Get(300032)); - progressDialog.SetPercentage(100); - progressDialog.StartModal(GUIWindowManager.ActiveWindow); - - if (DownloadFile(internalMovieImagesGrabberScriptFile, internalMovieImagesGrabberScriptUrl, Encoding.Default) == false) - { - progressDialog.Close(); - return; - } - - IMDB.InternalActorsScriptGrabber.ResetGrabber(); - Util.InternalCSScriptGrabbersLoader.Movies.ImagesGrabber.ResetGrabber(); - progressDialog.Close(); - } - - if (DownloadFile(_grabberIndexFile, _grabberIndexUrl, Encoding.Default) == false) - { - progressDialog.Close(); - return; - } - - - // read index file - if (!File.Exists(_grabberIndexFile)) - { - GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); - dlgOk.SetHeading(257); - dlgOk.SetLine(1, GUILocalizeStrings.Get(1261)); // No grabber index found - dlgOk.DoModal(GUIWindowManager.ActiveWindow); - progressDialog.Close(); - return; - } - - XmlDocument doc = new XmlDocument(); - doc.Load(_grabberIndexFile); - XmlNodeList sectionNodes = doc.SelectNodes("MovieInfoGrabber/grabber"); - - // download all grabbers - int percent = 0; - - if (sectionNodes != null) - { - for (int i = 0; i < sectionNodes.Count; i++) - { - if (progressDialog.IsCanceled) - { - break; - } - - string url = sectionNodes[i].Attributes["url"].Value; - string id = Path.GetFileName(url); - progressDialog.SetLine(1, GUILocalizeStrings.Get(300034) + id); // Downloading grabber: - progressDialog.SetLine(2, GUILocalizeStrings.Get(300035)); - progressDialog.SetPercentage(percent); - percent += 100 / (sectionNodes.Count - 1); - progressDialog.Progress(); - - if (DownloadFile(IMDB.ScriptDirectory + @"\" + id, url, Encoding.Default) == false) - { - progressDialog.Close(); - return; - } - } - } - progressDialog.Close(); - } - - private static bool DownloadFile(string filepath, string url, Encoding enc) - { - string grabberTempFile = Path.GetTempFileName(); - - //Application.DoEvents(); - try - { - if (File.Exists(grabberTempFile)) - { - File.Delete(grabberTempFile); - } - - //Application.DoEvents(); - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); - try - { - // Use the current user in case an NTLM Proxy or similar is used. - // request.Proxy = WebProxy.GetDefaultProxy(); - request.Proxy.Credentials = CredentialCache.DefaultCredentials; - } - catch (Exception ex) - { - Log.Error("GUIVideoFiles: DownloadFile {0}", ex.Message); - } - - using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) - { - //Application.DoEvents(); - using (Stream resStream = response.GetResponseStream()) - { - using (TextReader tin = new StreamReader(resStream, enc)) - { - using (TextWriter tout = File.CreateText(grabberTempFile)) - { - while (true) - { - string line = tin.ReadLine(); - - if (line == null) - { - break; - } - - tout.WriteLine(line); - } - } - } - } - } - - File.Delete(filepath); - File.Move(grabberTempFile, filepath); - return true; - } - catch (Exception ex) - { - Log.Error("EXCEPTION in DownloadFile | {0}\r\n{1}", ex.Message, ex.Source); - return false; - } - } - - public static void SetDefaultGrabber() - { - GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_MENU); - - if (dlg == null) - { - return; - } - - dlg.Reset(); - dlg.SetHeading(1263); // menu - - // read index file - if (!File.Exists(_grabberIndexFile)) - { - GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); - dlgOk.SetHeading(257); - dlgOk.SetLine(1, GUILocalizeStrings.Get(1261)); // No grabber index found - dlgOk.DoModal(GUIWindowManager.ActiveWindow); - return; - } - - _grabberList = new Dictionary(); - - Directory.CreateDirectory(IMDB.ScriptDirectory); - DirectoryInfo di = new DirectoryInfo(IMDB.ScriptDirectory); - - FileInfo[] fileList = di.GetFiles("*.csscript", SearchOption.AllDirectories); - GUIWaitCursor.Show(); - - foreach (FileInfo f in fileList) - { - try - { - CSScript.GlobalSettings.AddSearchDir(AppDomain.CurrentDomain.BaseDirectory); - - using (AsmHelper script = new AsmHelper(CSScript.Compile(f.FullName), "Temp", true)) - { - script.ProbingDirs = CSScript.GlobalSettings.SearchDirs.Split(';'); - IIMDBScriptGrabber grabber = (IIMDBScriptGrabber) script.CreateObject("Grabber"); - - ComboBoxItemDatabase item = new ComboBoxItemDatabase(); - item.Database = Path.GetFileNameWithoutExtension(f.FullName); - item.Language = grabber.GetLanguage(); - item.Limit = IMDB.DEFAULT_SEARCH_LIMIT.ToString(); - item.Name = grabber.GetName(); - _grabberList.Add(item.Database, item); - } - } - catch (Exception ex) - { - Log.Error("Script grabber error file: {0}, message : {1}", f.FullName, ex.Message); - } - } - - string defaultDatabase = string.Empty; - int defaultIndex = 0; - int dbNumber; - - using (Profile.Settings xmlreader = new MPSettings()) - { - defaultDatabase = xmlreader.GetValueAsString("moviedatabase", "database" + 0, "IMDB"); - dbNumber = xmlreader.GetValueAsInt("moviedatabase", "number", 0); - } - - foreach (KeyValuePair grabber in _grabberList) - { - dlg.Add(grabber.Value.Name + " - " + grabber.Value.Language); - - if (defaultDatabase == grabber.Key) - { - dlg.SelectedLabel = defaultIndex; - } - else - { - defaultIndex++; - } - } - - GUIWaitCursor.Hide(); - - dlg.DoModal(GUIWindowManager.ActiveWindow); - - if (dlg.SelectedId == -1) - { - return; - } - - using (Profile.Settings xmlwriter = new MPSettings()) - { - KeyValuePair grabber = _grabberList.ElementAt(dlg.SelectedLabel); - - - if (grabber.Key != "IMDB") - { - if (dbNumber == 0) - { - dbNumber = 1; - } - xmlwriter.SetValue("moviedatabase", "number", dbNumber); - xmlwriter.SetValue("moviedatabase", "database" + 0, grabber.Key); - xmlwriter.SetValue("moviedatabase", "title" + 0, grabber.Value.Name); - xmlwriter.SetValue("moviedatabase", "language" + 0, grabber.Value.Language); - xmlwriter.SetValue("moviedatabase", "limit" + 0, 25); - } - else - { - for (int i = 0; i < 4; i++) - { - xmlwriter.SetValue("moviedatabase", "number", 0); - xmlwriter.RemoveEntry("moviedatabase", "database" + i); - xmlwriter.RemoveEntry("moviedatabase", "title" + i); - xmlwriter.RemoveEntry("moviedatabase", "language" + i); - xmlwriter.RemoveEntry("moviedatabase", "limit" + i); - } - } - } - - IMDB.MovieInfoDatabase.ResetGrabber(); - } - - public static void ResetShares() - { - _virtualDirectory.Reset(); - _virtualDirectory.DefaultShare = null; - _virtualDirectory.LoadSettings("movies"); - - if (_virtualDirectory.DefaultShare != null) - { - string pincode; - bool folderPinProtected = _virtualDirectory.IsProtectedShare(_virtualDirectory.DefaultShare.Path, out pincode); - - if (folderPinProtected) - { - _currentFolder = string.Empty; - } - else - { - _currentFolder = _virtualDirectory.DefaultShare.Path; - } - } - } - - public static void ResetExtensions(ArrayList extensions) - { - _virtualDirectory.SetExtensions(extensions); - } - - #endregion - - #region Private methods - - private void RefreshMediaInfo(GUIListItem item) - { - if (GUIGraphicsContext.CurrentState == GUIGraphicsContext.State.STOPPING) - { - return; - } - - if (item != null) - { - string file = item.Path; - SelectDVDHandler sdh = new SelectDVDHandler(); - SelectBDHandler bdh = new SelectBDHandler(); - - if (sdh.IsDvdDirectory(item.Path)) - { - if (File.Exists(item.Path + @"\VIDEO_TS\VIDEO_TS.IFO")) - { - file = file + @"\VIDEO_TS\VIDEO_TS.IFO"; - } - } - - if (bdh.IsBDDirectory(item.Path)) - { - if (File.Exists(item.Path + @"\BDMV\INDEX.BDMV")) - { - file = file + @"\BDMV\INDEX.BDMV"; - } - } - - ArrayList files = new ArrayList(); - files = AddFileToDatabase(file); - MovieDuration(files, true); - int movieId = VideoDatabase.GetMovieId(file); - IMDBMovie mInfo = new IMDBMovie(); - mInfo.SetMediaInfoProperties(file, true); - mInfo.SetDurationProperty(movieId); - IMDBMovie.SetMovieData(item); - - GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_REFRESH_MEDIAINFO, 0, 0, 0, 0, 0, 0); - GUIWindowManager.SendMessage(msg); - } - } - - private static bool WakeUpSrv(string newFolderName) - { - bool wakeOnLanEnabled; - if (!Util.Utils.IsUNCNetwork(newFolderName)) - { - // Check if letter drive is a network drive - string detectedFolderName = Util.Utils.FindUNCPaths(newFolderName); - if (Util.Utils.IsUNCNetwork(detectedFolderName)) - { - wakeOnLanEnabled = _virtualDirectory.IsWakeOnLanEnabled(_virtualDirectory.GetShare(newFolderName)); - newFolderName = detectedFolderName; - } - else - { - return true; - } - } - else - { - wakeOnLanEnabled = _virtualDirectory.IsWakeOnLanEnabled(_virtualDirectory.GetShare(newFolderName)); - } - - string serverName = string.Empty; - - if (wakeOnLanEnabled) - { - serverName = Util.Utils.GetServerNameFromUNCPath(newFolderName); - - DateTime now = DateTime.Now; - TimeSpan ts = now - _prevWolTime; - - if (serverName == _prevServerName && _wolResendTime*60 > ts.TotalSeconds) - { - return true; - } - - _prevWolTime = DateTime.Now; - _prevServerName = serverName; - - try - { - Log.Debug("WakeUpSrv: FolderName = {0}, ShareName = {1}, WOL enabled = {2}", newFolderName, - _virtualDirectory.GetShare(newFolderName).Name, wakeOnLanEnabled); - } - catch - { - } - - if (!string.IsNullOrEmpty(serverName)) - { - return WakeupUtils.HandleWakeUpServer(serverName, _wolTimeout); - } - } - return true; - } - - private void LoadDirectory(string newFolderName, bool useCache) - { - if (newFolderName == null) - { - Log.Warn("GUIVideoFiles::LoadDirectory called with invalid argument. newFolderName is null!"); - return; - } - - if (facadeLayout == null) - { - return; - } - - if (!WakeUpSrv(newFolderName)) - { - return; - } - - GUIWaitCursor.Show(); - - if (_videoFolderWatcher != null && _videoFolderWatcher.GetPendingEventsCount > 0) - { - useCache = false; - } - - if (_videoFolderWatcher != null) - { - _videoFolderWatcher.ChangeMonitoring(false); - } - - if (!string.IsNullOrEmpty(newFolderName)) - { - _videoFolderWatcher = new VideoFolderWatcherHelper(newFolderName); - _videoFolderWatcher.SetMonitoring(true); - _videoFolderWatcher.StartMonitor(); - } - - if (newFolderName != _currentFolder && _mapSettings != null) - { - SaveFolderSettings(_currentFolder); - } - - if (newFolderName != _currentFolder || _mapSettings == null) - { - LoadFolderSettings(newFolderName); - } - // Image file is not listed as a valid movie so we need to handle it - // as a folder and enable browsing for it - if (VirtualDirectory.IsImageFile(Path.GetExtension(newFolderName))) - { - if (!MountImageFile(GetID, newFolderName, true)) - { - return; - } - - _currentFolder = DaemonTools.GetVirtualDrive(); - } - else - { - _currentFolder = newFolderName; - } - - IMDBMovie.ResetMovieProperties(); // Clear skin properties values - GUIControl.ClearControl(GetID, facadeLayout.GetID); - List itemlist = null; - List itemlist2 = new List(); // for GetMediaInfoThread - ISelectDVDHandler selectDvdHandler = GetSelectDvdHandler(); - ISelectBDHandler selectBDHandler = GetSelectBDHandler(); - - //Tweak to boost performance when starting/stopping playback - //For further details see comment in Core\Util\VirtualDirectory.cs - if (!string.IsNullOrEmpty(_currentFolder) && useCache && _cachedDir == _currentFolder && _cachedItems != null && _cachedItems.Count > 0) - { - itemlist = _cachedItems; - int currentItemIndex = 0; - - foreach (GUIListItem item in itemlist) - { - - // Get last watch status (IMDBMovie containes old one in caced objects) - string file = item.Path; - int percentWatched = 0; - int timesWatched = 0; - int movieId = VideoDatabase.GetMovieId(file); - bool played = VideoDatabase.GetmovieWatchedStatus(movieId, out percentWatched, out timesWatched); - - if (_mapSettings != null && _mapSettings.Stack) - { - item.Duration = VideoDatabase.GetMovieDuration(movieId); - } - else - { - int fileID = VideoDatabase.GetFileId(item.Path); - item.Duration = VideoDatabase.GetVideoDuration(fileID); - } - - // set label 1 & 2 - SetLabel(item); - - // Set watched status and label 3 - if (item.IsBdDvdFolder || Util.Utils.IsVideo(item.Path)) - { - // Check db for watched status for played movie or changed status in movie info window - - if (item.IsFolder) - { - file = selectDvdHandler.GetFolderVideoFile(item.Path); - - if (file == string.Empty) - { - file = selectBDHandler.GetFolderVideoFile(item.Path); - } - } - - // Update full IMDBMovie object for last selected item (Movie info screen can change many info data) - if (currentItemIndex == _currentSelectedItem) - { - IMDBMovie.SetMovieData(item); - } - else - { - // Update watch statuses for other items - IMDBMovie movie = item.AlbumInfoTag as IMDBMovie; - - if (movie != null) - { - movie.WatchedPercent = percentWatched; - movie.WatchedCount = timesWatched; - - if (played) - { - movie.Watched = 1; - } - - item.AlbumInfoTag = movie; - } - } - - if (_markWatchedFiles) - { - item.IsPlayed = played; - } - - if (item.IsBdDvdFolder) - { - if (selectDvdHandler.IsDvdDirectory(item.Path)) - { - item.Label3 = MediaTypes.DVD.ToString() + " " + percentWatched + "% #" + timesWatched; - item.Label2 = string.Empty; - } - else - { - item.Label3 = MediaTypes.BD.ToString() + " " + percentWatched + "% #" + timesWatched; - item.Label2 = string.Empty; - } - } - else if (VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) - { - item.Label3 = MediaTypes.ISO.ToString() + " " + percentWatched + "% #" + timesWatched; - } - else - { - item.Label3 = percentWatched + "% #" + timesWatched; - } - if (movieId < 0 || movieId != -1 && item.Duration == 0) - { - itemlist2.Add(item); - } - } - - if (!item.IsFolder) - { - item.HasProgressBar = true; - item.ProgressBarPercentage = percentWatched; - } - - //Do NOT add OnItemSelected event handler here, because its still there... - - if (item.IsFolder || !item.IsFolder && !_hideWatchedFiles && item.IsPlayed || !item.IsFolder && !item.IsPlayed) - { - facadeLayout.Add(item); - currentItemIndex++; - } - } - } // End Cached items - else - { - _removableDrivesHandlerThread.Join(); - - // here we get ALL files in every subdir, look for folderthumbs, defaultthumbs, etc - itemlist = _virtualDirectory.GetDirectoryExt(_currentFolder); - - if (_currentFolder == string.Empty) - { - RemovableDrivesHandler.FilterDrives(ref itemlist); - } - - if (_mapSettings != null && _mapSettings.Stack) - { - Dictionary> stackings = new Dictionary>(itemlist.Count); - - for (int i = 0; i < itemlist.Count; ++i) - { - - GUIListItem item1 = itemlist[i]; - string cleanFilename = item1.Label; - Util.Utils.RemoveStackEndings(ref cleanFilename); - List innerList; - - if (stackings.TryGetValue(cleanFilename, out innerList)) - { - for (int j = 0; j < innerList.Count; j++) - { - GUIListItem item2 = innerList[j]; - - if (((!item1.IsFolder || !item2.IsFolder) || (item1.IsFolder && IsMovieFolder(item1.Path) || item2.IsFolder && IsMovieFolder(item2.Path))) - && (!item1.IsRemote && !item2.IsRemote) - && Util.Utils.ShouldStack(item1.Path, item2.Path)) - { - if (String.Compare(item1.Path, item2.Path, StringComparison.OrdinalIgnoreCase) > 0) - { - item2.FileInfo.Length += item1.FileInfo.Length; - } - else - { - // keep item1, it's path is lexicographically before item2 path - item1.FileInfo.Length += item2.FileInfo.Length; - innerList[j] = item1; - } - item1 = null; - break; - } - } - - if (item1 != null) // not stackable - { - innerList.Add(item1); - } - } - else - { - innerList = new List { item1 }; - stackings.Add(cleanFilename, innerList); - } - } - - foreach (KeyValuePair> pair in stackings) - { - List innerList = pair.Value; - - for (int i = 0; i < innerList.Count; i++) - { - GUIListItem item = innerList[i]; - bool isMovieFolder = false; - - if (!string.IsNullOrEmpty(newFolderName) || UNCTools.UNCFileFolderExists(item.Path, _virtualDirectory.GetShareHostDetectMethod(item.Path))) - { - if (item.IsFolder) - { - isMovieFolder = IsMovieFolder(item.Path); - } - else - { - isMovieFolder = false; - } - - if (VirtualDirectory.IsValidExtension(item.Path, Util.Utils.VideoExtensions, false) || isMovieFolder) - { - item.Label = pair.Key; - } - } - int percentWatched = 0; - // Check db for watched status for played movie or changed status in movie info window - string file = item.Path; - if (!item.IsFolder || isMovieFolder) - { - // Special folders (DVD/Blu-Ray) - if (isMovieFolder) - { - item.IsBdDvdFolder = true; - file = selectDvdHandler.GetFolderVideoFile(item.Path); - - if (file == string.Empty) - { - file = selectBDHandler.GetFolderVideoFile(item.Path); - } - } - - int timesWatched = 0; - int movieId = VideoDatabase.GetMovieId(file); - bool played = VideoDatabase.GetmovieWatchedStatus(movieId, out percentWatched, out timesWatched); - - item.Duration = VideoDatabase.GetMovieDuration(movieId); - - if (_markWatchedFiles) - { - item.IsPlayed = played; - } - - if (item.IsBdDvdFolder) - { - if (selectDvdHandler.IsDvdDirectory(item.Path)) - { - item.Label3 = MediaTypes.DVD.ToString() + " " + percentWatched + "% #" + timesWatched; - item.Label2 = string.Empty; - } - else - { - item.Label3 = MediaTypes.BD.ToString() + " " + percentWatched + "% #" + timesWatched; - item.Label2 = string.Empty; - } - } - else if (VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) - { - item.Label3 = MediaTypes.ISO.ToString() + " " + percentWatched + "% #" + timesWatched; - } - else - { - item.Label3 = percentWatched + "% #" + timesWatched; - } - if (movieId < 0 || movieId != -1 && item.Duration == 0) - { - itemlist2.Add(item); - } - } - - SetLabel(item); - item.OnItemSelected += item_OnItemSelected; - - if (!item.IsFolder) - { - item.HasProgressBar = true; - item.ProgressBarPercentage = percentWatched; - } - - if (item.IsFolder || !item.IsFolder && !_hideWatchedFiles && item.IsPlayed || !item.IsFolder && !item.IsPlayed) - { - facadeLayout.Add(item); - } - } - } - itemlist = facadeLayout.ListLayout.ListItems; - } - else - { - foreach (GUIListItem item in itemlist) - { - // Check db for watched status for played movie or changed status in movie info window - string file = item.Path; - bool isMovieFolder; - - if (item.IsFolder) - { - isMovieFolder = IsMovieFolder(item.Path); - } - else - { - isMovieFolder = false; - } - - int percentWatched = 0; - - if (!item.IsFolder || isMovieFolder) - { - // Special folders (DVD/BluRay) - if (isMovieFolder) - { - item.IsBdDvdFolder = true; - file = selectDvdHandler.GetFolderVideoFile(item.Path); - - if (file == string.Empty) - { - file = selectBDHandler.GetFolderVideoFile(item.Path); - } - } - - int timesWatched = 0; - int movieId = VideoDatabase.GetMovieId(file); - bool played = VideoDatabase.GetmovieWatchedStatus(movieId, out percentWatched, out timesWatched); - - int fileID = VideoDatabase.GetFileId(item.Path); - item.Duration = VideoDatabase.GetVideoDuration(fileID); - - if (_markWatchedFiles) - { - item.IsPlayed = played; - } - - if (item.IsBdDvdFolder) - { - if (selectDvdHandler.IsDvdDirectory(item.Path)) - { - item.Label3 = MediaTypes.DVD.ToString() + " " + percentWatched + "% #" + timesWatched; - } - else - { - item.Label3 = MediaTypes.BD.ToString() + " " + percentWatched + "% #" + timesWatched; - } - } - else if (VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) - { - item.Label3 = MediaTypes.ISO.ToString() + " " + percentWatched + "% #" + timesWatched; - } - else - { - item.Label3 = percentWatched + "% #" + timesWatched; - } - if (movieId < 0 || movieId != -1 && item.Duration == 0) - { - itemlist2.Add(item); - } - } - - SetLabel(item); - item.OnItemSelected += item_OnItemSelected; - - if (!item.IsFolder) - { - item.HasProgressBar = true; - item.ProgressBarPercentage = percentWatched; - } - - if (item.IsFolder || !item.IsFolder && !_hideWatchedFiles && item.IsPlayed || !item.IsFolder && !item.IsPlayed) - { - facadeLayout.Add(item); - } - } - } - } // End non cache items - - facadeLayout.Sort(new VideoSort(CurrentSortMethod, CurrentSortAsc)); - UpdateButtonStates(); - - if (_cachedItems != null) - { - _cachedItems.Clear(); - _cachedItems.AddRange(facadeLayout.ListLayout.ListItems); - } - - _cachedDir = _currentFolder; - - // Update thumbs for all items (cached also - > cover can be changed in VideoInfoScreen and if we do - // not update cover, old one will be visible) - SetImdbThumbs(itemlist, selectDvdHandler); - - int selectedIndex = -1; - Int32.TryParse(_history.Get(_currentFolder), out selectedIndex); - int maxIndex = itemlist.Count - 1; - - if (maxIndex >= selectedIndex) - { - GUIControl.SelectItemControl(GetID, facadeLayout.GetID, selectedIndex); - } - - int totalItems = itemlist.Count; - - if (totalItems > 0) - { - GUIListItem rootItem = itemlist[0]; - if (rootItem.Label == "..") - { - totalItems--; - } - } - else - { - if (_resetCount == 0) - { - _resetCount++; - ResetShares(); - - if (_virtualDirectory.DefaultShare != null && _virtualDirectory.DefaultShare.Path != string.Empty) - { - LoadDirectory(_virtualDirectory.DefaultShare.Path, false); - } - else - { - LoadDirectory(string.Empty, false); - } - - GUIWaitCursor.Hide(); - return; - } - } - - //set object count label - GUIPropertyManager.SetProperty("#itemcount", Util.Utils.GetObjectCountLabel(totalItems)); - - // Reload thumbs if previous load thumb thread aborted (only when cache is active) - // If thumb thread was aborted and on next loaddirectory with cache "on", some thumbs - // can be missing and wan't be loaded, so here we reload them again. - if (_setThumbsThreadAborted) - { - SetImdbThumbs(itemlist, selectDvdHandler); - } - - // if have new item we close the previous thread and start a new one - if ((_addVideoFilesToDb || CurrentSortMethod == VideoSort.SortMethod.Name_With_Duration) && itemlist2.Count != 0) - { - try - { - if (_getMediaInfoThread != null &&_getMediaInfoThread.IsAlive) - { - // dont want to abort, rather send a signal and wait to finish, it is a clean exit - Log.Debug("GetMediaInfoThread: send an exit signal to the last thread and waiting for exit."); - _getMediaInfoThreadAbort = true; - _getMediaInfoThread.Join(); - Log.Debug("GetMediaInfoThread: after join."); - } - } +#region Copyright (C) 2005-2023 Team MediaPortal + +// Copyright (C) 2005-2023 Team MediaPortal +// http://www.team-mediaportal.com +// +// MediaPortal is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 2 of the License, or +// (at your option) any later version. +// +// MediaPortal is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with MediaPortal. If not, see . + +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Xml; +using System.Xml.Serialization; +using CSScriptLibrary; +using Common.GUIPlugins; +using MediaPortal.Configuration; +using MediaPortal.Database; +using MediaPortal.Dialogs; +using MediaPortal.GUI.Library; +using MediaPortal.GUI.View; +using MediaPortal.Player; +using MediaPortal.Playlists; +using MediaPortal.Services; +using MediaPortal.Util; +using MediaPortal.Video.Database; +using MediaPortal.Player.Subtitles; +using MediaPortal.Profile; +using Action = MediaPortal.GUI.Library.Action; +using Layout = MediaPortal.GUI.Library.GUIFacadeControl.Layout; + +#pragma warning disable 108 + +namespace MediaPortal.GUI.Video +{ + internal class ComboBoxItemDatabase + { + public string Database; + public string Name; + public string Language; + public string Limit; + + public override string ToString() + { + return String.Format("{0}: {1} [{2}]", Language, Name, Database); + } + } + + /// + /// MyVideo GUI class when not using DB driven views. + /// + [PluginIcons("GUIVideos.Video.gif", "GUIVideos.VideoDisabled.gif")] + public class GUIVideoFiles : GUIVideoBaseWindow, ISetupForm, IShowPlugin, IMDB.IProgress + { + #region map settings + + [Serializable] + public class MapSettings + { + protected int _SortBy; + protected int _ViewAs; + protected bool _Stack; + protected bool _SortAscending; + + public MapSettings() + { + _SortBy = 0; //name + _ViewAs = 0; //list + _Stack = true; + _SortAscending = true; + } + + [XmlElement("SortBy")] + public int SortBy + { + get { return _SortBy; } + set { _SortBy = value; } + } + + [XmlElement("ViewAs")] + public int ViewAs + { + get { return _ViewAs; } + set { _ViewAs = value; } + } + + [XmlElement("Stack")] + public bool Stack + { + get { return _Stack; } + set { _Stack = value; } + } + + [XmlElement("SortAscending")] + public bool SortAscending + { + get { return _SortAscending; } + set { _SortAscending = value; } + } + } + + #endregion + + #region variables + + public static int _getMediaInfoThreadNumber = 0; + public static Thread _getMediaInfoThread; + private static bool _getMediaInfoThreadAbort = false; + private Thread _refreshMediaInfoThread; + private static bool _refreshMediaInfoThreadAbort = false; + private static bool _askBeforePlayingDVDImage; + private static VirtualDirectory _virtualDirectory; + private static string _currentFolder = string.Empty; + private static PlayListPlayer _playlistPlayer; + private static PlayListType _currentPlaylistType; + private static int _currentPlaylistIndex = -1; + private static Thread _removableDrivesHandlerThread; + private VideoFolderWatcherHelper _videoFolderWatcher; + private MapSettings _mapSettings = new MapSettings(); + private DirectoryHistory _history = new DirectoryHistory(); + private string _virtualStartDirectory = string.Empty; + private int _currentSelectedItem = -1; + + // File menu + private string _fileMenuDestinationDir = string.Empty; + private bool _fileMenuEnabled; + private string _fileMenuPinCode = string.Empty; + + private bool _addVideoFilesToDb; // add automatically video files to database for show video duration in list view + private bool _scanning; + private int _scanningFileNumber = 1; + private int _scanningFileTotal = 1; + private bool _isFuzzyMatching; + private bool _scanSkipExisting; + private bool _getActors = true; + private bool _markWatchedFiles = true; + private bool _hideWatchedFiles = false; + private ArrayList _conflictFiles = new ArrayList(); + private bool _switchRemovableDrives; + // Stacked files duration - for watched status/also used in GUIVideoTitle + public static int TotalMovieDuration; + public static ArrayList StackedMovieFiles = new ArrayList(); + public static bool IsStacked; + + private List _cachedItems = new List(); + private string _cachedDir; + + private bool _resetSMSsearch; + private bool _oldStateSMSsearch; + private DateTime _resetSMSsearchDelay; + + private int _howToPlayAll = 3; + //Video info in share view before play + private bool _videoInfoInShare; + private bool _playClicked; + + // external player + private static bool _useInternalVideoPlayer = true; + private static bool _useInternalDVDVideoPlayer = true; + private static string _externalPlayerExtensions = string.Empty; + + private int _watchedPercentage = 95; + public static GUIListItem CurrentSelectedGUIItem; + + private Thread _setThumbs; + private List _threadGUIItems = new List(); + private ISelectDVDHandler _threadISelectDVDHandler; + private bool _setThumbsThreadAborted; + + // grabber index holds information/urls of available grabbers to download + private static string _grabberIndexFile = Config.GetFile(Config.Dir.Config, "MovieInfoGrabber.xml"); + private static string _grabberIndexUrl = @"http://install.team-mediaportal.com/MP1/MovieInfoGrabber_V16.xml"; + private static Dictionary _grabberList; + + private int _resetCount; + private string _selectedFilename = string.Empty; + + //Internal BDInternalMenu + private static bool _BDInternalMenu = true; + private static bool _BDDetect = false; + + private bool _useSortTitle = false; + private bool _useOnlyNfoScraper = false; + private bool _doNotUseDatabase = false; + + private static string _prevServerName = string.Empty; + private static DateTime _prevWolTime; + private static int _wolTimeout; + private static int _wolResendTime; + private GUIDialogProgress _progressDialogForUpdateMediaInfo; + + #endregion + + #region constructors + + static GUIVideoFiles() + { + _playlistPlayer = PlayListPlayer.SingletonPlayer; + } + + public GUIVideoFiles() + { + GetID = (int)Window.WINDOW_VIDEOS; + } + + #endregion + + #region Overrides + + protected override bool CurrentSortAsc + { + get { return _mapSettings.SortAscending; } + set { _mapSettings.SortAscending = value; } + } + + protected override VideoSort.SortMethod CurrentSortMethod + { + get { return (VideoSort.SortMethod)_mapSettings.SortBy; } + set { _mapSettings.SortBy = (int)value; } + } + + protected override Layout CurrentLayout + { + get { return (Layout)_mapSettings.ViewAs; } + set { _mapSettings.ViewAs = (int)value; } + } + + public override bool Init() + { + return Load(GUIGraphicsContext.GetThemedSkinFile(@"\myVideo.xml")); + } + + public override void OnAdded() + { + base.OnAdded(); + new IMDB(this); + g_Player.PlayBackStopped += OnPlayBackStopped; + g_Player.PlayBackEnded += OnPlayBackEnded; + g_Player.PlayBackStarted += OnPlayBackStarted; + g_Player.PlayBackChanged += OnPlayBackChanged; + GUIWindowManager.Receivers += GUIWindowManager_OnNewMessage; + LoadSettings(); + + _removableDrivesHandlerThread = new Thread(ListRemovableDrives); + _removableDrivesHandlerThread.IsBackground = true; + _removableDrivesHandlerThread.Name = "VideoRemovableDrivesHandlerThread"; + _removableDrivesHandlerThread.Start(); + } + + private void ListRemovableDrives() + { + RemovableDrivesHandler.ListRemovableDrives(_virtualDirectory.GetDirectoryExt(string.Empty)); + } + + protected override void OnSearchNew() + { + if (_doNotUseDatabase) + { + GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK); + dlgOk.SetHeading(string.Empty); + dlgOk.SetLine(1, GUILocalizeStrings.Get(416)); // Not available + dlgOk.DoModal(GUIWindowManager.ActiveWindow); + return; + } + + int maximumShares = 128; + ArrayList availablePaths = new ArrayList(); + + using (Profile.Settings xmlreader = new MPSettings()) + { + for (int index = 0; index < maximumShares; index++) + { + string sharePath = String.Format("sharepath{0}", index); + string shareDir = xmlreader.GetValueAsString("movies", sharePath, ""); + string shareScan = String.Format("sharescan{0}", index); + bool shareScanData = xmlreader.GetValueAsBool("movies", shareScan, true); + + if (shareScanData && shareDir != string.Empty) + { + availablePaths.Add(shareDir); + } + } + + ArrayList nfoFiles = new ArrayList(); + + foreach (string availablePath in availablePaths) + { + GetNfoFiles(availablePath, ref nfoFiles); + } + + if (!_useOnlyNfoScraper) // Normal scraper + { + // First try nfo files + IMDBFetcher fetcher = new IMDBFetcher(this); + fetcher.FetchNfo(nfoFiles, true, false); + // Then video files without nfo + IMDBFetcher.ScanIMDB(this, availablePaths, true, true, true, false); + } + else + { + // Only nfo files + IMDBFetcher fetcher = new IMDBFetcher(this); + fetcher.FetchNfo(nfoFiles, true, false); + } + + // Send global message that movie is refreshed/scanned + GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VIDEOINFO_REFRESH, 0, 0, 0, 0, 0, null); + GUIWindowManager.SendMessage(msg); + + _currentSelectedItem = facadeLayout.SelectedListItemIndex; + + if (_currentSelectedItem > 0) + { + _currentSelectedItem--; + } + + LoadDirectory(_currentFolder); + + if (_currentSelectedItem >= 0) + { + GUIControl.SelectItemControl(GetID, facadeLayout.GetID, _currentSelectedItem); + } + } + } + + #region Serialisation + + protected override void LoadSettings() + { + base.LoadSettings(); + using (Profile.Settings xmlreader = new Profile.MPSettings()) + { + currentLayout = (Layout)xmlreader.GetValueAsInt(SerializeName, "layout", (int)Layout.List); + m_bSortAscending = xmlreader.GetValueAsBool(SerializeName, "sortasc", true); + VideoState.StartWindow = xmlreader.GetValueAsInt("movies", "startWindow", GetID); + VideoState.View = xmlreader.GetValueAsString("movies", "startview", "369"); + + // Prevent unaccesible My Videos from corrupted config + if (!IsVideoWindow(VideoState.StartWindow)) + { + VideoState.StartWindow = GetID; + VideoState.View = "369"; + } + + _addVideoFilesToDb = xmlreader.GetValueAsBool("gui", "addVideoFilesToDb", false); + _isFuzzyMatching = xmlreader.GetValueAsBool("movies", "fuzzyMatching", false); + _scanSkipExisting = xmlreader.GetValueAsBool("moviedatabase", "scanskipexisting", false); + _getActors = xmlreader.GetValueAsBool("moviedatabase", "getactors", true); + _markWatchedFiles = xmlreader.GetValueAsBool("movies", "markwatched", true); + //_eachFolderIsMovie = xmlreader.GetValueAsBool("movies", "eachFolderIsMovie", false); + _fileMenuEnabled = xmlreader.GetValueAsBool("filemenu", "enabled", true); + _fileMenuPinCode = Util.Utils.DecryptPassword(xmlreader.GetValueAsString("filemenu", "pincode", string.Empty)); + _howToPlayAll = xmlreader.GetValueAsInt("movies", "playallinfolder", 3); + _watchedPercentage = xmlreader.GetValueAsInt("movies", "playedpercentagewatched", 95); + _videoInfoInShare = xmlreader.GetValueAsBool("moviedatabase", "movieinfoshareview", false); + _BDInternalMenu = xmlreader.GetValueAsBool("bdplayer", "useInternalBDPlayer", true); + + _virtualDirectory = VirtualDirectories.Instance.Movies; + // External player + _useInternalVideoPlayer = xmlreader.GetValueAsBool("movieplayer", "internal", true); + _useInternalDVDVideoPlayer = xmlreader.GetValueAsBool("dvdplayer", "internal", true); + _externalPlayerExtensions = xmlreader.GetValueAsString("movieplayer", "extensions", ""); + + _wolTimeout = xmlreader.GetValueAsInt("WOL", "WolTimeout", 10); + _wolResendTime = xmlreader.GetValueAsInt("WOL", "WolResendTime", 1); + + if (_virtualStartDirectory == string.Empty) + { + if (_virtualDirectory.DefaultShare != null) + { + if (_virtualDirectory.DefaultShare.IsFtpShare) + { + //remote:hostname?port?login?password?folder + _currentFolder = _virtualDirectory.GetShareRemoteURL(_virtualDirectory.DefaultShare); + _virtualStartDirectory = _currentFolder; + } + else + { + _currentFolder = _virtualDirectory.DefaultShare.Path; + _virtualStartDirectory = _virtualDirectory.DefaultShare.Path; + } + } + } + + _askBeforePlayingDVDImage = xmlreader.GetValueAsBool("daemon", "askbeforeplaying", false); + + if (xmlreader.GetValueAsBool("movies", "rememberlastfolder", false)) + { + string lastFolder = xmlreader.GetValueAsString("movies", "lastfolder", _currentFolder); + if (VirtualDirectory.IsImageFile(Path.GetExtension(lastFolder))) + { + lastFolder = "root"; + } + if (lastFolder != "root") + { + _currentFolder = lastFolder; + } + } + + _switchRemovableDrives = xmlreader.GetValueAsBool("movies", "SwitchRemovableDrives", true); + _useOnlyNfoScraper = xmlreader.GetValueAsBool("moviedatabase", "useonlynfoscraper", false); + _doNotUseDatabase = xmlreader.GetValueAsBool("moviedatabase", "donotusedatabase", false); + + } + + if (_currentFolder.Length > 0 && _currentFolder == _virtualStartDirectory) + { + VirtualDirectory vDir = new VirtualDirectory(); + vDir.LoadSettings("movies"); + } + } + + protected override void SaveSettings() + { + base.SaveSettings(); + + using (Profile.Settings xmlwriter = new MPSettings()) + { + xmlwriter.SetValue(SerializeName, "layout", (int)currentLayout); + xmlwriter.SetValueAsBool(SerializeName, "sortasc", m_bSortAscending); + } + } + + #endregion + + protected override string SerializeName + { + get { return "myvideo"; } + } + + public override void OnAction(Action action) + { + if ((action.wID == Action.ActionType.ACTION_PREVIOUS_MENU) && (facadeLayout.Focus)) + { + GUIListItem item = facadeLayout[0]; + if ((item != null) && item.IsFolder && (item.Label == "..")) + { + _history.Set("0", _currentFolder); + LoadDirectory(item.Path); + return; + } + } + + if (action.wID == Action.ActionType.ACTION_PARENT_DIR) + { + GUIListItem item = facadeLayout[0]; + if ((item != null) && item.IsFolder && (item.Label == "..")) + { + _history.Set("0", _currentFolder); + LoadDirectory(item.Path); + } + return; + } + + if (action.wID == Action.ActionType.ACTION_DELETE_ITEM && _fileMenuEnabled) + { + ShowFileMenu(true); + } + + if (action.wID == Action.ActionType.ACTION_PLAY || action.wID == Action.ActionType.ACTION_MUSIC_PLAY) + { + _playClicked = true; + } + + if (action.wID == Action.ActionType.ACTION_EJECTCD) + { + GUIListItem item = facadeLayout.SelectedListItem; + if (item == null || item.Path == null || Util.Utils.getDriveType(item.Path) != 5) + { + Util.Utils.EjectCDROM(); + } + else + { + Util.Utils.EjectCDROM(Path.GetPathRoot(item.Path)); + } + + LoadDirectory(string.Empty); + } + + base.OnAction(action); + } + + protected override void OnPageLoad() + { + base.OnPageLoad(); + + if (!VideoDatabase.DbHealth) + { + GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); + pDlgOK.SetHeading(315); + pDlgOK.SetLine(1, string.Empty); + pDlgOK.SetLine(2, GUILocalizeStrings.Get(190010, new object[] { GUILocalizeStrings.Get(3) })); + pDlgOK.DoModal(GUIWindowManager.ActiveWindow); ; + } + if (!FolderSettings.DbHealth) + { + GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); + pDlgOK.SetHeading(315); + pDlgOK.SetLine(1, string.Empty); + pDlgOK.SetLine(2, GUILocalizeStrings.Get(190010, new object[] { GUILocalizeStrings.Get(190011) })); + pDlgOK.DoModal(GUIWindowManager.ActiveWindow); + } + + base.LoadSettings(); + bool result = false; + + if (_loadParameter != null && _loadParameter != string.Empty) + { + foreach (GUIListItem item in VirtualDirectories.Instance.Movies.GetRootExt()) + { + if (item.Label.ToUpper() == _loadParameter.ToUpper()) + { + _currentFolder = item.Path; + result = true; + base.SetView(0); + } + } + if (!result) + { + if (_loadParameter == "134") + { + base.SetView(0); + Log.Debug("GUIVideoFiles.OnPageLoad: selectedView.Name = share"); + } + else + { + try + { + string selectedView; + + try + { + selectedView = GUILocalizeStrings.Get(Convert.ToInt32(_loadParameter)); + } + catch + { + selectedView = _loadParameter; + } + + for (int i = 0; i < handler.Views.Count; i++) + { + if (handler.Views[i].LocalizedName == selectedView) + { + Log.Debug("GUIVideoFiles.OnPageLoad: selectedView.Name = {0}", handler.Views[i].LocalizedName); + + base.SetView(i + 1); + + break; + } + } + } + catch (Exception ex) + { + Log.Error("GUIVideoFiles.OnPageLoad: Exception {0}", ex); + } + } + } + } + + // This can't be in LoadSettings beacuse settings are loaded on MP start and it will disable SortTitle setting always + using (Profile.Settings xmlreader = new Profile.MPSettings()) + { + // Don't sort by sorttitle + _useSortTitle = xmlreader.GetValueAsBool("moviedatabase", "usesorttitle", false); + xmlreader.SetValueAsBool("moviedatabase", "usesorttitle", false); + } + + if (!KeepVirtualDirectory(PreviousWindowId)) + { + Reset(); + } + + if (!IsVideoWindow(PreviousWindowId) && IsFolderPinProtected(_cachedDir)) + { + //when the user left MyVideos completely make sure that we don't use the cache + //if folder is pin protected and reload the dir completly including PIN request etc. + _cachedItems.Clear(); + _cachedDir = null; + } + + if (VideoState.StartWindow != GetID) + { + GUIWindowManager.ReplaceWindow(VideoState.StartWindow); + return; + } + + _resetCount = 0; + + // Go to default share from main MP menu + if (_currentFolder == string.Empty) + { + _currentFolder = _virtualStartDirectory; + } + + LoadFolderSettings(_currentFolder); + + //OnPageLoad is sometimes called when stopping playback. + //So we use the cached version of the function here. + LoadDirectory(_currentFolder, true); + } + + protected override void OnPageDestroy(int newWindowId) + { + // set back Sort by sorttitle + using (Profile.Settings xmlwriter = new Profile.MPSettings()) + { + xmlwriter.SetValueAsBool("moviedatabase", "usesorttitle", _useSortTitle); + } + + if (_videoFolderWatcher != null) + { + _videoFolderWatcher.PauseMonitoring(true); + } + + if (_setThumbs != null && _setThumbs.IsAlive) + { + _setThumbs.Abort(); + _setThumbs = null; + } + + // Set folder history when video window is not actually left (ie.: play movie, video info..) + if (IsVideoWindow(newWindowId)) + { + if (facadeLayout != null) + { + _history.Set(facadeLayout.SelectedListItemIndex.ToString(), _currentFolder); + } + } + else // For real exit (ie.: to home, reset folder history) + { + _history.Set("0", _currentFolder); + } + + SaveFolderSettings(_currentFolder); + ReleaseResources(); + base.OnPageDestroy(newWindowId); + } + + public override bool OnMessage(GUIMessage message) + { + switch (message.Message) + { + case GUIMessage.MessageType.GUI_MSG_CD_REMOVED: + if (g_Player.Playing && g_Player.IsDVD && + message.Label.Equals(g_Player.CurrentFile.Substring(0, 2), StringComparison.InvariantCultureIgnoreCase)) + // test if it is our drive + { + Log.Info("GUIVideoFiles: Stop dvd since DVD is ejected"); + g_Player.Stop(); + } + + if (GUIWindowManager.ActiveWindow == GetID) + { + if (Util.Utils.IsDVD(_currentFolder)) + { + _currentFolder = string.Empty; + LoadDirectory(_currentFolder); + } + } + break; + + case GUIMessage.MessageType.GUI_MSG_FILE_DOWNLOADING: + facadeLayout.OnMessage(message); + break; + + case GUIMessage.MessageType.GUI_MSG_FILE_DOWNLOADED: + + facadeLayout.OnMessage(message); + break; + + case GUIMessage.MessageType.GUI_MSG_VIDEOFILE_CREATED: + AddItem(message.Label, -1); + break; + + case GUIMessage.MessageType.GUI_MSG_VIDEOFILE_DELETED: + DeleteItem(message.Label); + SelectCurrentItem(); + break; + + case GUIMessage.MessageType.GUI_MSG_VIDEOFILE_RENAMED: + ReplaceItem(message.Label2, message.Label); + SelectCurrentItem(); + break; + + case GUIMessage.MessageType.GUI_MSG_VIDEODIRECTORY_CREATED: + AddItem(message.Label, -1); + break; + + case GUIMessage.MessageType.GUI_MSG_VIDEODIRECTORY_DELETED: + DeleteItem(message.Label); + SelectCurrentItem(); + break; + + case GUIMessage.MessageType.GUI_MSG_VIDEODIRECTORY_RENAMED: + ReplaceItem(message.Label2, message.Label); + SelectCurrentItem(); + break; + + case GUIMessage.MessageType.GUI_MSG_SHOW_DIRECTORY: + // Make sure file view is the current window + if (VideoState.StartWindow != GetID) + { + VideoState.StartWindow = GetID; + Reset(); + GUIWindowManager.ReplaceWindow(GetID); + } + _currentFolder = message.Label; + LoadDirectory(_currentFolder); + break; + + case GUIMessage.MessageType.GUI_MSG_ADD_REMOVABLE_DRIVE: + if (_switchRemovableDrives) + { + _currentFolder = message.Label; + if (!Util.Utils.IsRemovable(message.Label)) + { + _virtualDirectory.AddRemovableDrive(message.Label, message.Label2); + } + } + if (_removableDrivesHandlerThread != null) + { + _removableDrivesHandlerThread.Join(); + } + + RemovableDrivesHandler.ListRemovableDrives(_virtualDirectory.GetDirectoryExt(string.Empty)); + LoadDirectory(_currentFolder); + break; + + case GUIMessage.MessageType.GUI_MSG_REMOVE_REMOVABLE_DRIVE: + if (!Util.Utils.IsRemovable(message.Label)) + { + _virtualDirectory.Remove(message.Label); + } + if (_currentFolder.Contains(message.Label)) + { + _currentFolder = string.Empty; + } + LoadDirectory(_currentFolder); + break; + + case GUIMessage.MessageType.GUI_MSG_VOLUME_INSERTED: + case GUIMessage.MessageType.GUI_MSG_VOLUME_REMOVED: + if (_currentFolder == string.Empty || _currentFolder.Substring(0, 2) == message.Label) + { + _currentFolder = string.Empty; + LoadDirectory(_currentFolder); + } + break; + + case GUIMessage.MessageType.GUI_MSG_PLAY_DVD: + OnPlayDVD(message.Label, GetID); + break; + + case GUIMessage.MessageType.GUI_MSG_LAYOUT_CHANGED: + FolderSetting folderSetting = new FolderSetting(); + folderSetting.UpdateFolders(-1, CurrentSortAsc, (int)CurrentLayout); + break; + + case GUIMessage.MessageType.GUI_MSG_REFRESH_MEDIAINFO: + SelectCurrentItem(); + break; + } + return base.OnMessage(message); + } + + protected override void LoadDirectory(string newFolderName) + { + this.LoadDirectory(newFolderName, false); + } + + protected override void OnClick(int iItem) + { + GUIListItem item = facadeLayout.SelectedListItem; + TotalMovieDuration = 0; + IsStacked = false; + StackedMovieFiles.Clear(); + + if (item == null) + { + _playClicked = false; + return; + } + + if (!WakeUpSrv(item.Path)) + { + return; + } + + string path = item.Path; + + if (item.IsBdDvdFolder) + { + // Check if folder is actually a DVD. If so don't browse this folder, but play the DVD! + if (File.Exists(path + @"\VIDEO_TS\VIDEO_TS.IFO")) + { + path = item.Path + @"\VIDEO_TS\VIDEO_TS.IFO"; + } + // Then it's a Blu-Ray. Play the Blu-Ray! + else + { + path = item.Path + @"\BDMV\index.bdmv"; + } + } + + if ((item.IsFolder && !item.IsBdDvdFolder)) + { + // Play all in folder + if (_playClicked) + { + if (!item.IsRemote && item.Label != ".." && !VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) + { + if (!_virtualDirectory.RequestPin(item.Path)) + { + _playClicked = false; + return; + } + + OnPlayAll(item.Path); + _playClicked = false; + } + } + else + { + _currentSelectedItem = -1; + + if (facadeLayout != null) + { + _history.Set(facadeLayout.SelectedListItemIndex.ToString(), _currentFolder); + } + + LoadDirectory(path, true); + } + } + else + { + if (!_virtualDirectory.RequestPin(path)) + { + _playClicked = false; + return; + } + + if (_virtualDirectory.IsRemote(path)) + { + if (!_virtualDirectory.IsRemoteFileDownloaded(path, item.FileInfo.Length)) + { + if (!_virtualDirectory.ShouldWeDownloadFile(path)) + { + _playClicked = false; + return; + } + + if (!_virtualDirectory.DownloadRemoteFile(path, item.FileInfo.Length)) + { + //show message that we are unable to download the file + GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SHOW_WARNING, 0, 0, 0, 0, 0, 0); + msg.Param1 = 916; + msg.Param2 = 920; + msg.Param3 = 0; + msg.Param4 = 0; + GUIWindowManager.SendMessage(msg); + _playClicked = false; + return; + } + //download subtitle files + Thread subLoaderThread = new Thread(DownloadSubtitles); + subLoaderThread.IsBackground = true; + subLoaderThread.Name = "SubtitleLoader"; + subLoaderThread.Start(); + } + } + + if (item.FileInfo != null) + { + if (!_virtualDirectory.IsRemoteFileDownloaded(path, item.FileInfo.Length)) + { + _playClicked = false; + return; + } + } + + string movieFileName = path; + movieFileName = _virtualDirectory.GetLocalFilename(movieFileName); + + if (PlayListFactory.IsPlayList(movieFileName)) + { + LoadPlayList(movieFileName); + _playClicked = false; + return; + } + + if (!CheckMovie(movieFileName)) + { + _playClicked = false; + return; + } + + if (_videoInfoInShare && VideoDatabase.HasMovieInfo(movieFileName) && !_playClicked) + { + OnInfo(facadeLayout.SelectedListItemIndex); + return; + } + + bool askForResumeMovie = true; + _playClicked = false; + + #region StackEnabled and file is stackable + + // Proceed to file stack check if file is stackable + if (_mapSettings.Stack && IsFileStackable(movieFileName)) + { + IsStacked = true; + int selectedFileIndex = 0; + int movieDuration = 0; + ArrayList movies = new ArrayList(); + List items = new List(); + IMDBMovie movie = item.AlbumInfoTag as IMDBMovie; + + // This will return all stackable files for current clicked item + // Also will add all stackable files to videodatabase if they are not exist + StackedMovieFiles = AddFileToDatabase(movieFileName); + + // Add movie files to list + foreach (string file in StackedMovieFiles) + { + FileInformation fi = new FileInformation(); + GUIListItem itemMovie = new GUIListItem(Util.Utils.GetFilename(file), "", file, false, fi); + items.Add(itemMovie); + } + + // In the list must be at least 2 files so we check stackable movie for resume + // (which file have a stop time) + bool asked = false; + string title = item.Label; // Dlg title + + if (movie != null && !movie.IsEmpty) + { + title = movie.Title; + } + + for (int i = 0; i < items.Count; ++i) + { + IMDBMovie.SetMovieData(items[i]); // This will set IMDBMovie object and it will never be null + movie = items[i].AlbumInfoTag as IMDBMovie; + + if (!asked) + { + selectedFileIndex++; + } + + int idFile = VideoDatabase.GetFileId(movie.VideoFileName); + + if (idFile != -1) + { + int timeMovieStopped = VideoDatabase.GetMovieStopTime(idFile); + + if (timeMovieStopped > 0) + { + if (!asked) + { + asked = true; + GUIResumeDialog.Result result = + GUIResumeDialog.ShowResumeDialog(title, movieDuration + timeMovieStopped, + GUIResumeDialog.MediaType.Video); + + if (result == GUIResumeDialog.Result.Abort) + { + _playlistPlayer.Reset(); + _playlistPlayer.CurrentPlaylistType = _currentPlaylistType; + _playlistPlayer.CurrentSong = _currentPlaylistIndex; + return; + } + + if (result == GUIResumeDialog.Result.PlayFromBeginning) + { + VideoDatabase.DeleteMovieStopTime(idFile); + } + else + { + askForResumeMovie = false; + } + } + } + + // Total movie duration + movieDuration += VideoDatabase.GetVideoDuration(idFile); + TotalMovieDuration = movieDuration; + } + } + + for (int i = 0; i < items.Count; ++i) + { + GUIListItem temporaryListItem = (GUIListItem)items[i]; + movie = (IMDBMovie)temporaryListItem.AlbumInfoTag; + + if (Util.Utils.IsVideo(movie.VideoFileName) && !PlayListFactory.IsPlayList(movie.VideoFileName)) + { + movies.Add(movie.VideoFileName); + } + } + + if (movies.Count == 0) + { + movies.Add(movieFileName); + } + + if (movies.Count > 1) + { + movies.Sort(); + + // Stacked movies duration + if (TotalMovieDuration == 0) + { + MovieDuration(movies, false); + StackedMovieFiles = movies; + } + + // Ask for resume + if (askForResumeMovie) + { + GUIDialogFileStacking dlg = + (GUIDialogFileStacking)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_FILESTACKING); + + if (null != dlg) + { + dlg.SetFiles(movies); + dlg.DoModal(GetID); + selectedFileIndex = dlg.SelectedFile; + + if (selectedFileIndex < 1) + { + return; + } + } + } + } + // This can happen if user have one file and it is stackable (filename ends with CDx...) + else + { + MovieDuration(movies, false); + } + + // Get current playlist + _currentPlaylistType = new PlayListType(); + _currentPlaylistType = _playlistPlayer.CurrentPlaylistType; + _currentPlaylistIndex = _playlistPlayer.CurrentSong; + + _playlistPlayer.Reset(); + _playlistPlayer.CurrentPlaylistType = PlayListType.PLAYLIST_VIDEO_TEMP; + PlayList playlist = _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO_TEMP); + playlist.Clear(); + + for (int i = 0; i < (int)movies.Count; ++i) + { + movieFileName = (string)movies[i]; + PlayListItem itemNew = new PlayListItem(); + itemNew.FileName = movieFileName; + itemNew.Type = PlayListItem.PlayListItemType.Video; + playlist.Add(itemNew); + } + + // play movie...(2 or more files) + PlayMovieFromPlayList(askForResumeMovie, selectedFileIndex - 1, true); + return; + } + + #endregion + + #region StackDisabled or file not stackable + + // play movie...(only 1 file) + AddFileToDatabase(movieFileName); + + // Get current playlist + _currentPlaylistType = new PlayListType(); + _currentPlaylistType = _playlistPlayer.CurrentPlaylistType; + _currentPlaylistIndex = _playlistPlayer.CurrentSong; + + _playlistPlayer.Reset(); + _playlistPlayer.CurrentPlaylistType = PlayListType.PLAYLIST_VIDEO_TEMP; + PlayList newPlayList = _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO_TEMP); + newPlayList.Clear(); + PlayListItem NewItem = new PlayListItem(); + NewItem.FileName = movieFileName; + NewItem.Type = PlayListItem.PlayListItemType.Video; + newPlayList.Add(NewItem); + PlayMovieFromPlayList(true, true); + + #endregion + } + } + + protected override void OnQueueItem(int itemIndex) + { + // add item 2 playlist + GUIListItem listItem = facadeLayout[itemIndex]; + + if (listItem == null) + { + return; + } + + if (listItem.IsRemote) + { + return; + } + + if (!_virtualDirectory.RequestPin(listItem.Path)) + { + return; + } + + if (PlayListFactory.IsPlayList(listItem.Path)) + { + LoadPlayList(listItem.Path); + return; + } + + AddItemToPlayList(listItem); + + //move to next item + GUIControl.SelectItemControl(GetID, facadeLayout.GetID, itemIndex + 1); + } + + protected override void AddItemToPlayList(GUIListItem listItem) + { + if (listItem.IsFolder) + { + // recursive + if (listItem.Label == "..") + { + return; + } + + List itemlist = _virtualDirectory.GetDirectoryUnProtectedExt(listItem.Path, true); + + foreach (GUIListItem item in itemlist) + { + AddItemToPlayList(item); + } + } + else + { + if (Util.Utils.IsVideo(listItem.Path) && !PlayListFactory.IsPlayList(listItem.Path)) + { + PlayListItem playlistItem = new PlayListItem(); + playlistItem.FileName = listItem.Path; + playlistItem.Description = listItem.Label; + playlistItem.Duration = listItem.Duration; + playlistItem.Type = PlayListItem.PlayListItemType.Video; + _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO).Add(playlistItem); + } + } + } + + protected override void OnInfo(int iItem) + { + GUIListItem pItem = facadeLayout.SelectedListItem; + CurrentSelectedGUIItem = pItem; + + if (pItem == null || pItem.IsRemote || + !_virtualDirectory.RequestPin(pItem.Path) || + pItem.IsFolder && (!pItem.IsBdDvdFolder || pItem.Label == "..")) + { + return; + } + + IMDBMovie movieDetails = pItem.AlbumInfoTag as IMDBMovie; + + if (movieDetails == null) + { + return; + } + + if (_doNotUseDatabase && movieDetails.ID < 1) + { + if (string.IsNullOrEmpty(movieDetails.MovieNfoFile)) + { + return; + } + } + + if (movieDetails.ID < 1 && !_doNotUseDatabase) + { + + // Check for nfo file + if (_useOnlyNfoScraper && File.Exists(movieDetails.MovieNfoFile)) + { + // Import nfo into database + VideoDatabase.ImportNfo(movieDetails.MovieNfoFile, false, false); + // Refresh movie info + VideoDatabase.GetMovieInfo(movieDetails.VideoFileName, ref movieDetails); + } + else if (!Win32API.IsConnectedToInternet()) + { + if (File.Exists(movieDetails.MovieNfoFile)) + { + // Try nfo file + VideoDatabase.ImportNfo(movieDetails.MovieNfoFile, false, false); + // Refresh movie info + VideoDatabase.GetMovieInfo(movieDetails.VideoFileName, ref movieDetails); + // Send global message that movie is refreshed/scanned + GUIMessage msgNfo = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VIDEOINFO_REFRESH, 0, 0, 0, 0, 0, null); + GUIWindowManager.SendMessage(msgNfo); + return; + } + + GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); + dlgOk.SetHeading(257); + dlgOk.SetLine(1, GUILocalizeStrings.Get(703)); + dlgOk.DoModal(GUIWindowManager.ActiveWindow); + return; + } + else + { + if (File.Exists(movieDetails.MovieNfoFile)) + { + // Try nfo file + VideoDatabase.ImportNfo(movieDetails.MovieNfoFile, false, false); + // Refresh movie info + VideoDatabase.GetMovieInfo(movieDetails.VideoFileName, ref movieDetails); + } + else + { + bool isDedicatedMovieFolder = Util.Utils.IsFolderDedicatedMovieFolder(pItem.Path); + + if (isDedicatedMovieFolder) + { + if (pItem.IsBdDvdFolder) + { + movieDetails.SearchString = pItem.Label; + } + else + { + movieDetails.SearchString = Path.GetFileName(movieDetails.VideoFilePath); + } + } + else + { + // Remove extension from label if exist (when "Do not show file extesnion setting" is inactive) + movieDetails.SearchString = Util.Utils.GetFilename(pItem.Label, true); + } + + movieDetails.File = Path.GetFileName(movieDetails.VideoFileName); + Log.Info("GUIVideoFiles: IMDB search: {0}, file:{1}, path:{2}", movieDetails.SearchString, movieDetails.File, + movieDetails.Path); + + if (!IMDBFetcher.GetInfoFromIMDB(this, ref movieDetails, _isFuzzyMatching, false)) + { + return; + } + } + } + // Send global message that movie is refreshed/scanned + GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VIDEOINFO_REFRESH, 0, 0, 0, 0, 0, null); + GUIWindowManager.SendMessage(msg); + } + + // Open video info screen + GUIVideoInfo videoInfo = (GUIVideoInfo)GUIWindowManager.GetWindow((int)Window.WINDOW_VIDEO_INFO); + videoInfo.Movie = movieDetails; + + if (pItem.IsFolder) + { + videoInfo.FolderForThumbs = pItem.Path; + } + else + { + videoInfo.FolderForThumbs = string.Empty; + } + + GUIWindowManager.ActivateWindow((int)Window.WINDOW_VIDEO_INFO); + } + + protected override void SelectCurrentItem() + { + if (_currentSelectedItem >= 0) + { + GUIControl.SelectItemControl(GetID, facadeLayout.GetID, _currentSelectedItem); + } + else + { + GUIPropertyManager.SetProperty("#watchedcount", "-1"); + GUIPropertyManager.SetProperty("#videoruntime", string.Empty); + } + } + + protected override void OnShowContextMenu() + { + GUIListItem item = facadeLayout.SelectedListItem; + int itemNo = facadeLayout.SelectedListItemIndex; + GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_MENU); + + if (dlg == null) + { + return; + } + + dlg.Reset(); + dlg.SetHeading(498); // menu + + if (item == null) + { + dlg.AddLocalizedString(868); // Reset virtual directory + } + else if (item.IsRemote || (item.IsFolder) && (item.Label == "..") && _virtualDirectory.IsShareOfflineDetected()) + { + dlg.AddLocalizedString(868); // Force reset virtual directory if user want to refresh offline share + } + else if (item.IsRemote || (item.IsFolder) && (item.Label == "..")) + { + return; + } + else + { + IMDBMovie movie = item.AlbumInfoTag as IMDBMovie; + + if (!facadeLayout.Focus) + { + // Menu button context menuu + if (!_virtualDirectory.IsRemote(_currentFolder)) + { + dlg.AddLocalizedString(102); //Scan + dlg.AddLocalizedString(368); //IMDB + } + } + else + { + // DVD & files + if ((Path.GetFileName(item.Path) != string.Empty) || Util.Utils.IsDVD(item.Path)) + { + // DVD disc drive + if (Util.Utils.IsDVD(item.Path)) + { + if (File.Exists(item.Path + @"\VIDEO_TS\VIDEO_TS.IFO") || + File.Exists(item.Path + @"\BDMV\index.bdmv")) + { + dlg.AddLocalizedString(341); //play + } + else + { + dlg.AddLocalizedString(926); //Queue + dlg.AddLocalizedString(102); //Scan + } + + dlg.AddLocalizedString(368); //IMDB + } + // Folder + else if (item.IsFolder) + { + bool useMediaInfo = false; + + if (VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) + { + dlg.AddLocalizedString(208); //play + useMediaInfo = true; + } + + if (!VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) + { + // Simple folder + if (!item.IsBdDvdFolder) + { + dlg.AddLocalizedString(1204); // Play All in selected folder + dlg.AddLocalizedString(926); //Queue + dlg.AddLocalizedString(102); //Scan + dlg.AddLocalizedString(1280); // Scan using nfo files + dlg.AddLocalizedString(830); //Reset watched status + } + // DVD folder + else if (item.IsBdDvdFolder) + { + useMediaInfo = true; + dlg.AddLocalizedString(208); //play + dlg.AddLocalizedString(926); //Queue + dlg.AddLocalizedString(368); //IMDB + + if (movie != null && !movie.IsEmpty) + { + if (item.IsPlayed) + { + { + dlg.AddLocalizedString(830); //Reset watched status for DVD folder + } + } + else + { + dlg.AddLocalizedString(1260); // Set watched status + } + } + } + } + + if (!IsFolderPinProtected(item.Path) && _fileMenuEnabled) + { + dlg.AddLocalizedString(500); // FileMenu + } + + if (useMediaInfo) + { + dlg.AddLocalizedString(1264); //Media info + } + } + else + { + dlg.AddLocalizedString(208); //Play + dlg.AddLocalizedString(926); //Queue + dlg.AddLocalizedString(368); //IMDB + + if (item.IsPlayed) + { + dlg.AddLocalizedString(830); //Reset watched status + } + else + { + dlg.AddLocalizedString(1260); // Set watched status + } + + if (!IsFolderPinProtected(item.Path) && !item.IsRemote && _fileMenuEnabled) + { + dlg.AddLocalizedString(500); // FileMenu + } + dlg.AddLocalizedString(1264); //Media info + } + } + else if (Util.Utils.IsNetwork(item.Path)) // Process network root with drive letter + { + dlg.AddLocalizedString(1204); // Play All in selected folder + } + } + if (!_mapSettings.Stack) + { + dlg.AddLocalizedString(346); //Stack + } + else + { + dlg.AddLocalizedString(347); //Unstack + } + + #region Eject/Load + + // CD/DVD/BD + if (Util.Utils.getDriveType(item.Path) == 5) + { + if (item.Path != null) + { + var driveInfo = new DriveInfo(Path.GetPathRoot(item.Path)); + + // There is no easy way in NET to detect open tray so we will check + // if media is inside (load will be visible also in case that tray is closed but + // media is not loaded) + if (!driveInfo.IsReady) + { + dlg.AddLocalizedString(607); //Load + } + + dlg.AddLocalizedString(654); //Eject + } + } + + // Removable/USB HDD + if (Util.Utils.IsRemovable(item.Path) || Util.Utils.IsUsbHdd(item.Path)) + { + dlg.AddLocalizedString(831); + } + + #endregion + + dlg.AddLocalizedString(1299); // Refresh current directory + + if (_virtualDirectory.IsRootShare(item.Path) || _virtualDirectory.IsShareOfflineDetected()) + { + dlg.AddLocalizedString(868); // Force reset virtual directory if user want to refresh offline share + } + } + + dlg.AddLocalizedString(1262); // Update grabber scripts + dlg.AddLocalizedString(1307); // Update internal grabber scripts + dlg.AddLocalizedString(1263); // Set default grabber + + if (item != null && !item.IsFolder) + { + dlg.AddLocalizedString(1984); // Refresh thumb + if (!_hideWatchedFiles) + { + dlg.AddLocalizedString(2498); // Hide watched movies + } + else + { + dlg.AddLocalizedString(2499); // Unhide watched movies + } + } + + if (item != null && (item.IsFolder && item.Label != "..")) + { + dlg.AddLocalizedString(1995); // Create 4x4 folder.jpg + if (_refreshMediaInfoThread != null && _refreshMediaInfoThread.IsAlive) + { + dlg.AddLocalizedString(2161); // Abort Update MediaInfo thread in the folder + } + else + { + dlg.AddLocalizedString(2160); // Update MediaInfo in the folder + } + } + + dlg.DoModal(GetID); + + if (dlg.SelectedId == -1) + { + return; + } + switch (dlg.SelectedId) + { + case 368: // IMDB + OnInfo(itemNo); + break; + + case 208: // play + _playClicked = true; + OnClick(itemNo); + break; + + case 926: // add to playlist + OnQueueItem(itemNo); + break; + + case 136: // show playlist + GUIWindowManager.ActivateWindow((int)Window.WINDOW_VIDEO_PLAYLIST); + break; + + case 607: // Load (only CDROM) + Util.Utils.CloseCDROM(Path.GetPathRoot(item.Path)); + break; + + case 654: // Eject + if (item == null || item.Path == null || Util.Utils.getDriveType(item.Path) != 5) + { + Util.Utils.EjectCDROM(); + } + else + { + Util.Utils.EjectCDROM(Path.GetPathRoot(item.Path)); + } + + LoadDirectory(string.Empty); + break; + + case 341: //Play dvd + OnPlayDVD(item.Path, GetID); + break; + + case 346: //Stack + _mapSettings.Stack = true; + LoadDirectory(_currentFolder); + UpdateButtonStates(); + SaveFolderSettings(_currentFolder); + break; + + case 347: //Unstack + _mapSettings.Stack = false; + LoadDirectory(_currentFolder); + UpdateButtonStates(); + SaveFolderSettings(_currentFolder); + break; + + case 102: //Scan + if (_doNotUseDatabase) + { + GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK); + dlgOk.SetHeading(string.Empty); + dlgOk.SetLine(1, GUILocalizeStrings.Get(416)); // Not available + dlgOk.DoModal(GUIWindowManager.ActiveWindow); + return; + } + + if (facadeLayout.Focus) + { + if (item.IsFolder) + { + if (item.Label == "..") + { + return; + } + if (item.IsRemote) + { + return; + } + } + } + + if (!_virtualDirectory.RequestPin(item.Path)) + { + return; + } + + int currentIndex = facadeLayout.SelectedListItemIndex; + ArrayList scanNfoFiles = new ArrayList(); + GetNfoFiles(item.Path, ref scanNfoFiles); + + if (_useOnlyNfoScraper) + { + IMDBFetcher scanFetcher = new IMDBFetcher(this); + scanFetcher.FetchNfo(scanNfoFiles, true, false); + // Send global message that movie is refreshed/scanned + GUIMessage scanNfoMsg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VIDEOINFO_REFRESH, 0, 0, 0, 0, 0, null); + GUIWindowManager.SendMessage(scanNfoMsg); + LoadDirectory(_currentFolder); + facadeLayout.SelectedListItemIndex = currentIndex; + } + else + { + // Try nfo files first + IMDBFetcher scanFetcher = new IMDBFetcher(this); + scanFetcher.FetchNfo(scanNfoFiles, true, false); + // Then the rest + ArrayList availablePaths = new ArrayList(); + availablePaths.Add(item.Path); + IMDBFetcher.ScanIMDB(this, availablePaths, _isFuzzyMatching, true, _getActors, false); + // Send global message that movie is refreshed/scanned + GUIMessage scanMsg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VIDEOINFO_REFRESH, 0, 0, 0, 0, 0, null); + GUIWindowManager.SendMessage(scanMsg); + LoadDirectory(_currentFolder); + facadeLayout.SelectedListItemIndex = currentIndex; + } + break; + + case 1280: //Scan using nfo files + if (_doNotUseDatabase) + { + GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK); + dlgOk.SetHeading(string.Empty); + dlgOk.SetLine(1, GUILocalizeStrings.Get(416)); // Not available + dlgOk.DoModal(GUIWindowManager.ActiveWindow); + return; + } + + if (facadeLayout.Focus) + { + if (item.IsFolder) + { + if (item.Label == "..") + { + return; + } + if (item.IsRemote) + { + return; + } + } + } + + if (!_virtualDirectory.RequestPin(item.Path)) + { + return; + } + + currentIndex = facadeLayout.SelectedListItemIndex; + ArrayList nfoFiles = new ArrayList(); + GetNfoFiles(item.Path, ref nfoFiles); + IMDBFetcher fetcher = new IMDBFetcher(this); + fetcher.FetchNfo(nfoFiles, true, false); + // Send global message that movie is refreshed/scanned + GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_VIDEOINFO_REFRESH, 0, 0, 0, 0, 0, null); + GUIWindowManager.SendMessage(msg); + LoadDirectory(_currentFolder); + facadeLayout.SelectedListItemIndex = currentIndex; + break; + + case 830: // Reset watched status + if (item.IsFolder && !item.IsBdDvdFolder) + { + //reset all items in this folder + ResetWatchedForAllMoviesInFolder(item.Path); + } + else + { + SetMovieWatchStatus(item.Path, item.IsFolder, false); + } + int selectedIndex = facadeLayout.SelectedListItemIndex; + LoadDirectory(_currentFolder, false); + UpdateButtonStates(); + facadeLayout.SelectedListItemIndex = selectedIndex; + break; + + case 1260: // Set watched status + SetMovieWatchStatus(item.Path, item.IsFolder, true); + selectedIndex = facadeLayout.SelectedListItemIndex; + LoadDirectory(_currentFolder, false); + UpdateButtonStates(); + facadeLayout.SelectedListItemIndex = selectedIndex; + break; + + case 500: // File menu + { + ShowFileMenu(false); + } + break; + + case 831: + string message = string.Empty; + + if (Util.Utils.IsUsbHdd(item.Path) || Util.Utils.IsRemovableUsbDisk(item.Path)) + { + if (!RemovableDriveHelper.EjectDrive(item.Path, out message)) + { + GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); + pDlgOK.SetHeading(831); + pDlgOK.SetLine(1, GUILocalizeStrings.Get(832)); + pDlgOK.SetLine(2, string.Empty); + pDlgOK.SetLine(3, message); + pDlgOK.DoModal(GUIWindowManager.ActiveWindow); + } + else + { + GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); + pDlgOK.SetHeading(831); + pDlgOK.SetLine(1, GUILocalizeStrings.Get(833)); + pDlgOK.DoModal(GUIWindowManager.ActiveWindow); + } + } + else if (!RemovableDriveHelper.EjectMedia(item.Path, out message)) + { + GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); + pDlgOK.SetHeading(831); + pDlgOK.SetLine(1, GUILocalizeStrings.Get(832)); + pDlgOK.SetLine(2, string.Empty); + pDlgOK.SetLine(3, message); + pDlgOK.DoModal(GUIWindowManager.ActiveWindow); + } + else + { + GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); + pDlgOK.SetHeading(831); + pDlgOK.SetLine(1, GUILocalizeStrings.Get(833)); + pDlgOK.DoModal(GUIWindowManager.ActiveWindow); + } + break; + + case 1204: // Play all + { + if (!_virtualDirectory.RequestPin(item.Path)) + { + return; + } + OnPlayAll(item.Path); + } + break; + + case 1299: // Refresh current directory + { + if (facadeLayout.ListLayout.ListItems.Count > 0 && !string.IsNullOrEmpty(_currentFolder)) + { + facadeLayout.SelectedListItemIndex = 0; + LoadDirectory(_currentFolder, false); + } + } + break; + + case 868: // Reset V.directory + { + ResetShares(); + + if (_virtualDirectory.DefaultShare != null && _virtualDirectory.DefaultShare.Path != string.Empty) + { + LoadDirectory(_virtualDirectory.DefaultShare.Path, false); + } + else + { + LoadDirectory(string.Empty, false); + } + } + break; + + case 1262: // Update grabber scripts + UpdateGrabberScripts(false); + break; + case 1307: // Update internal grabber scripts + UpdateGrabberScripts(true); + break; + case 1263: // Set deault grabber script + SetDefaultGrabber(); + break; + case 1984: // Refresh video thumb + Log.Debug("Thumb refresh from context menu: {0}", item.Path); + if (Util.Utils.FileExistsInCache(item.Path)) + { + string strThumbPath = Util.Utils.GetVideosThumbPathname(item.Path); + + bool success = Util.VideoThumbCreator.CreateVideoThumb(item.Path, strThumbPath, true, true); + if (success) + { + Log.Debug("Refresh success!"); + if (facadeLayout.ListLayout.ListItems.Count > 0 && !string.IsNullOrEmpty(_currentFolder)) + { + selectedIndex = facadeLayout.SelectedListItemIndex; + LoadDirectory(_currentFolder, false); + facadeLayout.SelectedListItemIndex = selectedIndex; + } + } + } + + break; + case 2498: // Hide watched movies + Log.Debug("GUIVideoFiles: Hide watched movies"); + _hideWatchedFiles = true; + LoadDirectory(_currentFolder); + UpdateButtonStates(); + break; + case 2499: // Unhide watched movies + Log.Debug("GUIVideoFiles: Unhide watched movies"); + _hideWatchedFiles = false; + LoadDirectory(_currentFolder); + UpdateButtonStates(); + break; + case 1995: // Create 4x4 folder.jpg + Log.Debug("Create folder.jpg from context menu: {0}", item.Path); + CreateFolderThumb(item, true); + break; + case 1264: // Get media info (refresh mediainfo and duration) + RefreshMediaInfo(item); + break; + + case 2160: // Update mediainfo in all files in the folder + UpdateMediaInfoInFolder(item); + break; + + case 2161: // Abort update mediainfo thread in all files in the folder + if (_refreshMediaInfoThread.IsAlive) + { + _refreshMediaInfoThreadAbort = true; + } + break; + } + } + + public override void Process() + { + if ((_resetSMSsearch == true) && (_resetSMSsearchDelay.Subtract(DateTime.Now).Seconds < -2)) + { + _resetSMSsearchDelay = DateTime.Now; + _resetSMSsearch = true; + facadeLayout.EnableSMSsearch = _oldStateSMSsearch; + } + + base.Process(); + } + + #endregion + + #region Public methods + + /// + /// Total video duration in seconds (single or multiple -> stacked file(s)) + /// Also sets duration into videodatabase (movie table) -> full lenght with stacked parts + /// Parameter refresh force duration update even if data is in the videodatabase + /// + /// + /// + /// + public static int MovieDuration(ArrayList files, bool refresh) + { + TotalMovieDuration = 0; + + if (files == null || files.Count == 0) + { + return TotalMovieDuration; + } + + try + { + foreach (string file in files) + { + int fileID = VideoDatabase.GetFileId(file); + int tempDuration = VideoDatabase.GetVideoDuration(fileID); + + if (tempDuration > 0 && !refresh) + { + TotalMovieDuration += tempDuration; + } + else + { + VideoFilesMediaInfo mInfo = new VideoFilesMediaInfo(); + + if (fileID > -1) + { + // Set/update video file duration and media info + VideoDatabase.GetVideoFilesMediaInfo(file, ref mInfo, refresh); + TotalMovieDuration += (int)mInfo.Duration; + } + } + } + // Set movie duration + VideoDatabase.SetMovieDuration(VideoDatabase.GetMovieId(files[0].ToString()), TotalMovieDuration); + } + catch (Exception ex) + { + Log.Error("GUIVideoFiles: Movie duration exception: {0}", ex.Message); + } + + return TotalMovieDuration; + } + + public bool CheckMovie(string movieFileName) + { + if (!VideoDatabase.HasMovieInfo(movieFileName)) + { + return true; + } + + IMDBMovie movieDetails = new IMDBMovie(); + int idMovie = VideoDatabase.GetMovieInfo(movieFileName, ref movieDetails); + + if (idMovie < 0) + { + return true; + } + + return CheckMovie(idMovie); + } + + public static bool CheckMovie(int idMovie) + { + IMDBMovie movieDetails = new IMDBMovie(); + VideoDatabase.GetMovieInfoById(idMovie, ref movieDetails); + + if (!Util.Utils.IsDVD(movieDetails.Path)) + { + return true; + } + + string cdlabel = string.Empty; + cdlabel = Util.Utils.GetDriveSerial(movieDetails.Path); + + if (cdlabel.Equals(movieDetails.CDLabel)) + { + return true; + } + + GUIDialogYesNo dlg = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_YES_NO); + if (dlg == null) + { + return true; + } + + while (true) + { + dlg.SetHeading(428); + dlg.SetLine(1, 429); + dlg.SetLine(2, movieDetails.DVDLabel); + dlg.SetLine(3, movieDetails.Title); + dlg.SetYesLabel(GUILocalizeStrings.Get(186)); //OK + dlg.SetNoLabel(GUILocalizeStrings.Get(222)); //Cancel + dlg.SetDefaultToYes(true); + dlg.DoModal(GUIWindowManager.ActiveWindow); + + if (dlg.IsConfirmed) + { + if (movieDetails.CDLabel.StartsWith("nolabel")) + { + ArrayList movies = new ArrayList(); + VideoDatabase.GetFilesForMovie(idMovie, ref movies); + if (File.Exists( /*movieDetails.Path+movieDetails.File*/(string)movies[0])) + { + cdlabel = Util.Utils.GetDriveSerial(movieDetails.Path); + VideoDatabase.UpdateCDLabel(movieDetails, cdlabel); + movieDetails.CDLabel = cdlabel; + return true; + } + } + else + { + cdlabel = Util.Utils.GetDriveSerial(movieDetails.Path); + + if (cdlabel.Equals(movieDetails.CDLabel)) + { + return true; + } + } + } + else + { + break; + } + } + return false; + } + + public static void GetStringFromKeyboard(ref string strLine) + { + VirtualKeyboard keyboard = (VirtualKeyboard)GUIWindowManager.GetWindow((int)Window.WINDOW_VIRTUAL_KEYBOARD); + + if (null == keyboard) + { + return; + } + keyboard.IsSearchKeyboard = true; + keyboard.Reset(); + keyboard.Text = strLine; + keyboard.DoModal(GUIWindowManager.ActiveWindow); + strLine = string.Empty; + + if (keyboard.IsConfirmed) + { + strLine = keyboard.Text; + } + } + + [Obsolete("This method is obsolete; use method PlayMovieFromPlayList(bool askForResumeMovie, bool requestPin) instead.")] + public static void PlayMovieFromPlayList(bool askForResumeMovie) + { + PlayMovieFromPlayList(askForResumeMovie, -1, false); + } + + public static void PlayMovieFromPlayList(bool askForResumeMovie, bool requestPin) + { + PlayMovieFromPlayList(askForResumeMovie, -1, requestPin); + } + + public static void PlayMovieFromPlayList(bool askForResumeMovie, int iMovieIndex, bool requestPin) + { + bool BDInternalMenu = false; + bool NoBDResume = false; + _BDDetect = false; + g_Player.ForcePlay = false; + g_Player.SetResumeBDTitleState = g_Player.BdDefaultTitle; + string filename; + if (iMovieIndex == -1) + { + filename = _playlistPlayer.GetNext(); + } + else + { + filename = _playlistPlayer.Get(iMovieIndex); + } + + _playlistPlayer.Reset(); + + // If the file is an image file, it should be mounted before playing + bool isImage = false; + if (VirtualDirectory.IsImageFile(System.IO.Path.GetExtension(filename))) + { + if (!MountImageFile(GUIWindowManager.ActiveWindow, filename, requestPin)) + return; + isImage = true; + } + + // Convert BD ISO filenames for to BD index file (...BDMV\index.bdmv) + if (isImage) + { + // Covert filename + if (Util.Utils.IsBDImage(filename, ref filename)) + { + // Change also playlist filename + int index = iMovieIndex; + + if (iMovieIndex == -1) + index = 0; + + _playlistPlayer.GetPlaylist(_playlistPlayer.CurrentPlaylistType)[index].FileName = filename; + isImage = false; + } + } + + //Resume BD only for Title mode + if (filename.EndsWith(@"\BDMV\index.bdmv")) + { + _BDDetect = true; + } + + using (Profile.Settings xmlreader = new MPSettings()) + { + BDInternalMenu = xmlreader.GetValueAsBool("bdplayer", "useInternalBDPlayer", true); + } + + int timeMovieStopped = 0; + byte[] resumeData = null; + + { + // Skip resume for external player and BluRays (not implemented yet in BDLIB) + if (!CheckExternalPlayer(filename, isImage)) + { + // Check if we play image file to search db with the proper filename + if (Util.Utils.IsISOImage(filename)) + { + filename = DaemonTools.MountedIsoFile; + } + IMDBMovie movieDetails = new IMDBMovie(); + VideoDatabase.GetMovieInfo(filename, ref movieDetails); + int idFile = VideoDatabase.GetFileId(filename); + int idMovie = VideoDatabase.GetMovieId(filename); + + if (_BDDetect) + { + g_Player.SetResumeBDTitleState = VideoDatabase.GetTitleBDId(idFile, out resumeData); + if ((BDInternalMenu && g_Player.SetResumeBDTitleState >= g_Player.BdDefaultTitle) || (!BDInternalMenu && g_Player.SetResumeBDTitleState < g_Player.BdRemuxTitle)) + { + NoBDResume = true; + } + } + + if ((idMovie >= 0) && (idFile >= 0) && !NoBDResume) + { + timeMovieStopped = VideoDatabase.GetMovieStopTimeAndResumeData(idFile, out resumeData, + g_Player.SetResumeBDTitleState); + if (timeMovieStopped > 0) + { + string title = Path.GetFileName(filename); + VideoDatabase.GetMovieInfoById(idMovie, ref movieDetails); + if (movieDetails.Title != string.Empty) + { + title = movieDetails.Title; + } + + if (askForResumeMovie && g_Player.SetResumeBDTitleState >= 0) + { + if (_BDDetect) + g_Player.ForcePlay = true; + + GUIResumeDialog.Result result = + GUIResumeDialog.ShowResumeDialog(title, timeMovieStopped, + GUIResumeDialog.MediaType.Video); + + if (result == GUIResumeDialog.Result.Abort) + { + g_Player.ForcePlay = false; + timeMovieStopped = 0; + if (!_BDDetect) + { + _playlistPlayer.Reset(); + _playlistPlayer.CurrentPlaylistType = _currentPlaylistType; + _playlistPlayer.CurrentSong = _currentPlaylistIndex; + return; + } + // Return to list if we cancel resume dialog (needed when BD is remuxed) + else if (g_Player.SetResumeBDTitleState == g_Player.BdDefaultTitle || g_Player.SetResumeBDTitleState == g_Player.BdRemuxTitle) + { + return; + } + } + + if (result == GUIResumeDialog.Result.PlayFromBeginning) + timeMovieStopped = 0; + } + } + } + } + } + + // TODO Handle STOP when it comes from MyMusic otherwise Video Playlist will not work + //if (g_Player.Playing && !g_Player.IsDVD) + // g_Player.Stop(); + + string currentFile = g_Player.CurrentFile; + if (Util.Utils.IsISOImage(currentFile)) + { + if (!String.IsNullOrEmpty(Util.DaemonTools.GetVirtualDrive()) && + g_Player.IsDvdDirectory(Util.DaemonTools.GetVirtualDrive())) + Util.DaemonTools.UnMount(); + } + + if (iMovieIndex == -1) + { + _playlistPlayer.PlayNext(); + } + else + { + _playlistPlayer.Play(iMovieIndex); + } + + if (g_Player.Playing && timeMovieStopped > 0) + { + if (g_Player.IsDVD && !_BDDetect) + { + // send resume thread async + var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SET_RESUME_STATE, 0, 0, 0, 0, 0, resumeData); + GUIWindowManager.SendThreadMessage(msg); + } + else + { + GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SEEK_POSITION, 0, 0, 0, 0, 0, null); + msg.Param1 = timeMovieStopped; + GUIGraphicsContext.SendMessage(msg); + } + } + } + + public static void PlayMovieFromBDPlayList(bool askForResumeMovie, int iMovieIndex, bool requestPin) + { + //Resume BD only for Title mode + _BDDetect = false; + string filename = g_Player.currentFileName; + + // If the file is an image file, it should be mounted before playing + bool isImage = false; + if (VirtualDirectory.IsImageFile(System.IO.Path.GetExtension(filename))) + { + if (!MountImageFile(GUIWindowManager.ActiveWindow, filename, requestPin)) + return; + isImage = true; + } + + // Convert BD ISO filenames for to BD index file (...BDMV\index.bdmv) + if (isImage) + { + // Covert filename + if (Util.Utils.IsBDImage(filename, ref filename)) + { + // Change also playlist filename + int index = iMovieIndex; + + if (iMovieIndex == -1) + index = 0; + + _playlistPlayer.GetPlaylist(_playlistPlayer.CurrentPlaylistType)[index].FileName = filename; + isImage = false; + } + } + + int timeMovieStopped = 0; + byte[] resumeData = null; + + // Skip resume for external player and BluRays (not implemented yet in BDLIB) + if (!CheckExternalPlayer(filename, isImage)) + { + // Check if we play image file to search db with the proper filename + if (Util.Utils.IsISOImage(filename)) + { + filename = DaemonTools.MountedIsoFile; + } + IMDBMovie movieDetails = new IMDBMovie(); + VideoDatabase.GetMovieInfo(filename, ref movieDetails); + int idFile = VideoDatabase.GetFileId(filename); + int idMovie = VideoDatabase.GetMovieId(filename); + + if ((idMovie >= 0) && (idFile >= 0)) + { + timeMovieStopped = VideoDatabase.GetMovieStopTimeAndResumeData(idFile, out resumeData, g_Player.SetResumeBDTitleState); + if (timeMovieStopped > 0) + { + string title = Path.GetFileName(filename); + VideoDatabase.GetMovieInfoById(idMovie, ref movieDetails); + if (movieDetails.Title != string.Empty) + { + title = movieDetails.Title; + } + if (askForResumeMovie) + { + GUIResumeDialog.Result result = + GUIResumeDialog.ShowResumeDialog(title, timeMovieStopped, + GUIResumeDialog.MediaType.Video); + + if (result == GUIResumeDialog.Result.Abort) + { + g_Player.SetResumeBDTitleState = -1; + return; + } + + if (result == GUIResumeDialog.Result.PlayFromBeginning) + timeMovieStopped = 0; + } + } + } + GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SEEK_POSITION, 0, 0, 0, 0, 0, null); + msg.Param1 = timeMovieStopped; + GUIWindowManager.SendThreadMessage(msg); + } + } + + [Obsolete("This method is obsolete; use method MountImageFile(int WindowID, string file) instead.")] + public static bool MountImageFile(int windowID, string file) + { + return MountImageFile(windowID, file, false); + } + + public static bool MountImageFile(int windowID, string file, bool requestPin) + { + Log.Debug("GUIVideoFiles: MountImageFile"); + if (!DaemonTools.IsMounted(file)) + { + if (_askBeforePlayingDVDImage) + { + GUIDialogYesNo dlgYesNo = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_YES_NO); + + if (dlgYesNo != null) + { + dlgYesNo.SetHeading(713); + dlgYesNo.SetLine(1, 531); + dlgYesNo.DoModal(windowID); + if (!dlgYesNo.IsConfirmed) + { + return false; + } + } + } + + List items = new List(); + + if (requestPin) + { + items = _virtualDirectory.GetDirectoryExt(file); + } + else + { + items = _virtualDirectory.GetDirectoryUnProtectedExt(file, true); + } + + if (items.Count == 1 && file != string.Empty) + { + return false; // protected share, with wrong pincode + } + } + return DaemonTools.IsMounted(file); + } + + /// + /// Returns true if the specified window belongs to the my videos plugin + /// + /// id of window + /// + /// true: belongs to the my videos plugin + /// false: does not belong to the my videos plugin + public static bool IsVideoWindow(int windowId) + { + if (windowId == (int)Window.WINDOW_DVD) + { + return true; + } + + if (windowId == (int)Window.WINDOW_FULLSCREEN_VIDEO) + { + return true; + } + + if (windowId == (int)Window.WINDOW_VIDEO_ARTIST_INFO) + { + return true; + } + + if (windowId == (int)Window.WINDOW_VIDEO_INFO) + { + return true; + } + + if (windowId == (int)Window.WINDOW_VIDEO_PLAYLIST) + { + return true; + } + + if (windowId == (int)Window.WINDOW_VIDEO_TITLE) + { + return true; + } + + if (windowId == (int)Window.WINDOW_VIDEOS) + { + return true; + } + + return false; + } + + /// + /// Returns true if the specified window should maintain virtual directory + /// + /// id of window + /// + /// true: if the specified window should maintain virtual directory + /// false: if the specified window should not maintain virtual directory + public static bool KeepVirtualDirectory(int windowId) + { + if (windowId == (int)Window.WINDOW_DVD) + { + return true; + } + + if (windowId == (int)Window.WINDOW_FULLSCREEN_VIDEO) + { + return true; + } + + if (windowId == (int)Window.WINDOW_VIDEO_ARTIST_INFO) + { + return true; + } + + if (windowId == (int)Window.WINDOW_VIDEO_INFO) + { + return true; + } + + if (windowId == (int)Window.WINDOW_VIDEO_PLAYLIST) + { + return true; + } + + if (windowId == (int)Window.WINDOW_VIDEOS) + { + return true; + } + + return false; + } + + public static void Reset() + { + Log.Debug("GUIVideoFiles: Resetting virtual directory"); + _virtualDirectory.Reset(); + } + + [Obsolete("This method is obsolete; use method PlayMovie(int idMovie, bool requestPin) instead.")] + public static void PlayMovie(int idMovie) + { + PlayMovie(idMovie, false); + } + + public static void PlayMovie(int idMovie, bool requestPin) + { + + int selectedFileIndex = 1; + + if (IsStacked) + { + selectedFileIndex = 0; + } + + ArrayList movieFiles = new ArrayList(); + VideoDatabase.GetFilesForMovie(idMovie, ref movieFiles); + + if (movieFiles.Count <= 0 || !CheckMovie(idMovie)) + { + return; + } + + bool askForResumeMovie = true; + int movieDuration = 0; + + List items = new List(); + + foreach (string file in movieFiles) + { + FileInformation fi = new FileInformation(); + GUIListItem item = new GUIListItem(Util.Utils.GetFilename(file), "", file, false, fi); + items.Add(item); + + if (!WakeUpSrv(item.Path)) + { + return; + } + } + + if (items.Count <= 0) + { + return; + } + + if (requestPin) + { + string strDir = Path.GetDirectoryName(items[0].Path); + + if (strDir != null && strDir.EndsWith(@"\")) + { + strDir = strDir.Substring(0, strDir.Length - 1); + } + + if (strDir == null || strDir.Length > 254) + { + Log.Warn("GUIVideoFiles.PlayTitleMovie: Received a path which contains too many chars"); + return; + } + + string iPincodeCorrect; + if (_virtualDirectory.IsProtectedShare(strDir, out iPincodeCorrect)) + { + #region Pin protected + + bool retry = true; + { + while (retry) + { + //no, then ask user to enter the pincode + GUIMessage msgGetPassword = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GET_PASSWORD, 0, 0, 0, 0, 0, 0); + GUIWindowManager.SendMessage(msgGetPassword); + + if (msgGetPassword.Label != iPincodeCorrect) + { + GUIMessage msgWrongPassword = new GUIMessage(GUIMessage.MessageType.GUI_MSG_WRONG_PASSWORD, 0, 0, 0, 0, 0, + 0); + GUIWindowManager.SendMessage(msgWrongPassword); + + if (!(bool)msgWrongPassword.Object) + { + return; + } + } + else + { + retry = false; + } + } + } + + #endregion + } + } + + //check if we can resume 1 of those movies + if (items.Count > 1) + { + bool asked = false; + + for (int i = 0; i < items.Count; ++i) + { + GUIListItem temporaryListItem = (GUIListItem)items[i]; + + if (!asked) + { + selectedFileIndex++; + } + + IMDBMovie movieDetails = new IMDBMovie(); + int idFile = VideoDatabase.GetFileId(temporaryListItem.Path); + + if ((idMovie >= 0) && (idFile >= 0)) + { + VideoDatabase.GetMovieInfo((string)movieFiles[0], ref movieDetails); + string title = Path.GetFileName((string)movieFiles[0]); + + if ((VirtualDirectory.IsValidExtension((string)movieFiles[0], Util.Utils.VideoExtensions, false))) + { + Util.Utils.RemoveStackEndings(ref title); + } + + if (movieDetails.Title != string.Empty) + { + title = movieDetails.Title; + } + + int timeMovieStopped = VideoDatabase.GetMovieStopTime(idFile); + + if (timeMovieStopped > 0) + { + if (!asked) + { + asked = true; + + GUIResumeDialog.Result result = + GUIResumeDialog.ShowResumeDialog(title, movieDuration + timeMovieStopped, + GUIResumeDialog.MediaType.Video); + + if (result == GUIResumeDialog.Result.Abort) + { + _playlistPlayer.Reset(); + _playlistPlayer.CurrentPlaylistType = _currentPlaylistType; + _playlistPlayer.CurrentSong = _currentPlaylistIndex; + return; + } + + if (result == GUIResumeDialog.Result.PlayFromBeginning) + { + VideoDatabase.DeleteMovieStopTime(idFile); + } + else + { + askForResumeMovie = false; + } + } + } + // Total movie duration + movieDuration += VideoDatabase.GetVideoDuration(idFile); + } + } + + if (askForResumeMovie) + { + GUIDialogFileStacking dlg = + (GUIDialogFileStacking)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_FILESTACKING); + + if (null != dlg) + { + dlg.SetFiles(movieFiles); + dlg.DoModal(GUIWindowManager.ActiveWindow); + selectedFileIndex = dlg.SelectedFile; + if (selectedFileIndex < 1) + { + return; + } + } + } + } + + // Get current playlist + _currentPlaylistType = new PlayListType(); + _currentPlaylistType = _playlistPlayer.CurrentPlaylistType; + _currentPlaylistIndex = _playlistPlayer.CurrentSong; + + _playlistPlayer.Reset(); + _playlistPlayer.CurrentPlaylistType = PlayListType.PLAYLIST_VIDEO_TEMP; + PlayList playlist = _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO_TEMP); + playlist.Clear(); + + for (int i = selectedFileIndex - 1; i < movieFiles.Count; ++i) + { + string movieFileName = (string)movieFiles[i]; + PlayListItem newitem = new PlayListItem(); + newitem.FileName = movieFileName; + newitem.Type = PlayListItem.PlayListItemType.Video; + playlist.Add(newitem); + } + + // play movie... + PlayMovieFromPlayList(askForResumeMovie, requestPin); + } + + public static bool IsMovieFolder(string path) + { + ISelectDVDHandler selectDvdHandler = GetSelectDvdHandler(); + ISelectBDHandler selectBdHandler = GetSelectBDHandler(); + + if (selectBdHandler.IsBDDirectory(path) || selectDvdHandler.IsDvdDirectory(path)) + { + return true; + } + + return false; + } + + /// + /// Get/Set BDHandler interface from/to registered services. + /// + /// BDHandler interface + public static ISelectBDHandler GetSelectBDHandler() + { + ISelectBDHandler selectBDHandler; + if (GlobalServiceProvider.IsRegistered()) + { + selectBDHandler = GlobalServiceProvider.Get(); + } + else + { + selectBDHandler = new SelectBDHandler(); + GlobalServiceProvider.Add(selectBDHandler); + } + return selectBDHandler; + } + + /// + /// Get/Set DVDHandler interface from/to registered services. + /// + /// DVDHandler interface + public static ISelectDVDHandler GetSelectDvdHandler() + { + ISelectDVDHandler selectDVDHandler; + + if (GlobalServiceProvider.IsRegistered()) + { + selectDVDHandler = GlobalServiceProvider.Get(); + } + else + { + selectDVDHandler = new SelectDVDHandler(); + GlobalServiceProvider.Add(selectDVDHandler); + } + + return selectDVDHandler; + } + + public static void UpdateGrabberScripts(bool internalScript) + { + // Check Internet connection + + if (!Win32API.IsConnectedToInternet()) + { + GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); + dlgOk.SetHeading(257); + dlgOk.SetLine(1, GUILocalizeStrings.Get(703)); + dlgOk.DoModal(GUIWindowManager.ActiveWindow); + return; + } + + // Initialize progress bar + GUIDialogProgress progressDialog = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + progressDialog.Reset(); + progressDialog.SetHeading(GUILocalizeStrings.Get(300030)); + progressDialog.ShowProgressBar(true); + progressDialog.SetLine(1, GUILocalizeStrings.Get(300031)); + progressDialog.SetLine(2, GUILocalizeStrings.Get(300032)); //Downloading + progressDialog.SetPercentage(25); + progressDialog.StartModal(GUIWindowManager.ActiveWindow); + + if (internalScript) + { + string parserIndexFile = Config.GetFile(Config.Dir.Config, "scripts\\VDBParserStrings.xml"); + string parserIndexUrl = @"http://install.team-mediaportal.com/MP1/VDBParserStrings.xml"; + string internalGrabberScriptFile = Config.GetFile(Config.Dir.Config, "scripts\\InternalActorMoviesGrabber.csscript"); + string internalGrabberScriptUrl = @"http://install.team-mediaportal.com/MP1/InternalGrabber/InternalActorMoviesGrabber.csscript"; + string internalMovieImagesGrabberScriptFile = Config.GetFile(Config.Dir.Config, "scripts\\InternalMovieImagesGrabber.csscript"); + string internalMovieImagesGrabberScriptUrl = @"http://install.team-mediaportal.com/MP1/InternalGrabber/InternalMovieImagesGrabber.csscript"; + + // VDB parser update + progressDialog.SetHeading(GUILocalizeStrings.Get(1316)); // Updating internal scripts... + progressDialog.ShowProgressBar(true); + progressDialog.SetLine(1, GUILocalizeStrings.Get(1317));// Downloading internal scripts... + progressDialog.SetLine(2, GUILocalizeStrings.Get(300032)); //Downloading + progressDialog.SetPercentage(50); + progressDialog.StartModal(GUIWindowManager.ActiveWindow); + + if (DownloadFile(parserIndexFile, parserIndexUrl, Encoding.UTF8) == false) + { + progressDialog.Close(); + return; + } + + // Internal actors grabber script update + progressDialog.SetHeading(GUILocalizeStrings.Get(1316)); + progressDialog.ShowProgressBar(true); + progressDialog.SetLine(1, GUILocalizeStrings.Get(1317)); + progressDialog.SetLine(2, GUILocalizeStrings.Get(300032)); + progressDialog.SetPercentage(75); + progressDialog.StartModal(GUIWindowManager.ActiveWindow); + + if (DownloadFile(internalGrabberScriptFile, internalGrabberScriptUrl, Encoding.Default) == false) + { + progressDialog.Close(); + return; + } + + // Internal images grabber script update + progressDialog.SetHeading(GUILocalizeStrings.Get(1316)); + progressDialog.ShowProgressBar(true); + progressDialog.SetLine(1, GUILocalizeStrings.Get(1317)); + progressDialog.SetLine(2, GUILocalizeStrings.Get(300032)); + progressDialog.SetPercentage(100); + progressDialog.StartModal(GUIWindowManager.ActiveWindow); + + if (DownloadFile(internalMovieImagesGrabberScriptFile, internalMovieImagesGrabberScriptUrl, Encoding.Default) == false) + { + progressDialog.Close(); + return; + } + + IMDB.InternalActorsScriptGrabber.ResetGrabber(); + Util.InternalCSScriptGrabbersLoader.Movies.ImagesGrabber.ResetGrabber(); + progressDialog.Close(); + } + + if (DownloadFile(_grabberIndexFile, _grabberIndexUrl, Encoding.Default) == false) + { + progressDialog.Close(); + return; + } + + + // read index file + if (!File.Exists(_grabberIndexFile)) + { + GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); + dlgOk.SetHeading(257); + dlgOk.SetLine(1, GUILocalizeStrings.Get(1261)); // No grabber index found + dlgOk.DoModal(GUIWindowManager.ActiveWindow); + progressDialog.Close(); + return; + } + + XmlDocument doc = new XmlDocument(); + doc.Load(_grabberIndexFile); + XmlNodeList sectionNodes = doc.SelectNodes("MovieInfoGrabber/grabber"); + + // download all grabbers + int percent = 0; + + if (sectionNodes != null) + { + for (int i = 0; i < sectionNodes.Count; i++) + { + if (progressDialog.IsCanceled) + { + break; + } + + string url = sectionNodes[i].Attributes["url"].Value; + string id = Path.GetFileName(url); + progressDialog.SetLine(1, GUILocalizeStrings.Get(300034) + id); // Downloading grabber: + progressDialog.SetLine(2, GUILocalizeStrings.Get(300035)); + progressDialog.SetPercentage(percent); + percent += 100 / (sectionNodes.Count - 1); + progressDialog.Progress(); + + if (DownloadFile(IMDB.ScriptDirectory + @"\" + id, url, Encoding.Default) == false) + { + progressDialog.Close(); + return; + } + } + } + progressDialog.Close(); + } + + private static bool DownloadFile(string filepath, string url, Encoding enc) + { + string grabberTempFile = Path.GetTempFileName(); + + //Application.DoEvents(); + try + { + if (File.Exists(grabberTempFile)) + { + File.Delete(grabberTempFile); + } + + //Application.DoEvents(); + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + try + { + // Use the current user in case an NTLM Proxy or similar is used. + // request.Proxy = WebProxy.GetDefaultProxy(); + request.Proxy.Credentials = CredentialCache.DefaultCredentials; + } + catch (Exception ex) + { + Log.Error("GUIVideoFiles: DownloadFile {0}", ex.Message); + } + + using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) + { + //Application.DoEvents(); + using (Stream resStream = response.GetResponseStream()) + { + using (TextReader tin = new StreamReader(resStream, enc)) + { + using (TextWriter tout = File.CreateText(grabberTempFile)) + { + while (true) + { + string line = tin.ReadLine(); + + if (line == null) + { + break; + } + + tout.WriteLine(line); + } + } + } + } + } + + File.Delete(filepath); + File.Move(grabberTempFile, filepath); + return true; + } + catch (Exception ex) + { + Log.Error("EXCEPTION in DownloadFile | {0}\r\n{1}", ex.Message, ex.Source); + return false; + } + } + + public static void SetDefaultGrabber() + { + GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_MENU); + + if (dlg == null) + { + return; + } + + dlg.Reset(); + dlg.SetHeading(1263); // menu + + // read index file + if (!File.Exists(_grabberIndexFile)) + { + GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); + dlgOk.SetHeading(257); + dlgOk.SetLine(1, GUILocalizeStrings.Get(1261)); // No grabber index found + dlgOk.DoModal(GUIWindowManager.ActiveWindow); + return; + } + + _grabberList = new Dictionary(); + + Directory.CreateDirectory(IMDB.ScriptDirectory); + DirectoryInfo di = new DirectoryInfo(IMDB.ScriptDirectory); + + FileInfo[] fileList = di.GetFiles("*.csscript", SearchOption.AllDirectories); + GUIWaitCursor.Show(); + + foreach (FileInfo f in fileList) + { + try + { + CSScript.GlobalSettings.AddSearchDir(AppDomain.CurrentDomain.BaseDirectory); + + using (AsmHelper script = new AsmHelper(CSScript.Compile(f.FullName), "Temp", true)) + { + script.ProbingDirs = CSScript.GlobalSettings.SearchDirs.Split(';'); + IIMDBScriptGrabber grabber = (IIMDBScriptGrabber)script.CreateObject("Grabber"); + + ComboBoxItemDatabase item = new ComboBoxItemDatabase(); + item.Database = Path.GetFileNameWithoutExtension(f.FullName); + item.Language = grabber.GetLanguage(); + item.Limit = IMDB.DEFAULT_SEARCH_LIMIT.ToString(); + item.Name = grabber.GetName(); + _grabberList.Add(item.Database, item); + } + } catch (Exception ex) { - Log.Error("GUIVideoFiles: LoadDirectory {0}", ex.Message); - } - - _getMediaInfoThreadAbort = false; - - // The last _getMediaInfoThread is closed we can start a new one - _getMediaInfoThreadNumber++; - _getMediaInfoThread = new Thread(GetMediaInfoThread); - _getMediaInfoThread.Priority = ThreadPriority.Lowest; - _getMediaInfoThread.IsBackground = true; - _getMediaInfoThread.Name = "GetMediaInfoThread " + _getMediaInfoThreadNumber; - _getMediaInfoThread.Start(itemlist2); - } - - GUIWaitCursor.Hide(); - } - - private void ReplaceItem(string oldPath, string newPath) - { - if (Directory.Exists(newPath) || (Util.Utils.IsVideo(oldPath) && Util.Utils.IsVideo(newPath))) - { - for (int i = 0; i < facadeLayout.Count; i++) - { - if (facadeLayout[i].Path == oldPath) - { - AddItem(newPath, i); - return; - } - } - } - - if (Util.Utils.IsVideo(newPath)) - { - AddItem(newPath, -1); - } - - if (Util.Utils.IsVideo(oldPath)) - { - DeleteItem(oldPath); - } - } - - private int DeleteItem(string path) - { - int oldItem = -1; - try - { - for (int i = 0; i < facadeLayout.Count; i++) - { - if (facadeLayout[i].Path == path) - { - facadeLayout.RemoveItem(i); - if (_currentSelectedItem >= i) - { - _currentSelectedItem--; - } - oldItem = i; - break; - } - } - int totalItems = facadeLayout.Count; - - if (totalItems > 0) - { - GUIListItem rootItem = facadeLayout[0]; - if (rootItem.Label == "..") - { - totalItems--; - } - } - - GUIPropertyManager.SetProperty("#itemcount", Util.Utils.GetObjectCountLabel(totalItems)); - } - catch (Exception ex) - { - Log.Error("GUIVideoFiles.DeleteItem Exception: {0}", ex.Message); - } - return oldItem; - } - - private void AddItem(string path, int index) - { - try - { - for (int i = 0; i < facadeLayout.Count; i++) - { - if (facadeLayout[i].Path == path) - { - Log.Debug("GUIVideoFiles.AddItem Duplicated item found: {0}", path); - return; - } - } - - ISelectDVDHandler selectDvdHandler = GetSelectDvdHandler(); - ISelectBDHandler selectBDHandler = GetSelectBDHandler(); - FileInformation fi = new FileInformation(); - if (File.Exists(path)) - { - FileInfo f = new FileInfo(path); - fi.CreationTime = File.GetCreationTime(path); - fi.Length = f.Length; - } - else - { - fi = new FileInformation(); - fi.CreationTime = DateTime.Now; - fi.Length = 0; - } - GUIListItem item = new GUIListItem(Util.Utils.GetFilename(path), "", path, true, fi); - - item.IsFolder = Directory.Exists(path); - - Util.Utils.SetDefaultIcons(item); - Util.Utils.SetThumbnails(ref item); - - // Check db for watched status for played movie or changed status in movie info window - string file = item.Path; - bool isMovieFolder = IsMovieFolder(item.Path); - - if (!item.IsFolder || isMovieFolder) - { - // Special folders (DVD/BluRay) - if (isMovieFolder) - { - item.IsBdDvdFolder = true; - file = selectDvdHandler.GetFolderVideoFile(item.Path); - - if (file == string.Empty) - { - file = selectBDHandler.GetFolderVideoFile(item.Path); - } - } - - int percentWatched = 0; - int timesWatched = 0; - int movieId = VideoDatabase.GetMovieId(file); - bool played = VideoDatabase.GetmovieWatchedStatus(movieId, out percentWatched, out timesWatched); - item.Duration = VideoDatabase.GetMovieDuration(movieId); - - if (item.Duration == 0) - { - RefreshMediaInfo(item); - item.Duration = VideoDatabase.GetMovieDuration(movieId); - } - - SetLabel(item); - - if (_markWatchedFiles) - { - item.IsPlayed = played; - } - - if (item.IsBdDvdFolder) - { - if (selectDvdHandler.IsDvdDirectory(item.Path)) - { - item.Label3 = MediaTypes.DVD.ToString() + " " + percentWatched + "% #" + timesWatched; - } - else - { - item.Label3 = MediaTypes.BD.ToString() + " " + percentWatched + "% #" + timesWatched; - } - } - else if (VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) - { - item.Label3 = MediaTypes.ISO.ToString() + " " + percentWatched + "% #" + timesWatched; - } - else - { - item.Label3 = percentWatched + "% #" + timesWatched; - } - } - - List itemlist = new List(); - itemlist.Add(item); - SetImdbThumbs(itemlist, selectDvdHandler); - - item.OnItemSelected += item_OnItemSelected; - - if (index == -1) - { - facadeLayout.Add(item); - } - else - { - facadeLayout.Replace(index, item); - } - - int totalItems = facadeLayout.Count; - - if (totalItems > 0) - { - GUIListItem rootItem = facadeLayout[0]; - if (rootItem.Label == "..") - { - totalItems--; - } - } - GUIPropertyManager.SetProperty("#itemcount", Util.Utils.GetObjectCountLabel(totalItems)); - } - catch (Exception ex) - { - Log.Error("GUIVideoFiles.AddItem Exception: {0}", ex.Message); - } - } - - // main thread. It adds all file to database and refresh the ListLayout on the screen. - private void GetMediaInfoThread(object i) - { - List itemlist = (List)i; - - Log.Debug("GetMediaInfoThread: current folder: {0}, itemlist count: {1}", _currentFolder, itemlist.Count); - - foreach (GUIListItem item in itemlist) - { - if (_getMediaInfoThreadAbort) - { - Log.Debug("GetMediaInfoThread: finished with _getMediaInfoThreadAbort signal."); - return; - } - try - { - Log.Debug("GetMediaInfoThread: Work on {0}", item.Path); - - RefreshMediaInfo(item); - - int newMovieId = VideoDatabase.GetMovieId(item.Path); - item.Duration = VideoDatabase.GetMovieDuration(newMovieId); - if (item.Duration > 0) - { - for (int n = facadeLayout.ListLayout.ListItems.Count - 1; n > 0; n--) - { - if (facadeLayout.ListLayout.ListItems[n].Label == item.Label) - { - SetLabel(item); - facadeLayout.ListLayout.ListItems[n].Label2 = item.Label2; - break; - } - } - } - } - catch (ThreadAbortException) - { - Log.Debug("GetMediaInfoThread: ThreadAbortException"); - } - catch (Exception ex) - { - Log.Error("GetMediaInfoThread: {0}", ex.Message); - } - Thread.Sleep(100); - } - Log.Debug("GetMediaInfoThread: Finished."); - } - - private void UpdateMediaInfoInFolder(GUIListItem item) - { - List itemlist = new List(); - - ListFilesForUpdateMediaInfo(item, ref itemlist); - Log.Debug("UpdateMediaInfoInFolder: File count {0}", itemlist.Count); - - _progressDialogForUpdateMediaInfo = - (GUIDialogProgress)GUIWindowManager.GetWindow(101); //(int)Window.WINDOW_DIALOG_PROGRESS - _progressDialogForUpdateMediaInfo.Reset(); - _progressDialogForUpdateMediaInfo.SetHeading(GUILocalizeStrings.Get(2160)); - _progressDialogForUpdateMediaInfo.ShowProgressBar(true); - _progressDialogForUpdateMediaInfo.SetLine(1, item.Path.Replace("\\", "/")); - _progressDialogForUpdateMediaInfo.SetLine(2, string.Empty); - _progressDialogForUpdateMediaInfo.SetLine(3, "Movie count: " + itemlist.Count + "/0"); - _progressDialogForUpdateMediaInfo.StartModal(GUIWindowManager.ActiveWindow); - - if (_refreshMediaInfoThread != null && _refreshMediaInfoThread.IsAlive) - { - _refreshMediaInfoThread.Abort(); - } - - _refreshMediaInfoThreadAbort = false; - _refreshMediaInfoThread = new Thread(RefreshMediaInfoThread); - _refreshMediaInfoThread.Priority = ThreadPriority.Lowest; - _refreshMediaInfoThread.IsBackground = true; - _refreshMediaInfoThread.Name = "RefreshMediaInfoThread"; - _refreshMediaInfoThread.Start(itemlist); - } - - private void RefreshMediaInfoThread(object o) - { - List itemlist = (List)o; - try - { - for (int i = 0; i < itemlist.Count; i++) - { - if (_refreshMediaInfoThreadAbort) - { - Log.Info("RefreshMediaInfoThread: Aborted by the user."); - return; - } - - int perc = (i * 100) / itemlist.Count; - _progressDialogForUpdateMediaInfo.SetPercentage(perc); - _progressDialogForUpdateMediaInfo.SetLine(1, itemlist[i].Path.Replace("\\", "/")); - _progressDialogForUpdateMediaInfo.SetLine(3, "Movie count: " + itemlist.Count + "/" + i); - _progressDialogForUpdateMediaInfo.Progress(); - - RefreshMediaInfo(itemlist[i]); - Thread.Sleep(100); - - while (g_Player.Playing || g_Player.Starting) - { - Thread.Sleep(5000); - Log.Debug("RefreshMediaInfoThread: g_Player is Playing, waiting for the end."); - } - } - } - catch (Exception ex) - { - Log.Error("RefreshMediaInfoThread: {0}", ex); - } - finally - { - _progressDialogForUpdateMediaInfo.Close(); - } - Log.Info("RefreshMediaInfoThread: Finished."); - } - - private void ListFilesForUpdateMediaInfo(GUIListItem item, ref List itemlist) - { - if (item != null) - { - // Process the list of files found in the directory. - VirtualDirectory virtualDirectory = new VirtualDirectory(); - virtualDirectory.SetExtensions(Util.Utils.VideoExtensions); - List inertItemlist = virtualDirectory.GetDirectoryUnProtectedExt(item.Path, true); - foreach (GUIListItem subItem in inertItemlist) - { - if (!subItem.IsFolder) - { - itemlist.Add(subItem); - } - else - { - if (subItem.Label != "..") - { - ListFilesForUpdateMediaInfo(subItem, ref itemlist); - } - } - } - } - } - - private void LoadFolderSettings(string folderName) - { - if (folderName == string.Empty) - { - folderName = "root"; - } - object o; - FolderSettings.GetFolderSetting(folderName, "VideoFiles", typeof(MapSettings), out o); - if (o != null) - { - _mapSettings = o as MapSettings; - - if (_mapSettings == null) - { - _mapSettings = new MapSettings(); - } - - CurrentSortAsc = _mapSettings.SortAscending; - CurrentSortMethod = (VideoSort.SortMethod)_mapSettings.SortBy; - currentLayout = (Layout)_mapSettings.ViewAs; - } - else - { - Share share = _virtualDirectory.GetShare(folderName); - - if (share != null) - { - if (_mapSettings == null) - { - _mapSettings = new MapSettings(); - } - CurrentSortAsc = _mapSettings.SortAscending; - CurrentSortMethod = (VideoSort.SortMethod)_mapSettings.SortBy; - currentLayout = (Layout)share.DefaultLayout; - CurrentLayout = (Layout)share.DefaultLayout; - } - } - - using (Profile.Settings xmlreader = new Profile.MPSettings()) - { - if (xmlreader.GetValueAsBool("movies", "rememberlastfolder", false)) - { - xmlreader.SetValue("movies", "lastfolder", folderName); - } - } - - SwitchLayout(); - UpdateButtonStates(); - } - - private void SaveFolderSettings(string folderName) - { - if (folderName == string.Empty) - { - folderName = "root"; - } - FolderSettings.AddFolderSetting(folderName, "VideoFiles", typeof(MapSettings), _mapSettings); - } - - private void ShowFileMenu(bool preselectDelete) - { - // get pincode - if (_fileMenuPinCode != string.Empty) - { - string userCode = string.Empty; - if (GetUserPasswordString(ref userCode) && userCode == _fileMenuPinCode) - { - OnShowFileMenu(preselectDelete); - } - } - else - { - OnShowFileMenu(preselectDelete); - } - } - - private static bool CheckExternalPlayer(string filename, bool isImage) - { - if (!_useInternalVideoPlayer) - { - if (!isImage) - { - // extensions filter - if (!string.IsNullOrEmpty(_externalPlayerExtensions)) - { - // Use external player if extension is valid - if (CheckExtension(filename)) - { - return true; - } - } - else - { - return true; - } - } - } - // DVD files - if (!_useInternalDVDVideoPlayer) - { - if (isImage && Util.Utils.IsDVDImage(filename)) - { - return true; - } - else if (!isImage) - { - if (filename.ToUpperInvariant().IndexOf(@"\VIDEO_TS\VIDEO_TS.IFO", StringComparison.InvariantCultureIgnoreCase) >= 0) - return true; - } - } - - return false; - } - - private static bool CheckExtension(string filename) - { - char[] splitter = { ';' }; - string[] extensions = _externalPlayerExtensions.Split(splitter); - - foreach (string extension in extensions) - { - if (extension.Trim().Equals(Path.GetExtension(filename), StringComparison.InvariantCultureIgnoreCase)) - { - return true; - } - } - return false; - } - - private void DoOnPlayBackStoppedOrChanged(g_Player.MediaType type, int timeMovieStopped, string filename, - string caller) - { - if (type != g_Player.MediaType.Video || filename.EndsWith("&txe=.wmv")) - { - return; - } - - // BD and IMAGES stop time (change to index.bdmv if mpls file is played or to IMG file) - ISelectBDHandler selectBDHandler = GetSelectBDHandler(); - selectBDHandler.IsBDPlayList(ref filename); - // Handle all movie files from idMovie - ArrayList movies = new ArrayList(); - int iidMovie = VideoDatabase.GetMovieId(filename); - VideoDatabase.GetFilesForMovie(iidMovie, ref movies); - HashSet watchedMovies = new HashSet(); - - int playTimePercentage = 0; - - // Stacked movies duration - if (IsStacked && TotalMovieDuration != 0) - { - int duration = 0; - - for (int i = 0; i < StackedMovieFiles.Count; i++) - { - int fileID = VideoDatabase.GetFileId((string)StackedMovieFiles[i]); - - if (g_Player.CurrentFile != (string)StackedMovieFiles[i]) - { - duration += VideoDatabase.GetVideoDuration(fileID); - continue; - } - playTimePercentage = (100 * (duration + timeMovieStopped) / TotalMovieDuration); - break; - } - } - else - { - if (g_Player.Player.Duration >= 1) - { - playTimePercentage = (int)Math.Ceiling((timeMovieStopped / g_Player.Player.Duration) * 100); - } - } - - if (movies.Count <= 0) - { - return; - } - - for (int i = 0; i < movies.Count; i++) - { - string strFilePath = (string)movies[i]; - - int idFile = VideoDatabase.GetFileId(strFilePath); - int idMovie = VideoDatabase.GetMovieId(strFilePath); - - if (idFile < 0) - { - break; - } - - if (g_Player.IsDVDMenu) - { - VideoDatabase.SetMovieStopTimeAndResumeData(idFile, 0, null, g_Player.SetResumeBDTitleState); - watchedMovies.Add(strFilePath); - VideoDatabase.SetMovieWatchedStatus(idMovie, true, 100); - VideoDatabase.MovieWatchedCountIncrease(idMovie); - } - else if ((filename.Trim().ToLowerInvariant().Equals(strFilePath.Trim().ToLowerInvariant())) && (timeMovieStopped > 0) && g_Player.SetResumeBDTitleState != -2) - { - byte[] resumeData = null; - g_Player.Player.GetResumeState(out resumeData); - Log.Info("GUIVideoFiles: {0} idFile={1} timeMovieStopped={2} resumeData={3} bdtitle={4}", caller, idFile, timeMovieStopped, - resumeData, g_Player.SetResumeBDTitleState); - VideoDatabase.SetMovieStopTimeAndResumeData(idFile, timeMovieStopped, resumeData, g_Player.SetResumeBDTitleState); - Log.Debug("GUIVideoFiles: {0} store resume time", caller); - - //Set file "watched" only if user % value or higher played time (share view) - if (playTimePercentage >= _watchedPercentage) - { - watchedMovies.Add(strFilePath); - VideoDatabase.SetMovieWatchedStatus(idMovie, true, playTimePercentage); - VideoDatabase.MovieWatchedCountIncrease(idMovie); - } - else - { - int iPercent = 0; // Not used, just needed for the watched status call - int iTImesWatched = 0; - bool watched = VideoDatabase.GetmovieWatchedStatus(idMovie, out iPercent, - out iTImesWatched); - - if (!watched) - { - VideoDatabase.SetMovieWatchedStatus(idMovie, false, playTimePercentage); - } - else // Update new percentage if already watched - { - VideoDatabase.SetMovieWatchedStatus(idMovie, true, playTimePercentage); - } - } - } - else - { - VideoDatabase.DeleteMovieStopTime(idFile); - } - // Update groups with rules - VideoDatabase.UpdateUserGroupWithRule(idMovie); - } - - if (_markWatchedFiles) - { - // Update db view watched status for played movie - IMDBMovie movie = new IMDBMovie(); - VideoDatabase.GetMovieInfo(filename, ref movie); - - if (!movie.IsEmpty) - //Flag movie "watched" status only if user % value or higher played time (database view) - { - if (playTimePercentage >= _watchedPercentage || g_Player.IsDVDMenu) - { - movie.Watched = 1; - } - movie.DateWatched = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); - VideoDatabase.SetMovieInfoById(movie.ID, ref movie); - } - - if (VideoState.StartWindow != GetID) // Is play initiator dbview? - { - UpdateButtonStates(); - } - } - - if (SubEngine.GetInstance().IsModified()) - { - bool shouldSave = false; - - if (SubEngine.GetInstance().AutoSaveType == AutoSaveTypeEnum.ASK) - { - if (!g_Player.Paused) - { - g_Player.Pause(); - } - - GUIDialogYesNo dlgYesNo = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_YES_NO); - dlgYesNo.SetHeading(GUILocalizeStrings.Get(1318));// Save subtitle - dlgYesNo.SetLine(1, GUILocalizeStrings.Get(1319)); // Save modified subtitle? - dlgYesNo.SetDefaultToYes(true); - dlgYesNo.DoModal(GUIWindowManager.ActiveWindow); - shouldSave = dlgYesNo.IsConfirmed; - } - - if (shouldSave || SubEngine.GetInstance().AutoSaveType == AutoSaveTypeEnum.ALWAYS) - { - SubEngine.GetInstance().SaveToDisk(); - } - } - } - - private void OnPlayBackChanged(g_Player.MediaType type, int timeMovieStopped, string filename) - { - DoOnPlayBackStoppedOrChanged(type, timeMovieStopped, filename, "OnPlayBackChanged"); - } - - private void OnPlayBackStopped(g_Player.MediaType type, int timeMovieStopped, string filename) - { - DoOnPlayBackStoppedOrChanged(type, timeMovieStopped, filename, "OnPlayBackStopped"); - } - - private void OnPlayBackEnded(g_Player.MediaType type, string filename) - { - if (type != g_Player.MediaType.Video) - { - return; - } - - // BD-DVD image stop time (change to index.bdmv if mpls file is played) - ISelectBDHandler selectBDHandler = GetSelectBDHandler(); - selectBDHandler.IsBDPlayList(ref filename); - - // Handle all movie files from idMovie - ArrayList movies = new ArrayList(); - HashSet watchedMovies = new HashSet(); - - int idMovie = VideoDatabase.GetMovieId(filename); - - if (idMovie >= 0) - { - VideoDatabase.GetFilesForMovie(idMovie, ref movies); - - for (int i = 0; i < movies.Count; i++) - { - string strFilePath = (string)movies[i]; - byte[] resumeData = null; - int idFile = VideoDatabase.GetFileId(strFilePath); - if (idFile < 0) - { - break; - } - // Set resumedata to zero - VideoDatabase.GetMovieStopTimeAndResumeData(idFile, out resumeData, g_Player.SetResumeBDTitleState); - VideoDatabase.SetMovieStopTimeAndResumeData(idFile, 0, resumeData, g_Player.SetResumeBDTitleState); - watchedMovies.Add(strFilePath); - } - - int playTimePercentage = 0; - - if (IsStacked && TotalMovieDuration != 0) - { - int duration = 0; - - for (int i = 0; i < StackedMovieFiles.Count; i++) - { - int fileID = VideoDatabase.GetFileId((string)StackedMovieFiles[i]); - - if (filename != (string)StackedMovieFiles[i]) - { - duration += VideoDatabase.GetVideoDuration(fileID); - continue; - } - playTimePercentage = (int)(100 * (duration + g_Player.Player.CurrentPosition) / TotalMovieDuration); - break; - } - } - else - { - playTimePercentage = 100; - } - - IMDBMovie details = new IMDBMovie(); - VideoDatabase.GetMovieInfoById(idMovie, ref details); - - if (playTimePercentage >= _watchedPercentage) - { - details.Watched = 1; - VideoDatabase.SetWatched(details); - VideoDatabase.SetMovieWatchedStatus(idMovie, true, playTimePercentage); - VideoDatabase.MovieWatchedCountIncrease(idMovie); - // Set date watched - VideoDatabase.SetDateWatched(details); - } - else - { - int percent = 0; - int timesWatched = 0; - bool wStatus = VideoDatabase.GetmovieWatchedStatus(idMovie, out percent, out timesWatched); - VideoDatabase.SetMovieWatchedStatus(idMovie, wStatus, playTimePercentage); - } - // Update groups with rules - VideoDatabase.UpdateUserGroupWithRule(idMovie); - } - } - - private void OnPlayBackStarted(g_Player.MediaType type, string filename) - { - if (type != g_Player.MediaType.Video) - { - return; - } - - if (!Util.Utils.IsRemoteUrl(filename)) - { - int idFile = VideoDatabase.GetFileId(filename); - - if (idFile == -1) - { - AddFileToDatabase(filename); - idFile = VideoDatabase.GetFileId(filename); - } - - if (idFile != -1) - { - int videoDuration = (int) g_Player.Duration; - VideoDatabase.SetVideoDuration(idFile, videoDuration); - } - } - } - - // Play all files in selected directory - private void OnPlayAll(string path) - { - // Get all video files in selected folder and it's subfolders - ArrayList playFiles = new ArrayList(); - AddVideoFiles(path, ref playFiles); - - if(playFiles.Count == 0) - { - return; - } - - int selectedOption = 0; - - GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_MENU); - - // Check and play according to setting value - if (_howToPlayAll == 3) // Ask, select sort method from options in GUIDialogMenu - { - if (dlg == null) - { - return; - } - dlg.Reset(); - dlg.SetHeading(498); // menu - dlg.AddLocalizedString(103); // By Name - dlg.AddLocalizedString(104); // By Date - dlg.AddLocalizedString(191); // Shuffle - // Show GUIDialogMenu - dlg.DoModal(GetID); - - if (dlg.SelectedId == -1) - { - return; - } - - selectedOption = dlg.SelectedId; - } - else // Don't ask, sort according to setting and play videos - { - selectedOption = _howToPlayAll; - } - - // Get current playlist - _currentPlaylistType = new PlayListType(); - _currentPlaylistType = _playlistPlayer.CurrentPlaylistType; - _currentPlaylistIndex = _playlistPlayer.CurrentSong; - - // Reset playlist - _playlistPlayer.Reset(); - _playlistPlayer.CurrentPlaylistType = PlayListType.PLAYLIST_VIDEO; - PlayList tmpPlayList = _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO); - tmpPlayList.Clear(); - - // Do sorting - switch (selectedOption) - { - // - // ****** Watch out for fallthrough of empty cases if reordering CASE ******* - // - case 0: // By name == 103 - case 103: - AddToPlayList(tmpPlayList, playFiles.ToArray()); - List sortedPlayListItems = new List(); - sortedPlayListItems.AddRange(tmpPlayList); - sortedPlayListItems.Sort((item1, item2) => StringLogicalComparer.Compare(item1.Description, item2.Description)); - tmpPlayList.Clear(); - - foreach (PlayListItem playListItem in sortedPlayListItems) - { - tmpPlayList.Add(playListItem); - } - - break; - - case 1: // By date (date modified) == 104 - case 104: - IOrderedEnumerable sortedPlayList = playFiles.ToArray().OrderBy(fn => new FileInfo((string)fn).LastWriteTime); - AddToPlayList(tmpPlayList, sortedPlayList); - break; - - case 2: // Shuffle == 191 - case 191: - AddToPlayList(tmpPlayList, playFiles.ToArray()); - tmpPlayList.Shuffle(); - break; - } - // Play movies - PlayMovieFromPlayList(false, true); - } - - private void AddToPlayList(PlayList tmpPlayList, IEnumerable sortedPlayList) - { - foreach (string file in sortedPlayList) - { - // Remove stop data if exists - int idFile = VideoDatabase.GetFileId(file); - - if (idFile >= 0) - { - VideoDatabase.DeleteMovieStopTime(idFile); - } - - // Add file to tmp playlist - PlayListItem newItem = new PlayListItem(); - newItem.FileName = file; - // Set file description (for sorting by name -> DVD IFO file problem) - string description = string.Empty; - - if (file.ToUpperInvariant().IndexOf(@"\VIDEO_TS\VIDEO_TS.IFO", StringComparison.InvariantCultureIgnoreCase) >= 0) - { - string dvdFolder = file.Substring(0, file.ToUpperInvariant().IndexOf(@"\VIDEO_TS\VIDEO_TS.IFO", StringComparison.InvariantCultureIgnoreCase)); - description = Path.GetFileName(dvdFolder); - } - if (file.ToUpperInvariant().IndexOf(@"\BDMV\INDEX.BDMV", StringComparison.InvariantCultureIgnoreCase) >= 0) - { - string bdFolder = file.Substring(0, file.ToUpperInvariant().IndexOf(@"\BDMV\INDEX.BDMV", StringComparison.InvariantCultureIgnoreCase)); - description = Path.GetFileName(bdFolder); - } - else - { - description = Path.GetFileName(file); - } - - newItem.Description = description; - newItem.Type = PlayListItem.PlayListItemType.Video; - tmpPlayList.Add(newItem); - } - } - - /// - /// Adds file (full path) and it's stacked parts (method will search - /// for them inside strFile folder) into videodatabase (movie table) - /// This method will also fill mediaInfo data and file duration id - /// if they are not exists. - /// - /// - /// - private ArrayList AddFileToDatabase(string strFile) - { - ArrayList files = new ArrayList(); - // Stop is file is not video - if (!Util.Utils.IsVideo(strFile)) - { - return files; - } - // ?? - if (PlayListFactory.IsPlayList(strFile)) - { - return files; - } - // Don't add web streams (e.g.: from Online videos) - if (strFile.StartsWith("http:")) - { - return files; - } - - ArrayList allFiles = new ArrayList(); - - // If this is database movie, get files and return - if (VideoDatabase.HasMovieInfo(strFile)) - { - IMDBMovie movie = new IMDBMovie(); - VideoDatabase.GetMovieInfo(strFile, ref movie); - VideoDatabase.GetFilesForMovie(movie.ID, ref allFiles); - - // Check if we have mediainfo for files and add it if necessary - foreach (string file in allFiles) - { - if (!VideoDatabase.HasMediaInfo(file)) - { - VideoDatabase.AddMovieFile(file); - } - } - - return allFiles; - } - // If file is not scanned (movie is not in the db ie. user video) - int movieId = VideoDatabase.AddMovieFile(strFile); - files.Add(strFile); - - // Check if file is stackable and get rest of the stack - if (IsFileStackable(strFile)) - { - List items = _virtualDirectory.GetDirectoryUnProtectedExt(_currentFolder, true); - - for (int i = 0; i < items.Count; ++i) - { - GUIListItem temporaryListItem = (GUIListItem)items[i]; - - if (temporaryListItem.IsFolder) - { - if(!IsMovieFolder(temporaryListItem.Path)) - { - continue; - } - else - { - temporaryListItem.IsBdDvdFolder = true; - } - } - - IMDBMovie movie = (IMDBMovie) temporaryListItem.AlbumInfoTag; - - if (temporaryListItem.AlbumInfoTag == null) - { - IMDBMovie.SetMovieData(temporaryListItem); - movie = temporaryListItem.AlbumInfoTag as IMDBMovie; - } - - if (movie == null) - { - continue; - } - - if (movie.VideoFileName != strFile) - { - // Add rest of stackable items for main file (main file is already in array) - if (!temporaryListItem.IsBdDvdFolder) - { - if (Util.Utils.ShouldStack(movie.VideoFileName, strFile)) - { - allFiles.Add(items[i]); - } - } - else - { - string strPath, strFileName; - Util.Utils.Split(strFile, out strPath, out strFileName); - - if (Util.Utils.PathShouldStack(movie.VideoFilePath, strPath)) - { - allFiles.Add(items[i]); - } - } - } - } - - // Add rest of the stackable files - foreach (GUIListItem item in allFiles) - { - IMDBMovie movie = (IMDBMovie) item.AlbumInfoTag; - int idFile = VideoDatabase.GetFileId(movie.VideoFileName); - - if (idFile == -1) - { - string path, filename; - DatabaseUtility.Split(movie.VideoFileName, out path, out filename); - int pathId = VideoDatabase.AddPath(path); - VideoDatabase.AddFile(movieId, pathId, filename); - } - - files.Add(movie.VideoFileName); - } - } - - return files; - } - - private void SetLabel(GUIListItem item) - { - ISelectDVDHandler sDvd = GUIVideoFiles.GetSelectDvdHandler(); - ISelectBDHandler sBd = GUIVideoFiles.GetSelectBDHandler(); - - string strSize1 = string.Empty, strDate = string.Empty; - - if (item.FileInfo != null && !item.IsFolder) - { - strSize1 = Util.Utils.GetSize(item.FileInfo.Length); - } - - if (item.FileInfo != null && !item.IsFolder) - { - if (CurrentSortMethod == VideoSort.SortMethod.Modified) - { - strDate = item.FileInfo.ModificationTime.ToShortDateString() + " " + - item.FileInfo.ModificationTime.ToString("t", CultureInfo.CurrentCulture.DateTimeFormat); - } - else - { - strDate = item.FileInfo.CreationTime.ToShortDateString() + " " + - item.FileInfo.CreationTime.ToString("t", CultureInfo.CurrentCulture.DateTimeFormat); - } - } - - if (CurrentSortMethod == VideoSort.SortMethod.Name) - { - if (item.IsFolder && (sDvd.IsDvdDirectory(item.Path) || sBd.IsBDDirectory(item.Path))) - { - // Reserved if needed - } - else - { - item.Label2 = strSize1; - } - - } - - if (CurrentSortMethod == VideoSort.SortMethod.Name_With_Duration && !item.IsFolder && item.Label != "..") - { - if (item.Duration > 0) - { - item.Label2 = Util.Utils.SecondsToShortHMSString(item.Duration); - } - else - { - item.Label2 = string.Empty; - } - } - else if (CurrentSortMethod == VideoSort.SortMethod.Created || CurrentSortMethod == VideoSort.SortMethod.Date || CurrentSortMethod == VideoSort.SortMethod.Modified) - { - item.Label2 = strDate; - } - else - { - if (item.IsFolder && (sDvd.IsDvdDirectory(item.Path) || sBd.IsBDDirectory(item.Path))) - { - //Reserved if needed - } - else - { - item.Label2 = strSize1; - } - } - } - - private void GUIWindowManager_OnNewMessage(GUIMessage message) - { - switch (message.Message) - { - case GUIMessage.MessageType.GUI_MSG_AUTOPLAY_VOLUME: - if (message.Param1 == (int)Ripper.AutoPlay.MediaType.VIDEO) - { - if (message.Param2 == (int)Ripper.AutoPlay.MediaSubType.DVD) - OnPlayDVD(message.Label, GetID); - - if (message.Param2 == (int)Ripper.AutoPlay.MediaSubType.BLURAY) - { - OnPlayBD(message.Label, GetID); - } - - else if (message.Param2 == (int)Ripper.AutoPlay.MediaSubType.VCD || - message.Param2 == (int)Ripper.AutoPlay.MediaSubType.FILES) - OnPlayFiles((System.Collections.ArrayList)message.Object); - } - break; - - case GUIMessage.MessageType.GUI_MSG_VOLUME_REMOVED: - if (g_Player.Playing && g_Player.IsVideo && - message.Label.Equals(g_Player.CurrentFile.Substring(0, 2), StringComparison.InvariantCultureIgnoreCase)) - { - if (!File.Exists(g_Player.CurrentFile)) - { - Log.Info("GUIVideoFiles: Stop since media is ejected"); - g_Player.Stop(); - _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO_TEMP).Clear(); - _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO).Clear(); - } - else - { - return; - } - } - - if (GUIWindowManager.ActiveWindow == GetID) - { - if (Util.Utils.IsDVD(_currentFolder)) - { - _currentFolder = string.Empty; - LoadDirectory(_currentFolder); - } - } - break; - - case GUIMessage.MessageType.GUI_MSG_ONRESUME: - using (Settings xmlreader = new MPSettings()) - { - if (!xmlreader.GetValueAsBool("general", "showlastactivemodule", false)) - { - _currentFolder = string.Empty; - } - } - - Log.Debug("{0}:{1}", SerializeName, message.Message); - break; - } - } - - private void SetMovieWatchStatus(string movieFileName, bool isFolder, bool watched) - { - ISelectDVDHandler selectDvdHandler = GetSelectDvdHandler(); - ISelectBDHandler selectBDHandler = GetSelectBDHandler(); - - if (isFolder && selectDvdHandler.IsDvdDirectory(movieFileName)) - { - movieFileName = selectDvdHandler.GetFolderVideoFile(movieFileName); - } - if (isFolder && selectBDHandler.IsBDDirectory(movieFileName)) - { - movieFileName = selectBDHandler.GetFolderVideoFile(movieFileName); - } - - VideoDatabase.AddMovieFile(movieFileName); - - if (VideoDatabase.HasMovieInfo(movieFileName)) - { - IMDBMovie movieDetails = new IMDBMovie(); - VideoDatabase.GetMovieInfo(movieFileName, ref movieDetails); - - if (!watched) - { - movieDetails.Watched = 0; - } - else - { - movieDetails.Watched = 1; - } - - VideoDatabase.SetWatched(movieDetails); - // Update groups with rules - VideoDatabase.UpdateUserGroupWithRule(movieDetails.ID); - } - - int iTimesWatched = 0; - int movieId = VideoDatabase.GetMovieId(movieFileName); - - if (!watched) - { - VideoDatabase.SetMovieWatchedStatus(movieId, false, 0); - VideoDatabase.SetMovieStopTime(movieId, 0); - VideoDatabase.SetMovieWatchedCount(movieId, 0); - } - else - { - int iPercent = 100; - VideoDatabase.GetmovieWatchedStatus(movieId, out iPercent, out iTimesWatched); - VideoDatabase.SetMovieWatchedStatus(movieId, true, 100); - - if (iTimesWatched <= 0) - { - VideoDatabase.MovieWatchedCountIncrease(movieId); - } - } - } - - private void item_OnItemSelected(GUIListItem item, GUIControl parent) - { - GUIPropertyManager.SetProperty("#groupmovielist", string.Empty); - - _currentSelectedItem = facadeLayout.SelectedListItemIndex; - IMDBMovie info = item.AlbumInfoTag as IMDBMovie; - - // Read database only once per item - if (item.AlbumInfoTag == null) - { - IMDBMovie.SetMovieData(item); - info = item.AlbumInfoTag as IMDBMovie; - } - - if (info == null) - { - return; - } - - _selectedFilename = info.VideoFileName; - IMDBMovie.SetMovieProperties(item); - GUIFilmstripControl filmstrip = parent as GUIFilmstripControl; - - if (filmstrip != null) - { - filmstrip.InfoImageFileName = item.ThumbnailImage; - } - } - - private bool GetUserPasswordString(ref string sString) - { - VirtualKeyboard keyboard = (VirtualKeyboard)GUIWindowManager.GetWindow((int)Window.WINDOW_VIRTUAL_KEYBOARD); - - if (null == keyboard) - { - return false; - } - - keyboard.IsSearchKeyboard = true; - keyboard.Reset(); - keyboard.Password = true; - keyboard.Text = sString; - keyboard.DoModal(GetID); // show it... - - if (keyboard.IsConfirmed) - { - sString = keyboard.Text; - } - - return keyboard.IsConfirmed; - } - - private void OnShowFileMenu(bool preselectDelete) - { - GUIListItem item = facadeLayout.SelectedListItem; - - if (item == null) - { - return; - } - - if (item.IsFolder && item.Label == "..") - { - return; - } - - if (!_virtualDirectory.RequestPin(item.Path)) - { - return; - } - - // init - GUIDialogFile dlgFile = (GUIDialogFile)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_FILE); - - if (dlgFile == null) - { - return; - } - - // File operation settings - dlgFile.SetSourceItem(item); - dlgFile.SetSourceDir(_currentFolder); - dlgFile.SetDestinationDir(_fileMenuDestinationDir); - dlgFile.SetDirectoryStructure(_virtualDirectory); - - if (preselectDelete) - { - dlgFile.PreselectDelete(); - } - - dlgFile.DoModal(GetID); - _fileMenuDestinationDir = dlgFile.GetDestinationDir(); - //final - _oldStateSMSsearch = facadeLayout.EnableSMSsearch; - facadeLayout.EnableSMSsearch = false; - - if (dlgFile.Reload()) - { - int selectedItem = facadeLayout.SelectedListItemIndex; - - if (_currentFolder != dlgFile.GetSourceDir()) - { - selectedItem = -1; - } - - LoadDirectory(_currentFolder); - - if (selectedItem >= 0) - { - if (selectedItem >= facadeLayout.Count) - selectedItem = facadeLayout.Count - 1; - GUIControl.SelectItemControl(GetID, facadeLayout.GetID, selectedItem); - } - } - - dlgFile.DeInit(); - dlgFile = null; - _resetSMSsearchDelay = DateTime.Now; - _resetSMSsearch = true; - } - - private static bool IsFolderPinProtected(string folder) - { - string pinCode = string.Empty; - return _virtualDirectory.IsProtectedShare(folder, out pinCode); - } - - private static void AddVideoFiles(string path, ref ArrayList availableFiles) - { - // - // Count the files in the current directory - // - bool currentCreateVideoThumbs = false; - - try - { - VirtualDirectory dir = new VirtualDirectory(); - dir.SetExtensions(Util.Utils.VideoExtensions); - // Temporary disable thumbcreation - using (Profile.Settings xmlreader = new MPSettings()) - { - currentCreateVideoThumbs = xmlreader.GetValueAsBool("thumbnails", "videoondemand", true); - } - using (Profile.Settings xmlwriter = new MPSettings()) - { - xmlwriter.SetValueAsBool("thumbnails", "videoondemand", false); - } - - List items = dir.GetDirectoryUnProtectedExt(path, true); - - foreach (GUIListItem item in items) - { - if (item.IsFolder) - { - if (item.Label != "..") - { - if (item.Path.ToUpperInvariant().IndexOf("VIDEO_TS") >= 0) - { - string strFile = String.Format(@"{0}\VIDEO_TS.IFO", item.Path); - availableFiles.Add(strFile); - } - if (item.Path.ToUpperInvariant().IndexOf("BDMV") >= 0) - { - string strFile = String.Format(@"{0}\index.bdmv", item.Path); - availableFiles.Add(strFile); - } - else - { - AddVideoFiles(item.Path, ref availableFiles); - } - } - } - else - { - availableFiles.Add(item.Path); - } - } - } - catch (Exception e) - { - Log.Info("Exception counting files:{0}", e); - // Ignore - } - finally - { - // Restore thumbcreation setting - using (Profile.Settings xmlwriter = new MPSettings()) - { - xmlwriter.SetValueAsBool("thumbnails", "videoondemand", currentCreateVideoThumbs); - } - } - } - - private void DownloadSubtitles() - { - try - { - GUIListItem item = facadeLayout.SelectedListItem; - - if (item == null) - { - return; - } - string path = item.Path; - bool isDVD = (path.ToUpperInvariant().IndexOf("VIDEO_TS") >= 0); - List listFiles = _virtualDirectory.GetDirectoryUnProtectedExt(_currentFolder, false); - string[] subExts = { - ".utf", ".utf8", ".utf-8", ".sub", ".srt", ".smi", ".rt", ".txt", ".ssa", ".aqt", ".jss", - ".ass", ".idx", ".ifo", ".webvtt", ".vtt" - }; - if (!isDVD) - { - // check if movie has subtitles - for (int i = 0; i < subExts.Length; i++) - { - for (int x = 0; x < listFiles.Count; ++x) - { - if (listFiles[x].IsFolder) - { - continue; - } - string subTitleFileName = listFiles[x].Path; - subTitleFileName = Path.ChangeExtension(subTitleFileName, subExts[i]); - - if (String.Compare(listFiles[x].Path, subTitleFileName, true) == 0) - { - string localSubtitleFileName = _virtualDirectory.GetLocalFilename(subTitleFileName); - Util.Utils.FileDelete(localSubtitleFileName); - _virtualDirectory.DownloadRemoteFile(subTitleFileName, 0); - } - } - } - } - else //download entire DVD - { - for (int i = 0; i < listFiles.Count; ++i) - { - if (listFiles[i].IsFolder) - { - continue; - } - - if (String.Compare(listFiles[i].Path, path, true) == 0) - { - continue; - } - - _virtualDirectory.DownloadRemoteFile(listFiles[i].Path, 0); - } - } - } - catch (ThreadAbortException) { } - } - - private bool IsFileStackable(string filename) - { - var pattern = Util.Utils.StackExpression(); - - for (int i = 0; i < pattern.Length; i++) - { - if (pattern[i].IsMatch(filename)) - { - return true; - } - } - return false; - } - - private void GetNfoFiles(string path, ref ArrayList nfoFiles) - { - string[] files = Directory.GetFiles(path, "*.nfo", SearchOption.AllDirectories); - var sortedFiles = files.OrderBy(f => f); - - foreach (string file in sortedFiles) - { - nfoFiles.Add(file); - } - } - - private void ReleaseResources() - { - if (facadeLayout != null) - { - facadeLayout.Clear(); - } - } - - private void CreateFolderThumb(GUIListItem item, bool recreateAll) - { - // find first 4 jpegs in this subfolder - - List itemlist = _virtualDirectory.GetDirectoryUnProtectedExt(item.Path, true); - - if (!recreateAll) - { - Filter(ref itemlist); - } - - List pictureList = new List(); - foreach (GUIListItem subitem in itemlist) - { - if (!subitem.IsFolder) - { - string[] thumbs = { - Util.Utils.GetVideosLargeThumbPathname(subitem.Path), - Path.ChangeExtension(subitem.Path, ".jpg"), - Path.ChangeExtension(subitem.Path, ".tbn"), - Path.ChangeExtension(subitem.Path, ".png") - }; - - foreach (string s in thumbs) - { - string thumbStr = s; - if (Util.Utils.FileExistsInCache(thumbStr)) - { - pictureList.Add(thumbStr); - break; - } - } - } - if (pictureList.Count >= 4) - { - break; - } - } - // combine 4 image files into one folder.jpg - - string filePath = Path.Combine(item.Path, @"Folder.jpg"); - - if (pictureList.Count == 1) - { - try - { - File.Copy(pictureList[0], filePath, true); - } - catch - { - Log.Error("CreateFolderThumb:: unable to create {0}", filePath); - } - } - else if (pictureList.Count > 1) - { - Util.Utils.FileDelete(filePath); - Util.Utils.CreateFolderPreviewThumb(pictureList, filePath, false); - } - - int selectedIndex = facadeLayout.SelectedListItemIndex; - LoadDirectory(_currentFolder, false); - facadeLayout.SelectedListItemIndex = selectedIndex; - } - - private static void Filter(ref List itemlist) - { - itemlist.RemoveAll(ContainsFolderThumb); - } - - private static bool ContainsFolderThumb(GUIListItem aItem) - { - if (!aItem.IsFolder && aItem.Path.Contains(@"folder.jpg")) - { - return true; - } - else - { - return false; - } - } - - #endregion - - #region Thread Set thumbs - - private void SetImdbThumbs(List itemlist, ISelectDVDHandler selectDVDHandler) - { - if (_setThumbs != null && _setThumbs.IsAlive) - { - _setThumbs.Abort(); - _setThumbs = null; - } - - _setThumbsThreadAborted = false; - - _threadGUIItems.Clear(); - _threadGUIItems.AddRange(itemlist); - _threadISelectDVDHandler = selectDVDHandler; - - _setThumbs = new Thread(ThreadSetIMDBThumbs); - _setThumbs.Priority = ThreadPriority.Lowest; - _setThumbs.IsBackground = true; - _setThumbs.Start(); - } - - private void ThreadSetIMDBThumbs() - { - try - { - _threadISelectDVDHandler.SetIMDBThumbs(_threadGUIItems, _markWatchedFiles); - // Refresh thumb on selected item - _currentSelectedItem = facadeLayout.SelectedListItemIndex; - SelectCurrentItem(); - } - catch (ThreadAbortException) - { - Log.Debug("GUIVideoFiles: Thread SetIMDBThumbs aborted."); - _setThumbsThreadAborted = true; - } - } - - #endregion - - #region IMDB.IProgress - - public bool OnDisableCancel(IMDBFetcher fetcher) - { - GUIDialogProgress pDlgProgress = - (GUIDialogProgress) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_PROGRESS); - if (pDlgProgress.IsInstance(fetcher)) - { - pDlgProgress.DisableCancel(true); - } - return true; - } - - public void OnProgress(string line1, string line2, string line3, int percent) - { - if (!GUIWindowManager.IsRouted) - { - return; - } - GUIDialogProgress pDlgProgress = - (GUIDialogProgress) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_PROGRESS); - pDlgProgress.ShowProgressBar(true); - pDlgProgress.SetLine(1, line1); - pDlgProgress.SetLine(2, line2); - if (percent > 0) - { - pDlgProgress.SetPercentage(percent); - } - pDlgProgress.Progress(); - } - - public bool OnSearchStarting(IMDBFetcher fetcher) - { - GUIDialogProgress pDlgProgress = - (GUIDialogProgress) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_PROGRESS); - // show dialog that we're busy querying www.imdb.com - String heading; - if (_scanning) - { - heading = String.Format("{0}:{1}/{2}", GUILocalizeStrings.Get(197), _scanningFileNumber, _scanningFileTotal); - } - else - { - heading = GUILocalizeStrings.Get(197); - } - pDlgProgress.Reset(); - pDlgProgress.SetHeading(heading); - pDlgProgress.SetLine(1, fetcher.MovieName); - pDlgProgress.SetLine(2, string.Empty); - pDlgProgress.SetObject(fetcher); - pDlgProgress.StartModal(GUIWindowManager.ActiveWindow); - return true; - } - - public bool OnSearchStarted(IMDBFetcher fetcher) - { - GUIDialogProgress pDlgProgress = - (GUIDialogProgress) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_PROGRESS); - pDlgProgress.SetObject(fetcher); - pDlgProgress.DoModal(GUIWindowManager.ActiveWindow); - if (pDlgProgress.IsCanceled) - { - return false; - } - return true; - } - - public bool OnSearchEnd(IMDBFetcher fetcher) - { - GUIDialogProgress pDlgProgress = - (GUIDialogProgress) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_PROGRESS); - if ((pDlgProgress != null) && (pDlgProgress.IsInstance(fetcher))) - { - pDlgProgress.Close(); - } - return true; - } - - public bool OnMovieNotFound(IMDBFetcher fetcher) - { - if (_scanning) - { - _conflictFiles.Add(fetcher.Movie); - return false; - } - // show dialog... - GUIDialogOK pDlgOk = (GUIDialogOK) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_OK); - pDlgOk.SetHeading(195); - pDlgOk.SetLine(1, fetcher.MovieName); - pDlgOk.SetLine(2, string.Empty); - pDlgOk.DoModal(GUIWindowManager.ActiveWindow); - return true; - } - - public bool OnDetailsStarting(IMDBFetcher fetcher) - { - GUIDialogProgress pDlgProgress = - (GUIDialogProgress) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_PROGRESS); - // show dialog that we're downloading the movie info - String heading; - if (_scanning) - { - heading = String.Format("{0}:{1}/{2}", GUILocalizeStrings.Get(198), _scanningFileNumber, _scanningFileTotal); - } - else - { - heading = GUILocalizeStrings.Get(198); - } - pDlgProgress.Reset(); - pDlgProgress.SetHeading(heading); - //pDlgProgress.SetLine(0, strMovieName); - pDlgProgress.SetLine(1, fetcher.MovieName); - pDlgProgress.SetLine(2, string.Empty); - pDlgProgress.SetObject(fetcher); - pDlgProgress.StartModal(GUIWindowManager.ActiveWindow); - return true; - } - - public bool OnDetailsStarted(IMDBFetcher fetcher) - { - GUIDialogProgress pDlgProgress = - (GUIDialogProgress) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_PROGRESS); - pDlgProgress.SetObject(fetcher); - pDlgProgress.DoModal(GUIWindowManager.ActiveWindow); - if (pDlgProgress.IsCanceled) - { - return false; - } - return true; - } - - public bool OnDetailsEnd(IMDBFetcher fetcher) - { - GUIDialogProgress pDlgProgress = - (GUIDialogProgress) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_PROGRESS); - if ((pDlgProgress != null) && (pDlgProgress.IsInstance(fetcher))) - { - pDlgProgress.Close(); - } - return true; - } - - public bool OnActorsStarting(IMDBFetcher fetcher) - { - GUIDialogProgress pDlgProgress = - (GUIDialogProgress) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_PROGRESS); - // show dialog that we're downloading the actor info - String heading; - if (_scanning) - { - heading = String.Format("{0}:{1}/{2}", GUILocalizeStrings.Get(986), _scanningFileNumber, _scanningFileTotal); - } - else - { - heading = GUILocalizeStrings.Get(1301); - } - pDlgProgress.Reset(); - pDlgProgress.SetHeading(heading); - //pDlgProgress.SetLine(0, strMovieName); - pDlgProgress.SetLine(1, fetcher.MovieName); - pDlgProgress.SetLine(2, string.Empty); - pDlgProgress.SetObject(fetcher); - pDlgProgress.StartModal(GUIWindowManager.ActiveWindow); - return true; - } - - public bool OnActorInfoStarting(IMDBFetcher fetcher) - { - GUIDialogProgress pDlgProgress = - (GUIDialogProgress) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_PROGRESS); - // show dialog that we're downloading the actor info - String heading; - if (_scanning) - { - heading = String.Format("{0}:{1}/{2}", GUILocalizeStrings.Get(986), _scanningFileNumber, _scanningFileTotal); - } - else - { - heading = GUILocalizeStrings.Get(1302); - } - pDlgProgress.Reset(); - pDlgProgress.SetHeading(heading); - //pDlgProgress.SetLine(0, strMovieName); - pDlgProgress.SetLine(1, fetcher.ActorName); - pDlgProgress.SetLine(2, string.Empty); - pDlgProgress.SetObject(fetcher); - pDlgProgress.StartModal(GUIWindowManager.ActiveWindow); - return true; - } - - public bool OnActorsStarted(IMDBFetcher fetcher) - { - GUIDialogProgress pDlgProgress = - (GUIDialogProgress) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_PROGRESS); - pDlgProgress.SetObject(fetcher); - pDlgProgress.DoModal(GUIWindowManager.ActiveWindow); - if (pDlgProgress.IsCanceled) - { - return false; - } - return true; - } - - public bool OnActorsEnd(IMDBFetcher fetcher) - { - return true; - } - - public bool OnDetailsNotFound(IMDBFetcher fetcher) - { - if (_scanning) - { - _conflictFiles.Add(fetcher.Movie); - return false; - } - // show dialog... - GUIDialogOK pDlgOk = (GUIDialogOK) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_OK); - // show dialog... - pDlgOk.SetHeading(195); - pDlgOk.SetLine(1, fetcher.MovieName); - pDlgOk.SetLine(2, string.Empty); - pDlgOk.DoModal(GUIWindowManager.ActiveWindow); - return false; - } - - public bool OnRequestMovieTitle(IMDBFetcher fetcher, out string movieName) - { - movieName = string.Empty; - - if (_scanning) - { - _conflictFiles.Add(fetcher.Movie); - movieName = string.Empty; - return false; - } - - string filename = string.Empty; - - if (!string.IsNullOrEmpty(_selectedFilename)) - { - try - { - if (_selectedFilename.ToUpperInvariant().Contains(@"\VIDEO_TS\VIDEO_TS.IFO")) - { - filename = _selectedFilename.ToUpperInvariant().Replace(@"\VIDEO_TS\VIDEO_TS.IFO", string.Empty); - int iIndex = 0; - iIndex = filename.LastIndexOf(@"\"); - movieName = filename.Substring(iIndex + 1); - } - else if (_selectedFilename.ToUpperInvariant().Contains(@"\BDMV\INDEX.BDMV")) - { - filename = _selectedFilename.ToUpperInvariant().Replace(@"\BDMV\INDEX.BDMV", string.Empty); - int iIndex = 0; - iIndex = filename.LastIndexOf(@"\"); - movieName = filename.Substring(iIndex + 1); - } - else - { - movieName = Path.GetFileNameWithoutExtension(_selectedFilename); - Util.Utils.RemoveStackEndings(ref filename); - } - } - catch (Exception ex) - { - Log.Error("GUIVideoFiles: OnRequestMovieTitle {0}", ex.Message); - } - } - else - { - movieName = fetcher.MovieName; - } - - if (VirtualKeyboard.GetKeyboard(ref movieName, GetID)) - { - if (movieName == string.Empty) - { - return false; - } - return true; - } - - movieName = string.Empty; - return false; - } - - public bool OnSelectMovie(IMDBFetcher fetcher, out int selectedMovie) - { - if (_scanning) - { - _conflictFiles.Add(fetcher.Movie); - selectedMovie = -1; - return false; - } - GUIDialogSelect pDlgSelect = (GUIDialogSelect) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_SELECT); - // more then 1 movie found - // ask user to select 1 - string filename = string.Empty; - - if (!string.IsNullOrEmpty(_selectedFilename)) - { - if (_selectedFilename.ToUpperInvariant().Contains(@"VIDEO_TS\VIDEO_TS.IFO")) - { - filename = _selectedFilename.ToUpperInvariant().Replace(@"\VIDEO_TS\VIDEO_TS.IFO", string.Empty); - int iIndex = 0; - iIndex = filename.LastIndexOf(@"\"); - filename = filename.Substring(iIndex + 1); - } - else if (_selectedFilename.ToUpperInvariant().Contains(@"BDMV\INDEX.BDMV")) - { - filename = _selectedFilename.ToUpperInvariant().Replace(@"\BDMV\INDEX.BDMV", string.Empty); - int iIndex = 0; - iIndex = filename.LastIndexOf(@"\"); - filename = filename.Substring(iIndex + 1); - } - else - { - filename = Path.GetFileNameWithoutExtension(_selectedFilename); - Util.Utils.RemoveStackEndings(ref filename); - } - } - - string strHeading = GUILocalizeStrings.Get(196); - - if (!string.IsNullOrEmpty(filename)) - { - GUIPropertyManager.SetProperty("#selecteditem", filename); - } - - pDlgSelect.SetHeading(strHeading); - pDlgSelect.Reset(); - - for (int i = 0; i < fetcher.Count; ++i) - { - pDlgSelect.Add(fetcher[i].Title); - } - - pDlgSelect.EnableButton(true); - pDlgSelect.SetButtonLabel(413); // manual - pDlgSelect.DoModal(GUIWindowManager.ActiveWindow); - // and wait till user selects one - selectedMovie = pDlgSelect.SelectedLabel; - - if (pDlgSelect.IsButtonPressed) - { - return true; - } - if (selectedMovie == -1) - { - return false; - } - return true; - } - - public bool OnSelectActor(IMDBFetcher fetcher, out int selectedActor) - { - GUIDialogSelect pDlgSelect = (GUIDialogSelect) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_SELECT); - // more then 1 actor found - // ask user to select 1 - pDlgSelect.SetHeading(GUILocalizeStrings.Get(1310)); //select actor - pDlgSelect.Reset(); - for (int i = 0; i < fetcher.Count; ++i) - { - pDlgSelect.Add(fetcher[i].Title); - } - pDlgSelect.EnableButton(false); - pDlgSelect.DoModal(GUIWindowManager.ActiveWindow); - - // and wait till user selects one - selectedActor = pDlgSelect.SelectedLabel; - if (selectedActor != -1) - { - return true; - } - return false; - } - - public bool OnScanStart(int total) - { - _scanning = true; - _conflictFiles.Clear(); - _scanningFileTotal = total; - _scanningFileNumber = 1; - return true; - } - - public bool OnScanEnd() - { - _scanning = false; - if (_conflictFiles.Count > 0) - { - GUIDialogSelect pDlgSelect = (GUIDialogSelect) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_SELECT); - // more than 1 movie found - // ask user to select 1 - do - { - pDlgSelect.Reset(); - pDlgSelect.SetHeading(892); //select movie - for (int i = 0; i < _conflictFiles.Count; ++i) - { - IMDBMovie currentMovie = (IMDBMovie) _conflictFiles[i]; - string strFileName = string.Empty; - string path = currentMovie.Path; - string filename = currentMovie.File; - if (path != string.Empty) - { - if (path.EndsWith(@"\")) - { - path = path.Substring(0, path.Length - 1); - currentMovie.Path = path; - } - if (filename.StartsWith(@"\")) - { - filename = filename.Substring(1); - currentMovie.File = filename; - } - strFileName = path + @"\" + filename; - } - else - { - strFileName = filename; - } - pDlgSelect.Add(strFileName); - } - pDlgSelect.EnableButton(true); - pDlgSelect.SetButtonLabel(4517); // manual - pDlgSelect.DoModal(GUIWindowManager.ActiveWindow); - - // and wait till user selects one - int selectedMovie = pDlgSelect.SelectedLabel; - if (pDlgSelect.IsButtonPressed) - { - break; - } - if (selectedMovie == -1) - { - break; - } - IMDBMovie movieDetails = (IMDBMovie) _conflictFiles[selectedMovie]; - string searchText = movieDetails.Title; - if (searchText == string.Empty) - { - searchText = movieDetails.SearchString; - } - if (VirtualKeyboard.GetKeyboard(ref searchText, GetID)) - { - if (searchText != string.Empty) - { - movieDetails.SearchString = searchText; - if (IMDBFetcher.GetInfoFromIMDB(this, ref movieDetails, false, true)) - { - if (movieDetails != null) - { - _conflictFiles.RemoveAt(selectedMovie); - } - } - } - } - } while (_conflictFiles.Count > 0); - } - return true; - } - - public bool OnScanIterating(int count) - { - _scanningFileNumber = count; - return true; - } - - public bool OnScanIterated(int count) - { - _scanningFileNumber = count; - GUIDialogProgress pDlgProgress = - (GUIDialogProgress) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_PROGRESS); - if (pDlgProgress.IsCanceled) - { - return false; - } - return true; - } - - #endregion - - #region ISetupForm Members - - public bool CanEnable() - { - return true; - } - - public bool HasSetup() - { - return false; - } - - public string PluginName() - { - return "Videos"; - } - - public bool DefaultEnabled() - { - return true; - } - - public int GetWindowId() - { - return GetID; - } - - public bool GetHome(out string strButtonText, out string strButtonImage, out string strButtonImageFocus, - out string strPictureImage) - { - strButtonText = GUILocalizeStrings.Get(3); - strButtonImage = string.Empty; - strButtonImageFocus = string.Empty; - strPictureImage = @"hover_my videos.png"; - return true; - } - - public string Author() - { - return "Frodo, ajs"; - } - - public string Description() - { - return "Watch and organize your video files"; - } - - public void ShowPlugin() - { - // TODO: Add GUIVideoFiles.ShowPlugin implementation - } - - #endregion - - #region IShowPlugin Members - - public bool ShowDefaultHome() - { - return true; - } - - #endregion - - public static string GetCurrentFolder - { - get { return _currentFolder; } - } - } + Log.Error("Script grabber error file: {0}, message : {1}", f.FullName, ex.Message); + } + } + + string defaultDatabase = string.Empty; + int defaultIndex = 0; + int dbNumber; + + using (Profile.Settings xmlreader = new MPSettings()) + { + defaultDatabase = xmlreader.GetValueAsString("moviedatabase", "database" + 0, "IMDB"); + dbNumber = xmlreader.GetValueAsInt("moviedatabase", "number", 0); + } + + foreach (KeyValuePair grabber in _grabberList) + { + dlg.Add(grabber.Value.Name + " - " + grabber.Value.Language); + + if (defaultDatabase == grabber.Key) + { + dlg.SelectedLabel = defaultIndex; + } + else + { + defaultIndex++; + } + } + + GUIWaitCursor.Hide(); + + dlg.DoModal(GUIWindowManager.ActiveWindow); + + if (dlg.SelectedId == -1) + { + return; + } + + using (Profile.Settings xmlwriter = new MPSettings()) + { + KeyValuePair grabber = _grabberList.ElementAt(dlg.SelectedLabel); + + + if (grabber.Key != "IMDB") + { + if (dbNumber == 0) + { + dbNumber = 1; + } + xmlwriter.SetValue("moviedatabase", "number", dbNumber); + xmlwriter.SetValue("moviedatabase", "database" + 0, grabber.Key); + xmlwriter.SetValue("moviedatabase", "title" + 0, grabber.Value.Name); + xmlwriter.SetValue("moviedatabase", "language" + 0, grabber.Value.Language); + xmlwriter.SetValue("moviedatabase", "limit" + 0, 25); + } + else + { + for (int i = 0; i < 4; i++) + { + xmlwriter.SetValue("moviedatabase", "number", 0); + xmlwriter.RemoveEntry("moviedatabase", "database" + i); + xmlwriter.RemoveEntry("moviedatabase", "title" + i); + xmlwriter.RemoveEntry("moviedatabase", "language" + i); + xmlwriter.RemoveEntry("moviedatabase", "limit" + i); + } + } + } + + IMDB.MovieInfoDatabase.ResetGrabber(); + } + + public static void ResetShares() + { + _virtualDirectory.Reset(); + _virtualDirectory.DefaultShare = null; + _virtualDirectory.LoadSettings("movies"); + + if (_virtualDirectory.DefaultShare != null) + { + string pincode; + bool folderPinProtected = _virtualDirectory.IsProtectedShare(_virtualDirectory.DefaultShare.Path, out pincode); + + if (folderPinProtected) + { + _currentFolder = string.Empty; + } + else + { + _currentFolder = _virtualDirectory.DefaultShare.Path; + } + } + } + + public static void ResetExtensions(ArrayList extensions) + { + _virtualDirectory.SetExtensions(extensions); + } + + #endregion + + #region Private methods + + private void RefreshMediaInfo(GUIListItem item) + { + if (GUIGraphicsContext.CurrentState == GUIGraphicsContext.State.STOPPING) + { + return; + } + + if (item != null) + { + string file = item.Path; + SelectDVDHandler sdh = new SelectDVDHandler(); + SelectBDHandler bdh = new SelectBDHandler(); + + if (sdh.IsDvdDirectory(item.Path)) + { + if (File.Exists(item.Path + @"\VIDEO_TS\VIDEO_TS.IFO")) + { + file = file + @"\VIDEO_TS\VIDEO_TS.IFO"; + } + } + + if (bdh.IsBDDirectory(item.Path)) + { + if (File.Exists(item.Path + @"\BDMV\INDEX.BDMV")) + { + file = file + @"\BDMV\INDEX.BDMV"; + } + } + + ArrayList files = new ArrayList(); + files = AddFileToDatabase(file); + MovieDuration(files, true); + int movieId = VideoDatabase.GetMovieId(file); + IMDBMovie mInfo = new IMDBMovie(); + mInfo.SetMediaInfoProperties(file, true); + mInfo.SetDurationProperty(movieId); + IMDBMovie.SetMovieData(item); + + GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_REFRESH_MEDIAINFO, 0, 0, 0, 0, 0, 0); + GUIWindowManager.SendMessage(msg); + } + } + + private static bool WakeUpSrv(string newFolderName) + { + bool wakeOnLanEnabled; + if (!Util.Utils.IsUNCNetwork(newFolderName)) + { + // Check if letter drive is a network drive + string detectedFolderName = Util.Utils.FindUNCPaths(newFolderName); + if (Util.Utils.IsUNCNetwork(detectedFolderName)) + { + wakeOnLanEnabled = _virtualDirectory.IsWakeOnLanEnabled(_virtualDirectory.GetShare(newFolderName)); + newFolderName = detectedFolderName; + } + else + { + return true; + } + } + else + { + wakeOnLanEnabled = _virtualDirectory.IsWakeOnLanEnabled(_virtualDirectory.GetShare(newFolderName)); + } + + string serverName = string.Empty; + + if (wakeOnLanEnabled) + { + serverName = Util.Utils.GetServerNameFromUNCPath(newFolderName); + + DateTime now = DateTime.Now; + TimeSpan ts = now - _prevWolTime; + + if (serverName == _prevServerName && _wolResendTime * 60 > ts.TotalSeconds) + { + return true; + } + + _prevWolTime = DateTime.Now; + _prevServerName = serverName; + + try + { + Log.Debug("WakeUpSrv: FolderName = {0}, ShareName = {1}, WOL enabled = {2}", newFolderName, + _virtualDirectory.GetShare(newFolderName).Name, wakeOnLanEnabled); + } + catch + { + } + + if (!string.IsNullOrEmpty(serverName)) + { + return WakeupUtils.HandleWakeUpServer(serverName, _wolTimeout); + } + } + return true; + } + + private void LoadDirectory(string newFolderName, bool useCache) + { + if (newFolderName == null) + { + Log.Warn("GUIVideoFiles::LoadDirectory called with invalid argument. newFolderName is null!"); + return; + } + + if (facadeLayout == null) + { + return; + } + + if (!WakeUpSrv(newFolderName)) + { + return; + } + + GUIWaitCursor.Show(); + + if (_videoFolderWatcher != null && _videoFolderWatcher.GetPendingEventsCount > 0) + { + useCache = false; + } + + if (_videoFolderWatcher != null) + { + _videoFolderWatcher.ChangeMonitoring(false); + } + + if (!string.IsNullOrEmpty(newFolderName)) + { + _videoFolderWatcher = new VideoFolderWatcherHelper(newFolderName); + _videoFolderWatcher.SetMonitoring(true); + _videoFolderWatcher.StartMonitor(); + } + + if (newFolderName != _currentFolder && _mapSettings != null) + { + SaveFolderSettings(_currentFolder); + } + + if (newFolderName != _currentFolder || _mapSettings == null) + { + LoadFolderSettings(newFolderName); + } + // Image file is not listed as a valid movie so we need to handle it + // as a folder and enable browsing for it + if (VirtualDirectory.IsImageFile(Path.GetExtension(newFolderName))) + { + if (!MountImageFile(GetID, newFolderName, true)) + { + return; + } + + _currentFolder = DaemonTools.GetVirtualDrive(); + } + else + { + _currentFolder = newFolderName; + } + + IMDBMovie.ResetMovieProperties(); // Clear skin properties values + GUIControl.ClearControl(GetID, facadeLayout.GetID); + List itemlist = null; + List itemlist2 = new List(); // for GetMediaInfoThread + ISelectDVDHandler selectDvdHandler = GetSelectDvdHandler(); + ISelectBDHandler selectBDHandler = GetSelectBDHandler(); + + //Tweak to boost performance when starting/stopping playback + //For further details see comment in Core\Util\VirtualDirectory.cs + if (!string.IsNullOrEmpty(_currentFolder) && useCache && _cachedDir == _currentFolder && _cachedItems != null && _cachedItems.Count > 0) + { + itemlist = _cachedItems; + int currentItemIndex = 0; + + foreach (GUIListItem item in itemlist) + { + + // Get last watch status (IMDBMovie containes old one in caced objects) + string file = item.Path; + int percentWatched = 0; + int timesWatched = 0; + int movieId = VideoDatabase.GetMovieId(file); + bool played = VideoDatabase.GetmovieWatchedStatus(movieId, out percentWatched, out timesWatched); + + if (_mapSettings != null && _mapSettings.Stack) + { + item.Duration = VideoDatabase.GetMovieDuration(movieId); + } + else + { + int fileID = VideoDatabase.GetFileId(item.Path); + item.Duration = VideoDatabase.GetVideoDuration(fileID); + } + + // set label 1 & 2 + SetLabel(item); + + // Set watched status and label 3 + if (item.IsBdDvdFolder || Util.Utils.IsVideo(item.Path)) + { + // Check db for watched status for played movie or changed status in movie info window + + if (item.IsFolder) + { + file = selectDvdHandler.GetFolderVideoFile(item.Path); + + if (file == string.Empty) + { + file = selectBDHandler.GetFolderVideoFile(item.Path); + } + } + + // Update full IMDBMovie object for last selected item (Movie info screen can change many info data) + if (currentItemIndex == _currentSelectedItem) + { + IMDBMovie.SetMovieData(item); + } + else + { + // Update watch statuses for other items + IMDBMovie movie = item.AlbumInfoTag as IMDBMovie; + + if (movie != null) + { + movie.WatchedPercent = percentWatched; + movie.WatchedCount = timesWatched; + + if (played) + { + movie.Watched = 1; + } + + item.AlbumInfoTag = movie; + } + } + + if (_markWatchedFiles) + { + item.IsPlayed = played; + } + + if (item.IsBdDvdFolder) + { + if (selectDvdHandler.IsDvdDirectory(item.Path)) + { + item.Label3 = MediaTypes.DVD.ToString() + " " + percentWatched + "% #" + timesWatched; + item.Label2 = string.Empty; + } + else + { + item.Label3 = MediaTypes.BD.ToString() + " " + percentWatched + "% #" + timesWatched; + item.Label2 = string.Empty; + } + } + else if (VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) + { + item.Label3 = MediaTypes.ISO.ToString() + " " + percentWatched + "% #" + timesWatched; + } + else + { + item.Label3 = percentWatched + "% #" + timesWatched; + } + if (movieId < 0 || movieId != -1 && item.Duration == 0) + { + itemlist2.Add(item); + } + } + + if (!item.IsFolder) + { + item.HasProgressBar = true; + item.ProgressBarPercentage = percentWatched; + } + + //Do NOT add OnItemSelected event handler here, because its still there... + + if (item.IsFolder || !item.IsFolder && !_hideWatchedFiles && item.IsPlayed || !item.IsFolder && !item.IsPlayed) + { + facadeLayout.Add(item); + currentItemIndex++; + } + } + } // End Cached items + else + { + _removableDrivesHandlerThread.Join(); + + // here we get ALL files in every subdir, look for folderthumbs, defaultthumbs, etc + itemlist = _virtualDirectory.GetDirectoryExt(_currentFolder); + + if (_currentFolder == string.Empty) + { + RemovableDrivesHandler.FilterDrives(ref itemlist); + } + + if (_mapSettings != null && _mapSettings.Stack) + { + Dictionary> stackings = new Dictionary>(itemlist.Count); + + for (int i = 0; i < itemlist.Count; ++i) + { + + GUIListItem item1 = itemlist[i]; + string cleanFilename = item1.Label; + Util.Utils.RemoveStackEndings(ref cleanFilename); + List innerList; + + if (stackings.TryGetValue(cleanFilename, out innerList)) + { + for (int j = 0; j < innerList.Count; j++) + { + GUIListItem item2 = innerList[j]; + + if (((!item1.IsFolder || !item2.IsFolder) || (item1.IsFolder && IsMovieFolder(item1.Path) || item2.IsFolder && IsMovieFolder(item2.Path))) + && (!item1.IsRemote && !item2.IsRemote) + && Util.Utils.ShouldStack(item1.Path, item2.Path)) + { + if (String.Compare(item1.Path, item2.Path, StringComparison.OrdinalIgnoreCase) > 0) + { + item2.FileInfo.Length += item1.FileInfo.Length; + } + else + { + // keep item1, it's path is lexicographically before item2 path + item1.FileInfo.Length += item2.FileInfo.Length; + innerList[j] = item1; + } + item1 = null; + break; + } + } + + if (item1 != null) // not stackable + { + innerList.Add(item1); + } + } + else + { + innerList = new List { item1 }; + stackings.Add(cleanFilename, innerList); + } + } + + foreach (KeyValuePair> pair in stackings) + { + List innerList = pair.Value; + + for (int i = 0; i < innerList.Count; i++) + { + GUIListItem item = innerList[i]; + bool isMovieFolder = false; + + if (!string.IsNullOrEmpty(newFolderName) || UNCTools.UNCFileFolderExists(item.Path, _virtualDirectory.GetShareHostDetectMethod(item.Path))) + { + if (item.IsFolder) + { + isMovieFolder = IsMovieFolder(item.Path); + } + else + { + isMovieFolder = false; + } + + if (VirtualDirectory.IsValidExtension(item.Path, Util.Utils.VideoExtensions, false) || isMovieFolder) + { + item.Label = pair.Key; + } + } + int percentWatched = 0; + // Check db for watched status for played movie or changed status in movie info window + string file = item.Path; + if (!item.IsFolder || isMovieFolder) + { + // Special folders (DVD/Blu-Ray) + if (isMovieFolder) + { + item.IsBdDvdFolder = true; + file = selectDvdHandler.GetFolderVideoFile(item.Path); + + if (file == string.Empty) + { + file = selectBDHandler.GetFolderVideoFile(item.Path); + } + } + + int timesWatched = 0; + int movieId = VideoDatabase.GetMovieId(file); + bool played = VideoDatabase.GetmovieWatchedStatus(movieId, out percentWatched, out timesWatched); + + item.Duration = VideoDatabase.GetMovieDuration(movieId); + + if (_markWatchedFiles) + { + item.IsPlayed = played; + } + + if (item.IsBdDvdFolder) + { + if (selectDvdHandler.IsDvdDirectory(item.Path)) + { + item.Label3 = MediaTypes.DVD.ToString() + " " + percentWatched + "% #" + timesWatched; + item.Label2 = string.Empty; + } + else + { + item.Label3 = MediaTypes.BD.ToString() + " " + percentWatched + "% #" + timesWatched; + item.Label2 = string.Empty; + } + } + else if (VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) + { + item.Label3 = MediaTypes.ISO.ToString() + " " + percentWatched + "% #" + timesWatched; + } + else + { + item.Label3 = percentWatched + "% #" + timesWatched; + } + if (movieId < 0 || movieId != -1 && item.Duration == 0) + { + itemlist2.Add(item); + } + } + + SetLabel(item); + item.OnItemSelected += item_OnItemSelected; + + if (!item.IsFolder) + { + item.HasProgressBar = true; + item.ProgressBarPercentage = percentWatched; + } + + if (item.IsFolder || !item.IsFolder && !_hideWatchedFiles && item.IsPlayed || !item.IsFolder && !item.IsPlayed) + { + facadeLayout.Add(item); + } + } + } + itemlist = facadeLayout.ListLayout.ListItems; + } + else + { + foreach (GUIListItem item in itemlist) + { + // Check db for watched status for played movie or changed status in movie info window + string file = item.Path; + bool isMovieFolder; + + if (item.IsFolder) + { + isMovieFolder = IsMovieFolder(item.Path); + } + else + { + isMovieFolder = false; + } + + int percentWatched = 0; + + if (!item.IsFolder || isMovieFolder) + { + // Special folders (DVD/BluRay) + if (isMovieFolder) + { + item.IsBdDvdFolder = true; + file = selectDvdHandler.GetFolderVideoFile(item.Path); + + if (file == string.Empty) + { + file = selectBDHandler.GetFolderVideoFile(item.Path); + } + } + + int timesWatched = 0; + int movieId = VideoDatabase.GetMovieId(file); + bool played = VideoDatabase.GetmovieWatchedStatus(movieId, out percentWatched, out timesWatched); + + int fileID = VideoDatabase.GetFileId(item.Path); + item.Duration = VideoDatabase.GetVideoDuration(fileID); + + if (_markWatchedFiles) + { + item.IsPlayed = played; + } + + if (item.IsBdDvdFolder) + { + if (selectDvdHandler.IsDvdDirectory(item.Path)) + { + item.Label3 = MediaTypes.DVD.ToString() + " " + percentWatched + "% #" + timesWatched; + } + else + { + item.Label3 = MediaTypes.BD.ToString() + " " + percentWatched + "% #" + timesWatched; + } + } + else if (VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) + { + item.Label3 = MediaTypes.ISO.ToString() + " " + percentWatched + "% #" + timesWatched; + } + else + { + item.Label3 = percentWatched + "% #" + timesWatched; + } + if (movieId < 0 || movieId != -1 && item.Duration == 0) + { + itemlist2.Add(item); + } + } + + SetLabel(item); + item.OnItemSelected += item_OnItemSelected; + + if (!item.IsFolder) + { + item.HasProgressBar = true; + item.ProgressBarPercentage = percentWatched; + } + + if (item.IsFolder || !item.IsFolder && !_hideWatchedFiles && item.IsPlayed || !item.IsFolder && !item.IsPlayed) + { + facadeLayout.Add(item); + } + } + } + } // End non cache items + + facadeLayout.Sort(new VideoSort(CurrentSortMethod, CurrentSortAsc)); + UpdateButtonStates(); + + if (_cachedItems != null) + { + _cachedItems.Clear(); + _cachedItems.AddRange(facadeLayout.ListLayout.ListItems); + } + + _cachedDir = _currentFolder; + + // Update thumbs for all items (cached also - > cover can be changed in VideoInfoScreen and if we do + // not update cover, old one will be visible) + SetImdbThumbs(itemlist, selectDvdHandler); + + int selectedIndex = -1; + Int32.TryParse(_history.Get(_currentFolder), out selectedIndex); + int maxIndex = itemlist.Count - 1; + + if (maxIndex >= selectedIndex) + { + GUIControl.SelectItemControl(GetID, facadeLayout.GetID, selectedIndex); + } + + int totalItems = itemlist.Count; + + if (totalItems > 0) + { + GUIListItem rootItem = itemlist[0]; + if (rootItem.Label == "..") + { + totalItems--; + } + } + else + { + if (_resetCount == 0) + { + _resetCount++; + ResetShares(); + + if (_virtualDirectory.DefaultShare != null && _virtualDirectory.DefaultShare.Path != string.Empty) + { + LoadDirectory(_virtualDirectory.DefaultShare.Path, false); + } + else + { + LoadDirectory(string.Empty, false); + } + + GUIWaitCursor.Hide(); + return; + } + } + + //set object count label + GUIPropertyManager.SetProperty("#itemcount", Util.Utils.GetObjectCountLabel(totalItems)); + + // Reload thumbs if previous load thumb thread aborted (only when cache is active) + // If thumb thread was aborted and on next loaddirectory with cache "on", some thumbs + // can be missing and wan't be loaded, so here we reload them again. + if (_setThumbsThreadAborted) + { + SetImdbThumbs(itemlist, selectDvdHandler); + } + + // if have new item we close the previous thread and start a new one + if ((_addVideoFilesToDb || CurrentSortMethod == VideoSort.SortMethod.Name_With_Duration) && itemlist2.Count != 0) + { + try + { + if (_getMediaInfoThread != null && _getMediaInfoThread.IsAlive) + { + // dont want to abort, rather send a signal and wait to finish, it is a clean exit + Log.Debug("GetMediaInfoThread: send an exit signal to the last thread and waiting for exit."); + _getMediaInfoThreadAbort = true; + _getMediaInfoThread.Join(); + Log.Debug("GetMediaInfoThread: after join."); + } + } + catch (Exception ex) + { + Log.Error("GUIVideoFiles: LoadDirectory {0}", ex.Message); + } + + _getMediaInfoThreadAbort = false; + + // The last _getMediaInfoThread is closed we can start a new one + _getMediaInfoThreadNumber++; + _getMediaInfoThread = new Thread(GetMediaInfoThread); + _getMediaInfoThread.Priority = ThreadPriority.Lowest; + _getMediaInfoThread.IsBackground = true; + _getMediaInfoThread.Name = "GetMediaInfoThread " + _getMediaInfoThreadNumber; + _getMediaInfoThread.Start(itemlist2); + } + + GUIWaitCursor.Hide(); + } + + private void ReplaceItem(string oldPath, string newPath) + { + if (Directory.Exists(newPath) || (Util.Utils.IsVideo(oldPath) && Util.Utils.IsVideo(newPath))) + { + for (int i = 0; i < facadeLayout.Count; i++) + { + if (facadeLayout[i].Path == oldPath) + { + AddItem(newPath, i); + return; + } + } + } + + if (Util.Utils.IsVideo(newPath)) + { + AddItem(newPath, -1); + } + + if (Util.Utils.IsVideo(oldPath)) + { + DeleteItem(oldPath); + } + } + + private int DeleteItem(string path) + { + int oldItem = -1; + try + { + for (int i = 0; i < facadeLayout.Count; i++) + { + if (facadeLayout[i].Path == path) + { + facadeLayout.RemoveItem(i); + if (_currentSelectedItem >= i) + { + _currentSelectedItem--; + } + oldItem = i; + break; + } + } + int totalItems = facadeLayout.Count; + + if (totalItems > 0) + { + GUIListItem rootItem = facadeLayout[0]; + if (rootItem.Label == "..") + { + totalItems--; + } + } + + GUIPropertyManager.SetProperty("#itemcount", Util.Utils.GetObjectCountLabel(totalItems)); + } + catch (Exception ex) + { + Log.Error("GUIVideoFiles.DeleteItem Exception: {0}", ex.Message); + } + return oldItem; + } + + private void AddItem(string path, int index) + { + try + { + for (int i = 0; i < facadeLayout.Count; i++) + { + if (facadeLayout[i].Path == path) + { + Log.Debug("GUIVideoFiles.AddItem Duplicated item found: {0}", path); + return; + } + } + + ISelectDVDHandler selectDvdHandler = GetSelectDvdHandler(); + ISelectBDHandler selectBDHandler = GetSelectBDHandler(); + FileInformation fi = new FileInformation(); + if (File.Exists(path)) + { + FileInfo f = new FileInfo(path); + fi.CreationTime = File.GetCreationTime(path); + fi.Length = f.Length; + } + else + { + fi = new FileInformation(); + fi.CreationTime = DateTime.Now; + fi.Length = 0; + } + GUIListItem item = new GUIListItem(Util.Utils.GetFilename(path), "", path, true, fi); + + item.IsFolder = Directory.Exists(path); + + Util.Utils.SetDefaultIcons(item); + Util.Utils.SetThumbnails(ref item); + + // Check db for watched status for played movie or changed status in movie info window + string file = item.Path; + bool isMovieFolder = IsMovieFolder(item.Path); + + if (!item.IsFolder || isMovieFolder) + { + // Special folders (DVD/BluRay) + if (isMovieFolder) + { + item.IsBdDvdFolder = true; + file = selectDvdHandler.GetFolderVideoFile(item.Path); + + if (file == string.Empty) + { + file = selectBDHandler.GetFolderVideoFile(item.Path); + } + } + + int percentWatched = 0; + int timesWatched = 0; + int movieId = VideoDatabase.GetMovieId(file); + bool played = VideoDatabase.GetmovieWatchedStatus(movieId, out percentWatched, out timesWatched); + item.Duration = VideoDatabase.GetMovieDuration(movieId); + + if (item.Duration == 0) + { + RefreshMediaInfo(item); + item.Duration = VideoDatabase.GetMovieDuration(movieId); + } + + SetLabel(item); + + if (_markWatchedFiles) + { + item.IsPlayed = played; + } + + if (item.IsBdDvdFolder) + { + if (selectDvdHandler.IsDvdDirectory(item.Path)) + { + item.Label3 = MediaTypes.DVD.ToString() + " " + percentWatched + "% #" + timesWatched; + } + else + { + item.Label3 = MediaTypes.BD.ToString() + " " + percentWatched + "% #" + timesWatched; + } + } + else if (VirtualDirectory.IsImageFile(Path.GetExtension(item.Path))) + { + item.Label3 = MediaTypes.ISO.ToString() + " " + percentWatched + "% #" + timesWatched; + } + else + { + item.Label3 = percentWatched + "% #" + timesWatched; + } + } + + List itemlist = new List(); + itemlist.Add(item); + SetImdbThumbs(itemlist, selectDvdHandler); + + item.OnItemSelected += item_OnItemSelected; + + if (index == -1) + { + facadeLayout.Add(item); + } + else + { + facadeLayout.Replace(index, item); + } + + int totalItems = facadeLayout.Count; + + if (totalItems > 0) + { + GUIListItem rootItem = facadeLayout[0]; + if (rootItem.Label == "..") + { + totalItems--; + } + } + GUIPropertyManager.SetProperty("#itemcount", Util.Utils.GetObjectCountLabel(totalItems)); + } + catch (Exception ex) + { + Log.Error("GUIVideoFiles.AddItem Exception: {0}", ex.Message); + } + } + + // main thread. It adds all file to database and refresh the ListLayout on the screen. + private void GetMediaInfoThread(object i) + { + List itemlist = (List)i; + + Log.Debug("GetMediaInfoThread: current folder: {0}, itemlist count: {1}", _currentFolder, itemlist.Count); + + foreach (GUIListItem item in itemlist) + { + if (_getMediaInfoThreadAbort) + { + Log.Debug("GetMediaInfoThread: finished with _getMediaInfoThreadAbort signal."); + return; + } + try + { + Log.Debug("GetMediaInfoThread: Work on {0}", item.Path); + + RefreshMediaInfo(item); + + int newMovieId = VideoDatabase.GetMovieId(item.Path); + item.Duration = VideoDatabase.GetMovieDuration(newMovieId); + if (item.Duration > 0) + { + for (int n = facadeLayout.ListLayout.ListItems.Count - 1; n > 0; n--) + { + if (facadeLayout.ListLayout.ListItems[n].Label == item.Label) + { + SetLabel(item); + facadeLayout.ListLayout.ListItems[n].Label2 = item.Label2; + break; + } + } + } + } + catch (ThreadAbortException) + { + Log.Debug("GetMediaInfoThread: ThreadAbortException"); + } + catch (Exception ex) + { + Log.Error("GetMediaInfoThread: {0}", ex.Message); + } + Thread.Sleep(100); + } + Log.Debug("GetMediaInfoThread: Finished."); + } + + private void UpdateMediaInfoInFolder(GUIListItem item) + { + List itemlist = new List(); + + ListFilesForUpdateMediaInfo(item, ref itemlist); + Log.Debug("UpdateMediaInfoInFolder: File count {0}", itemlist.Count); + + _progressDialogForUpdateMediaInfo = + (GUIDialogProgress)GUIWindowManager.GetWindow(101); //(int)Window.WINDOW_DIALOG_PROGRESS + _progressDialogForUpdateMediaInfo.Reset(); + _progressDialogForUpdateMediaInfo.SetHeading(GUILocalizeStrings.Get(2160)); + _progressDialogForUpdateMediaInfo.ShowProgressBar(true); + _progressDialogForUpdateMediaInfo.SetLine(1, item.Path.Replace("\\", "/")); + _progressDialogForUpdateMediaInfo.SetLine(2, string.Empty); + _progressDialogForUpdateMediaInfo.SetLine(3, "Movie count: " + itemlist.Count + "/0"); + _progressDialogForUpdateMediaInfo.StartModal(GUIWindowManager.ActiveWindow); + + if (_refreshMediaInfoThread != null && _refreshMediaInfoThread.IsAlive) + { + _refreshMediaInfoThread.Abort(); + } + + _refreshMediaInfoThreadAbort = false; + _refreshMediaInfoThread = new Thread(RefreshMediaInfoThread); + _refreshMediaInfoThread.Priority = ThreadPriority.Lowest; + _refreshMediaInfoThread.IsBackground = true; + _refreshMediaInfoThread.Name = "RefreshMediaInfoThread"; + _refreshMediaInfoThread.Start(itemlist); + } + + private void RefreshMediaInfoThread(object o) + { + List itemlist = (List)o; + try + { + for (int i = 0; i < itemlist.Count; i++) + { + if (_refreshMediaInfoThreadAbort) + { + Log.Info("RefreshMediaInfoThread: Aborted by the user."); + return; + } + + int perc = (i * 100) / itemlist.Count; + _progressDialogForUpdateMediaInfo.SetPercentage(perc); + _progressDialogForUpdateMediaInfo.SetLine(1, itemlist[i].Path.Replace("\\", "/")); + _progressDialogForUpdateMediaInfo.SetLine(3, "Movie count: " + itemlist.Count + "/" + i); + _progressDialogForUpdateMediaInfo.Progress(); + + RefreshMediaInfo(itemlist[i]); + Thread.Sleep(100); + + while (g_Player.Playing || g_Player.Starting) + { + Thread.Sleep(5000); + Log.Debug("RefreshMediaInfoThread: g_Player is Playing, waiting for the end."); + } + } + } + catch (Exception ex) + { + Log.Error("RefreshMediaInfoThread: {0}", ex); + } + finally + { + _progressDialogForUpdateMediaInfo.Close(); + } + Log.Info("RefreshMediaInfoThread: Finished."); + } + + private void ListFilesForUpdateMediaInfo(GUIListItem item, ref List itemlist) + { + if (item != null) + { + // Process the list of files found in the directory. + VirtualDirectory virtualDirectory = new VirtualDirectory(); + virtualDirectory.SetExtensions(Util.Utils.VideoExtensions); + List inertItemlist = virtualDirectory.GetDirectoryUnProtectedExt(item.Path, true); + foreach (GUIListItem subItem in inertItemlist) + { + if (!subItem.IsFolder) + { + itemlist.Add(subItem); + } + else + { + if (subItem.Label != "..") + { + ListFilesForUpdateMediaInfo(subItem, ref itemlist); + } + } + } + } + } + + private void LoadFolderSettings(string folderName) + { + if (folderName == string.Empty) + { + folderName = "root"; + } + object o; + FolderSettings.GetFolderSetting(folderName, "VideoFiles", typeof(MapSettings), out o); + if (o != null) + { + _mapSettings = o as MapSettings; + + if (_mapSettings == null) + { + _mapSettings = new MapSettings(); + } + + CurrentSortAsc = _mapSettings.SortAscending; + CurrentSortMethod = (VideoSort.SortMethod)_mapSettings.SortBy; + currentLayout = (Layout)_mapSettings.ViewAs; + } + else + { + Share share = _virtualDirectory.GetShare(folderName); + + if (share != null) + { + if (_mapSettings == null) + { + _mapSettings = new MapSettings(); + } + CurrentSortAsc = _mapSettings.SortAscending; + CurrentSortMethod = (VideoSort.SortMethod)_mapSettings.SortBy; + currentLayout = (Layout)share.DefaultLayout; + CurrentLayout = (Layout)share.DefaultLayout; + } + } + + using (Profile.Settings xmlreader = new Profile.MPSettings()) + { + if (xmlreader.GetValueAsBool("movies", "rememberlastfolder", false)) + { + xmlreader.SetValue("movies", "lastfolder", folderName); + } + } + + SwitchLayout(); + UpdateButtonStates(); + } + + private void SaveFolderSettings(string folderName) + { + if (folderName == string.Empty) + { + folderName = "root"; + } + FolderSettings.AddFolderSetting(folderName, "VideoFiles", typeof(MapSettings), _mapSettings); + } + + private void ShowFileMenu(bool preselectDelete) + { + // get pincode + if (_fileMenuPinCode != string.Empty) + { + string userCode = string.Empty; + if (GetUserPasswordString(ref userCode) && userCode == _fileMenuPinCode) + { + OnShowFileMenu(preselectDelete); + } + } + else + { + OnShowFileMenu(preselectDelete); + } + } + + private static bool CheckExternalPlayer(string filename, bool isImage) + { + if (!_useInternalVideoPlayer) + { + if (!isImage) + { + // extensions filter + if (!string.IsNullOrEmpty(_externalPlayerExtensions)) + { + // Use external player if extension is valid + if (CheckExtension(filename)) + { + return true; + } + } + else + { + return true; + } + } + } + // DVD files + if (!_useInternalDVDVideoPlayer) + { + if (isImage && Util.Utils.IsDVDImage(filename)) + { + return true; + } + else if (!isImage) + { + if (filename.ToUpperInvariant().IndexOf(@"\VIDEO_TS\VIDEO_TS.IFO", StringComparison.InvariantCultureIgnoreCase) >= 0) + return true; + } + } + + return false; + } + + private static bool CheckExtension(string filename) + { + char[] splitter = { ';' }; + string[] extensions = _externalPlayerExtensions.Split(splitter); + + foreach (string extension in extensions) + { + if (extension.Trim().Equals(Path.GetExtension(filename), StringComparison.InvariantCultureIgnoreCase)) + { + return true; + } + } + return false; + } + + private void DoOnPlayBackStoppedOrChanged(g_Player.MediaType type, int timeMovieStopped, string filename, + string caller) + { + if (type != g_Player.MediaType.Video || filename.EndsWith("&txe=.wmv")) + { + return; + } + + // BD and IMAGES stop time (change to index.bdmv if mpls file is played or to IMG file) + ISelectBDHandler selectBDHandler = GetSelectBDHandler(); + selectBDHandler.IsBDPlayList(ref filename); + // Handle all movie files from idMovie + ArrayList movies = new ArrayList(); + int iidMovie = VideoDatabase.GetMovieId(filename); + VideoDatabase.GetFilesForMovie(iidMovie, ref movies); + HashSet watchedMovies = new HashSet(); + + int playTimePercentage = 0; + + // Stacked movies duration + if (IsStacked && TotalMovieDuration != 0) + { + int duration = 0; + + for (int i = 0; i < StackedMovieFiles.Count; i++) + { + int fileID = VideoDatabase.GetFileId((string)StackedMovieFiles[i]); + + if (g_Player.CurrentFile != (string)StackedMovieFiles[i]) + { + duration += VideoDatabase.GetVideoDuration(fileID); + continue; + } + playTimePercentage = (100 * (duration + timeMovieStopped) / TotalMovieDuration); + break; + } + } + else + { + if (g_Player.Player.Duration >= 1) + { + playTimePercentage = (int)Math.Ceiling((timeMovieStopped / g_Player.Player.Duration) * 100); + } + } + + if (movies.Count <= 0) + { + return; + } + + for (int i = 0; i < movies.Count; i++) + { + string strFilePath = (string)movies[i]; + + int idFile = VideoDatabase.GetFileId(strFilePath); + int idMovie = VideoDatabase.GetMovieId(strFilePath); + + if (idFile < 0) + { + break; + } + + if (g_Player.IsDVDMenu) + { + VideoDatabase.SetMovieStopTimeAndResumeData(idFile, 0, null, g_Player.SetResumeBDTitleState); + watchedMovies.Add(strFilePath); + VideoDatabase.SetMovieWatchedStatus(idMovie, true, 100); + VideoDatabase.MovieWatchedCountIncrease(idMovie); + } + else if ((filename.Trim().ToLowerInvariant().Equals(strFilePath.Trim().ToLowerInvariant())) && (timeMovieStopped > 0) && g_Player.SetResumeBDTitleState != -2) + { + byte[] resumeData = null; + g_Player.Player.GetResumeState(out resumeData); + Log.Info("GUIVideoFiles: {0} idFile={1} timeMovieStopped={2} resumeData={3} bdtitle={4}", caller, idFile, timeMovieStopped, + resumeData, g_Player.SetResumeBDTitleState); + VideoDatabase.SetMovieStopTimeAndResumeData(idFile, timeMovieStopped, resumeData, g_Player.SetResumeBDTitleState); + Log.Debug("GUIVideoFiles: {0} store resume time", caller); + + //Set file "watched" only if user % value or higher played time (share view) + if (playTimePercentage >= _watchedPercentage) + { + watchedMovies.Add(strFilePath); + VideoDatabase.SetMovieWatchedStatus(idMovie, true, playTimePercentage); + VideoDatabase.MovieWatchedCountIncrease(idMovie); + } + else + { + int iPercent = 0; // Not used, just needed for the watched status call + int iTImesWatched = 0; + bool watched = VideoDatabase.GetmovieWatchedStatus(idMovie, out iPercent, + out iTImesWatched); + + if (!watched) + { + VideoDatabase.SetMovieWatchedStatus(idMovie, false, playTimePercentage); + } + else // Update new percentage if already watched + { + VideoDatabase.SetMovieWatchedStatus(idMovie, true, playTimePercentage); + } + } + } + else + { + VideoDatabase.DeleteMovieStopTime(idFile); + } + // Update groups with rules + VideoDatabase.UpdateUserGroupWithRule(idMovie); + } + + if (_markWatchedFiles) + { + // Update db view watched status for played movie + IMDBMovie movie = new IMDBMovie(); + VideoDatabase.GetMovieInfo(filename, ref movie); + + if (!movie.IsEmpty) + //Flag movie "watched" status only if user % value or higher played time (database view) + { + if (playTimePercentage >= _watchedPercentage || g_Player.IsDVDMenu) + { + movie.Watched = 1; + } + movie.DateWatched = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); + VideoDatabase.SetMovieInfoById(movie.ID, ref movie); + } + + if (VideoState.StartWindow != GetID) // Is play initiator dbview? + { + UpdateButtonStates(); + } + } + + if (SubEngine.GetInstance().IsModified()) + { + bool shouldSave = false; + + if (SubEngine.GetInstance().AutoSaveType == AutoSaveTypeEnum.ASK) + { + if (!g_Player.Paused) + { + g_Player.Pause(); + } + + GUIDialogYesNo dlgYesNo = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_YES_NO); + dlgYesNo.SetHeading(GUILocalizeStrings.Get(1318));// Save subtitle + dlgYesNo.SetLine(1, GUILocalizeStrings.Get(1319)); // Save modified subtitle? + dlgYesNo.SetDefaultToYes(true); + dlgYesNo.DoModal(GUIWindowManager.ActiveWindow); + shouldSave = dlgYesNo.IsConfirmed; + } + + if (shouldSave || SubEngine.GetInstance().AutoSaveType == AutoSaveTypeEnum.ALWAYS) + { + SubEngine.GetInstance().SaveToDisk(); + } + } + } + + private void OnPlayBackChanged(g_Player.MediaType type, int timeMovieStopped, string filename) + { + DoOnPlayBackStoppedOrChanged(type, timeMovieStopped, filename, "OnPlayBackChanged"); + } + + private void OnPlayBackStopped(g_Player.MediaType type, int timeMovieStopped, string filename) + { + DoOnPlayBackStoppedOrChanged(type, timeMovieStopped, filename, "OnPlayBackStopped"); + } + + private void OnPlayBackEnded(g_Player.MediaType type, string filename) + { + if (type != g_Player.MediaType.Video) + { + return; + } + + // BD-DVD image stop time (change to index.bdmv if mpls file is played) + ISelectBDHandler selectBDHandler = GetSelectBDHandler(); + selectBDHandler.IsBDPlayList(ref filename); + + // Handle all movie files from idMovie + ArrayList movies = new ArrayList(); + HashSet watchedMovies = new HashSet(); + + int idMovie = VideoDatabase.GetMovieId(filename); + + if (idMovie >= 0) + { + VideoDatabase.GetFilesForMovie(idMovie, ref movies); + + for (int i = 0; i < movies.Count; i++) + { + string strFilePath = (string)movies[i]; + byte[] resumeData = null; + int idFile = VideoDatabase.GetFileId(strFilePath); + if (idFile < 0) + { + break; + } + // Set resumedata to zero + VideoDatabase.GetMovieStopTimeAndResumeData(idFile, out resumeData, g_Player.SetResumeBDTitleState); + VideoDatabase.SetMovieStopTimeAndResumeData(idFile, 0, resumeData, g_Player.SetResumeBDTitleState); + watchedMovies.Add(strFilePath); + } + + int playTimePercentage = 0; + + if (IsStacked && TotalMovieDuration != 0) + { + int duration = 0; + + for (int i = 0; i < StackedMovieFiles.Count; i++) + { + int fileID = VideoDatabase.GetFileId((string)StackedMovieFiles[i]); + + if (filename != (string)StackedMovieFiles[i]) + { + duration += VideoDatabase.GetVideoDuration(fileID); + continue; + } + playTimePercentage = (int)(100 * (duration + g_Player.Player.CurrentPosition) / TotalMovieDuration); + break; + } + } + else + { + playTimePercentage = 100; + } + + IMDBMovie details = new IMDBMovie(); + VideoDatabase.GetMovieInfoById(idMovie, ref details); + + if (playTimePercentage >= _watchedPercentage) + { + details.Watched = 1; + VideoDatabase.SetWatched(details); + VideoDatabase.SetMovieWatchedStatus(idMovie, true, playTimePercentage); + VideoDatabase.MovieWatchedCountIncrease(idMovie); + // Set date watched + VideoDatabase.SetDateWatched(details); + } + else + { + int percent = 0; + int timesWatched = 0; + bool wStatus = VideoDatabase.GetmovieWatchedStatus(idMovie, out percent, out timesWatched); + VideoDatabase.SetMovieWatchedStatus(idMovie, wStatus, playTimePercentage); + } + // Update groups with rules + VideoDatabase.UpdateUserGroupWithRule(idMovie); + } + } + + private void OnPlayBackStarted(g_Player.MediaType type, string filename) + { + if (type != g_Player.MediaType.Video) + { + return; + } + + if (!Util.Utils.IsRemoteUrl(filename)) + { + int idFile = VideoDatabase.GetFileId(filename); + + if (idFile == -1) + { + AddFileToDatabase(filename); + idFile = VideoDatabase.GetFileId(filename); + } + + if (idFile != -1) + { + int videoDuration = (int)g_Player.Duration; + VideoDatabase.SetVideoDuration(idFile, videoDuration); + } + } + } + + // Play all files in selected directory + private void OnPlayAll(string path) + { + // Get all video files in selected folder and it's subfolders + ArrayList playFiles = new ArrayList(); + AddVideoFiles(path, ref playFiles); + + if (playFiles.Count == 0) + { + return; + } + + int selectedOption = 0; + + GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_MENU); + + // Check and play according to setting value + if (_howToPlayAll == 3) // Ask, select sort method from options in GUIDialogMenu + { + if (dlg == null) + { + return; + } + dlg.Reset(); + dlg.SetHeading(498); // menu + dlg.AddLocalizedString(103); // By Name + dlg.AddLocalizedString(104); // By Date + dlg.AddLocalizedString(191); // Shuffle + // Show GUIDialogMenu + dlg.DoModal(GetID); + + if (dlg.SelectedId == -1) + { + return; + } + + selectedOption = dlg.SelectedId; + } + else // Don't ask, sort according to setting and play videos + { + selectedOption = _howToPlayAll; + } + + // Get current playlist + _currentPlaylistType = new PlayListType(); + _currentPlaylistType = _playlistPlayer.CurrentPlaylistType; + _currentPlaylistIndex = _playlistPlayer.CurrentSong; + + // Reset playlist + _playlistPlayer.Reset(); + _playlistPlayer.CurrentPlaylistType = PlayListType.PLAYLIST_VIDEO; + PlayList tmpPlayList = _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO); + tmpPlayList.Clear(); + + // Do sorting + switch (selectedOption) + { + // + // ****** Watch out for fallthrough of empty cases if reordering CASE ******* + // + case 0: // By name == 103 + case 103: + AddToPlayList(tmpPlayList, playFiles.ToArray()); + List sortedPlayListItems = new List(); + sortedPlayListItems.AddRange(tmpPlayList); + sortedPlayListItems.Sort((item1, item2) => StringLogicalComparer.Compare(item1.Description, item2.Description)); + tmpPlayList.Clear(); + + foreach (PlayListItem playListItem in sortedPlayListItems) + { + tmpPlayList.Add(playListItem); + } + + break; + + case 1: // By date (date modified) == 104 + case 104: + IOrderedEnumerable sortedPlayList = playFiles.ToArray().OrderBy(fn => new FileInfo((string)fn).LastWriteTime); + AddToPlayList(tmpPlayList, sortedPlayList); + break; + + case 2: // Shuffle == 191 + case 191: + AddToPlayList(tmpPlayList, playFiles.ToArray()); + tmpPlayList.Shuffle(); + break; + } + // Play movies + PlayMovieFromPlayList(false, true); + } + + private void AddToPlayList(PlayList tmpPlayList, IEnumerable sortedPlayList) + { + foreach (string file in sortedPlayList) + { + // Remove stop data if exists + int idFile = VideoDatabase.GetFileId(file); + + if (idFile >= 0) + { + VideoDatabase.DeleteMovieStopTime(idFile); + } + + // Add file to tmp playlist + PlayListItem newItem = new PlayListItem(); + newItem.FileName = file; + // Set file description (for sorting by name -> DVD IFO file problem) + string description = string.Empty; + + if (file.ToUpperInvariant().IndexOf(@"\VIDEO_TS\VIDEO_TS.IFO", StringComparison.InvariantCultureIgnoreCase) >= 0) + { + string dvdFolder = file.Substring(0, file.ToUpperInvariant().IndexOf(@"\VIDEO_TS\VIDEO_TS.IFO", StringComparison.InvariantCultureIgnoreCase)); + description = Path.GetFileName(dvdFolder); + } + if (file.ToUpperInvariant().IndexOf(@"\BDMV\INDEX.BDMV", StringComparison.InvariantCultureIgnoreCase) >= 0) + { + string bdFolder = file.Substring(0, file.ToUpperInvariant().IndexOf(@"\BDMV\INDEX.BDMV", StringComparison.InvariantCultureIgnoreCase)); + description = Path.GetFileName(bdFolder); + } + else + { + description = Path.GetFileName(file); + } + + newItem.Description = description; + newItem.Type = PlayListItem.PlayListItemType.Video; + tmpPlayList.Add(newItem); + } + } + + /// + /// Adds file (full path) and it's stacked parts (method will search + /// for them inside strFile folder) into videodatabase (movie table) + /// This method will also fill mediaInfo data and file duration id + /// if they are not exists. + /// + /// + /// + private ArrayList AddFileToDatabase(string strFile) + { + ArrayList files = new ArrayList(); + // Stop is file is not video + if (!Util.Utils.IsVideo(strFile)) + { + return files; + } + // ?? + if (PlayListFactory.IsPlayList(strFile)) + { + return files; + } + // Don't add web streams (e.g.: from Online videos) + if (strFile.StartsWith("http:")) + { + return files; + } + + ArrayList allFiles = new ArrayList(); + + // If this is database movie, get files and return + if (VideoDatabase.HasMovieInfo(strFile)) + { + IMDBMovie movie = new IMDBMovie(); + VideoDatabase.GetMovieInfo(strFile, ref movie); + VideoDatabase.GetFilesForMovie(movie.ID, ref allFiles); + + // Check if we have mediainfo for files and add it if necessary + foreach (string file in allFiles) + { + if (!VideoDatabase.HasMediaInfo(file)) + { + VideoDatabase.AddMovieFile(file); + } + } + + return allFiles; + } + // If file is not scanned (movie is not in the db ie. user video) + int movieId = VideoDatabase.AddMovieFile(strFile); + files.Add(strFile); + + // Check if file is stackable and get rest of the stack + if (IsFileStackable(strFile)) + { + List items = _virtualDirectory.GetDirectoryUnProtectedExt(_currentFolder, true); + + for (int i = 0; i < items.Count; ++i) + { + GUIListItem temporaryListItem = (GUIListItem)items[i]; + + if (temporaryListItem.IsFolder) + { + if (!IsMovieFolder(temporaryListItem.Path)) + { + continue; + } + else + { + temporaryListItem.IsBdDvdFolder = true; + } + } + + IMDBMovie movie = (IMDBMovie)temporaryListItem.AlbumInfoTag; + + if (temporaryListItem.AlbumInfoTag == null) + { + IMDBMovie.SetMovieData(temporaryListItem); + movie = temporaryListItem.AlbumInfoTag as IMDBMovie; + } + + if (movie == null) + { + continue; + } + + if (movie.VideoFileName != strFile) + { + // Add rest of stackable items for main file (main file is already in array) + if (!temporaryListItem.IsBdDvdFolder) + { + if (Util.Utils.ShouldStack(movie.VideoFileName, strFile)) + { + allFiles.Add(items[i]); + } + } + else + { + string strPath, strFileName; + Util.Utils.Split(strFile, out strPath, out strFileName); + + if (Util.Utils.PathShouldStack(movie.VideoFilePath, strPath)) + { + allFiles.Add(items[i]); + } + } + } + } + + // Add rest of the stackable files + foreach (GUIListItem item in allFiles) + { + IMDBMovie movie = (IMDBMovie)item.AlbumInfoTag; + int idFile = VideoDatabase.GetFileId(movie.VideoFileName); + + if (idFile == -1) + { + string path, filename; + DatabaseUtility.Split(movie.VideoFileName, out path, out filename); + int pathId = VideoDatabase.AddPath(path); + VideoDatabase.AddFile(movieId, pathId, filename); + } + + files.Add(movie.VideoFileName); + } + } + + return files; + } + + private void SetLabel(GUIListItem item) + { + ISelectDVDHandler sDvd = GUIVideoFiles.GetSelectDvdHandler(); + ISelectBDHandler sBd = GUIVideoFiles.GetSelectBDHandler(); + + string strSize1 = string.Empty, strDate = string.Empty; + + if (item.FileInfo != null && !item.IsFolder) + { + strSize1 = Util.Utils.GetSize(item.FileInfo.Length); + } + + if (item.FileInfo != null && !item.IsFolder) + { + if (CurrentSortMethod == VideoSort.SortMethod.Modified) + { + strDate = item.FileInfo.ModificationTime.ToShortDateString() + " " + + item.FileInfo.ModificationTime.ToString("t", CultureInfo.CurrentCulture.DateTimeFormat); + } + else + { + strDate = item.FileInfo.CreationTime.ToShortDateString() + " " + + item.FileInfo.CreationTime.ToString("t", CultureInfo.CurrentCulture.DateTimeFormat); + } + } + + if (CurrentSortMethod == VideoSort.SortMethod.Name) + { + if (item.IsFolder && (sDvd.IsDvdDirectory(item.Path) || sBd.IsBDDirectory(item.Path))) + { + // Reserved if needed + } + else + { + item.Label2 = strSize1; + } + + } + + if (CurrentSortMethod == VideoSort.SortMethod.Name_With_Duration && !item.IsFolder && item.Label != "..") + { + if (item.Duration > 0) + { + item.Label2 = Util.Utils.SecondsToShortHMSString(item.Duration); + } + else + { + item.Label2 = string.Empty; + } + } + else if (CurrentSortMethod == VideoSort.SortMethod.Created || CurrentSortMethod == VideoSort.SortMethod.Date || CurrentSortMethod == VideoSort.SortMethod.Modified) + { + item.Label2 = strDate; + } + else + { + if (item.IsFolder && (sDvd.IsDvdDirectory(item.Path) || sBd.IsBDDirectory(item.Path))) + { + //Reserved if needed + } + else + { + item.Label2 = strSize1; + } + } + } + + private void GUIWindowManager_OnNewMessage(GUIMessage message) + { + switch (message.Message) + { + case GUIMessage.MessageType.GUI_MSG_AUTOPLAY_VOLUME: + if (message.Param1 == (int)Ripper.AutoPlay.MediaType.VIDEO) + { + if (message.Param2 == (int)Ripper.AutoPlay.MediaSubType.DVD) + OnPlayDVD(message.Label, GetID); + + if (message.Param2 == (int)Ripper.AutoPlay.MediaSubType.BLURAY) + { + OnPlayBD(message.Label, GetID); + } + + else if (message.Param2 == (int)Ripper.AutoPlay.MediaSubType.VCD || + message.Param2 == (int)Ripper.AutoPlay.MediaSubType.FILES) + OnPlayFiles((System.Collections.ArrayList)message.Object); + } + break; + + case GUIMessage.MessageType.GUI_MSG_VOLUME_REMOVED: + if (g_Player.Playing && g_Player.IsVideo && + message.Label.Equals(g_Player.CurrentFile.Substring(0, 2), StringComparison.InvariantCultureIgnoreCase)) + { + if (!File.Exists(g_Player.CurrentFile)) + { + Log.Info("GUIVideoFiles: Stop since media is ejected"); + g_Player.Stop(); + _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO_TEMP).Clear(); + _playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO).Clear(); + } + else + { + return; + } + } + + if (GUIWindowManager.ActiveWindow == GetID) + { + if (Util.Utils.IsDVD(_currentFolder)) + { + _currentFolder = string.Empty; + LoadDirectory(_currentFolder); + } + } + break; + + case GUIMessage.MessageType.GUI_MSG_ONRESUME: + using (Settings xmlreader = new MPSettings()) + { + if (!xmlreader.GetValueAsBool("general", "showlastactivemodule", false)) + { + _currentFolder = string.Empty; + } + } + + Log.Debug("{0}:{1}", SerializeName, message.Message); + break; + } + } + + private void SetMovieWatchStatus(string movieFileName, bool isFolder, bool watched) + { + ISelectDVDHandler selectDvdHandler = GetSelectDvdHandler(); + ISelectBDHandler selectBDHandler = GetSelectBDHandler(); + + if (isFolder && selectDvdHandler.IsDvdDirectory(movieFileName)) + { + movieFileName = selectDvdHandler.GetFolderVideoFile(movieFileName); + } + if (isFolder && selectBDHandler.IsBDDirectory(movieFileName)) + { + movieFileName = selectBDHandler.GetFolderVideoFile(movieFileName); + } + + VideoDatabase.AddMovieFile(movieFileName); + + if (VideoDatabase.HasMovieInfo(movieFileName)) + { + IMDBMovie movieDetails = new IMDBMovie(); + VideoDatabase.GetMovieInfo(movieFileName, ref movieDetails); + + if (!watched) + { + movieDetails.Watched = 0; + } + else + { + movieDetails.Watched = 1; + } + + VideoDatabase.SetWatched(movieDetails); + // Update groups with rules + VideoDatabase.UpdateUserGroupWithRule(movieDetails.ID); + } + + int iTimesWatched = 0; + int movieId = VideoDatabase.GetMovieId(movieFileName); + + if (!watched) + { + VideoDatabase.SetMovieWatchedStatus(movieId, false, 0); + VideoDatabase.SetMovieStopTime(movieId, 0); + VideoDatabase.SetMovieWatchedCount(movieId, 0); + } + else + { + int iPercent = 100; + VideoDatabase.GetmovieWatchedStatus(movieId, out iPercent, out iTimesWatched); + VideoDatabase.SetMovieWatchedStatus(movieId, true, 100); + + if (iTimesWatched <= 0) + { + VideoDatabase.MovieWatchedCountIncrease(movieId); + } + } + } + + private void ResetWatchedForAllMoviesInFolder(string folderName) + { + if (OnResetFolderSettings()) + VideoDatabase.ResetWatchedForAllMoviesInFolder(folderName); + } + + private void item_OnItemSelected(GUIListItem item, GUIControl parent) + { + GUIPropertyManager.SetProperty("#groupmovielist", string.Empty); + + _currentSelectedItem = facadeLayout.SelectedListItemIndex; + IMDBMovie info = item.AlbumInfoTag as IMDBMovie; + + // Read database only once per item + if (item.AlbumInfoTag == null) + { + IMDBMovie.SetMovieData(item); + info = item.AlbumInfoTag as IMDBMovie; + } + + if (info == null) + { + return; + } + + _selectedFilename = info.VideoFileName; + IMDBMovie.SetMovieProperties(item); + GUIFilmstripControl filmstrip = parent as GUIFilmstripControl; + + if (filmstrip != null) + { + filmstrip.InfoImageFileName = item.ThumbnailImage; + } + } + + private bool GetUserPasswordString(ref string sString) + { + VirtualKeyboard keyboard = (VirtualKeyboard)GUIWindowManager.GetWindow((int)Window.WINDOW_VIRTUAL_KEYBOARD); + + if (null == keyboard) + { + return false; + } + + keyboard.IsSearchKeyboard = true; + keyboard.Reset(); + keyboard.Password = true; + keyboard.Text = sString; + keyboard.DoModal(GetID); // show it... + + if (keyboard.IsConfirmed) + { + sString = keyboard.Text; + } + + return keyboard.IsConfirmed; + } + + private void OnShowFileMenu(bool preselectDelete) + { + GUIListItem item = facadeLayout.SelectedListItem; + + if (item == null) + { + return; + } + + if (item.IsFolder && item.Label == "..") + { + return; + } + + if (!_virtualDirectory.RequestPin(item.Path)) + { + return; + } + + // init + GUIDialogFile dlgFile = (GUIDialogFile)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_FILE); + + if (dlgFile == null) + { + return; + } + + // File operation settings + dlgFile.SetSourceItem(item); + dlgFile.SetSourceDir(_currentFolder); + dlgFile.SetDestinationDir(_fileMenuDestinationDir); + dlgFile.SetDirectoryStructure(_virtualDirectory); + + if (preselectDelete) + { + dlgFile.PreselectDelete(); + } + + dlgFile.DoModal(GetID); + _fileMenuDestinationDir = dlgFile.GetDestinationDir(); + //final + _oldStateSMSsearch = facadeLayout.EnableSMSsearch; + facadeLayout.EnableSMSsearch = false; + + if (dlgFile.Reload()) + { + int selectedItem = facadeLayout.SelectedListItemIndex; + + if (_currentFolder != dlgFile.GetSourceDir()) + { + selectedItem = -1; + } + + LoadDirectory(_currentFolder); + + if (selectedItem >= 0) + { + if (selectedItem >= facadeLayout.Count) + selectedItem = facadeLayout.Count - 1; + GUIControl.SelectItemControl(GetID, facadeLayout.GetID, selectedItem); + } + } + + dlgFile.DeInit(); + dlgFile = null; + _resetSMSsearchDelay = DateTime.Now; + _resetSMSsearch = true; + } + + private static bool IsFolderPinProtected(string folder) + { + string pinCode = string.Empty; + return _virtualDirectory.IsProtectedShare(folder, out pinCode); + } + + private static void AddVideoFiles(string path, ref ArrayList availableFiles) + { + // + // Count the files in the current directory + // + bool currentCreateVideoThumbs = false; + + try + { + VirtualDirectory dir = new VirtualDirectory(); + dir.SetExtensions(Util.Utils.VideoExtensions); + // Temporary disable thumbcreation + using (Profile.Settings xmlreader = new MPSettings()) + { + currentCreateVideoThumbs = xmlreader.GetValueAsBool("thumbnails", "videoondemand", true); + } + using (Profile.Settings xmlwriter = new MPSettings()) + { + xmlwriter.SetValueAsBool("thumbnails", "videoondemand", false); + } + + List items = dir.GetDirectoryUnProtectedExt(path, true); + + foreach (GUIListItem item in items) + { + if (item.IsFolder) + { + if (item.Label != "..") + { + if (item.Path.ToUpperInvariant().IndexOf("VIDEO_TS") >= 0) + { + string strFile = String.Format(@"{0}\VIDEO_TS.IFO", item.Path); + availableFiles.Add(strFile); + } + if (item.Path.ToUpperInvariant().IndexOf("BDMV") >= 0) + { + string strFile = String.Format(@"{0}\index.bdmv", item.Path); + availableFiles.Add(strFile); + } + else + { + AddVideoFiles(item.Path, ref availableFiles); + } + } + } + else + { + availableFiles.Add(item.Path); + } + } + } + catch (Exception e) + { + Log.Info("Exception counting files:{0}", e); + // Ignore + } + finally + { + // Restore thumbcreation setting + using (Profile.Settings xmlwriter = new MPSettings()) + { + xmlwriter.SetValueAsBool("thumbnails", "videoondemand", currentCreateVideoThumbs); + } + } + } + + private void DownloadSubtitles() + { + try + { + GUIListItem item = facadeLayout.SelectedListItem; + + if (item == null) + { + return; + } + string path = item.Path; + bool isDVD = (path.ToUpperInvariant().IndexOf("VIDEO_TS") >= 0); + List listFiles = _virtualDirectory.GetDirectoryUnProtectedExt(_currentFolder, false); + string[] subExts = { + ".utf", ".utf8", ".utf-8", ".sub", ".srt", ".smi", ".rt", ".txt", ".ssa", ".aqt", ".jss", + ".ass", ".idx", ".ifo", ".webvtt", ".vtt" + }; + if (!isDVD) + { + // check if movie has subtitles + for (int i = 0; i < subExts.Length; i++) + { + for (int x = 0; x < listFiles.Count; ++x) + { + if (listFiles[x].IsFolder) + { + continue; + } + string subTitleFileName = listFiles[x].Path; + subTitleFileName = Path.ChangeExtension(subTitleFileName, subExts[i]); + + if (String.Compare(listFiles[x].Path, subTitleFileName, true) == 0) + { + string localSubtitleFileName = _virtualDirectory.GetLocalFilename(subTitleFileName); + Util.Utils.FileDelete(localSubtitleFileName); + _virtualDirectory.DownloadRemoteFile(subTitleFileName, 0); + } + } + } + } + else //download entire DVD + { + for (int i = 0; i < listFiles.Count; ++i) + { + if (listFiles[i].IsFolder) + { + continue; + } + + if (String.Compare(listFiles[i].Path, path, true) == 0) + { + continue; + } + + _virtualDirectory.DownloadRemoteFile(listFiles[i].Path, 0); + } + } + } + catch (ThreadAbortException) { } + } + + private bool IsFileStackable(string filename) + { + var pattern = Util.Utils.StackExpression(); + + for (int i = 0; i < pattern.Length; i++) + { + if (pattern[i].IsMatch(filename)) + { + return true; + } + } + return false; + } + + private void GetNfoFiles(string path, ref ArrayList nfoFiles) + { + string[] files = Directory.GetFiles(path, "*.nfo", SearchOption.AllDirectories); + var sortedFiles = files.OrderBy(f => f); + + foreach (string file in sortedFiles) + { + nfoFiles.Add(file); + } + } + + private void ReleaseResources() + { + if (facadeLayout != null) + { + facadeLayout.Clear(); + } + } + + private void CreateFolderThumb(GUIListItem item, bool recreateAll) + { + // find first 4 jpegs in this subfolder + + List itemlist = _virtualDirectory.GetDirectoryUnProtectedExt(item.Path, true); + + if (!recreateAll) + { + Filter(ref itemlist); + } + + List pictureList = new List(); + foreach (GUIListItem subitem in itemlist) + { + if (!subitem.IsFolder) + { + string[] thumbs = { + Util.Utils.GetVideosLargeThumbPathname(subitem.Path), + Path.ChangeExtension(subitem.Path, ".jpg"), + Path.ChangeExtension(subitem.Path, ".tbn"), + Path.ChangeExtension(subitem.Path, ".png") + }; + + foreach (string s in thumbs) + { + string thumbStr = s; + if (Util.Utils.FileExistsInCache(thumbStr)) + { + pictureList.Add(thumbStr); + break; + } + } + } + if (pictureList.Count >= 4) + { + break; + } + } + // combine 4 image files into one folder.jpg + + string filePath = Path.Combine(item.Path, @"Folder.jpg"); + + if (pictureList.Count == 1) + { + try + { + File.Copy(pictureList[0], filePath, true); + } + catch + { + Log.Error("CreateFolderThumb:: unable to create {0}", filePath); + } + } + else if (pictureList.Count > 1) + { + Util.Utils.FileDelete(filePath); + Util.Utils.CreateFolderPreviewThumb(pictureList, filePath, false); + } + + int selectedIndex = facadeLayout.SelectedListItemIndex; + LoadDirectory(_currentFolder, false); + facadeLayout.SelectedListItemIndex = selectedIndex; + } + + private static void Filter(ref List itemlist) + { + itemlist.RemoveAll(ContainsFolderThumb); + } + + private static bool ContainsFolderThumb(GUIListItem aItem) + { + if (!aItem.IsFolder && aItem.Path.Contains(@"folder.jpg")) + { + return true; + } + else + { + return false; + } + } + + #endregion + + #region Thread Set thumbs + + private void SetImdbThumbs(List itemlist, ISelectDVDHandler selectDVDHandler) + { + if (_setThumbs != null && _setThumbs.IsAlive) + { + _setThumbs.Abort(); + _setThumbs = null; + } + + _setThumbsThreadAborted = false; + + _threadGUIItems.Clear(); + _threadGUIItems.AddRange(itemlist); + _threadISelectDVDHandler = selectDVDHandler; + + _setThumbs = new Thread(ThreadSetIMDBThumbs); + _setThumbs.Priority = ThreadPriority.Lowest; + _setThumbs.IsBackground = true; + _setThumbs.Start(); + } + + private void ThreadSetIMDBThumbs() + { + try + { + _threadISelectDVDHandler.SetIMDBThumbs(_threadGUIItems, _markWatchedFiles); + // Refresh thumb on selected item + _currentSelectedItem = facadeLayout.SelectedListItemIndex; + SelectCurrentItem(); + } + catch (ThreadAbortException) + { + Log.Debug("GUIVideoFiles: Thread SetIMDBThumbs aborted."); + _setThumbsThreadAborted = true; + } + } + + #endregion + + #region IMDB.IProgress + + public bool OnDisableCancel(IMDBFetcher fetcher) + { + GUIDialogProgress pDlgProgress = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + if (pDlgProgress.IsInstance(fetcher)) + { + pDlgProgress.DisableCancel(true); + } + return true; + } + + public void OnProgress(string line1, string line2, string line3, int percent) + { + if (!GUIWindowManager.IsRouted) + { + return; + } + GUIDialogProgress pDlgProgress = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + pDlgProgress.ShowProgressBar(true); + pDlgProgress.SetLine(1, line1); + pDlgProgress.SetLine(2, line2); + if (percent > 0) + { + pDlgProgress.SetPercentage(percent); + } + pDlgProgress.Progress(); + } + + public bool OnSearchStarting(IMDBFetcher fetcher) + { + GUIDialogProgress pDlgProgress = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + // show dialog that we're busy querying www.imdb.com + String heading; + if (_scanning) + { + heading = String.Format("{0}:{1}/{2}", GUILocalizeStrings.Get(197), _scanningFileNumber, _scanningFileTotal); + } + else + { + heading = GUILocalizeStrings.Get(197); + } + pDlgProgress.Reset(); + pDlgProgress.SetHeading(heading); + pDlgProgress.SetLine(1, fetcher.MovieName); + pDlgProgress.SetLine(2, string.Empty); + pDlgProgress.SetObject(fetcher); + pDlgProgress.StartModal(GUIWindowManager.ActiveWindow); + return true; + } + + public bool OnSearchStarted(IMDBFetcher fetcher) + { + GUIDialogProgress pDlgProgress = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + pDlgProgress.SetObject(fetcher); + pDlgProgress.DoModal(GUIWindowManager.ActiveWindow); + if (pDlgProgress.IsCanceled) + { + return false; + } + return true; + } + + public bool OnSearchEnd(IMDBFetcher fetcher) + { + GUIDialogProgress pDlgProgress = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + if ((pDlgProgress != null) && (pDlgProgress.IsInstance(fetcher))) + { + pDlgProgress.Close(); + } + return true; + } + + public bool OnMovieNotFound(IMDBFetcher fetcher) + { + if (_scanning) + { + _conflictFiles.Add(fetcher.Movie); + return false; + } + // show dialog... + GUIDialogOK pDlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); + pDlgOk.SetHeading(195); + pDlgOk.SetLine(1, fetcher.MovieName); + pDlgOk.SetLine(2, string.Empty); + pDlgOk.DoModal(GUIWindowManager.ActiveWindow); + return true; + } + + public bool OnDetailsStarting(IMDBFetcher fetcher) + { + GUIDialogProgress pDlgProgress = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + // show dialog that we're downloading the movie info + String heading; + if (_scanning) + { + heading = String.Format("{0}:{1}/{2}", GUILocalizeStrings.Get(198), _scanningFileNumber, _scanningFileTotal); + } + else + { + heading = GUILocalizeStrings.Get(198); + } + pDlgProgress.Reset(); + pDlgProgress.SetHeading(heading); + //pDlgProgress.SetLine(0, strMovieName); + pDlgProgress.SetLine(1, fetcher.MovieName); + pDlgProgress.SetLine(2, string.Empty); + pDlgProgress.SetObject(fetcher); + pDlgProgress.StartModal(GUIWindowManager.ActiveWindow); + return true; + } + + public bool OnDetailsStarted(IMDBFetcher fetcher) + { + GUIDialogProgress pDlgProgress = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + pDlgProgress.SetObject(fetcher); + pDlgProgress.DoModal(GUIWindowManager.ActiveWindow); + if (pDlgProgress.IsCanceled) + { + return false; + } + return true; + } + + public bool OnDetailsEnd(IMDBFetcher fetcher) + { + GUIDialogProgress pDlgProgress = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + if ((pDlgProgress != null) && (pDlgProgress.IsInstance(fetcher))) + { + pDlgProgress.Close(); + } + return true; + } + + public bool OnActorsStarting(IMDBFetcher fetcher) + { + GUIDialogProgress pDlgProgress = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + // show dialog that we're downloading the actor info + String heading; + if (_scanning) + { + heading = String.Format("{0}:{1}/{2}", GUILocalizeStrings.Get(986), _scanningFileNumber, _scanningFileTotal); + } + else + { + heading = GUILocalizeStrings.Get(1301); + } + pDlgProgress.Reset(); + pDlgProgress.SetHeading(heading); + //pDlgProgress.SetLine(0, strMovieName); + pDlgProgress.SetLine(1, fetcher.MovieName); + pDlgProgress.SetLine(2, string.Empty); + pDlgProgress.SetObject(fetcher); + pDlgProgress.StartModal(GUIWindowManager.ActiveWindow); + return true; + } + + public bool OnActorInfoStarting(IMDBFetcher fetcher) + { + GUIDialogProgress pDlgProgress = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + // show dialog that we're downloading the actor info + String heading; + if (_scanning) + { + heading = String.Format("{0}:{1}/{2}", GUILocalizeStrings.Get(986), _scanningFileNumber, _scanningFileTotal); + } + else + { + heading = GUILocalizeStrings.Get(1302); + } + pDlgProgress.Reset(); + pDlgProgress.SetHeading(heading); + //pDlgProgress.SetLine(0, strMovieName); + pDlgProgress.SetLine(1, fetcher.ActorName); + pDlgProgress.SetLine(2, string.Empty); + pDlgProgress.SetObject(fetcher); + pDlgProgress.StartModal(GUIWindowManager.ActiveWindow); + return true; + } + + public bool OnActorsStarted(IMDBFetcher fetcher) + { + GUIDialogProgress pDlgProgress = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + pDlgProgress.SetObject(fetcher); + pDlgProgress.DoModal(GUIWindowManager.ActiveWindow); + if (pDlgProgress.IsCanceled) + { + return false; + } + return true; + } + + public bool OnActorsEnd(IMDBFetcher fetcher) + { + return true; + } + + public bool OnDetailsNotFound(IMDBFetcher fetcher) + { + if (_scanning) + { + _conflictFiles.Add(fetcher.Movie); + return false; + } + // show dialog... + GUIDialogOK pDlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK); + // show dialog... + pDlgOk.SetHeading(195); + pDlgOk.SetLine(1, fetcher.MovieName); + pDlgOk.SetLine(2, string.Empty); + pDlgOk.DoModal(GUIWindowManager.ActiveWindow); + return false; + } + + public bool OnRequestMovieTitle(IMDBFetcher fetcher, out string movieName) + { + movieName = string.Empty; + + if (_scanning) + { + _conflictFiles.Add(fetcher.Movie); + movieName = string.Empty; + return false; + } + + string filename = string.Empty; + + if (!string.IsNullOrEmpty(_selectedFilename)) + { + try + { + if (_selectedFilename.ToUpperInvariant().Contains(@"\VIDEO_TS\VIDEO_TS.IFO")) + { + filename = _selectedFilename.ToUpperInvariant().Replace(@"\VIDEO_TS\VIDEO_TS.IFO", string.Empty); + int iIndex = 0; + iIndex = filename.LastIndexOf(@"\"); + movieName = filename.Substring(iIndex + 1); + } + else if (_selectedFilename.ToUpperInvariant().Contains(@"\BDMV\INDEX.BDMV")) + { + filename = _selectedFilename.ToUpperInvariant().Replace(@"\BDMV\INDEX.BDMV", string.Empty); + int iIndex = 0; + iIndex = filename.LastIndexOf(@"\"); + movieName = filename.Substring(iIndex + 1); + } + else + { + movieName = Path.GetFileNameWithoutExtension(_selectedFilename); + Util.Utils.RemoveStackEndings(ref filename); + } + } + catch (Exception ex) + { + Log.Error("GUIVideoFiles: OnRequestMovieTitle {0}", ex.Message); + } + } + else + { + movieName = fetcher.MovieName; + } + + if (VirtualKeyboard.GetKeyboard(ref movieName, GetID)) + { + if (movieName == string.Empty) + { + return false; + } + return true; + } + + movieName = string.Empty; + return false; + } + + public bool OnSelectMovie(IMDBFetcher fetcher, out int selectedMovie) + { + if (_scanning) + { + _conflictFiles.Add(fetcher.Movie); + selectedMovie = -1; + return false; + } + GUIDialogSelect pDlgSelect = (GUIDialogSelect)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_SELECT); + // more then 1 movie found + // ask user to select 1 + string filename = string.Empty; + + if (!string.IsNullOrEmpty(_selectedFilename)) + { + if (_selectedFilename.ToUpperInvariant().Contains(@"VIDEO_TS\VIDEO_TS.IFO")) + { + filename = _selectedFilename.ToUpperInvariant().Replace(@"\VIDEO_TS\VIDEO_TS.IFO", string.Empty); + int iIndex = 0; + iIndex = filename.LastIndexOf(@"\"); + filename = filename.Substring(iIndex + 1); + } + else if (_selectedFilename.ToUpperInvariant().Contains(@"BDMV\INDEX.BDMV")) + { + filename = _selectedFilename.ToUpperInvariant().Replace(@"\BDMV\INDEX.BDMV", string.Empty); + int iIndex = 0; + iIndex = filename.LastIndexOf(@"\"); + filename = filename.Substring(iIndex + 1); + } + else + { + filename = Path.GetFileNameWithoutExtension(_selectedFilename); + Util.Utils.RemoveStackEndings(ref filename); + } + } + + string strHeading = GUILocalizeStrings.Get(196); + + if (!string.IsNullOrEmpty(filename)) + { + GUIPropertyManager.SetProperty("#selecteditem", filename); + } + + pDlgSelect.SetHeading(strHeading); + pDlgSelect.Reset(); + + for (int i = 0; i < fetcher.Count; ++i) + { + pDlgSelect.Add(fetcher[i].Title); + } + + pDlgSelect.EnableButton(true); + pDlgSelect.SetButtonLabel(413); // manual + pDlgSelect.DoModal(GUIWindowManager.ActiveWindow); + // and wait till user selects one + selectedMovie = pDlgSelect.SelectedLabel; + + if (pDlgSelect.IsButtonPressed) + { + return true; + } + if (selectedMovie == -1) + { + return false; + } + return true; + } + + public bool OnSelectActor(IMDBFetcher fetcher, out int selectedActor) + { + GUIDialogSelect pDlgSelect = (GUIDialogSelect)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_SELECT); + // more then 1 actor found + // ask user to select 1 + pDlgSelect.SetHeading(GUILocalizeStrings.Get(1310)); //select actor + pDlgSelect.Reset(); + for (int i = 0; i < fetcher.Count; ++i) + { + pDlgSelect.Add(fetcher[i].Title); + } + pDlgSelect.EnableButton(false); + pDlgSelect.DoModal(GUIWindowManager.ActiveWindow); + + // and wait till user selects one + selectedActor = pDlgSelect.SelectedLabel; + if (selectedActor != -1) + { + return true; + } + return false; + } + + public bool OnScanStart(int total) + { + _scanning = true; + _conflictFiles.Clear(); + _scanningFileTotal = total; + _scanningFileNumber = 1; + return true; + } + + public bool OnScanEnd() + { + _scanning = false; + if (_conflictFiles.Count > 0) + { + GUIDialogSelect pDlgSelect = (GUIDialogSelect)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_SELECT); + // more than 1 movie found + // ask user to select 1 + do + { + pDlgSelect.Reset(); + pDlgSelect.SetHeading(892); //select movie + for (int i = 0; i < _conflictFiles.Count; ++i) + { + IMDBMovie currentMovie = (IMDBMovie)_conflictFiles[i]; + string strFileName = string.Empty; + string path = currentMovie.Path; + string filename = currentMovie.File; + if (path != string.Empty) + { + if (path.EndsWith(@"\")) + { + path = path.Substring(0, path.Length - 1); + currentMovie.Path = path; + } + if (filename.StartsWith(@"\")) + { + filename = filename.Substring(1); + currentMovie.File = filename; + } + strFileName = path + @"\" + filename; + } + else + { + strFileName = filename; + } + pDlgSelect.Add(strFileName); + } + pDlgSelect.EnableButton(true); + pDlgSelect.SetButtonLabel(4517); // manual + pDlgSelect.DoModal(GUIWindowManager.ActiveWindow); + + // and wait till user selects one + int selectedMovie = pDlgSelect.SelectedLabel; + if (pDlgSelect.IsButtonPressed) + { + break; + } + if (selectedMovie == -1) + { + break; + } + IMDBMovie movieDetails = (IMDBMovie)_conflictFiles[selectedMovie]; + string searchText = movieDetails.Title; + if (searchText == string.Empty) + { + searchText = movieDetails.SearchString; + } + if (VirtualKeyboard.GetKeyboard(ref searchText, GetID)) + { + if (searchText != string.Empty) + { + movieDetails.SearchString = searchText; + if (IMDBFetcher.GetInfoFromIMDB(this, ref movieDetails, false, true)) + { + if (movieDetails != null) + { + _conflictFiles.RemoveAt(selectedMovie); + } + } + } + } + } while (_conflictFiles.Count > 0); + } + return true; + } + + public bool OnScanIterating(int count) + { + _scanningFileNumber = count; + return true; + } + + public bool OnScanIterated(int count) + { + _scanningFileNumber = count; + GUIDialogProgress pDlgProgress = + (GUIDialogProgress)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_PROGRESS); + if (pDlgProgress.IsCanceled) + { + return false; + } + return true; + } + + #endregion + + #region ISetupForm Members + + public bool CanEnable() + { + return true; + } + + public bool HasSetup() + { + return false; + } + + public string PluginName() + { + return "Videos"; + } + + public bool DefaultEnabled() + { + return true; + } + + public int GetWindowId() + { + return GetID; + } + + public bool GetHome(out string strButtonText, out string strButtonImage, out string strButtonImageFocus, + out string strPictureImage) + { + strButtonText = GUILocalizeStrings.Get(3); + strButtonImage = string.Empty; + strButtonImageFocus = string.Empty; + strPictureImage = @"hover_my videos.png"; + return true; + } + + public string Author() + { + return "Frodo, ajs"; + } + + public string Description() + { + return "Watch and organize your video files"; + } + + public void ShowPlugin() + { + // TODO: Add GUIVideoFiles.ShowPlugin implementation + } + + #endregion + + #region IShowPlugin Members + + public bool ShowDefaultHome() + { + return true; + } + + #endregion + + public static string GetCurrentFolder + { + get { return _currentFolder; } + } + } } \ No newline at end of file