⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fireeagleupdateservice.cs

📁 Some time ago, I stated in another article that I d take the idea of location broadcasting and devel
💻 CS
📖 第 1 页 / 共 2 页
字号:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Configuration;
using System.Collections.Specialized;
using System.Net;
using System.IO;
using System.Collections;
using System.Xml.Serialization;
using DeepCast.Location;
using System.Security.Cryptography;
using DeepCast;

namespace DeepCast.Services
{
    internal class FireEagleService : GeoService
    {
        #region Constants
        private const string FireEagleApiUri = "https://fireeagle.yahooapis.com/";

        private const string DeepCastKey = "cMCZVybPlXKF";
        private const string DeepcastSecret = "60hxslqYBZyfTO4K3zOXCpBiFyotsInQ";

        private const string OAuthVersion = "1.0";
        private const string OAuthParameterPrefix = "oauth_";
        private const string OAuthConsumerKeyKey = "oauth_consumer_key";
        private const string OAuthCallbackKey = "oauth_callback";
        private const string OAuthVersionKey = "oauth_version";
        private const string OAuthSignatureMethodKey = "oauth_signature_method";
        private const string OAuthSignatureKey = "oauth_signature";
        private const string OAuthTimestampKey = "oauth_timestamp";
        private const string OAuthNonceKey = "oauth_nonce";
        private const string OAuthTokenKey = "oauth_token";
        private const string OAuthTokenSecretKey = "oauth_token_secret";
        private const string HMACSHA1SignatureType = "HMAC-SHA1";
        private const string PlainTextSignatureType = "PLAINTEXT";
        private const string RSASHA1SignatureType = "RSA-SHA1";
        private string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";

        #endregion

        private string normalizedUrl = null;
        private string normalizedRequestParameters = null;
        private Random random = new Random();

        #region .ctor
        public FireEagleService()
        {

        }

        #endregion

        #region Methods
        /// <summary>
        /// Generates a request token/secret pair.
        /// </summary>
        public void GetRequestToken()
        {
            NameValueCollection token = CallOauth("GET", FireEagleApiUri + "oauth/request_token", null);
            this.OauthToken = token["oauth_token"];
            this.OauthTokenSecret = token["oauth_token_secret"];
        }
        /// <summary>
        /// Exchanges the request pair for an authorization pair.
        /// </summary>
        public void GetAccessToken()
        {
            NameValueCollection token = CallOauth("GET", FireEagleApiUri + "oauth/access_token", null);
            this.OauthToken = token["oauth_token"];
            this.OauthTokenSecret = token["oauth_token_secret"];
        }
        /// <summary>
        /// Calls the oauth service.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="base_url">The base_url.</param>
        /// <param name="args">The args.</param>
        /// <returns></returns>
        private NameValueCollection CallOauth(string method, string base_url, NameValueCollection args)
        {
            string text = CallInternal(method, base_url, args);
            NameValueCollection resp = new NameValueCollection();

            foreach (string pair in text.Split(new char[] { '&' }))
            {
                string[] split_pair = pair.Split(new char[] { '=' });
                resp.Add(split_pair[0], split_pair[1]);
            }

            return resp;
        }
        /// <summary>
        /// Calls Fire Eagle via HTTP.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="args">The args.</param>
        /// <returns></returns>
        public string CallHttp(string method, NameValueCollection args)
        {
            string http_method = (method == "user") ? "GET" : "POST";
            string base_url = FireEagleApiUri + "api/0.1/" + method + ".json";
            string raw_data = CallInternal(http_method, base_url, args);

            return raw_data;
        }
        /// <summary>
        /// Calls Fire Eagle.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="base_url">The base_url.</param>
        /// <param name="args">The args.</param>
        /// <returns></returns>
        private string CallInternal(string method, string baseUrl, NameValueCollection args)
        {
            string url = baseUrl;

            // Process the data to send to the service
            if (args != null)
            {
                string data = "";
                foreach (string arg in args)
                {
                    data += (data == "" ? "" : "&") + UrlEncode(arg) + "=" + UrlEncode(args[arg]);
                }

                if (data != "") url += (baseUrl.IndexOf("?") == -1 ? "?" : "&") + data;
            }

            Uri uri = new Uri(url);
            string ts = GenerateTimeStamp();
            string nonce = GenerateNonce();
            
            // Fire Eagle requires a hashed signature based on the input parameters.
            string full_url = GenerateSignature(uri, DeepCastKey, DeepcastSecret, OauthToken, OauthTokenSecret, method, ts, nonce);

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(method == "POST" ? normalizedUrl : full_url);
            req.Method = method;
            req.ContentType = "application/x-www-form-urlencoded";
            
            try
            {
                if (method == "POST")
                {
                    byte[] post_data = Encoding.UTF8.GetBytes(normalizedRequestParameters);
                    req.ContentLength = post_data.Length;

                    Stream post_stream = req.GetRequestStream();
                    post_stream.Write(post_data, 0, post_data.Length);
                    post_stream.Close();
                }

                string rawData = "";

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                StreamReader resp_stream = new StreamReader(resp.GetResponseStream());
                rawData = resp_stream.ReadToEnd();
                resp.Close();

                return rawData;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// Computes the hash for the input data.
        /// </summary>
        /// <param name="hashAlgorithm">The hash algorithm.</param>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        private string ComputeHash(HashAlgorithm hashAlgorithm, string data)
        {
            byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(data);
            byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer);
            
            return Convert.ToBase64String(hashBytes);
        }
        /// <summary>
        /// Builds the query string
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        private List<QueryParameter> GetQueryParameters(string parameters)
        {
            if (parameters.StartsWith("?"))
            {
                parameters = parameters.Remove(0, 1);
            }

            List<QueryParameter> result = new List<QueryParameter>();

            if (!string.IsNullOrEmpty(parameters))
            {
                string[] values = parameters.Split('&');
                foreach (string val in values)
                {
                    if (!string.IsNullOrEmpty(val) && !val.StartsWith(OAuthParameterPrefix))
                    {
                        if (val.IndexOf('=') > -1)
                        {
                            string[] parts = val.Split('=');
                            result.Add(new QueryParameter(parts[0], parts[1]));
                        }
                        else
                        {
                            result.Add(new QueryParameter(val, string.Empty));
                        }
                    }
                }
            }

            return result;
        }
        /// <summary>
        /// Fire Eagle specific URL encoding.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        protected string UrlEncode(string value)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -