Code Monkey home page Code Monkey logo

Comments (31)

peterjuras avatar peterjuras commented on June 1, 2024 2

Thanks for the quick fix! I'll give it a spin on the weekend and will let you know 🙌

from spotify-api.js.

peterjuras avatar peterjuras commented on June 1, 2024 1

Thanks, it works correctly now 👍 🙌

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

Well there is a mistake in your code.

const client = await new Client({
      token,
      userAuthorizedToken: true,
      cacheSettings: { cacheUser: true }});

console.log(Client.user);

Here you are accessing the user property from the Client class not the client object. Try doing it like

console.log(client.user);

Sorry for the late response....

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

I am expiring similar issue:

  await new SpotifyClient({
    token: {
      // redirectURL: "http://localhost/",
      clientID: "",
      clientSecret: "",
    },
    userAuthorizedToken: true,

    refreshToken: true,
    async onReady(c) {
      console.log(`🚀 ~ onReady ~ c.user;`, c.user);
    },
    onRefresh() {
      consoleInfo("Refreshed Spotify token", "**\n**", null, true);
    },
  });```
  
  returning undefined

Kindly do not expose your client secret and client id @niveKKumar. And I guess you mean experiencing not expiring.
And in the above code, what is returning the undefined?

If you are awaiting the client then there is no use of onReady. Try to do things like this:

const client = await SpotifyClient.create({
     token: {
           // redirectURL: "http://localhost/",
          clientID: "ur client id",
          clientSecret: "ur client secret",
     },
     userAuthorizedToken: true,
     refreshToken: true,
     onRefresh: () => consoleInfo("Refreshed Spotify token", "**\n**", null, true)
});

console.log('Client is ready.');

Moreover, you have used userAuthorizedToken to true but you have not provided the necessary parameters in token.
For further doubts, open a new issue.

from spotify-api.js.

niveKKumar avatar niveKKumar commented on June 1, 2024

Thanks for your prompt message. That were a lot mistakes, I should ve checked

export const spotifyApi = async () => {
  if (spotify) return spotify;
  spotify = await SpotifyClient.create({
    token: {
      // redirectURL: "http://localhost/",
      clientID: "",
      clientSecret: "",
    },
    userAuthorizedToken: true,
    refreshToken: true,
    onRefresh() {
      consoleInfo("Refreshed Spotify token", "**\n**", null, true);
    },
  });
return spotify;
};

async function test() {
  const kev = (await spotifyApi()).user
  console.log(`🚀 ~ test ~ kev`, kev);
}
test();

What am I missing here ? I want saved Podcasts to be loaded from the api, which as far I understand should work like this:

await kev.getSavedShows({})

But user here is undefined...

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

Well, here you are mistaken with something, you want to access the current user api for that you would require code and redirectURL fields in token. So, the code would look something like this:

export const spotifyApi = async () => {
  if (spotify) return spotify;
  spotify = await SpotifyClient.create({
    token: {
      redirectURL: "redirect url here",
      code: "your code here",
      clientID: "",
      clientSecret: "",
    },
    userAuthorizedToken: true,
    refreshToken: true,
    onRefresh() {
      consoleInfo("Refreshed Spotify token", "**\n**", null, true);
    },
  });
return spotify;
};

from spotify-api.js.

niveKKumar avatar niveKKumar commented on June 1, 2024

Well, here you are mistaken with something, you want to access the current user api for that you would require code and redirectURL fields in token. So, the code would look something like this:

export const spotifyApi = async () => {
  if (spotify) return spotify;
  spotify = await SpotifyClient.create({
    token: {
      redirectURL: "redirect url here",
      code: "your code here",
      clientID: "",
      clientSecret: "",
    },
    userAuthorizedToken: true,
    refreshToken: true,
    onRefresh() {
      consoleInfo("Refreshed Spotify token", "**\n**", null, true);
    },
  });
return spotify;
};

I want the user associated to my clientId, I have a pure node application (no website, express or anything similar).

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

niveKKumar

But if you want a client to access the current user, you would require those parameters through web server, even if you don't use this module, you have to go through the same process by using api methods.

There is one more way,

  1. Get the access token using the express api (first time).
  2. Create the client with the access token with the refreshToken option set to true so that when the access token gets expired, the client will regenerate a new token.

from spotify-api.js.

niveKKumar avatar niveKKumar commented on June 1, 2024

niveKKumar

But if you want a client to access the current user, you would require those parameters through web server, even if you don't use this module, you have to go through the same process by using api methods.

There is one more way,

  1. Get the access token using the express api (first time).
  2. Create the client with the access token with the refreshToken option set to true so that when the access token gets expired, the client will regenerate a new token.

I would need to do that upon every restart of the application right ?

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

niveKKumar

But if you want a client to access the current user, you would require those parameters through web server, even if you don't use this module, you have to go through the same process by using api methods.
There is one more way,

  1. Get the access token using the express api (first time).
  2. Create the client with the access token with the refreshToken option set to true so that when the access token gets expired, the client will regenerate a new token.

I would need to do that upon every restart of the application right ?

Yeah. When the program restarts, you want to change your access token to the last refresh token.

You can solve this issue by the following:

  1. Get the initial token through spotify web api or through spotify web api dashboard.
  2. Save the token in some sort of database.
  3. Whenever the program starts, get the token from the database and use it as an access token.
  4. And save the new access token whenever the module refreshes the token using the onRefresh event.

from spotify-api.js.

niveKKumar avatar niveKKumar commented on June 1, 2024

Appreciate your help, just only problem I have. I was able to retrieve my access token and my refreshtoken
image
How can i pass it to my client spotify client ?
I passed my earlier application credits from my spotify app and also passed my retrieved refresh token, which still returns my user (Client#user) as undefined

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

Appreciate your help, just only problem I have. I was able to retrieve my access token and my refreshtoken image How can i pass it to my client spotify client ? I passed my earlier application credits from my spotify app and also passed my retrieved refresh token, which still returns my user (Client#user) as undefined

You can create the Client with the following options,

await SpotifyClient.create({
    token: 'Your access token',
    userAuthorizedToken: true,
    refreshToken: true,
    onReady (client) {
        // Setup details
        client.refreshMeta = {
              ...client.refreshMeta,
              clientID: "",
              clientSecret: "",
              refreshToken: ""
        };
    },
    onRefresh () {
        consoleInfo("Refreshed Spotify token", "**\n**", null, true);
    },
  });

With this code, you will get a stack trace on console saying [SpotifyClientWarn]: You have provided a token and used refreshToken option. Try to provide clientID, clientSecret or user authenication details.. You can ignore that warning.

The warning is because the current spotify version doesn't support direct current user access token. This will be fixed in the upcoming version.

If you get any different errors, you can reply it here.

And once things are done, if you want to test if the client can refresh token you can do,

// @ts-ignore
await client.refreshFromMeta();

If you get no errors, that means the token has been refreshed.

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

@niveKKumar, with the latest release of v9.1.0, you can do it like this without a lot of mess,

const client = await Client.create({
     userAuthorizedToken: true,
     refreshToken: true,
     token: {
          accessToken: "access token here",
          clientID: "client id",
          clientSecret: "client secret",
          redirectURL: "redirect url here"
    }

    // Your other options...
});

from spotify-api.js.

niveKKumar avatar niveKKumar commented on June 1, 2024

Awesome thanks ! Its token: { token: ...} tho

Its not possible to have the releaseDate as Date Object right ?
I would like to send new released podcasts, so I would need to manually check if there is a new episode through comparing an old fetch with the new fetched episodes or is there some way to search for episodes released exactly after a certain date (every 3 hours)

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

Awesome thanks ! Its token: { token: ...} tho

Its not possible to have the releaseDate as Date Object right ? I would like to send new released podcasts, so I would need to manually check if there is a new episode through comparing an old fetch with the new fetched episodes or is there some way to search for episodes released exactly after a certain date (every 3 hours)

Its token: { accessToken: '' }. Is it not working?

If you want it like a date object just create one,

let date = new Date(item.releaseDate);

from spotify-api.js.

niveKKumar avatar niveKKumar commented on June 1, 2024

Thats the syntax:

 token: {
        token: t != undefined ? t : (await getSpotifyAccessToken())?.token,
        ...credit,
      },
  Spotify doesnt give the hours right ? Only the day
  So I could only check for hourly changes through comparing to my cache 

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

Thats the syntax:

 token: {
        token: t != undefined ? t : (await getSpotifyAccessToken())?.token,
        ...credit,
      },
  Spotify doesnt give the hours right ? Only the day
  So I could only check for hourly changes through comparing to my cache 

It should be token: { accessToken }.
And about the releaseDate issue, are you talking about the releaseDate of Shows?

from spotify-api.js.

niveKKumar avatar niveKKumar commented on June 1, 2024

image

Yes I am talking about shows, seems that the api doesnt give any option to get a more precise date...

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

image

Yes I am talking about shows, seems that the api doesnt give any option to get a more precise date...

My mistake. It was supposed to be accessToken. Now, I guess let it be like that.

And about the precise release date of Shows, the spotify api does not provides it. Source
But, if i find any way to get the precise release date, i will let you know.

from spotify-api.js.

niveKKumar avatar niveKKumar commented on June 1, 2024

image

Yes I am talking about shows, seems that the api doesnt give any option to get a more precise date...

My mistake. It was supposed to be accessToken. Now, I guess let it be like that.

And about the precise release date of Shows, the spotify api does not provides it. Source
But, if i find any way to get the precise release date, i will let you know.

Comparing new Shows with the cache would give a more precise date not?

Like I fetch every 1 hour the episodes and a new episode pops up which isn't in the cache. You could atleast give an hourly timeframe (date) for the new episode right?

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

image
Yes I am talking about shows, seems that the api doesnt give any option to get a more precise date...

My mistake. It was supposed to be accessToken. Now, I guess let it be like that.
And about the precise release date of Shows, the spotify api does not provides it. Source
But, if i find any way to get the precise release date, i will let you know.

Comparing new Shows with the cache would give a more precise date not?

Like I fetch every 1 hour the episodes and a new episode pops up which isn't in the cache. You could atleast give an hourly timeframe (date) for the new episode right?

Yeah, initially I had the same idea and wanted to add this feature to this module. But, this might result in continuous fetch requests which may increase ratelimits but if its for every 1 hour, then its not an issue. This feature is not added to the module yet because it would make module more complicated.

Moreover, you cannot trust on cache since when the program restarts, the cache will be empty. You have to use a database and save the IDs of the episodes.

The idea would work since most of the third party notification service use the same method. You can implement this feature in your project. In future, i will try to create a separate module for such methods.

from spotify-api.js.

niveKKumar avatar niveKKumar commented on June 1, 2024

@scientific-dev

The token is much shorter then my access token i obtain manually

  Using the saved token it throws the Error 


  statusText: 'Unauthorized',
onRefresh() {
        consoleInfo("Refreshed Spotify token", `**${spotify.token} \n**`, null, true);
        new SpotifyLog({ token: spotify.token }).save().then(() => {
          consoleInfo("Refreshed spotify and saved to db", null, null, true);
        });
      },

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

@scientific-dev

The token is much shorter then my access token i obtain manually

  Using the saved token it throws the Error 


  statusText: 'Unauthorized',
onRefresh() {
        consoleInfo("Refreshed Spotify token", `**${spotify.token} \n**`, null, true);
        new SpotifyLog({ token: spotify.token }).save().then(() => {
          consoleInfo("Refreshed spotify and saved to db", null, null, true);
        });
      },

What is the issue here?

from spotify-api.js.

niveKKumar avatar niveKKumar commented on June 1, 2024

With the given token (spotify.token), I cant create a new Client...
The returned token is also much shorter than the "normal" access token
I can login first with my manual token, the onRefresh throws the Error then...

image

export const spotifyApi = async (t = manual) => {
  // if (spotify) return spotify;
  // await SpotifyLog({ token: manual }).save();
  try {
    spotify = await SpotifyClient.create({
      userAuthorizedToken: true,
      token: {
        token: t != undefined ? t : (await getSpotifyAccessToken())?.token,
        ...credit,
      },
      refreshToken: true,
      async onRefresh() {
        consoleInfo("Refreshed Spotify token", `**${spotify.token} \n**`, null, true);
        new SpotifyLog({ token: spotify.token }).save().then(() => {
          consoleInfo("Refreshed spotify and saved to db", null, null, true);
        });
        console.log(await spotifyApi(spotify.token));
      },
    });
  } catch (error) {
    console.log(`🚀 ~ spotifyApi ~ Catched`, error);
  }
  Sleep(4000).then(() => {
    spotify.refreshFromMeta();
  });
  return spotify;
};

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

With the given token (spotify.token), I cant create a new Client... The returned token is also much shorter than the "normal" access token I can login first with my manual token, the onRefresh throws the Error then...

image

export const spotifyApi = async (t = manual) => {
  // if (spotify) return spotify;
  // await SpotifyLog({ token: manual }).save();
  try {
    spotify = await SpotifyClient.create({
      userAuthorizedToken: true,
      token: {
        token: t != undefined ? t : (await getSpotifyAccessToken())?.token,
        ...credit,
      },
      refreshToken: true,
      async onRefresh() {
        consoleInfo("Refreshed Spotify token", `**${spotify.token} \n**`, null, true);
        new SpotifyLog({ token: spotify.token }).save().then(() => {
          consoleInfo("Refreshed spotify and saved to db", null, null, true);
        });
        console.log(await spotifyApi(spotify.token));
      },
    });
  } catch (error) {
    console.log(`🚀 ~ spotifyApi ~ Catched`, error);
  }
  Sleep(4000).then(() => {
    spotify.refreshFromMeta();
  });
  return spotify;
};

I guess, you still don't understand, you do not have to worry about the refreshing the token for every hour or particular duration limit, the module itself would refresh the token if the refreshToken option is set to true. If you have supplied the required refresh options in token, it would refresh itself whenever it receives an access token expired response.

from spotify-api.js.

niveKKumar avatar niveKKumar commented on June 1, 2024

Yeah I know and thats great on this module as it handles it itself

My problem is, that I want to have only the information of a specific user (mine) to get its shows, but I have a node only enviroment, no browser with logging in. You suggested me to

Get the initial token through spotify web api or through spotify web api dashboard.
Save the token in some sort of database.
Whenever the program starts, get the token from the database and use it as an access token.
And save the new access token whenever the module refreshes the token using the onRefresh event.

Which is what i am trying here with the code, but it doesnt work through obtaining the new token from the client, as you can see in the onRefresh creating a new Client with the new token from the client
@scientific-dev Appreciate your help !

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

Yeah I know and thats great on this module as it handles it itself

My problem is, that I want to have only the information of a specific user (mine) to get its shows, but I have a node only enviroment, no browser with logging in. You suggested me to

Get the initial token through spotify web api or through spotify web api dashboard. Save the token in some sort of database. Whenever the program starts, get the token from the database and use it as an access token. And save the new access token whenever the module refreshes the token using the onRefresh event.

Which is what i am trying here with the code, but it doesnt work through obtaining the new token from the client, as you can see in the onRefresh creating a new Client with the new token from the client @scientific-dev Appreciate your help !

Why are you creating another client? You can use the same client right?

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

The following issue has been fixed in v9.2.0. Try to run the same program in the new version.

from spotify-api.js.

peterjuras avatar peterjuras commented on June 1, 2024

This is still happening for me. client.user is undefined. This is my initialization code:

const client = await Client.create({
    token: {
      clientID: spotifyConfig.SPOTIFY_CLIENT_ID,
      clientSecret: spotifyConfig.SPOTIFY_CLIENT_SECRET,
      refreshToken: spotifyUser.refreshToken,
    },
    userAuthorizedToken: true,
    refreshToken: true,
  });

// client.user is not defined.

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

This is still happening for me. client.user is undefined. This is my initialization code:

const client = await Client.create({
    token: {
      clientID: spotifyConfig.SPOTIFY_CLIENT_ID,
      clientSecret: spotifyConfig.SPOTIFY_CLIENT_SECRET,
      refreshToken: spotifyUser.refreshToken,
    },
    userAuthorizedToken: true,
    refreshToken: true,
  });

// client.user is not defined.

I didn't noticed this bug and thanks for noticing it and telling us. This issue is fixed in v9.2.1. Try running it in the newer version.

from spotify-api.js.

scientific-dev avatar scientific-dev commented on June 1, 2024

Thanks, it works correctly now 👍 🙌

Your welcome.

from spotify-api.js.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.