Spotify API 1.x get user session

2019-06-06 04:16发布

问题:

Trying Spotify API 1.x. My manifest

"Dependencies": {
      "api": "1.20.1",
      "views": "1.24.1"
  }

Having problem getting the current session with the new spotify API. Session Docs

After a while I got the user information with this:

require(['$api/models','$api/models#User','$api/models#Session'], function(models) {
    var user = models.User.fromURI('spotify:user:@');
    user.load('username', 'name').done(function(u) {
        userUid = u.identifier;
    });
});

But the Session doesn't have the load method (getting throw error) and when looking at the models.Session I can't se any values??? :(

回答1:

I changed on manifest.json API version to:

"api": "1.3.0"

Now I can get information from the session, for example my country:

var userCountry = models.session.country;


回答2:

I find the Spotify documentation a bit misleading regarding Sessions. There are a number of things I have found out by trial-and-error and Googling, rather than from the docs.

Like @Backer says, change the API version to 1.3.0 (or higher, when available). Please note you have to restart Spotify for this to take effect.

Then you can access the Session object like this (here, "session" must be lower case):

models.session.load('product','connection','device','user').done(function(s){
    console.log('sess:',s)
});

The User object will be part of this, but it won't be populated with properties unless you load them. Here is an example of retrieving a subset of properties from Session and User:

require([
'$api/models','$api/models#Session'
], function(models) {
app.user = {};
    models.session.load('product','connection','device','user').done(function(sess){
       sess.user.load('name', 'username', 'subscribed').done(function(user){
           app.user.name = user.name; // string
           app.user.username = user.username; // string
           app.user.subscribed = user.subscribed; // boolean
       });
       app.user.connection = sess.connection; // string
       app.user.country = sess.country; // string ISO-2
       app.user.device = sess.device; // string
       app.user.language = sess.language; // string ISO-2
       app.user.product = sess.product; // string

    });
});

The entire Session object:

Session
_done: 65535
_listening: true
_ob: Object
_obcount: 1
_requestArgs: Array[0]
_requestName: "session_event_wait"
capabilities: Object
connecting: false
connection: "wlan"
country: "SE"
developer: true
device: "desktop"
incognito: false
language: "en"
online: true
product: "open"
resolution: 1
streaming: "enabled"
testGroup: 000
user: User
    _done: 255
    currentUser: true
    identifier: "longcodehere"
    image: "http://profile-images.scdn.co/artists/default/anotherlongcodehere"
    images: Array[2]
    name: "My Name"
    subscribed: false
    uri: "spotify:user:@"
    username: "myusername"
    __proto__: c
    __proto__: c


标签: spotify