Skip to content

Commit

Permalink
トークンを発行できる機能を追加
Browse files Browse the repository at this point in the history
  • Loading branch information
eyr1n committed Feb 17, 2024
1 parent a8fd738 commit 5bd850f
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 24 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
```sh
npx wrangler secret put SPOTIFY_CLIENT_ID
npx wrangler secret put SPOTIFY_CLIENT_SECRET
npx wrangler kv:key put --binding=SPOTIFY_NOW_PLAYING_KV "access-token" "[Access Token]"
npx wrangler kv:key put --binding=SPOTIFY_NOW_PLAYING_KV "refresh-token" "[Refresh Token]"
```
84 changes: 61 additions & 23 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
interface Env {
CLIENT_ID: string;
CLIENT_SECRET: string;
SPOTIFY_CLIENT_ID: string;
SPOTIFY_CLIENT_SECRET: string;
SPOTIFY_REDIRECT_URL?: string;
SPOTIFY_NOW_PLAYING_KV: KVNamespace;
}

Expand Down Expand Up @@ -56,19 +57,58 @@ interface WorkerCurrentlyPlaying {
}

export default {
// AccessTokenを使用してNowPlayingを取得
async fetch(_request: Request, env: Env, _ctx: ExecutionContext): Promise<Response> {
const accessToken = await env.SPOTIFY_NOW_PLAYING_KV.get('access-token').then((token) => {
if (!token) {
throw new Error('access-token is null');
// Access Tokenを使用して再生中の音楽を取得
async fetch(request: Request, env: Env, _ctx: ExecutionContext): Promise<Response> {
if (env.SPOTIFY_REDIRECT_URL) {
const code = new URL(request.url).searchParams.get('code');
if (!code) {
return Response.redirect(
`https://accounts.spotify.com/authorize?${new URLSearchParams({
response_type: 'code',
client_id: env.SPOTIFY_CLIENT_ID,
scope: 'user-read-currently-playing',
redirect_uri: env.SPOTIFY_REDIRECT_URL,
})}`,
302
);
}
return token;
});

const response: { access_token: string; refresh_token: string } = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${btoa(env.SPOTIFY_CLIENT_ID + ':' + env.SPOTIFY_CLIENT_SECRET)}`,
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code: code,
redirect_uri: env.SPOTIFY_REDIRECT_URL,
}),
}).then((res) => {
if (res.status !== 200) {
throw new Error('Spotify API Error');
}
return res.json();
});

await env.SPOTIFY_NOW_PLAYING_KV.put('access-token', response.access_token);
await env.SPOTIFY_NOW_PLAYING_KV.put('refresh-token', response.refresh_token);

return Response.json({
access_token: response.access_token,
refresh_token: response.refresh_token,
});
}

const accessToken = await env.SPOTIFY_NOW_PLAYING_KV.get('access-token');
if (!accessToken) {
throw new Error('access-token is null');
}

const spotifyResponse: SpotifyCurrentlyPlaying = await fetch('https://api.spotify.com/v1/me/player/currently-playing?market=JP', {
method: 'GET',
headers: { Authorization: `Bearer ${accessToken}` },
}).then(async (res) => {
}).then((res) => {
if (res.status === 204) {
return {};
}
Expand All @@ -91,25 +131,23 @@ export default {
return Response.json(workerResponse);
},

// 30分ごとにAccessTokenを更新
// 30分ごとにAccess Tokenを更新
async scheduled(_event: ScheduledEvent, env: Env, _ctx: ExecutionContext) {
const refreshToken = await env.SPOTIFY_NOW_PLAYING_KV.get('refresh-token').then((token) => {
if (!token) {
throw new Error('refresh-token is null');
}
return token;
});
const refreshToken = await env.SPOTIFY_NOW_PLAYING_KV.get('refresh-token');
if (!refreshToken) {
throw new Error('refresh-token is null');
}

const res: { access_token: string; refresh_token?: string } = await fetch('https://accounts.spotify.com/api/token', {
const response: { access_token: string; refresh_token?: string } = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${btoa(env.CLIENT_ID + ':' + env.CLIENT_SECRET)}`,
Authorization: `Basic ${btoa(env.SPOTIFY_CLIENT_ID + ':' + env.SPOTIFY_CLIENT_SECRET)}`,
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: env.CLIENT_ID,
client_id: env.SPOTIFY_CLIENT_ID,
}),
}).then((res) => {
if (res.status !== 200) {
Expand All @@ -118,9 +156,9 @@ export default {
return res.json();
});

await env.SPOTIFY_NOW_PLAYING_KV.put('access-token', res.access_token);
if (res.refresh_token) {
await env.SPOTIFY_NOW_PLAYING_KV.put('refresh-token', res.refresh_token);
await env.SPOTIFY_NOW_PLAYING_KV.put('access-token', response.access_token);
if (response.refresh_token) {
await env.SPOTIFY_NOW_PLAYING_KV.put('refresh-token', response.refresh_token);
}
},
};
2 changes: 1 addition & 1 deletion wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ id = "42b3d8e238164f89966d351af22e5958"
crons = ["*/30 * * * *"]

[[routes]]
pattern = "now-playing.eyrin.jp"
pattern = "nowplaying.eyrin.jp"
custom_domain = true

0 comments on commit 5bd850f

Please sign in to comment.