Exemplo n.º 1
0
        public static void PrintTrack(SpotifySession aSession, Track aTrack)
        {
            int duration = aTrack.Duration();

            Console.Write(" {0} ", Track.IsStarred(aSession, aTrack) ? "*" : " ");
            Console.Write("Track {0} [{1}:{2:D02}] has {3} artist(s), {4}% popularity",
                          aTrack.Name(),
                          duration / 60000,
                          (duration / 1000) % 60,
                          aTrack.NumArtists(),
                          aTrack.Popularity());
            if (aTrack.Disc() != 0)
            {
                Console.Write(", {0} on disc {1}",
                              aTrack.Index(),
                              aTrack.Disc());
            }
            for (int i = 0; i < aTrack.NumArtists(); ++i)
            {
                var artist = aTrack.Artist(i);
                Console.Write("\tArtist {0}: {1}", i + 1, artist.Name());
            }
            var link = Link.CreateFromTrack(aTrack, 0);

            Console.WriteLine("\t\t{0}", link.AsString());
            link.Release();
        }
Exemplo n.º 2
0
 public PlaylistManager(SpotifySession aSession, IConsoleReader aConsoleReader, Browser aBrowser)
 {
     iSession       = aSession;
     iConsoleReader = aConsoleReader;
     iBrowser       = aBrowser;
     iCallbacks     = new Callbacks(this);
 }
Exemplo n.º 3
0
        public override int MusicDelivery(SpotifySession session, AudioFormat format, IntPtr frames, int num_frames)
        {
            if (num_frames == 0)
            {
                return(0);
            }

            var size = num_frames * format.channels * 2;
            var data = new byte[size];

            Marshal.Copy(frames, data, 0, size);

            wr.Write(data);

            if (OnDownloadProgress != null)
            {
                counter++;
                var duration = downloadingTrack.Duration();
                var process  = (int)Math.Round((double)100 / duration * (46.4 * counter), 0);
                OnDownloadProgress(process);
            }

            return(num_frames);
            // return base.MusicDelivery(session, format, frames, num_frames);
        }
Exemplo n.º 4
0
        public SpotifyDownloader()
        {
            tmpPath      = Downtify.GUI.frmMain.configuration.GetConfiguration("cache", "cache/");
            downloadPath = Downtify.GUI.frmMain.configuration.GetConfiguration("download", "download/");

            if (!Directory.Exists(tmpPath))
            {
                Directory.CreateDirectory(tmpPath);
            }

            if (!Directory.Exists(downloadPath))
            {
                Directory.CreateDirectory(downloadPath);
            }

            var config = new SpotifySessionConfig()
            {
                ApiVersion       = 12,
                CacheLocation    = tmpPath,
                SettingsLocation = tmpPath,
                ApplicationKey   = File.ReadAllBytes("spotify_appkey.key"),
                UserAgent        = "downtify",
                Listener         = this
            };

            syncContext = SynchronizationContext.Current;
            session     = SpotifySession.Create(config);
        }
Exemplo n.º 5
0
 public static async Task <ApiClient> BuildApiClient([NotNull] SpotifySession session)
 {
     return(new ApiClient()
     {
         Home = await CreateAndRegister <IHome>(session),
         Library = await CreateAndRegister <ILibrary>(session),
         User = await CreateAndRegister <IUserService>(session),
         Player = await CreateAndRegister <IPlayer>(session),
         PathFinder = await CreateAndRegister <IPathFinder>(session),
         Track = await CreateAndRegister <ITrack>(session),
         Playlist = await CreateAndRegister <IPlaylist>(session),
         PlaylistExtender = await CreateAndRegister <IPlaylistExtender>(session),
         StorageResolve = await CreateAndRegister <IStorageResolveService>(session),
         Metadata = await CreateAndRegister <IMetadata>(session),
         ConnectState = await CreateAndRegister <IConnectState>(session),
         Melody = await CreateAndRegister <IMelody>(session),
         Follow = await CreateAndRegister <IFollow>(session),
         Search = await CreateAndRegister <ISearch>(session),
         Artist = await CreateAndRegister <IArtist>(session),
         Album = await CreateAndRegister <IAlbum>(session),
         OpenArtist = await CreateAndRegister <IOpenIArtist>(session),
         SeekTableService = await CreateAndRegister <ISeektables>(session),
         LicenseService = await CreateAndRegister <IPlaybackLicense>(session),
         CanvazService = new CanvazService()
     });
 }
        public SpotifyDownloader()
        {
            if (!Directory.Exists(_tmpPath))
            {
                Directory.CreateDirectory(_tmpPath);
            }

            if (!Directory.Exists(_downloadPath))
            {
                Directory.CreateDirectory(_downloadPath);
            }

            var config = new SpotifySessionConfig()
            {
                ApiVersion       = 12,
                CacheLocation    = _tmpPath,
                SettingsLocation = _tmpPath,
                ApplicationKey   = File.ReadAllBytes("spotify_appkey.key"),
                UserAgent        = "downtify",
                Listener         = this
            };

            _syncContext = SynchronizationContext.Current;
            _session     = SpotifySession.Create(config);
        }
Exemplo n.º 7
0
 private void Pause()
 {
     SpotifySession.PlayerPause();
     isPaused      = true;
     player.Paused = true;
     CF_setPlayPauseButton(true, _zone);
 }
Exemplo n.º 8
0
        void PlaybackMonitor_Tick(object sender, EventArgs e)
        {
            if (currentTrack == null)
            {
                throw new Exception("Playback monitor started, but no track playing");
            }

            var position = player.Position + currentTrackPositionOffset;
            var duration = currentTrack.Duration;

            if (position >= duration)
            {
                this.ParentForm.BeginInvoke(new MethodInvoker(delegate()
                {
                    if (!PlayNextTrack(false))
                    {
                        currentTrack = null;
                        SpotifySession.PlayerUnload();
                        PlaybackMonitor.Stop();
                        player.Stop();
                        isPaused = false;
                        currentTrackPositionOffset = new TimeSpan(0);
                    }
                }));
            }
        }
Exemplo n.º 9
0
        public override int MusicDelivery(SpotifySession session, AudioFormat format, IntPtr frames, int num_frames)
        {
            if (num_frames == 0)
            {
                return(0);
            }

            var size = num_frames * format.channels * 2;
            var data = new byte[size];

            Marshal.Copy(frames, data, 0, size);

            wr.Write(data);

            if (OnDownloadProgress != null)
            {
                counter++;
                var duration = downloadingTrack.Duration();
                // Todo: Find out how to calculate this correctly,
                // so far 46.4 is used to calculate the process
                // but there should be a way to calculate this
                // with the given variables
                var process = (int)Math.Round((double)100 / duration * (46.4 * counter), 0);
                OnDownloadProgress(process);
            }

            return(num_frames);
            // return base.MusicDelivery(session, format, frames, num_frames);
        }
Exemplo n.º 10
0
        public SpotifyDownloader()
        {
            if (!Directory.Exists(tmpPath))
            {
                Directory.CreateDirectory(tmpPath);
            }

            if (!Directory.Exists(downloadPath))
            {
                Directory.CreateDirectory(downloadPath);
            }

            var config = new SpotifySessionConfig()
            {
                ApiVersion       = 12,
                CacheLocation    = tmpPath,
                SettingsLocation = tmpPath,
                ApplicationKey   = File.ReadAllBytes("spotify_appkey.key"),
                UserAgent        = "downtify",
                Listener         = this
            };

            syncContext = SynchronizationContext.Current;
            session     = SpotifySession.Create(config);
            Task.Factory.StartNew(() => InvokeProcessEvents());
        }
Exemplo n.º 11
0
 private void SeekCurrentTrack(int milliseconds)
 {
     player.Stop();
     currentTrackPositionOffset = new TimeSpan(0, 0, 0, 0, milliseconds);
     player.ReadyPlay();
     SpotifySession.PlayerSeek(milliseconds);
 }
Exemplo n.º 12
0
        public override async void LoggedIn(SpotifySession session, SpotifyError error)
        {
            base.LoggedIn(session, error);
            await WaitForBool(session.User().IsLoaded);

            session.PreferredBitrate(BitRate._320k);
        }
Exemplo n.º 13
0
 public override void LogMessage(SpotifySession session, string data)
 {
     if (iLogToStderr)
     {
         Console.Error.WriteLine(data);
     }
 }
Exemplo n.º 14
0
 public Browser(SpotifySession aSession, IMetadataWaiter aMetadataWaiter, IConsoleReader aConsoleReader)
 {
     iSession          = aSession;
     iMetadataWaiter   = aMetadataWaiter;
     iConsoleReader    = aConsoleReader;
     iPlaylistListener = new BrowsingPlaylistListener(this);
 }
Exemplo n.º 15
0
 private void Play()
 {
     player.ReadyPlay();
     player.Paused = false;
     SpotifySession.PlayerPlay();
     isPaused = false;
     CF_setPlayPauseButton(false, _zone);
 }
Exemplo n.º 16
0
        private static async Task UpdateMelody([NotNull] SpotifySession _sess)
        {
            var time = await _sess.Api().Melody.GetTime();

            var diff = time.timestamp - CurrentTimeMillisSystem();

            Interlocked.Exchange(ref _offset, diff);
        }
Exemplo n.º 17
0
 public void Dispose()
 {
     if (iSession != null)
     {
         iSession.Dispose();
     }
     iSession = null;
 }
Exemplo n.º 18
0
        public void SetSpotifySession(string oneTimeCode, SpotifySession spotifySession)
        {
            memoryCache.Remove(oneTimeCode);
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                                    .SetAbsoluteExpiration(tokenTimeout);

            memoryCache.Set(oneTimeCode, spotifySession, cacheEntryOptions);
        }
Exemplo n.º 19
0
        private void LoadImage(string imageId)
        {
            currentImageId = imageId;

            CF_clearPictureImage("pictureBox");
            if (currentImage != null)
            {
                currentImage.Dispose();
            }

            if (!string.IsNullOrEmpty(imageId))
            {
                ThreadPool.QueueUserWorkItem(delegate(object obj)
                {
                    try
                    {
                        var image = SpotifySession.GetImageFromId(imageId);
                        image.WaitForLoaded(); //and it's not really loaded yet :(
                        if (imageId.Equals(currentImageId))
                        {
                            for (int i = 0; i < 60; i++)
                            {
                                if (image.Format == sp_imageformat.SP_IMAGE_FORMAT_UNKNOWN)
                                {
                                    Thread.Sleep(1000);
                                }
                                else
                                {
                                    break;
                                }
                            }

                            var imageObject = image.GetImage();
                            if (imageId.Equals(currentImageId))
                            {
                                imageObject = ResizeToFitBox(imageObject);
                                this.ParentForm.BeginInvoke(new MethodInvoker(delegate()
                                {
                                    if (imageId.Equals(currentImageId))
                                    {
                                        currentImage = imageObject;
                                        CF_setPictureImage("pictureBox", imageObject);
                                    }
                                    else
                                    {
                                        imageObject.Dispose();
                                    }
                                }));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteError(ex);
                    }
                });
            }
        }
Exemplo n.º 20
0
        public override void MetadataUpdated(SpotifySession session)
        {
            Action callbacks = iMetadataUpdatedCallbacks;

            if (callbacks != null)
            {
                callbacks();
            }
        }
Exemplo n.º 21
0
 public void StopAllPlayback()
 {
     currentTrack = null;
     SpotifySession.PlayerUnload();
     isPaused = false;
     currentTrackPositionOffset = new TimeSpan(0);
     player.Stop();
     PlaybackMonitor.Stop();
 }
Exemplo n.º 22
0
        public static PagesLoader From([NotNull] SpotifySession session, [NotNull] String context)
        {
            var loader = new PagesLoader(session)
            {
                _resolveUrl = context
            };

            return(loader);
        }
Exemplo n.º 23
0
 public override void ConnectionstateUpdated(SpotifySession session)
 {
     if (session.Connectionstate() == ConnectionState.LoggedIn)
     {
         OnLoginResult?.Invoke(true);
     }
     Console.WriteLine(session.Connectionstate().ToString());
     base.ConnectionstateUpdated(session);
 }
Exemplo n.º 24
0
        public override async void EndOfTrack(SpotifySession session)
        {
            session.PlayerPlay(false);
            wr.Close();

            // Move File
            var dir = downloadPath + escape(downloadingTrack.Album().Name()) + "\\";

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            var fileName = dir + escape(GetTrackFullName(downloadingTrack)) + ".mp3";

            if (GetDownloadType() == DownloadType.OVERWRITE && File.Exists(fileName))
            {
                File.Delete(fileName);
            }
            File.Move("downloading", fileName);

            // Tag
            var u = new UltraID3();

            u.Read(fileName);
            u.Artist   = GetTrackArtistsNames(downloadingTrack);
            u.Title    = downloadingTrack.Name();
            u.Album    = downloadingTrack.Album().Name();
            u.TrackNum = (short)downloadingTrack.Index();
            u.Year     = (short)downloadingTrack.Album().Year();

            var imageID = downloadingTrack.Album().Cover(ImageSize.Large);
            var image   = SpotifySharp.Image.Create(session, imageID);

            await WaitForBool(image.IsLoaded);

            var tc  = TypeDescriptor.GetConverter(typeof(Bitmap));
            var bmp = (Bitmap)tc.ConvertFrom(image.Data());

            var pictureFrame = new ID3v23PictureFrame(bmp, PictureTypes.CoverFront, "image", TextEncodingTypes.ISO88591);

            u.ID3v2Tag.Frames.Add(pictureFrame);

            u.Write();

            base.EndOfTrack(session);

            if (OnDownloadProgress != null)
            {
                OnDownloadProgress(100);
            }

            if (OnDownloadComplete != null)
            {
                OnDownloadComplete(true);
            }
        }
Exemplo n.º 25
0
 public override int MusicDelivery(SpotifySession session, AudioFormat format, IntPtr frames, int num_frames)
 {
     if (MusicDataAvailable != null)
     {
         MusicDeliveryEventArgs args = new MusicDeliveryEventArgs(frames, num_frames, format.sample_rate, format.channels, 16);
         MusicDataAvailable(this, args);
         return(args.NumFramesRead);
     }
     return(0);
 }
Exemplo n.º 26
0
 public override void PlayTokenLost(SpotifySession session)
 {
     if (_TrackDownloadService != null)
     {
         if (_TrackDownloadService.Active)
         {
             _TrackDownloadService.Cancel(TrackDownloadService.CancellationReason.PlayTokenLost);
         }
     }
 }
Exemplo n.º 27
0
        public override async void LoggedIn(SpotifySession session, SpotifyError error)
        {
            if (error == SpotifyError.Ok)
            {
                await SpotifyObject.WaitForInitialization(session.User().IsLoaded);

                _Session.PreferredBitrate(BitRate._320k);
            }

            _LoggedInCallback(error);
        }
Exemplo n.º 28
0
 public SpotifyPlayer(SpotifySession session,
                      ISpotifyDevice device,
                      uint initialVolume,
                      int volumeSteps)
 {
     _session    = session;
     this.events = new EventsDispatcher(this);
     Device      = device;
     InitState(initialVolume, volumeSteps);
     Current = this;
 }
Exemplo n.º 29
0
 public override void GetAudioBufferStats(SpotifySession session, out AudioBufferStats stats)
 {
     stats         = new AudioBufferStats();
     stats.samples = 0;
     stats.stutter = 0;
     if (CheckBuffer != null)
     {
         CheckBufferEventArgs args = new CheckBufferEventArgs();
         CheckBuffer(this, args);
         stats.samples = args.NumberOfSamples / 4;
     }
 }
Exemplo n.º 30
0
        public SpotifyPlayerSession([NotNull] SpotifySession session,
                                    [NotNull] ISpotifyDevice sink,
                                    [NotNull] String sessionId,
                                    [NotNull] IPlayerSessionListener listener)
        {
            this.session   = session;
            this.sink      = sink;
            this.sessionId = sessionId;
            this.listener  = listener;
            this.queue     = new PlayerQueue();
            Debug.WriteLine($"Created new session. id: {sessionId}");

            //todo: clear sink
        }