Example #1
0
        public bool IsScrobblingPossible(SocialProvider provider)
        {
            bool possible = false;

            ThrowHelper.ThrowIfError(LibSpotify.sp_session_is_scrobbling_possible_r(Handle, provider, ref possible));
            return(possible);
        }
Example #2
0
        public IAsyncResult BeginLoadImage(Session session, AsyncCallback userCallback, object state)
        {
            byte[] imageId = new byte[20];

            bool hasImage = LibSpotify.sp_playlist_get_image_r(Handle, imageId);

            if (!hasImage)
            {
                AsyncLoadImageResult result = new AsyncLoadImageResult(userCallback, state);
                result.CompletedSynchronously = true;
                result.SetCallbackComplete();
                result.SetCompleted(Error.Ok);
                return(result);
            }

            IntPtr p = System.Runtime.InteropServices.Marshal.AllocHGlobal(imageId.Length);

            try
            {
                System.Runtime.InteropServices.Marshal.Copy(imageId, 0, p, imageId.Length);
                return(ImageLoader.Begin((ptr, size) => { return ptr; }, p, session, ImageSize.Normal, userCallback, state));
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.FreeHGlobal(p);
            }
        }
Example #3
0
        public ScrobblingState GetScrobbling(SocialProvider provider)
        {
            ScrobblingState state = ScrobblingState.GlobalDisabled;

            ThrowHelper.ThrowIfError(LibSpotify.sp_session_is_scrobbling_r(Handle, provider, ref state));
            return(state);
        }
Example #4
0
        public IAsyncResult BeginArtistBrowse(Artist artist, ArtistBrowseType browseType, AsyncCallback userCallback, object state)
        {
            AsyncArtistBrowseResult result = new AsyncArtistBrowseResult(userCallback, state);

            LibSpotify.sp_artistbrowse_create_r(Handle, artist.Handle, browseType, result.HandleBrowseComplete, IntPtr.Zero);
            return(result);
        }
Example #5
0
        public IAsyncResult BeginLoadPlaylistContainer(AsyncCallback userCallback, object state)
        {
            IntPtr p = LibSpotify.sp_session_playlistcontainer_r(Handle);

            if (p == IntPtr.Zero)
            {
                return new AsyncLoadableResult <PlaylistContainer>(
                    null,
                    (container) => { return Error.Ok; },
                    userCallback,
                    state)
                       {
                           CompletedSynchronously = true
                       }
            }
            ;

            PlaylistContainer playlistContainer = new PlaylistContainer(p, false);

            return(AsyncLoadableResult <PlaylistContainer> .Begin(
                       playlistContainer,
                       (container) => { return Error.Ok; },
                       userCallback,
                       state));
        }
Example #6
0
        private int OnMusicDelivery(IntPtr sessionHandle, IntPtr audioFormatHandle, IntPtr frames, int numFrames)
        {
            if (numFrames == 0)
            {
                return(0);
            }

            if (frames == IntPtr.Zero)
            {
                return(0);
            }

            AudioFormat audioFormat = LibSpotify.AudioFormatFromHandle(audioFormatHandle);

            int n = numFrames * FrameSize(audioFormat);

            byte[] pcmData = new byte[n];

            Marshal.Copy(frames, pcmData, 0, n);

            EventDispatcher.Dispatch(this, sessionHandle, MusicDelivered,
                                     new MusicDeliveryEventArgs(pcmData, audioFormat));

            pcmData = null;

            return(numFrames);
        }
Example #7
0
        public long GetPlaylistFolderId(Playlist playList)
        {
            // TODO: Does this really need uint64?
            ulong id = LibSpotify.sp_playlistcontainer_playlist_folder_id_r(Handle, playList.Index);

            return(Convert.ToInt64(id));
        }
Example #8
0
        public void ReorderTracks(IEnumerable <Track> tracks, int position)
        {
            int[] indices = tracks.Select(t => t.Index).ToArray();
            ThrowIfDuplicates(indices);

            ThrowHelper.ThrowIfError(
                LibSpotify.sp_playlist_reorder_tracks_r(Handle, indices, indices.Length, position));
        }
Example #9
0
 public static void ThrowIfError(Error e, string message)
 {
     if (e != Error.Ok)
     {
         string s = string.Format("{0}. {0}", message, LibSpotify.sp_error_message(e));
         throw new Spotify.Exception(e, s);
     }
 }
Example #10
0
        public string GetPlaylistFolderName(Playlist playList)
        {
            StringBuilder builder = new StringBuilder(512);

            ThrowHelper.ThrowIfError(LibSpotify.sp_playlistcontainer_playlist_folder_name_r(Handle, playList.Index,
                                                                                            builder, builder.Capacity));

            return(builder.ToString());
        }
Example #11
0
        public void ClearUnseenTracks(Playlist playList)
        {
            int ret = LibSpotify.sp_playlistcontainer_clear_unseen_tracks_r(Handle, playList.Handle);

            if (ret == -1)
            {
                throw new InvalidOperationException("failed to clear unseen tracks"); // why?
            }
        }
Example #12
0
        public Track ToTrack(ref TimeSpan offset)
        {
            ThrowHelper.AssertLinkConverstion(LinkType, LinkType.Track);

            int   n = 0;
            Track t = new Track(LibSpotify.sp_link_as_track_and_offset_r(Handle, ref n), false);

            offset = TimeSpan.FromMilliseconds(n);
            return(t);
        }
Example #13
0
        private TimeSpan ProcessEventsInternal()
        {
            int nextTimeout = 0;

            lock (_lock)
            {
                ThrowHelper.ThrowIfError(LibSpotify.sp_session_process_events_r(Handle, ref nextTimeout));
            }
            return(TimeSpan.FromMilliseconds(nextTimeout));
        }
Example #14
0
        public IAsyncResult BeginLogin(LoginParameters loginParams, AsyncCallback userCallback, object stateObject)
        {
            AsyncLoginResult result = new AsyncLoginResult(userCallback, stateObject);

            this.LoggedIn += result.HandleLoggedIn;

            ThrowHelper.ThrowIfError(LibSpotify.sp_session_login_r(Handle, loginParams.UserName,
                                                                   loginParams.Password, loginParams.RememberMe, IntPtr.Zero));

            return(result);
        }
Example #15
0
        public IAsyncResult BeginBrowse(Session session, AsyncCallback userCallback, object state)
        {
            Internal.ThrowHelper.ThrowIfNull(session, "session");
            Internal.ThrowHelper.ThrowIfNull(userCallback, "userCallback");

            BrowseResult browseResult = new BrowseResult(userCallback, state);

            LibSpotify.sp_albumbrowse_create_r(session.Handle, Handle, browseResult.Complete, IntPtr.Zero);

            return(browseResult);
        }
Example #16
0
        internal PlaylistContainer(IntPtr handle, bool preIncremented = true)
            : base(handle, LibSpotify.sp_playlistcontainer_add_ref_r, LibSpotify.sp_playlistcontainer_release_r, preIncremented)
        {
            LibSpotify.sp_playlistcontainer_callbacks callbacks = new LibSpotify.sp_playlistcontainer_callbacks();
            callbacks.playlist_added   = OnPlaylistAdded;
            callbacks.playlist_removed = OnPlaylistRemoved;
            callbacks.playlist_moved   = OnPlaylistMoved;
            callbacks.container_loaded = OnContainerLoaded;

            ThrowHelper.ThrowIfError(LibSpotify.sp_playlistcontainer_add_callbacks_r(Handle,
                                                                                     ref callbacks, IntPtr.Zero));
        }
Example #17
0
        protected override void Dispose(bool disposing)
        {
            if (IsDisposed)
            {
                return;
            }

            if (disposing)
            {
                LibSpotify.sp_image_remove_load_callback_r(Handle, OnImageLoaded, IntPtr.Zero);
            }

            base.Dispose(disposing);
        }
Example #18
0
        public static void SetStarred(Session session, IList <Track> tracks, bool starred)
        {
            ThrowHelper.ThrowIfNull(session, "session");
            ThrowHelper.ThrowIfNull(tracks, "tracks");

            if (tracks.Count > 0)
            {
                IntPtr[] trackHandles = new IntPtr[tracks.Count];
                for (int i = 0; i < tracks.Count; ++i)
                {
                    trackHandles[i] = tracks[i].Handle;
                }

                ThrowHelper.ThrowIfError(LibSpotify.sp_track_set_starred_r(session.Handle, trackHandles,
                                                                           trackHandles.Length, starred));
            }
        }
Example #19
0
        public IList <Track> GetUnseenTracks(Playlist playlist)
        {
            IntPtr[] unseen = new IntPtr[1024];

            int n = LibSpotify.sp_playlistcontainer_get_unseen_tracks_r(Handle, playlist.Handle, unseen, unseen.Length);

            System.Diagnostics.Debug.Assert(n < unseen.Length);

            List <Track> tracks = new List <Track>();

            for (int i = 0; i < n; ++i)
            {
                tracks.Add(new Track(unseen[i], false));
            }

            return(tracks);
        }
Example #20
0
        public static IAsyncResult Begin(ImageLoad load, IntPtr p, Session session, ImageSize size,
                                         AsyncCallback userCallback, object state)
        {
            AsyncLoadImageResult result = new AsyncLoadImageResult(userCallback, state);
            Image image = new Image(LibSpotify.sp_image_create_r(session.Handle, load(p, size)));

            result.Closure = image;
            image.Loaded  += result.HandleImageLoaded;

            // It's possible the image loaded before we registered the result.HandleImageLoaded
            if (image.IsLoaded)
            {
                result.CompletedSynchronously = true;
                result.SetCompleted(image.Error);
            }

            return(result);
        }
Example #21
0
        // There are so many "Changed" Events. I wonder if using PropertyChange is more appropriate.
        // public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        internal Playlist(IntPtr handle, bool preIncremented = true)
            : base(handle, LibSpotify.sp_playlist_add_ref_r, LibSpotify.sp_playlist_release_r, preIncremented)
        {
            _callbacks = new LibSpotify.sp_playlist_callbacks();
            _callbacks.description_changed         = OnDescriptionChanged;
            _callbacks.image_changed               = OnImageChanged;
            _callbacks.playlist_metadata_updated   = OnMetadataUpdated;
            _callbacks.playlist_renamed            = OnRenamed;
            _callbacks.playlist_state_changed      = OnStateChanged;
            _callbacks.playlist_update_in_progress = OnUpdateInProgress;
            _callbacks.subscribers_changed         = OnSubscribersChanged;
            _callbacks.track_created_changed       = OnCreatedChanged;
            _callbacks.track_message_changed       = OnMessageChanged;
            _callbacks.track_seen_changed          = OnSeenChanged;
            _callbacks.tracks_added   = OnTracksAdded;
            _callbacks.tracks_moved   = OnTracksMoved;
            _callbacks.tracks_removed = OnTracksRemoved;

            ThrowHelper.ThrowIfError(LibSpotify.sp_playlist_add_callbacks_r(Handle, ref _callbacks, IntPtr.Zero));
        }
Example #22
0
        public IAsyncResult BeginSearch(SearchParameters searchParams, AsyncCallback userCallback, object state)
        {
            ThrowHelper.ThrowIfNull(searchParams, "searchParams");
            AsyncSearchResult searchResult = new AsyncSearchResult(userCallback, state);

            LibSpotify.sp_search_create_r(
                Handle,
                searchParams.Query,
                searchParams.TrackOffset,
                searchParams.TrackCount,
                searchParams.AlbumOffset,
                searchParams.AlbumCount,
                searchParams.ArtistOffset,
                searchParams.AlbumCount,
                searchParams.PlaylistOffset,
                searchParams.PlaylistCount,
                searchParams.SearchType,
                searchResult.SearchComplete,
                IntPtr.Zero);

            return(searchResult);
        }
Example #23
0
        private void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            // make sure we dispose of any DomainOjects that are still around instead of
            // waiting for the finalizer, otherwise we get exceptions from the unmanaged
            // layer when we try to release objects after releasing the session
            DomainObject.DisposeAllRemaingObjects();

            System.Diagnostics.Debug.Assert(Handle != IntPtr.Zero);
            if (Handle != IntPtr.Zero)
            {
                LibSpotify.sp_session_release_r(Handle);
            }


            Handle    = IntPtr.Zero;
            _disposed = true;
        }
Example #24
0
        public OfflineSyncStatus GetOfflineSyncStatus()
        {
            OfflineSyncStatus syncStatus = null;

            LibSpotify.sp_offline_sync_status status = new LibSpotify.sp_offline_sync_status();
            if (LibSpotify.sp_offline_sync_get_status_r(Handle, ref status))
            {
                syncStatus = new OfflineSyncStatus()
                {
                    QueuedBytes       = Convert.ToInt64(status.queued_bytes),
                    QueuedTracks      = status.queued_tracks,
                    DoneBytes         = Convert.ToInt64(status.done_bytes),
                    DoneTracks        = status.done_tracks,
                    CopiedBytes       = Convert.ToInt64(status.copied_bytes),
                    CopiedTracks      = status.copied_tracks,
                    WillNotCopyTracks = status.willnotcopy_tracks,
                    ErorrTracks       = status.error_tracks,
                    Syncing           = status.syncing
                };
            }
            return(syncStatus);
        }
Example #25
0
        private static IList <string> MarshalPlaylistSubscribers(IntPtr playlist)
        {
            List <string> subscribers = new List <string>();

            IntPtr p = LibSpotify.sp_playlist_subscribers_r(playlist);

            if (p != IntPtr.Zero)
            {
                int n = Marshal.ReadInt32(p);

                int offset = Marshal.SizeOf(typeof(Int32));
                for (int i = 0; i < n; ++i)
                {
                    subscribers.Add(LibSpotify.ReadUtf8(Marshal.ReadIntPtr(p, offset)));
                    offset += Marshal.SizeOf(typeof(IntPtr));
                }

                LibSpotify.sp_playlist_subscribers_free_r(p);
            }

            return(subscribers);
        }
Example #26
0
        public IAsyncResult BeginLoadPortraits(Session session, AsyncCallback userCallback, object state)
        {
            ThrowHelper.ThrowIfNull(session, "session");

            int n = LibSpotify.sp_artistbrowse_num_portraits_r(Handle);
            AsyncLoadPortraitsResult result = new AsyncLoadPortraitsResult(n, userCallback, state);

            result.Closure = new List <Image>();

            for (int i = 0; i < n; ++i)
            {
                Image image = new Image(LibSpotify.sp_image_create_r(session.Handle, LibSpotify.sp_artistbrowse_portrait_r(Handle, i)));
                image.Loaded += result.HandleImageLoaded;
                result.Closure.Add(image);
            }

            if (result.CheckComplete())
            {
                result.CompletedSynchronously = true;
            }

            return(result);
        }
Example #27
0
 internal Exception(Error code)
     : base(LibSpotify.ReadUtf8(LibSpotify.sp_error_message_r(code)))
 {
     ErrorCode = code;
 }
Example #28
0
 private void OnGetAudioBufferStats(IntPtr sessionHandle, IntPtr statsHandle)
 {
     AudioBufferStats stats = LibSpotify.AudioBufferStatsFromHandle(statsHandle);
     //Dispatch(sessionHandle, OnAud)
 }
Example #29
0
        public static Session Create(SessionConfig sessionConfig)
        {
            Session session = new Session();

            IntPtr applicationKeyHandle = IntPtr.Zero;
            IntPtr callbacksHandle      = IntPtr.Zero;

            try
            {
                LibSpotify.sp_session_config config = new LibSpotify.sp_session_config();
                config.api_version = sessionConfig.ApiVersion;

                byte[] key = GetApplicationKey(sessionConfig);
                applicationKeyHandle = Marshal.AllocHGlobal(key.Length);
                Marshal.Copy(key, 0, applicationKeyHandle, key.Length);
                config.application_key = applicationKeyHandle;

                config.application_key_size             = new IntPtr(key.Length);
                config.cache_location                   = sessionConfig.CacheLocation;
                config.compress_playlists               = sessionConfig.CompressPlaylists;
                config.device_id                        = sessionConfig.DeviceId;
                config.dont_dave_metadata_for_playlists = sessionConfig.DontSaveMetadatForPlaylists;
                config.initially_unload_playlist        = sessionConfig.InitiallyUnloadPlaylists;
                config.proxy             = sessionConfig.Proxy;
                config.proxy_password    = sessionConfig.ProxyPassword;
                config.proxy_username    = sessionConfig.ProxyUserName;
                config.settings_location = sessionConfig.SettingsLocation;
                config.tracefile         = sessionConfig.TraceFile;
                config.user_agent        = sessionConfig.UserAgent;
                config.userdata          = IntPtr.Zero;

                session._callbacks                    = new LibSpotify.sp_session_callbacks();
                session._callbacks.logged_in          = session.OnLoggedInEvent;
                session._callbacks.logged_out         = session.OnLoggedOutEvent;
                session._callbacks.notify_main_thread = session.OnNotifyMainThread;

                session._callbacks.log_message                  = session.OnLogMessage;
                session._callbacks.metadata_updated             = session.OnMetadataUpdated;
                session._callbacks.connection_error             = session.OnConnectionError;
                session._callbacks.message_to_user              = session.OnMessageToUser;
                session._callbacks.music_delivery               = session.OnMusicDelivery;
                session._callbacks.play_token_lost              = session.OnPlayTokenLost;
                session._callbacks.log_message                  = session.OnLogMessage;
                session._callbacks.end_of_track                 = session.OnEndOfTrack;
                session._callbacks.streaming_error              = session.OnStreamingError;
                session._callbacks.userinfo_updated             = session.OnUserInfoUpdated;
                session._callbacks.start_playback               = session.OnStartPlayback;
                session._callbacks.stop_playback                = session.OnStopPlayback;
                session._callbacks.offline_status_updated       = session.OnOfflineStatusUpdated;
                session._callbacks.get_audio_buffer_stats       = session.OnGetAudioBufferStats;
                session._callbacks.offline_error                = session.OnOfflineError;
                session._callbacks.credentials_blob_updated     = session.OnCredentialsBlobUpdated;
                session._callbacks.connectionstate_updated      = session.OnConnectionStateUpdated;
                session._callbacks.scrobble_error               = session.OnScrobbleError;
                session._callbacks.private_session_mode_changed = session.OnPrivateSessionModeChanged;

                callbacksHandle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LibSpotify.sp_session_callbacks)));
                Marshal.StructureToPtr(session._callbacks, callbacksHandle, false);
                config.callbacks = callbacksHandle;

                IntPtr ptr = IntPtr.Zero;

                // This call results in a callback to OnNotifyMainThread, but the
                // actual _handle has not been set yet.
                session._running = true;
                ThrowHelper.ThrowIfError(LibSpotify.sp_session_create_r(ref config, ref ptr));
                session.Handle = ptr;
            }
            finally
            {
                if (applicationKeyHandle != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(applicationKeyHandle);
                }

                if (callbacksHandle != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(callbacksHandle);
                }
            }

            return(session);
        }
Example #30
0
 public void SetSocialCredentials(SocialProvider provider, string username, string password)
 {
     ThrowHelper.ThrowIfError(LibSpotify.sp_session_set_social_credentials_r(Handle, provider,
                                                                             username, password));
 }