/// <summary> /// Event handler for connected devices. /// </summary> /// <param name="sender">Sender of the event.</param> /// <param name="args">Event arguments.</param> private void OnDeviceConnected(object sender, CDMEventArgs args) { Device device = args.Device; if (configuration.ShowNotificationPopups) { string message = "'" + device.Name + "' has been connected. " + "You may now synchronize the device " + "with the playlist for this device.\n\nDevices currently connected:"; foreach (Device d in connectedDevices.GetConnectedDevices()) { message += "\n - " + d.Name; } itaTray.ShowBalloonTip(5, "Device connected!", message, ToolTipIcon.Info); } IITPlaylist playlist = PlaylistExists(device); //Delete playlist if it exists. //if (playlist != null) // playlist.Delete(); if (playlist == null) { try { if (configuration.UseListFolder) { CreateMyDevicesFolder(); playlist = folderMyDevices.CreatePlaylist(device.Name); } else { playlist = itunes.CreatePlaylist(device.Name); } } catch (Exception e) { l.Error(e); MessageBox.Show("Failed to create list for device '" + device.Name + "'. You will not be able to synchronize this device with iTunes.", "Playlist error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { //If the option to use "My Devices" folder is set, move the playlist to that folder. if (configuration.UseListFolder && (playlist.Kind == ITPlaylistKind.ITPlaylistKindUser) && (device.Playlist == null || device.Playlist.Length == 0)) { CreateMyDevicesFolder(); object parent = (object)folderMyDevices; ((IITUserPlaylist)playlist).set_Parent(ref parent); } } }
public void SetupAndRunAutomatedPlaylist(iTunesApp itunes, params IITTrack[] tracks) { IITUserPlaylist pl; do // If we call delete mid loop, we sometimes don't get second instances of playlist. { pl = null; foreach (IITUserPlaylist old in itunes.LibrarySource.Playlists.OfType <IITUserPlaylist>()) { if (old.Name != automated_playlist_name) { continue; } pl = old; break; } pl?.Delete(); }while (pl != null); var sortable_tracks = tracks.Select(t => new SamTrack(t)).Sorted(); pl = (IITUserPlaylist)(itunes.CreatePlaylist(automated_playlist_name)); foreach (var t in sortable_tracks) { object track = t._Track; pl.AddTrack(ref track); } this.PlayPlaylist(pl); }
private void sortButton_Click(object sender, RoutedEventArgs e) { Task.Factory.StartNew(() => { try { this.Dispatch(() => { this.IsEnabled = false; }); var iTunes = new iTunesApp(); var playlists = this.playlistSortListView.Items .Cast <UserPlaylistViewModel>() .Where(x => x.IsChecked == true); playlists.AsParallel().ForAll(playlist => { var created = iTunes.CreatePlaylist(playlist.Name) as IITUserPlaylist; var source = playlist.Model; created.Shuffle = source.Shuffle; created.SongRepeat = source.SongRepeat; created.AddRangeTracks( source.Tracks .Cast <IITTrack>() .OrderBy("Comment", "DiscNumber", "TrackNumber") .ToArray()); source.Delete(); playlist.Model = created; playlist.IsChecked = false; }); this.Dispatch(() => { MessageBox.Show(this, "completed"); }); } finally { this.Dispatch(() => { this.IsEnabled = true; }); } }); }
private void sortButton_Click(object sender, RoutedEventArgs e) { Task.Factory.StartNew(() => { try { this.Dispatch(() => { this.IsEnabled = false; }); var iTunes = new iTunesApp(); var playlists = this.playlistSortListView.Items .Cast<UserPlaylistViewModel>() .Where(x => x.IsChecked == true); playlists.AsParallel().ForAll(playlist => { var created = iTunes.CreatePlaylist(playlist.Name) as IITUserPlaylist; var source = playlist.Model; created.Shuffle = source.Shuffle; created.SongRepeat = source.SongRepeat; created.AddRangeTracks( source.Tracks .Cast<IITTrack>() .OrderBy("Comment", "DiscNumber", "TrackNumber") .ToArray()); source.Delete(); playlist.Model = created; playlist.IsChecked = false; }); this.Dispatch(() => { MessageBox.Show(this, "completed"); }); } finally { this.Dispatch(() => { this.IsEnabled = true; }); } }); }
private static void MakeFolderPlaylist(iTunesApp app, string name, IEnumerable <IITFileOrCDTrack> tracks) { var playlist = app.CreatePlaylist(name) as IITUserPlaylist; if (playlist == null) { throw new InvalidOperationException("no playlist found!"); } foreach (var track in tracks.OrderBy(t => t.TrackNumber).ThenBy(t => t.Location)) { var currentTrack = track as object; playlist.AddTrack(ref currentTrack); } }
/// <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); } }
private void playlistGenerateButton_Click(object sender, RoutedEventArgs e) { Task.Factory.StartNew(() => { try { this.Dispatch(() => { this.IsEnabled = false; }); var itunes = new iTunesApp(); var trackGroups = itunes.LibraryPlaylist.GetCommentedTracks() .GroupBy(x => x.Comment.Split('@').First()) .ToArray(); trackGroups.AsParallel().ForAll(trackGroup => { var playlist = itunes.CreatePlaylist(trackGroup.Key) as IITUserPlaylist; playlist.SongRepeat = ITPlaylistRepeatMode.ITPlaylistRepeatModeAll; var orderdTracks = trackGroup.OrderBy("Comment", "DiscNumber", "TrackNumber"); playlist.AddRangeTracks(orderdTracks.ToArray()); }); this.Dispatch(() => { MessageBox.Show(this, "completed"); }); } finally { this.Dispatch(() => { this.IsEnabled = true; }); } }); }
/// <summary> /// It is critical to make the playlist, then iterate through all the itunes songs to find the /// specific songs for that playlist. If you iterate through itunes first, then make the playlist, /// then add the songs you find, you occasionally get an "item was deleted" COMException. I belive /// this is because itunes identifies songs by 4 id's, including what playlist they are from, and /// when the LibraryPlaylist gets switched around the references break. /// </summary> /// <param name="itunes"></param> /// <returns></returns> public IITUserPlaylist SetupAutomatedPlaylist(iTunesApp itunes) { IITUserPlaylist pl; do // If we call delete mid loop, we sometimes don't get second instances of playlist. { pl = null; foreach (IITUserPlaylist old in itunes.LibrarySource.Playlists.OfType <IITUserPlaylist>()) { if (old.Name != automated_playlist_name) { continue; } pl = old; break; } pl?.Delete(); }while (pl != null); // do loop return((IITUserPlaylist)(itunes.CreatePlaylist(automated_playlist_name))); }
// flags has bit indicators whether 2 way rating and/or playcount is requested (only set if enabled in the device properties) // for files(): // Key - the SynchronisationCategory the file should be sychronised to if appropriate for the device // Value is 3 strings // (0) - source file or playlist to be synchronised - use to query MusicBee for file tags, or files in a playlist // (1) - the filename extension of the file to be synchronised - normally the same as the extension for (0) but if the file would need to be re-encoded to meet the user's synch preferences then the extension for the encoded file // (2) - if SyncOrganisedFolders is enabled, filename as formatted by a naming template otherwise null // for each file that is synchronised, call Sync_FileStart(filename(0)) // MusicBee will determine if the file needs to be re-encoded depending on the user synch settings and if so the returned filename will be the temporary encoded filename // call Sync_FileEnd(filename(0), success, errorMessage) when that file has been synched or not // return true if all files synchronised ok public bool Synchronise(SynchronisationSettings flags, KeyValuePair <int, string[]>[] syncItems) { while (ReadyForSync == null) { ; // Wait if still opening iTunes } try { if (SynchronizationInProgress) { lastEx = null; return(false); } SynchronizationInProgress = true; var playlistKeys = new Dictionary <long, string>(); var trackKeys = new Dictionary <long, MusicBeeFile>(); foreach (var item in syncItems) { if (AbortSynchronization) { SynchronizationInProgress = false; AbortSynchronization = false; lastEx = null; return(true); } if (item.Key == (int)SynchronisationCategory.Playlist) { // Create or verify playlist. Populate after all files have been processed. var name = Regex.Replace(item.Value[0], "^.*\\\\(.*)(\\..*)", "$1"); var playlist = iTunes.GetPlaylist(name) ?? iTunes.CreatePlaylist(name); var key = iTunes.GetPersistentId(playlist); Marshal.ReleaseComObject(playlist); playlistKeys[key] = item.Value[0]; } else { // item.Value[0] is the URL to a MusicBee file to be sync'ed // item.Value[1] is the extension of the file // indicate to MusicBee that you want to synch the file // the returned filename is either the same as the supplied filename or // if re-encoding/forced embedding artwork, a temporary filename is returned var filename = Plugin.MbApiInterface.Sync_FileStart(item.Value[0]); // if filename is returned as null, that means MusicBee wasnt able to encode the file and it should be skipped from synchronisation if (filename == null) { continue; } bool success = false; string errorMessage = null; try { var mbFile = new MusicBeeFile(item.Value[0]); IITTrack itTrack = null; string itTrackPath = null; if (mbFile.WebFile) { itTrackPath = mbFile.Url; } else if (!File.Exists(filename)) { throw new IOException(Text.L("Track source file not found: {0}", filename)); } else if (mbFile.Url == filename) { itTrackPath = filename; } else { // Track was converted to a format that iTunes accepts... // Create a unique name for the converted file and store it in the MB file record var trackGUID = mbFile.ReencodingFileName; if (string.IsNullOrEmpty(trackGUID)) { trackGUID = Guid.NewGuid().ToString(); mbFile.ReencodingFileName = trackGUID; mbFile.CommitChanges(); } itTrackPath = Path.Combine(ReencodedFilesStorage, trackGUID + item.Value[1]); File.Copy(filename, itTrackPath, true); } var itKey = mbFile.ITunesKey; // Track was synced before if (itKey != 0) { itTrack = iTunes.GetTrackByPersistentId(itKey); if (itTrack == null) { Trace.WriteLine("A file in MusicBee appears to have been sync'ed to iTunes before but is not found in iTunes: " + mbFile.Url); itKey = 0; } else if (!mbFile.WebFile) { //Local or local network file ((IITFileOrCDTrack)itTrack).UpdateInfoFromFile(); } } // Track was never synced before or was deleted from iTunes library if (itTrack == null) { if (mbFile.WebFile) { itTrack = iTunes.LibraryPlaylist.AddURL(itTrackPath); } else { var operation = iTunes.LibraryPlaylist.AddFile(itTrackPath).Await(); var tracks = operation.Tracks; itTrack = tracks[1]; Marshal.ReleaseComObject(tracks); Marshal.ReleaseComObject(operation); itKey = iTunes.GetPersistentId(itTrack); mbFile.ITunesKey = itKey; mbFile.CommitChanges(); } } // Sync ratings & play counts to iTunes itTrack.SyncMusicBeeHistoryToITunes(mbFile); mbFile.SyncFileTimestamp(itTrackPath); Marshal.ReleaseComObject(itTrack); trackKeys[itKey] = mbFile; success = true; errorMessage = null; } catch (Exception ex) { Trace.WriteLine(ex); lastEx = ex; if (errorMessage == null) { errorMessage = ex.Message; } } finally { Plugin.MbApiInterface.Sync_FileEnd(item.Value[0], success, errorMessage); } } } // Remove non-sync'ed tracks foreach (var track in iTunes.GetAllTracks()) { var key = iTunes.GetPersistentId(track); if (!trackKeys.ContainsKey(key)) { Plugin.MbApiInterface.MB_SetBackgroundTaskMessage(Text.L("Removing track: \"{0}\"", track.Name)); track.Delete(); } Marshal.ReleaseComObject(track); } // Remove non-sync'ed playlists and populate the remaining ones foreach (var playlist in iTunes.GetPlaylists()) { var key = iTunes.GetPersistentId(playlist); if (playlistKeys.ContainsKey(key)) { Plugin.MbApiInterface.MB_SetBackgroundTaskMessage(Text.L("Clearing playlist: \"{0}\"", playlist.Name)); playlist.DeleteAllTracks(); var m = 0; var playlistFiles = MusicBeeFile.GetPlaylistFiles(playlistKeys[key]).ToArray(); foreach (var playlistFile in playlistFiles) { m++; Plugin.MbApiInterface.MB_SetBackgroundTaskMessage(Text.L("Adding track {0} of {1} to playlist: \"{2}\"", m, playlistFiles.Length, playlist.Name)); iTunes.AddTrackToPlaylistByPersistentId(playlist, playlistFile.ITunesKey); } } else { Plugin.MbApiInterface.MB_SetBackgroundTaskMessage(Text.L("Removing playlist: \"{0}\"", playlist.Name)); playlist.Delete(); } Marshal.ReleaseComObject(playlist); } return(lastEx == null); } catch (Exception ex) { Trace.WriteLine(ex); MbApiInterface.MB_SendNotification(CallbackType.StorageFailed); lastEx = ex; return(false); } finally { Plugin.MbApiInterface.MB_SetBackgroundTaskMessage(""); SynchronizationInProgress = false; } }
private static void StartServer() { var serv = new TwitterService(AuthVars.ConsumerKey, AuthVars.ConsumerSecret); serv.AuthenticateWith(AuthVars.TokenPublic, AuthVars.TokenSecret); string song = null; string artist = null; string album = null; var iT = new iTunesApp(); var currPl = (iT.LibrarySource.Playlists.ItemByName["C# Interface"] ?? iT.CreatePlaylist("C# Interface")) as IITUserPlaylist; if (currPl == null) { Console.WriteLine("Could not find or create playlist. Exiting"); throw new Exception("Could not find or create playlist. Exiting"); } TwitterStatus tw = null; while (true) { List<TwitterStatus> tweets = tw != null ? new List<TwitterStatus>(serv.ListTweetsMentioningMe(new ListTweetsMentioningMeOptions { SinceId = tw.Id })) : new List<TwitterStatus>(serv.ListTweetsMentioningMe(new ListTweetsMentioningMeOptions())); tweets = tweets.Where(s => s.Text.Substring(s.Text.IndexOf(" ", StringComparison.Ordinal) + 1).Replace("&", "&").StartsWith("DJ:")).ToList(); if (tweets.Count > 0) { tweets.Reverse(); foreach (var tweet in tweets) { tw = tweet; IITTrack t = null; var tweetText = tweet.Text; tweetText = tweetText.Substring(tweetText.IndexOf(" ", StringComparison.Ordinal) + 1).Replace("&", "&"); if (tweetText.Contains("|")) { tweetText = tweetText.Substring(tweetText.IndexOf("DJ:", StringComparison.Ordinal) + "DJ:".Length); var songParts = tweetText.Split('|'); foreach (var part in songParts) { Console.Write(part); Console.Write("||"); } Console.WriteLine(); song = songParts[1].Trim().ToUpper(); artist = songParts[0].Trim().ToUpper(); album = songParts.Length == 3 ? songParts[2].Trim().ToUpper() : ""; string searchText = song + " " + artist + " " + album; var s = iT.LibraryPlaylist.Search(searchText, ITPlaylistSearchField.ITPlaylistSearchFieldVisible); t = s.Cast<IITTrack>().First(t2 => t2.Name.ToUpper() == song && t2.Artist.ToUpper() == artist && (t2.Album.ToUpper() == album || album == "")); Console.WriteLine(t.Artist + "||" + t.Album + "||" + t.Name); } else if (tweetText.ToUpper().Contains("SHUFFLE") || tweetText.ToUpper().Contains("RANDOM")) { var rnd = new Random(10); var libSize = iT.LibraryPlaylist.Tracks.Count; var idx = rnd.Next(libSize); t = iT.LibraryPlaylist.Tracks.ItemByPlayOrder[idx]; song = t.Name; artist = t.Artist; album = t.Album; } var tInPl = currPl.Tracks; if (t != null && (tInPl.ItemByName[song] == null || tInPl.ItemByName[artist] == null)) { if (album != "") { if (tInPl.ItemByName[album] == null) currPl.AddTrack(t); } else { currPl.AddTrack(t); } } Console.WriteLine("\n**********************"); } Console.WriteLine("Waiting 30 seconds before checking again"); } else { Console.WriteLine("No tweets found, either new or old, waiting 30sec"); } System.Threading.Thread.Sleep(30000); } }
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; }
void playlistGenerator_DoWork(object sender, DoWorkEventArgs e) { bool breakExecution = false; this.BeginProgress(); this.SetProgress("Generating playlist", 0, 0); if (listBox.Items.Count > 0) { List <string> source = new List <string>(); foreach (string str in listBox.Items) { source.Add(str); } source = Engine.ShuffleList(source); List <Song> playlist = new List <Song>(); foreach (string key in source) { if (playlist.Count % 4 == 0) { playlist.Add(library.GetBumper()); } playlist.Add(library.GetTrack(key)); if (playlist[playlist.Count - 1] == null) { MessageBox.Show(string.Format("{0} does not match a track in the iTunes library", key)); breakExecution = true; break; } } if (library.SignoffFound) { playlist.Add(library.GetSignoff()); } if (!breakExecution) { string dateString = DateTime.Now.ToString("M/d/yy H:mm:ss"); int playlistCount = 1; if (this.limitCheckBox.Checked) { playlistCount = (int)Math.Ceiling(playlist.Count / this.limitNumericUpDown.Value); } List <IITUserPlaylist> itplaylists = new List <IITUserPlaylist>(); for (int x = 0; x < playlistCount; x++) { itplaylists.Add((IITUserPlaylist)app.CreatePlaylist("JRay-FM " + dateString + (playlistCount > 1 ? string.Format(" {0}/{1}", x + 1, playlistCount) : string.Empty))); } int trackCount = 0; int playlistIndex = 0; foreach (Song track in playlist) { itplaylists[playlistIndex].AddFile(track.Path); trackCount++; if (playlistIndex < playlistCount - 1 && trackCount >= this.limitNumericUpDown.Value) { trackCount = 0; playlistIndex++; } } } } this.EndProgress(); }
private static void MakeFolderPlaylist(iTunesApp app, string name, IEnumerable<IITFileOrCDTrack> tracks) { var playlist = app.CreatePlaylist(name) as IITUserPlaylist; if (playlist == null) { throw new InvalidOperationException("no playlist found!"); } foreach (var track in tracks.OrderBy(t=>t.TrackNumber).ThenBy(t=>t.Location)) { var currentTrack = track as object; playlist.AddTrack(ref currentTrack); } }