private async Task CreatePlaylists(IEnumerable <IEnumerable <Track> > playlists, CreatePlaylistsCommand command)
        {
            var user = await spotify.UserProfile.Current();

            var reversedPlaylists = playlists.Reverse();

            foreach (var(playlist, index) in reversedPlaylists.Select((playlist, index) => (playlist, index)))
            {
                var playlistNumber = playlists.Count() - index;
                var playlistName   = GeneratePlaylistName(command, playlistNumber);

                var playlistCreateRequest = new PlaylistCreateRequest(playlistName)
                {
                    Public      = !command.IsSecret,
                    Description = command.Description
                };

                var createdPlaylist = await spotify.Playlists.Create(user.Id, playlistCreateRequest);

                createdPlaylists.Add(createdPlaylist);

                for (var i = 0; i < (double)playlist.Count() / MaxItemsPerRequest; i++)
                {
                    var request = new PlaylistAddItemsRequest(playlist.Skip(i * MaxItemsPerRequest)
                                                              .Take(MaxItemsPerRequest)
                                                              .Select(x => x.Uri)
                                                              .ToList());

                    await spotify.Playlists.AddItems(createdPlaylist.Id, request);

                    await taskManager.ReportProgress("Adding tracks");
                }
            }
            await taskManager.ReportProgress("Complete", true);
        }
        public async Task <SimplePlaylist> CreatePlaylist(string name)
        {
            var client = await Client.UserProfile.Current();

            var playlistReq = new PlaylistCreateRequest(name);
            var playlist    = await Client.Playlists.Create(client.Id, playlistReq);

            var playlists = await GetPlaylists();

            return(playlists
                   .Where(p => p.Id.Equals(playlist.Id))
                   .First());
        }
예제 #3
0
        public async void CreatePlaylist()
        {
            VisualLogger.AddLine($"Creating playlist with {PlaylistSize} tracks...");
            PlaylistCreateRequest request = new PlaylistCreateRequest(Playlist.Name);

            request.Description = "Created via Akinify.";
            FullPlaylist playlist = await CurrentUser.Playlists.Create(CurrentUserProfile.Id, request);

            List <List <string> > trackUriBatches = Playlist.SelectTracks(PlaylistSize, CurrentSelectionType);

            foreach (List <string> trackUris in trackUriBatches)
            {
                await Task.Delay(100);

                await CurrentUser.Playlists.AddItems(playlist.Id, new PlaylistAddItemsRequest(trackUris));
            }
            VisualLogger.AddLine($"Playlist created: {Playlist.Name}");
        }
예제 #4
0
        public async Task <IActionResult> PostPlaylist(PlaylistCreateRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(StatusCode(400));
            }

            var dto = _mapper.Map <PlaylistCreateDTO>(request);

            dto.DateCreated = DateTime.Now;
            dto.OwnerId     = GetUser();

            if (await _manager.CreatePlaylist(dto))
            {
                return(StatusCode(201));
            }

            throw new Exception();
        }
예제 #5
0
        public async Task CreatePlaylist(PlaylistCreateRequest request)
        {
            try
            {
                var userId = await GetUserIdAsync();

                if (userId != Guid.Empty)
                {
                    // Create or update the playlist
                    PlaylistVM playlist = request.Id == Guid.Empty
                    ? await _dal.CreatePlaylistAsync(request, userId)
                    : await _dal.UpdatePlaylistAsync(request, userId);

                    await Clients.Caller.SendAsync("ReceivePlaylist", playlist);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
예제 #6
0
        /// <summary>
        /// Creates a new playlist for current user.
        /// </summary>
        /// <param name="name">
        /// The name of the new playlist.
        /// </param>
        /// <param name="tracks">
        /// The tracks to add to the newly created playlist (Optional).
        /// </param>
        /// <returns></returns>
        public async Task <FullPlaylist> CreateSpotifyPlaylist(string name, string description, IEnumerable <Track> tracks = null, string base64Jpg = null)
        {
            try
            {
                var spotify = await Authentication.GetSpotifyClientAsync();

                PlaylistCreateRequest request = new PlaylistCreateRequest(name);
                if (!string.IsNullOrEmpty(description))
                {
                    request.Description = description;
                }
                var playlist = await spotify.Playlists.Create(Profile.Id, request);

                if (tracks != null && tracks.Count() > 0)
                {
                    var plRequest = new PlaylistAddItemsRequest(tracks.Select(c => c.Uri).ToList());
                    await spotify.Playlists.AddItems(playlist.Id, plRequest);
                }

                try
                {
                    if (!string.IsNullOrEmpty(base64Jpg))
                    {
                        await spotify.Playlists.UploadCover(playlist.Id, base64Jpg); //how to handle image data thats > 256kb?
                    }
                }
                catch (Exception)
                {
                }
                return(await spotify.Playlists.Get(playlist.Id));
            }
            catch (Exception)
            {
                ViewModels.Helpers.DisplayDialog("Error", "An error occured while creating your playlist");
                return(null);
            }
        }
예제 #7
0
    public async Task <SpotifyPlaylist> CreatePlaylistAsync(string playlistName, IReadOnlyList <SpotifyTrack> tracks, IProgress <int> progress)
    {
        var client = this.clientProviderService.GetSpotifyClient();

        this.serviceLogger.LogInfo($"CreatePlaylistAsync: Create playlist request; Playlist name = {playlistName}");

        var user = await client.UserProfile.Current();

        var request = new PlaylistCreateRequest(playlistName)
        {
            Description = PLAYLIST_MARKET
        };
        var playlist = await client.Playlists.Create(user.Id, request);

        this.serviceLogger.LogInfo($"CreatePlaylistAsync: Playlist {playlistName} was created successfully");

        if (playlist.Id == null)
        {
            return(null);
        }

        var chunks = tracks.Select(t => t.Uri).ChunkBy(100).ToList();

        this.serviceLogger.LogInfo($"CreatePlaylistAsync: Adding tracks to playlist {playlistName}...");
        foreach ((var chunk, int progressPercent) in chunks.ProgressForEach())
        {
            progress.Report(progressPercent);
            await client.Playlists.AddItems(playlist.Id, new PlaylistAddItemsRequest(chunk));
        }

        this.serviceLogger.LogInfo($"CreatePlaylistAsync: {tracks.Count} track(s) was successfully to playlist {playlistName}");

        var updatedPlaylist = await client.Playlists.Get(playlist.Id);

        return(SpotifyApiConverters.Convert(updatedPlaylist));
    }
예제 #8
0
        public async Task <List <IPlaylistSyncError> > SyncToSpotify(MusicBeeSyncHelper mb, List <MusicBeePlaylist> mbPlaylistsToSync,
                                                                     bool includeFoldersInPlaylistName = false, bool includeZAtStartOfDatePlaylistName = true)
        {
            List <IPlaylistSyncError> errors = new List <IPlaylistSyncError>();

            foreach (MusicBeePlaylist playlist in mbPlaylistsToSync)
            {
                // Use LINQ to check for a playlist with the same name
                // If there is one, clear it's contents, otherwise create one
                // Unless it's been deleted, in which case pretend it doesn't exist.
                // I'm not sure how to undelete a playlist, or even if you can
                string spotifyPlaylistName = null;
                if (includeFoldersInPlaylistName)
                {
                    spotifyPlaylistName = playlist.Name;
                }
                else
                {
                    spotifyPlaylistName = playlist.Name.Split('\\').Last();
                }

                if (includeZAtStartOfDatePlaylistName)
                {
                    // if it starts with a 2, it's a date playlist
                    if (spotifyPlaylistName.StartsWith("2"))
                    {
                        spotifyPlaylistName = $"Z {spotifyPlaylistName}";
                    }
                }

                // If Spotify playlist with same name already exists, clear it.
                // Otherwise create one
                SimplePlaylist thisPlaylist = Playlists.FirstOrDefault(p => p.Name == spotifyPlaylistName);
                string         thisPlaylistId;
                if (thisPlaylist != null)
                {
                    var request = new PlaylistReplaceItemsRequest(new List <string>()
                    {
                    });
                    var success = await Spotify.Playlists.ReplaceItems(thisPlaylist.Id, request);

                    if (!success)
                    {
                        Log("Error while trying to clear playlist before syncing new tracks");
                        return(errors);
                    }
                    thisPlaylistId = thisPlaylist.Id;
                }
                else
                {
                    var          request     = new PlaylistCreateRequest(spotifyPlaylistName);
                    FullPlaylist newPlaylist = await Spotify.Playlists.Create(Profile.Id, request);

                    thisPlaylistId = newPlaylist.Id;
                }


                List <FullTrack> songsToAdd = new List <FullTrack>();
                // And get the title and artist of each file, and add it to the GMusic playlist
                foreach (var song in playlist.Songs)
                {
                    string title  = song.Title;
                    string artist = song.Artist;
                    string album  = song.Album;

                    string         artistEsc = EscapeChar(artist.ToLower());
                    string         titleEsc  = EscapeChar(title.ToLower());
                    string         searchStr = $"artist:{artistEsc} track:{titleEsc}";
                    var            request   = new SearchRequest(SearchRequest.Types.Track, searchStr);
                    SearchResponse search    = await Spotify.Search.Item(request);

                    if (search.Tracks == null || search.Tracks.Items == null)
                    {
                        Log($"Could not find track on Spotify '{searchStr}' for '{title}' by '{artist}'");
                        continue;
                    }

                    if (search.Tracks.Items.Count == 0)
                    {
                        Log($"Found 0 results on Spotify for: {searchStr} for '{title}' by '{artist}'");
                        continue;
                    }

                    // try to find track matching artist and title
                    FullTrack trackToAdd = null;
                    foreach (FullTrack track in search.Tracks.Items)
                    {
                        bool titleMatches  = (track.Name.ToLower() == title.ToLower());
                        bool artistMatches = (track.Artists.Exists(a => a.Name.ToLower() == artist.ToLower()));
                        bool albumMatches  = (track.Album.Name.ToLower() == album.ToLower());
                        if (titleMatches && artistMatches && albumMatches)
                        {
                            trackToAdd = track;
                            break;
                        }
                        else if ((titleMatches && artistMatches) || (titleMatches && albumMatches) || (artistMatches && albumMatches))
                        {
                            // if two of them match, guessing this track is correct is
                            // probably better than just using the firstordefault, but keep looping hoping for a better track
                            trackToAdd = track;
                        }
                        else if (artistMatches && trackToAdd == null)
                        {
                            // if just the artist matches and we haven't found anything yet... this might be our best guess
                            trackToAdd = track;
                        }
                    }

                    if (trackToAdd == null)
                    {
                        trackToAdd = search.Tracks.Items.FirstOrDefault();
                        Log($"Didn't find a perfect match for {searchStr} for '{title}' by '{artist}', so using '{trackToAdd.Name}' by '{trackToAdd.Artists.FirstOrDefault().Name}' instead");
                    }

                    songsToAdd.Add(trackToAdd);
                }

                List <string> uris = songsToAdd.ConvertAll(x => x.Uri);
                while (uris.Count > 0)
                {
                    List <string> currUris = uris.Take(75).ToList();
                    if (currUris.Count == 0)
                    {
                        break;
                    }

                    uris.RemoveRange(0, currUris.Count);
                    var request = new PlaylistAddItemsRequest(currUris);
                    var resp    = await Spotify.Playlists.AddItems(thisPlaylistId, request);

                    if (resp == null)
                    {
                        Log("Error while trying to update playlist with track uris");
                        return(errors);
                    }
                }
            }

            return(errors);
        }