Ejemplo n.º 1
0
 public int GetPlaying()
 {
     try
     {
         return(SpotifySession.GetPlaying());
     }
     catch (System.Exception ex)
     {
         logger.Warn(ex);
         throw new HttpResponseException(HttpStatusCode.InternalServerError);
     }
 }
Ejemplo n.º 2
0
 public int SetPosition(
     int pos)
 {
     try
     {
         return(SpotifySession.SetPosition(pos));
     }
     catch (System.Exception ex)
     {
         logger.Warn(ex);
         throw new HttpResponseException(HttpStatusCode.InternalServerError);
     }
 }
Ejemplo n.º 3
0
 public int Stop()
 {
     try
     {
         SpotifySession.Stop();
     }
     catch (System.Exception ex)
     {
         logger.Warn(ex);
         throw new HttpResponseException(HttpStatusCode.InternalServerError);
     }
     return(0);
 }
Ejemplo n.º 4
0
 public IEnumerable <String> GetQueuedTracks()
 {
     try
     {
         var tracks = SpotifySession.GetQueuedTracks();
         return(tracks == null ? new String[0] : tracks.Select(t => t.GetLink().ToString()));
     }
     catch (Exception ex)
     {
         logger.Warn(ex);
         throw new HttpResponseException(HttpStatusCode.InternalServerError);
     }
 }
Ejemplo n.º 5
0
 public String GetCurrentTrack()
 {
     try
     {
         var track = SpotifySession.GetCurrentTrack();
         return(track == null ? null : track.GetLink().ToString());
     }
     catch (Exception ex)
     {
         logger.Warn(ex);
         throw new HttpResponseException(HttpStatusCode.InternalServerError);
     }
 }
Ejemplo n.º 6
0
 async Task <Boolean> PlayAlbumAsync(
     Album album,
     bool append = false)
 {
     try
     {
         SpotifySession.EnqueueTracks((await album.Browse()).Tracks.Where(t => t.IsAvailable), append);
         return(true);
     }
     catch (Exception ex)
     {
         logger.Warn(ex);
         return(false);
     }
 }
Ejemplo n.º 7
0
 async Task <Boolean> PlayTrackAsync(
     Track track,
     bool append = false)
 {
     if ((await track).IsAvailable)
     {
         try
         {
             SpotifySession.EnqueueTrack(track, append);
         }
         catch (Exception ex)
         {
             logger.Warn(ex);
             throw new HttpResponseException(HttpStatusCode.InternalServerError);
         }
     }
     return(true);
 }
Ejemplo n.º 8
0
 public Boolean PlayTrack(
     string id,
     bool append = false)
 {
     try
     {
         Track track = SpotifySession.GetTrack(id);
         if (track == null)
         {
             return(false);
         }
         return(PlayTrackAsync(track, append).Result);
     }
     catch (Exception ex)
     {
         logger.Warn(ex);
         return(false);
     }
 }
Ejemplo n.º 9
0
 public String RemoveQueuedTrack(
     string id)
 {
     try
     {
         Track track = SpotifySession.GetTrack(id);
         if (track != null)
         {
             SpotifySession.RemoveQueuedTrack(track);
             return(track.GetLink().ToString());
         }
         return(null);
     }
     catch (Exception ex)
     {
         logger.Warn(ex);
         throw new HttpResponseException(HttpStatusCode.InternalServerError);
     }
 }
Ejemplo n.º 10
0
 public Boolean PlayAlbum(
     string id,
     bool append = false)
 {
     try
     {
         Album album = SpotifySession.GetAlbum(id);
         if (album == null)
         {
             return(false);
         }
         return(PlayAlbumAsync(album, append).Result);
     }
     catch (Exception ex)
     {
         logger.Warn(ex);
         return(false);
     }
 }
Ejemplo n.º 11
0
        static void Main()
        {
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

            logger.Info("Spotify Player Started");

            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            try
            {
                if (!File.Exists(SpotifySession.SpotifyAppKeyFileName))
                {
                    MessageBox.Show(
                        string.Format("Spotify requires a key file named '{0}'", SpotifySession.SpotifyAppKeyFileName),
                        "Spotify Player", MessageBoxButtons.OK);
                    logger.Fatal("Spotify Player has no AppKey");
                    return;
                }
                var config = new HttpSelfHostConfiguration("http://localhost:8383");

                config.Routes.MapHttpRoute(
                    "API Default", "api/{controller}/{action}/{id}",
                    new { id = RouteParameter.Optional });

                RegistryKey key = Registry.CurrentUser.CreateSubKey("Avid");

                string user = key.GetValue("SpotifyUser") as string;
                string pass = key.GetValue("SpotifyPass") as string;

                while (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(pass))
                {
                    GetSpotifyCredentials gsc = new GetSpotifyCredentials(user ?? "", pass ?? "");
                    if (gsc.ShowDialog() == DialogResult.Cancel)
                    {
                        return;
                    }

                    user = gsc.SpotifyUser;
                    pass = gsc.SpotifyPass;

                    key.SetValue("SpotifyUser", user);
                    key.SetValue("SpotifyPass", pass);
                }

                SpotifySession.SpotifyUser = user;
                SpotifySession.SpotifyPass = pass;

                //  If we have no saved SpotifyRefreshUrl, get it via an HTTP handshake and
                //  save it persistently in the registry).
                //  This will use a browser to ask for credentials, but only the one time it is needed.
                RegistryKey  webKey = Registry.LocalMachine.OpenSubKey("Software", true).CreateSubKey("Avid");
                const string SpotifyRefreshUrlRegistryValue = "SpotifyRefreshUrl";

                try
                {
                    SecurityIdentifier sid     = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    NTAccount          account = sid.Translate(typeof(NTAccount)) as NTAccount;

                    // Get ACL from Windows
                    RegistrySecurity rs = webKey.GetAccessControl();

                    // Creating registry access rule for 'Everyone' NT account
                    RegistryAccessRule rar = new RegistryAccessRule(
                        account.ToString(),
                        RegistryRights.FullControl,
                        InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                        PropagationFlags.None,
                        AccessControlType.Allow);

                    rs.AddAccessRule(rar);
                    webKey.SetAccessControl(rs);
                }
                catch (System.Exception ex)
                {
                    logger.Error(ex, "Unable to grant write access to the Avid registry subkey: {0}", ex.Message);
                }

                if (string.IsNullOrEmpty(webKey.GetValue(SpotifyRefreshUrlRegistryValue) as string))
                {
                    logger.Info("Must authenticate to Spotify Web API");
                    const String RedirectUri = "http://brianavid.dnsalias.com/SpotifyAuth/Auth/";
                    var          auth        = new SpotifyAPI.Web.Auth.AutorizationCodeAuth()
                    {
                        ClientId    = "b2d4e764bb8c49f39f1211dfc6b71b34",
                        RedirectUri = RedirectUri + "Authenticate",

                        //How many permissions we need?
                        Scope = SpotifyAPI.Web.Enums.Scope.UserReadPrivate |
                                SpotifyAPI.Web.Enums.Scope.UserReadEmail |
                                SpotifyAPI.Web.Enums.Scope.PlaylistReadPrivate |
                                SpotifyAPI.Web.Enums.Scope.UserLibrarayRead |
                                SpotifyAPI.Web.Enums.Scope.UserLibraryModify |
                                SpotifyAPI.Web.Enums.Scope.UserReadPrivate |
                                SpotifyAPI.Web.Enums.Scope.UserFollowRead |
                                SpotifyAPI.Web.Enums.Scope.UserFollowModify |
                                SpotifyAPI.Web.Enums.Scope.PlaylistModifyPrivate |
                                SpotifyAPI.Web.Enums.Scope.PlaylistModifyPublic |
                                SpotifyAPI.Web.Enums.Scope.UserReadBirthdate
                    };

                    //  Open up a browser to authenticate
                    auth.DoAuth();

                    //  Try for two minutes to get the RefreshToken constructed as part of the OAUTH exchange
                    for (int i = 0; i < 120; i++)
                    {
                        HttpWebRequest request =
                            (HttpWebRequest)HttpWebRequest.Create(RedirectUri + "GetLastRefreshToken");
                        request.Method      = WebRequestMethods.Http.Get;
                        request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

                        HttpWebResponse response         = (HttpWebResponse)request.GetResponse();
                        var             lastRefreshToken = new StreamReader(response.GetResponseStream()).ReadToEnd();
                        if (!string.IsNullOrEmpty(lastRefreshToken))
                        {
                            //  Save the required authentication refresh URL into the registry so that the main
                            //  Avid4 web app can authenticate using the same credentials
                            webKey.SetValue(SpotifyRefreshUrlRegistryValue, RedirectUri + "Refresh?refresh_token=" + lastRefreshToken);
                            logger.Info("Authenticated to Spotify Web API");
                            break;
                        }
                        System.Threading.Thread.Sleep(1000);
                    }
                }

                if (string.IsNullOrEmpty(webKey.GetValue(SpotifyRefreshUrlRegistryValue) as string))
                {
                    MessageBox.Show(
                        string.Format("Failed to authenticate to Spotify"),
                        "Spotify Player", MessageBoxButtons.OK);
                    logger.Fatal("Failed to authenticate to Spotify");
                    return;
                }


                using (HttpSelfHostServer server = new HttpSelfHostServer(config))
                {
                    server.OpenAsync().Wait();
                    applicationContext = new CustomApplicationContext();
                    Application.Run(applicationContext);
                    logger.Info("Spotify Player Exit");
                    SpotifySession.CloseSession(false);
                }
            }
            catch (Exception ex)
            {
                logger.Fatal(ex);
            }
        }