示例#1
0
        public static string KeyValueToString(Dictionary <string, string> payload)
        {
            string body = "";

            foreach (var item in payload)
            {
                body += String.Format("{0}={1}&",
                                      VimeoHelper.PercentEncode(item.Key),
                                      VimeoHelper.PercentEncode(item.Value));
            }
            if (body[body.Length - 1] == '&')
            {
                body = body.Substring(0, body.Length - 1);
            }
            return(body);
        }
        /// <summary>
        /// This is your portal to Vimeo. Use it to call a method with a bunch of parameters.
        /// Example: get your own profile by calling
        /// Request("/me", null, "GET")
        /// </summary>
        /// <param name="url">The endpoint. It should be a relative URL specifying the API method you want to call, such as "/me"</param>
        /// <param name="parameters">Call parameters. Put null if you don't feel like it.</param>
        /// <param name="method">HTTP method: e.g. "GET", "POST", "PUT", etc.</param>
        /// <param name="jsonBody">true: set content type to json</param>
        /// <returns>Deserialized JSON as Dictionary of strings to objects</returns>
        public Dictionary <string, object> Request(
            string url,
            Dictionary <string, string> parameters,
            string method,
            bool jsonBody = true)
        {
            var headers = new WebHeaderCollection()
            {
                { "Authorization", String.Format("Bearer {0}", AccessToken) }
            };

            method = method.ToUpper();
            url    = apiRoot + url;
            string body        = "";
            string contentType = "application/x-www-form-urlencoded";

            if (parameters != null && parameters.Count > 0)
            {
                if (method == "GET")
                {
                    url += "?" + VimeoHelper.KeyValueToString(parameters);
                }
                else if (method == "POST" || method == "PATCH" || method == "PUT" || method == "DELETE")
                {
                    if (jsonBody)
                    {
                        contentType = "application/json";
                        body        = jsonEncode(parameters);
                    }
                    else
                    {
                        body = VimeoHelper.KeyValueToString(parameters);
                    }
                }
            }
            return(json.Deserialize <Dictionary <string, object> >(
                       VimeoHelper.HTTPFetch(url, method, headers, body, contentType)));
        }
示例#3
0
        /// <summary>
        /// Generates a new access token given the authorization code generated by the page
        /// at get_auth_url().
        ///
        /// In the context of a web server, the programmer should retrieve the auth_code
        /// generated by the page at get_auth_url() and use it as the input to this function.
        /// The programmer should then use the string returned from this function to
        /// authenticate calls to the API library on behalf of the corresponding user.
        ///
        /// Note: The following URLs must be identical:
        /// This function's redirect parameter
        /// The redirect parameter passed to get_access_token
        /// One of the redirect URIs listed on the app setup page
        /// </summary>
        /// <param name="authCode">The authorization code given in the 'code' query parameter of the page URI after redirecting from the result of get_auth_url</param>
        /// <param name="cid">The client ID for the current app</param>
        /// <param name="secret">The client secret for the current app</param>
        /// <param name="redirect">The redirect URI for the app (see note)</param>
        /// <param name="apiRoot">The root url of the API being used (in OldVimeoClient, accessible via config['apiroot'])</param>
        /// <returns>Access Token JSON. result["access_token"].ToString() contains access token in string</returns>
        public static Dictionary <string, object> GetAccessToken(
            string authCode, string cid, string secret, string redirect, string apiRoot)
        {
            string encoded = VimeoHelper.ToBase64(String.Format("{0}:{1}", cid, secret));

            Debug.WriteLine(String.Format("Encoded: {0}", encoded));
            var payload = new Dictionary <string, string>
            {
                { "grant_type", "authorization_code" },
                { "code", authCode },
                { "redirect_uri", redirect }
            };
            var headers = new WebHeaderCollection()// Dictionary<string, string>
            {
//{"Accept", "application/vnd.vimeo.*+json; version=3.2"},
                { "Authorization", String.Format("Basic {0}", encoded) }
            };
            var response = VimeoHelper.HTTPFetch(
                String.Format("{0}/oauth/access_token", apiRoot),
                "POST", headers, payload);

            return(new JavaScriptSerializer().Deserialize <Dictionary <string, object> >(response));
        }
示例#4
0
        /// <summary>
        /// Generates a bearer token for the registered application.
        /// This token will exist without a user context, but will allow for access to data in the API.
        /// </summary>
        /// <param name="clientId">The client ID for the current app</param>
        /// <param name="clientSecret">The client secret for the current app</param>
        /// <param name="scopes">A list of permission scopes that the user will be prompted to allow</param>
        /// <param name="apiRoot">The root url of the API being used (in OldVimeoClient, accessible via config['apiroot'])</param>
        /// <returns>a bearer token for the registered application.</returns>
        public static string GetClientCredentials(string clientId, string clientSecret, string scopes = null, string apiRoot = "https://api.vimeo.com")
        {
            var basicAuth = VimeoHelper.ToBase64(String.Format("{0}:{1}", clientId, clientSecret));
            var payload   = new Dictionary <string, string>
            {
                { "grant_type", "client_credentials" }
            };
            var headers = new WebHeaderCollection
            {
//{"Accept", "application/vnd.vimeo.*+json; version=3.2"},
                { "Authorization", String.Format("Basic {0}", basicAuth) }
            };

            if (scopes != null)
            {
                payload.Add("scope", scopes);
            }
            var response = VimeoHelper.HTTPFetch(String.Format("{0}/oauth/authorize/client", apiRoot),
                                                 "POST", headers, payload);
            var json = new JavaScriptSerializer().Deserialize <Dictionary <string, string> >(response);

            return(json["access_token"]);
        }
示例#5
0
        public static string HTTPFetch(string url, string method,
                                       WebHeaderCollection headers, string payload,
                                       string contentType = "application/x-www-form-urlencoded")
        {
            HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(url);

            if (Proxy != null)
            {
                request.Proxy = Proxy;
            }
            request.Headers     = headers;
            request.Method      = method;
            request.Accept      = "application/vnd.vimeo.*+json; version=3.2";
            request.ContentType = contentType;
            request.KeepAlive   = false;
            if (!String.IsNullOrWhiteSpace(payload))
            {
                var streamBytes = VimeoHelper.ToByteArray(payload);
                request.ContentLength = streamBytes.Length;
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(streamBytes, 0, streamBytes.Length);
                reqStream.Close();
            }
            HttpWebResponse response = (HttpWebResponse)(request.GetResponse());

            Debug.WriteLine(((HttpWebResponse)response).StatusDescription);
            var          dataStream         = response.GetResponseStream();
            StreamReader reader             = new StreamReader(dataStream);
            string       responseFromServer = reader.ReadToEnd();

            reader.Close();
            dataStream.Close();
            response.Close();
            Debug.WriteLine(String.Format("Response from URL {0}:", url), "HTTPFetch");
            Debug.WriteLine(responseFromServer, "HTTPFetch");
            return(responseFromServer);
        }