Пример #1
0
        /// <summary>
        /// Calculates the message parameters, including the oaut_signature
        /// </summary>
        /// OAuthUtility.GetMessageParameters(apiKey, appSecret, url, method, accessToken, args);
        internal static string GetMessageParameters(string APIKey, string Secret, string url, string methodName, Token tok, params object[] args)
        {
            List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>(oauth_timestamp, OAuthUtility.GenerateTimestamp()),
                new KeyValuePair <string, string>(oauth_nonce, OAuthUtility.GenerateNonce()),
                new KeyValuePair <string, string>(oauth_consumer_key, APIKey),
                new KeyValuePair <string, string>(oauth_signature_method, "HMAC-SHA1"),
                new KeyValuePair <string, string>(oauth_version, "1.0"),
                //new KeyValuePair<string,string>("Pretty", "true")
            };

            var method = new KeyValuePair <string, string>("method", methodName);

            parameters.Add(method);

            // add the access token if present
            if (tok != null)
            {
                parameters.Add(new KeyValuePair <string, string>(oauth_token, tok.id));
            }

            for (int i = 0; i < args.Length; i += 2)
            {
                parameters.Add(new KeyValuePair <string, string>(args[i].ToString(), args[i + 1].ToString()));
            }

            string baseString = OAuthUtility.GenerateBaseString(url, "GET", parameters);
            string sig        = OAuthUtility.EncodeValue(OAuthUtility.GenerateHMACDigest(baseString, Secret, tok == null ? "" : tok.Secret));

            parameters.Add(new KeyValuePair <string, string>(oauth_signature, sig));

            parameters.Remove(method);

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("method={0}", methodName);

            foreach (var param in parameters)
            {
                if (param.Key.StartsWith("oauth_"))
                {
                    sb.AppendFormat("&{0}={1}", param.Key, HttpUtility.HtmlEncode(param.Value));
                }
                else
                {
                    sb.AppendFormat("&{0}={1}", param.Key, EncodeValue(param.Value));
                }
            }

            return(sb.ToString());
        }
Пример #2
0
        /// <summary>
        /// Calculates teh Authorization header to use with the oAuth authentication
        /// </summary>
        internal static string GetAuthorizationHeader(string apiKey, string appSecret, Token tok, string endpoint, params object[] args)
        {
            List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>(oauth_timestamp, OAuthUtility.GenerateTimestamp()),
                new KeyValuePair <string, string>(oauth_nonce, OAuthUtility.GenerateNonce()),
                new KeyValuePair <string, string>(oauth_consumer_key, apiKey),
                new KeyValuePair <string, string>(oauth_signature_method, "HMAC-SHA1"),
                new KeyValuePair <string, string>(oauth_token, tok.id),
                new KeyValuePair <string, string>(oauth_token_secret, tok.Secret)
            };

            // Add of the other parameters to the mix
            for (int i = 0; i < args.Length; i += 2)
            {
                parameters.Add(new KeyValuePair <string, string>(args[i].ToString(), args[i + 1].ToString()));
            }

            string baseString = OAuthUtility.GenerateBaseString(endpoint, "PUT", parameters);
            string sig        = OAuthUtility.EncodeValue(OAuthUtility.GenerateHMACDigest(baseString, appSecret, tok == null ? "" : tok.Secret));

            parameters.Add(new KeyValuePair <string, string>(oauth_signature, sig));

            // the authorization header only consists of oauth_ tokens


            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("OAuth ");

            foreach (var param in parameters)
            {
                if (param.Key.StartsWith("oauth", StringComparison.OrdinalIgnoreCase))
                {
                    sb.AppendFormat("{0}=\"{1}\",", param.Key, param.Value);
                }
            }
            // remove the trailing ,
            sb.Remove(sb.Length - 1, 1);

            return(sb.ToString());
        }
Пример #3
0
        /// <summary>
        /// Uploads the Image to SmugMug using HTTP Post replacing the existing image
        /// </summary>
        /// <param name="stream">The stream to the image on disk.</param>
        /// <param name="albumID">The id for the Image to be added.</param>
        /// <returns>Throws an <see cref="SmugMugUploadException"/>
        /// if an error occurs trying to upload the Image.</remarks>
        public UploadContext PrepareUpload(Stream photoStream, string fileName, string keywords, long albumID, string albumKey, long imageID)
        {
            UploadContext cookie = new UploadContext(fileName);

            logger.InfoFormat("Preparing file for upload: {0}, album id: {1}, album key: {2}",
                              fileName, albumID, albumKey);



            //int timeOut = ((int)photoStream.Length / 1024) * 1000;
            //cookie.Request.Timeout = timeOut;
            cookie.Request.Timeout          = Timeout.Infinite;
            cookie.Request.ReadWriteTimeout = Timeout.Infinite;

            cookie.Request.ConnectionGroupName = Guid.NewGuid().ToString();

            //cookie.Request.Headers.Add("X-Smug-SessionID", this.account.Session.id);
            cookie.Request.Headers.Add("X-Smug-Version", SmugMugApi.VERSION);
            cookie.Request.Headers.Add("X-Smug-ResponseType", "JSON");
            cookie.Request.Headers.Add("X-Smug-AlbumID", albumID.ToString());
            cookie.Request.Headers.Add("X-Smug-AlbumKey", albumKey);

            if (imageID > 0) // we are replacing the image if the ID is passed in
            {
                cookie.Request.Headers.Add("X-Smug-imageID", imageID.ToString());
            }

            // removed this as non ascii characters we not sent
            //cookie.Request.Headers.Add("X-Smug-FileName", fileName);

            //if (String.IsNullOrEmpty(caption) == false)
            //{
            //    cookie.Request.Headers.Add("X-Smug-Caption", HttpUtility.UrlEncode(caption));
            //}

            if (String.IsNullOrEmpty(keywords) == false)
            {
                cookie.Request.Headers.Add("X-Smug-Keywords", keywords);
            }

            // Add the authorization header
            string uploadURL = SmugMugApi.UploadUrl + fileName;

            cookie.Request.Headers.Add("Authorization", OAuthUtility.GetAuthorizationHeader(this.apiKey, this.appSecret, this.accessToken, uploadURL));

            // disable HTTP/1.1 Continue
            // http://haacked.com/archive/2004/05/15/http-web-request-expect-100-continue.aspx
            ServicePointManager.Expect100Continue = false;

            string md5sum;
            MD5    md5 = new MD5CryptoServiceProvider();

            byte[] hash = md5.ComputeHash(photoStream);

            StringBuilder buff = new StringBuilder();

            foreach (byte hashByte in hash)
            {
                buff.Append(String.Format("{0:x2}", hashByte));
            }

            md5sum = buff.ToString();
            cookie.Request.Headers.Add("Content-MD5", md5sum);
            cookie.PhotoStream = photoStream;

            cookie.Request.ContentLength = cookie.PhotoStream.Length;

            // This option prevents uploads from being buffered into memory, avoiding OutOfMemory
            // exceptions on large uploads.
            cookie.Request.AllowWriteStreamBuffering = false;

            cookie.PhotoStream.Position = 0;

            cookie.RequestStream = cookie.Request.GetRequestStream();
            cookie.ChunkSize     = Math.Max((int)(cookie.PhotoStream.Length / 100), 65536);

            logger.InfoFormat("Image upload start time: {0}", DateTime.Now.ToString());

            return(cookie);
        }
Пример #4
0
        public static string ExecuteSmugMugHttpRequest(string method, string apiKey, string appSecret, Token accessToken, bool secure = false, params string[] args)
        {
            //if we don't have a method or the parameters are not in pairs of 2, bail
            if (string.IsNullOrEmpty(method))
            {
                throw new ArgumentException("The method cannot be null or empty", "method");
            }

            if (args.Length > 0 && args.Length % 2 != 0)
            {
                throw new ArgumentException("The number of arguments must be even", "args");
            }

            // we need to check the last null value if we have an "Extras" key but not a value
            if (args != null && args.Length > 0)
            {
                if (args[args.Length - 1] == null)
                {
                    throw new ArgumentException("Passed in an Extras key without a value", "args");
                }
            }

            // Generate the request string (with the oauth_signature)
            string message = OAuthUtility.GetMessageParameters(apiKey, appSecret, SmugMugApi.JsonUrlSecure, method, accessToken, args.ToArray());

            var myWebRequest = HttpWebRequest.Create(SmugMugApi.JsonUrlSecure + "?" + message);

            ((HttpWebRequest)myWebRequest).UserAgent = SmugMugRequest.UserAgent;
            ((HttpWebRequest)myWebRequest).AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

            //do we have a proxy?
            if (SmugMugApi.Proxy != null && !SmugMugApi.Proxy.IsBypassed(new Uri(SmugMugApi.JsonUrlSecure)))
            {
                myWebRequest.Proxy = SmugMugApi.Proxy;
            }

            myWebRequest.Method = "GET";
            myWebRequest.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";

            logger.InfoFormat("HTTP request: {0}", myWebRequest.RequestUri);

            //we read the response
            string result = string.Empty;

            using (var response = myWebRequest.GetResponse())
            {
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }
            }

            logger.InfoFormat("HTTP result: {0}", result);

            if (String.IsNullOrEmpty(result))
            {
                throw new Exception("SmugMug request returned null");
            }

            return(result);
        }