Ejemplo n.º 1
0
        public NowPlayingMusic(Song song)
        {
            ItemId = song.Id;
            Album = song.Album;
            AlbumArtist = song.AlbumArtist;
            Artist = song.Artist;
            BitRate = song.BitRate;
            BitRateMode = song.BitRateMode;
            BPM = song.BPM;
            Channels = song.Channels;
            Codec = song.Codec;
            Comment = song.Comment;
            Composer = song.Composer;
            Conductor = song.Conductor;
            DateTimeModified = song.DateTimeModified;
            DateTimePlayed = song.DateTimePlayed;
            DiscId = song.DiscId;
            DiscTotal = song.DiscTotal;
            Duration = song.Duration;
            Genre = song.Genre;
            Lyrics = song.Lyrics;
            Rating = song.Rating;
            SampleRate = song.SampleRate;
            TimesPlayed = song.TimesPlayed;
            Title = song.Title;
            Track = song.Track;
            TrackTotal = song.TrackTotal;
            URL = song.URL;
            WebImage = song.WebImage;
            Year = song.Year;

            ImageName = MediaPortal.Util.Utils.GetAlbumThumbName(song.Artist, song.Album);
            ImageName = MediaPortal.Util.Utils.ConvertToLargeCoverArt(ImageName);
        }
 public QueuedTrack(Song track)
 {
   this.artist = track.Artist;
   this.title = track.Title;
   this.start_time = track.getQueueTime(true);
   this.source = track.getSourceParam();
   this.rating = track.getRateActionParam();
   this.duration = (int)track.Duration;
   this.album = track.Album;
   this.tracknr = track.Track;
   this.auth = track.AuthToken;
 }
Ejemplo n.º 3
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;
            }
        }
Ejemplo n.º 4
0
    public bool AssignAllSongFieldsFromResultSet(ref Song aSong, SQLiteResultSet aResult, int aRow)
    {
      if (aSong == null || aResult == null || aResult.Rows.Count < 1)
      {
        return false;
      }

      aSong.Id = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.idTrack");
      aSong.FileName = DatabaseUtility.Get(aResult, aRow, "tracks.strPath");
      aSong.Artist = DatabaseUtility.Get(aResult, aRow, "tracks.strArtist").Trim(trimChars);
      aSong.AlbumArtist = DatabaseUtility.Get(aResult, aRow, "tracks.strAlbumArtist").Trim(trimChars);
      aSong.Album = DatabaseUtility.Get(aResult, aRow, "tracks.strAlbum");
      aSong.Genre = DatabaseUtility.Get(aResult, aRow, "tracks.strGenre").Trim(trimChars);
      aSong.Title = DatabaseUtility.Get(aResult, aRow, "tracks.strTitle");
      aSong.Track = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iTrack");
      aSong.TrackTotal = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iNumTracks");
      aSong.Duration = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iDuration");
      aSong.Year = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iYear");
      aSong.TimesPlayed = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iTimesPlayed");
      aSong.Rating = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iRating");
      aSong.Favorite = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iFavorite") != 0;
      aSong.ResumeAt = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iResumeAt");
      aSong.DiscId = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iDisc");
      aSong.DiscTotal = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iNumDisc");
      aSong.Lyrics = DatabaseUtility.Get(aResult, aRow, "tracks.strLyrics");
      aSong.Composer = DatabaseUtility.Get(aResult, aRow, "tracks.strComposer").Trim(trimChars);
      aSong.Conductor = DatabaseUtility.Get(aResult, aRow, "tracks.strConductor").Trim(trimChars);
      aSong.Comment = DatabaseUtility.Get(aResult, aRow, "tracks.strComment").Trim(trimChars);
      aSong.FileType = DatabaseUtility.Get(aResult, aRow, "tracks.strFileType").Trim(trimChars);
      aSong.Codec = DatabaseUtility.Get(aResult, aRow, "tracks.strFullCodec").Trim(trimChars);
      aSong.BitRateMode = DatabaseUtility.Get(aResult, aRow, "tracks.strBitRateMode").Trim(trimChars);
      aSong.BPM = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iBPM");
      aSong.BitRate = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iBitRate");
      aSong.Channels = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iChannels");
      aSong.SampleRate = DatabaseUtility.GetAsInt(aResult, aRow, "tracks.iSampleRate");
      try
      {
        aSong.DateTimePlayed = DatabaseUtility.GetAsDateTime(aResult, aRow, "dateLastPlayed");
        aSong.DateTimeModified = DatabaseUtility.GetAsDateTime(aResult, aRow, "dateAdded");
      }
      catch (Exception ex)
      {
        Log.Warn("MusicDatabase Lookup: Exception parsing date fields: {0} stack: {1}", ex.Message, ex.StackTrace);
      }
      return true;
    }
Ejemplo n.º 5
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();
            }
        }
Ejemplo n.º 6
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;
        }
Ejemplo n.º 7
0
    public void SetRating(string aFilename, int aRating)
    {
      if (string.IsNullOrEmpty(aFilename))
      {
        return;
      }

      try
      {
        Song song = new Song();
        string strFileName = aFilename;
        DatabaseUtility.RemoveInvalidChars(ref strFileName);

        strSQL = String.Format("UPDATE tracks SET iRating={0} WHERE strPath='{1}'", aRating, strFileName);

        DirectExecute(strSQL);

        // Let's fire the Ratings change event
        if (MusicRatingChanged != null)
        {
          MusicRatingChanged(this, strFileName, aRating);
        }
        return;
      }
      catch (Exception ex)
      {
        Log.Error("musicdatabase exception err:{0} stack:{1}", ex.Message, ex.StackTrace);
        Open();
      }

      return;
    }
Ejemplo n.º 8
0
    private void ShowSong()
    {
      GUIDialogNotify dlg = (GUIDialogNotify)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_NOTIFY);
      if (dlg == null)
      {
        return;
      }

      //get albumart
      string albumart = g_Player.CurrentFile;
      int e = albumart.LastIndexOf(@"\") + 1;
      albumart = albumart.Remove(e);
      if (_slideList[_currentSlideIndex].Contains(albumart))
      {
        albumart = string.Empty;
      }
      else
      {
        albumart = Util.Utils.GetFolderThumbForDir(albumart);
        if (!Util.Utils.FileExistsInCache(albumart))
        {
          albumart = string.Empty;
        }
      }
      // get Song-info

      // hwahrmann 2006-11-22 Using the Tagreader caused a COM exception in Win Media SDK, when reading WMA files
      // Accessing the Music Database instead of using the Tagreader.
      //MediaPortal.TagReader.MusicTag tag = MediaPortal.TagReader.TagReader.ReadTag(g_Player.CurrentFile);
      Song song = new Song();

      // If we don't have a tag in the db, we use the filename without the extension as song.title
      song.Title = Path.GetFileNameWithoutExtension(g_Player.CurrentFile);
      mDB.GetSongByFileName(g_Player.CurrentFile, ref song);

      // Show Dialog
      dlg.Reset();
      dlg.Dispose();
      dlg.SetImage(albumart);
      dlg.SetHeading(4540);
      //dlg.SetText(tag.Title + "\n" + tag.Artist + "\n" + tag.Album);
      dlg.SetText(song.Title + "\n" + song.Artist + "\n" + song.Album);
      dlg.TimeOut = 5;
      dlg.DoModal(GUIWindowManager.ActiveWindow);
    }
Ejemplo n.º 9
0
    public void SetFavorite(Song aSong)
    {
      try
      {
        if (aSong.Id == -1)
        {
          return;
        }

        int iFavorite = 0;
        if (aSong.Favorite)
        {
          iFavorite = 1;
        }
        string strSQL = String.Format("UPDATE tracks SET iFavorite={0} WHERE idTrack={1}", iFavorite, aSong.Id);
        DirectExecute(strSQL);
        return;
      }
      catch (Exception ex)
      {
        Log.Error("musicdatabase exception err:{0} stack:{1}", ex.Message, ex.StackTrace);
        Open();
      }
    }
Ejemplo n.º 10
0
    private void ShowSong(string filename)
    {
      GUIDialogNotify dlg = (GUIDialogNotify) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_NOTIFY);
      if (dlg == null)
      {
        return;
      }

      //get albumart
      string albumart = g_Player.CurrentFile;
      int e = albumart.LastIndexOf(@"\") + 1;
      albumart = albumart.Remove(e);
      if (_slideList[_currentSlideIndex].Contains(albumart))
      {
        albumart = string.Empty;
      }
      else
      {
        albumart = Util.Utils.GetFolderThumbForDir(albumart);
        if (!Util.Utils.FileExistsInCache(albumart))
        {
          albumart = string.Empty;
        }
      }
      // get Song-info

      // hwahrmann 2006-11-22 Using the Tagreader caused a COM exception in Win Media SDK, when reading WMA files
      // Accessing the Music Database instead of using the Tagreader.
      //MediaPortal.TagReader.MusicTag tag = MediaPortal.TagReader.TagReader.ReadTag(g_Player.CurrentFile);
      Song song = new Song();
      MusicTag currentSong = new MusicTag();

      // If we don't have a tag in the db, we use the filename without the extension as song.title
      if (!mDB.GetSongByFileName(g_Player.CurrentFile, ref song))
      {
        try
        {
          // try Tagreader method to parse information
          var pl = PlayListPlayer.SingletonPlayer.GetPlaylist(PlayListPlayer.SingletonPlayer.CurrentPlaylistType);
          var plI = pl.First(plItem => plItem.FileName == filename);
          if (plI != null || plI.MusicTag != null)
          {
            currentSong = (MusicTag)plI.MusicTag;
          }
        }
        catch (Exception)
        {
          // Catch the COM execption but continue code with Music Database instead.
        }
      }

      // Show Dialog
      dlg.Reset();
      dlg.Dispose();
      dlg.SetImage(albumart);
      dlg.SetHeading(4540);
      if (currentSong == null || string.IsNullOrEmpty(currentSong.Title) ||
          (string.IsNullOrEmpty(currentSong.Artist) && string.IsNullOrEmpty(currentSong.AlbumArtist)))
      {
        song.Title = Path.GetFileNameWithoutExtension(g_Player.CurrentFile);
        dlg.SetText(song.Title + "\n" + song.Artist + "\n" + song.Album);
      }
      else
      {
        dlg.SetText(currentSong.Title + "\n" + currentSong.Artist + "\n" + currentSong.Album);
      }
      dlg.TimeOut = 5;
      dlg.DoModal(GUIWindowManager.ActiveWindow);
    }
Ejemplo n.º 11
0
    public Song Clone()
    {
      var newsong = new Song
                      {
                        Id = Id,
                        Album = Album,
                        Artist = Artist,
                        AlbumArtist = AlbumArtist,
                        Duration = Duration,
                        FileName = FileName,
                        Genre = Genre,
                        Composer = Composer,
                        Conductor = Conductor,
                        TimesPlayed = TimesPlayed,
                        Title = Title,
                        Track = Track,
                        TrackTotal = TrackTotal,
                        Year = Year,
                        Rating = Rating,
                        Favorite = Favorite,
                        DateTimeModified = DateTimeModified,
                        DateTimePlayed = DateTimePlayed,
                        URL = URL,
                        ResumeAt = ResumeAt,
                        DiscId = DiscId,
                        DiscTotal = DiscTotal,
                        Lyrics = Lyrics,
                        AuthToken = AuthToken,
                        Comment = Comment,
                        FileType = FileType,
                        Codec = Codec,
                        BitRateMode = BitRateMode,
                        BPM = BPM,
                        Channels = Channels,
                        SampleRate = SampleRate
                      };

      return newsong;
    }
    /// <summary>
    /// Push the given song on the queue.
    /// </summary>
    /// <param name="song_">The song to be enqueued.</param>
    public static void pushQueue(Song song_)
    {
      string logmessage = "Adding to queue: " + song_.ToShortString();
      if (_useDebugLog)
      {
        Log.Debug("AudioscrobblerBase: {0}", logmessage);
      }

      // Enqueue the song
      lock (queueLock)
      {
        queue.Add(song_);
      }

      if (submitThread != null)
      {
        if (submitThread.IsAlive)
        {
          try
          {
            Log.Debug("AudioscrobblerBase: trying to kill submit thread (no longer needed)");
            StopSubmitQueueThread();
          }
          catch (Exception ex)
          {
            Log.Warn("AudioscrobblerBase: Result of pre-submit thread abort - {0}", ex.Message);
          }
        }
      }

      // Try to submit immediately.
      StartSubmitQueueThread();
    }
Ejemplo n.º 13
0
    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
            FilterDefinition defPrevious = (FilterDefinition)currentView.Filters[i];
            if (defPrevious.Where == "album")
            {
              if (whereClause != "")
              {
                whereClause += " and ";
              }

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

              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
          FilterDefinition defPrevious = (FilterDefinition)currentView.Filters[i];
          if (defPrevious.Where == "album")
          {
            if (whereClause != "")
            {
              whereClause += " and ";
            }

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

            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;
    }
Ejemplo n.º 14
0
    private void DoScrobbleLookups()
    {
      PlayList currentPlaylist = playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_MUSIC);

      MusicDatabase dbs = MusicDatabase.Instance;
      Song current10SekSong = new Song();
      List<Song> scrobbledArtists = new List<Song>();

      ascrobbler.RemoveRequest(_lastRequest);
      switch (currentScrobbleMode)
      {
        case ScrobbleMode.Similar:
          if (_rememberStartTrack && _scrobbleStartTrack != null)
          {
            if (_totalScrobbledSongs > REINSERT_AFTER_THIS_MANY_SONGS)
            {
              _totalScrobbledSongs = 0;
              Song tmpArtist = new Song();
              tmpArtist = _scrobbleStartTrack;
              scrobbledArtists.Add(tmpArtist);
              break;
            }
          }
          string strFile = string.Empty;
          if (g_Player.Player.CurrentFile != null && g_Player.Player.CurrentFile != string.Empty && g_Player.IsMusic)
          {
            strFile = g_Player.Player.CurrentFile;

            bool songFound = dbs.GetSongByFileName(strFile, ref current10SekSong);
            if (songFound)
            {
              if (_scrobbleStartTrack == null || _scrobbleStartTrack.Artist == string.Empty)
              {
                _scrobbleStartTrack = current10SekSong.Clone();
              }

              try
              {
                UpdateSimilarArtists(current10SekSong.Artist);
                //scrobbledArtists = ascrobbler.getSimilarArtists(current10SekSong.ToURLArtistString(), _useSimilarRandom);
                return;
              }
              catch (Exception ex)
              {
                Log.Error("ScrobbleLookupThread: exception on lookup Similar - {0}", ex.Message);
              }
            }
          }
          break;

        case ScrobbleMode.Neighbours:
          //lock (ScrobbleLock)
          //{
          try
          {
            UpdateNeighboursArtists(true);
          }
          catch (Exception ex)
          {
            Log.Error("ScrobbleLookupThread: exception on lookup Neighbourhood - {0}", ex.Message);
          }
          //}
          break;

        case ScrobbleMode.Friends:
          //lock (ScrobbleLock)
          //{
          try
          {
            UpdateFriendsArtists(true);
          }
          catch (Exception ex)
          {
            Log.Error("ScrobbleLookupThread: exception on lookup - Friends {0}", ex.Message);
          }
          //}
          break;
        case ScrobbleMode.Random:
          try
          {
            switch (currentOfflineMode)
            {
              case offlineMode.random:
                UpdateRandomTracks();
                break;
              case offlineMode.timesplayed:
                UpdateUnheardTracks();
                break;
              case offlineMode.favorites:
                UpdateFavoriteTracks();
                break;
              default:
                UpdateRandomTracks();
                break;
            }
          }
          catch (Exception ex)
          {
            Log.Error("ScrobbleLookupThread: exception on lookup - Random {0}", ex.Message);
          }
          break;
      }

      OnScrobbleLookupsCompleted(scrobbledArtists);
    }
Ejemplo n.º 15
0
    private bool AddRandomSongToPlaylist(ref Song song)
    {
      //check duplication
      PlayList playlist = playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_MUSIC);
      for (int i = 0; i < playlist.Count; i++)
      {
        PlayListItem item = playlist[i];
        if (item.FileName == song.FileName)
        {
          return false;
        }
      }

      //add to playlist
      PlayListItem playlistItem = new PlayListItem();
      playlistItem.Type = PlayListItem.PlayListItemType.Audio;
      StringBuilder sb = new StringBuilder();

      playlistItem.FileName = song.FileName;
      sb.Append(song.Track);
      sb.Append(". ");
      sb.Append(song.Artist);
      sb.Append(" - ");
      sb.Append(song.Title);
      playlistItem.Description = sb.ToString();
      playlistItem.Duration = song.Duration;

      MusicTag tag = new MusicTag();
      tag = song.ToMusicTag();

      playlistItem.MusicTag = tag;

      playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_MUSIC).Add(playlistItem);
      return true;
    }
 public void OnUpdateArtistInfoCompleted(ArtistInfoRequest request, Song song)
 {
   if (request.Equals(_lastArtistRequest))
   {
     GUIGraphicsContext.form.Invoke(new ArtistInfoCompletedDelegate(DoUpdateArtistInfo), new object[] {request, song});
   }
   else
   {
     Log.Warn("NowPlaying.OnUpdateArtistInfoCompleted: unexpected response for request: {0}", request.Type);
   }
 }
    private void DoUpdateArtistInfo(ArtistInfoRequest request, Song song)
    {
      // artist tag can contain multiple artists and 
      // will be separated by " | " so split by | then trim
      // so we will add one thumb for artist
      String[] strArtists = CurrentTrackTag.Artist.Split('|');
      foreach (String strArtist in strArtists)
      {
        CurrentThumbFileName = Util.Utils.GetCoverArtName(Thumbs.MusicArtists,
                                                          Util.Utils.MakeFileName(strArtist.Trim()));
        if (CurrentThumbFileName.Length > 0)
        {
          // let us test if there is a larger cover art image
          string strLarge = Util.Utils.ConvertToLargeCoverArt(CurrentThumbFileName);
          if (Util.Utils.FileExistsInCache(strLarge))
          {
            CurrentThumbFileName = strLarge;
          }

          AddImageToImagePathContainer(CurrentThumbFileName);
          UpdateImagePathContainer();
        }
      }
    }
    private void AddInfoTrackToPlaylist(GUIListItem chosenTrack_)
    {
      try
      {
        MusicDatabase mdb = MusicDatabase.Instance;
        Song addSong = new Song();
        MusicTag tempTag = new MusicTag();
        tempTag = (MusicTag)chosenTrack_.MusicTag;

        if (mdb.GetSongByMusicTagInfo(tempTag.Artist, tempTag.Album, tempTag.Title, true, ref addSong))
        {
          if (AddSongToPlaylist(ref addSong))
          {
            Log.Info("GUIMusicPlayingNow: Song inserted: {0} - {1}", addSong.Artist, addSong.Title);
          }
        }
        else
        {
          Log.Info("GUIMusicPlayingNow: DB lookup for Artist: {0} Title: {1} unsuccessful", tempTag.Artist,
                   tempTag.Title);
        }
      }
      catch (Exception ex)
      {
        Log.Error("GUIMusicPlayingNow: DB lookup for Song failed - {0}", ex.Message);
      }
    }
Ejemplo n.º 19
0
        private void SetLevelForPlayback(string mediaType, string Level)
        {
            if ((previousLevel == "Play" || previousLevel == "Pause") && (Level == "Play") && (previousMediaType != mediaType))
            {
                previousLevel = "Stop";
            }
            string part2String;
            string part3String;
            string lengthString = "";
            string Genre = "";
            string CurrentFile = "";
            string SearchFile = "";
            if (!mediaType.Equals("Plugin"))
            {
                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");
                        lengthString = "Short.";
                    }
                    else
                    {
                        if (DebugMode) Logger.Debug("Length is Long");
                        lengthString = "Long.";
                    }
                }
                if (g_Player.IsDVD)
                {
                    if (DebugMode) Logger.Debug("Length is Long (Media is DVD)");
                    lengthString = "Long.";
                }

                if (Level == "Play")
                {
                    CurrentFile = g_Player.Player.CurrentFile;
                    SearchFile = CurrentFile;
                    if (g_Player.IsMusic)
                    {
                        Song song = new Song();
                        MusicDatabase musicDatabase = MusicDatabase.Instance;
                        musicDatabase.GetSongByFileName(SearchFile, ref song);
                        if (song != null)
                        {
                            Genre = song.Genre.ToString();
                        }
                    }
                    if (g_Player.IsVideo)
                    {
                        if (!SearchFile.StartsWith("http://localhost/")) // Online Video is not in DB so skip DB Search
                        {
                            try
                            {
                                if (DebugMode) Logger.Debug("Check to see if the video is a mounted disc.");
                                SearchFile = MountHelper.CheckMount(ref SearchFile);
                            }
                            catch
                            {
                                Logger.Warning("Daemontools not installed/configured");
                            }
                            if (DebugMode) Logger.Debug("Check to see if video is in MyVideos database.");
                            IMDBMovie movie = new IMDBMovie();
                            int movieID = VideoDatabase.GetMovieId(SearchFile);
                            VideoDatabase.GetMovieInfoById(movieID, ref movie);
                            if (movie.ID > 0)
                            {
                                if (DebugMode) Logger.Debug("Video is in MyVideos database.");
                                Genre = movie.Genre.ToString();
                            }
                            else // Movie not in MyVideo's DB
                            {
                                if (DebugMode) Logger.Debug("Video is not in MyVideos database.");
                                if (DebugMode) Logger.Debug("Check to see if video is in MovingPictures database.");
                                try
                                {
                                    if (Genre.Equals("")) Genre = MovingPicturesHelper.CheckDB(ref SearchFile);
                                }
                                catch
                                {
                                    Logger.Warning("Error while searching MovingPictures Database, probaly not installed");
                                }
                                if (DebugMode) Logger.Debug("Check to see if video is in TVSeries database.");
                                try
                                {
                                    if (Genre.Equals("")) Genre = TVSeriesHelper.CheckDB(SearchFile);
                                }
                                catch
                                {
                                    Logger.Warning("Error while searching TVSeries Database, probaly not installed");
                                }
                            }
                        }
                        else
                        {
                            if (DebugMode) Logger.Debug("Media is OnlineVideo");
                        }
                    }
                }
            }
            part2String = (egPart2.Equals("Type")) ? mediaType : Level;
            part3String = (egPart3.Equals("Type")) ? mediaType : Level;
            Genre = (Genre != "") ? "\"" + Genre + "\"" : "";
            SearchFile = (SearchFile != "") ? "\"" + SearchFile + "\"" : "";
            if (DebugMode) Logger.Debug("ACTION " + Level + " Media: " + mediaType);
            if (SearchFile != "") if (DebugMode) Logger.Debug("Filename: " + SearchFile);
            if (Genre != "") if (DebugMode) Logger.Debug("Genre: " + Genre);
            if (lengthString != "") if (DebugMode) Logger.Debug("Length: " + lengthString);
            if (Level.Equals("Play"))
            {
                if (egPayload)
                {
                    SendEvent(lengthString + part2String, new string[] {part3String, SearchFile, Genre});
                }
                else
                {
                    SendEvent(lengthString + part2String + "." + part3String, new string[] {SearchFile, Genre});
                }
            }
            else
            {
                if (egPayload)
                {
                    SendEvent(lengthString + part2String, new string[] { part3String});
                }
                else
                {
                    SendEvent(lengthString + part2String + "." + part3String, new string[] {});
                }
            }
            previousLevel = Level;
            previousMediaType = mediaType;
        }
Ejemplo n.º 20
0
 public static string GetFieldValue(Song song, string where)
 {
   if (where == "album")
   {
     return song.Album;
   }
   if (where == "artist")
   {
     return song.Artist;
   }
   if (where == "albumartist")
   {
     return song.AlbumArtist;
   }
   if (where == "title")
   {
     return song.Title;
   }
   if (where == "genre")
   {
     return song.Genre;
   }
   if (where == "composer")
   {
     return song.Composer;
   }
   if (where == "conductor")
   {
     return song.Conductor;
   }
   if (where == "year")
   {
     return song.Year.ToString();
   }
   if (where == "track")
   {
     return song.Track.ToString();
   }
   if (where == "timesplayed")
   {
     return song.TimesPlayed.ToString();
   }
   if (where == "rating")
   {
     return song.Rating.ToString();
   }
   if (where == "favorites")
   {
     if (song.Favorite)
     {
       return "1";
     }
     return "0";
   }
   if (where == "recently added")
   {
     return song.DateTimeModified.ToShortDateString();
   }
   if (where == "disc#")
   {
     return song.DiscId.ToString();
   }
   return "";
 }
Ejemplo n.º 21
0
    public bool IncrTop100CounterByFileName(string aFileName)
    {
      try
      {
        Song song = new Song();
        string strFileName = aFileName;
        DatabaseUtility.RemoveInvalidChars(ref strFileName);

        strSQL = String.Format("SELECT * from tracks WHERE strPath = '{0}'", strFileName);

        SQLiteResultSet results = MusicDbClient.Execute(strSQL);
        if (results.Rows.Count == 0)
        {
          return false;
        }

        int idSong = DatabaseUtility.GetAsInt(results, 0, "idTrack");
        int iTimesPlayed = DatabaseUtility.GetAsInt(results, 0, "iTimesPlayed");

        strSQL = String.Format("UPDATE tracks SET iTimesPlayed={0}, dateLastPlayed='{1}' where idTrack='{2}'", 
          ++iTimesPlayed, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), idSong);
        if (DirectExecute(strSQL).Rows.Count > 0)
        {
          Log.Debug("MusicDatabase: increased playcount for song {1} to {0}", Convert.ToString(iTimesPlayed), aFileName);
          return true;
        }
      }
      catch (Exception ex)
      {
        Log.Error("musicdatabase exception err:{0} stack:{1}", ex.Message, ex.StackTrace);
        Open();
      }

      return false;
    }
Ejemplo n.º 22
0
    /// <summary>
    /// Add or enque a song to the current playlist - call OnSongInserted() after this!!!
    /// </summary>
    /// <param name="song">the song to add</param>
    /// <returns>if the action was successful</returns>
    private bool AddSongToPlaylist(ref Song song)
    {
      PlayList playlist;
      if (PlaylistPlayer.CurrentPlaylistType == PlayListType.PLAYLIST_MUSIC_TEMP)
      {
        playlist = PlaylistPlayer.GetPlaylist(PlayListType.PLAYLIST_MUSIC_TEMP);
      }
      else
      {
        playlist = PlaylistPlayer.GetPlaylist(PlayListType.PLAYLIST_MUSIC);
      }
      
      if (playlist == null)
      {
        return false;
      }

      //add to playlist
      PlayListItem playlistItem = new PlayListItem();
      playlistItem.Type = PlayListItem.PlayListItemType.Audio;
      StringBuilder sb = new StringBuilder();

      playlistItem.FileName = song.FileName;
      sb.Append(song.Track);
      sb.Append(". ");
      sb.Append(song.Artist);
      sb.Append(" - ");
      sb.Append(song.Title);
      playlistItem.Description = sb.ToString();
      playlistItem.Duration = song.Duration;

      playlistItem.MusicTag = song.ToMusicTag();
      playlist.Add(playlistItem);

      OnSongInserted();
      return true;
    }
    private static void LoadSettings()
    {
      using (Settings xmlreader = new MPSettings())
      {
        username = xmlreader.GetValueAsString("audioscrobbler", "user", String.Empty);
        _recordToProfile = xmlreader.GetValueAsBool("audioscrobbler", "submitradiotracks", true);
        _artistPrefixes = xmlreader.GetValueAsString("musicfiles", "artistprefixes", "The, Les, Die");
        _artistsStripped = xmlreader.GetValueAsBool("musicfiles", "stripartistprefixes", false);
        _getLastfmCover = xmlreader.GetValueAsBool("musicmisc", "fetchlastfmcovers", true);
        _switchArtist = xmlreader.GetValueAsBool("musicmisc", "switchArtistOnLastFMSubmit", false);

        string tmpPass;

        tmpPass =
          MusicDatabase.Instance.AddScrobbleUserPassword(
            Convert.ToString(MusicDatabase.Instance.AddScrobbleUser(username)), String.Empty);
        _useDebugLog =
          (MusicDatabase.Instance.AddScrobbleUserSettings(
            Convert.ToString(MusicDatabase.Instance.AddScrobbleUser(username)), "iDebugLog", -1) == 1)
            ? true
            : false;

        if (tmpPass != string.Empty)
        {
          try
          {
            EncryptDecrypt Crypter = new EncryptDecrypt();
            password = Crypter.Decrypt(tmpPass);
          }
          catch (Exception ex)
          {
            Log.Error("Audioscrobbler: Password decryption failed {0}", ex.Message);
          }
        }
      }

      queue = new AudioscrobblerQueue(Config.GetFile(Config.Dir.Database, "LastFmCache-" + Username + ".xml"));

      queueLock = new Object();
      submitLock = new Object();

      lastHandshake = DateTime.MinValue;
      handshakeInterval = new TimeSpan(0, HANDSHAKE_INTERVAL, 0);
      handshakeRadioInterval = new TimeSpan(0, 5 * HANDSHAKE_INTERVAL, 0);
      // Radio is session based - no need to re-handshake soon
      lastConnectAttempt = DateTime.MinValue;
      minConnectWaitTime = new TimeSpan(0, 0, CONNECT_WAIT_TIME);
      _cookies = new CookieContainer();
      _radioStreamLocation = string.Empty;
      _radioSession = string.Empty;
      _subscriber = false;
      _currentSong = new Song();
      _currentPostSong = new Song();
    }
Ejemplo n.º 24
0
        private DBTrackInfo getMusicVideoTrack(string artist, string track)
        {
            if (track == null)
            {
                return(null);
            }

            logger.Debug("In Method: getMusicVideoTrack(Artist: " + artist + " Track: " + track + ")");

            MusicDatabase m_db = null;

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

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

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

            DBTrackInfo mv = new DBTrackInfo();

            mv.Track = trackInfo.Title;
            // mv.MdID = value;
            // Artist
            var _artist = string.Empty;

            if (!string.IsNullOrEmpty(trackInfo.AlbumArtist))
            {
                _artist = trackInfo.AlbumArtist;
            }
            else if (!string.IsNullOrEmpty(trackInfo.Artist))
            {
                _artist = trackInfo.Artist;
            }
            if (!string.IsNullOrEmpty(_artist))
            {
                DBArtistInfo d4 = new DBArtistInfo();
                setMusicVideoArtist(ref d4, _artist, null);
                mv.ArtistInfo.Add(d4);
            }
            // Album
            if (!string.IsNullOrEmpty(trackInfo.Album))
            {
                DBAlbumInfo d4 = new DBAlbumInfo();
                setMusicVideoAlbum(ref d4, _artist, trackInfo.Album, null);
                // Have we actually got a valid album?
                if (d4.Album.Trim() != string.Empty)
                {
                    mv.AlbumInfo.Add(d4);
                }
            }
            // Tag
            char[]   delimiters = new char[] { ',' };
            string[] tags       = trackInfo.Genre.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
            foreach (string tag in tags)
            {
                mv.Tag.Add(tag.Trim());
            }
            // mv.bioSummary = mvCentralUtils.StripHTML(cdataSection.Value);
            // mv.bioContent = mvCentralUtils.StripHTML(cdataSection.Value);

            if (mv.ArtistInfo.Count == 0)
            {
                return(null);
            }

            return(mv);
        }
Ejemplo n.º 25
0
 private void ClearScrobbleStartTrack()
 {
   if (_rememberStartTrack && _scrobbleStartTrack != null)
   {
     _scrobbleStartTrack = null;
   }
 }
Ejemplo n.º 26
0
 public void Select(Song song)
 {
   FilterDefinition definition = (FilterDefinition)currentView.Filters[CurrentLevel];
   definition.SelectedValue = GetFieldValue(song, definition.Where).ToString();
   if (currentLevel < currentView.Filters.Count)
   {
     currentLevel++;
   }
   currentSong = song;
 }
Ejemplo n.º 27
0
    private bool ScrobbleSimilarArtists(string Artist_)
    {
      MusicDatabase dbs = MusicDatabase.Instance;
      PlayList list = playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_MUSIC);
      List<Song> songList = new List<Song>();
      double avgPlayCount = 0;
      int songsAdded = 0;
      int j = 0;

      dbs.GetSongsByArtist(Artist_, ref songList);

      //      Log.Debug("GUIMusicPlaylist: ScrobbleSimilarArtists found {0} songs allowed to add", Convert.ToString(songList.Count));

      // exit if not enough songs were found
      if (songList.Count < _maxScrobbledSongsPerArtist)
      {
        return false;
      }

      // lookup how many times this artist's songs were played
      avgPlayCount = dbs.GetAveragePlayCountForArtist(Artist_);

      switch (_preferCountForTracks)
      {
        case 0:
          // delete all heard songs
          for (int s = 0; s < songList.Count; s++)
          {
            if (songList[s].TimesPlayed > 0)
            {
              songList.Remove(songList[s]);
              s--;
            }
          }
          break;
        case 1:
          // delete all well known songs
          if (avgPlayCount < 0.5)
          {
            goto case 0;
          }
          else
          {
            for (int s = 0; s < songList.Count; s++)
            {
              // song was played more often than average
              if (songList[s].TimesPlayed > avgPlayCount)
              {
                // give 1x played songs a chance...
                if (songList[s].TimesPlayed > 1)
                {
                  songList.Remove(songList[s]);
                }
              }
            }
          }
          break;
        case 2:
          break;
        case 3:
          // only well known songs
          for (int s = 0; s < songList.Count; s++)
          {
            // delete all rarely heard songs
            if (songList[s].TimesPlayed < avgPlayCount)
            {
              songList.Remove(songList[s]);
              s--;
            }
          }

          // get new average playcount of remaining files
          if (songList.Count > 0)
          {
            int avgOfKnownSongs = 0;
            foreach (Song favSong in songList)
            {
              avgOfKnownSongs += favSong.TimesPlayed;
            }
            avgOfKnownSongs /= songList.Count;
            avgOfKnownSongs = avgOfKnownSongs > 0 ? avgOfKnownSongs : 2;

            int songListCount = songList.Count;
            for (int s = 0; s < songListCount; s++)
            {
              if (songList[s].TimesPlayed < avgOfKnownSongs)
              {
                songList.Remove(songList[s]);
                songListCount = songList.Count;
                s--;
              }
            }
          }
          //songList.Sort(CompareSongsByTimesPlayed);
          break;
      }

      // check if there are still enough songs
      if (songList.Count < _maxScrobbledSongsPerArtist)
      {
        return false;
      }

      PseudoRandomNumberGenerator rand = new PseudoRandomNumberGenerator();

      int randomPosition;

      while (songsAdded < _maxScrobbledSongsPerArtist)
      {
        if (_preferCountForTracks == 3)
        {
          randomPosition = rand.Next(0, songList.Count / 2);
        }
        else
        {
          randomPosition = rand.Next(0, songList.Count - 1);
        }

        Song refSong = new Song();

        refSong = songList[randomPosition];

        //        Log.Debug("GUIMusicPlaylist: ScrobbleSimilarArtists tries to add this song - {0}", refSong.ToShortString());

        if (AddRandomSongToPlaylist(ref refSong))
        {
          songsAdded++;
          _totalScrobbledSongs++;
        }

        j++;

        if (j > songList.Count * 5)
        {
          break;
        }
      }
      // _maxScrobbledSongsPerArtist are inserted
      return true;
    }
Ejemplo n.º 28
0
    private void ShowSong(g_Player.MediaType type, string filename)
    {
      try
      {
        // Show song only when we are on MyPictures Plugin or slideshow when playing/change music track
        string activeWindowName;
        GUIWindow.Window activeWindow;
        activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
        activeWindow = (GUIWindow.Window) Enum.Parse(typeof (GUIWindow.Window), activeWindowName);
        if (activeWindow == GUIWindow.Window.WINDOW_SLIDESHOW || activeWindow == GUIWindow.Window.WINDOW_PICTURES)
          if (g_Player.IsMusic)
          {
            if (mDB == null)
            {
              mDB = MusicDatabase.Instance;
            }
            if (!resumeSong)
            {
              GUIDialogNotify dlg = (GUIDialogNotify) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_NOTIFY);
              if (dlg == null)
              {
                return;
              }

              //get albumart
              string albumart = g_Player.CurrentFile;
              int e = albumart.LastIndexOf(@"\") + 1;
              if (!String.IsNullOrEmpty(albumart))
              {
                albumart = albumart.Remove(e);
              }
              if (_slideList.Count > 0 && _slideList[_currentSlideIndex].Contains(albumart))
              {
                albumart = string.Empty;
              }
              else
              {
                albumart = Util.Utils.GetFolderThumbForDir(albumart);
                if (!Util.Utils.FileExistsInCache(albumart))
                {
                  albumart = string.Empty;
                }
              }
              // get Song-info

              // hwahrmann 2006-11-22 Using the Tagreader caused a COM exception in Win Media SDK, when reading WMA files
              // Accessing the Music Database instead of using the Tagreader.
              //MediaPortal.TagReader.MusicTag tag = MediaPortal.TagReader.TagReader.ReadTag(g_Player.CurrentFile);
              Song song = new Song();
              MusicTag currentSong = new MusicTag();

              // If we don't have a tag in the db, we use the filename without the extension as song.title
              if (!mDB.GetSongByFileName(g_Player.CurrentFile, ref song))
              {
                try
                {
                  // try Tagreader method to parse information
                  var pl = PlayListPlayer.SingletonPlayer.GetPlaylist(PlayListPlayer.SingletonPlayer.CurrentPlaylistType);
                  var plI = pl.First(plItem => plItem.FileName == filename);
                  if (plI != null || plI.MusicTag != null)
                  {
                    currentSong = (MusicTag) plI.MusicTag;
                  }
                }
                catch (Exception)
                {
                  // Catch the COM execption but continue code with Music Database instead.
                }
              }

              // Show Dialog
              dlg.Reset();
              dlg.Dispose();
              dlg.SetImage(albumart);
              dlg.SetHeading(4540);
              if (currentSong == null || string.IsNullOrEmpty(currentSong.Title) ||
                  (string.IsNullOrEmpty(currentSong.Artist) && string.IsNullOrEmpty(currentSong.AlbumArtist)))
              {
                song.Title = Path.GetFileNameWithoutExtension(g_Player.CurrentFile);
                dlg.SetText(song.Title + "\n" + song.Artist + "\n" + song.Album);
              }
              else
              {
                dlg.SetText(currentSong.Title + "\n" + currentSong.Artist + "\n" + currentSong.Album);
              }
              dlg.TimeOut = 5;
              dlg.DoModal(GUIWindowManager.ActiveWindow);
            }
            resumeSong = false;
          }
      }
      catch (Exception e)
      {
        Log.Debug("GUISlideShow.OnPlayBackStarted", e.Message);
      }
    }
    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.ToLowerInvariant().CompareTo(song.Artist.ToLowerInvariant()) != 0)
          {
            difArtistCount++;
          }
        }

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

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

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

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

      return IsCompilationAlbum;
    }
Ejemplo n.º 30
0
    protected void LoadPlayList(string strPlayList, bool startPlayback, bool isAsynch, bool defaultLoad)
    {
      IPlayListIO loader = PlayListFactory.CreateIO(strPlayList);
      if (loader == null)
      {
        return;
      }

      PlayList playlist = new PlayList();

      if (!Util.Utils.FileExistsInCache(strPlayList))
      {
        Log.Info("Playlist: Skipping non-existing Playlist file: {0}", strPlayList);
        return;
      }

      if (!loader.Load(playlist, strPlayList))
      {
        if (isAsynch && defaultLoad) // we might not be in GUI yet! we have asynch and default load because we might want to use asynch loading from gui button too, later!
          throw new Exception(string.Format("Unable to load Playlist file: {0}", strPlayList)); // exception is handled in backgroundworker
        else
          TellUserSomethingWentWrong();
        return;
      }

      if (_autoShuffleOnLoad)
      {
        playlist.Shuffle();
      }

      playlistPlayer.CurrentPlaylistName = Path.GetFileNameWithoutExtension(strPlayList);
      if (playlist.Count == 1 && startPlayback)
      {
        Log.Info("GUIMusic:Play: play single playlist item - {0}", playlist[0].FileName);
        // Default to type Music, when a playlist has been selected from My Music
        g_Player.Play(playlist[0].FileName, g_Player.MediaType.Music);
        return;
      }

      if (null != bw && isAsynch && bw.CancellationPending)
        return;

      // clear current playlist
      //playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_MUSIC).Clear();

      Song song = new Song();
      PlayList newPlaylist = new PlayList();

      // add each item of the playlist to the playlistplayer
      for (int i = 0; i < playlist.Count; ++i)
      {
        if (null != bw && isAsynch && bw.CancellationPending)
          return;

        PlayListItem playListItem = playlist[i];
        m_database.GetSongByFileName(playListItem.FileName, ref song);
        MusicTag tag = new MusicTag();
        tag = song.ToMusicTag();
        playListItem.MusicTag = tag;
        if (Util.Utils.FileExistsInCache(playListItem.FileName) ||
            playListItem.Type == PlayListItem.PlayListItemType.AudioStream)
        {
          newPlaylist.Add(playListItem);
        }
        else
        {
          Log.Info("Playlist: File {0} no longer exists. Skipping item.", playListItem.FileName);
        }
      }

      if (null != bw && isAsynch && bw.CancellationPending)
        return;

      ReplacePlaylist(newPlaylist);

      if (startPlayback)
        StartPlayingPlaylist();
    }
Ejemplo n.º 31
0
    protected override void OnShowContextMenu()
    {
      GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_MENU);
      MusicDatabase dbs;

      if (dlg == null)
      {
        return;
      }

      dlg.Reset();
      dlg.SetHeading(498); // Menu

      dlg.AddLocalizedString(930); //Add to favorites

      if (CurrentTrackTag.Album != null)
      {
        dlg.AddLocalizedString(33041);
      }

      if (PluginManager.IsPluginNameEnabled2("LastFMScrobbler"))
      {
        dlg.AddLocalizedString(34010); //last.fm love
        dlg.AddLocalizedString(34011); //last.fm ban
      }

      dlg.DoModal(GetID);

      if (dlg.SelectedId == -1)
      {
        return;
      }

      switch (dlg.SelectedId)
      {
        case 928: // Find Coverart
          if (_MusicWindow != null)
          {
            string albumFolderPath = Path.GetDirectoryName(CurrentTrackFileName);

            _MusicWindow.FindCoverArt(false, CurrentTrackTag.Artist, CurrentTrackTag.Album, albumFolderPath,
                                      CurrentTrackTag, -1);
            CurrentThumbFileName = GUIMusicBaseWindow.GetCoverArt(false, CurrentTrackFileName, CurrentTrackTag);

            if (CurrentThumbFileName.Length > 0)
            {
              // let us test if there is a larger cover art image
              string strLarge = Util.Utils.ConvertToLargeCoverArt(CurrentThumbFileName);
              if (Util.Utils.FileExistsInCache(strLarge))
              {
                CurrentThumbFileName = strLarge;
              }
              AddImageToImagePathContainer(CurrentThumbFileName);

              UpdateImagePathContainer();
            }
          }
          break;

        case 4521: // Show Album Info
          if (_MusicWindow != null)
          {
            string albumFolderPath = Path.GetDirectoryName(CurrentTrackFileName);
            if (_MusicWindow != null)
            {
              _MusicWindow.ShowAlbumInfo(GetID, CurrentTrackTag.Artist, CurrentTrackTag.Album);
            }
          }
          break;

        case 930: // add to favorites
          dbs = MusicDatabase.Instance;
          Song currentSong = new Song();
          string strFile = g_Player.Player.CurrentFile;

          bool songFound = dbs.GetSongByFileName(strFile, ref currentSong);
          if (songFound)
          {
            if (currentSong == null)
            {
              return;
            }
            if (currentSong.Id < 0)
            {
              return;
            }
            currentSong.Favorite = true;
            dbs.SetFavorite(currentSong);
          }
          break;

        case 33041: //Play this album
          try
          {
            if (CurrentTrackTag != null)
            {
              dbs = MusicDatabase.Instance;
              ArrayList albumSongs = new ArrayList();
              String strAlbum = CurrentTrackTag.Album;

              bool albumSongsFound = dbs.GetSongsByAlbum(strAlbum, ref albumSongs);

              if (albumSongsFound)
              {
                for (int i = albumSongs.Count - 1; i >= 0; i--)
                {
                  Song song = (Song)albumSongs[i];
                  if (song.Title != CurrentTrackTag.Title && song.Artist == CurrentTrackTag.Artist)
                  {
                    AddSongToPlaylist(ref song);
                  }
                }
                OnSongInserted();
              }
            }
          }
          catch (Exception ex)
          {
            Log.Error("GUIMusicPlayingNow: error while adding album tracks for {0} - {1}", CurrentTrackTag.Album,
                      ex.Message);
          }
          break;
      }
    }
Ejemplo n.º 32
0
    public Song Clone()
    {
      Song newsong = new Song();
      newsong.Id = Id;
      newsong.Album = Album;
      newsong.Artist = Artist;
      newsong.AlbumArtist = AlbumArtist;
      newsong.Duration = Duration;
      newsong.FileName = FileName;
      newsong.Genre = Genre;
      newsong.Composer = Composer;
      newsong.Conductor = Conductor;
      newsong.TimesPlayed = TimesPlayed;
      newsong.Title = Title;
      newsong.Track = Track;
      newsong.TrackTotal = TrackTotal;
      newsong.Year = Year;
      newsong.Rating = Rating;
      newsong.Favorite = Favorite;
      newsong.DateTimeModified = DateTimeModified;
      newsong.DateTimePlayed = DateTimePlayed;
      newsong.AudioScrobblerStatus = AudioScrobblerStatus;
      newsong.URL = URL;
      newsong.WebImage = WebImage;
      newsong.LastFMMatch = LastFMMatch;
      newsong.ResumeAt = ResumeAt;
      newsong.DiscId = DiscId;
      newsong.DiscTotal = DiscTotal;
      newsong.Lyrics = Lyrics;
      newsong.Source = Source;
      newsong.AuthToken = AuthToken;
      newsong.AudioscrobblerAction = AudioscrobblerAction;
      newsong.Comment = Comment;
      newsong.FileType = FileType;
      newsong.Codec = Codec;
      newsong.BitRateMode = BitRateMode;
      newsong.BPM = BPM;
      newsong.Channels = Channels;
      newsong.SampleRate = SampleRate;

      return newsong;
    }