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!");
    }
    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;
    }
    public override bool OnMessage(GUIMessage message)
    {
      switch (message.Message)
      {
        case GUIMessage.MessageType.GUI_MSG_WINDOW_INIT:
          _showOverlayFlag = GUIGraphicsContext.Overlay;
          GUIGraphicsContext.Overlay = false;
          base.OnMessage(message);

          if (_returnedFromVideoPlayback)
          {
            GUIWindowManager.ShowPreviousWindow();
          }
          else
          {
            _update = false;
            _lastSlideShown = -1;
            _currentSlideIndex = -1;
          }
          // LoadSettings();
          return true;

        case GUIMessage.MessageType.GUI_MSG_WINDOW_DEINIT:
          if (!_returnedFromVideoPlayback && !_loadVideoPlayback)
            Reset();
          GUIGraphicsContext.Overlay = _showOverlayFlag;
          break;

        case GUIMessage.MessageType.GUI_MSG_PLAYBACK_STARTED:
          if (mDB == null)
          {
            mDB = MusicDatabase.Instance;
          }
          ShowSong();
          break;
      }
      return base.OnMessage(message);
    }
 /// <summary>
 /// Handle event fired by MP player.  Something has started playing so check if it is music then
 /// show song track on MyPictures Plugin or slideshow
 /// </summary>
 /// <param name="type">MediaType of item that has started</param>
 /// <param name="filename">filename of item that has started</param>
 private void OnPlayBackStarted(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)
         {
           ShowSong(filename);
         }
         resumeSong = false;
       }
   }
   catch (Exception e)
   {
     Log.Debug("GUISlideShow.OnPlayBackStarted", e.Message);
   }
 }
    public override bool OnMessage(GUIMessage message)
    {
      switch (message.Message)
      {
        case GUIMessage.MessageType.GUI_MSG_WINDOW_INIT:
          _showOverlayFlag = GUIGraphicsContext.Overlay;
          GUIGraphicsContext.Overlay = false;
          base.OnMessage(message);

          if (_returnedFromVideoPlayback)
          {
            if (GUIPictureSlideShow.SlideDirection == 1)
            {
              ShowNext();
            }
            //Backward
            if (GUIPictureSlideShow.SlideDirection == -1)
            {
              ShowPrevious();
            }
            if (GUIPictureSlideShow.SlideDirection == 0)
            {
              // Get folder path for recursive selectedItemIndex.
              if (_slideList.Count != 0)
              {
                _folderCurrentItem = _slideList[_currentSlideIndex];
              }
              GUIWindowManager.ShowPreviousWindow();
            }
          }
          else
          {
            _update = false;
            _lastSlideShown = -1;
            _currentSlideIndex = -1;
          }
          // LoadSettings();
          return true;

        case GUIMessage.MessageType.GUI_MSG_WINDOW_DEINIT:
          if (!_returnedFromVideoPlayback && !_loadVideoPlayback)
          {
            // Get folder path for recursive selectedItemIndex.
            if (_slideList.Count != 0)
            {
              _folderCurrentItem = _slideList[_currentSlideIndex];
            }
            Reset();
          }
          GUIGraphicsContext.Overlay = _showOverlayFlag;
          break;

        case GUIMessage.MessageType.GUI_MSG_PLAYBACK_STARTED:
          if (g_Player.IsMusic)
          {
            if (mDB == null)
            {
              mDB = MusicDatabase.Instance;
            }
            if (!resumeSong)
            {
              ShowSong();
            }
            resumeSong = false;
          }
          break;
      }
      return base.OnMessage(message);
    }
    protected override void OnPageLoad()
    {
      // Update current playing (might have changed when other window was running)
      PlayListItem currentItem = playlistPlayer.GetCurrentItem();
      if (currentItem != null)
      {
        _currentPlaying = currentItem.FileName;
      }

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

      if (handler == null)
      {
        handler = new MusicViewHandler();
      }

      LoadSettings();

      if (btnSortBy != null)
      {
        btnSortBy.SortChanged += new SortEventHandler(SortChanged);
      }

      base.OnPageLoad();
    }
    public GUIMusicBaseWindow()
    {
      if (m_database == null)
      {
        m_database = MusicDatabase.Instance;
      }

      playlistPlayer = PlayListPlayer.SingletonPlayer;

      playlistPlayer.PlaylistChanged += new PlayListPlayer.PlaylistChangedEventHandler(playlistPlayer_PlaylistChanged); 

      using (Profile.Settings xmlreader = new Profile.MPSettings())
      {
        string playNowJumpTo = xmlreader.GetValueAsString("music", "playnowjumpto", "none");

        switch (playNowJumpTo)
        {
          case "none":
            PlayNowJumpTo = PlayNowJumpToType.None;
            break;

          case "nowPlayingAlways":
            PlayNowJumpTo = PlayNowJumpToType.NowPlayingAlways;
            break;

          case "nowPlayingMultipleItems":
            PlayNowJumpTo = PlayNowJumpToType.NowPlayingMultipleItems;
            break;

          case "currentPlaylistAlways":
            PlayNowJumpTo = PlayNowJumpToType.CurrentPlaylistAlways;
            break;

          case "currentPlaylistMultipleItems":
            PlayNowJumpTo = PlayNowJumpToType.CurrentPlaylistMultipleItems;
            break;

          case "fullscreenAlways":
            PlayNowJumpTo = PlayNowJumpToType.FullscreenIfVizEnabledAlways;
            break;

          case "fullscreenMultipleItems":
            PlayNowJumpTo = PlayNowJumpToType.FullscreenIfVizEnabledMultipleItems;
            break;

          default:
            PlayNowJumpTo = PlayNowJumpToType.None;
            break;
        }

        _autoShuffleOnLoad = xmlreader.GetValueAsBool("musicfiles", "autoshuffle", false);
      }

      UsingInternalMusicPlayer = BassMusicPlayer.IsDefaultMusicPlayer;
    }
    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);
      }
    }
    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) {}

      database = MusicDatabase.Instance;
    }
        public override bool Init()
        {
            mdb = MusicDatabase.Instance;
            m_strDirectory = System.IO.Directory.GetCurrentDirectory();

            using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
            {
                _enableScrobbling = xmlreader.GetValueAsBool("plugins", "Audioscrobbler", false);
                _currentScrobbleUser = xmlreader.GetValueAsString("audioscrobbler", "user", "Username");
                _useSimilarRandom = xmlreader.GetValueAsBool("audioscrobbler", "usesimilarrandom", true);
                _announceNowPlaying = xmlreader.GetValueAsBool("audioscrobbler", "EnableNowPlaying", true);

            }

            _scrobbleUsers = mdb.GetAllScrobbleUsers();
            // no users in database
            if (_scrobbleUsers.Count > 0 && _enableScrobbling)
                LoadScrobbleUserSettings();

            ascrobbler = AudioscrobblerUtils.Instance;
            //      ScrobbleLock = new object();
            //added by Sam
            GUIWindowManager.Receivers += new SendMessageHandler(this.OnThreadMessage);
            GUIWindowManager.OnNewAction += new OnActionHandler(this.OnNewAction);
            g_Player.PlayBackStopped += new g_Player.StoppedHandler(g_Player_PlayBackStopped);
            Youtube2MP.player.PlayBegin += new YoutubePlaylistPlayer.EventHandler(player_PlayBegin);

            return Load(GUIGraphicsContext.Skin + @"\youtubeplaylist.xml");
        }
    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);
    }
        public void InitDB(string type)
        {
            logger.Debug("initDB: Start: "+type);
            try
            {
                IsScraping = false;
                var DBFile = Config.GetFile((Config.Dir) 4, dbFilename);
                var flag = false;

                flag = (!File.Exists(DBFile));

                dbClient = new SQLiteClient(DBFile);
                dbClient.Execute("PRAGMA synchronous=OFF;");
                dbClient.Execute("PRAGMA encoding='UTF-8';");
                dbClient.Execute("PRAGMA cache_size=5000;");
                dbClient.Execute("PRAGMA temp_store = MEMORY;");

                if (flag)
                  CreateDBMain() ;

                logger.Info("Successfully Opened Database: "+dbFilename);

                UpgradeDBMain(type);

                if (type.Equals("upgrade", StringComparison.CurrentCulture))
                  return;

                if (HtAnyFanart == null)
                  HtAnyFanart = new Hashtable();

                try
                {
                  m_db = MusicDatabase.Instance;
                  logger.Debug("Successfully Opened Database: "+m_db.DatabaseName);
                } catch { }
                try
                {
                  // v_db = VideoDatabase.Instance;
                  logger.Debug("Successfully Opened Database: "+VideoDatabase.DatabaseName);
                } catch { }

            }
            catch (Exception ex)
            {
                logger.Error("initDB: Could Not Open Database: "+dbFilename+". " + ex);
                dbClient = null;
            }
        }
 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);
     }
   }
 }