Ejemplo n.º 1
0
        public async Task <bool> GetInfo(AccessToken token, string path, CancellationTokenSource cts)
        {
            var args = new GetInfoCompletedArgs();

            if (NetworkInterface.NetworkInterfaceType == NetworkInterfaceType.None)
            {
                args.Canceled = true;
                OnGetInfoFinished(args);
                return(true);
            }
            try
            {
                using (var client = OAuthUtility.CreateOAuthClient(ConsumerKey, ConsumerSecret, token))
                {
                    if (!Cts.Token.IsCancellationRequested)
                    {
                        using (Cts.Token.Register(() => client.CancelPendingRequests()))
                        {
                            args.Json = await client.GetStringAsync(BaseUrl + path);

                            args.Canceled = false;
                        }
                        OnGetInfoFinished(args);
                    }
                }
            }
            catch (Exception)
            {
                CancelTask();
                args.Canceled = true;
                OnGetInfoFinished(args);
            }
            return(true);
        }
Ejemplo n.º 2
0
        // if you use Rx, you can write follows
        public IObservable <string> GetStream()
        {
            return(Observable.Create <string>(async(observer, ct) =>
            {
                try
                {
                    var client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);
                    client.Timeout = System.Threading.Timeout.InfiniteTimeSpan; // set infinite timespan

                    using (var stream = await client.GetStreamAsync("https://userstream.twitter.com/1.1/user.json").ConfigureAwait(false))
                        using (var sr = new StreamReader(stream))
                        {
                            while (!sr.EndOfStream && !ct.IsCancellationRequested)
                            {
                                var s = await sr.ReadLineAsync().ConfigureAwait(false);
                                s = Regex.Unescape(s);
                                observer.OnNext(HttpUtility.HtmlDecode(s));
                            }
                        }
                }
                catch (Exception ex)
                {
                    observer.OnError(ex);
                    return;
                }
                if (!ct.IsCancellationRequested)
                {
                    observer.OnCompleted();
                }
            }));
        }
Ejemplo n.º 3
0
 public IObservable <HttpClient> Authorize(string pincode)
 {
     return(authorizer.GetAccessToken(accessTokenUrl, requestToken, pincode)
            .ToObservable()
            .Do(x => Setting.AccessToken = x.Token)
            .Select(x => OAuthUtility.CreateOAuthClient(key, secret, x.Token)));
 }
Ejemplo n.º 4
0
        public async Task <string> GetSims()
        {
            HttpClient client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            string json = await client.GetStringAsync(BaseUrl + "msisdn_list.json?alias=1");

            return(json);
        }
Ejemplo n.º 5
0
        //REFERRALS
        public async Task <string> GetVikingPointsReferrals()
        {
            HttpClient client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            string json = await client.GetStringAsync(BaseUrl + "points/referrals.json");

            return(json);
        }
Ejemplo n.º 6
0
        // see console app sample

        // sample flow for Twitter authroize
        //public async static Task<AccessToken> AuthorizeSample(string consumerKey, string consumerSecret)
        //{
        //    // create authorizer
        //    var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);

        //    // get request token
        //    var tokenResponse = await authorizer.GetRequestToken("https://api.twitter.com/oauth/request_token");
        //    var requestToken = tokenResponse.Token;

        //    var pinRequestUrl = authorizer.BuildAuthorizeUrl("https://api.twitter.com/oauth/authorize", requestToken);

        //    // open browser and get PIN Code
        //    Process.Start(pinRequestUrl);

        //    // enter pin
        //    Console.WriteLine("ENTER PIN");
        //    var pinCode = Console.ReadLine();

        //    // get access token
        //    var accessTokenResponse = await authorizer.GetAccessToken("https://api.twitter.com/oauth/access_token", requestToken, pinCode);

        //    // save access token.
        //    var accessToken = accessTokenResponse.Token;
        //    Console.WriteLine("Key:" + accessToken.Key);
        //    Console.WriteLine("Secret:" + accessToken.Secret);

        //    return accessToken;
        //}

        public async Task <string> GetTimeline(int count, int page)
        {
            var client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            var json = await client.GetStringAsync("https://api.twitter.com/1.1/statuses/home_timeline.json?count=" + count + "&page=" + page);

            return(json);
        }
Ejemplo n.º 7
0
        public async Task <string> GetPricePlan()
        {
            HttpClient client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            string json = await client.GetStringAsync(BaseUrl + "price_plan_details.json");

            return(json);
        }
Ejemplo n.º 8
0
        public async Task <string> GetBalance()
        {
            HttpClient client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            string json = await client.GetStringAsync(BaseUrl + "sim_balance.json");

            return(json);
        }
Ejemplo n.º 9
0
        public TwitterClientBase(ConsumerData consumerData, AccessTokenData token)
        {
            this.consumerData = consumerData;

            this.accessToken = token;
            httpClient       = OAuthUtility.CreateOAuthClient(ConsumerData.ConsumerKey, ConsumerData.ConsumerSecret, new AccessToken(AccessToken.AccessToken, AccessToken.TokenSecret));

            httpClient.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
        }
Ejemplo n.º 10
0
        public async Task <string> GetUsage()
        {
            DateTime fromdate = DateTime.Now.AddMonths(-1);
            //API requires: YYYY-MM-DDTHH:MM:SS
            //write extension to convert time to API format
            HttpClient client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            string json = await client.GetStringAsync(BaseUrl + string.Format("usage.json?fromdate={0}", fromdate.ToString("yyyy-MM-ddTHH:mm:ss")));

            return(json);
        }
Ejemplo n.º 11
0
        public static HttpClient GetClient()
        {
            if (!IsAuthorized)
            {
                throw new InvalidOperationException();
            }

            var token = Setting.AccessToken;

            return(OAuthUtility.CreateOAuthClient(key, secret, token));
        }
Ejemplo n.º 12
0
 private async Task <HttpResponseMessage> PerformGetRequest(string requestUrl)
 {
     try
     {
         return(await OAuthUtility.CreateOAuthClient(this._consumerKey, this._consumerKeySecret, this._accessToken, null).GetAsync(requestUrl));
     }
     catch
     {
     }
     return(null);
 }
Ejemplo n.º 13
0
        /**********************************************************************************/

        public async Task Diff(DiffObject diffObject = null)
        {
            var now = DateTime.Now;

            try
            {
                Logger.Trace("Diffiniarizing...");

                if (diffObject == null)
                {
                    diffObject = new DiffObject();
                }

                diffObject.LastSyncronizationTimestamp = _settings.LastServerTimestamp;
                diffObject.ClientTimeStamp             = now.ToTimeStamp();

                diffObject.Transactions = GetPendingTransactions();

                var uri = new Uri(ApiBaseUrl + "/v6/diff/");

                var httpClient = OAuthUtility.CreateOAuthClient(ConsumerKey, ConsumerSecret, _accessToken);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var postJson = JsonConvert.SerializeObject(diffObject);

                Logger.Trace("Request: \n\n" + postJson);

                var response = await httpClient.PostAsync(uri, new StringContent(postJson, Encoding.UTF8, "application/json"));

                var json = await response.Content.ReadAsStringAsync();

                Logger.Trace("Response: \n\n" + json);

                var diffResponse = JsonConvert.DeserializeObject <DiffRespnseObject>(json);
                _settings.LastSyncTime        = now;
                _settings.LastServerTimestamp = diffResponse.ServerTimestamp;

                await SaveChanges(diffResponse);


                if (diffResponse.Transactions != null)
                {
                    var updatetedTransactionIds = diffResponse.Transactions.Select(x => x.Id).ToArray();
                    Upserts.RemoveAll(x => updatetedTransactionIds.Contains(x.Id));
                    _db.Table <Upsert>().DeleteByKeys(updatetedTransactionIds);
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex, "Exception in (ZenmoneyClient.cs)\\[ZenmoneyClient.GetProfile] ");
                throw;
            }
        }
Ejemplo n.º 14
0
        public async Task <string> PostUpdate(string status)
        {
            var client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            var content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("status", status) });

            var response = await client.PostAsync("https://api.twitter.com/1.1/statuses/update.json", content);

            var json = await response.Content.ReadAsStringAsync();

            return(json);
        }
Ejemplo n.º 15
0
        public async Task <string> Favorite(string id)
        {
            //http://api.twitter.com/1/favorites/create/id.format
            var client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            var content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("id", id) });

            var response = await client.PostAsync("http://api.twitter.com/1.1/favorites/create.json", content);

            var json = await response.Content.ReadAsStringAsync();

            return(json);
        }
Ejemplo n.º 16
0
        void CreateHttpClient()
        {
            if (client != null)
            {
                return;
            }

            client = OAuthUtility.CreateOAuthClient(oAuthConsumerKey, oAuthConsumerSecret, oAuthAccessToken);
            var userAgent = $"HatebuTagManager made by misshiki using by {Environment.MachineName}-{Environment.UserName}";

            client.DefaultRequestHeaders.Add("User-Agent", userAgent);
            // dispose不要
        }
Ejemplo n.º 17
0
        public async Task <string> UpdateWithMedia(string status, byte[] media, string fileName)
        {
            var client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            var content = new MultipartFormDataContent();

            content.Add(new StringContent(status), "\"status\"");
            content.Add(new ByteArrayContent(media), "media[]", "\"" + fileName + "\"");

            var response = await client.PostAsync("https://upload.twitter.com/1/statuses/update_with_media.json", content);

            var json = await response.Content.ReadAsStringAsync();

            return(json);
        }
Ejemplo n.º 18
0
 public TwitterClient()
 {
     // See AsyncOAuth docs (differs for WinRT)
     OAuthUtility.ComputeHash = (key, buffer) =>
     {
         using (var hmac = new HMACSHA1(key))
         {
             return(hmac.ComputeHash(buffer));
         }
     };
     // Best to store secrets outside app (Azure Portal/etc.)
     _httpClient = OAuthUtility.CreateOAuthClient(
         AppSettings.TwitterAppId, AppSettings.TwitterAppSecret,
         new AccessToken(AppSettings.TwitterAccessTokenKey, AppSettings.TwitterAccessTokenSecret));
 }
Ejemplo n.º 19
0
        public async Task GetStream(Action <string> fetchAction)
        {
            var client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            using (var stream = await client.GetStreamAsync("https://userstream.twitter.com/1.1/user.json"))
                using (var sr = new StreamReader(stream))
                {
                    while (!sr.EndOfStream)
                    {
                        var s = await sr.ReadLineAsync();

                        fetchAction(s);
                    }
                }
        }
Ejemplo n.º 20
0
 private async Task <HttpResponseMessage> PerformPostRequest(string requestUrl, List <KeyValuePair <string, string> > parameters)
 {
     try
     {
         HttpClient            oauthClient        = OAuthUtility.CreateOAuthClient(this._consumerKey, this._consumerKeySecret, this._accessToken, null);
         FormUrlEncodedContent urlEncodedContent1 = new FormUrlEncodedContent((IEnumerable <KeyValuePair <string, string> >)parameters);
         string str = requestUrl;
         FormUrlEncodedContent urlEncodedContent2 = urlEncodedContent1;
         return(await oauthClient.PostAsync(str, (HttpContent)urlEncodedContent2));
     }
     catch
     {
     }
     return(null);
 }
Ejemplo n.º 21
0
        public async Task <string> GetUserTimeline(int count)
        {
            var client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            try
            {
                var json = await client.GetStringAsync("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=theqeditor&count=" + count);

                return(json);
            }
            catch (Exception ex)
            {
                string s = ex.Message;

                return(s);
            }
        }
Ejemplo n.º 22
0
        public async Task GetStream(Action <string> fetchAction)
        {
            var client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken);

            client.Timeout = System.Threading.Timeout.InfiniteTimeSpan; // set infinite timespan

            using (var stream = await client.GetStreamAsync("https://userstream.twitter.com/1.1/user.json").ConfigureAwait(false))
                using (var sr = new StreamReader(stream))
                {
                    while (!sr.EndOfStream)
                    {
                        var s = await sr.ReadLineAsync().ConfigureAwait(false);

                        //s = Regex.Unescape(s);
                        fetchAction(HttpUtility.HtmlDecode(s));
                    }
                }
        }
Ejemplo n.º 23
0
        public async Task <List <Item> > GetItems()
        {
            try
            {
                TwitterData = new List <Item>();
                client      = OAuthUtility.CreateOAuthClient(AppSettings.TwitterConsumerKey, AppSettings.TwitterConsumerSecret, new AccessToken(AppSettings.TwitterAccessToken, AppSettings.TwitterAccessSecret));

                foreach (var twitterSource in AppSettings.TwitterAddressCollection)
                {
                    twitterSource.Type = "TwitterSource";
                    await Parse(twitterSource);
                }
            }
            catch (Exception e)
            {
                ServiceLocator.MessageService.ShowErrorAsync("Error when retrieving items from TwitterService", "Application Error");
            }

            return(TwitterData);
        }
Ejemplo n.º 24
0
        private async Task <IList <Notifications> > getNotificationsAsync()
        {
            try
            {
                OAuthUtility.ComputeHash = (key, buffer) =>
                {
                    var crypt     = Windows.Security.Cryptography.Core.MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
                    var keyBuffer = Windows.Security.Cryptography.CryptographicBuffer.CreateFromByteArray(key);
                    var cryptKey  = crypt.CreateKey(keyBuffer);

                    var dataBuffer = Windows.Security.Cryptography.CryptographicBuffer.CreateFromByteArray(buffer);
                    var signBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.Sign(cryptKey, dataBuffer);

                    byte[] value;
                    Windows.Security.Cryptography.CryptographicBuffer.CopyToByteArray(signBuffer, out value);
                    return(value);
                };

                HttpClient client = OAuthUtility.CreateOAuthClient("etGuasDJQxqFTfpVFsWdeunzraxAtfi3cCNxwcOL", "S3cIJuC7IC2FaNj6EjGThZKREt0zXnTcVODUmBLJ", new AccessToken(Helpers.AccessToken, Helpers.AccessTokenSecret));
                client.BaseAddress  = new Uri("https://secure.splitwise.com/api/v3.0/");
                getNotificationsURL = getNotificationsURL + "&updated_after=" + Helpers.NotificationsLastUpdated ?? DateTime.UtcNow.ToString("u");
                HttpResponseMessage response = await client.GetAsync(getNotificationsURL);

                Newtonsoft.Json.Linq.JToken root      = Newtonsoft.Json.Linq.JObject.Parse(await response.Content.ReadAsStringAsync());
                Newtonsoft.Json.Linq.JToken testToken = root["notifications"];
                JsonSerializerSettings      settings  = new JsonSerializerSettings {
                    NullValueHandling = NullValueHandling.Ignore
                };
                List <Notifications> notifications = Newtonsoft.Json.JsonConvert.DeserializeObject <List <Notifications> >(testToken.ToString(), settings);
                Helpers.NotificationsLastUpdated = DateTime.UtcNow.ToString("u");
                notifications.Reverse();
                return(notifications);
            }
            catch (Exception)
            {
                return(new List <Notifications>());
            }
        }
Ejemplo n.º 25
0
 HttpClient CreateOAuthClient()
 {
     return(OAuthUtility.CreateOAuthClient(HatenaConfig.CONSUMER_KEY, HatenaConfig.CONSUMER_SECRET, accessToken));
 }
Ejemplo n.º 26
0
        public async Task <ActionResult> AccessTokenFlow()
        {
            //seting the authorizer varable with consumerKey/Secret as in Withings. Will become variable for later injection
            //grab value in URL to place in varables

            var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);

            var accessToken   = Request.QueryString["oauth_token"].ToString();
            var oAuthVerifier = Request.QueryString["oauth_verifier"].ToString();
            List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >();

            parameters.Add(new KeyValuePair <string, string>("oauth_token", accessToken));



            //  List<KeyValuePair<string, string>> parameters = new List<KeyValuePair<string, string>>();
            //   parameters.Add(new KeyValuePair<string, string>("oauth_verifier", oAuthVerifier));

            var requestToken = Session["requestToken"] as RequestToken;

            //send them out as access_tokens to get access granted by Withings
            var accessTokenResponse = await authorizer.GetAccessToken("https://oauth.withings.com/account/access_token", requestToken, oAuthVerifier);

            var accessTokens = accessTokenResponse.Token;

            string userId = Request.QueryString["userid"]; //todo: Find out how to assign the real user id from OAuth call



            var client = OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessTokens);


            //string withingsDateApiUrl = "&date=";

            //string withingsStartDateApiUrl = "&startdateymd=";

            //string withingsEndDateApiUrl = "&enddateymd=";
            //DateTime date = DateTime.Now;
            //string dateFormat = date.ToString("yyyy-MM-dd");
            //string startDateFormat = "2017-03-10";

            //string endDateFormat = "2017-03-21";

            // string dateFormat = "2017-03-13";

            //string oauthenticator = "&"+consumerSecret+"&"+accessToken;
            var oAuth_params = OAuthUtility.BuildBasicParameters(consumerKey, consumerSecret, "https://wbsapi.withings.net", HttpMethod.Get, accessTokens)
                               .Where(p => p.Key != "oauth_signature")
                               .OrderBy(p => p.Key);


            string requestUri = $"https://wbsapi.withings.net/measure?action=getmeas&userid={userId}&";

            requestUri += string.Join("&", oAuth_params.Select(kvp => kvp.Key + "=" + kvp.Value));

            var signature = OAuthUtility.BuildBasicParameters(consumerKey, consumerSecret, requestUri, HttpMethod.Get, accessTokens)
                            .First(p => p.Key == "oauth_signature").Value;

            string json = await client.GetStringAsync(requestUri + "&oauth_signature=" + signature);

            var o = JObject.Parse(json);

            int updateTime = (int)o["body"]["updatetime"];

            ViewBag.measureGroups = o["body"]["measuregrps"].Select(no => new
            {
                GroupId = no["grpid"],
                Attrib  = no["attrib"]
            });

            ViewBag.serializedResult = "JsonData";
            return(View("AccessTokenFlow"));
        }
Ejemplo n.º 27
0
        public virtual void Initialize()
        {
            httpClient = OAuthUtility.CreateOAuthClient(ConsumerData.ConsumerKey, ConsumerData.ConsumerSecret, new AccessToken(AccessToken.AccessToken, AccessToken.TokenSecret));

            httpClient.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
        }
Ejemplo n.º 28
0
 public static WithingsClient Create(string consumerKey, string consumerSecret)
 {
     var client = OAuthUtility.CreateOAuthClient("consumerKey", "consumerSecret", new AccessToken("accessToken", "accessTokenSecret"));
 }
Ejemplo n.º 29
0
 HttpClient CreateOAuthClient()
 {
     return(OAuthUtility.CreateOAuthClient(consumerKey, consumerSecret, accessToken));
 }