public string TestAuth () {
        // Flickr downloader = new Flickr (this._apikey, this._email, this._password );
        uploader = new Flickr (_apikey, _sharedsecret);
        return uploader.AuthGetFrob ();
        // Looking to licenses
        try {
           Licenses licenses = uploader.PhotosLicensesGetInfo(); 
           //foreach (License license in licenses.LicenseCollection) {
           //    Console.WriteLine("License: {0} {1}", license.LicenseName, license.LicenseId);
           //}
        } catch( FlickrNet.FlickrException e ) {
			Console.WriteLine( e.Code + ": " + e.Verbose );
		}
        // Searching some photos with a license
        int licenseNumber = 5; // att-sa
        string text = "infinity";
        string[] tags = {"infinity", "love"};
        photoURL = "http://www.flickr.com/photo_zoom.gne?id=";        

        //for (int i=0; i < 2; i++) {
        //    searchPags (text, 10, 1);
        //    searchText (text);
        //    searchTextLicense (text, licenseNumber);
        //    searchTags (tags);
        //}
    }
Пример #2
0
 private void ConnectToFlickr()
 {
     this.flickrObj = new Flickr(this._apikey, this._secret);
       frob = this.flickrObj.AuthGetFrob();
       string url = this.flickrObj.AuthCalcUrl(frob, AuthLevel.Delete);
       System.Diagnostics.Process.Start(url);
 }
Пример #3
0
        public static void GetDataResponseAsync(Flickr flickr, string baseUrl, Dictionary<string, string> parameters, string url, Action<FlickrResult<string>> callback)
        {
            bool oAuth = parameters.ContainsKey("oauth_consumer_key");

            if (oAuth)
                GetDataResponseOAuthAsync(flickr, baseUrl, parameters, url, callback);
            else
                GetDataResponseNormalAsync(flickr, baseUrl, parameters, callback);
        }
Пример #4
0
        public void PhotosGetInfoWithPeople()
        {
            Flickr f       = TestData.GetInstance();
            string photoId = "3547137580"; // http://www.flickr.com/photos/samjudson/3547137580/in/photosof-samjudson/

            PhotoInfo info = f.PhotosGetInfo(photoId);

            Assert.IsNotNull(info);
            Assert.IsTrue(info.HasPeople, "HasPeople should be true.");
        }
Пример #5
0
        public void TagsGetMostFrequentlyUsedTest()
        {
            Flickr f = TestData.GetAuthInstance();

            var tags = f.TagsGetMostFrequentlyUsed();

            Assert.IsNotNull(tags);

            Assert.AreNotEqual(0, tags.Count);
        }
Пример #6
0
        public void PhotosGetInfoTestLocation()
        {
            string photoId = "4268756940";

            Flickr f = TestData.GetAuthInstance();

            PhotoInfo info = f.PhotosGetInfo(photoId);

            Assert.IsNotNull(info.Location);
        }
Пример #7
0
        private static void GetAuthToken(Flickr flickr)
        {
            OAuthAccessToken accessToken     = null;
            string           path            = ConfigurationManager.AppSettings["location"];
            string           accessTokenFile = Path.Combine(path, "access-token.json");

            if (File.Exists(accessTokenFile))
            {
                Console.WriteLine("Found access token in file.");
                string json = File.ReadAllText(accessTokenFile);
                accessToken                   = JsonConvert.DeserializeObject <OAuthAccessToken>(json);
                flickr.OAuthAccessToken       = accessToken.Token;
                flickr.OAuthAccessTokenSecret = accessToken.TokenSecret;
                Auth check = flickr.AuthOAuthCheckToken();
                if (check != null)
                {
                    return;
                }
                Console.WriteLine("Token didn't check out.");
            }


            var requestToken = flickr.OAuthGetRequestToken("oob");

            Console.WriteLine($"The request token was {requestToken.Token}");
            string url = $"https://www.flickr.com/services/oauth/authorize?oauth_token={requestToken.Token}";

            Console.WriteLine("About to direct you to " + url);
            Console.WriteLine("Once you have completed authentication with this application you can return here and continue.");
            Process.Start(url);
            Console.WriteLine("Paste the verifier when done:");
            while (accessToken == null)
            {
                Console.Write("Verifier> ");
                string verifier = Console.ReadLine();

                accessToken = flickr.OAuthGetAccessToken(requestToken, verifier);
                if (accessToken == null)
                {
                    Console.WriteLine("Could not get an access token with that verifier. Try again.");
                }
            }

            Console.WriteLine("Saving token to file for future reference.");
            string jsonOut = JsonConvert.SerializeObject(accessToken, Formatting.Indented);

            File.WriteAllText(accessTokenFile, jsonOut);

            Console.WriteLine("Access token details:");
            Console.WriteLine("    Token     : " + accessToken.Token);
            Console.WriteLine("    Secret    : " + accessToken.TokenSecret);
            Console.WriteLine("    Full Name : " + accessToken.FullName);
            Console.WriteLine("    UserId    : " + accessToken.UserId);
            Console.WriteLine("    User Name : " + accessToken.Username);
        }
        public async Task <string> GetLastUploadedPhotoUrl(string apiKey, string apiSecret, string userId, PhotoSize size = PhotoSize.Large)
        {
            if (apiKey == null)
            {
                throw new ArgumentNullException(nameof(apiKey));
            }
            if (apiSecret == null)
            {
                throw new ArgumentNullException(nameof(apiSecret));
            }
            if (userId == null)
            {
                throw new ArgumentNullException(nameof(userId));
            }

            var service = new Flickr(apiKey, apiSecret);

            var options = new PhotoSearchOptions(userId)
            {
                PerPage = 1,
                Extras  = PhotoSearchExtras.DateUploaded
            };

            _logger.LogDebug(() => $"Using Flickr user id: '{userId}'");
            _logger.Log($"Searching for latest photo ...");
            var photos = await service.PhotosSearchAsync(options);

            _logger.Log($"{photos.Count} photos found.");

            if (photos.Any())
            {
                var photo = photos[0];
                _logger.Log("Photo Id={0} Title=\"{1}\", Uploaded on {2}, URL={3}", photo.PhotoId, photo.Title,
                            photo.DateUploaded, photo.Medium640Url);

                switch (size)
                {
                case PhotoSize.Original:
                    return(photo.OriginalUrl);

                case PhotoSize.Medium:
                    return(photo.MediumUrl);

                case PhotoSize.Small:
                    return(photo.SmallUrl);

                default:
                    // you may not be able to access the original version of another user's photo
                    return(photo.LargeUrl);
                }
            }

            _logger.Log("No photos found.");
            return(null);
        }
Пример #9
0
        public FlickrAuthorizer(Flickr flickr)
        {
            InitializeComponent();
            this.flickr = flickr;
            Icon        = Properties.Resources.trayIcon_Icon;

            textBox.Text  = "This program requires your authorization before it can upload data to Flickr\r\n\r\n";
            textBox.Text += "Authorizing is a simple process which takes place in your web browser. ";
            textBox.Text += "When you are finished, return to this window to complete authorization\r\n\r\n";
            textBox.Text += "(You must be connected to the internet in order to authorize this program)";
        }
Пример #10
0
        public static void SetWallpaper(String assunto)
        {
            SmallBasicApplication.BeginProgram();



            SmallBasicProgram.foto = Flickr.GetRandomPicture(assunto);
            Desktop.SetWallPaper(SmallBasicProgram.foto);

            GraphicsWindow.ShowMessage("Papel de parede mudado para" + SmallBasicProgram.assunto, "OK");
        }
Пример #11
0
        public PhotoCollection GetData()
        {
            Flickr flickr = new Flickr("43299afdd8dd4f0d915c524507aff544", "d3793728e72cb582");
            //var options = new PhotoSearchOptions { Tags = "sunset", PerPage = 20, Page = 1 };
            var options = new PhotoSearchOptions {
                Tags = "sunset", Extras = PhotoSearchExtras.Large2048Url
            };
            PhotoCollection photos = flickr.PhotosSearch(options);

            return(photos);
        }
 public MainWindow()
 {
     InitializeComponent();
     flickr              = new Flickr("88d44f3a042188839bfb65a05cdd8f63");
     flickr.ApiSecret    = "8734fda1ef5162da";
     ItemList            = new List <Item>();
     ImgList.DataContext = this;
     ImgList.ItemsSource = ItemList;
     isConnected         = false;
     page = 1;
 }
Пример #13
0
        public void CheckRequestAuthenticationDoesNotThrowWhenAuthTokenPresent()
        {
            var f = new Flickr();

            f.ApiKey    = "X";
            f.ApiSecret = "Y";

            f.AuthToken = "Z";

            Assert.DoesNotThrow(f.CheckRequiresAuthentication);
        }
        public void ContactsGetPublicListTest()
        {
            Flickr f = TestData.GetInstance();

            ContactCollection contacts = f.ContactsGetPublicList(TestData.TestUserId);

            Assert.IsNotNull(contacts, "Contacts should not be null.");

            Assert.AreNotEqual(0, contacts.Total, "Total should not be zero.");
            Assert.AreNotEqual(0, contacts.PerPage, "PerPage should not be zero.");
        }
        private Flickr CreateNewFlickrClient(string apiKey, string apiSecret, string tokenFilePath)
        {
            var flickr     = new Flickr(apiKey, apiSecret);
            var accesToken = CreateNewAccessToken(flickr);

            flickr.OAuthAccessToken       = accesToken.Token;
            flickr.OAuthAccessTokenSecret = accesToken.TokenSecret;
            _fileService.Serialize(accesToken, tokenFilePath);
            _console.WriteLine($"* Access token saved in '{tokenFilePath}' file.");
            return(flickr);
        }
Пример #16
0
        public void PhotosGetInfoDataTakenGranularityTest()
        {
            string photoid = "4386780023";

            Flickr f = TestData.GetInstance();

            PhotoInfo info = f.PhotosGetInfo(photoid);

            Assert.AreEqual(new DateTime(2009, 1, 1), info.DateTaken);
            Assert.AreEqual(DateGranularity.Circa, info.DateTakenGranularity);
        }
Пример #17
0
        public static Flickr GetAuthInstance()
        {
            var f = new Flickr(ApiKey, SharedSecret)
            {
                InstanceCacheDisabled = true
            };

            f.OAuthAccessToken       = OAuthToken.Token;
            f.OAuthAccessTokenSecret = OAuthToken.TokenSecret;
            return(f);
        }
Пример #18
0
        public void Initialize(string mountPointId, string configurationXmlElement, IHostServices hostServices)
        {
            MountPointId            = mountPointId;
            HostServices            = hostServices;
            ConfigurationXmlElement = configurationXmlElement;

            // read ExtenalContentLibrary.xml for this mountpoint
            XElement config = XElement.Parse(configurationXmlElement);

            Flickr = new Flickr(config.Element(FlickrNs + "FlickrApiKey").Value, config.Element(FlickrNs + "FlickrNSID").Value);
        }
Пример #19
0
        public void PhotosetsGetPhotosOrignalTest()
        {
            Flickr f = TestData.GetAuthInstance();

            var photos = f.PhotosetsGetPhotos("72157623027759445", PhotoSearchExtras.AllUrls);

            foreach (var photo in photos)
            {
                Assert.IsNotNull(photo.OriginalUrl, "Original URL should not be null.");
            }
        }
Пример #20
0
        public void PhotosGetExifAsyncTest()
        {
            Flickr f = TestData.GetInstance();

            var w = new AsyncSubject <FlickrResult <ExifTagCollection> >();

            f.PhotosGetExifAsync(TestData.PhotoId, r => { w.OnNext(r); w.OnCompleted(); });
            var result = w.Next().First();

            Assert.IsFalse(result.HasError);
        }
Пример #21
0
        public PhotoCollection GetPhotoCollectionByName(string name)
        {
            FoundUser user = Flickr.PeopleFindByUserName(name);

            FlickrNet.PhotoSearchOptions options = new FlickrNet.PhotoSearchOptions();
            options.UserId  = user.UserId;
            options.PerPage = 20;
            options.Page    = 1;

            return(Flickr.PhotosSearch(options));
        }
Пример #22
0
        public static Flickr GetAuthInstance()
        {
            var f = new Flickr(ApiKey, SharedSecret);

            if (OAuthToken != null)
            {
                f.OAuthAccessToken       = OAuthToken.Token;
                f.OAuthAccessTokenSecret = OAuthToken.TokenSecret;
            }
            return(f);
        }
Пример #23
0
        public void GroupsGetInfoNoGroupIconTest()
        {
            string groupId = "562176@N20";
            Flickr f       = TestData.GetInstance();

            GroupFullInfo info = f.GroupsGetInfo(groupId);

            Assert.IsNotNull(info, "GroupFullInfo should not be null");
            Assert.AreEqual("0", info.IconServer, "Icon Server should be zero");
            Assert.AreEqual("https://www.flickr.com/images/buddyicon.jpg", info.GroupIconUrl);
        }
        public void PhotosGetContactsPublicPhotosUserIdTest()
        {
            Flickr f = TestData.GetInstance();

            string userId = TestData.TestUserId;

            var photos = f.PhotosGetContactsPublicPhotos(userId);

            Assert.IsNotNull(photos);
            Assert.AreNotEqual(0, photos.Count, "Should have returned more than 0 photos");
        }
Пример #25
0
        public void PhotosetsGetInfoAsyncTest()
        {
            Flickr f = Instance;

            var photoset = f.PhotosetsGetList(TestData.TestUserId).First();

            var w = new AsyncSubject <FlickrResult <Photoset> >();

            f.PhotosetsGetInfoAsync(photoset.PhotosetId, r => { w.OnNext(r); w.OnCompleted(); });
            var result = w.Next().First();
        }
Пример #26
0
        private static ExifTagCollection WriteExifData(Flickr flickr, Photo item)
        {
            var    exif         = flickr.PhotosGetExif(item.PhotoId);
            string path         = ConfigurationManager.AppSettings["location"];
            string metadataPath = Path.Combine(path, $"photos/{item.PhotoId}-exif.json");
            string json         = JsonConvert.SerializeObject(exif, Formatting.Indented);

            File.WriteAllText(metadataPath, json);

            return(exif);
        }
Пример #27
0
 public EventService(
     IEventbriteClient eventbriteClient,
     Flickr flickrClient,
     IConfiguration configuration,
     IEventRepository eventRepository)
 {
     _eventbriteClient = eventbriteClient;
     _flickrClient     = flickrClient;
     _configuration    = configuration;
     _eventRepository  = eventRepository;
 }
Пример #28
0
        public void PhotosGetUntaggedNoParamsTest()
        {
            Flickr f = TestData.GetAuthInstance();

            var photos = f.PhotosGetUntagged();

            Assert.IsNotNull(photos);
            Assert.AreNotEqual(0, photos.Count);

            var photo = photos.First();
        }
Пример #29
0
        protected void AuthenticateButton_Click(object sender, EventArgs e)
        {
            Flickr            f     = FlickrManager.GetInstance();
            OAuthRequestToken token = f.OAuthGetRequestToken(Request.Url.AbsoluteUri);

            Session["RequestToken"] = token;

            string url = f.OAuthCalculateAuthorizationUrl(token.Token, AuthLevel.Read);

            Response.Redirect(url);
        }
        public void PhotosGetContactsPublicPhotosUserIdExtrasTest()
        {
            Flickr f = Instance;

            string            userId = TestData.TestUserId;
            PhotoSearchExtras extras = PhotoSearchExtras.All;
            var photos = f.PhotosGetContactsPublicPhotos(userId, extras);

            Assert.IsNotNull(photos);
            Assert.AreNotEqual(0, photos.Count, "Should have returned more than 0 photos");
        }
Пример #31
0
        public void PhotosSearchSignedTest()
        {
            Flickr             f = TestData.GetSignedInstance();
            PhotoSearchOptions o = new PhotoSearchOptions();

            o.Tags    = "Test";
            o.PerPage = 5;
            PhotoCollection photos = f.PhotosSearch(o);

            Assert.AreEqual(5, photos.PerPage, "PerPage should equal 5.");
        }
	public FlickrRemote (string token, Service service)
	{
		if (token == null || token.Length == 0) {
			this.flickr = new Flickr (service.ApiKey, service.Secret);
			this.token = null;
		} else {
			this.flickr = new Flickr (service.ApiKey, service.Secret, token);
			this.token = token;
		}

		this.flickr.CurrentService = service.Id;
	}
Пример #33
0
        public void GroupsBrowseBasicTest()
        {
            Flickr        f   = TestData.GetAuthInstance();
            GroupCategory cat = f.GroupsBrowse();

            Assert.IsNotNull(cat, "GroupCategory should not be null.");
            Assert.AreEqual("/", cat.CategoryName, "CategoryName should be '/'.");
            Assert.AreEqual("/", cat.Path, "Path should be '/'.");
            Assert.AreEqual("", cat.PathIds, "PathIds should be empty string.");
            Assert.AreEqual(0, cat.Subcategories.Count, "No sub categories should be returned.");
            Assert.AreEqual(0, cat.Groups.Count, "No groups should be returned.");
        }
Пример #34
0
        private void btnAuth_Click(object sender, EventArgs e)
        {
            Flickr flickr = FlickrManager.GetInstance();

            // what's "oob" ?
            // I have tried "flickr-up", then error. hmm...
            RequestToken = flickr.OAuthGetRequestToken("oob");

            String uri = flickr.OAuthCalculateAuthorizationUrl(RequestToken.Token, AuthLevel.Write);

            System.Diagnostics.Process.Start(uri);
        }
        /// <summary>
        /// Gets a data response for the given base url and parameters, 
        /// either using OAuth or not depending on which parameters were passed in.
        /// </summary>
        /// <param name="flickr">The current instance of the <see cref="Flickr"/> class.</param>
        /// <param name="baseUrl">The base url to be called.</param>
        /// <param name="parameters">A dictionary of parameters.</param>
        /// <returns></returns>
        public static string GetDataResponse(Flickr flickr, string baseUrl, IDictionary<string, string> parameters)
        {
            const string method = "POST";

            // Remove api key if it exists.
            if (parameters.ContainsKey("api_key")) parameters.Remove("api_key");
            if (parameters.ContainsKey("api_sig")) parameters.Remove("api_sig");

            // If OAuth Access Token is set then add token and generate signature.
            if (!String.IsNullOrEmpty(flickr.OAuthAccessToken) && !parameters.ContainsKey("oauth_token"))
            {
                OAuthGetBasicParameters(parameters);
                parameters.Add("oauth_token", flickr.OAuthAccessToken);
            }
            if (!String.IsNullOrEmpty(flickr.OAuthAccessTokenSecret) && !parameters.ContainsKey("oauth_signature"))
            {
                var sig = flickr.OAuthCalculateSignature(method, baseUrl, parameters, flickr.OAuthAccessTokenSecret);
                parameters.Add("oauth_signature", sig);
            }

            // Calculate post data, content header and auth header
            string data = OAuthCalculatePostData(parameters);
            string authHeader = OAuthCalculateAuthHeader(parameters);

            flickr.LastRequest = baseUrl + "?" + data;

            // Download data.
            try
            {
                return DownloadData(method, baseUrl, data, PostContentType, authHeader);
            }
            catch (WebException ex)
            {
                if (ex.Status != WebExceptionStatus.ProtocolError) throw;

                var response = ex.Response as HttpWebResponse;
                if (response == null) throw;

                if (response.StatusCode != HttpStatusCode.BadRequest &&
                    response.StatusCode != HttpStatusCode.Unauthorized) throw;

                using (var responseReader = new StreamReader(response.GetResponseStream()))
                {
                    string responseData = responseReader.ReadToEnd();
                    responseReader.Close();

                    Debug.WriteLine("OAuth response = " + responseData);

                    throw new OAuthException(responseData, ex);
                }
            }
        }
        public static async Task<string> GetDataResponseAsync(Flickr flickr, string baseUrl, IDictionary<string, string> parameters)
        {
            const string method = "POST";

            // Remove api key if it exists.
            if (parameters.ContainsKey("api_key")) parameters.Remove("api_key");
            if (parameters.ContainsKey("api_sig")) parameters.Remove("api_sig");

            if (!parameters.ContainsKey("oauth_consumer_key"))
                parameters.Add("oauth_consumer_key", flickr.ApiKey);

            // If OAuth Access Token is set then add token and generate signature.
            if (!String.IsNullOrEmpty(flickr.OAuthAccessToken) && !parameters.ContainsKey("oauth_token"))
            {
                OAuthGetBasicParameters(parameters);
                parameters.Add("oauth_token", flickr.OAuthAccessToken);
            }
            if (!String.IsNullOrEmpty(flickr.OAuthAccessTokenSecret) && !parameters.ContainsKey("oauth_signature"))
            {
                var sig = flickr.OAuthCalculateSignature(method, baseUrl, parameters, flickr.OAuthAccessTokenSecret);
                parameters.Add("oauth_signature", sig);
            }

            // Calculate post data, content header and auth header
            var data = OAuthCalculatePostData(parameters);
            var authHeader = OAuthCalculateAuthHeader(parameters);

            // Download data.
            try
            {
                return await DownloadDataAsync(method, baseUrl, data, PostContentType, authHeader);
            }
            catch (WebException ex)
            {
                var response = ex.Response as HttpWebResponse;
                if (response == null) throw;

                if (response.StatusCode != HttpStatusCode.BadRequest &&
                    response.StatusCode != HttpStatusCode.Unauthorized) throw;

                var stream = response.GetResponseStream();
                if (stream == null) throw;

                using (var responseReader = new StreamReader(stream))
                {
                    var responseData = responseReader.ReadToEnd();
                    throw new OAuthException(responseData, ex);
                }
            }
        }
Пример #37
0
    public void AttemptConnection()
    {
        string token = PersistentInformation.GetInstance().Token;
          try {
            flickrObj = new Flickr(_apikey, _secret, token);
            flickrObj.TestLogin();
        _isConnected = true;
          } catch (FlickrNet.FlickrApiException e) {
            PrintException(e);
            _isConnected = false;
            return;
          }

          Gtk.Application.Invoke (delegate {
        if (_isConnected) {
          DeskFlickrUI.GetInstance().SetStatusLabel("Login Successful.");
        } else {
          DeskFlickrUI.GetInstance().SetStatusLabel("Unable to connect.");
        }
          });
          UpdateUIAboutConnection();
    }
Пример #38
0
		private Facts PrepareFacts( Flickr.Photo[] photos, string uriFormat )
		{
			Facts facts = new Facts();

			foreach ( Flickr.Photo photo in photos )
			{
				if ( !string.IsNullOrEmpty( photo.Title )
					&& !string.IsNullOrEmpty( photo.OwnerName ) )
				{
					string title = photo.Title;
					string owner = photo.OwnerName[ 0 ].ToString();
					DateTime date = new DateTime( photo.DateTaken.Year, 1, 1 );

					Facts.WhatRow what = facts.What.FindByID( title );
					Facts.WhereRow where = facts.Where.FindByID( owner );
					Facts.WhenRow when = facts.When.FindByID( date );

					if ( ( what != null || facts.What.Count < maxSize )
						&& ( where != null || facts.Where.Count < maxSize )
						&& ( when != null || facts.When.Count < maxSize ) )
					{
						if ( what == null ) what = facts.What.AddWhatRow( title );
						if ( where == null ) where = facts.Where.AddWhereRow( owner );
						if ( when == null ) when = facts.When.AddWhenRow( date );

						string uri = string.Format( uriFormat,
							Uri.EscapeDataString( Convert.ToBase64String( Encoding.UTF8.GetBytes( photo.ThumbnailUrl ) ) ) );

						if ( facts.Fact.FindByWhatWhereWhen( what.ID, where.ID, when.ID ) == null )
						{
							facts.Fact.AddFactRow( what, where, when, uri );
						}
					}
				}
			}

			return facts;
		}
 /// <summary>
 /// Gets a data response for the given base url and parameters, 
 /// either using OAuth or not depending on which parameters were passed in.
 /// </summary>
 /// <param name="flickr">The current instance of the <see cref="Flickr"/> class.</param>
 /// <param name="baseUrl">The base url to be called.</param>
 /// <param name="parameters">A dictionary of parameters.</param>
 /// <param name="callback"></param>
 /// <returns></returns>
 public static void GetDataResponseAsync(Flickr flickr, string baseUrl, Dictionary<string, string> parameters,
                                         Action<FlickrResult<string>> callback)
 {
     GetDataResponseOAuthAsync(flickr, baseUrl, parameters, callback);
 }
Пример #40
0
        private static void GetDataResponseNormalAsync(Flickr flickr, string baseUrl, Dictionary<string, string> parameters, Action<FlickrResult<string>> callback)
        {
            var method = flickr.CurrentService == SupportedService.Zooomr ? "GET" : "POST";

            var data = string.Empty;

            foreach (var k in parameters)
            {
                data += k.Key + "=" + UtilityMethods.EscapeDataString(k.Value) + "&";
            }

            if (method == "GET" && data.Length > 2000) method = "POST";

            if (method == "GET")
                DownloadDataAsync(method, baseUrl + "?" + data, null, null, null, callback);
            else
                DownloadDataAsync(method, baseUrl, data, PostContentType, null, callback);
        }
Пример #41
0
        private static void GetDataResponseOAuthAsync(Flickr flickr, string baseUrl, Dictionary<string, string> parameters, string url, Action<FlickrResult<string>> callback)
        {
            const string method = "";

            // Remove api key if it exists.
            if (parameters.ContainsKey("api_key")) parameters.Remove("api_key");
            if (parameters.ContainsKey("api_sig")) parameters.Remove("api_sig");

            // If OAuth Access Token is set then add token and generate signature.
            if (!string.IsNullOrEmpty(flickr.OAuthAccessToken) && !parameters.ContainsKey("oauth_token"))
            {
                parameters.Add("oauth_token", flickr.OAuthAccessToken);
            }
            if (!string.IsNullOrEmpty(flickr.OAuthAccessTokenSecret) && !parameters.ContainsKey("oauth_signature"))
            {
                string sig = flickr.OAuthCalculateSignature(method, baseUrl, parameters, flickr.OAuthAccessTokenSecret);
                parameters.Add("oauth_signature", sig);
            }

            // Calculate post data, content header and auth header
            string data = OAuthCalculatePostData(parameters);
            string authHeader = OAuthCalculateAuthHeader(parameters);

            // Download data.
            try
            {
                DownloadDataAsync(method, baseUrl, data, PostContentType, authHeader, url, callback);
            }
            catch (WebException ex)
            {
                var response = ex.Response as HttpWebResponse;
                if (response == null) throw;

                if (response.StatusCode != HttpStatusCode.BadRequest && response.StatusCode != HttpStatusCode.Unauthorized) throw;

                using (var responseReader = new StreamReader(response.GetResponseStream()))
                {
                    string responseData = responseReader.ReadToEnd();
                    throw new OAuthException(responseData, ex);
                }
            }
        }