public void Should_serialize_playlist_as_expected()
        {
            var expectedXmlOutput = File.ReadAllText("StubRequests/Playlist.xml").Replace("\r\n", "").Replace("\t", "");
            var playlist          = new PlaylistRequest
            {
                Name       = "Test Playlist",
                Visibility = PlaylistVisibilityType.Private,
                Tracks     = new List <Product>
                {
                    new Product
                    {
                        ArtistAppearsAs        = "MGMT",
                        ArtistId               = "123",
                        AudioUrl               = "test.mp3",
                        ReleaseArtistAppearsAs = "MGMT",
                        ReleaseArtistId        = "123",
                        ReleaseId              = "123",
                        ReleaseTitle           = "Oracula Spectacular",
                        ReleaseVersion         = "extended",
                        Source       = "local",
                        TrackId      = "123",
                        TrackTitle   = "Weekend Wars",
                        TrackVersion = "deluxe",
                        ImageUrl     = "http://my.image.com/image.jpg"
                    }
                }
            };

            _fluentApi.WithPayload(playlist);

            var xml = new XmlPayloadSerializer().Serialize(playlist);

            Assert.That(xml, Is.EqualTo(expectedXmlOutput));
        }
        public async Task <Playlist> CrawlAsync(PlaylistRequest request)
        {
            var playlistBuilder = new PlaylistBuilder()
                                  .SetStart(request.Start)
                                  .SetEnd(request.End);

            PlaylistItem lastItem = null;
            DateTime     end      = request.End;

            do
            {
                System.Diagnostics.Debug.WriteLine($"Start request for time: {end.ToString()}");
                var html = await httpCrawler.GetHtmlAsync(end);

                var items = parser.ParseHtmlPlaylist(html);

                foreach (var item in items)
                {
                    System.Diagnostics.Debug.WriteLine($"Handle item at ${item.Time.ToString()}");
                    if (item.Time >= request.Start &&
                        item.Time < request.End &&
                        !playlistBuilder.HasItem(item.Time, item.Title, item.Artist))
                    {
                        playlistBuilder.AddItem(item);
                        lastItem = item;
                    }

                    end = item.Time;
                }
            } while (lastItem != null && end >= request.Start);

            return(playlistBuilder.GetPlaylist());
        }
        public async Task <PlayList> Create(PlaylistRequest plRequest)
        {
            var playlist = new PlayList();

            if (plRequest != null)
            {
                PlayList checkName = new PlayList();
                foreach (var item in GetAll().Where(x => x.UserId == plRequest.UserId))
                {
                    if (ConvertUnSigned.convertToUnSign(item.Name.ToLower()).Contains(ConvertUnSigned.convertToUnSign(plRequest.Name.ToLower())))
                    {
                        checkName = item;
                        break;
                    }
                }
                if (checkName.Name == null)
                {
                    playlist.Name       = plRequest.Name;
                    playlist.Status     = plRequest.Status;
                    playlist.UserId     = plRequest.UserId;
                    playlist.CreateDate = new GetDateNow().DateNow;
                    _context.PlayList.Add(playlist);
                    await _context.SaveChangesAsync();

                    var getPlaylist = _context.PlayList.OrderByDescending(x => x.Id).
                                      FirstOrDefault(x => x.Name == plRequest.Name && x.UserId == plRequest.UserId);
                    return(getPlaylist);
                }
            }
            return(null);
        }
        private async void SyncPlaylist()
        {
            IsBusy = true;
            var selectedPlaylist = Playlist;

            // Step One: Download playlist from 1LIVE
            Status   = "(1/3) Lade 1LIVE Playlist herunter";
            Progress = null;

            var request = new PlaylistRequest
            {
                Start = StartTime.Value,
                End   = EndTime.Value
            };

            var playlist = await crawler.CrawlAsync(request);

            // Step Two: Search tracks at Spotify

            Progress = 0;

            var i      = 0;
            var tracks = new List <Track>();

            SearchResults.Clear();

            foreach (var item in playlist.Items)
            {
                Status = $"(2/3) Suche {item.Artist} - {item.Title}";

                var track = await spotify.SearchOneTrackAsync(item.Artist, item.Title);

                if (track != null)
                {
                    tracks.Add(track);
                }

                var result = new SearchResult
                {
                    SpotifyTrack = track,
                    PlaylistItem = item
                };

                SearchResults.Add(result);

                i++;
                Progress = ((double)i / playlist.Items.Count) * 100;
            }

            // Step Three: Replace playlist tracks with new track list
            Progress = null;
            Status   = "(3/3) Aktualisiere Playlist";

            await spotify.UpdatePlaylistTracksAsync(selectedPlaylist, tracks);

            Progress = 0;
            Status   = "Fertig 😊";

            IsBusy = false;
        }
Exemplo n.º 5
0
        public void Should_serialize_playlist_request_to_json()
        {
            var playlistRequest = new PlaylistRequest
            {
                Description = "A New Playlist Description",
                ImageUrl    = "an-image-url",
                Name        = "New Playlist",
                Tracks      = new List <Product> {
                    new Product {
                        TrackId = "12345"
                    },
                    new Product {
                        TrackId = "98765"
                    }
                },
                Status = "Published",
                Tags   = new List <Tag>
                {
                    new Tag {
                        Name = "tag1", PlaylistPosition = 1
                    },
                    new Tag {
                        Name = "tag2"
                    }
                },
                Visibility  = PlaylistVisibilityType.Private,
                Annotations = new List <Annotation>
                {
                    new Annotation("key", "value"),
                    new Annotation("another key", "another value")
                }
            };

            var json = new JsonPayloadSerializer().Serialize(playlistRequest);

            Debug.WriteLine(json);

            var expectedJson = string.Join("",
                                           "{",
                                           "\"tracks\":[{\"trackId\":\"12345\"},{\"trackId\":\"98765\"}],",
                                           "\"name\":\"New Playlist\",",
                                           "\"visibility\":\"Private\",",
                                           "\"status\":\"Published\",",
                                           "\"description\":\"A New Playlist Description\",",
                                           "\"imageUrl\":\"an-image-url\",",
                                           "\"tags\":[{\"name\":\"tag1\",\"playlistPosition\":1},{\"name\":\"tag2\",\"playlistPosition\":null}],",
                                           "\"annotations\":{",
                                           "\"key\":\"value\",",
                                           "\"another key\":\"another value\"",
                                           "}",
                                           "}"
                                           );

            Assert.That(json, Is.EqualTo(expectedJson));
        }
        public async Task <int> Update(PlaylistRequest plRequest)
        {
            var playlist = _context.PlayList.FirstOrDefault(X => X.Id == plRequest.Id);

            if (playlist != null)
            {
                playlist.Name = plRequest.Name;
                _context.Update(playlist);
                return(await _context.SaveChangesAsync());
            }
            return(-1);
        }
        public async Task <IActionResult> UpdateName(PlaylistRequest request)
        {
            if (request != null)
            {
                var result = await _playlistService.Update(request);

                if (result > 0)
                {
                    return(Content("Success"));
                }
            }
            return(Content("Error"));
        }
Exemplo n.º 8
0
        public void Should_serialize_playlist_request_to_xml()
        {
            var playlistRequest = new PlaylistRequest
            {
                Description = "A New Playlist Description",
                ImageUrl    = "an-image-url",
                Name        = "New Playlist",
                Tracks      = new List <Product> {
                    new Product {
                        TrackId = "12345"
                    },
                    new Product {
                        TrackId = "98765"
                    }
                },
                Status = "Published",
                Tags   = new List <Tag>
                {
                    new Tag {
                        Name = "tag1", PlaylistPosition = 1
                    },
                    new Tag {
                        Name = "tag2"
                    }
                },
                Visibility  = PlaylistVisibilityType.Private,
                Annotations = new List <Annotation>
                {
                    new Annotation("key", "value"),
                    new Annotation("another key", "another value")
                }
            };

            var xml = new XmlPayloadSerializer().Serialize(playlistRequest);

            Debug.WriteLine(xml);

            const string expectedXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                       "<playlist>" +
                                       "<name>New Playlist</name>" +
                                       "<visibility>Private</visibility>" +
                                       "<status>Published</status>" +
                                       "<description>A New Playlist Description</description>" +
                                       "<image>an-image-url</image>" +
                                       "<tags><tag><name>tag1</name><playlistPosition>1</playlistPosition></tag><tag><name>tag2</name><playlistPosition p4:nil=\"true\" xmlns:p4=\"http://www.w3.org/2001/XMLSchema-instance\" /></tag></tags>" +
                                       "<annotations><annotation key=\"key\">value</annotation><annotation key=\"another key\">another value</annotation></annotations>" +
                                       "<tracks><track><trackId>12345</trackId></track><track><trackId>98765</trackId></track></tracks>" +
                                       "</playlist>";

            Assert.That(xml, Is.EqualTo(expectedXml));
        }
        public static void ProcessPlaylistRequest(PlaylistRequest request, AppDbContext context)
        {
            var authObj = context.AuthenticationObjects.FirstOrDefault();

            if (authObj == null)
            {
                return;
            }

            var user = ClientApi.QueryServiceForCurrentUser(authObj);

            var playlist = CreatePlaylist(request, authObj, user);
            var tracks   = GenerateTracksForPlaylist(authObj, request).ToList();

            AddTracksToPlaylist(authObj, playlist, tracks);
        }
        public async Task <ActionResult> Create(PlaylistRequest request)
        {
            if (request != null)
            {
                var result = await _playlistService.Create(request);

                if (result != null)
                {
                    var playlist_vm = new DetailPlayListVideo();
                    playlist_vm.Id          = result.Id;
                    playlist_vm.Name        = result.Name;
                    playlist_vm.UserId      = result.UserId;
                    playlist_vm.PosterVideo = null;
                    playlist_vm.Status      = result.Status;
                    playlist_vm.CreateDate  = result.CreateDate;
                    return(Content(JsonConvert.SerializeObject(playlist_vm)));
                }
            }
            return(Content("null"));
        }
        private static SpotifyPlaylist CreatePlaylist(PlaylistRequest request, AuthenticationObject authObj, SpotifyUser user)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authObj.access_token);

                var httpRequest = new HttpRequestMessage(HttpMethod.Post, $"https://api.spotify.com/v1/users/{user.id}/playlists")
                {
                    Content = new StringContent($"{{\"name\":\"{request.Name}\"}}",
                                                Encoding.UTF8,
                                                "application/json")
                };

                httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                var response = client.SendAsync(httpRequest).Result;

                var responseContent = response.Content.ReadAsStringAsync().Result;

                return(JsonConvert.DeserializeObject <SpotifyPlaylist>(responseContent));
            }
        }
        public string GetAllUserPlaylists([FromBody] PlaylistRequest request)
        {
            List <Playlist> playlists = new List <Playlist>();
            int             offset    = 0;
            WebClient       web       = new WebClient();

            web.Headers.Set("Authorization", $"Bearer {request.accessToken}");
            bool looper = true;

            while (looper)
            {
                JObject response = JObject.Parse(web.DownloadString(request.userUrl + $"/playlists?offset={offset}&limit=50"));
                JArray  items    = response["items"].ToObject <JArray>();
                foreach (JObject item in items)
                {
                    Playlist playlist = new Playlist
                    {
                        name = item["name"].ToString(),
                        href = item["href"].ToString(),
                        uri  = item["uri"].ToString(),
                    };
                    playlists.Add(playlist);
                }
                int count = items.Count;
                if (count == 50)
                {
                    offset += 50;
                }
                else
                {
                    looper = false;
                }
            }
            string result = JsonConvert.SerializeObject(playlists);

            return(result);
        }
        private static IEnumerable <SpotifyTrack> GenerateTracksForPlaylist(AuthenticationObject authObj, PlaylistRequest request)
        {
            var tracksForPlaylist = new List <SpotifyTrack>();
            var avoidableTracks   = new List <SpotifyTrack>();
            var coveredDuration   = 0;
            var overshootLimit    = 30000;
            var maxNumberOfTries  = 50;
            var numberOfTries     = 0;

            while (coveredDuration < request.Duration * 60000 - 10000 && numberOfTries < maxNumberOfTries)
            {
                foreach (var playlistToLook in request.PlaylistsToLook)
                {
                    var tracks = GetPlaylistTracks(authObj, playlistToLook).Select(x => x.track).ToList();

                    var trackToAdd = tracks
                                     .OrderByDescending(x => x.popularity)
                                     .First();

                    if (trackToAdd == null)
                    {
                        numberOfTries++;
                        continue;
                    }
                    if (tracksForPlaylist.Select(x => x.id).ToList().Contains(trackToAdd.id) ||
                        avoidableTracks.Select(x => x.id).ToList().Contains(trackToAdd.id))
                    {
                        var random = new Random();
                        var index  = random.Next(2, tracks.Count());
                        trackToAdd = tracks.ElementAt(index);
                    }

                    if (coveredDuration + trackToAdd.duration_ms > request.Duration * 60000 + overshootLimit)
                    {
                        avoidableTracks.Add(trackToAdd);
                        numberOfTries++;
                        continue;
                    }

                    tracksForPlaylist.Add(trackToAdd);
                    coveredDuration += trackToAdd.duration_ms;
                }
            }
            return(tracksForPlaylist);
        }
Exemplo n.º 14
0
        public PlaylistRequest GetData(string name)
        {
            Log.Info("Generating test data for playlist " + name);
            PlaylistRequest data = new PlaylistRequest
                                       {
                                           DeviceId = Guid.NewGuid().ToString("N"),
                                           DeviceMediaRoot = "file:///SDCard/Blackberry/music/WiFiSync",
                                           PlaylistDevicePath =
                                               "file:///SDCard/Blackberry/music/WiFiSync/" + name + ".m3u"
                                       };
            IPlaylist pls = CachedXmlLibrary.Library.GetFirstPlaylistByName(name);
            if(pls != null){
                data.PlaylistData = (from t in pls.Tracks
                                     select t.GetPlaylistLine(data.DeviceMediaRoot)).ToArray();
            }

            ResetStatusLater();
            return data;
        }
Exemplo n.º 15
0
 /// <summary>
 /// Gets the path to a particular playlist.
 /// </summary>
 public static string GetDevicePlaylistPath(PlaylistRequest request)
 {
     return GetDevicePlaylistPath(request.SafeDeviceId, request.SafePlaylistDevicePath);
 }
Exemplo n.º 16
0
 public IActionResult Update(int id, PlaylistRequest r) =>
 Repo
 .Update(r.ToModel(id))
 .ToActionResult(x => ToGetPlaylistReply(x));
Exemplo n.º 17
0
 public IActionResult Create(PlaylistRequest r) =>
 Repo
 .Create(r.ToModel())
 .ToActionResult(x => ToGetPlaylistShortReply(x.Value));