Пример #1
0
func addTracksToPlaylist(client *spotify.Client, user *spotify.PrivateUser, playlist *spotify.SimplePlaylist, trackIDs []spotify.ID) error {
	allTracks := make(map[spotify.ID]spotify.FullTrack)
	limit := 100
	offset := 0

	var options spotify.Options
	options.Limit = &limit
	options.Offset = &offset

	for {
		tracksPage, err := client.GetPlaylistTracksOpt(user.ID, playlist.ID, &options, "")
		if err != nil {
			return err
		}

		log.Printf("Playlist %v: fetched page of %v track(s)", playlist.Name, len(tracksPage.Tracks))

		for _, playlistTrack := range tracksPage.Tracks {
			track := playlistTrack.Track
			allTracks[track.ID] = track
		}

		// The Spotify API always returns full pages unless it has none left to
		// return.
		if len(tracksPage.Tracks) < 100 {
			break
		}

		offset = offset + len(tracksPage.Tracks)
	}

	log.Printf("Playlist %v: %v track(s)", playlist.Name, len(allTracks))

	var trackIDsToAdd []spotify.ID
	for _, id := range trackIDs {
		if _, ok := allTracks[id]; !ok {
			trackIDsToAdd = append(trackIDs, id)
		}
	}

	log.Printf("Playlist %v: Need to add %v track(s)", playlist.Name,
		len(trackIDsToAdd))

	for i := 0; i < len(trackIDsToAdd); i += 100 {
		bound := i + 100
		if bound > len(trackIDsToAdd) {
			bound = len(trackIDsToAdd)
		}

		_, err := client.AddTracksToPlaylist(user.ID, playlist.ID, trackIDsToAdd[i:bound]...)
		if err != nil {
			return err
		}
		log.Printf("Playlist %v: added page of %v track(s)", playlist.Name,
			len(trackIDsToAdd[i:bound]))
	}

	return nil
}
Пример #2
0
func GetTrax(c *spotify.Client, id spotify.ID) ([]spotify.ID, error) {
	discTrax, err := c.GetPlaylistTracksOpt("spotifydiscover", id, nil, "items(track(id, name))")
	if err != nil {
		return nil, errors.New("getplay err: " + err.Error())
	}

	ids := make([]spotify.ID, 0, len(discTrax.Tracks))
	for _, t := range discTrax.Tracks {
		fmt.Printf("ID: %v, Name: %v\n", t.Track.ID, t.Track.Name)
		ids = append(ids, spotify.ID(t.Track.ID))
	}

	return ids, nil
}