Exemplo n.º 1
0
        public async Task <SpotifyPlaylist> SearchForPlaylist(string query)
        {
            var response = await _httpClient.GetAsync($"https://api.spotify.com/v1/search?q={query}&type=playlist");

            response.EnsureSpotifySuccess();

            var playlist = (await JsonSerializerExtensions.DeserializeAnonymousTypeAsync(
                                await response.Content.ReadAsStreamAsync(),
                                new
            {
                playlists = new
                {
                    items = default(IEnumerable <SpotifyPlaylist>)
                }
            })).playlists.items.FirstOrDefault();

            if (playlist == null)
            {
                throw new NoSearchResultException();
            }

            playlist.Tracks = await _playlistService.GetTracksInPlaylist(playlist.Id);

            return(playlist);
        }
Exemplo n.º 2
0
 private static LiveRecommendResponse ParseLiveRecommendJson(string json)
 {
     return(new LiveRecommendResponse()
     {
         _RecommendItems = JsonSerializerExtensions.Load <List <LiveRecommendData> >(json)
     });
 }
Exemplo n.º 3
0
            public static async Task <NicoliveVideoInfoResponse> GetLiveInfoAsync(NiconicoContext context, string liveId)
            {
                var json = await GetLiveInfoJsonAsync(context, liveId);

                var resContainer = JsonSerializerExtensions.Load <NicoliveVideoInfoResponseContainer>(json);

                return(resContainer.NicoliveVideoResponse);
            }
Exemplo n.º 4
0
            public static async Task <NicoliveCommunityVideoResponse> GetLiveCommunityVideoAsync(NiconicoContext context, string communityOrChannelId)
            {
                var json = await GetLiveCommunityVideoJsonAsync(context, communityOrChannelId);

                var resContainer = JsonSerializerExtensions.Load <NicoliveCommunityVideoResponseContainer>(json);

                return(resContainer.NicoliveVideoResponse);
            }
Exemplo n.º 5
0
        public static async Task <VideoInfoArrayResponse> GetVideoInfoArrayAsync(
            NiconicoContext context
            , IEnumerable <string> videoIdList
            )
        {
            var json = await GetVideoArrayDataAsync(context, videoIdList);

            var res = JsonSerializerExtensions.Load <VideoInfoArrayResponseContainer>(json);

            return(res.DataContainer);
        }
Exemplo n.º 6
0
        public async Task <IEnumerable <SpotifyTrack> > GetTopTracksForArtist(string id)
        {
            var response = await _httpClient.GetAsync($"https://api.spotify.com/v1/artists/{id}/top-tracks?market=GB");

            response.EnsureSpotifySuccess();

            return((await JsonSerializerExtensions.DeserializeAnonymousTypeAsync(await response.Content.ReadAsStreamAsync(),
                                                                                 new
            {
                tracks = default(IEnumerable <SpotifyTrack>)
            })).tracks);
        }
Exemplo n.º 7
0
        public async Task <T> GetValueAsync <T>(string key)
        {
            var value = await _database.StringGetAsync(key);

            if (value.HasValue)
            {
                return(JsonSerializerExtensions.DeserializeObject <T>(value));
            }
            else
            {
                return(default(T));
            }
        }
Exemplo n.º 8
0
        public async Task <IEnumerable <SpotifyTrack> > GetTracksForAlbum(string albumId)
        {
            var response = await _httpClient.GetAsync($"https://api.spotify.com/v1/albums/{albumId}/tracks");

            response.EnsureSpotifySuccess();

            return((await JsonSerializerExtensions.DeserializeAnonymousTypeAsync(
                        await response.Content.ReadAsStreamAsync(),
                        new
            {
                items = default(IEnumerable <SpotifyTrack>)
            })).items);
        }
Exemplo n.º 9
0
        public void ReadAnonymous()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();

            const string json      = @"{""Id"":12,""Name"":""foo""}";
            var          prototype = new { Id = default(int), Name = default(string) };

            var obj = JsonSerializerExtensions.DeserializeAnonymousType(json, prototype, options);

            Assert.Equal(12, obj.Id);
            Assert.Equal("foo", obj.Name);
        }
Exemplo n.º 10
0
        public async Task <IEnumerable <SpotifyAlbum> > GetDiscographyForArtist(string id)
        {
            var response = await _httpClient.GetAsync($"https://api.spotify.com/v1/artists/{id}/albums?market=GB&include_groups=album");

            response.EnsureSpotifySuccess();

            var albums = (await JsonSerializerExtensions.DeserializeAnonymousTypeAsync(await response.Content.ReadAsStreamAsync(),
                                                                                       new
            {
                items = default(IEnumerable <SpotifyAlbum>)
            })).items;

            //Spotify returns the albums in date order descending. Discography should be played in ascending order.
            return(albums.Reverse());
        }
Exemplo n.º 11
0
        public async Task <IEnumerable <SpotifyTrack> > SearchForTrack(string query)
        {
            var response = await _httpClient.GetAsync($"https://api.spotify.com/v1/search?q={query}&type=track");

            response.EnsureSpotifySuccess();

            return((await JsonSerializerExtensions.DeserializeAnonymousTypeAsync(await response.Content.ReadAsStreamAsync(),
                                                                                 new
            {
                tracks = new
                {
                    items = default(IEnumerable <SpotifyTrack>)
                }
            }))?.tracks?.items);
        }
Exemplo n.º 12
0
        private void AlterDocument(Func <JToken, bool> alterFunc)
        {
            PathEx.CreateFilePath(Filename);

            using (var stream = File.Open(Filename, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
                var document = Serializer.Deserialize(stream, true);

                if (!alterFunc(document))
                {
                    return;
                }

                stream.SetLength(0);
                JsonSerializerExtensions.Serialize(Serializer, stream, document);
            }
        }
Exemplo n.º 13
0
        private static RecommendResponse ParseRecommendPageHtml(string html)
        {
            const string Nico_RecommendationsParams = "Nico_RecommendationsParams=";

            var index        = html.IndexOf(Nico_RecommendationsParams);
            int openBrakets  = 0;
            int closeBrakets = 0;
            int cnt          = 0;

            // {}の個数を数えて、イコールになった地点までをリコメンドパラメータJSONとして取得する
            foreach (var c in html.Skip(index + Nico_RecommendationsParams.Length))
            {
                if (c == '{')
                {
                    ++openBrakets;
                }
                else if (c == '}')
                {
                    ++closeBrakets;
                }

                ++cnt;

                if (openBrakets == closeBrakets)
                {
                    break;
                }
            }

            if (openBrakets != closeBrakets)
            {
                throw new Exception("Failed recommend page parse, page not contains <Nico_RecommendationsParams>");
            }

            var recommendFirstParam = new string(html.Skip(index + Nico_RecommendationsParams.Length).Take(cnt).ToArray());

            // JSONのルートオブジェクトのキーがダブルクオーテーションで囲まれていないことへの対処
            var replaced = recommendFirstParam;

            replaced = replaced.Replace("page:", "\"page\":");
            replaced = replaced.Replace("seed:", "\"seed\":");
            replaced = replaced.Replace("user_tag_param:", "\"user_tag_param\":");
            replaced = replaced.Replace("compiled_tpl:", "\"compiled_tpl\":");
            replaced = replaced.Replace("first_data:", "\"first_data\":");

            return(JsonSerializerExtensions.Load <RecommendResponse>(replaced));
        }
Exemplo n.º 14
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task <List <T> > HashValuesAsync <T>(string key)
        {
            var result = new List <T>();

            HashEntry[] arr = await _database.HashGetAllAsync(key);

            foreach (var item in arr)
            {
                string values = item.Name;
                if (!item.Value.IsNullOrEmpty)
                {
                    var val = JsonSerializerExtensions.DeserializeObject <T>(item.Value);
                    result.Add(val);
                }
            }
            return(result);
        }
Exemplo n.º 15
0
        public void ConfigureServices(IServiceCollection services)
        {
            ConfigureSettings(services);
            var jsonOptions = JsonSerializerExtensions.GetDefaultJsonSerializerSettings();

            services.ConfigureHealthChecks(Configuration);
            services.AddControllers()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.DateFormatString  = jsonOptions.DateFormatString;
                options.SerializerSettings.NullValueHandling = jsonOptions.NullValueHandling;
                options.SerializerSettings.ContractResolver  = jsonOptions.ContractResolver;
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
            });

            ConfigureDatabases(services);
            services.ConfigureSwaggerSettings(Configuration);
            services.ConfigureSwaggerInfo();
        }
Exemplo n.º 16
0
        public async Task <IEnumerable <SpotifyTrack> > GetTracksInPlaylist(string id)
        {
            var response = await _httpClient.GetAsync($"https://api.spotify.com/v1/playlists/{id}/tracks?market=GB");

            response.EnsureSpotifySuccess();

            var items = (await JsonSerializerExtensions.DeserializeAnonymousTypeAsync(await response.Content.ReadAsStreamAsync(),
                                                                                      new
            {
                items = default(IEnumerable <SpotifyPlaylistTrack>)
            })).items.ToList();

            if (items.IsNullOrEmpty())
            {
                throw new NoSearchResultException();
            }

            return(items.Select(x => x.Track));
        }
Exemplo n.º 17
0
        public async Task <SpotifyArtist> SearchForArtist(string query, ArtistOption option)
        {
            var metadataResponse = await _httpClient.GetAsync($"https://api.spotify.com/v1/search?q={query}&type=artist");

            metadataResponse.EnsureSpotifySuccess();

            var artist = (await JsonSerializerExtensions.DeserializeAnonymousTypeAsync(
                              await metadataResponse.Content.ReadAsStreamAsync(),
                              new
            {
                artists = new
                {
                    items = default(IEnumerable <SpotifyArtist>)
                }
            })).artists.items.FirstOrDefault();

            if (artist == null)
            {
                throw new NoSearchResultException();
            }

            if (option == ArtistOption.Discography)
            {
                artist.Tracks = await _albumService.GetTracksFromAlbumCollection(await _artistService.GetDiscographyForArtist(artist.Id));
            }

            if (option == ArtistOption.Popular)
            {
                artist.Tracks = await _artistService.GetTopTracksForArtist(artist.Id);
            }

            if (option == ArtistOption.Essential)
            {
                artist.Tracks = (await SearchForPlaylist($"This Is {artist.Name}")).Tracks;
            }

            if (artist.Tracks.IsNullOrEmpty())
            {
                throw new NoSearchResultException();
            }

            return(artist);
        }
Exemplo n.º 18
0
        public async Task <List <ShopperHistory> > GetShopperHistoryAsync()
        {
            using var responseMessage =
                      await _httpClient.GetAsync($"shopperHistory?token={_productServiceConfig.Token}");

            try
            {
                var stream = await responseMessage.Content.ReadAsStreamAsync();

                responseMessage.EnsureSuccessStatusCode();
                var serializerOptions = JsonSerializerExtensions.GetDefaultJsonSerializerOptions();
                return(await JsonSerializer.DeserializeAsync <List <ShopperHistory> >(stream,
                                                                                      serializerOptions));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "ProductServiceException.GetShopperHistoryAsync");
                throw new ProductServiceException(
                          $"ProductServiceException.GetShopperHistoryAsync {ex.Message} {responseMessage.StatusCode}");
            }
        }
Exemplo n.º 19
0
        public async Task <SpotifyAlbum> SearchForAlbum(string query)
        {
            var metadataResponse = await _httpClient.GetAsync($"https://api.spotify.com/v1/search?q={query}&type=album");

            metadataResponse.EnsureSpotifySuccess();

            var album = (await JsonSerializerExtensions.DeserializeAnonymousTypeAsync(await metadataResponse.Content.ReadAsStreamAsync(),
                                                                                      new
            {
                albums = new
                {
                    items = default(IEnumerable <SpotifyAlbum>)
                }
            })).albums.items.FirstOrDefault();

            if (album == null)
            {
                throw new NoSearchResultException();
            }

            var albumResponse = await _httpClient.GetAsync($"https://api.spotify.com/v1/albums/{album.Id}/tracks");

            albumResponse.EnsureSpotifySuccess();

            album.Tracks = (await JsonSerializerExtensions.DeserializeAnonymousTypeAsync(
                                await albumResponse.Content.ReadAsStreamAsync(),
                                new
            {
                items = default(IEnumerable <SpotifyTrack>)
            })).items;

            if (album.Tracks.IsNullOrEmpty())
            {
                throw new NoSearchResultException();
            }

            return(album);
        }
Exemplo n.º 20
0
        public async Task <ActionResult> ImportFromFile(HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (file == null)
                {
                    TempData["Info"] = "Please select a file to upload";
                }
                else if (file.ContentLength > 0)
                {
                    string[] allowedFileExtensions = new string[] { ".csf" };

                    if (!allowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
                    {
                        TempData["Info"] = "Please select a file of type: " + string.Join(", ", allowedFileExtensions);
                    }
                    else
                    {
                        StreamReader stream      = new StreamReader(file.InputStream);
                        var          fileContent = stream.ReadToEnd();
                        stream.Close();
                        Dictionary <string, string> fileSettings = JsonSerializerExtensions.FromJson <Dictionary <string, string> >(fileContent);
                        if (fileSettings.Any())
                        {
                            SaveConfigurationChanges(fileSettings);
                            SetAdminSettings(fileSettings);
                        }

                        TempData["Info"] = "Settings uploaded from file and updated";

                        // Wait for settings to be updated before reloading the page
                        await Task.Delay(2000);
                    }
                }
            }

            return(RedirectToAction("Index"));
        }
Exemplo n.º 21
0
        public async Task <decimal> GetTrollyTotalAsync(TrolleyTotalRequest request)
        {
            HttpContent httpContent = new StringContent(JsonSerializer.Serialize(request),
                                                        Encoding.UTF8, MediaTypeNames.Application.Json);

            using var responseMessage =
                      await _httpClient.PostAsync(
                          $"trolleyCalculator?token={_productServiceConfig.Token}", httpContent);

            try
            {
                var response = await responseMessage.Content.ReadAsStreamAsync();

                responseMessage.EnsureSuccessStatusCode();
                var serializerOptions = JsonSerializerExtensions.GetDefaultJsonSerializerOptions();
                return(await JsonSerializer.DeserializeAsync <decimal>(response, serializerOptions));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "ProductServiceException.GetTrollyTotalAsync");
                throw new ProductServiceException(
                          $"ProductServiceException, {ex.Message} {responseMessage.StatusCode}");
            }
        }
Exemplo n.º 22
0
        public static async Task <LiveSearchResponse> GetLiveSearchAsync(
            NiconicoContext context,
            string q,
            int offset,
            int limit,
            SearchTargetType targets    = SearchTargetType.All,
            LiveSearchFieldType fields  = LiveSearchFieldType.ContentId,
            LiveSearchSortType sortType = LiveSearchSortType.StartTime | LiveSearchSortType.SortDecsending,
            ISearchFilter searchFilter  = null
            )
        {
            if (string.IsNullOrWhiteSpace(q))
            {
                throw new ArgumentException("q value must contains any character.");
            }
            if (offset < 0 || offset >= SearchConstants.MaxSearchOffset)
            {
                throw new ArgumentException("offset value out of bounds. (0 <= offset <= 1600)");
            }

            if (limit < 0 || limit >= SearchConstants.MaxSearchLimit)
            {
                throw new ArgumentException("limit value out of bounds. (0 <= limit <= 100)");
            }

            var dict = new Dictionary <string, string>()
            {
                { SearchConstants.QuaryParameter, q },
                { SearchConstants.OffsetParameter, offset.ToString() },
                { SearchConstants.LimitParameter, limit.ToString() },
                { SearchConstants.TargetsParameter, SearchHelpers.ToQueryString(targets) },
            };

            if (context.AdditionalUserAgent != null)
            {
                dict.Add(SearchConstants.ContextParameter, context.AdditionalUserAgent);
            }

            if (fields != LiveSearchFieldType.None)
            {
                dict.Add(SearchConstants.FieldsParameter, SearchHelpers.ToQueryString(fields));
            }

            if (sortType != LiveSearchSortType.None)
            {
                dict.Add(SearchConstants.SortParameter, SearchHelpers.ToQueryString(sortType));
            }

            if (searchFilter != null)
            {
                var filters = searchFilter.GetFilterKeyValues();
                foreach (var f in filters)
                {
                    dict.Add(f.Key, f.Value);
                }
            }

            var json = await context.GetStringAsync(SearchConstants.LiveSearchEndPoint, dict);

            return(JsonSerializerExtensions.Load <LiveSearchResponse>(json));
        }
Exemplo n.º 23
0
 public static OnAirStreamsResponse ParseOnAirStreamsData(string onAirStreamsData)
 {
     return(JsonSerializerExtensions.Load <OnAirStreamsResponse>(onAirStreamsData));
 }
Exemplo n.º 24
0
 public static SearchProgramsResponse ParseSearchProgramsData(string searchProgramsData)
 {
     return(JsonSerializerExtensions.Load <SearchProgramsResponseWrapper>(ProgramsResponseWrapper.PatchJson2(searchProgramsData)).Response);
 }
Exemplo n.º 25
0
 public static RemoveHistoryResponse ParseRemoveHistoryData(string historiesData)
 {
     return(JsonSerializerExtensions.Load <RemoveHistoryResponse>(historiesData));
 }
Exemplo n.º 26
0
 public static ChannelFollowResult ParseChannelFollowResult(string json)
 {
     return(JsonSerializerExtensions.Load <ChannelFollowResult>(json));
 }
Exemplo n.º 27
0
        private static MylistSearchResponse ParseVideoResponseJson(string mylistSearchResponseJson)
        {
            var responseContainer = JsonSerializerExtensions.Load <MylistSearchResponseContainer>(mylistSearchResponseJson);

            return(responseContainer.nicovideo_mylist_response);
        }
Exemplo n.º 28
0
        public static async Task <ProgramInfo> GetProgramInfoAsync(NiconicoContext context, string liveId)
        {
            var json = await context.GetStringAsync($"http://live2.nicovideo.jp/watch/{liveId}/programinfo");

            return(JsonSerializerExtensions.Load <ProgramInfo>(json));
        }
Exemplo n.º 29
0
        private static VideoListingResponse ParseVideoResponseJson(string videoSearchResponseJson)
        {
            var responseContainer = JsonSerializerExtensions.Load <VideoListingResponseContainer>(videoSearchResponseJson);

            return(responseContainer.niconico_response);
        }
Exemplo n.º 30
0
        private static VideoInfoResponse ParseVideoInfoResponseJson(string json)
        {
            var responseContainer = JsonSerializerExtensions.Load <VideoInfoResponseContainer>(json);

            return(responseContainer.NicovideoVideoResponse);
        }