Example #1
0
        public void fetchXml()
        {
            User = usernamBox.Text.Replace(" ", "").Replace("/", "").Replace(".", "");
            URL = new Uri("http://" + User + ".tumblr.com/api/read/json");

            int max = 0;
            var client = new RestClient();
            client.Authority = URL.ToString();
            var request = new RestRequest();
            request.AddParameter("type", "photo");
            request.AddParameter("num", "50");
            request.AddParameter("filter", "text");
            var r1 = client.Request(request);
            var t = r1.Content.ToString().Replace("var tumblr_api_read = ", "");
            var firstResponse = JsonParser.FromJson(t);
            max = Convert.ToInt32(firstResponse["posts-total"]);
            // to eventually make each fetch a separate request
            for (int i = 0; i < max; i += 51)
            {
                if (i != 0)
                {
                    request.AddParameter("start", i.ToString());
                }
                var r2 = client.Request(request);
                var t2 = r2.Content.ToString().Replace("var tumblr_api_read = ", "");
                var Response = JsonParser.FromJson(t2);

                getUrls(Response.ToDictionary(x => x.Key, x => x.Value));
            }
        }
Example #2
0
        public void AddComments(String id, String text, CompleteHandler handler)
        {
            if (m_netEngine == null)
                m_netEngine = new DoubanNetEngine();
            RestRequest request = new RestRequest();
            request.Method = WebMethod.Post;
            request.Path = String.Format("shuo/v2/statuses/{0}/comments", id);
            request.AddParameter("text", text);
            request.AddParameter("source", DoubanSdkData.AppKey);

            m_netEngine.SendRequest(request, (DoubanSdkResponse response) =>
            {
                if (response.errCode == DoubanSdkErrCode.SUCCESS)
                {
                    DoubanEventArgs args = new DoubanEventArgs();
                    args.errorCode = DoubanSdkErrCode.SUCCESS;
                    args.specificCode = response.specificCode;
                    handler(args);
                }
                else
                {
                    DoubanEventArgs args = new DoubanEventArgs();
                    args.errorCode = response.errCode;
                    args.specificCode = response.specificCode;
                    handler(args);
                }
            });
        }
Example #3
0
        public RestResponse GetFavorites(string user, int page, int pageSize)
        {
            // Documentation for GET /favorites
            // https://dev.twitter.com/docs/api/1/get/favorites

            // Create the REST Client
            var client = new RestClient {Authority = "http://api.twitter.com/1"};

            // Create the REST Request
            var request = new RestRequest {Path = "favorites.json", Method = WebMethod.Get};
            request.AddParameter("id", user);
            request.AddParameter("page", page.ToString());
            request.AddParameter("count", pageSize.ToString());

            // Set API authentication tokens
            var appSettings = ConfigurationManager.AppSettings;
            request.Credentials = OAuthCredentials.ForProtectedResource(
                appSettings["ConsumerKey"], appSettings["ConsumerSecret"], appSettings["Token"],
                appSettings["TokenSecret"]);

            // Make request
            var response = client.Request(request);

            return response;
        }
        public void BeginUserRealtimeLinks(BitlyLogin user, RestCallback callback)
        {
            var request = new RestRequest {Path = "user/realtime_links"};
            request.AddParameter("format", "json");
            request.AddParameter("access_token", user.access_token);

            _sslClient.BeginRequest(request, callback);
        }
        public void BeginGetAccessToken(string code, RestCallback callback)
        {
            var oauthClient = new RestClient {Authority = _sslClient.Authority};

            //Build an OAuth request manually - the Bit.ly documentation didn't indicate that I needed signatures
            var request = new RestRequest {Method = WebMethod.Post, Path = "/oauth/access_token"};

            request.AddParameter("client_id", Settings.ConsumerKey);
            request.AddParameter("client_secret", Settings.ConsumerSecret);
            request.AddParameter("code", code);
            request.AddParameter("redirect_uri", Settings.RedirectUrl);

            oauthClient.BeginRequest(request, callback);
        }
Example #6
0
        /// <summary>
        /// ログインユーザのステータスメッセージを更新します
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static dynamic CreateLoginUsersStatusMessage(string accessToken, string message)
        {
            // see http://developers.facebook.com/docs/reference/api/user/

            var client = new RestClient { Authority = "https://graph.facebook.com/" };
            var request = new RestRequest
            {
                Path = "me/feed",
                Method = Hammock.Web.WebMethod.Post,
            };
            request.AddParameter("access_token", accessToken);
            request.AddParameter("message", message);
            var response = client.Request(request);
            return DynamicJson.Parse(response.Content);
        }
Example #7
0
        public void GetComments(String id, int count, GetCommentsCompleteHandler handler)
        {
            if (m_netEngine == null)
                m_netEngine = new DoubanNetEngine();
            RestRequest request = new RestRequest();
            request.Method = WebMethod.Get;
            request.Path = String.Format("shuo/v2/statuses/{0}/comments", id);
            request.AddParameter("count", count.ToString());

            m_netEngine.SendRequest(request, (DoubanSdkResponse response) =>
            {
                if (response.errCode == DoubanSdkErrCode.SUCCESS)
                {
                    GetCommentsEventArgs args = new GetCommentsEventArgs();
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Comment>));
                    List<Comment> list = ser.ReadObject(response.stream) as List<Comment>;
                    args.comments = list;
                    args.errorCode = DoubanSdkErrCode.SUCCESS;
                    args.specificCode = response.specificCode;
                    handler(args);
                }
                else
                {
                    GetCommentsEventArgs args = new GetCommentsEventArgs();
                    args.comments = null;
                    args.errorCode = response.errCode;
                    args.specificCode = response.specificCode;
                    handler(args);
                }
            });
        }
Example #8
0
        /// <summary>
        /// ステータスを更新します
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="accessTokenSecret"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static dynamic UpdateStatus(string accessToken, string accessTokenSecret, string message)
        {
            var client = new RestClient
            {
                Authority = "http://api.twitter.com",
                UserAgent = "OAuthSample",
            };

            var credentials = OAuthCredentials.ForProtectedResource(
                Config.TwitterConsumerKey,
                Config.TwitterConsumerSecret,
                accessToken,
                accessTokenSecret);
            credentials.ParameterHandling = OAuthParameterHandling.UrlOrPostParameters;

            var request = new RestRequest
            {
                Path = "statuses/update.json",
                Method = WebMethod.Post,
                Credentials = credentials,
            };

            request.AddParameter("status", message);

            var response = client.Request(request);
            return DynamicJson.Parse(response.Content);
        }
Example #9
0
    void getFacebookData()
    {
        string CallbackUrl = "http://localhost:27393/facebookyeni/callback.aspx";
        var client = new RestClient { Authority = "https://graph.facebook.com/oauth/" };
        var request = new RestRequest { Path = "access_token" };

        request.AddParameter("client_id", ConfigurationManager.AppSettings["FacebookClientId"]);
        request.AddParameter("redirect_uri", CallbackUrl);
        request.AddParameter("client_secret", ConfigurationManager.AppSettings["FacebookApplicationSecret"]);
        request.AddParameter("code", Request["code"]);

        RestResponse response = client.Request(request);
        StringDictionary result = FacebookConnect.ParseQueryString(response.Content);
        string aToken = result["access_token"];

        responseFacebookUserInfo(aToken);
    }
Example #10
0
        public void SendRequest(RestRequest request, RequestBack callBack)
        {
            Action<string> errAction = (e1) =>
            {
                if (null != callBack)
                {
                    DoubanSdkErrCode sdkErr = DoubanSdkErrCode.XPARAM_ERR;
                    callBack(new DoubanSdkResponse
                    {
                        //requestID = null != data ? data.requestId : "",
                        errCode = sdkErr,
                        specificCode = "",
                        content = e1,
                        stream = null
                    });
                }
            };

            if (null == request)
            {
                errAction("request should`t be null.");
                return;
            }

            m_Client.Authority = ConstDefine.PublicApiUrl;
            m_Client.HasElevatedPermissions = true;

            //添加鉴权
            request.DecompressionMethods = DecompressionMethods.GZip;
            request.Encoding = Encoding.UTF8;

            IWebCredentials credentials = null;

            if (null != DoubanAPI.DoubanInfo.tokenInfo && !string.IsNullOrEmpty(DoubanAPI.DoubanInfo.tokenInfo.access_token))
            {
                request.AddHeader("Authorization", string.Format("Bearer {0}", DoubanAPI.DoubanInfo.tokenInfo.access_token));
            }
            else
            {
                request.AddParameter("source", DoubanSdkData.AppKey);
            }
            request.AddParameter("curtime", DateTime.Now.ToString());
            request.Credentials = credentials;

            m_Client.BeginRequest(request, (e1, e2, e3) => AsyncCallback(e1, e2, callBack));
        }
Example #11
0
        protected override RestRequest CreateTokensRequest(NameValueCollection parameters)
        {
            var request = new RestRequest
            {
                Path = "/1/oauth2/token.json",
                Method = Hammock.Web.WebMethod.Post,

            };

            request.AddParameter("client_id", SensitiveData.BufferClientId);
            request.AddParameter("client_secret", SensitiveData.BufferClientSecret);
            request.AddParameter("redirect_uri", callbackUrl);
            request.AddParameter("code", parameters["code"]);
            request.AddParameter("grant_type", "authorization_code");

            return request;
        }
Example #12
0
        /// <summary>
        /// ログインユーザ情報を取得します
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static dynamic GetUserInformation(string accessToken)
        {
            // see http://developers.facebook.com/docs/reference/api/user/

            var client = new RestClient { Authority = "https://graph.facebook.com/" };
            var request = new RestRequest { Path = "me" };
            request.AddParameter("access_token", accessToken);
            var response = client.Request(request);
            return DynamicJson.Parse(response.Content);
        }
Example #13
0
        public ActionResult CallbackFacebook(string code)
        {
            if (String.IsNullOrEmpty(code))
            {
                // TempData is equivalent to flash of rails.
                TempData["message"] = "認証に失敗しました";
                return RedirectToAction("Login");
            }

            var client = new RestClient
            {
                Authority = "https://graph.facebook.com/oauth/",
            };

            var request = new RestRequest
            {
                Path = "access_token",
            };

            request.AddParameter("client_id", Config.FacebookAppId);
            request.AddParameter("redirect_uri", Config.ApplicationUrl + "/Account/CallbackFacebook");
            request.AddParameter("client_secret", Config.FacebookAppSecret);
            request.AddParameter("code", code);

            var response = client.Request(request);

            // response contains access_token and expires
            var result = HttpUtility.ParseQueryString(response.Content);

            // to handle expired access tokens, see the blog
            // https://developers.facebook.com/blog/post/500/

            var accessToken = result["access_token"];
            var user = (User)Session["user"] ?? new User();

            user.FacebookAccessToken = accessToken;
            user.FacebookUser = Facebook.GetUserInformation(accessToken);

            Session["user"] = user;

            return RedirectToAction("Index", "Tubuyaki");
        }
Example #14
0
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            string auth_key = String.Format("full_auth_token {0}", settings["me2day_token"]);
            IWebCredentials credentials = new BasicAuthCredentials
            {
                Username = (string)settings["me2day_userid"],
                Password = auth_key
            };

            RestClient client = new RestClient
            {
                Authority = "http://me2day.net/api/"
            };

            RestRequest request = new RestRequest
            {
                Credentials = credentials,
                Path = String.Format("create_post/{0}.xml?akey=aed420d038f9b1a7fe3b5c0d94df22f5", settings["me2day_userid"])
            };
            request.AddParameter("post[body]", WatermarkTB.Text);
            request.AddParameter("post[tags]", WatermarkTB2.Text);

            if (imgstream != null)
            {
                request.AddFile("attachment", "image.jpg", imgstream, "image/jpeg");
            }

            var callback = new RestCallback(
                (restRequest, restResponse, userState) =>
                {
                    // Callback when signalled
                }
            );

            client.BeginRequest(request, callback);

            MessageBox.Show("Share successfully.", "Thanks", MessageBoxButton.OK);
            this.NavigationService.GoBack();
        }
Example #15
0
        //protected void DoRequest(string sEndpoint, WebMethod wmTransferType, Dictionary<string, string> dssParams, APIReturn aprReturn)
        protected void DoRequest(RestRequest rrRequest, OAuthCredentials oaCredentials, APIReturn aprReturn)
        {
            //suggested by the smart guys at dev.twitter.com
            rrRequest.AddParameter("oauth_callback", "oob");

            RestClient rcClient = new RestClient
            {
                Authority = C_OAUTH_BASE_URL,
                Credentials = oaCredentials
            };

            //post request, update credentials object
            rcClient.BeginRequest(rrRequest, DoRequestCallback, aprReturn);
        }
Example #16
0
        public void LoadSinaWeiboCommentByStatusID(String id, LoadSinaWeiboCommentsCompleteDelegate dele)
        {
            String MyID = PreferenceHelper.GetPreference("SinaWeibo_ID");
            if (string.IsNullOrEmpty(MyID))
                return;
            // Define a new net engine
            m_netEngine = new SdkNetEngine();
            // Define a new command base
            m_cmdBase = new SdkCmdBase
            {
                acessToken = App.SinaWeibo_AccessToken,
            };
            RestRequest request = new RestRequest();
            request.Method = WebMethod.Get;
            request.Path = "comments/show.json";
            request.AddParameter("access_token", App.SinaWeibo_AccessToken);
            request.AddParameter("id", id);
            //request.CacheOptions.Mode = Hammock.Caching.CacheMode.AbsoluteExpiration;

            ++App.Test3;
            System.Diagnostics.Debug.WriteLine("Test3: " + App.Test3);
            m_netEngine.SendRequest(request, m_cmdBase, (SdkResponse response) =>
            {
                ++App.Test2;
                System.Diagnostics.Debug.WriteLine("Test2: " + App.Test2);
                if (response.errCode == SdkErrCode.SUCCESS)
                {
                    Comments comments;
                    try
                    {
                        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Comments));
                        comments = ser.ReadObject(response.stream) as Comments;
                        dele(comments);
                    }
                    catch (Exception)
                    {
                        dele(null);
                    }
                }
                else
                {
                    dele(null);
                }
            });
        }
Example #17
0
        public static void CallDailyBurnApi(string apiExtensionPath, RestCallback callback, Dictionary<string, string> parameters)
        {
            string accessToken = HelperMethods.GetKeyValue("accessToken");
            string accessTokenSecret = HelperMethods.GetKeyValue("accessTokenSecret");
            var credentials = new OAuthCredentials
            {
                Type = OAuthType.ProtectedResource,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey = DailyBurnSettings.consumerKey,
                ConsumerSecret = DailyBurnSettings.consumerKeySecret,
                Token = accessToken,
                TokenSecret = accessTokenSecret,
                Version = "1.0"
            };


            var restClient = new RestClient
            {
                Authority = DailyBurnSettings.AuthorityUri,
                HasElevatedPermissions = true,
                Credentials = credentials,
                Method = WebMethod.Get
            };

            var restRequest = new RestRequest
            {
                Path = apiExtensionPath,
                Method = WebMethod.Get
            };

            if (parameters != null)
            {
                foreach (KeyValuePair<string, string> param in parameters)
                {
                    restRequest.AddParameter(param.Key, param.Value);
                }
            }
            
            restClient.BeginRequest(restRequest, new RestCallback(callback));
        }
Example #18
0
        protected void DoRequest(string sEndpoint, WebMethod wmTransferType, Dictionary<string, string> dssParams, APIReturn aprReturn)
        {
            RestRequest rrRequest = new RestRequest();

            rrRequest.Path = sEndpoint;
            m_oaCredentials.Type = OAuthType.ProtectedResource;
            m_oaCredentials.Verifier = null;

            foreach (KeyValuePair<string, string> kvpCur in dssParams)
                rrRequest.AddParameter(kvpCur.Key, kvpCur.Value);

            RestClient rcClient = new RestClient
            {
                Authority = C_BASE_URL,
                VersionPath = "1",
                Credentials = m_oaCredentials,
                Method = wmTransferType
            };

            rcClient.BeginRequest(rrRequest, DoRequestCallback, aprReturn);
        }
Example #19
0
    void responseFacebookUserInfo(string sToken)
    {
        var client = new RestClient { Authority = "https://graph.facebook.com/" };
        var request = new RestRequest { Path = "me" };
        request.AddParameter("access_token", sToken);
        RestResponse facebookResponse = client.Request(request);

        JavaScriptSerializer ser = new JavaScriptSerializer();
        var FacebookUser = ser.Deserialize<FacebookUser>(facebookResponse.Content);

        HttpCookie cookie = new HttpCookie("FacebookUserInfo");
        cookie.Expires = DateTime.Now.AddDays(1);

        cookie.Values.Add("id", FacebookUser.id);
        cookie.Values.Add("firsName", FacebookUser.first_name);
        cookie.Values.Add("lastName", FacebookUser.last_name);
        cookie.Values.Add("userName", FacebookUser.username);
        cookie.Values.Add("birthday", FacebookUser.birthday);
        cookie.Values.Add("email", FacebookUser.email);
        cookie.Values.Add("location", FacebookUser.location.name);
        cookie.Values.Add("imageUrl", string.Format("http://graph.facebook.com/{0}/picture?type=small", FacebookUser.id));
        cookie.Values.Add("accessToken", sToken);

        foreach (var item in FacebookUser.education)
        {
            cookie.Values.Add("schoolName", item.school.name);
            foreach (var items in item.concentration)
            {
                cookie.Values.Add("schoolSectionName", items.name);
                break;
            }
            break;
        }

        Response.Cookies.Add(cookie);

        ClientScript.RegisterStartupScript(this.GetType(), "pageClose", "<script>closePage();</script>");
    }
Example #20
0
        private void LoadStatuses(long sinceId)
        {
            if (!_authorized)
            {
                if (LoadedCompleteEvent != null)
                    LoadedCompleteEvent(this, EventArgs.Empty);
                return;
            }

            var request = new RestRequest
            {
                Credentials = _credentials,
                Path = "/statuses/friends_timeline.xml",
            };

            request.AddParameter("count", MaxCount);

            if (sinceId != 0)
                request.AddParameter("since_id", sinceId.ToString());

            request.AddParameter("include_rts", "1");

            _client.BeginRequest(request, new RestCallback(TwitterGetStatusesCompleted));
        }
Example #21
0
        public void NewTweet(string tweetText)
        {
            if (!_authorized)
            {
                if (ErrorEvent != null)
                    ErrorEvent(this, EventArgs.Empty);
                return;
            }

            var request = new RestRequest
            {
                Credentials = _credentials,
                Path = "/statuses/update.xml",
                Method = WebMethod.Post
            };

            request.AddParameter("status", tweetText);

            _client.BeginRequest(request, new RestCallback(NewTweetCompleted));
            App.ViewModel.IsDataLoaded = false;
        }
Example #22
0
        public void LoadDirectMessages(long sinceId)
        {
            if (!_authorized)
            {
                if (LoadedCompleteEvent != null)
                    LoadedCompleteEvent(this, EventArgs.Empty);

                return;
            }

            var request = new RestRequest
            {
                Credentials = _credentials,
                Path = "/direct_messages.xml",
            };

            request.AddParameter("count", MaxCount);

            if (sinceId != 0)
                request.AddParameter("since_id", sinceId.ToString());

            _client.BeginRequest(request, new RestCallback(TwitterGetDirectMessagesCompleted));
        }
Example #23
0
        public void PostStatusesWithPic(String text, String path, CompleteHandler handler)
        {
            if (m_netEngine == null)
                m_netEngine = new DoubanNetEngine();
            RestRequest request = new RestRequest();
            request.Method = WebMethod.Post;
            request.Path = "shuo/v2/statuses/";
            request.AddParameter("text", text);
            request.AddParameter("source", DoubanSdkData.AppKey);

            //path = "";
            if (!String.IsNullOrEmpty(path))
            {
                IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
                if (!file.FileExists(path))
                {
                    file.Dispose();
                    DoubanEventArgs args = new DoubanEventArgs();
                    args.errorCode = DoubanSdkErrCode.XPARAM_ERR;
                    handler(args);
                    return;
                }
                file.Dispose();
                string picType = System.IO.Path.GetExtension(path);
                string picName = System.IO.Path.GetFileName(path);
                if ("png" == picType)
                {
                    request.AddFile("image", picName, path, "image/png");
                }
                else
                {
                    request.AddFile("image", picName, path, "image/jpeg");
                }
            }

            m_netEngine.SendRequest(request, (DoubanSdkResponse response) =>
            {
                if (response.errCode == DoubanSdkErrCode.SUCCESS)
                {
                    DoubanEventArgs args = new DoubanEventArgs();
                    args.errorCode = DoubanSdkErrCode.SUCCESS;
                    args.specificCode = response.specificCode;
                    handler(args);
                }
                else
                {
                    DoubanEventArgs args = new DoubanEventArgs();
                    args.errorCode = response.errCode;
                    args.specificCode = response.specificCode;
                    handler(args);
                }
            });
        }
        /// <summary>
        /// Posts the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        public override void PostMessage(string message)
        {
            if (Tokens == null || Tokens.Count != 4)
            {
                throw new InvalidCredentialException();
            }

            _restClient.Authority   = "http://api.twitter.com";
            _restClient.Credentials = new OAuthCredentials
                {
                    Type              = OAuthType.ProtectedResource,
                    SignatureMethod   = OAuthSignatureMethod.HmacSha1,
                    ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                    ConsumerKey       = ConsumerKey,
                    ConsumerSecret    = ConsumerSecret,
                    Token             = Tokens[2],
                    TokenSecret       = Tokens[3]
                };

            var request = new RestRequest
                {
                    Path   = "/statuses/update.json",
                    Method = WebMethod.Post
                };

            request.AddParameter("status", message.CutIfLonger(140));

            _restClient.Request(request);
        }
Example #25
0
        private void SinaWeiboSend()
        {
            String statusID = m_itemViewModel.ID;
            if (String.IsNullOrEmpty(statusID))
                return;

            String commentText = StatusMessageBox.Text;

            netEngine = new SdkNetEngine();
            // Define a new command base
            cmdBase = new SdkCmdBase
            {
                acessToken = App.SinaWeibo_AccessToken,
            };

            RestRequest request = new RestRequest();
            request.Method = WebMethod.Post;
            request.Path = "comments/create.json";
            request.AddParameter("access_token", App.SinaWeibo_AccessToken);
            request.AddParameter("id", statusID);
            request.AddParameter("comment", commentText);
            request.AddParameter("comment_ori", "0");

            netEngine.SendRequest(request, cmdBase, (SdkResponse response) =>
            {
                if (response.errCode == SdkErrCode.SUCCESS)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("发送成功!");
                        // go back to CommentView.
                        // CommentView should refresh itself to show the newly added comment
                        NavigationService.GoBack();
                    }
                    );
                }
                else
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("发送失败!");
                        // go back to CommentView.
                        // CommentView should refresh itself to show the newly added comment
                        NavigationService.GoBack();
                    });
                }
            });
        }
        /// <summary>
        /// Posts the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        public override void PostMessage(string message)
        {
            if (Tokens == null || Tokens.Count != 4)
            {
                throw new InvalidCredentialException();
            }

            _restClient.Authority = "https://graph.facebook.com";

            var request = new RestRequest
                {
                    Path = "/me/feed",
                    Method = WebMethod.Post
                };

            request.AddParameter("access_token", Tokens[3]);
            request.AddParameter("message",      message.CutIfLonger(420));

            _restClient.Request(request);
        }
        /// <summary>
        /// Finishes the authorization by using the user-specified PIN.
        /// </summary>
        /// <param name="pin">The PIN.</param>
        /// <returns>
        /// List of tokens required for further communication with the server.
        /// </returns>
        public override List<string> FinishAuthorizationWithPin(string pin)
        {
            _restClient.Authority = "https://graph.facebook.com/oauth";

            var request = new RestRequest { Path = "/access_token" };
            request.AddParameter("client_id",     ConsumerKey);
            request.AddParameter("redirect_uri",  "https://www.facebook.com/connect/login_success.html");
            request.AddParameter("client_secret", ConsumerSecret);
            request.AddParameter("code",          pin);

            var response = _restClient.Request(request);
            var parsed   = Utils.ParseQueryString(response.Content);

            if (!parsed.ContainsKey("access_token"))
            {
                throw new Exception("Invalid response from server. (No tokens were returned.)");
            }

            _restClient.Authority = "https://graph.facebook.com";

            var request2 = new RestRequest { Path = "/me" };
            request2.AddParameter("access_token", parsed["access_token"]);

            var response2 = _restClient.Request(request2);
            var user      = JObject.Parse(response2.Content);

            return new List<string>
                {
                    user["id"].Value<string>(),
                    user["name"].Value<string>(),
                    user["username"].Value<string>(),
                    parsed["access_token"]
                };
        }
Example #28
0
        private IAsyncResult BeginStreamInternal()
        {
            if (StreamingAsyncResult != null)
            {
                if (!StreamingAsyncResult.IsCompleted)
                    return StreamingAsyncResult;
            }

            _lastConnectAttempt = DateTime.Now;
            ((OAuthCredentials)Credentials).CallbackUrl = null;
            var streamClient = new RestClient
                                   {
                                       Authority = "https://userstream.twitter.com",
                                       VersionPath = "2",
                                       Credentials = Credentials,
#if SILVERLIGHT
                                       HasElevatedPermissions = true
#endif
                                   };

            var req = new RestRequest
                          {
                              Path = "user.json",
                              StreamOptions = new StreamOptions
                                                  {
                                                      ResultsPerCallback = 1,
                                                  },
                          };

            if (Tracks != null)
                req.AddParameter("track", string.Join(",", Tracks.ToArray()));

#if !SILVERLIGHT
            if (_timer == null)
            {
                _timer = new System.Timers.Timer(20000);
                _timer.Elapsed += TimerElapsed;
                _timer.Start();
            }

            StreamingAsyncResult = streamClient.BeginRequest(req, StreamCallback);
#else
            streamClient.BeginRequest(req, StreamCallback);
#endif
            return StreamingAsyncResult;
        }
Example #29
0
        public ActionResult CallbackMixi(string code)
        {
            var client = new RestClient
            {
                Authority = "https://secure.mixi-platform.com",
            };

            var request = new RestRequest
            {
                Path = "2/token",
                Method = WebMethod.Post,
            };
            request.AddParameter("grant_type", "authorization_code");
            request.AddParameter("client_id", Config.MixiConsumerKey);
            request.AddParameter("client_secret", Config.MixiConsumerSecret);
            request.AddParameter("code", code);
            // redirect_uri needs to be same as redirect url of mixi's application configuration
            request.AddParameter("redirect_uri", "http://twi-ll.timedia.co.jp/Account/CallbackMixi");

            var response = client.Request(request);

            var result = DynamicJson.Parse(response.Content);

            var user = (User)Session["user"] ?? new User();

            user.MixiAccessToken = result.access_token;
            user.MixiExpires = DateTime.Now.AddSeconds((double)result.expires_in);
            user.MixiRefreshToken = result.refresh_token;

            Session["user"] = user;

            return RedirectToAction("Index", "Tubuyaki");
        }
        /// <summary>
        /// Searches for videos on Netflix.
        /// </summary>
        /// <param name="ep">The episode.</param>
        /// <returns>
        /// URL of the video.
        /// </returns>
        public override string Search(Episode ep)
        {
            var rest = new RestClient
                {
                    QueryHandling        = QueryHandling.AppendToParameters,
                    DecompressionMethods = DecompressionMethods.GZip,
                    UserAgent            = Signature.Software + "/" + Signature.Version,
                    FollowRedirects      = true,
                    Authority            = "http://api.netflix.com/",
                    Credentials          = new OAuthCredentials
                        {
                            Type              = OAuthType.ProtectedResource,
                            SignatureMethod   = OAuthSignatureMethod.HmacSha1,
                            ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                            ConsumerKey       = ConsumerKey,
                            ConsumerSecret    = SharedSecret
                        }
                };

            #region Detect and set proxy
            string proxy = null;
            object proxyId;
            if (Settings.Get<Dictionary<string, object>>("Proxied Domains").TryGetValue("netflix.com", out proxyId) || Settings.Get<Dictionary<string, object>>("Proxied Domains").TryGetValue("api.netflix.com", out proxyId))
            {
                proxy = (string)Settings.Get<Dictionary<string, object>>("Proxies")[(string)proxyId];
            }

            if (proxy != null)
            {
                var proxyUri = new Uri(proxy.Replace("$domain.", string.Empty));

                switch (proxyUri.Scheme.ToLower())
                {
                    case "http":
                        if (proxy.Contains("$url") || (proxy.Contains("$domain") && proxy.Contains("$path")))
                        {
                            throw new Exception("Web-based proxies are not supported with Netflix for now, because of OAuth signatures.");
                        }
                        else
                        {
                            rest.Proxy = proxyUri.Host + ":" + proxyUri.Port;
                        }
                        break;

                    case "socks4":
                    case "socks4a":
                    case "socks5":
                        var tunnel = new HttpToSocks { RemoteProxy = HttpToSocks.Proxy.ParseUri(proxyUri) };
                        tunnel.Listen();
                        rest.Proxy = tunnel.LocalProxy.Host + ":" + tunnel.LocalProxy.Port;
                        break;
                }
            }
            #endregion

            var request = new RestRequest { Path = "catalog/titles" };
            request.AddParameter("term", ep.Show.Title);
            request.AddParameter("max_results", "1");
            request.AddParameter("expand", "seasons");

            var resp  = XDocument.Parse(rest.Request(request).Content);
            var links = resp.XPathSelectElements("//link[@rel='http://schemas.netflix.com/catalog/title.season']");

            string seasonid = null;
            foreach (var link in links)
            {
                if (link.Attribute("title").Value.EndsWith(" " + ep.Season))
                {
                    seasonid = link.Attribute("href").Value;
                    break;
                }
            }

            if (seasonid != null)
            {
                request = new RestRequest { Path = seasonid.Replace("http://api.netflix.com/", string.Empty) + "/episodes" };
                resp    = XDocument.Parse(rest.Request(request).Content);
                var ids = resp.XPathSelectElements("//id").ToList();

                if (ids.Count >= ep.Number)
                {
                    return ids[ep.Number - 1].Value.Replace("http://api.netflix.com/catalog/titles/programs/", "http://movies.netflix.com/WiPlayer?movieid=");
                }
            }

            throw new OnlineVideoNotFoundException("No matching videos were found.", "Open Netflix search page", "http://movies.netflix.com/WiSearch?v1=" + Utils.EncodeURL(ep.Show.Title));
        }