Example #1
0
        private void ListboxArtistsUpdate(object sender, EventArgs e)
        {
            _mMDb = MusicDatabase.Instance;
            var artists = new ArrayList();

            //mdb.GetArtists(0, String.Empty, ref artists);
            _mMDb.GetAllArtists(ref artists);

            lvArtists.Items.Clear();
            lbSelectedArtist.Text = String.Empty;

            MDelegateStringUpdate    = UpdateStringMethod;
            MDelegateStatusUpdate    = UpdateStatusMethod;
            MDelegateLyricFound      = LyricFoundMethod;
            MDelegateLyricNotFound   = LyricNotFoundMethod;
            MDelegateThreadFinished  = ThreadFinishedMethod;
            MDelegateThreadException = ThreadExceptionMethod;

            foreach (var artist in artists)
            {
                var lvi = new ListViewItem((string)artist);
                lvArtists.Items.Add(lvi);
            }

            lvArtists.Sorting = SortOrder.Ascending;
            lvSongs.Items.Clear();
            lbArtistNumber.Text = String.Format("{0} artists found", lvArtists.Items.Count);
        }
Example #2
0
 /// <summary>
 /// Does a lookup by filename on the local music databae
 /// </summary>
 /// <returns>Whether a song could be found</returns>
 private bool GetCurrentSong()
 {
     try
     {
         MusicDatabase dbs        = MusicDatabase.Instance;
         string        strFile    = g_Player.Player.CurrentFile;
         Song          lookupSong = new Song();
         if (strFile == string.Empty)
         {
             return(false);
         }
         else
         {
             if (dbs.GetSongByFileName(strFile, ref lookupSong))
             {
                 AudioscrobblerBase.CurrentPlayingSong = lookupSong;
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
     }
     catch (Exception)
     {
         return(false);
     }
 }
Example #3
0
        /// <summary>
        /// Load settings and register player events
        /// </summary>
        public void Start()
        {
            string currentUser = String.Empty;

            _alertTime = INFINITE_TIME;

            GUIWindowManager.OnNewAction += new OnActionHandler(OnNewAction);
            g_Player.PlayBackStarted     += new g_Player.StartedHandler(OnPlayBackStarted);
            g_Player.PlayBackEnded       += new g_Player.EndedHandler(OnPlayBackEnded);
            g_Player.PlayBackStopped     += new g_Player.StoppedHandler(OnPlayBackStopped);

            using (Settings xmlreader = new MPSettings())
            {
                currentUser         = xmlreader.GetValueAsString("audioscrobbler", "user", String.Empty);
                _announceNowPlaying = xmlreader.GetValueAsBool("audioscrobbler", "EnableNowPlaying", true);
            }

            MusicDatabase mdb = MusicDatabase.Instance;

            _doSubmit = (mdb.AddScrobbleUserSettings(Convert.ToString(mdb.AddScrobbleUser(currentUser)), "iSubmitOn", -1) == 1)
                    ? true
                    : false;

            Log.Info("Audioscrobbler plugin: Submit songs: {0}, announce Now Playing: {1}", Convert.ToString(_doSubmit),
                     Convert.ToString(_announceNowPlaying));

            if (_doSubmit)
            {
                OnManualConnect(null, null);
            }
        }
        private void buttonNeighboursFilter_Click(object sender, EventArgs e)
        {
            //      buttonNeighboursFilter.Enabled = false;
            listViewNeighbours.Clear();
            tabControlLiveFeeds.Enabled = false;
            ArrayList artistsInDB = new ArrayList();

            songList = new List <Song>();
            songList = lastFmLookup.getNeighboursArtists(false);
            listViewNeighbours.Columns.Add("Artist", 250);
            for (int i = 0; i < songList.Count; i++)
            {
                MusicDatabase mdb = MusicDatabase.Instance;
                if (mdb.GetArtists(4, songList[i].Artist, ref artistsInDB))
                {
                    bool foundDoubleEntry = false;
                    for (int j = 0; j < listViewNeighbours.Items.Count; j++)
                    {
                        if (listViewNeighbours.Items[j].Text == songList[i].Artist)
                        {
                            foundDoubleEntry = true;
                            break;
                        }
                    }
                    if (!foundDoubleEntry)
                    {
                        listViewNeighbours.Items.Add(BuildListViewArtist(songList[i], false, false));
                    }
                }
                //else
                //  MessageBox.Show("Artist " + songList[i].Artist + " already in DB!");
            }
            tabControlLiveFeeds.Enabled = true;
        }
Example #5
0
 private void DeleteFromDatabase(GUIListItem item)
 {
     // delete from database
     if (Util.Utils.IsPicture(item.Path))
     {
         //Remove from picture database
         PictureDatabase.DeletePicture(item.Path);
     }
     else if (Util.Utils.IsVideo(item.Path))
     {
         //Remove from video database
         VideoDatabase.DeleteMovie(item.Path);
     }
     else if (Util.Utils.IsAudio(item.Path))
     {
         //Remove from music database
         if (dbMusic == null)
         {
             dbMusic = MusicDatabase.Instance;
         }
         if (dbMusic != null)
         {
             dbMusic.DeleteSong(item.Path, true);
         }
     }
 }
Example #6
0
        /// <summary>
        /// Create playlist item from a file
        /// </summary>
        /// <param name="file">Path to file</param>
        /// <returns>Playlist item</returns>
        internal static MediaPortal.Playlists.PlayListItem CreatePlaylistItemFromMusicFile(string file)
        {
            FileInfo info = null;

            MediaPortal.Playlists.PlayListItem item = new MediaPortal.Playlists.PlayListItem();

            try
            {
                info = new FileInfo(file);
            }
            catch (Exception e)
            {
                WifiRemote.LogMessage("Error loading music item from file: " + e.Message, WifiRemote.LogType.Error);
            }

            if (info != null)
            {
                item.Description = info.Name;
                item.FileName    = info.FullName;
                item.Type        = PlayListItem.PlayListItemType.Audio;
                MusicDatabase mpMusicDb = MusicDatabase.Instance;
                Song          song      = new Song();
                bool          inDb      = mpMusicDb.GetSongByFileName(item.FileName, ref song);

                if (inDb)
                {
                    item.Duration = song.Duration;
                }
            }

            return(item);
        }
Example #7
0
        public MusicViewHandler()
        {
            if (!File.Exists(customMusicViews))
            {
                File.Copy(defaultMusicViews, customMusicViews);
            }

            try
            {
                using (FileStream fileStream = new FileInfo(customMusicViews).OpenRead())
                {
                    SoapFormatter formatter = new SoapFormatter();
                    ArrayList     viewlist  = (ArrayList)formatter.Deserialize(fileStream);
                    foreach (ViewDefinition view in viewlist)
                    {
                        views.Add(view);
                    }
                    fileStream.Close();
                }
            }
            catch (Exception ex)
            {
                Log.Error("MusicViewHandler: MusicViewHandler {0}", ex.Message);
            }

            database = MusicDatabase.Instance;
        }
Example #8
0
 static void ScanDirectory(string path)
 {
     if (!Directory.Exists(path))
     {
         throw new DirectoryNotFoundException();
     }
     foreach (var file in Directory.EnumerateFiles(path))
     {
         if (!MusicDatabase.CheckFileSupported(file))
         {
             continue;
         }
         Console.WriteLine(file);
         var nb = new B()
         {
             BB = file.GetHashCode().ToString()
         };
         bColle.Insert(nb);
         aColle.Insert(new A()
         {
             AA = file, BB = nb
         });
         //MusicDatabase.CreateSongEntity(file);
     }
 }
        private void buttonCoverArtistsRefresh_Click(object sender, EventArgs e)
        {
            buttonCoverArtistsRefresh.Enabled = false;
            buttonCoverArtistsLookup.Enabled  = false;
            listViewCoverArtists.Clear();
            ArrayList     CoverArtists = new ArrayList();
            MusicDatabase mdb          = MusicDatabase.Instance;

            if (mdb.GetAllArtists(ref CoverArtists))
            {
                listViewCoverArtists.Columns.Add("Artist", 300);
                listViewCoverArtists.Columns.Add("Low res", 60);
                listViewCoverArtists.Columns.Add("High res", 60);

                progressBarCoverArtists.Maximum = CoverArtists.Count;
                progressBarCoverArtists.Value   = 0;
                progressBarCoverArtists.Visible = true;

                for (int i = 0; i < CoverArtists.Count; i++)
                {
                    try
                    {
                        string       curArtist = CoverArtists[i].ToString();
                        ListViewItem listItem  = new ListViewItem(curArtist);

                        // check low res
                        string strThumb = Util.Utils.GetCoverArt(Thumbs.MusicArtists, curArtist);
                        if (File.Exists(strThumb))
                        {
                            listItem.SubItems.Add((new FileInfo(strThumb).Length / 1024) + "KB");
                        }
                        else
                        {
                            listItem.SubItems.Add("none");
                            Log.Info("Audioscrobbler: Artist cover missing: {0}", curArtist);
                        }

                        // check high res
                        strThumb = Util.Utils.ConvertToLargeCoverArt(strThumb);
                        if (File.Exists(strThumb))
                        {
                            listItem.SubItems.Add((new FileInfo(strThumb).Length / 1024) + "KB");
                        }
                        else
                        {
                            listItem.SubItems.Add("none");
                        }

                        listViewCoverArtists.Items.Add(listItem);

                        progressBarCoverArtists.Value = i + 1;
                    }
                    catch (Exception) {}
                }
                progressBarCoverArtists.Visible = false;
            }
            buttonCoverArtistsRefresh.Enabled = true;
            buttonCoverArtistsLookup.Enabled  = true;
        }
Example #10
0
        private int m_TimerInterval = 2000; // milliseconds

        #endregion

        #region Constructors/Destructors

        public MusicShareWatcherHelper()
        {
            // Create Log File
            Log.BackupLogFile(LogType.MusicShareWatcher);

            musicDB = MusicDatabase.Instance;
            LoadShares();
            Log.Info(LogType.MusicShareWatcher, "MusicShareWatcher starting up!");
        }
Example #11
0
        private void setMusicVideoArtist(ref DBArtistInfo mv, string artistName, string artistmbid)
        {
            if (string.IsNullOrEmpty(artistName))
            {
                return;
            }
            logger.Debug("In Method: setMusicVideoArtist(ref DBArtistInfo mv, Artist: " + artistName + " MBID: " + artistmbid + ")");

            MusicDatabase m_db = null;

            try
            {
                m_db = MusicDatabase.Instance;
            }
            catch (Exception e)
            {
                logger.Error("setMusicVideoArtist: Music database init failed " + e.ToString());
                return;
            }

            var artistInfo = new MediaPortal.Music.Database.ArtistInfo();

            if (!m_db.GetArtistInfo(artistName, ref artistInfo))
            {
                return;
            }

            // Name
            mv.Artist = artistName;
            // MBID
            // mv.MdID =
            // Tags
            char[]   delimiters = new char[] { ',' };
            string[] tags       = artistInfo.Genres.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
            foreach (string tag in tags)
            {
                mv.Tag.Add(tag.Trim());
            }
            tags = artistInfo.Styles.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
            foreach (string tag in tags)
            {
                mv.Tag.Add(tag.Trim());
            }
            // Bio
            mv.bioSummary = artistInfo.AMGBio;
            mv.bioContent = artistInfo.AMGBio;
            // Additional
            mv.Born        = artistInfo.Born;
            mv.Genre       = artistInfo.Genres;
            mv.Styles      = artistInfo.Styles;
            mv.YearsActive = artistInfo.YearsActive;
            // Image URL
            if (!string.IsNullOrEmpty(artistInfo.Image) && !mv.ArtUrls.Contains(artistInfo.Image))
            {
                mv.ArtUrls.Add(artistInfo.Image);
            }
        }
        private void buttonDelUser_Click(object sender, EventArgs e)
        {
            MusicDatabase mdb = MusicDatabase.Instance;

            mdb.DeleteScrobbleUser(comboBoxUserName.Text);
            if (comboBoxUserName.Items.Count <= 1)
            {
                buttonDelUser.Enabled = false;
                maskedTextBoxASPassword.Clear();
            }
            comboBoxUserName.Items.Clear();
            LoadSettings();
        }
Example #13
0
        /// <summary>
        /// Add MpExtended information to playlist item
        /// </summary>
        /// <param name="item">MediaPortal playlist item</param>
        /// <param name="message">Playlist message item that is sent to client</param>
        internal static void AddMpExtendedInfo(MediaPortal.Playlists.PlayListItem item, PlaylistEntry message)
        {
            MusicDatabase mpMusicDb = MusicDatabase.Instance;
            Song          song      = new Song();
            bool          inDb      = mpMusicDb.GetSongByFileName(item.FileName, ref song);

            if (inDb)
            {
                message.Name2           = song.Album;
                message.AlbumArtist     = song.AlbumArtist;
                message.Title           = song.Title;
                message.MpExtId         = song.Id.ToString();
                message.MpExtMediaType  = (int)MpExtended.MpExtendedMediaTypes.MusicTrack;
                message.MpExtProviderId = (int)MpExtended.MpExtendedProviders.MPMusic;
            }
        }
Example #14
0
        /// <summary>
        /// Plays a music file, starting from a given position
        /// </summary>
        /// <param name="file">File that is played</param>
        /// <param name="startPos">Start position within the song  (in ms)</param>
        internal static void PlayFile(string file, int startPos)
        {
            MusicDatabase mpMusicDb = MusicDatabase.Instance;
            Song          song      = new Song();
            bool          inDb      = mpMusicDb.GetSongByFileName(file, ref song);

            if (inDb)
            {
                //TODO: fill OSD information
                new Communication().PlayAudioFile(file, startPos);
            }
            else
            {
                new Communication().PlayAudioFile(file, startPos);
            }
        }
Example #15
0
        public static void RestartMP()
        {
            bool hideTaskBar = false;

            using (Settings xmlreader = new MPSettings())
            {
                hideTaskBar = xmlreader.GetValueAsBool("general", "hidetaskbar", false);
            }

            if (hideTaskBar)
            {
                Win32API.EnableStartBar(true);
                Win32API.ShowStartBar(true);
            }

            Log.Info("argustv: OnRestart - prepare for restart!");
            File.Delete(Config.GetFile(Config.Dir.Config, "mediaportal.running"));
            Log.Info("argustv: OnRestart - saving settings...");
            Settings.SaveCache();

            Log.Info("argustv: disposing databases.");
            FolderSettings.Dispose();
            PictureDatabase.Dispose();
            VideoDatabase.Dispose();
            MusicDatabase.Dispose();
            VolumeHandler.Dispose();

            System.Diagnostics.Process restartScript = new System.Diagnostics.Process();
            restartScript.EnableRaisingEvents        = false;
            restartScript.StartInfo.WorkingDirectory = Config.GetFolder(Config.Dir.Base);
            restartScript.StartInfo.FileName         = Config.GetFile(Config.Dir.Base, @"restart.vbs");
            Log.Debug("argustv: OnRestart - executing script {0}", restartScript.StartInfo.FileName);
            restartScript.Start();

            try
            {
                // Maybe the scripting host is not available therefore do not wait infinitely.
                if (!restartScript.HasExited)
                {
                    restartScript.WaitForExit();
                }
            }
            catch (Exception ex)
            {
                Log.Error("argustv: OnRestart - WaitForExit: {0}", ex.Message);
            }
        }
Example #16
0
        public MusicDBReorg()
        {
            // load settings
            using (Settings reader = new MPSettings())
            {
                _runMondays    = reader.GetValueAsBool("musicdbreorg", "monday", false);
                _runTuesdays   = reader.GetValueAsBool("musicdbreorg", "tuesday", false);
                _runWednesdays = reader.GetValueAsBool("musicdbreorg", "wednesday", false);
                _runThursdays  = reader.GetValueAsBool("musicdbreorg", "thursday", false);
                _runFridays    = reader.GetValueAsBool("musicdbreorg", "friday", false);
                _runSaturdays  = reader.GetValueAsBool("musicdbreorg", "saturday", false);
                _runSundays    = reader.GetValueAsBool("musicdbreorg", "sunday", false);
                _runHours      = reader.GetValueAsInt("musicdbreorg", "hours", 0);
                _runMinutes    = reader.GetValueAsInt("musicdbreorg", "minutes", 0);
            }

            mDB = MusicDatabase.Instance;
        }
Example #17
0
        private void UpdateCurrentTrackRating(int RatingValue)
        {
            if (RatingValue < 0 || RatingValue > 5)
            {
                RatingValue = -1;
            }

            CurrentTrackTag.Rating = RatingValue;
            GUIPropertyManager.SetProperty("#Play.Current.Rating",
                                           (Convert.ToDecimal(2 * CurrentTrackTag.Rating + 1)).ToString());

            MusicDatabase dbs     = MusicDatabase.Instance;
            string        strFile = g_Player.CurrentFile;

            dbs.SetRating(strFile, RatingValue);
            Log.Info("GUIMusicPlayingNow: Set rating for song {0} to {1}", Path.GetFileName(g_Player.CurrentFile),
                     Convert.ToString(RatingValue));
        }
Example #18
0
        /// <summary>
        /// Adds a song to a playlist
        /// </summary>
        /// <param name="type">Type of the playlist</param>
        /// <param name="entry">Item that gets added</param>
        /// <param name="index">Index where the item should be added</param>
        /// <param name="refresh">Should the playlist be refreshed after the item is added</param>
        public static void AddItemToPlaylist(String type, PlaylistEntry entry, int index, bool refresh)
        {
            PlayListType   plType         = GetTypeFromString(type);
            PlayListPlayer playListPlayer = PlayListPlayer.SingletonPlayer;
            PlayList       playList       = playListPlayer.GetPlaylist(plType);
            PlayListItem   item           = null;

            //If it's a music item, try to find it in the db
            if (plType == PlayListType.PLAYLIST_MUSIC)
            {
                MusicDatabase mpMusicDb = MusicDatabase.Instance;
                Song          song      = new Song();
                bool          inDb      = mpMusicDb.GetSongByFileName(entry.FileName, ref song);


                if (inDb)
                {
                    item = ToPlayListItem(song);
                }
            }
            else if (plType == PlayListType.PLAYLIST_VIDEO)
            {
                IMDBMovie movie = new IMDBMovie();
                int       id    = VideoDatabase.GetMovieInfo(entry.FileName, ref movie);

                if (id > 0)
                {
                    item = ToPlayListItem(movie);
                }
            }

            if (item == null)
            {
                item = new PlayListItem(entry.Name, entry.FileName, entry.Duration);
            }

            playList.Insert(item, index);

            if (refresh)
            {
                RefreshPlaylistIfVisible();
            }
        }
Example #19
0
        /// <summary>
        /// Grab the track data and process
        /// </summary>
        /// <param name="mv"></param>
        /// <param name="artist"></param>
        /// <param name="track"></param>
        /// <param name="mbid"></param>
        private void setMusicVideoTrack(ref DBTrackInfo mv, string artist, string track, string mbid)
        {
            if (track == null && mbid == null)
            {
                return;
            }
            logger.Debug("In Method: setMusicVideoTrack(ref DBTrackInfo mv, Artist: " + artist + ", Track: " + track + ", MBID: " + mbid + ")");

            MusicDatabase m_db = null;

            try
            {
                m_db = MusicDatabase.Instance;
            }
            catch (Exception e)
            {
                logger.Error("setMusicVideoTrack: Music database init failed " + e.ToString());
                return;
            }

            var trackInfo = new MediaPortal.Music.Database.Song();

            if (!m_db.GetSongByMusicTagInfo(artist, string.Empty, track, false, ref trackInfo))
            {
                return;
            }

            mv.Track = trackInfo.Title;
            //mv.MdID = value;
            // Tag
            char[]   delimiters = new char[] { ',' };
            string[] tags       = trackInfo.Genre.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
            foreach (string tag in tags)
            {
                mv.Tag.Add(tag.Trim());
            }
            // mv.ArtUrls.Add(trackInfo.Image);
            // mv.bioSummary = mvCentralUtils.StripHTML(cdataSection.Value);
            // mv.bioContent = mvCentralUtils.StripHTML(cdataSection.Value);
            return;
        }
        private bool IsCanceled()
        {
            GUIDialogProgress pDlgProgress =
                (GUIDialogProgress)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_PROGRESS);

            if (null == pDlgProgress)
            {
                return(false);
            }

            pDlgProgress.ProgressKeys();
            if (pDlgProgress.IsCanceled)
            {
                try
                {
                    MusicDatabase.DirectExecute("rollback");
                }
                catch (Exception) {}
                return(true);
            }
            return(false);
        }
Example #21
0
 private void OnThreadMessage(GUIMessage message)
 {
     switch (message.Message)
     {
     case GUIMessage.MessageType.GUI_MSG_PLAYING_10SEC:
         if (GUIWindowManager.ActiveWindow == GetID)
         {
             // SV
             //if (handler != null && handler.CurrentView == "Top100") return;
         }
         string strFile = message.Label;
         if (strFile.StartsWith(@"http://"))
         {
             break; // Don't try increasing the Top100 for streams
         }
         if (Util.Utils.IsAudio(strFile))
         {
             MusicDatabase dbs = MusicDatabase.Instance;
             dbs.IncrTop100CounterByFileName(strFile);
         }
         break;
     }
 }
Example #22
0
        private MusicTag GetTrackTag(MusicDatabase dbs, string strFile, bool useID3, string title, string artist)
        {
            MusicTag tag;
            var      song   = new Song();
            var      bFound = dbs.GetSongByFileName(strFile, ref song);

            if (!bFound)
            {
                // Track information already available
                if (!string.IsNullOrEmpty(title) && !string.IsNullOrEmpty(artist))
                {
                    song.Title  = title;
                    song.Artist = artist;
                    song.Album  = string.Empty;
                    tag         = song.ToMusicTag();
                    return(tag);
                }

                // If allowed, read tag from file
                if (useID3)
                {
                    tag = TagReader.ReadTag(strFile);
                    if (tag != null && !string.IsNullOrEmpty(tag.Title) && !string.IsNullOrEmpty(tag.Artist))
                    {
                        return(tag);
                    }
                }

                // tagreader failed or not using it and no available track information
                song.Title  = Path.GetFileNameWithoutExtension(strFile);
                song.Artist = string.Empty;
                song.Album  = string.Empty;
            }
            tag = song.ToMusicTag();
            return(tag);
        }
Example #23
0
        private void bgWorkerSearch_DoWork(object sender, DoWorkEventArgs e)
        {
//            Thread.CurrentThread.Name = "bgWorker - Search";

            #region 1. Sorting song
            lyricConfigInfosQueue = new Queue();

            if (m_SearchOnlyMarkedSongs == false)
            {
                //System.IO.Directory.SetCurrentDirectory(@"C:\Program Files\Team MediaPortal\MediaPortal");
                //string test = System.IO.Directory.GetCurrentDirectory();

                MusicDatabase dbs = new MusicDatabase();

                dbs.GetArtists(ref artists);

                m_noOfArtistsToSearch = artists.Count;

                for (int albumIndex = 0; albumIndex < artists.Count; albumIndex++)
                {
                    // If the user has cancelled the search => end this
                    if (stopCollectingOfTitles)
                    {
                        bgWorkerSearch.CancelAsync();
                        return;
                    }

                    string currentArtist = (string)artists[albumIndex];
                    dbs.GetSongsByArtist(currentArtist, ref songs);

                    for (int i = 0; i < songs.Count; i++)
                    {
                        // if song isn't known in lyric database the progressbar should not be incremented
                        int  songNotKnown = -1;
                        Song song         = (Song)songs[i];

                        /* Don't include song if one of the following is true
                         * 1. The artist isn't known (MP issue - should be deleted?)
                         * 2. Various artister should not be considered and the artist is "various artist"
                         * 3. Song with a lyric in the tag should not be considered, but instead include the file to the database right away */

                        MusicTag tag = null;

                        if (song.Artist.Equals("unknown") ||
                            (m_DisregardVariousArtist && (song.Artist.ToLower().Equals("various artists") || song.Artist.ToLower().Equals("diverse kunstnere"))))
                        {
                            m_DisregardedSongs += 1;
                        }
                        else if ((m_DisregardSongWithLyricInTag == false && ((tag = MediaPortal.TagReader.TagReader.ReadTag(song.FileName)) != null) && tag.Lyrics.Length > 0))
                        {
                            m_SongsWithLyric += 1;

                            string capArtist = LyricUtil.CapatalizeString(tag.Artist);
                            string capTitle  = LyricUtil.CapatalizeString(tag.Title);

                            if (DatabaseUtil.IsTrackInLyricsDatabase(MyLyricsSettings.LyricsDB, capArtist, capTitle).Equals(DatabaseUtil.LYRIC_NOT_FOUND))
                            {
                                MyLyricsSettings.LyricsDB.Add(DatabaseUtil.CorrectKeyFormat(capArtist, capTitle), new LyricsItem(capArtist, capTitle, tag.Lyrics, "Tag"));
                            }

                            if (DatabaseUtil.IsTrackInLyricsMarkedDatabase(MyLyricsSettings.LyricsMarkedDB, capArtist, capTitle).Equals(DatabaseUtil.LYRIC_MARKED))
                            {
                                MyLyricsSettings.LyricsMarkedDB.Remove(DatabaseUtil.CorrectKeyFormat(capArtist, capTitle));
                            }
                        }
                        else
                        {
                            int  status = DatabaseUtil.IsTrackInLyricsDatabase(MyLyricsSettings.LyricsDB, song.Artist, song.Title);
                            bool isTrackInLyricsMarkedDatabase = true;

                            if (!m_DisregardKnownLyric && status.Equals(DatabaseUtil.LYRIC_FOUND) ||
                                (!m_DisregardMarkedLyric && ((isTrackInLyricsMarkedDatabase = DatabaseUtil.IsTrackInLyricsMarkedDatabase(MyLyricsSettings.LyricsMarkedDB, song.Artist, song.Title).Equals(DatabaseUtil.LYRIC_MARKED)) || status.Equals(DatabaseUtil.LYRIC_MARKED))) ||
                                (status.Equals(DatabaseUtil.LYRIC_NOT_FOUND) && !DatabaseUtil.IsTrackInLyricsMarkedDatabase(MyLyricsSettings.LyricsMarkedDB, song.Artist, song.Title).Equals(DatabaseUtil.LYRIC_MARKED)))
                            {
                                songNotKnown = 1;
                                if (++m_SongsNotKnown > m_Limit)
                                {
                                    songNotKnown = 0;
                                    bgWorkerSearch.ReportProgress(songNotKnown);
                                    goto startSearch;
                                }

                                string[] lyricId = new string[2] {
                                    song.Artist, song.Title
                                };
                                lyricConfigInfosQueue.Enqueue(lyricId);

                                m_SongsToSearch = lyricConfigInfosQueue.Count;
                                bgWorkerSearch.ReportProgress(songNotKnown);
                            }
                            else if (status.Equals(DatabaseUtil.LYRIC_FOUND))
                            {
                                m_SongsWithLyric += 1;
                            }
                            else //if (status.Equals(MyLyricsUtil.LYRIC_MARKED))
                            {
                                m_SongsWithMark += 1;
                            }
                        }
                        bgWorkerSearch.ReportProgress(songNotKnown);
                    }
                }
            }
            else
            {
                foreach (KeyValuePair <string, LyricsItem> kvp in MyLyricsSettings.LyricsMarkedDB)
                {
                    int songNotKnown = 1;
                    if (++m_SongsNotKnown > m_Limit)
                    {
                        songNotKnown = 0;
                        bgWorkerSearch.ReportProgress(-1);
                        goto startSearch;
                    }
                    string[] lyricId = new string[2] {
                        kvp.Value.Artist, kvp.Value.Title
                    };
                    lyricConfigInfosQueue.Enqueue(lyricId);
                    m_SongsToSearch = lyricConfigInfosQueue.Count;
                    bgWorkerSearch.ReportProgress(songNotKnown);
                }
            }

startSearch:



            # endregion

            #region 2. Searching for lyrics
            // create worker thread instance
            if (lyricConfigInfosQueue.Count > 0)
            {
                // start running the lyricController
                lc = new LyricsController(this, m_EventStopThread, sitesToSearchArray, false);

                lc.NoOfLyricsToSearch = lyricConfigInfosQueue.Count;
                ThreadStart runLyricController = delegate
                {
                    lc.Run();
                };
                m_LyricControllerThread = new Thread(runLyricController);
                m_LyricControllerThread.Start();

                lc.StopSearches = false;


                while (lyricConfigInfosQueue.Count != 0)
                {
                    // If the user has cancelled the search => end this
                    if (stopCollectingOfTitles && lc != null)
                    {
                        bgWorkerSearch.CancelAsync();
                        return;
                    }
                    else if (lc == null)
                    {
                        return;
                    }

                    if (m_noOfCurrentlySearches < m_NoOfCurrentSearchesAllowed && lc.StopSearches == false)
                    {
                        m_noOfCurrentlySearches += 1;
                        string[] lyricID = (string[])lyricConfigInfosQueue.Dequeue();
                        lc.AddNewLyricSearch(lyricID[0], lyricID[1]);
                    }

                    Thread.Sleep(100);
                }
            }
            else
            {
                ThreadFinished = new string[] { "", "", "There is no titles to search", "" };
            }
            #endregion
        }
Example #24
0
 public Peer(string name, MusicDatabase database, ReceiveResponse responseCallback)
 {
     Name          = name;
     PeerContainer = new PeerContainer();
     SearchEngine  = new SearchEngine(database, responseCallback);
 }
        private void GetCoverArt()
        {
            if (!Win32API.IsConnectedToInternet())
            {
                return;
            }

            GrabInProgress = true;
            GUICoverArtGrabberResults.CancelledByUser = false;
            _AbortedByUser = false;
            _Abort         = false;

            btnStart.Focus  = false;
            btnCancel.Focus = true;

            progCurrent.Percentage = 0;
            progOverall.Percentage = 0;

            lblCurrentAlbum.Label    = "";
            lblCurrentProgress.Label = "";
            lblFilteredSearch.Label  = "";
            lblFolderName.Label      = "";
            lblOverallProgress.Label = "";

            EnableControls(false);

            // Force a redraw...
            GUIWindowManager.Process();

            if (_MusicDatabase == null)
            {
                _MusicDatabase = MusicDatabase.Instance;
            }

            int albumCount = 0;
            int curCount   = 0;

            songs.Clear();

            try
            {
                ShowWaitCursor();
                string status = GUILocalizeStrings.Get(4503);

                if (status.Length == 0)
                {
                    status = "Getting album count. Please wait...";
                }

                lblCurrentAlbum.Label     = status;
                lblCurrentAlbum.Visible   = true;
                lblFilteredSearch.Visible = true;

                GUIWindowManager.Process();

                Log.Info("Cover art grabber:getting folder count for {0}...", _TopLevelFolderName);
                GetAlbumCount(_TopLevelFolderName, ref albumCount);
                Log.Info("Cover art grabber:{0} folders found", albumCount);
            }

            finally
            {
                HideWaitCursor();
            }

            lblFilteredSearch.Label    = "";
            lblCurrentProgress.Label   = "";
            lblCurrentProgress.Visible = true;
            ShowTotalProgressBar(true);
            GUIWindowManager.Process();

            Log.Info("Cover art grabber:getting pending cover count...");
            GetCoverArtList(_TopLevelFolderName, ref albumCount, ref curCount, _SkipIfCoverArtExists, ref songs);
            Log.Info("Cover art grabber:{0} covers queued for update", albumCount);

            if (_Abort)
            {
                Cleanup();
                return;
            }

            _CoversGrabbed = 0;
            _AbortedByUser = false;
            _AlbumCount    = songs.Count;

            try
            {
                if (_AlbumCount > 0)
                {
                    GuiCoverArtResults =
                        (GUICoverArtGrabberResults)GUIWindowManager.GetWindow((int)Window.WINDOW_MUSIC_COVERART_GRABBER_RESULTS);

                    if (null == GuiCoverArtResults)
                    {
                        return;
                    }

                    GuiCoverArtResults.SearchMode            = GUICoverArtGrabberResults.SearchDepthMode.Share;
                    GuiCoverArtResults.FindCoverArtProgress +=
                        new GUICoverArtGrabberResults.FindCoverArtProgressHandler(OnFindCoverArtProgress);
                    GuiCoverArtResults.FindCoverArtDone +=
                        new GUICoverArtGrabberResults.FindCoverArtDoneHandler(OnFindCoverArtDone);
                    GuiCoverArtResults.AlbumNotFoundRetryingFiltered +=
                        new GUICoverArtGrabberResults.AlbumNotFoundRetryingFilteredHandler(OnAlbumNotFoundRetryingFiltered);

                    ShowTotalProgressBar(true);
                    ShowCurrentProgressBar(true);

                    lblOverallProgress.Visible = true;
                    lblCurrentProgress.Visible = true;

                    GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_REFRESH, 0, 0, 0, GetID, 0, null);
                    GUIWindowManager.SendMessage(msg);

                    for (int i = 0; i < songs.Count; i++)
                    {
                        if (_Abort)
                        {
                            break;
                        }

                        lblFilteredSearch.Clear();
                        lblFilteredSearch.Visible = false;

                        Song curSong = songs[i];
                        CurrentCoverArtIndex = i + 1;
                        SetCurrentCoverArtProgressLabel(curSong.Album, 0);
                        Application.DoEvents();

                        lblCurrentAlbum.Label = string.Format(GrabbingAlbumNameFormatString, curSong.Album);
                        string progressText = GetCurrentProgressString(0, curSong.Album);
                        SetCurrentProgressPercentage(0);
                        SetCurrentCoverArtProgressLabel(progressText, 0);
                        GUIWindowManager.Process();

                        if (curSong.FileName.Length == 0)
                        {
                            continue;
                        }

                        string albumPath = Path.GetDirectoryName(curSong.FileName);
                        GuiCoverArtResults.GetAlbumCovers(curSong.Artist, curSong.Album, albumPath, GetID, true);

                        if (IsAbortedByUser())
                        {
                            break;
                        }

                        GuiCoverArtResults.DoModal(GetID);

                        if (IsAbortedByUser())
                        {
                            break;
                        }

                        if (GuiCoverArtResults.SelectedAlbum != null)
                        {
                            _CoversGrabbed++;

                            if (CoverArtSelected != null)
                            {
                                GuiCoverArtResults.SelectedAlbum.Artist = curSong.Artist;
                                GuiCoverArtResults.SelectedAlbum.Album  = curSong.Album;
                                CoverArtSelected(GuiCoverArtResults.SelectedAlbum, albumPath, _SaveImageToAlbumFolder,
                                                 _SaveImageToThumbsFolder);
                            }
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                Log.Info("Cover art grabber exception:{0}", ex.ToString());
                _GrabCompletedSuccessfully = false;
            }

            finally
            {
                Cleanup();
            }

            if (CoverArtGrabDone != null)
            {
                CoverArtGrabDone(this);
            }

            ShowResultsDialog(_AbortedByUser, _GrabCompletedSuccessfully, _CoversGrabbed, GetID);
        }
Example #26
0
        private static void ThreadEncodeTrack()
        {
            m_Ripping = true;

            try
            {
                CreateTempFolder();
                if (mp3Background)
                {
                    GUIWaitCursor.Show();
                }
                else if (dlgProgress != null)
                {
                    dlgProgress.Reset();
                    dlgProgress.SetPercentage(0);
                    dlgProgress.StartModal(GetID);
                    dlgProgress.Progress();
                    dlgProgress.ShowProgressBar(true);
                }

                while (importQueue.Count > 0)
                {
                    TrackInfo trackInfo = (TrackInfo)importQueue.Dequeue();
                    if ((dlgProgress != null) && !mp3Background)
                    {
                        if (importQueue.Count > 0)
                        {
                            dlgProgress.SetHeading(
                                string.Format(GUILocalizeStrings.Get(1105) + " ({0} " + GUILocalizeStrings.Get(1104) + ")",
                                              importQueue.Count + 1));
                        }
                        else
                        {
                            dlgProgress.SetHeading(GUILocalizeStrings.Get(1103));
                        }

                        dlgProgress.SetLine(2,
                                            string.Format("{0:00}. {1} - {2}", trackInfo.MusicTag.Track, trackInfo.MusicTag.Artist,
                                                          trackInfo.MusicTag.Title));
                        //dlgProgress.SetLine(2, trackInfo.TempFileName);
                        if (dlgProgress.IsCanceled)
                        {
                            m_CancelRipping = true;
                        }
                    }

                    if (!m_CancelRipping)
                    {
                        m_Drive = new CDDrive();
                        SaveTrack(trackInfo);
                        if (File.Exists(trackInfo.TempFileName) && !m_CancelRipping)
                        {
                            #region Tagging

                            try
                            {
                                Tags tags = Tags.FromFile(trackInfo.TempFileName);
                                tags["TRCK"] = trackInfo.MusicTag.Track.ToString() + "/" + trackInfo.TrackCount.ToString();
                                tags["TALB"] = trackInfo.MusicTag.Album;
                                tags["TPE1"] = trackInfo.MusicTag.Artist;
                                tags["TIT2"] = trackInfo.MusicTag.Title;
                                tags["TCON"] = trackInfo.MusicTag.Genre;
                                if (trackInfo.MusicTag.Year > 0)
                                {
                                    tags["TYER"] = trackInfo.MusicTag.Year.ToString();
                                }
                                tags["TENC"] = "MediaPortal / Lame";
                                tags.Save(trackInfo.TempFileName);
                            }
                            catch
                            {
                            }

                            #endregion

                            #region Database

                            try
                            {
                                if (!Directory.Exists(trackInfo.TargetDir))
                                {
                                    Directory.CreateDirectory(trackInfo.TargetDir);
                                }

                                if (File.Exists(trackInfo.TargetFileName))
                                {
                                    if (mp3ReplaceExisting)
                                    {
                                        File.Delete(trackInfo.TargetFileName);
                                    }
                                }

                                if (!File.Exists(trackInfo.TargetFileName))
                                {
                                    File.Move(trackInfo.TempFileName, trackInfo.TargetFileName);
                                }

                                if (File.Exists(trackInfo.TargetFileName) && mp3Database)
                                {
                                    if (importUnknown || (trackInfo.MusicTag.Artist != "Unknown Artist") ||
                                        (trackInfo.MusicTag.Album != "Unknown Album"))
                                    {
                                        MusicDatabase dbs = MusicDatabase.Instance;
                                        dbs.AddSong(trackInfo.TargetFileName);
                                    }
                                }
                            }
                            catch
                            {
                                Log.Info("CDIMP: Error moving encoded file {0} to new location {1}", trackInfo.TempFileName,
                                         trackInfo.TargetFileName);
                            }

                            #endregion
                        }
                    }
                }
                if (mp3Background)
                {
                    GUIWaitCursor.Hide();
                }
                else
                {
                    dlgProgress.Close();
                }
            }
            finally
            {
                CleanupTempFolder();
            }
            m_CancelRipping = false;
            m_Ripping       = false;
        }
        public bool Execute(out List <Song> songs)
        {
            if (currentLevel < 0)
            {
                previousLevel = -1;
                songs         = new List <Song>();
                return(false);
            }

            string           whereClause = string.Empty;
            string           orderClause = string.Empty;
            FilterDefinition definition  = (FilterDefinition)currentView.Filters[CurrentLevel];

            restrictionLength = 0;
            for (int i = 0; i < CurrentLevel; ++i)
            {
                BuildSelect((FilterDefinition)currentView.Filters[i], ref whereClause, i);
            }
            BuildWhere((FilterDefinition)currentView.Filters[CurrentLevel], ref whereClause);
            BuildRestriction((FilterDefinition)currentView.Filters[CurrentLevel], ref whereClause);
            BuildOrder((FilterDefinition)currentView.Filters[CurrentLevel], ref orderClause);

            if (CurrentLevel > 0)
            {
                // When grouping is active, we need to omit the "where ";
                if (!whereClause.Trim().StartsWith("group ") && whereClause.Trim() != "")
                {
                    whereClause = "where " + whereClause;
                }
            }

            //execute the query
            string sql = "";

            if (CurrentLevel == 0)
            {
                FilterDefinition defRoot     = (FilterDefinition)currentView.Filters[0];
                string           table       = GetTable(defRoot.Where);
                string           searchField = GetField(defRoot.Where);

                // Handle the grouping of songs
                if (definition.SqlOperator == "group")
                {
                    string searchTable = table;
                    string countField  = searchField; // when grouping on Albums, we need to count the artists
                    // We don't have an album table anymore, so change the table to search for to tracks here.
                    if (table == "album")
                    {
                        searchTable = "tracks";
                        countField  = "strAlbumArtist";
                    }

                    sql = String.Format("Select UPPER(SUBSTR({0},1,{1})) as IX, Count(distinct {2}) from {3} GROUP BY IX",
                                        searchField, definition.Restriction, countField, searchTable);
                    // only group special characters into a "#" entry is field is text based
                    if (defRoot.Where == "rating" || defRoot.Where == "year" || defRoot.Where == "track" || defRoot.Where == "disc#" ||
                        defRoot.Where == "timesplayed" || defRoot.Where == "favourites" || defRoot.Where == "date")
                    {
                        database.GetSongsByFilter(sql, out songs, table);
                    }
                    else
                    {
                        database.GetSongsByIndex(sql, out songs, CurrentLevel, table);
                    }

                    previousLevel = currentLevel;

                    return(true);
                }

                switch (table)
                {
                case "artist":
                case "albumartist":
                case "genre":
                case "composer":
                    sql = String.Format("select * from {0} ", table);
                    if (whereClause != string.Empty)
                    {
                        sql += "where " + whereClause;
                    }
                    if (orderClause != string.Empty)
                    {
                        sql += orderClause;
                    }
                    break;

                case "album":
                    sql = String.Format("select * from tracks ");
                    if (whereClause != string.Empty)
                    {
                        sql += "where " + whereClause;
                    }
                    sql += " group by strAlbum, strAlbumArtist ";
                    // We need to group on AlbumArtist, to show Albums with same name for different artists
                    if (orderClause != string.Empty)
                    {
                        sql += orderClause;
                    }
                    break;

                case "tracks":
                    if (defRoot.Where == "year")
                    {
                        songs = new List <Song>();
                        sql   = String.Format("select distinct iYear from tracks ");
                        SQLiteResultSet results = MusicDatabase.DirectExecute(sql);
                        for (int i = 0; i < results.Rows.Count; i++)
                        {
                            Song song = new Song();
                            try
                            {
                                song.Year = (int)Math.Floor(0.5d + Double.Parse(DatabaseUtility.Get(results, i, "iYear")));
                            }
                            catch (Exception)
                            {
                                song.Year = 0;
                            }
                            if (song.Year > 1000)
                            {
                                songs.Add(song);
                            }
                        }

                        previousLevel = currentLevel;

                        return(true);
                    }
                    else if (defRoot.Where == "recently added")
                    {
                        try
                        {
                            whereClause = "";
                            TimeSpan ts         = new TimeSpan(Convert.ToInt32(defRoot.Restriction), 0, 0, 0);
                            DateTime searchDate = DateTime.Today - ts;

                            whereClause = String.Format("where {0} > '{1}'", searchField, searchDate.ToString("yyyy-MM-dd hh:mm:ss"));
                            sql         = String.Format("select * from tracks {0} {1}", whereClause, orderClause);
                        }
                        catch (Exception) {}
                    }
                    else if (defRoot.Where == "conductor")
                    {
                        whereClause = "";
                        BuildRestriction(defRoot, ref whereClause);
                        if (whereClause != string.Empty)
                        {
                            whereClause = String.Format("where {0}", whereClause);
                        }
                        sql = String.Format("select distinct strConductor from tracks {0} {1}", whereClause, orderClause);
                    }
                    else
                    {
                        whereClause = "";
                        BuildRestriction(defRoot, ref whereClause);
                        if (whereClause != string.Empty)
                        {
                            whereClause = String.Format("where {0}", whereClause);
                        }
                        sql = String.Format("select * from tracks {0} {1}", whereClause, orderClause);
                    }
                    break;
                }
                database.GetSongsByFilter(sql, out songs, table);
            }
            else if (CurrentLevel < MaxLevels - 1)
            {
                FilterDefinition defCurrent = (FilterDefinition)currentView.Filters[CurrentLevel];
                string           table      = GetTable(defCurrent.Where);

                // Now we need to check the previous filters, if we were already on the tracks table previously
                // In this case the from clause must contain the tracks table only
                bool   isUsingTrackTable = false;
                string allPrevColumns    = string.Empty;
                for (int i = CurrentLevel; i > -1; i--)
                {
                    FilterDefinition filter = (FilterDefinition)currentView.Filters[i];

                    allPrevColumns += " " + GetField(filter.Where) + " ,";
                    if (GetTable(filter.Where) != table)
                    {
                        isUsingTrackTable = true;
                    }
                }
                allPrevColumns = allPrevColumns.Remove(allPrevColumns.Length - 1, 1); // remove extra trailing comma

                if (defCurrent.SqlOperator == "group")
                {
                    // in an odd scenario here as we have a group operator
                    // but not at the first level of view

                    // Build correct table for search
                    string searchTable = GetTable(defCurrent.Where);
                    string searchField = GetField(defCurrent.Where);
                    string countField  = searchField;
                    // We don't have an album table anymore, so change the table to search for to tracks here.
                    if (table == "album")
                    {
                        searchTable = "tracks";
                        countField  = "strAlbumArtist";
                    }

                    if (isUsingTrackTable && searchTable != "tracks")
                    {
                        // have the messy case where previous filters in view
                        // do not use the same table as the current level
                        // which means we can not just lookup values in search table

                        string joinSQL;
                        if (IsMultipleValueField(searchField))
                        {
                            joinSQL = string.Format("and tracks.{1} like '%| '||{0}.{1}||' |%' ",
                                                    searchTable, searchField);
                        }
                        else
                        {
                            joinSQL = string.Format("and tracks.{1} = {0}.{1} ",
                                                    searchTable, searchField);
                        }

                        whereClause = whereClause.Replace("group by ix", "");
                        whereClause = string.Format(" where exists ( " +
                                                    "    select 0 " +
                                                    "    from tracks " +
                                                    "    {0} " +
                                                    "    {1} " +
                                                    ") " +
                                                    "group by ix "
                                                    , whereClause, joinSQL);
                    }

                    sql = String.Format("select UPPER(SUBSTR({0},1,{1})) IX, Count(distinct {2}) from {3} {4} {5}",
                                        searchField, Convert.ToInt16(defCurrent.Restriction), countField,
                                        searchTable, whereClause, orderClause);
                    database.GetSongsByIndex(sql, out songs, CurrentLevel, table);
                }
                else
                {
                    string from = String.Format("{1} from {0}", table, GetField(defCurrent.Where));

                    if (isUsingTrackTable && table != "album" && defCurrent.Where != "Disc#")
                    {
                        from  = String.Format("{0} from tracks", allPrevColumns);
                        table = "tracks";
                    }

                    // When searching for an album, we need to retrieve the AlbumArtist as well, because we could have same album names for different artists
                    // We need also the Path to retrieve the coverart
                    // We don't have an album table anymore, so change the table to search for to tracks here.

                    for (int i = 0; i < currentLevel; i++)
                    {
                        // get previous filter to see, if we had an album that was not a group level
                        FilterDefinition defPrevious = (FilterDefinition)currentView.Filters[i];
                        if (defPrevious.Where == "album" && defPrevious.SqlOperator != "group")
                        {
                            if (whereClause != "")
                            {
                                whereClause += " and ";
                            }

                            string selectedArtist = currentSong.AlbumArtist;
                            DatabaseUtility.RemoveInvalidChars(ref selectedArtist);

                            // we don't store "unknown" into the datbase, so let's correct empty values
                            if (selectedArtist == "unknown")
                            {
                                selectedArtist = string.Empty;
                            }

                            whereClause += String.Format("strAlbumArtist like '%| {0} |%'", selectedArtist);
                            break;
                        }
                    }

                    if (table == "album")
                    {
                        from         = String.Format("* from tracks", GetField(defCurrent.Where));
                        whereClause += " group by strAlbum, strAlbumArtist ";
                    }
                    if (defCurrent.Where == "disc#")
                    {
                        from         = String.Format("* from tracks", GetField(defCurrent.Where));
                        whereClause += " group by strAlbum, strAlbumArtist, iDisc ";
                    }

                    sql = String.Format("select distinct {0} {1} {2}", from, whereClause, orderClause);

                    database.GetSongsByFilter(sql, out songs, table);
                }
            }
            else
            {
                for (int i = 0; i < currentLevel; i++)
                {
                    // get previous filter to see, if we had an album that was not a group level
                    FilterDefinition defPrevious = (FilterDefinition)currentView.Filters[i];
                    if (defPrevious.Where == "album" && defPrevious.SqlOperator != "group")
                    {
                        if (whereClause != "")
                        {
                            whereClause += " and ";
                        }

                        string selectedArtist = currentSong.AlbumArtist;
                        DatabaseUtility.RemoveInvalidChars(ref selectedArtist);

                        // we don't store "unknown" into the datbase, so let's correct empty values
                        if (selectedArtist == "unknown")
                        {
                            selectedArtist = string.Empty;
                        }

                        whereClause += String.Format("strAlbumArtist like '%| {0} |%'", selectedArtist);
                        break;
                    }
                }

                sql = String.Format("select * from tracks {0} {1}", whereClause, orderClause);

                database.GetSongsByFilter(sql, out songs, "tracks");
            }

            if (songs.Count == 1 && definition.SkipLevel)
            {
                if (currentLevel < MaxLevels - 1)
                {
                    if (previousLevel < currentLevel)
                    {
                        FilterDefinition fd = (FilterDefinition)currentView.Filters[currentLevel];
                        fd.SelectedValue = GetFieldValue(songs[0], fd.Where);
                        currentLevel     = currentLevel + 1;
                    }
                    else
                    {
                        currentLevel = currentLevel - 1;
                    }
                    if (!Execute(out songs))
                    {
                        return(false);
                    }
                }
            }

            previousLevel = currentLevel;

            return(true);
        }
        public void DeleteSingleAlbum()
        {
            // CMusicDatabaseReorg is friend of CMusicDatabase

            // use the same databaseobject as CMusicDatabase
            // to rollback transactions even if CMusicDatabase
            // memberfunctions are called; create our working dataset

            string          strSQL;
            SQLiteResultSet results;

            strSQL  = String.Format("select distinct strAlbum, strAlbumArtist from tracks order by strAlbum");
            results = MusicDatabase.DirectExecute(strSQL);
            int iRowsFound = results.Rows.Count;

            if (iRowsFound == 0)
            {
                GUIDialogOK pDlg = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
                if (null != pDlg)
                {
                    pDlg.SetHeading(313);
                    pDlg.SetLine(1, 425);
                    pDlg.SetLine(2, "");
                    pDlg.SetLine(3, "");
                    pDlg.DoModal(GUIWindowManager.ActiveWindow);
                }
                return;
            }
            ArrayList vecAlbums = new ArrayList();

            for (int i = 0; i < results.Rows.Count; ++i)
            {
                AlbumInfoCache album = new AlbumInfoCache();
                album.Album  = DatabaseUtility.Get(results, i, "strAlbum");
                album.Artist = DatabaseUtility.Get(results, i, "strAlbumArtist");
                vecAlbums.Add(album);
            }

            //	Show a selectdialog that the user can select the album to delete
            string          szText     = GUILocalizeStrings.Get(181);
            GUIDialogSelect pDlgSelect =
                (GUIDialogSelect)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_SELECT);

            if (null != pDlgSelect)
            {
                pDlgSelect.SetHeading(szText);
                pDlgSelect.Reset();
                foreach (AlbumInfoCache album in vecAlbums)
                {
                    pDlgSelect.Add(album.Album + " - " + album.Artist);
                }
                pDlgSelect.DoModal(GUIWindowManager.ActiveWindow);

                // and wait till user selects one
                int iSelectedAlbum = pDlgSelect.SelectedLabel;
                if (iSelectedAlbum < 0)
                {
                    vecAlbums.Clear();
                    return;
                }

                AlbumInfoCache albumDel = (AlbumInfoCache)vecAlbums[iSelectedAlbum];
                //	Delete album
                strSQL = String.Format("delete from tracks where strAlbum='{0}' and strAlbumArtist like '%{1}'", albumDel.Album,
                                       albumDel.Artist);
                MusicDatabase.DirectExecute(strSQL);

                //	Delete album info
                strSQL = String.Format("delete from albuminfo where strAlbum='{0}' and strAlbumArtist like '%{1}'",
                                       albumDel.Album, albumDel.Artist);
                MusicDatabase.DirectExecute(strSQL);
            }
        }
Example #29
0
        private bool GetIsCompilationAlbum(string path, int numFilesToCheck)
        {
            MusicDatabase dbMusic = null;

            DirectoryInfo di = new DirectoryInfo(path);

            FileInfo[] files = null;

            if (di == null)
            {
                return(false);
            }

            files = di.GetFiles();

            if (files == null || files.Length == 0)
            {
                return(false);
            }

            dbMusic = MusicDatabase.Instance;

            string artist             = string.Empty;
            bool   IsCompilationAlbum = false;
            int    difArtistCount     = 0;

            int checkCount = 0;

            if (numFilesToCheck == -1)
            {
                checkCount = files.Length;
            }

            else
            {
                Math.Min(files.Length, numFilesToCheck);
            }

            MusicTag tag  = null;
            Song     song = null;

            for (int i = 0; i < checkCount; i++)
            {
                string curTrackPath = files[i].FullName;

                if (!Util.Utils.IsAudio(curTrackPath))
                {
                    continue;
                }

                song = new Song();

                if (dbMusic.GetSongByFileName(curTrackPath, ref song))
                {
                    if (artist == string.Empty)
                    {
                        artist = song.Artist;
                        continue;
                    }

                    if (artist.ToLower().CompareTo(song.Artist.ToLower()) != 0)
                    {
                        difArtistCount++;
                    }
                }

                else
                {
                    tag = TagReader.TagReader.ReadTag(curTrackPath);

                    if (tag != null)
                    {
                        if (artist == string.Empty)
                        {
                            artist = tag.Artist;
                            continue;
                        }

                        if (artist.ToLower().CompareTo(tag.Artist.ToLower()) != 0)
                        {
                            difArtistCount++;
                        }
                    }
                }
            }

            if (difArtistCount > 0)
            {
                IsCompilationAlbum = true;
            }

            return(IsCompilationAlbum);
        }
Example #30
0
        private void SetLevelForPlayback(string mediaType, string Level)
        {
            if ((previousLevel == "Play" || previousLevel == "Pause") && (Level == "Play") && (previousMediaType != mediaType))
            {
                previousLevel = "Stop";
            }

            Playback playback = new Playback()
            {
                Title        = string.Empty,
                LengthString = string.Empty,
                Genre        = string.Empty,
                FileName     = string.Empty,
                Poster       = string.Empty,
                Fanart       = string.Empty
            };

            if (!mediaType.Equals("Plugin"))
            {
                if (g_Player.IsDVD)
                {
                    if (DebugMode)
                    {
                        Logger.Debug("Length is Long (Media is DVD)");
                    }
                    playback.LengthString = "Long";
                }
                else if ((mediaType == g_Player.MediaType.Video.ToString()) || mediaType == g_Player.MediaType.Recording.ToString())
                {
                    if (g_Player.Duration < (setLevelForMediaDuration * 60))
                    {
                        if (DebugMode)
                        {
                            Logger.Debug("Length is Short");
                        }
                        playback.LengthString = "Short";
                    }
                    else
                    {
                        if (DebugMode)
                        {
                            Logger.Debug("Length is Long");
                        }
                        playback.LengthString = "Long";
                    }
                }

                if (Level == "Play")
                {
                    playback.FileName = g_Player.Player.CurrentFile;

                    if (g_Player.IsMusic)
                    {
                        Song          song          = new Song();
                        MusicDatabase musicDatabase = MusicDatabase.Instance;
                        musicDatabase.GetSongByFileName(playback.FileName, ref song);
                        if (song != null)
                        {
                            playback.Genre = song.Genre;
                            playback.Title = song.Artist + " - " + song.Album + " - " + song.Title;
                        }
                    }

                    if (g_Player.IsVideo)
                    {
                        if (!playback.FileName.StartsWith("http://localhost/")) // Online Video is not in DB so skip DB Search
                        {
                            LatestMediaHandler.MQTTItem item;
                            try
                            {
                                if (DebugMode)
                                {
                                    Logger.Debug("Check to see if the video is a mounted disc.");
                                }

                                string filename = playback.FileName;
                                filename          = MountHelper.CheckMount(ref filename);
                                playback.FileName = filename;
                            }
                            catch
                            {
                                Logger.Warning("Daemontools not installed/configured");
                            }

                            item = MyVideoHelper.CheckDB(playback.FileName);
                            if (!string.IsNullOrEmpty(item.Filename))
                            {
                                playback.Genre  = item.Genres;
                                playback.Title  = item.Title;
                                playback.Poster = item.Poster;
                                playback.Fanart = item.Fanart;
                            }
                            else // Movie not in MyVideo's DB
                            {
                                if (DebugMode)
                                {
                                    Logger.Debug("Video is not in MyVideos database.");
                                }
                                try
                                {
                                    item = TVSeriesHelper.CheckDB(playback.FileName);
                                    if (!string.IsNullOrEmpty(item.Filename))
                                    {
                                        playback.Genre  = item.Genres;
                                        playback.Title  = item.Title;
                                        playback.Poster = item.Poster;
                                        playback.Fanart = item.Fanart;
                                    }
                                }
                                catch
                                {
                                    Logger.Warning("Error while searching TVSeries Database, probaly not installed");
                                }

                                if (string.IsNullOrEmpty(item.Filename))
                                {
                                    try
                                    {
                                        item = MovingPicturesHelper.CheckDB(playback.FileName);
                                        if (!string.IsNullOrEmpty(item.Filename))
                                        {
                                            playback.Genre  = item.Genres;
                                            playback.Title  = item.Title;
                                            playback.Poster = item.Poster;
                                            playback.Fanart = item.Fanart;
                                        }
                                    }
                                    catch
                                    {
                                        Logger.Warning("Error while searching MovingPictures Database, probaly not installed");
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (DebugMode)
                            {
                                Logger.Debug("Media is OnlineVideo");
                            }
                        }
                    }
                }

                SendEvent("Player", new string[] { "type:" + mediaType, "state:" + Level });
            }

            playback.Genre = !string.IsNullOrEmpty(playback.Genre) ? playback.Genre.Trim('|').Replace("|", " / ") : "";
            if (DebugMode)
            {
                Logger.Debug("ACTION " + Level + " Media: " + mediaType);
                if (!string.IsNullOrEmpty(playback.Title))
                {
                    Logger.Debug("Title: " + playback.Title);
                }
                if (!string.IsNullOrEmpty(playback.FileName))
                {
                    Logger.Debug("Filename: " + playback.FileName);
                }
                if (!string.IsNullOrEmpty(playback.Genre))
                {
                    Logger.Debug("Genre: " + playback.Genre);
                }
                if (!string.IsNullOrEmpty(playback.LengthString))
                {
                    Logger.Debug("Length: " + playback.LengthString);
                }
            }

            if (Level.Equals("Play"))
            {
                SendEvent("Player/" + mediaType, new string[] { "action:" + Level,
                                                                "data:" + JsonConvert.SerializeObject(playback, Formatting.Indented, new JsonSerializerSettings {
                        ContractResolver = new Utils.LowercaseContractResolver()
                    }) });
            }
            else
            {
                SendEvent("Player/" + mediaType, "action:" + Level);
            }

            previousLevel     = Level;
            previousMediaType = mediaType;
        }