Beispiel #1
0
        /// <summary>
        /// For a given request token and verifier string return an access token.
        /// </summary>
        /// <param name="requestToken"></param>
        /// <param name="requestTokenSecret"></param>
        /// <param name="verifier"></param>
        /// <param name="callback"></param>
        public async Task <FlickrResult <OAuthAccessToken> > OAuthGetAccessTokenAsync(string requestToken, string requestTokenSecret, string verifier)
        {
            string url = "https://www.flickr.com/services/oauth/access_token";

            Dictionary <string, string> parameters = OAuthGetBasicParameters();

            parameters.Add("oauth_verifier", verifier);
            parameters.Add("oauth_token", requestToken);

            string sig = OAuthCalculateSignature("POST", url, parameters, requestTokenSecret);

            parameters.Add("oauth_signature", sig);

            var r = await FlickrResponder.GetDataResponseAsync(this, "", url, parameters);

            FlickrResult <OAuthAccessToken> result = new FlickrResult <OAuthAccessToken>();

            if (r.Error != null)
            {
                if (r.Error is System.Net.WebException)
                {
                    OAuthException ex = new OAuthException(r.Error);
                    result.Error = ex;
                }
                else
                {
                    result.Error = r.Error;
                }

                return(result);
            }
            result.Result = FlickrNet.OAuthAccessToken.ParseResponse(r.Result);
            return(result);
        }
        /// <summary>
        /// Get an <see cref="OAuthRequestToken"/> for the given callback URL.
        /// </summary>
        /// <remarks>Specify 'oob' as the callback url for no callback to be performed.</remarks>
        /// <param name="callbackUrl">The callback Uri, or 'oob' if no callback is to be performed.</param>
        /// <param name="callback"></param>
        async public Task <bool> OAuthGetRequestTokenAsync(string callbackUrl, Action <FlickrResult <OAuthRequestToken> > callback)
        {
            string url = "http://www.flickr.com/services/oauth/request_token";

            Dictionary <string, string> parameters = OAuthGetBasicParameters();

            parameters.Add("oauth_callback", callbackUrl);

            string sig = OAuthCalculateSignature("POST", url, parameters, null);

            parameters.Add("oauth_signature", sig);

            FlickrResponder.GetDataResponseAsync(this, url, parameters, (r) =>
            {
                FlickrResult <OAuthRequestToken> result = new FlickrResult <OAuthRequestToken>();
                if (r.Error != null)
                {
                    if (r.Error is System.Net.WebException)
                    {
                        OAuthException ex = new OAuthException(r.Error);
                        result.Error      = ex;
                    }
                    else
                    {
                        result.Error = r.Error;
                    }
                    callback(result);
                    return;
                }
                result.Result = FlickrNet.OAuthRequestToken.ParseResponse(r.Result);
                callback(result);
            });

            return(true);
        }
Beispiel #3
0
        /// <summary>
        /// For a given request token and verifier string return an access token.
        /// </summary>
        /// <param name="requestToken"></param>
        /// <param name="requestTokenSecret"></param>
        /// <param name="verifier"></param>
        /// <returns></returns>
        public OAuthAccessToken OAuthGetAccessToken(string requestToken, string requestTokenSecret, string verifier)
        {
            CheckApiKey();

            string url = "https://www.flickr.com/services/oauth/access_token";

            Dictionary <string, string> parameters = OAuthGetBasicParameters();

            parameters.Add("oauth_verifier", verifier);
            parameters.Add("oauth_token", requestToken);

            string sig = OAuthCalculateSignature("POST", url, parameters, requestTokenSecret);

            parameters.Add("oauth_signature", sig);

            string response = FlickrResponder.GetDataResponse(this, url, parameters);

            var accessToken = FlickrNet.OAuthAccessToken.ParseResponse(response);

            // Set current access token.
            OAuthAccessToken       = accessToken.Token;
            OAuthAccessTokenSecret = accessToken.TokenSecret;

            return(accessToken);
        }
Beispiel #4
0
        private string UploadData(Stream imageStream, string fileName, Uri uploadUri, Dictionary <string, string> parameters)
        {
            string boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);

            byte[] dataBuffer = CreateUploadData(imageStream, fileName, parameters, boundary);

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uploadUri);

            //req.UserAgent = "Mozilla/4.0 FlickrNet API (compatible; MSIE 6.0; Windows NT 5.1)";
            req.Method = "POST";
            if (Proxy != null)
            {
                req.Proxy = Proxy;
            }
            req.Timeout     = HttpTimeout;
            req.ContentType = "multipart/form-data; boundary=" + boundary;
            //req.Expect = String.Empty;
            if (!String.IsNullOrEmpty(authHeader))
            {
                req.Headers["Authorization"] = authHeader;
            }

            req.ContentLength = dataBuffer.Length;

            using (Stream reqStream = req.GetRequestStream())
            {
                int bufferSize = 32 * 1024;
                if (dataBuffer.Length / 100 > bufferSize)
                {
                    bufferSize = bufferSize * 2;
                }

                int uploadedSoFar = 0;

                while (uploadedSoFar < dataBuffer.Length)
                {
                    reqStream.Write(dataBuffer, uploadedSoFar, Math.Min(bufferSize, dataBuffer.Length - uploadedSoFar));
                    uploadedSoFar += bufferSize;

                    if (OnUploadProgress != null)
                    {
                        UploadProgressEventArgs args = new UploadProgressEventArgs(uploadedSoFar, dataBuffer.Length);
                        OnUploadProgress(this, args);
                    }
                }
                reqStream.Close();
            }

            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            StreamReader sr = new StreamReader(res.GetResponseStream());
            string       s  = sr.ReadToEnd();

            sr.Close();
            return(s);
        }
        public async Task <string> UploadPicture(Stream stream, string filename, string title, string description, string tags, bool isPublic, bool isFamily, bool isFriend, ContentType contentType, SafetyLevel safetyLevel, HiddenFromSearch hiddenFromSearch)
        {
            var parameters = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(title))
            {
                parameters.Add("title", title);
            }
            if (!string.IsNullOrEmpty(description))
            {
                parameters.Add("description", description);
            }
            if (!string.IsNullOrEmpty(tags))
            {
                parameters.Add("tags", tags);
            }

            parameters.Add("is_public", isPublic ? "1" : "0");
            parameters.Add("is_friend", isFriend ? "1" : "0");
            parameters.Add("is_family", isFamily ? "1" : "0");

            if (safetyLevel != SafetyLevel.None)
            {
                parameters.Add("safety_level", safetyLevel.ToString("D"));
            }
            if (contentType != ContentType.None)
            {
                parameters.Add("content_type", contentType.ToString("D"));
            }
            if (hiddenFromSearch != HiddenFromSearch.None)
            {
                parameters.Add("hidden", hiddenFromSearch.ToString("D"));
            }

            FlickrResponder.OAuthGetBasicParameters(parameters);
            parameters.Add("oauth_consumer_key", ApiKey);
            parameters.Add("oauth_token", OAuthAccessToken);
            parameters.Add("oauth_signature",
                           OAuthCalculateSignature("POST", UploadUrl, parameters, OAuthAccessTokenSecret));

            var boundary = FlickrResponder.CreateBoundary();
            var data     = FlickrResponder.CreateUploadData(stream, filename, parameters, boundary);

            var oauthHeader       = FlickrResponder.OAuthCalculateAuthHeader(parameters);
            var contentTypeHeader = "multipart/form-data; boundary=" + boundary;

            var response = await FlickrResponder.UploadDataAsync(UploadUrl, data, contentTypeHeader, oauthHeader);

            var match = Regex.Match(response, "<photoid>(\\d+)</photoid>");

            if (!match.Success)
            {
                throw new FlickrException("Unable to determine photo id from upload response: " + response);
            }

            return(match.Groups[1].Value);
        }
Beispiel #6
0
        private string UploadData(Stream imageStream, string fileName, Uri uploadUri, Dictionary <string, string> parameters)
        {
            var boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            var authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);
            var dataBuffer = CreateUploadData(imageStream, fileName, parameters, boundary);

            var req = (HttpWebRequest)WebRequest.Create(uploadUri);

            req.Method = "POST";
            if (Proxy != null)
            {
                req.Proxy = Proxy;
            }
            req.Timeout     = HttpTimeout;
            req.ContentType = "multipart/form-data; boundary=" + boundary;

            if (!string.IsNullOrEmpty(authHeader))
            {
                req.Headers["Authorization"] = authHeader;
            }

            req.AllowWriteStreamBuffering = false;
            req.SendChunked = true;
            //req.ContentLength = dataBuffer.Length;

            using (var reqStream = req.GetRequestStream())
            {
                var bufferSize = 32 * 1024;
                if (dataBuffer.Length / 100 > bufferSize)
                {
                    bufferSize = bufferSize * 2;
                }
                dataBuffer.UploadProgress += (o, e) => { if (OnUploadProgress != null)
                                                         {
                                                             OnUploadProgress(this, e);
                                                         }
                };
                dataBuffer.CopyTo(reqStream, bufferSize);
                reqStream.Flush();
            }

            var res    = (HttpWebResponse)req.GetResponse();
            var stream = res.GetResponseStream();

            if (stream == null)
            {
                throw new FlickrWebException("Unable to retrieve stream from web response.");
            }

            var sr = new StreamReader(stream);
            var s  = sr.ReadToEnd();

            sr.Close();
            return(s);
        }
        /// <summary>
        /// Get an <see cref="OAuthRequestToken"/> for the given callback URL.
        /// </summary>
        /// <remarks>Specify 'oob' as the callback for no callback to be performed.</remarks>
        /// <param name="callback">The callback Uri, or 'oob' if no callback is to be performed.</param>
        /// <returns></returns>
        public OAuthRequestToken OAuthGetRequestToken(string callback)
        {
            string url = "http://www.flickr.com/services/oauth/request_token";

            Dictionary <string, string> parameters = OAuthGetBasicParameters();

            parameters.Add("oauth_callback", callback);

            string sig = OAuthCalculateSignature("POST", url, parameters, null);

            parameters.Add("oauth_signature", sig);

            string response = FlickrResponder.GetDataResponse(this, url, parameters);;

            return(OAuthRequestToken.ParseResponse(response));
        }
        internal async Task <T> GetResponseAsync <T>(IDictionary <string, string> parameters) where T : class, IFlickrParsable, new()
        {
            if (!parameters.ContainsKey("oauth_consumer_key"))
            {
                parameters.Add("oauth_consumer_key", ApiKey);
            }

            var result = await FlickrResponder.GetDataResponseAsync(this, BaseApiUrl, parameters);

            var typeInfo = typeof(T).GetTypeInfo();

            if (typeInfo.IsEnum)
            {
                return(default(T));
            }
            if (typeInfo.ImplementedInterfaces.Any(t => t.Name == "IFlickrParsable"))
            {
                using (var reader = XmlReader.Create(new StringReader(result), new XmlReaderSettings {
                    IgnoreWhitespace = true
                }))
                {
                    if (!reader.ReadToDescendant("rsp"))
                    {
                        throw new XmlException("Unable to find response element 'rsp' in Flickr response");
                    }
                    while (reader.MoveToNextAttribute())
                    {
                        if (reader.LocalName == "stat" && reader.Value == "fail")
                        {
                            throw ExceptionHandler.CreateResponseException(reader);
                        }
                    }

                    reader.MoveToElement();
                    reader.Read();

                    var item = new T();
                    item.Load(reader);
                    return(item);
                }
            }

            return(default(T));
        }
Beispiel #9
0
        internal T GetResponse <T>(IDictionary <string, string> parameters) where T : class, IFlickrParsable, new()
        {
            if (!parameters.ContainsKey("oauth_consumer_key"))
            {
                parameters.Add("oauth_consumer_key", ApiKey);
            }

            var result = FlickrResponder.GetDataResponse(this, BaseApiUrl, parameters);

            LastResponse = result;

            if (typeof(T).IsEnum)
            {
                return(default(T));
            }
            if (typeof(T).GetInterface("FlickrNet.IFlickrParsable") != null)
            {
                using (var reader = new XmlTextReader(new StringReader(result)))
                {
                    reader.WhitespaceHandling = WhitespaceHandling.None;

                    if (!reader.ReadToDescendant("rsp"))
                    {
                        throw new XmlException("Unable to find response element 'rsp' in Flickr response");
                    }
                    while (reader.MoveToNextAttribute())
                    {
                        if (reader.LocalName == "stat" && reader.Value == "fail")
                        {
                            throw ExceptionHandler.CreateResponseException(reader);
                        }
                    }

                    reader.MoveToElement();
                    reader.Read();

                    var item = new T();
                    item.Load(reader);
                    return(item);
                }
            }

            return(default(T));
        }
        /// <summary>
        /// For a given request token and verifier string return an access token.
        /// </summary>
        /// <param name="requestToken"></param>
        /// <param name="requestTokenSecret"></param>
        /// <param name="verifier"></param>
        /// <param name="callback"></param>
        public void OAuthGetAccessTokenAsync(string requestToken, string requestTokenSecret, string verifier, Action <FlickrResult <OAuthAccessToken> > callback)
        {
            CheckApiKey();

#if SILVERLIGHT
            string url = "https://api.flickr.com/services/oauth/access_token";
#else
            string url = "https://www.flickr.com/services/oauth/access_token";
#endif

            Dictionary <string, string> parameters = OAuthGetBasicParameters();

            parameters.Add("oauth_verifier", verifier);
            parameters.Add("oauth_token", requestToken);

            string sig = OAuthCalculateSignature("POST", url, parameters, requestTokenSecret);

            parameters.Add("oauth_signature", sig);

            FlickrResponder.GetDataResponseAsync(this, url, parameters, (r) =>
            {
                FlickrResult <OAuthAccessToken> result = new FlickrResult <OAuthAccessToken>();
                if (r.Error != null)
                {
                    if (r.Error is System.Net.WebException)
                    {
                        OAuthException ex = new OAuthException(r.Error);
                        result.Error      = ex;
                    }
                    else
                    {
                        result.Error = r.Error;
                    }

                    callback(result);
                    return;
                }
                result.Result = FlickrNet.OAuthAccessToken.ParseResponse(r.Result);
                callback(result);
            });
        }
        public async Task <OAuthRequestToken> OAuthRequestTokenAsync(string callbackUrl)
        {
            const string url = "https://www.flickr.com/services/oauth/request_token";

            IDictionary <string, string> parameters = new Dictionary <string, string>();

            FlickrResponder.OAuthGetBasicParameters(parameters);
            parameters.Add("oauth_callback", callbackUrl);
            parameters.Add("oauth_consumer_key", ApiKey);

            var sig = OAuthCalculateSignature("POST", url, parameters, null);

            parameters.Add("oauth_signature", sig);

            var data       = FlickrResponder.OAuthCalculatePostData(parameters);
            var authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);

            var response = await FlickrResponder.DownloadDataAsync("POST", url, data, null, authHeader);

            return(OAuthRequestToken.ParseResponse(response));
        }
        public async Task <OAuthAccessToken> OAuthAccessTokenAsync(string requestToken, string requestTokenSecret, string verifier)
        {
            const string url = "https://www.flickr.com/services/oauth/access_token";

            if (verifier.Contains("://"))
            {
                var uri = new Uri(verifier);
                verifier =
                    uri.Query.Split(new[] { '&' })
                    .Select(s => s.Split(new[] { '=' }))
                    .First(s => s[0] == "oauth_verifier")[1];
            }
            IDictionary <string, string> parameters = new Dictionary <string, string>();

            FlickrResponder.OAuthGetBasicParameters(parameters);

            parameters.Add("oauth_consumer_key", ApiKey);
            parameters.Add("oauth_verifier", verifier);
            parameters.Add("oauth_token", requestToken);

            var sig = OAuthCalculateSignature("POST", url, parameters, requestTokenSecret);

            parameters.Add("oauth_signature", sig);

            var data       = FlickrResponder.OAuthCalculatePostData(parameters);
            var authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);
            var response   = await FlickrResponder.DownloadDataAsync("POST", url, data, null, authHeader);

            var accessToken = FlickrNet.OAuthAccessToken.ParseResponse(response);

            // Set current access token.
            OAuthAccessToken       = accessToken.Token;
            OAuthAccessTokenSecret = accessToken.TokenSecret;

            return(accessToken);
        }
Beispiel #13
0
        private void GetResponseAsync <T>(Dictionary <string, string> parameters, Action <FlickrResult <T> > callback) where T : IFlickrParsable, new()
        {
            CheckApiKey();

            parameters["api_key"] = ApiKey;

            // If performing one of the old 'flickr.auth' methods then use old authentication details.
            string method = parameters["method"];

            if (method.StartsWith("flickr.auth", StringComparison.Ordinal) && !method.EndsWith("oauth.checkToken", StringComparison.Ordinal))
            {
                if (!string.IsNullOrEmpty(AuthToken))
                {
                    parameters["auth_token"] = AuthToken;
                }
            }
            else
            {
                // If OAuth Token exists or no authentication required then use new OAuth
                if (!string.IsNullOrEmpty(OAuthAccessToken) || string.IsNullOrEmpty(AuthToken))
                {
                    OAuthGetBasicParameters(parameters);
                    if (!string.IsNullOrEmpty(OAuthAccessToken))
                    {
                        parameters["oauth_token"] = OAuthAccessToken;
                    }
                }
                else
                {
                    parameters["auth_token"] = AuthToken;
                }
            }


            var url = CalculateUri(parameters, !string.IsNullOrEmpty(sharedSecret));

            lastRequest = url;

            try
            {
                FlickrResponder.GetDataResponseAsync(this, BaseUri.AbsoluteUri, parameters, (r)
                                                     =>
                {
                    var result = new FlickrResult <T>();
                    if (r.HasError)
                    {
                        result.Error = r.Error;
                    }
                    else
                    {
                        try
                        {
                            lastResponse = r.Result;

                            var t = new T();
                            ((IFlickrParsable)t).Load(r.Result);
                            result.Result   = t;
                            result.HasError = false;
                        }
                        catch (Exception ex)
                        {
                            result.Error = ex;
                        }
                    }

                    if (callback != null)
                    {
                        callback(result);
                    }
                });
            }
            catch (Exception ex)
            {
                var result = new FlickrResult <T>();
                result.Error = ex;
                if (null != callback)
                {
                    callback(result);
                }
            }
        }
Beispiel #14
0
        public async Task <string> UploadPictureAsync(Stream stream, string filename, string title, string description, string tags, bool isPublic, bool isFamily, bool isFriend, ContentType contentType, SafetyLevel safetyLevel, HiddenFromSearch hiddenFromSearch)
        {
            var parameters = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(title))
            {
                parameters.Add("title", title);
            }
            if (!string.IsNullOrEmpty(description))
            {
                parameters.Add("description", description);
            }
            if (!string.IsNullOrEmpty(tags))
            {
                parameters.Add("tags", tags);
            }

            parameters.Add("is_public", isPublic ? "1" : "0");
            parameters.Add("is_friend", isFriend ? "1" : "0");
            parameters.Add("is_family", isFamily ? "1" : "0");

            if (safetyLevel != SafetyLevel.None)
            {
                parameters.Add("safety_level", safetyLevel.ToString("D"));
            }
            if (contentType != ContentType.None)
            {
                parameters.Add("content_type", contentType.ToString("D"));
            }
            if (hiddenFromSearch != HiddenFromSearch.None)
            {
                parameters.Add("hidden", hiddenFromSearch.ToString("D"));
            }

            FlickrResponder.OAuthGetBasicParameters(parameters);
            parameters.Add("oauth_consumer_key", ApiKey);
            parameters.Add("oauth_token", OAuthAccessToken);
            parameters.Add("oauth_signature",
                           OAuthCalculateSignature("POST", UploadUrl, parameters, OAuthAccessTokenSecret));

            var boundary = FlickrResponder.CreateBoundary();
            var data     = FlickrResponder.CreateUploadData(stream, filename, parameters, boundary);

            var oauthHeader       = FlickrResponder.OAuthCalculateAuthHeader(parameters);
            var contentTypeHeader = "multipart/form-data; boundary=" + boundary;

            var response = await FlickrResponder.UploadDataAsync(UploadUrl, data, contentTypeHeader, oauthHeader);

            var match = Regex.Match(response, "<photoid>(\\d+)</photoid>");

            if (match.Success)
            {
                return(match.Groups[1].Value);
            }

            using (var reader = XmlReader.Create(new StringReader(response), new XmlReaderSettings {
                IgnoreWhitespace = true
            }))
            {
                if (!reader.ReadToDescendant("rsp"))
                {
                    throw new XmlException("Unable to find response element 'rsp' in Flickr response");
                }
                while (reader.MoveToNextAttribute())
                {
                    if (reader.LocalName == "stat" && reader.Value == "fail")
                    {
                        throw ExceptionHandler.CreateResponseException(reader);
                    }
                }
            }

            throw new FlickrException("Unable to determine photo id from upload response: " + response);
        }
        private void GetResponseAsync <T>(Dictionary <string, string> parameters, Action <FlickrResult <T> > callback) where T : IFlickrParsable, new()
        {
            CheckApiKey();

            parameters["api_key"] = ApiKey;

            // If performing one of the old 'flickr.auth' methods then use old authentication details.
            string method = parameters["method"];

            if (method.StartsWith("flickr.auth", StringComparison.Ordinal) && !method.EndsWith("oauth.checkToken", StringComparison.Ordinal))
            {
                if (!string.IsNullOrEmpty(AuthToken))
                {
                    parameters["auth_token"] = AuthToken;
                }
            }
            else
            {
                // If OAuth Token exists or no authentication required then use new OAuth
                if (!string.IsNullOrEmpty(OAuthAccessToken) || string.IsNullOrEmpty(AuthToken))
                {
                    OAuthGetBasicParameters(parameters);
                    if (!string.IsNullOrEmpty(OAuthAccessToken))
                    {
                        parameters["oauth_token"] = OAuthAccessToken;
                    }
                }
                else
                {
                    parameters["auth_token"] = AuthToken;
                }
            }


            var url = CalculateUri(parameters, !string.IsNullOrEmpty(sharedSecret));

            lastRequest = url;

            try
            {
                FlickrResponder.GetDataResponseAsync(this, BaseUri.AbsoluteUri, parameters, (r)
                                                     =>
                {
                    var result = new FlickrResult <T>();
                    if (r.HasError)
                    {
                        result.Error = r.Error;
                    }
                    else
                    {
                        try
                        {
                            lastResponse = r.Result;

                            var settings = new XmlReaderSettings();
                            settings.IgnoreWhitespace = true;
                            XmlReader reader          = XmlReader.Create(new StringReader(r.Result), settings);

                            if (!reader.ReadToDescendant("rsp"))
                            {
                                throw new XmlException("Unable to find response element 'rsp' in Flickr response");
                            }
                            while (reader.MoveToNextAttribute())
                            {
                                if (reader.LocalName == "stat" && reader.Value == "fail")
                                {
                                    throw ExceptionHandler.CreateResponseException(reader);
                                }
                                continue;
                            }

                            reader.MoveToElement();
                            reader.Read();

                            var t = new T();
                            ((IFlickrParsable)t).Load(reader);
                            result.Result   = t;
                            result.HasError = false;
                        }
                        catch (Exception ex)
                        {
                            result.Error = ex;
                        }
                    }

                    if (callback != null)
                    {
                        callback(result);
                    }
                });
            }
            catch (Exception ex)
            {
                var result = new FlickrResult <T>();
                result.Error = ex;
                if (null != callback)
                {
                    callback(result);
                }
            }
        }
 internal async Task GetResponseAsync(IDictionary <string, string> parameters)
 {
     await FlickrResponder.GetDataResponseAsync(this, BaseApiUrl, parameters);
 }
Beispiel #17
0
        private string UploadData(Stream imageStream, string fileName, Uri uploadUri, Dictionary <string, string> parameters)
        {
            var boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            var authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);
            var dataBuffer = CreateUploadData(imageStream, fileName, parameters, boundary);

            var req = (HttpWebRequest)WebRequest.Create(uploadUri);

            req.Method = "POST";
            if (Proxy != null)
            {
                req.Proxy = Proxy;
            }
            req.Timeout     = HttpTimeout;
            req.ContentType = "multipart/form-data; boundary=" + boundary;

            if (!string.IsNullOrEmpty(authHeader))
            {
                req.Headers["Authorization"] = authHeader;
            }


            req.UserAgent



            // VTVT na zaklade: http://genjurosdojo.blogspot.cz/2012/10/the-remote-server-returned-error-504.html

            /*req.Headers["User-Agent"]*/ = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0)" +
                                            " (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";



            req.AllowWriteStreamBuffering = false;
            req.SendChunked = true;
            //req.ContentLength = dataBuffer.Length;

            using (var reqStream = req.GetRequestStream())
            {
                var bufferSize = 32 * 1024;
                if (dataBuffer.Length / 100 > bufferSize)
                {
                    bufferSize = bufferSize * 2;
                }
                dataBuffer.UploadProgress += (o, e) => { if (OnUploadProgress != null)
                                                         {
                                                             OnUploadProgress(this, e);
                                                         }
                };
                dataBuffer.CopyTo(reqStream, bufferSize);
                reqStream.Flush();
            }

            var res    = (HttpWebResponse)req.GetResponse();
            var stream = res.GetResponseStream();

            if (stream == null)
            {
                throw new FlickrWebException("Unable to retrieve stream from web response.");
            }

            var sr = new StreamReader(stream);
            var s  = sr.ReadToEnd();

            sr.Close();
            return(s);
        }
Beispiel #18
0
        private void UploadDataAsync(Stream imageStream, string fileName, Uri uploadUri, Dictionary <string, string> parameters, Action <FlickrResult <string> > callback)
        {
            string boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);

            byte[] dataBuffer = CreateUploadData(imageStream, fileName, parameters, boundary);

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uploadUri);

            req.Method      = "POST";
            req.ContentType = "multipart/form-data; boundary=" + boundary;
            if (!String.IsNullOrEmpty(authHeader))
            {
                req.Headers["Authorization"] = authHeader;
            }

            req.BeginGetRequestStream(
                r =>
            {
                Stream s       = req.EndGetRequestStream(r);
                int bufferSize = 1024 * 32;
                int soFar      = 0;
                while (soFar < dataBuffer.Length)
                {
                    if ((dataBuffer.Length - soFar) < bufferSize)
                    {
                        bufferSize = dataBuffer.Length - soFar;
                    }
                    s.Write(dataBuffer, soFar, bufferSize);
                    soFar += bufferSize;

                    if (OnUploadProgress != null)
                    {
                        UploadProgressEventArgs args = new UploadProgressEventArgs(soFar, dataBuffer.Length);
                        OnUploadProgress(this, args);
                    }
                }

                req.BeginGetResponse(
                    r2 =>
                {
                    FlickrResult <string> result = new FlickrResult <string>();

                    try
                    {
                        WebResponse res    = req.EndGetResponse(r2);
                        StreamReader sr    = new StreamReader(res.GetResponseStream());
                        string responseXml = sr.ReadToEnd();


                        XmlReaderSettings settings = new XmlReaderSettings();
                        settings.IgnoreWhitespace  = true;
                        XmlReader reader           = XmlReader.Create(new StringReader(responseXml), settings);

                        if (!reader.ReadToDescendant("rsp"))
                        {
                            throw new XmlException("Unable to find response element 'rsp' in Flickr response");
                        }
                        while (reader.MoveToNextAttribute())
                        {
                            if (reader.LocalName == "stat" && reader.Value == "fail")
                            {
                                throw ExceptionHandler.CreateResponseException(reader);
                            }
                            continue;
                        }

                        reader.MoveToElement();
                        reader.Read();

                        UnknownResponse t = new UnknownResponse();
                        ((IFlickrParsable)t).Load(reader);
                        result.Result   = t.GetElementValue("photoid");
                        result.HasError = false;
                    }
                    catch (Exception ex)
                    {
                        if (ex is WebException)
                        {
                            OAuthException oauthEx = new OAuthException(ex);
                            if (String.IsNullOrEmpty(oauthEx.Message))
                            {
                                result.Error = ex;
                            }
                            else
                            {
                                result.Error = oauthEx;
                            }
                        }
                        else
                        {
                            result.Error = ex;
                        }
                    }

                    callback(result);
                },
                    this);
            },
                this);
        }
Beispiel #19
0
        private T GetResponse <T>(Dictionary <string, string> parameters, TimeSpan cacheTimeout) where T : IFlickrParsable, new()
        {
            // Flow for GetResponse.
            // 1. Check API Key
            // 2. Calculate Cache URL.
            // 3. Check Cache for URL.
            // 4. Get Response if not in cache.
            // 5. Write Cache.
            // 6. Parse Response.

            CheckApiKey();

            parameters["api_key"] = ApiKey;

            // If performing one of the old 'flickr.auth' methods then use old authentication details.
            var method = parameters["method"];

            // User of obsolete AuthToken property while we transition over to the new OAuth authentication process.
#pragma warning disable 612,618
            if (method.StartsWith("flickr.auth", StringComparison.Ordinal) && !method.EndsWith("oauth.checkToken", StringComparison.Ordinal))
            {
                if (!string.IsNullOrEmpty(AuthToken))
                {
                    parameters["auth_token"] = AuthToken;
                }
            }
            else
            {
                // If OAuth Token exists or no authentication required then use new OAuth
                if (!string.IsNullOrEmpty(OAuthAccessToken) || string.IsNullOrEmpty(AuthToken))
                {
                    parameters.Remove("api_key");
                    OAuthGetBasicParameters(parameters);
                    if (!string.IsNullOrEmpty(OAuthAccessToken))
                    {
                        parameters["oauth_token"] = OAuthAccessToken;
                    }
                }
                else
                {
                    parameters["auth_token"] = AuthToken;
                }
            }
#pragma warning restore 612,618

            var url = CalculateUri(parameters, !string.IsNullOrEmpty(sharedSecret));

            lastRequest = url;

            string responseXml;

            if (InstanceCacheDisabled)
            {
                responseXml = FlickrResponder.GetDataResponse(this, BaseUri.AbsoluteUri, parameters);
            }
            else
            {
                var urlComplete = url;

                var cached = (ResponseCacheItem)Cache.Responses.Get(urlComplete, cacheTimeout, true);
                if (cached != null)
                {
                    Debug.WriteLine("Cache hit.");
                    responseXml = cached.Response;
                }
                else
                {
                    Debug.WriteLine("Cache miss.");
                    responseXml = FlickrResponder.GetDataResponse(this, BaseUri.AbsoluteUri, parameters);

                    var resCache = new ResponseCacheItem(new Uri(urlComplete), responseXml, DateTime.UtcNow);

                    Cache.Responses.Shrink(Math.Max(0, Cache.CacheSizeLimit - responseXml.Length));
                    Cache.Responses[urlComplete] = resCache;
                }
            }

            lastResponse = responseXml;

            var item = new T();
            item.Load(responseXml);

            return(item);
        }
        private void GetResponseAsync <T>(Dictionary <string, string> parameters, Action <FlickrResult <T> > callback) where T : IFlickrParsable, new()
        {
            CheckApiKey();

            parameters["api_key"] = ApiKey;

            if (!String.IsNullOrEmpty(OAuthAccessToken) || String.IsNullOrEmpty(AuthToken))
            {
                OAuthGetBasicParameters(parameters);
                parameters.Remove("api_key");
                if (!String.IsNullOrEmpty(OAuthAccessToken))
                {
                    parameters["oauth_token"] = OAuthAccessToken;
                }
            }
            else
            {
                parameters["auth_token"] = AuthToken;
            }

            Uri url;

            if (!String.IsNullOrEmpty(sharedSecret))
            {
                url = CalculateUri(parameters, true);
            }
            else
            {
                url = CalculateUri(parameters, false);
            }

            lastRequest = url.AbsoluteUri;

            try
            {
                FlickrResponder.GetDataResponseAsync(this, BaseUri.AbsoluteUri, parameters, (r)
                                                     =>
                {
                    FlickrResult <T> result = new FlickrResult <T>();
                    if (r.HasError)
                    {
                        result.Error = r.Error;
                    }
                    else
                    {
                        lastResponse = r.Result;

                        XmlReaderSettings settings = new XmlReaderSettings();
                        settings.IgnoreWhitespace  = true;
                        XmlReader reader           = XmlReader.Create(new StringReader(r.Result), settings);

                        if (!reader.ReadToDescendant("rsp"))
                        {
                            throw new XmlException("Unable to find response element 'rsp' in Flickr response");
                        }
                        while (reader.MoveToNextAttribute())
                        {
                            if (reader.LocalName == "stat" && reader.Value == "fail")
                            {
                                throw ExceptionHandler.CreateResponseException(reader);
                            }
                            continue;
                        }

                        reader.MoveToElement();
                        reader.Read();

                        T t = new T();
                        ((IFlickrParsable)t).Load(reader);
                        result.Result   = t;
                        result.HasError = false;
                    }

                    if (callback != null)
                    {
                        callback(result);
                    }
                });
            }
            catch (Exception ex)
            {
                FlickrResult <T> result = new FlickrResult <T>();
                result.Error = ex;
                if (null != callback)
                {
                    callback(result);
                }
            }
        }
        private void UploadDataAsync(Stream imageStream, string fileName, Uri uploadUri, Dictionary <string, string> parameters, Action <FlickrResult <string> > callback)
        {
            string boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);

            var dataBuffer = CreateUploadData(imageStream, fileName, parameters, boundary);

            var req = (HttpWebRequest)WebRequest.Create(uploadUri);

            req.Method      = "POST";
            req.ContentType = "multipart/form-data; boundary=" + boundary;
#if (!SILVERLIGHT && !WINDOWS_PHONE)
            req.SendChunked = true;
#endif
            req.AllowWriteStreamBuffering = false;

            if (!string.IsNullOrEmpty(authHeader))
            {
                req.Headers["Authorization"] = authHeader;
            }

            req.BeginGetRequestStream(
                r =>
            {
                var result = new FlickrResult <string>();

                using (var reqStream = req.EndGetRequestStream(r))
                {
                    try
                    {
                        var bufferSize = 32 * 1024;
                        if (dataBuffer.Length / 100 > bufferSize)
                        {
                            bufferSize = bufferSize * 2;
                        }
                        dataBuffer.UploadProgress += (o, e) =>
                        {
                            if (OnUploadProgress != null)
                            {
                                OnUploadProgress(this, e);
                            }
                        };
                        dataBuffer.CopyTo(reqStream, bufferSize);
                        reqStream.Close();
                    }
                    catch (Exception ex)
                    {
                        result.Error = ex;
                        callback(result);
                    }
                }

                req.BeginGetResponse(
                    r2 =>
                {
                    try
                    {
                        var res         = req.EndGetResponse(r2);
                        var sr          = new StreamReader(res.GetResponseStream());
                        var responseXml = sr.ReadToEnd();
                        sr.Close();

                        var t = new UnknownResponse();
                        ((IFlickrParsable)t).Load(responseXml);
                        result.Result   = t.GetElementValue("photoid");
                        result.HasError = false;
                    }
                    catch (Exception ex)
                    {
                        if (ex is WebException)
                        {
                            var oauthEx  = new OAuthException(ex);
                            result.Error = string.IsNullOrEmpty(oauthEx.Message) ? ex : oauthEx;
                        }
                        else
                        {
                            result.Error = ex;
                        }
                    }

                    callback(result);
                },
                    this);
            },
                this);
        }
Beispiel #22
0
        private void UploadDataAsync(Stream imageStream, string fileName, Uri uploadUri, Dictionary <string, string> parameters, Action <FlickrResult <string> > callback)
        {
            string boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string authHeader = FlickrResponder.OAuthCalculateAuthHeader(parameters);

            var dataBuffer = CreateUploadData(imageStream, fileName, parameters, boundary);

            var req = WebRequest.Create(uploadUri);

            req.Method      = "POST";
            req.ContentType = "multipart/form-data; boundary=" + boundary;
            if (!String.IsNullOrEmpty(authHeader))
            {
                req.Headers["Authorization"] = authHeader;
            }

            req.BeginGetRequestStream(
                r =>
            {
                using (var reqStream = req.EndGetRequestStream(r))
                {
                    var bufferSize = 32 * 1024;
                    if (dataBuffer.Length / 100 > bufferSize)
                    {
                        bufferSize = bufferSize * 2;
                    }
                    dataBuffer.UploadProgress += (o, e) => { if (OnUploadProgress != null)
                                                             {
                                                                 OnUploadProgress(this, e);
                                                             }
                    };
                    dataBuffer.CopyTo(reqStream, bufferSize);
                    reqStream.Close();
                }

                req.BeginGetResponse(
                    r2 =>
                {
                    var result = new FlickrResult <string>();

                    try
                    {
                        var res         = req.EndGetResponse(r2);
                        var sr          = new StreamReader(res.GetResponseStream());
                        var responseXml = sr.ReadToEnd();
                        sr.Close();

                        var settings = new XmlReaderSettings {
                            IgnoreWhitespace = true
                        };
                        var reader = XmlReader.Create(new StringReader(responseXml), settings);

                        if (!reader.ReadToDescendant("rsp"))
                        {
                            throw new XmlException("Unable to find response element 'rsp' in Flickr response");
                        }
                        while (reader.MoveToNextAttribute())
                        {
                            if (reader.LocalName == "stat" && reader.Value == "fail")
                            {
                                throw ExceptionHandler.CreateResponseException(reader);
                            }
                        }

                        reader.MoveToElement();
                        reader.Read();

                        var t = new UnknownResponse();
                        ((IFlickrParsable)t).Load(reader);
                        result.Result   = t.GetElementValue("photoid");
                        result.HasError = false;
                    }
                    catch (Exception ex)
                    {
                        if (ex is WebException)
                        {
                            var oauthEx  = new OAuthException(ex);
                            result.Error = String.IsNullOrEmpty(oauthEx.Message) ? ex : oauthEx;
                        }
                        else
                        {
                            result.Error = ex;
                        }
                    }

                    callback(result);
                },
                    this);
            },
                this);
        }
        private T GetResponse <T>(Dictionary <string, string> parameters, TimeSpan cacheTimeout) where T : IFlickrParsable, new()
        {
            // Flow for GetResponse.
            // 1. Check API Key
            // 2. Calculate Cache URL.
            // 3. Check Cache for URL.
            // 4. Get Response if not in cache.
            // 5. Write Cache.
            // 6. Parse Response.

            CheckApiKey();

            parameters["api_key"] = ApiKey;

            // If performing one of the old 'flickr.auth' methods then use old authentication details.
            var method = parameters["method"];

            // User of obsolete AuthToken property while we transition over to the new OAuth authentication process.
#pragma warning disable 612,618
            if (method.StartsWith("flickr.auth") && !method.EndsWith("oauth.checkToken"))
            {
                if (!String.IsNullOrEmpty(AuthToken))
                {
                    parameters["auth_token"] = AuthToken;
                }
            }
            else
            {
                // If OAuth Token exists or no authentication required then use new OAuth
                if (!String.IsNullOrEmpty(OAuthAccessToken) || String.IsNullOrEmpty(AuthToken))
                {
                    parameters.Remove("api_key");
                    OAuthGetBasicParameters(parameters);
                    if (!String.IsNullOrEmpty(OAuthAccessToken))
                    {
                        parameters["oauth_token"] = OAuthAccessToken;
                    }
                }
                else
                {
                    parameters["auth_token"] = AuthToken;
                }
            }
#pragma warning restore 612,618

            var url = CalculateUri(parameters, !String.IsNullOrEmpty(sharedSecret));

            lastRequest = url;

            string responseXml;

            if (InstanceCacheDisabled)
            {
                responseXml = FlickrResponder.GetDataResponse(this, BaseUri.AbsoluteUri, parameters);
            }
            else
            {
                var urlComplete = url;

                var cached = (ResponseCacheItem)Cache.Responses.Get(urlComplete, cacheTimeout, true);
                if (cached != null)
                {
                    Debug.WriteLine("Cache hit.");
                    responseXml = cached.Response;
                }
                else
                {
                    Debug.WriteLine("Cache miss.");
                    responseXml = FlickrResponder.GetDataResponse(this, BaseUri.AbsoluteUri, parameters);

                    var resCache = new ResponseCacheItem(new Uri(urlComplete), responseXml, DateTime.UtcNow);

                    Cache.Responses.Shrink(Math.Max(0, Cache.CacheSizeLimit - responseXml.Length));
                    Cache.Responses[urlComplete] = resCache;
                }
            }

            lastResponse = responseXml;

            //responseXml = responseXml.Trim();

            var reader = new XmlTextReader(new StringReader(responseXml))
            {
                WhitespaceHandling = WhitespaceHandling.None,
            };

            if (!reader.ReadToDescendant("rsp"))
            {
                throw new XmlException("Unable to find response element 'rsp' in Flickr response");
            }
            while (reader.MoveToNextAttribute())
            {
                if (reader.LocalName == "stat" && reader.Value == "fail")
                {
                    throw ExceptionHandler.CreateResponseException(reader);
                }
            }

            reader.MoveToElement();
            reader.Read();

            var item = new T();
            item.Load(reader);

            return(item);
        }
Beispiel #24
0
        private async Task <FlickrResult <T> > GetResponseAsync <T>(Dictionary <string, string> parameters) where T : IFlickrParsable, new()
        {
            var hashApiSig = CalculateAuthSignature(parameters);

            CheckApiKey();

            FlickrResult <T> result = new FlickrResult <T>();

            var parseResult = new Func <Uri, string, T>((uri, response) =>
            {
                lastResponse = response;

                XmlReaderSettings settings = new XmlReaderSettings();
                settings.IgnoreWhitespace  = true;
                XmlReader reader           = XmlReader.Create(new StringReader(response.Trim()), settings);

                if (!reader.ReadToDescendant("rsp"))
                {
                    throw new XmlException("Unable to find response element 'rsp' in Flickr response");
                }
                while (reader.MoveToNextAttribute())
                {
                    if (reader.LocalName == "stat" && reader.Value == "fail")
                    {
                        throw ExceptionHandler.CreateResponseException(reader);
                    }
                    continue;
                }

                reader.MoveToElement();
                reader.Read();

                T t = new T();
                ((IFlickrParsable)t).Load(reader);

                return(t);
            });



            parameters["api_key"] = ApiKey;

            if (!String.IsNullOrEmpty(OAuthAccessToken) || String.IsNullOrEmpty(AuthToken))
            {
                OAuthGetBasicParameters(parameters);
                parameters.Remove("api_key");
                if (!String.IsNullOrEmpty(OAuthAccessToken))
                {
                    parameters["oauth_token"] = OAuthAccessToken;
                }
            }
            else
            {
                parameters["auth_token"] = AuthToken;
            }

            Uri url;

            if (!String.IsNullOrEmpty(sharedSecret))
            {
                url = CalculateUri(parameters, true);
            }
            else
            {
                url = CalculateUri(parameters, false);
            }

            lastRequest = url.AbsoluteUri;

            //get cached result if its there
            var cachedResult = TryGetCacheCall(hashApiSig);

            if (!string.IsNullOrEmpty(cachedResult))
            {
                result.Result   = parseResult(url, cachedResult);
                result.HashCall = hashApiSig;
                result.HasError = false;
                return(result);
            }


            try
            {
                var r = await FlickrResponder.GetDataResponseAsync(this, hashApiSig, BaseUri.AbsoluteUri, parameters);

                if (r.HasError)
                {
                    result.Error = r.Error;
                }
                else
                {
                    //cache results
                    CacheCall(r.HashCall, r.Result);

                    result.Result   = parseResult(url, r.Result);
                    result.HashCall = r.HashCall;
                    result.HasError = false;
                }
            }
            catch (Exception ex)
            {
                result.Error = ex;
            }

            return(result);
        }