Example #1
0
        /// <summary>
        /// Check if the My Devices folder exists, if not create it.
        /// </summary>
        private void CreateMyDevicesFolder()
        {
            try
            {
                foreach (IITPlaylist p in itunes.LibrarySource.Playlists)
                {
                    if (p.Name == "My Devices" && p.Kind == ITPlaylistKind.ITPlaylistKindUser)
                    {
                        folderMyDevices = (IITUserPlaylist)p;
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                l.Error(ex);
            }

            try
            {
                object src = itunes.LibrarySource;
                folderMyDevices = (IITUserPlaylist)itunes.CreateFolderInSource("My Devices", ref src);
            }
            catch (COMException ex)
            {
                l.Error(ex);

                MessageBox.Show(this, "Unable to create 'My Devices' folder. This may "
                                + "be due to iTunes being busy with an other operation. If this error "
                                + "continues to occur, please turn the option off in the Preferences dialog.\n\n(" + ex.Message + ")",
                                "Failed to create My Devices folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private PlaylistCollection SearchForParentNode(IITUserPlaylist playlist)
        {
            // if the playlist doesn't have a parent return null to signal that.
            if (playlist.get_Parent() == null)
            {
                return(null);
            }

            // if the current object (this) is the parent node -> return
            if (Equals(playlist.get_Parent(), this))
            {
                return(this);
            }

            // perform the search one level deeper
            foreach (var playlistCollectionNode in PlaylistNodes)
            {
                var parentNode = playlistCollectionNode.SearchForParentNode(playlist);

                // did we find the parent node?
                if (parentNode != null)
                {
                    return(parentNode);
                }
            }
            // we've searched all child nodes and could still not find the parent node.
            // if the current node doesn't have a parent anymore, we've reached the end and won't continue our search.
            //if (_parent == null) return null;
            //return _parent.SearchForParentNode(playlist);
            return(null);
        }
Example #3
0
        private static IITUserPlaylist findPlaylist(IITPlaylistCollection pl, IITUserPlaylist playlist)
        {
            playlist = null;

            int count = 0;

            while (playlist == null && ++count < 10)
            {
                foreach (IITPlaylist p in pl)
                {
                    if (p.Name == playlistName)
                    {
                        playlist = p as IITUserPlaylist;
                        if (playlist != null)
                        {
                            if (playlist.Kind != ITPlaylistKind.ITPlaylistKindUser ||
                                playlist.Smart ||
                                (playlist.SpecialKind != ITUserPlaylistSpecialKind.ITUserPlaylistSpecialKindMusic &&
                                 playlist.SpecialKind != ITUserPlaylistSpecialKind.ITUserPlaylistSpecialKindNone))
                            {
                                playlistName = adjust(playlistName);
                                playlist     = null;
                            }
                        }
                        break;
                    }
                }
            }
            return(playlist);
        }
Example #4
0
 public static void DeleteAllTracks(this IITUserPlaylist playlist)
 {
     while (playlist.Tracks.Count > 0)
     {
         var track = playlist.Tracks[1];
         track.Delete();
         Marshal.ReleaseComObject(track);
     }
 }
Example #5
0
        public static void AddRangeTracks(this IITUserPlaylist self, params IITTrack[] tracks)
        {
            ArgumentValidator.Validate(self, tracks);

            foreach (IITTrack track in tracks)
            {
                self.AddTrack(track);
            }
        }
Example #6
0
        public void AddToPlaylist(IITUserPlaylist pl, params SamTrack[] sortable_tracks)
        {
            Array.Sort(sortable_tracks);

            foreach (var t in sortable_tracks)
            {
                object track = t._Track;
                pl.AddTrack(ref track);
            }
        }
Example #7
0
        public static void AddTrackToPlaylistByPersistentId(this iTunesApp iTunes, IITUserPlaylist playlist, long id)
        {
            var track = iTunes.GetTrackByPersistentId(id);

            if (track != null)
            {
                playlist.AddTrack(track);
                Marshal.ReleaseComObject(track);
            }
        }
Example #8
0
        public void DumpPlaylists()
        {
            iTunesAppClass        itunes    = new iTunesAppClass();
            IITPlaylistCollection playlists = itunes.LibrarySource.Playlists;

            foreach (IITPlaylist playlist in playlists)
            {
                if (playlist.Kind == ITPlaylistKind.ITPlaylistKindUser)
                {
                    IITUserPlaylist ulist = (IITUserPlaylist)playlist;

                    Console.WriteLine(String.Format(
                                          "[{0}:{1}] {2} - Kind:{3}, Visible:{4}, Smart:{5}, {6}",
                                          ulist.Index, ulist.playlistID,
                                          ulist.Name, ulist.Kind.ToString(), ulist.Visible,
                                          ulist.Smart, ulist.SpecialKind
                                          ));
                }
                else
                {
                    Console.WriteLine(String.Format(
                                          "[{0}:{1}] {2} - Kind:{3}, Visible:{4}",
                                          playlist.Index, playlist.playlistID,
                                          playlist.Name, playlist.Kind.ToString(), playlist.Visible
                                          ));
                }
            }

            Console.WriteLine();
            Console.WriteLine("Filtered:");
            Console.WriteLine();

            foreach (IITPlaylist playlist in playlists)
            {
                if ((playlist.Kind != ITPlaylistKind.ITPlaylistKindUser) ||
                    playlist.Name.Equals("Genius"))
                {
                    continue;
                }

                IITUserPlaylist ulist = (IITUserPlaylist)playlist;

                if ((ulist.SpecialKind == ITUserPlaylistSpecialKind.ITUserPlaylistSpecialKindNone) ||
                    (ulist.SpecialKind == ITUserPlaylistSpecialKind.ITUserPlaylistSpecialKindPurchases) ||
                    (ulist.SpecialKind == ITUserPlaylistSpecialKind.ITUserPlaylistSpecialKindFolder))
                {
                    Console.WriteLine(ulist.Name);
                }
            }

            itunes.Quit();
            Marshal.ReleaseComObject(itunes);
            itunes = null;
        }
Example #9
0
        public static iTunesLib.IITUserPlaylist GetiTunesPlaylist(iTunesLib.IiTunes iitApp, string strPlaylist)
        {
            IITUserPlaylist       returnPlaylist = null;
            IITPlaylistCollection playlists      = iitApp.LibrarySource.Playlists;
            int numPlaylists = playlists.Count;

            Object podcastfolder = null;

            // find the Dopppler Podcasts folder in iTunes
            foreach (IITPlaylist folder in iitApp.LibrarySource.Playlists)
            {
                if (folder.Name == "Doppler Podcasts")
                {
                    podcastfolder = folder;
                    break;
                }
            }
            if (podcastfolder == null)
            {
                podcastfolder = iitApp.CreateFolder("Doppler Podcasts");
            }


            while (numPlaylists != 0)
            {
                Object      currPlaylist = playlists[numPlaylists];
                IITPlaylist tempPlaylist = (IITPlaylist)currPlaylist;
                // is this a user playlist?
                if (tempPlaylist.Kind == ITPlaylistKind.ITPlaylistKindUser)
                {
                    IITUserPlaylist thisPlaylist = (IITUserPlaylist)currPlaylist;

                    if (thisPlaylist.Name == strPlaylist)
                    {
                        returnPlaylist = thisPlaylist;
                        break;
                    }
                }
                numPlaylists--;
            }
            if (returnPlaylist == null)
            {
                returnPlaylist = (IITUserPlaylist)iitApp.CreatePlaylist(strPlaylist);
                returnPlaylist.set_Parent(ref podcastfolder);
                //returnPlaylist = GetiTunesPlaylist(iitApp, strPlaylist);
            }

            return(returnPlaylist);
        }
        private static bool Equals(IITUserPlaylist x, PlaylistCollection y)
        {
            if (x == null && y == null || x == null && y.Name == "root")
            {
                return(true);
            }
            if (x == null)
            {
                return(false);
            }
            if (y == null)
            {
                return(false);
            }

            return(x.Name.Equals(y.Name) && Equals(x.get_Parent(), y._parent));
        }
Example #11
0
        /// <summary>
        /// Adds the downloaded item to a playlist in iTunes.
        /// </summary>
        /// <remarks>The title of the playlist is the name of the feed in RSS Bandit.</remarks>
        /// <param name="podcast"></param>
        private void AddPodcastToITunes(DownloadItem podcast)
        {
            try
            {
                if (!IsITunesFile(Path.GetExtension(podcast.File.LocalName)))
                {
                    return;
                }

                string     playlistName = Preferences.SinglePlaylistName;
                FeedSource source       = guiMain.FeedSourceOf(podcast.OwnerFeedId);

                if (!Preferences.SinglePodcastPlaylist && source != null)
                {
                    playlistName = source.GetFeeds()[podcast.OwnerFeedId].title;
                }

                // initialize iTunes application connection
                iTunesApp itunes = new iTunesApp();

                //get a handle to the playlist if it exists or create it if it doesn't
                IITUserPlaylist podcastPlaylist = null;

                foreach (IITPlaylist pl in itunes.LibrarySource.Playlists)
                {
                    if (pl.Name.Equals(playlistName))
                    {
                        podcastPlaylist = (IITUserPlaylist)pl;
                    }
                }

                if (podcastPlaylist == null)
                {
                    podcastPlaylist = (IITUserPlaylist)itunes.CreatePlaylist(playlistName);
                }

                //add podcast to our playlist for this feed
                podcastPlaylist.AddFile(Path.Combine(podcast.TargetFolder, podcast.File.LocalName));
            }
            catch (Exception e)
            {
                _log.Error("The following error occured in AddPodcastToITunes(): ", e);
            }
        }
        public static IITUserPlaylist ShufflePlayList(IITUserPlaylist playlist)
        {
            IITTrackCollection tracks = playlist.Tracks;
            Random             rndm   = new Random((int)DateTime.Now.Ticks);
            int nTracks = tracks.Count;

            // Generate shuffled track order
            int[] shuffle = new int[nTracks];
            for (int n = 0; n < nTracks; n++)
            {
                shuffle[n] = n + 1;
            }
            for (int n = 0; n < nTracks; n++)
            {
                int i1 = rndm.Next(nTracks);
                int i2 = rndm.Next(nTracks);
                int t  = shuffle[i1];
                shuffle[i1] = shuffle[i2];
                shuffle[i2] = t;
            }

            // Create temporary playlist
            string          plName  = playlist.Name;
            string          tplName = string.Format("{0}_shfl", plName);
            IITUserPlaylist parent  = playlist.get_Parent();
            IITUserPlaylist pl1     = (parent == null) ? App.iTunes.CreatePlaylist(tplName) as IITUserPlaylist : parent.CreatePlaylist(tplName) as IITUserPlaylist;

            // populate playlist with shuffled track order
            for (int n = 0; n < nTracks; n++)
            {
                IITTrack trk = tracks[shuffle[n]];
                pl1.AddTrack(trk);
            }

            // delete original playlist
            playlist.Delete();

            // rename new playlist to original name
            pl1.Name = plName;

            // Retuen new playlist so tree can be updated.
            return(pl1);
        }
 public IITUserPlaylist Find(string name, ITUserPlaylistSpecialKind kind, IITUserPlaylist parent)
 {
     foreach (IITPlaylist playlist in itunes.LibrarySource.Playlists)
     {
         if (playlist.Name == name && playlist.Kind == ITPlaylistKind.ITPlaylistKindUser)
         {
             IITUserPlaylist userPlaylist = (IITUserPlaylist)playlist;
             if (userPlaylist.SpecialKind == kind)
             {
                 var foundParent = userPlaylist.get_Parent();
                 if ((foundParent == null && parent == null) || (foundParent != null && foundParent.Name == parent.Name))
                 {
                     return userPlaylist;
                 }
             }
         }
     }
     return null;
 }
Example #14
0
 public IITUserPlaylist Find(string name, ITUserPlaylistSpecialKind kind, IITUserPlaylist parent)
 {
     foreach (IITPlaylist playlist in itunes.LibrarySource.Playlists)
     {
         if (playlist.Name == name && playlist.Kind == ITPlaylistKind.ITPlaylistKindUser)
         {
             IITUserPlaylist userPlaylist = (IITUserPlaylist)playlist;
             if (userPlaylist.SpecialKind == kind)
             {
                 var foundParent = userPlaylist.get_Parent();
                 if ((foundParent == null && parent == null) || (foundParent != null && foundParent.Name == parent.Name))
                 {
                     return(userPlaylist);
                 }
             }
         }
     }
     return(null);
 }
Example #15
0
        // Process all files in the directory passed in, recurse on any directories
        // that are found, and process the files they contain.
        public static void ProcessDirectory(string path, IITUserPlaylist parent)
        {
            Console.WriteLine("Processing directory '{0}'.", path);

            if (Directory.Exists(path))
            {
                var dir = new DirectoryInfo(path);

                IITUserPlaylist folder = null;
                var isFolder = DirectoryHelper.ContainsDirectories(path);
                if (isFolder)
                {
                    var fName = dir.Name;
                    // check if playlist folder exists at current location
                    folder = playlistHelper.Find(fName, ITUserPlaylistSpecialKind.ITUserPlaylistSpecialKindFolder, parent);
                    if (folder == null)
                    {
                        if (parent != null)
                        {
                            folder = (IITUserPlaylist)parent.CreateFolder(fName);
                        }
                        else
                        {
                            folder = (IITUserPlaylist)itunes.CreateFolder(fName);
                        }
                    }
                }

                IITUserPlaylist playlist = null;
                if (DirectoryHelper.ContainsFiles(path))
                {
                    var pName = isFolder ? "## Tracks ##" : dir.Name;
                    var playlistLocation = isFolder ? folder : parent;
                    playlist = playlistHelper.Find(pName, ITUserPlaylistSpecialKind.ITUserPlaylistSpecialKindNone, playlistLocation);
                    if (playlist == null)
                    {
                        if (playlistLocation != null)
                        {
                            playlist = (IITUserPlaylist)playlistLocation.CreatePlaylist(pName);
                        }
                        else
                        {
                            playlist = (IITUserPlaylist)itunes.CreatePlaylist(pName);
                        }
                    }

                    var tracks = playlist.Tracks;
                    var trackPaths = new List<string>();
                    foreach (IITTrack track in tracks)
                    {
                        trackPaths.Add(track.)
                    }

                    string[] fileEntries = Directory.GetFiles(path);
                    foreach (var file in fileEntries)
                    {
                        Console.WriteLine("Processing file '{0}'.", file);

                        playlist.AddFile(file);
                    }
                }

                // Recursively process the child folders
                string[] subDirectories = Directory.GetDirectories(path);
                foreach (string subDirectory in subDirectories)
                {
                    ProcessDirectory(subDirectory, folder);
                }
            }
            else
            {
                Console.WriteLine("{0} is not a valid directory.", path);
            }
        }
Example #16
0
        /// <summary>
        /// Check if the My Devices folder exists, if not create it.
        /// </summary>
        private void CreateMyDevicesFolder()
        {
            try
            {
                foreach (IITPlaylist p in itunes.LibrarySource.Playlists)
                {
                    if (p.Name == "My Devices" && p.Kind == ITPlaylistKind.ITPlaylistKindUser)
                    {
                        folderMyDevices = (IITUserPlaylist)p;
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                l.Error(ex);
            }

            try
            {
                object src = itunes.LibrarySource;
                folderMyDevices = (IITUserPlaylist)itunes.CreateFolderInSource("My Devices", ref src);
            }
            catch (COMException ex)
            {
                l.Error(ex);

                MessageBox.Show(this, "Unable to create 'My Devices' folder. This may "
                + "be due to iTunes being busy with an other operation. If this error "
                + "continues to occur, please turn the option off in the Preferences dialog.\n\n(" + ex.Message + ")",
                "Failed to create My Devices folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
Example #17
0
        private static void createPlaylist()
        {
            try
            {
                iTunesApp app = new iTunesApp();

                app.ForceToForegroundOnDialog = true;

                //app.SetOptions(); would be nice to kill autoarrange

                IITPlaylistCollection pl       = app.LibrarySource.Playlists;
                IITUserPlaylist       playlist = null;

                playlist = findPlaylist(pl, playlist);

                if (playlist == null)
                {
                    playlist = (IITUserPlaylist)app.CreatePlaylist(playlistName);
                }
                else
                {
                    // remove tracks, how?
                    foreach (IITTrack t in playlist.Tracks)
                    {
                        //t.Delete(); <== ?
                    }
                }

                iTunesLib.IITLibraryPlaylist lp = app.LibraryPlaylist;

                IITTrackCollection itTracks = app.LibraryPlaylist.Tracks;

                Dictionary <string, int> libraryTrackDictionary = new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase);
                List <string>            libraryTrackFiles      = new List <string>();

                foreach (IITTrack t in itTracks)
                {
                    if (Cancel)
                    {
                        break;
                    }

                    if (t.Kind == ITTrackKind.ITTrackKindFile)
                    {
                        string l = (t as IITFileOrCDTrack).Location;
                        if (l != null)
                        {
                            libraryTrackFiles.Add(l);
                            if (!libraryTrackDictionary.ContainsKey(l))
                            {
                                libraryTrackDictionary.Add(l, t.Index);
                            }
                        }
                    }
                }
                List <string> allTracks = new List <string>();
                foreach (Track t in tracks)
                {
                    allTracks.Add(t.FilePath);
                }

                object oo = (object)(allTracks.ToArray());
                playlist.AddFiles(ref oo);

                Controller.ShowMessage("Completed sending playlist to iTunes.");

                app.Quit();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                Clock.DoOnMainThread(ShowError);
            }
            Busy = false;
        }
Example #18
0
        /// <summary>
        /// <see cref="Notpod.ISynchronizer#SynchronizeDevice(IITUserPlaylist, string, Device)"/>
        /// </summary>
        public void SynchronizeDevice(IITUserPlaylist playlist, string drive, Device device)
        {
            //Check that configuration has been set.
            if (configuration == null)
                throw new SynchronizeException("Configuration has not been set.");

            DirectoryInfo di = new DirectoryInfo(drive + device.MediaRoot);

            // Check if the media root directory actually exists 
            // Thanks to Robert Grabowski for the contribution.
            try
            {
                if (!di.Exists)
                    di.Create();
            }
            catch (IOException ex)
            {
                string message = "Could not create directory '"
                    + di.Name + "' for device '" + device.Name
                    + "'. Unable to complete synchronization.";
                l.Error(message, ex);

                syncForm.AddLogText(message, Color.Red);
            }

            // Perform a write check to make sure Notpod has write 
            // access to the music folder of the device.
            String writeCheckPath = drive + device.MediaRoot + "\\wrtchk.ita";
            try
            {
                FileStream writeCheckStream = File.Create(writeCheckPath);
                writeCheckStream.Close();
                File.Delete(writeCheckPath);
            }
            catch (Exception e)
            {
                l.Error("Could not write " + writeCheckPath + ".", e);

                String message = "Error: I am unable to write to the music folder of "
                    + "your device. Please make sure I have the proper permissions"
                    + " and try again.";

                syncForm.AddLogText(message, Color.Red);
                return;
            }

            FileInfo[] files = FileHelper.GetFilesRecursive(di.ToString()).ToArray();

            //Find correct synchronize pattern for the device.
            SyncPattern devicePattern = null;
            foreach (SyncPattern sp in configuration.SyncPatterns)
            {
                if (sp.Identifier == device.SyncPattern)
                    devicePattern = sp;
            }

            //Throw an exception if the pattern could not be found.
            if (devicePattern == null)
            {
                OnSynchronizeError(device, "Illegal synchronize pattern '" + device.SyncPattern + "' for device '" + device.Name + "'. Unable to complete synchronization.");
                return;
            }

            syncForm.AddLogText("Synchronizing '" + device.Name + "'...");
            syncForm.SetDeviceName(device.Name, drive);

            syncForm.SetCurrentStatus("Initializing...");
            syncForm.SetMaxProgressValue(playlist.Tracks.Count);
            syncForm.SetProgressValue(0);


            // maintain a filename -> track object dictionary for the tracks to be copied onto the device           
            // Thanks to Robert Grabowski for the contribution.
            Dictionary<string, IITFileOrCDTrack> syncList = new Dictionary<string, IITFileOrCDTrack>();

            string deviceMediaRoot = drive + (device.MediaRoot.Length > 0 ? device.MediaRoot + "\\" : "");

            try
            {
                foreach (IITTrack track in playlist.Tracks)
                {
                    if (syncForm.GetOperationCancelled())
                    {
                        syncForm.SetCurrentStatus("Synchronization cancelled. 0 tracks added, 0 tracks removed.");
                        syncForm.AddLogText("Synchronization cancelled.", Color.OrangeRed);
                        OnSynchronizeCancelled();
                        return;
                    }

                    syncForm.SetProgressValue(syncForm.GetProgressValue() + 1);

                    //Continue if the track is not of kind "file" or the track is one of the initial tracks on the device.
                    if (track.Kind != ITTrackKind.ITTrackKindFile || device.InitialTracks.Contains(track))
                        continue;


                    string pathOnDevice = "";

                    IITTrack addTrack = track;

                    try
                    {
                        pathOnDevice = SyncPatternTranslator.Translate(devicePattern, (IITFileOrCDTrack)addTrack);                        
                    }
                    catch (Exception ex)
                    {
                        syncForm.AddLogText("An error occured while working with \"" + track.Artist + " - " + track.Name
                            + "\". This may be because the track has been deleted from disk. Look for an exclamation mark"
                            + "next to the track in your playlist.", Color.Orange);
                        continue;
                    }
                    string fullPath = deviceMediaRoot + pathOnDevice;
                    l.Debug(fullPath);

                    // Check if the list already contains a key - this happens in cases where there are duplicate 
                    // entries in the playlist for the same track. Although the track may have different locations on 
                    // the user's computer, Notpod will not handle this.
                    if (syncList.ContainsKey(fullPath))
                    {
                        syncForm.AddLogText("You have duplicate listings for " + track.Artist + " - " + track.Name
                            + " in your playlist. I will continue for now, but you should remove any duplicates "
                            + "when the synchronization is complete.", Color.Orange);
                        continue;
                    }

                    syncList.Add(fullPath, (IITFileOrCDTrack)addTrack);
                }
            }
            catch (Exception ex)
            {
                syncForm.SetCurrentStatus("");
                String message = "Error occured while initializing: " + ex.Message;
                syncForm.AddLogText(message, Color.Red);
                syncForm.DisableCancelButton();
                syncForm.SetProgressValue(0);
                OnSynchronizeError(device, message);

                l.Error(message, ex);
                return;
            }
            syncForm.AddLogText("Initialization completed.");

            syncForm.SetCurrentStatus("Checking tracks. Removing those that are no longer in the playlist...");
            int totalTracks = files.Length;
            syncForm.SetMaxProgressValue(totalTracks);
            syncForm.SetProgressValue(0);

            int tracksRemoved = 0;
            int tracksAdded = 0;
            long existingSize = 0;

            try
            {
                //Remove tracks from device which are no longer in the playlist.
                foreach (FileInfo file in files)
                {
                    l.Debug("Checking file: " + file.FullName);

                    // Check for cancelled operation.
                    if (syncForm.GetOperationCancelled())
                    {
                        syncForm.SetCurrentStatus("Synchronization cancelled. " + tracksAdded
                            + " track(s) added, " + tracksRemoved + " track(s) removed.");
                        syncForm.AddLogText("Synchronization cancelled.", Color.OrangeRed);
                        OnSynchronizeCancelled();
                        return;
                    }

                    //Increase progress bar
                    syncForm.SetProgressValue(syncForm.GetProgressValue() + 1);

                    //Continue with next track if it is not of a supported extension.
                    //if (file.Extension != ".mp3" && file.Extension != ".acc" && file.Extension != ".m4p" && file.Extension != ".m4a")
                    if (!extensions.Contains(file.Extension))
                        continue;
                    
                    if (syncList.ContainsKey(file.FullName))
                    {
                        FileInfo fi = new FileInfo(file.FullName);
                        existingSize += fi.Length;
                        continue;
                    }

                    //If the track was not found --- delete it!
                    string fileFullName = file.FullName;
                    file.Delete();
                    
                    l.Debug("Removing file no longer in playlist: " + fileFullName);
                    
                    CheckAndRemoveFolders(fileFullName, drive, device);

                    tracksRemoved++;

                }

                syncForm.AddLogText(tracksRemoved + " track(s) was removed from the device.",
                    Color.Orange);
            }
            catch (MissingTrackException ex)
            {
                syncForm.SetCurrentStatus("");
                String message = "You have a missing file in your library. Please clean up "
                    + "your playlist and remove the track '" + ex.Track.Artist + " - "
                    + ex.Track.Name + "' before re-synchronizing.";
                syncForm.AddLogText(message, Color.Red);
                syncForm.DisableCancelButton();
                syncForm.SetProgressValue(0);
                OnSynchronizeError(device, message);

                l.Error(message, ex);

                return;
            }
            catch (Exception ex)
            {
                syncForm.SetCurrentStatus("");
                String message = "Error occured while checking for deleted tracks: " + ex.Message;
                syncForm.AddLogText(message, Color.Red);
                syncForm.DisableCancelButton();
                syncForm.SetProgressValue(0);
                OnSynchronizeError(device, message);

                l.Error(message, ex);
                return;
            }

            files = null;

            // Check free space on the device
            double playlistSize = playlist.Size;
            DriveInfo driveInfo = new DriveInfo(drive.Substring(0, 1));
            long freeOnDisk = driveInfo.AvailableFreeSpace;

            if (freeOnDisk < playlistSize - existingSize)
            {
                string message = "There is not enough space on your device to synchronize the playlist.";
                OnSynchronizeError(device, message);
                syncForm.AddLogText(message, Color.Red);
                syncForm.SetCurrentStatus(message);
                syncForm.DisableCancelButton();
                syncForm.SetProgressValue(0);
                return;
            }

            try
            {
                syncForm.SetCurrentStatus("Copying new files...");
                syncForm.AddLogText("Preparing to copy new files.", Color.Black);
                syncForm.SetMaxProgressValue(syncList.Count);
                syncForm.SetProgressValue(0);

                //Check for new track in the playlist which should be copied to the device
                // NEW foreach: traverse synchronization list instead of playlist
                // Thanks to Robert Grabowski.                
                foreach (string filePath in syncList.Keys)
                {
                    IITTrack track = syncList[filePath];

                    // Check for cancelled operation.
                    if (syncForm.GetOperationCancelled())
                    {
                        syncForm.SetCurrentStatus("Synchronization cancelled. " + tracksAdded
                            + " track(s) added, " + tracksRemoved + " track(s) removed.");
                        syncForm.AddLogText("Synchronization cancelled.", Color.OrangeRed);
                        syncForm.DisableCancelButton();
                        syncForm.SetProgressValue(0);
                        OnSynchronizeCancelled();
                        return;
                    }


                    //Increase progress bar
                    syncForm.SetProgressValue(syncForm.GetProgressValue() + 1);

                    string trackPath = filePath.Substring(deviceMediaRoot.Length); // hack: cut out media root
                    l.Debug("Checking for copy: " + filePath);

                    if (File.Exists(filePath))
                        continue;

                    try
                    {
                        CheckAndCreateFolders(trackPath, drive, device);
                        syncForm.SetCurrentStatus("Copying " + filePath
                            + " (" + syncForm.GetProgressValue() + "/" + syncForm.GetMaxProgressValue() + ")");
                                                
                        File.Copy(((IITFileOrCDTrack)track).Location, filePath, true);
                        File.SetAttributes(filePath, FileAttributes.Normal);


                        syncForm.AddLogText(filePath + " copied successfully.", Color.Green);

                        l.Debug("Copied: " + filePath);
                    }
                    catch (Exception ex)
                    {
                        String message = "Failed to copy " + filePath + ".\n-> " + ex.Message;
                        syncForm.AddLogText(message, Color.Red);
                        OnSynchronizeError(device, message);

                        l.Error(message, ex);

                        return;
                    }

                    tracksAdded++;

                }
            }
            catch (MissingTrackException ex)
            {
                syncForm.SetCurrentStatus("");
                String message = "You have a missing file in your library. Please remove the track '" + ex.Track.Artist + " - " + ex.Track.Name + "' and try again. I am sorry for the inconvenience.";
                syncForm.AddLogText(message, Color.Red);
                syncForm.DisableCancelButton();
                syncForm.SetProgressValue(0);
                OnSynchronizeError(device, message);

                l.Error(message, ex);

                return;
            }
            catch (Exception ex)
            {
                string message = "An error occured while copying new tracks: " + ex.Message;
                syncForm.SetCurrentStatus("");
                syncForm.AddLogText(message,
                    Color.Red);
                syncForm.DisableCancelButton();
                syncForm.SetProgressValue(0);
                OnSynchronizeError(device, message);

                l.Error(message, ex);

                return;
            }

            syncForm.SetCurrentStatus("Synchronization completed. " + tracksAdded
                + " track(s) added, " + tracksRemoved + " track(s) removed.");
            syncForm.AddLogText("Completed. " + tracksAdded + " track(s) copied to your device.", Color.Green);
            syncForm.DisableCancelButton();
            OnSynchronizeComplete();

        }
Example #19
0
        public override bool Play(string strFile)
        {
            try
            {
                if (_iTunesApplication == null)
                {
                    _iTunesApplication = new iTunesAppClass();
                    _iTunesApplication.OnPlayerPlayEvent +=
                        new _IiTunesEvents_OnPlayerPlayEventEventHandler(_iTunesApplication_OnPlayerPlayEvent);
                    _iTunesApplication.OnPlayerStopEvent +=
                        new _IiTunesEvents_OnPlayerStopEventEventHandler(_iTunesApplication_OnPlayerStopEvent);
                    _iTunesApplication.OnPlayerPlayingTrackChangedEvent +=
                        new _IiTunesEvents_OnPlayerPlayingTrackChangedEventEventHandler(
                            _iTunesApplication_OnPlayerPlayingTrackChangedEvent);
                    IITPlaylist playList = null;
                    foreach (IITPlaylist pl in _iTunesApplication.LibrarySource.Playlists)
                    {
                        if (pl.Name.Equals("MediaPortalTemporaryPlaylist"))
                        {
                            playList = pl;
                            break;
                        }
                    }
                    if (playList == null)
                    {
                        _playList = (IITUserPlaylist)_iTunesApplication.CreatePlaylist("MediaPortalTemporaryPlaylist");
                    }
                    else
                    {
                        _playList = (IITUserPlaylist)playList;
                    }
                    _playList.SongRepeat = ITPlaylistRepeatMode.ITPlaylistRepeatModeOff;
                }

                // stop other media which might be active until now.
                if (g_Player.Playing)
                {
                    g_Player.Stop();
                }

                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_PLAYBACK_STARTED, 0, 0, 0, 0, 0, null);
                msg.Label = strFile;
                GUIWindowManager.SendThreadMessage(msg);

                _started = false;
                _ended   = false;
                foreach (IITTrack track in _playList.Tracks)
                {
                    track.Delete();
                }
                _playList.AddFile(strFile);
                _playList.PlayFirstTrack();

                _playerIsPaused  = false;
                _currentFile     = strFile;
                _duration        = -1;
                _currentPosition = -1;
                _playerState     = ITPlayerState.ITPlayerStateStopped;
                _updateTimer     = DateTime.MinValue;

                UpdateStatus();
                _notifyPlaying = true;
                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("ITunesPlugin.Play: Exception");
                Log.Error(ex);
                _notifyPlaying     = false;
                _iTunesApplication = null;
            }
            return(false);
        }
Example #20
0
    public override bool Play(string strFile)
    {
      try
      {
        if (_iTunesApplication == null)
        {
          _iTunesApplication = new iTunesAppClass();
          _iTunesApplication.OnPlayerPlayEvent +=
            new _IiTunesEvents_OnPlayerPlayEventEventHandler(_iTunesApplication_OnPlayerPlayEvent);
          _iTunesApplication.OnPlayerStopEvent +=
            new _IiTunesEvents_OnPlayerStopEventEventHandler(_iTunesApplication_OnPlayerStopEvent);
          _iTunesApplication.OnPlayerPlayingTrackChangedEvent +=
            new _IiTunesEvents_OnPlayerPlayingTrackChangedEventEventHandler(
              _iTunesApplication_OnPlayerPlayingTrackChangedEvent);
          IITPlaylist playList = null;
          foreach (IITPlaylist pl in _iTunesApplication.LibrarySource.Playlists)
          {
            if (pl.Name.Equals("MediaPortalTemporaryPlaylist"))
            {
              playList = pl;
              break;
            }
          }
          if (playList == null)
          {
            _playList = (IITUserPlaylist)_iTunesApplication.CreatePlaylist("MediaPortalTemporaryPlaylist");
          }
          else
          {
            _playList = (IITUserPlaylist)playList;
          }
          _playList.SongRepeat = ITPlaylistRepeatMode.ITPlaylistRepeatModeOff;
        }

        // stop other media which might be active until now.
        if (g_Player.Playing)
        {
          g_Player.Stop();
        }

        GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_PLAYBACK_STARTED, 0, 0, 0, 0, 0, null);
        msg.Label = strFile;
        GUIWindowManager.SendThreadMessage(msg);

        _started = false;
        _ended = false;
        foreach (IITTrack track in _playList.Tracks)
        {
          track.Delete();
        }
        _playList.AddFile(strFile);
        _playList.PlayFirstTrack();

        _playerIsPaused = false;
        _currentFile = strFile;
        _duration = -1;
        _currentPosition = -1;
        _playerState = ITPlayerState.ITPlayerStateStopped;
        _updateTimer = DateTime.MinValue;

        UpdateStatus();
        _notifyPlaying = true;
        return true;
      }
      catch (Exception ex)
      {
        Log.Error("ITunesPlugin.Play: Exception");
        Log.Error(ex);
        _notifyPlaying = false;
        _iTunesApplication = null;
      }
      return false;
    }
Example #21
0
        // Process all files in the directory passed in, recurse on any directories
        // that are found, and process the files they contain.
        public static void ProcessDirectory(string path, IITUserPlaylist parent)
        {
            Console.WriteLine("Processing directory '{0}'.", path);

            if (Directory.Exists(path))
            {
                var dir = new DirectoryInfo(path);

                IITUserPlaylist folder   = null;
                var             isFolder = DirectoryHelper.ContainsDirectories(path);
                if (isFolder)
                {
                    var fName = dir.Name;
                    // check if playlist folder exists at current location
                    folder = playlistHelper.Find(fName, ITUserPlaylistSpecialKind.ITUserPlaylistSpecialKindFolder, parent);
                    if (folder == null)
                    {
                        if (parent != null)
                        {
                            folder = (IITUserPlaylist)parent.CreateFolder(fName);
                        }
                        else
                        {
                            folder = (IITUserPlaylist)itunes.CreateFolder(fName);
                        }
                    }
                }

                IITUserPlaylist playlist = null;
                if (DirectoryHelper.ContainsFiles(path))
                {
                    var pName            = isFolder ? "## Tracks ##" : dir.Name;
                    var playlistLocation = isFolder ? folder : parent;
                    playlist = playlistHelper.Find(pName, ITUserPlaylistSpecialKind.ITUserPlaylistSpecialKindNone, playlistLocation);
                    if (playlist == null)
                    {
                        if (playlistLocation != null)
                        {
                            playlist = (IITUserPlaylist)playlistLocation.CreatePlaylist(pName);
                        }
                        else
                        {
                            playlist = (IITUserPlaylist)itunes.CreatePlaylist(pName);
                        }
                    }

                    var tracks     = playlist.Tracks;
                    var trackPaths = new List <string>();
                    foreach (IITTrack track in tracks)
                    {
                        trackPaths.Add(track.)
                    }

                    string[] fileEntries = Directory.GetFiles(path);
                    foreach (var file in fileEntries)
                    {
                        Console.WriteLine("Processing file '{0}'.", file);

                        playlist.AddFile(file);
                    }
                }

                // Recursively process the child folders
                string[] subDirectories = Directory.GetDirectories(path);
                foreach (string subDirectory in subDirectories)
                {
                    ProcessDirectory(subDirectory, folder);
                }
            }
            else
            {
                Console.WriteLine("{0} is not a valid directory.", path);
            }
        }
        private void IntializeGenerator()
        {
            selectedTracks = itunes.SelectedTracks;
            var playlistName = view.PlaylistName;

            if (playlistName.Length == 0)
            {
                playlistName = DEFAULT_PLAYLIST_NAME;
            }

            playlist = (IITUserPlaylist)itunes.CreatePlaylist(playlistName);

            maxTracksPerArtist = view.MaxTracksPerArtist;
            if (maxTracksPerArtist == 0)
                maxTracksPerArtist = MAX_TRACKS_PER_ARTIST;

            maxTracks = view.MaxTracks;
            if (maxTracks == 0)
                maxTracks = MAX_TRACKS;

            startingSimilarArtists = view.InitialSimilarArtists;
            if (startingSimilarArtists == 0)
                startingSimilarArtists = STARTING_SIMILAR_ARTISTS;

            additionalSimilarArtists = view.AdditionalSimilarArtists;
            if (additionalSimilarArtists == 0)
                additionalSimilarArtists = ADDITIONAL_SIMILAR_ARTISTS;
        }
Example #23
0
        public static CPlaylist LoadPlaylists(iTunesApp itunes)
        {
            CPlaylist             retPlaylist = new CPlaylist(null);
            IITSourceCollection   sources     = itunes.Sources;
            IITPlaylistCollection playlists   = null;
            IITSource             plSource    = null;

            foreach (IITSource source in sources)
            {
                if (source.Kind == ITSourceKind.ITSourceKindLibrary)
                {
                    plSource  = source;
                    playlists = source.Playlists;
                    break;
                }
            }
            foreach (IITPlaylist pl in playlists)
            {
                if (pl.Kind != ITPlaylistKind.ITPlaylistKindUser)
                {
                    continue;
                }
                try
                {
                    IITUserPlaylist upl = (IITUserPlaylist)pl;
                    if (upl.Smart)
                    {
                        continue;
                    }
                    if (upl.SpecialKind == ITUserPlaylistSpecialKind.ITUserPlaylistSpecialKindPodcasts)
                    {
                        continue;
                    }
                    string strDir = string.Empty;
                    Stack <IITUserPlaylist> parentStack = new Stack <IITUserPlaylist>();
                    IITUserPlaylist         uplp        = upl.get_Parent();
                    if (uplp != null)
                    {
                        parentStack.Push(uplp);
                        IITUserPlaylist uplc = uplp;
                        do
                        {
                            uplp = uplc.get_Parent();
                            if (uplp != null)
                            {
                                parentStack.Push(uplp);
                                uplc = uplp;
                            }
                        } while (uplp != null);
                    }
                    CPlaylist parentPL   = retPlaylist;
                    bool      bFoundLeaf = false;
                    do
                    {
                        uplp = (parentStack.Count > 0) ? parentStack.Pop() : null;
                        if (uplp == null)
                        {
                            bFoundLeaf = true;
                        }
                        else
                        {
                            CPlaylist childPL = null;
                            foreach (var item in parentPL.Children)
                            {
                                if (item.Name == uplp.Name)
                                {
                                    childPL = item;
                                    break;
                                }
                            }
                            if (childPL != null)
                            {
                                parentPL = childPL;
                            }
                            else
                            {
                                bFoundLeaf = true;
                            }
                        }
                    } while (!bFoundLeaf);
                    while (uplp != null)
                    {
                        CPlaylist plChild = new CPlaylist(uplp, true);
                        parentPL.Children.Add(plChild);
                        parentPL = plChild;
                        uplp     = (parentStack.Count > 0) ? parentStack.Pop() : null;
                    }
                    parentPL.Children.Add(new CPlaylist(upl));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            }
            return(retPlaylist);
        }
Example #24
0
        /// <summary>
        /// <see cref="Notpod.ISynchronizer#SynchronizeDevice(IITUserPlaylist, string, Device)"/>
        /// </summary>
        public void SynchronizeDevice(IITUserPlaylist playlist, string drive, Device device)
        {
            //Check that configuration has been set.
            if (configuration == null)
            {
                throw new SynchronizeException("Configuration has not been set.");
            }

            DirectoryInfo di = new DirectoryInfo(drive + device.MediaRoot);

            // Check if the media root directory actually exists
            // Thanks to Robert Grabowski for the contribution.
            try
            {
                if (!di.Exists)
                {
                    di.Create();
                }
            }
            catch (IOException ex)
            {
                string message = "Could not create directory '"
                                 + di.Name + "' for device '" + device.Name
                                 + "'. Unable to complete synchronization.";
                l.Error(message, ex);

                syncForm.AddLogText(message, Color.Red);
            }

            // Perform a write check to make sure Notpod has write
            // access to the music folder of the device.
            String writeCheckPath = drive + device.MediaRoot + "\\wrtchk.ita";

            try
            {
                FileStream writeCheckStream = File.Create(writeCheckPath);
                writeCheckStream.Close();
                File.Delete(writeCheckPath);
            }
            catch (Exception e)
            {
                l.Error("Could not write " + writeCheckPath + ".", e);

                String message = "Error: I am unable to write to the music folder of "
                                 + "your device. Please make sure I have the proper permissions"
                                 + " and try again.";

                syncForm.AddLogText(message, Color.Red);
                return;
            }

            FileInfo[] files = FileHelper.GetFilesRecursive(di.ToString()).ToArray();

            //Find correct synchronize pattern for the device.
            SyncPattern devicePattern = null;

            foreach (SyncPattern sp in configuration.SyncPatterns)
            {
                if (sp.Identifier == device.SyncPattern)
                {
                    devicePattern = sp;
                }
            }

            //Throw an exception if the pattern could not be found.
            if (devicePattern == null)
            {
                OnSynchronizeError(device, "Illegal synchronize pattern '" + device.SyncPattern + "' for device '" + device.Name + "'. Unable to complete synchronization.");
                return;
            }

            syncForm.AddLogText("Synchronizing '" + device.Name + "'...");
            syncForm.SetDeviceName(device.Name, drive);

            syncForm.SetCurrentStatus("Initializing...");
            syncForm.SetMaxProgressValue(playlist.Tracks.Count);
            syncForm.SetProgressValue(0);


            // maintain a filename -> track object dictionary for the tracks to be copied onto the device
            // Thanks to Robert Grabowski for the contribution.
            Dictionary <string, IITFileOrCDTrack> syncList = new Dictionary <string, IITFileOrCDTrack>();

            string deviceMediaRoot = drive + (device.MediaRoot.Length > 0 ? device.MediaRoot + "\\" : "");

            string playlistFile = null;

            if (device.ExportPlaylist != null && device.ExportPlaylist.File.Length > 0)
            {
                playlistFile = drive + device.ExportPlaylist.File;
            }

            IPlaylistWriter playlistWriter = null;

            if (File.Exists(playlistFile))
            {
                File.Delete(playlistFile);
            }

            try
            {
                // Create a new instance of one of the IPlaylistWriter implementations to
                // handle the file's contents.
                switch (device.ExportPlaylist.Type)
                {
                case PlaylistType.M3U:
                    playlistWriter = new M3UPlaylistWriter(playlistFile, playlist.Name);
                    break;

                case PlaylistType.EXT:
                    playlistWriter = new M3UExtPlaylistWriter(playlistFile, playlist.Name);
                    break;

                case PlaylistType.WPL:
                    playlistWriter = new WPLPlaylistWriter(playlistFile, playlist.Name);
                    break;

                case PlaylistType.ZPL:
                    playlistWriter = new ZPLPlaylistWriter(playlistFile, playlist.Name);
                    break;

                default:
                    break;
                }

                for (int i = 1; i <= playlist.Tracks.Count; i++)
                {
                    IITTrack track = playlist.Tracks.get_ItemByPlayOrder(i);

                    if (syncForm.GetOperationCancelled())
                    {
                        syncForm.SetCurrentStatus("Synchronization cancelled. 0 tracks added, 0 tracks removed.");
                        syncForm.AddLogText("Synchronization cancelled.", Color.OrangeRed);
                        OnSynchronizeCancelled();
                        return;
                    }

                    syncForm.SetProgressValue(syncForm.GetProgressValue() + 1);

                    //Continue if the track is not of kind "file" or the track is one of the initial tracks on the device.
                    if (track.Kind != ITTrackKind.ITTrackKindFile || device.InitialTracks.Contains(track))
                    {
                        continue;
                    }


                    string pathOnDevice = "";

                    IITTrack addTrack = track;

                    try
                    {
                        pathOnDevice = SyncPatternTranslator.Translate(devicePattern, (IITFileOrCDTrack)addTrack, i);
                    }
                    catch (Exception)
                    {
                        syncForm.AddLogText("An error occured while working with \"" + track.Artist + " - " + track.Name
                                            + "\". This may be because the track has been deleted from disk. Look for an exclamation mark"
                                            + "next to the track in your playlist.", Color.Orange);
                        continue;
                    }
                    string fullPath = deviceMediaRoot + pathOnDevice;
                    l.Debug(fullPath);

                    // Check if the list already contains a key - this happens in cases where there are duplicate
                    // entries in the playlist for the same track. Although the track may have different locations on
                    // the user's computer, Notpod will not handle this.
                    if (syncList.ContainsKey(fullPath))
                    {
                        syncForm.AddLogText("You have duplicate listings for " + track.Artist + " - " + track.Name
                                            + " in your playlist. I will continue for now, but you should remove any duplicates "
                                            + "when the synchronization is complete.", Color.Orange);
                        continue;
                    }

                    syncList.Add(fullPath, (IITFileOrCDTrack)addTrack);
                }
            }
            catch (Exception ex)
            {
                syncForm.SetCurrentStatus("");
                String message = "Error occured while initializing: " + ex.Message;
                syncForm.AddLogText(message, Color.Red);
                syncForm.DisableCancelButton();
                syncForm.SetProgressValue(0);
                OnSynchronizeError(device, message);

                l.Error(message, ex);
                return;
            }
            syncForm.AddLogText("Initialization completed.");

            syncForm.SetCurrentStatus("Checking tracks. Removing those that are no longer in the playlist...");
            int totalTracks = files.Length;

            syncForm.SetMaxProgressValue(totalTracks);
            syncForm.SetProgressValue(0);

            int  tracksRemoved = 0;
            int  tracksAdded   = 0;
            long existingSize  = 0;

            try
            {
                //Remove tracks from device which are no longer in the playlist.
                foreach (FileInfo file in files)
                {
                    l.Debug("Checking file: " + file.FullName);

                    // Check for cancelled operation.
                    if (syncForm.GetOperationCancelled())
                    {
                        syncForm.SetCurrentStatus("Synchronization cancelled. " + tracksAdded
                                                  + " track(s) added, " + tracksRemoved + " track(s) removed.");
                        syncForm.AddLogText("Synchronization cancelled.", Color.OrangeRed);
                        OnSynchronizeCancelled();
                        return;
                    }

                    //Increase progress bar
                    syncForm.SetProgressValue(syncForm.GetProgressValue() + 1);

                    //Continue with next track if it is not of a supported extension.
                    //if (file.Extension != ".mp3" && file.Extension != ".acc" && file.Extension != ".m4p" && file.Extension != ".m4a")
                    if (!extensions.Contains(file.Extension))
                    {
                        continue;
                    }

                    if (syncList.ContainsKey(file.FullName))
                    {
                        FileInfo fi = new FileInfo(file.FullName);
                        existingSize += fi.Length;
                        continue;
                    }

                    //If the track was not found --- delete it!
                    string fileFullName = file.FullName;
                    file.Delete();

                    l.Debug("Removing file no longer in playlist: " + fileFullName);

                    CheckAndRemoveFolders(fileFullName, drive, device);

                    tracksRemoved++;
                }

                syncForm.AddLogText(tracksRemoved + " track(s) was removed from the device.",
                                    Color.Orange);
            }
            catch (MissingTrackException ex)
            {
                syncForm.SetCurrentStatus("");
                String message = "You have a missing file in your library. Please clean up "
                                 + "your playlist and remove the track '" + ex.Track.Artist + " - "
                                 + ex.Track.Name + "' before re-synchronizing.";
                syncForm.AddLogText(message, Color.Red);
                syncForm.DisableCancelButton();
                syncForm.SetProgressValue(0);
                OnSynchronizeError(device, message);

                l.Error(message, ex);

                return;
            }
            catch (Exception ex)
            {
                syncForm.SetCurrentStatus("");
                String message = "Error occured while checking for deleted tracks: " + ex.Message;
                syncForm.AddLogText(message, Color.Red);
                syncForm.DisableCancelButton();
                syncForm.SetProgressValue(0);
                OnSynchronizeError(device, message);

                l.Error(message, ex);
                return;
            }

            files = null;

            // Check free space on the device
            double    playlistSize = playlist.Size;
            DriveInfo driveInfo    = new DriveInfo(drive.Substring(0, 1));
            long      freeOnDisk   = driveInfo.AvailableFreeSpace;

            if (freeOnDisk < playlistSize - existingSize)
            {
                string message = "There is not enough space on your device to synchronize the playlist.";
                OnSynchronizeError(device, message);
                syncForm.AddLogText(message, Color.Red);
                syncForm.SetCurrentStatus(message);
                syncForm.DisableCancelButton();
                syncForm.SetProgressValue(0);
                return;
            }

            try
            {
                syncForm.SetCurrentStatus("Copying new files...");
                syncForm.AddLogText("Preparing to copy new files.", Color.Black);
                syncForm.SetMaxProgressValue(syncList.Count);
                syncForm.SetProgressValue(0);

                // Check for new track in the playlist which should be copied to the device
                // NEW foreach: traverse synchronization list instead of playlist
                // Thanks to Robert Grabowski.
                foreach (string filePath in syncList.Keys)
                {
                    IITTrack track = syncList[filePath];

                    // Check for cancelled operation.
                    if (syncForm.GetOperationCancelled())
                    {
                        syncForm.SetCurrentStatus("Synchronization cancelled. " + tracksAdded
                                                  + " track(s) added, " + tracksRemoved + " track(s) removed.");
                        syncForm.AddLogText("Synchronization cancelled.", Color.OrangeRed);
                        syncForm.DisableCancelButton();
                        syncForm.SetProgressValue(0);
                        OnSynchronizeCancelled();
                        return;
                    }


                    //Increase progress bar
                    syncForm.SetProgressValue(syncForm.GetProgressValue() + 1);

                    //Continue with next track if it is not of a supported extension.
                    //if (file.Extension != ".mp3" && file.Extension != ".acc" && file.Extension != ".m4p" && file.Extension != ".m4a")
                    if (!extensions.Contains(Path.GetExtension(((IITFileOrCDTrack)track).Location)))
                    {
                        continue;
                    }

                    string trackPath = filePath.Substring(deviceMediaRoot.Length); // hack: cut out media root
                    l.Debug("Checking for copy: " + filePath);

                    string trackRelativePath = "";
                    if (playlistFile != null)
                    {
                        trackRelativePath = EvaluateRelativePath(Path.GetDirectoryName(playlistFile), filePath);
                    }

                    if (trackRelativePath.StartsWith(".\\"))
                    {
                        trackRelativePath = trackRelativePath.Substring(2);
                    }

                    if (File.Exists(filePath))
                    {
                        if (playlistWriter != null)
                        {
                            playlistWriter.WriteTrack(trackRelativePath, track);
                        }

                        continue;
                    }

                    try
                    {
                        CheckAndCreateFolders(trackPath, drive, device);
                        syncForm.SetCurrentStatus("Copying " + filePath
                                                  + " (" + syncForm.GetProgressValue() + "/" + syncForm.GetMaxProgressValue() + ")");

                        File.Copy(((IITFileOrCDTrack)track).Location, filePath, true);
                        File.SetAttributes(filePath, FileAttributes.Normal);

                        if (playlistWriter != null)
                        {
                            playlistWriter.WriteTrack(trackRelativePath, track);
                        }

                        syncForm.AddLogText(filePath + " copied successfully.", Color.Green);

                        l.Debug("Copied: " + filePath);
                    }
                    catch (Exception ex)
                    {
                        String message = "Failed to copy " + filePath + ".\n-> " + ex.Message;
                        syncForm.AddLogText(message, Color.Red);
                        OnSynchronizeError(device, message);

                        l.Error(message, ex);

                        return;
                    }

                    tracksAdded++;
                }
            } catch (MissingTrackException ex) {
                syncForm.SetCurrentStatus("");
                String message = "You have a missing file in your library. Please remove the track '" + ex.Track.Artist + " - " + ex.Track.Name + "' and try again. I am sorry for the inconvenience.";
                syncForm.AddLogText(message, Color.Red);
                syncForm.DisableCancelButton();
                syncForm.SetProgressValue(0);
                OnSynchronizeError(device, message);

                l.Error(message, ex);

                return;
            } catch (Exception ex) {
                string message = "An error occured while copying new tracks: " + ex.Message;
                syncForm.SetCurrentStatus("");
                syncForm.AddLogText(message,
                                    Color.Red);
                syncForm.DisableCancelButton();
                syncForm.SetProgressValue(0);
                OnSynchronizeError(device, message);

                l.Error(message, ex);

                return;
            }

            if (playlistWriter != null)
            {
                playlistWriter.Close();
                playlistWriter = null;
            }

            syncForm.SetCurrentStatus("Synchronization completed. " + tracksAdded
                                      + " track(s) added, " + tracksRemoved + " track(s) removed.");
            syncForm.AddLogText("Completed. " + tracksAdded + " track(s) copied to your device.", Color.Green);
            syncForm.DisableCancelButton();
            OnSynchronizeComplete();
        }