-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspotifyWebSdk.tsx
108 lines (93 loc) · 2.56 KB
/
spotifyWebSdk.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import * as React from 'react';
// tslint:disable-next-line
const noop = () => {};
interface Options {
name: string;
getOAuthToken: () => Promise<string>;
accountError?: (e: any) => void;
onReady?: (deviceId: string) => void;
onPlayerStateChanged?: Spotify.PlaybackStateListener;
}
declare global {
interface Window {
Spotify: any;
}
}
export function useSpotifyWebSdk({
name,
getOAuthToken,
accountError = noop,
onReady = noop,
onPlayerStateChanged = noop,
}: Options) {
const [isReady, setIsReady] = React.useState(false);
const [deviceId, setDeviceId] = React.useState<string>('');
const playerRef = React.useRef<Spotify.SpotifyPlayer | null>(null);
// playerRef.current!.
React.useEffect(() => {
if (window.Spotify) {
playerRef.current = new Spotify.Player({
name,
getOAuthToken: async cb => {
const token = await getOAuthToken();
cb(token);
},
});
setIsReady(true);
}
(window as any).onSpotifyWebPlaybackSDKReady = () => {
playerRef.current = new Spotify.Player({
name,
getOAuthToken: async cb => {
const token = await getOAuthToken();
cb(token);
},
});
setIsReady(true);
};
if (!window.Spotify) {
const scriptTag = document.createElement('script');
scriptTag.src = 'https://sdk.scdn.co/spotify-player.js';
document.head!.appendChild(scriptTag);
}
}, []);
const handleReady = React.useCallback(({ device_id: readyDeviceId }) => {
setDeviceId(readyDeviceId);
if (onReady) {
onReady(deviceId);
}
}, []);
React.useEffect(
() => {
if (isReady) {
playerRef.current!.connect();
}
},
[isReady],
);
React.useEffect(
() => {
const player = playerRef.current!;
if (isReady) {
player.addListener('account_error', accountError);
player.addListener('ready', handleReady);
player.addListener('initialization_error', accountError);
player.addListener('authentication_error', accountError);
player.addListener('not_ready', accountError);
player.addListener('player_state_changed', onPlayerStateChanged);
return () => {
player.removeListener('account_error', accountError);
player.removeListener('ready', handleReady);
player.removeListener('player_state_changed', onPlayerStateChanged);
};
}
return;
},
[isReady, onPlayerStateChanged],
);
return {
player: playerRef.current,
deviceId,
isReady,
};
}