Skip to content

Instantly share code, notes, and snippets.

@seresk
Created April 6, 2021 22:18
Show Gist options
  • Save seresk/9052f966fbb9601c2220c0e79994ea6d to your computer and use it in GitHub Desktop.
Save seresk/9052f966fbb9601c2220c0e79994ea6d to your computer and use it in GitHub Desktop.
SpotifyEngine with play and update methods
export class SpotifyEngine extends EngineBase
implements IStreamEngine{
///...
private async playTrack(trackId: string): Promise<void> {
await this.dataService.put<any>(
SpotifyURLResources.PlayTrack + `?device_id=${this.deviceService.activeDevice.id}`,
JSON.stringify({uris: [trackId]}),
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.authorizationService.spotifyAccessToken}`
}
}
);
}
private async _getCurrentlyPlaying(): Promise<CurrentlyPlayingResponseModel> {
const result = await this.dataService.get<SpotifyApi.CurrentlyPlayingResponse>(
SpotifyURLResources.CurrentlyPlaying,
this.authorizationService.getAuthorizationHeaders()
);
const response = new CurrentlyPlayingResponseModel();
if (result && result.context) {
if (result.context.type === 'playlist') {
response.playlistType = PlayListTypeEnum.playlist;
const stringArray = result.context.uri.split(':');
response.playlistId = stringArray[stringArray.length - 1];
}
if (result.context.type === 'album') {
response.playlistType = PlayListTypeEnum.album;
const stringArray = result.context.uri.split(':');
response.playlistId = stringArray[stringArray.length - 1];
}
}
if (result && result.context === null && (result as any).currently_playing_type === 'track') {
response.playlistType = PlayListTypeEnum.trackCollection;
response.playlistId = null;
}
if (result && result.item) {
const a = result.item;
const t = result.item;
response.track = new TrackModel({
id: t.id,
url: t.uri,
name: t.name,
artistName: t.artists[0].name,
albumName: a.album.name,
trackNumber: t.track_number,
totalNumberOfTrackInPlaylist: 0,
genre: '',
artworkUrl: a.album.images[0].url,
durationMs: t.duration_ms,
isPlayable: t.is_playable,
});
}
if (result && result.is_playing && (result.progress_ms || result.progress_ms === 0)) {
response.progressMs = result.progress_ms;
if (result.is_playing === true) {
response.playState = PlayStateEnum.Play;
}
if (!result.is_playing && result.progress_ms > 0) {
response.playState = PlayStateEnum.Pause;
}
if (!result.is_playing && result.progress_ms === 0) {
response.playState = PlayStateEnum.Stopped;
}
}
return response;
}
///...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment