Skip to content

Commit

Permalink
Remove duplicates from target playlist
Browse files Browse the repository at this point in the history
  • Loading branch information
pkarpovich committed Oct 21, 2022
1 parent e341f55 commit 7b49b36
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/funny-beers-care.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'playlist-synchronizer': patch
---

Update all dependencies
5 changes: 5 additions & 0 deletions .changeset/swift-hats-compete.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'playlist-synchronizer': patch
---

Remove duplicates from target playlist
20 changes: 18 additions & 2 deletions src/services/music-providers/spotify.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,19 @@ export class SpotifyService implements BaseMusicService {
nextPage = resp.body.next;
} while (nextPage);

return items.map<Track>(({ track }) => ({
const tracks = items.map<Track>(({ track }) => ({
id: track?.uri,
name: track?.name as string,
artists: track?.artists.map(({ name }) => name) as string[],
source: track,
}));

const duplicates = this.findDuplicateTracksInPlaylist(tracks);
await this.removeTracksFromPlaylist(duplicates, { id } as Playlist);

return tracks.filter(
(t) => duplicates.findIndex((dt) => dt.id === t.id) === -1,
);
}

async searchArtistByName(
Expand Down Expand Up @@ -182,7 +189,9 @@ export class SpotifyService implements BaseMusicService {
() =>
this.client.removeTracksFromPlaylist(
playlist.id,
tracks.map((t) => t.source as SpotifyApi.TrackObjectFull),
tracks.map(
(t) => ({ uri: t.id } as SpotifyApi.TrackObjectFull),
),
),
() => this.refreshAccess(),
);
Expand Down Expand Up @@ -235,4 +244,11 @@ export class SpotifyService implements BaseMusicService {

return mostRelevantBySearch;
}

private findDuplicateTracksInPlaylist(tracks: Track[]): Track[] {
return tracks.filter(
(track, index) =>
tracks.findIndex((t) => t.id === track.id) !== index,
);
}
}

0 comments on commit 7b49b36

Please sign in to comment.