Пример #1
0
        public async Task <string> TranslateAsync(string text, string langTo, string langFrom = null)
        {
            await this.UpdateAccessTokenIfExpired()
            .ConfigureAwait(false);

            var param = new Dictionary <string, string>
            {
                ["text"] = text,
                ["to"]   = langTo,
            };

            if (langFrom != null)
            {
                param["from"] = langFrom;
            }

            var requestUri = new Uri(TranslateEndpoint, "?" + MyCommon.BuildQueryString(param));

            using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken);

                using (var response = await this.Http.SendAsync(request).ConfigureAwait(false))
                {
                    return(await response.Content.ReadAsStringAsync()
                           .ConfigureAwait(false));
                }
            }
        }
Пример #2
0
        public Task DirectMessagesEventsDestroy(string eventId)
        {
            var endpoint = new Uri("direct_messages/events/destroy.json", UriKind.Relative);
            var param    = new Dictionary <string, string>
            {
                ["id"] = eventId.ToString(),
            };

            // なぜか application/x-www-form-urlencoded でパラメーターを送ると Bad Request になる謎仕様
            endpoint = new Uri(endpoint.OriginalString + "?" + MyCommon.BuildQueryString(param), UriKind.Relative);

            return(this.apiConnection.DeleteAsync(endpoint));
        }
Пример #3
0
        public async Task <string> GetAsync(Uri endpoint, IEnumerable <KeyValuePair <string, string> > param)
        {
            var paramWithToken = param.Concat(this.CreateAccessTokenParams());

            var requestUri = new Uri(new Uri(ApiBase, endpoint), "?" + MyCommon.BuildQueryString(paramWithToken));

            using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
                using (var response = await this.http.SendAsync(request).ConfigureAwait(false))
                {
                    return(await response.Content.ReadAsStringAsync()
                           .ConfigureAwait(false));
                }
        }
Пример #4
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var query = await GetParameters(request.RequestUri, request.Content)
                        .ConfigureAwait(false);

            var credential = OAuthUtility.CreateAuthorization(request.Method.ToString().ToUpperInvariant(), request.RequestUri, query,
                                                              this.ConsumerKey, this.ConsumerSecret, this.AccessToken, this.AccessSecret);

            request.Headers.TryAddWithoutValidation("Authorization", credential);

            if (request.Content is FormUrlEncodedContent postContent)
            {
                request.Content = new StringContent(MyCommon.BuildQueryString(query), Encoding.UTF8, "application/x-www-form-urlencoded");
                postContent.Dispose();
            }

            return(await base.SendAsync(request, cancellationToken)
                   .ConfigureAwait(false));
        }
Пример #5
0
        /// <summary>
        /// Foursquare のチェックイン URL から位置情報を取得します
        /// </summary>
        public async Task <GlobalLocation> FetchCheckinLocation(string url, CancellationToken token)
        {
            var match = UrlPatternRegex.Match(url);

            if (!match.Success)
            {
                return(null);
            }

            var checkinIdGroup = match.Groups["checkin_id"];

            try
            {
                // Foursquare のチェックイン情報を取得
                // 参照: https://developer.foursquare.com/docs/checkins/resolve

                var query = new Dictionary <string, string>
                {
                    ["client_id"]     = ApplicationSettings.FoursquareClientId,
                    ["client_secret"] = ApplicationSettings.FoursquareClientSecret,
                    ["v"]             = "20140419", // https://developer.foursquare.com/overview/versioning

                    ["shortId"] = checkinIdGroup.Value,
                };

                var apiUrl = new Uri(ApiBase + "/checkins/resolve?" + MyCommon.BuildQueryString(query));

                using (var response = await this.http.GetAsync(apiUrl, token).ConfigureAwait(false))
                {
                    response.EnsureSuccessStatusCode();

                    var jsonBytes = await response.Content.ReadAsByteArrayAsync()
                                    .ConfigureAwait(false);

                    return(ParseIntoLocation(jsonBytes));
                }
            }
            catch (HttpRequestException)
            {
                return(null);
            }
        }
Пример #6
0
        protected virtual async Task <XDocument> FetchContentInfoApiAsync(string contentId, CancellationToken token)
        {
            var query = new Dictionary <string, string>
            {
                ["api_key"] = ApplicationSettings.TINAMIApiKey,
                ["cont_id"] = contentId,
            };

            var apiUrl = new Uri("http://api.tinami.com/content/info?" + MyCommon.BuildQueryString(query));

            using (var response = await this.http.GetAsync(apiUrl, token).ConfigureAwait(false))
            {
                response.EnsureSuccessStatusCode();

                var xmlStr = await response.Content.ReadAsStringAsync()
                             .ConfigureAwait(false);

                return(XDocument.Parse(xmlStr));
            }
        }
Пример #7
0
        public static string CreateSignature(string consumerSecret, string?tokenSecret, string method, Uri uri, Dictionary <string, string> parameter)
        {
            // パラメタをソート済みディクショナリに詰替(OAuthの仕様)
            var sorted = new SortedDictionary <string, string>(parameter);
            // URLエンコード済みのクエリ形式文字列に変換
            var paramString = MyCommon.BuildQueryString(sorted);
            // アクセス先URLの整形
            var url = string.Format("{0}://{1}{2}", uri.Scheme, uri.Host, uri.AbsolutePath);
            // 署名のベース文字列生成(&区切り)。クエリ形式文字列は再エンコードする
            var signatureBase = string.Format("{0}&{1}&{2}", method, MyCommon.UrlEncode(url), MyCommon.UrlEncode(paramString));
            // 署名鍵の文字列をコンシューマー秘密鍵とアクセストークン秘密鍵から生成(&区切り。アクセストークン秘密鍵なくても&残すこと)
            var key = MyCommon.UrlEncode(consumerSecret) + "&";

            if (!MyCommon.IsNullOrEmpty(tokenSecret))
            {
                key += MyCommon.UrlEncode(tokenSecret);
            }
            // 鍵生成&署名生成
            using var hmac = new HMACSHA1(Encoding.ASCII.GetBytes(key));
            var hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(signatureBase));

            return(Convert.ToBase64String(hash));
        }
Пример #8
0
        public override async Task <ThumbnailInfo> GetThumbnailInfoAsync(string url, PostClass post, CancellationToken token)
        {
            // ツイートに位置情報が付与されている場合は何もしない
            if (post.PostGeo.Lat != 0 || post.PostGeo.Lng != 0)
            {
                return(null);
            }

            var match = UrlPatternRegex.Match(url);

            if (!match.Success)
            {
                return(null);
            }

            var checkinIdGroup = match.Groups["checkin_id"];
            var signatureGroup = match.Groups["signature"];

            try
            {
                // Foursquare のベニュー情報を取得
                // 参照: https://developer.foursquare.com/docs/venues/venues

                var query = new Dictionary <string, string>
                {
                    { "client_id", ApplicationSettings.FoursquareClientId },
                    { "client_secret", ApplicationSettings.FoursquareClientSecret },
                    { "v", "20140419" }, // https://developer.foursquare.com/overview/versioning
                };

                if (signatureGroup.Success)
                {
                    query["signature"] = signatureGroup.Value;
                }

                var apiUrl = new Uri(ApiBase + "/checkins/" + checkinIdGroup.Value + "?" + MyCommon.BuildQueryString(query));

                using (var response = await this.http.GetAsync(apiUrl, token).ConfigureAwait(false))
                {
                    response.EnsureSuccessStatusCode();

                    var jsonBytes = await response.Content.ReadAsByteArrayAsync()
                                    .ConfigureAwait(false);

                    var location = ParseIntoLocation(jsonBytes);
                    if (location == null)
                    {
                        return(null);
                    }

                    var map = MapThumb.GetDefaultInstance();

                    return(new ThumbnailInfo
                    {
                        ImageUrl = map.CreateMapLinkUrl(location.Latitude, location.Longitude),
                        ThumbnailUrl = map.CreateStaticMapUrl(location.Latitude, location.Longitude),
                        TooltipText = null,
                    });
                }
            }
            catch (HttpRequestException) { }

            return(null);
        }
Пример #9
0
        public override async Task <ThumbnailInfo> GetThumbnailInfoAsync(string url, PostClass post, CancellationToken token)
        {
            var match = Tumblr.UrlPatternRegex.Match(url);

            if (!match.Success)
            {
                return(null);
            }

            // 参照: http://www.tumblr.com/docs/en/api/v2#photo-posts

            var host   = match.Groups["host"].Value;
            var postId = match.Groups["postId"].Value;

            var param = new Dictionary <string, string>
            {
                ["api_key"] = ApplicationSettings.TumblrConsumerKey,
                ["id"]      = match.Groups["postId"].Value,
            };

            try
            {
                var apiUrl = string.Format("https://api.tumblr.com/v2/blog/{0}/posts?", host) + MyCommon.BuildQueryString(param);
                using (var response = await this.http.GetAsync(apiUrl, token).ConfigureAwait(false))
                {
                    var jsonBytes = await response.Content.ReadAsByteArrayAsync()
                                    .ConfigureAwait(false);

                    var thumbs = ParsePhotoPostJson(jsonBytes);

                    return(thumbs.FirstOrDefault());
                }
            }
            catch (HttpRequestException) { } // たまに api.tumblr.com が名前解決できない

            return(null);
        }