public static async Task<string> TagsAsync(string query, OAuthResponse oAuthResponse)
        {
            var tags = new InstaSharp.Endpoints.Tags(InstagramConfig, oAuthResponse);
            var searchResults = await tags.Recent(query);

            return SerializeResults(searchResults.Data);
        }
        public void Set(HttpContext context)
        {
            // check if we are authenticated already and for the auth object
            if (context.Session["InstaSharp.Authenticated"] != null) {
                isAuthenticated = false; // (bool)context.Session["InstaSharp.Authenticated"];

                if (isAuthenticated)
                {
                    oauthResponse = (OAuthResponse)context.Session["InstaSharp.AuthInfo"];

                    // if we are authenticated, then we need to check and see if there is a corresponding
                    // signalr clientid registered in the database
                }
            }

            // check the session for a config object
            if (context.Session["InstaSharp.Config"] == null)
            {
                // if we are not authenticated, create a config object
                var clientId = ConfigurationManager.AppSettings.Get("client_id");
                var clientSecret = ConfigurationManager.AppSettings.Get("client_secret");
                var redirectUri = ConfigurationManager.AppSettings.Get("redirect_uri");
                var realtimeUri = "";

                config = new InstaSharp.InstagramConfig(clientId, clientSecret, redirectUri, realtimeUri);

                context.Session.Add("InstaSharp.Config", config);
            }
            else {
                // just get it off the session and store it in the config variable
                config = (InstagramConfig)context.Session["InstaSharp.Config"];
            }
        }
Exemplo n.º 3
0
        public async Task <List <IComment> > GetComments(string mediaId)
        {
            InstaSharp.Models.Responses.CommentsResponse c = null;
            List <IComment> comments = null;

            InstaSharp.Models.Responses.OAuthResponse resp = GetOAuthResp();

            var commentEndPoint = new InstaSharp.Endpoints.Comments(_configService.GetMediaConfig, resp);

            c = await commentEndPoint.Get(mediaId);

            if (c != null && c.Data != null) // The Power of Null Check, it could be null if user does not enter valid id so this check allows this case to be successful response with items: null
            {
                int i = 0;
                foreach (var item in c.Data)
                {
                    comments = _mappers[MapperTypes.ListComments].Map <List <IComment> >(c.Data);
                    if (comments != null)
                    {
                        comments[i]      = _mappers[MapperTypes.Comment].Map <Comment>(item);
                        comments[i].From = _mappers[MapperTypes.UserInfo].Map <UserInfo>(item.From);
                    }
                    i++;
                }
            }
            return(comments);
        }
        public static async Task<string> SearchAsync(double latitude, double longitude, OAuthResponse oAuthResponse)
        {
            var media = new InstaSharp.Endpoints.Media(InstagramConfig, oAuthResponse);
            var searchResults = await media.Search(latitude, longitude, 5000);

            return SerializeResults(searchResults.Data);
        }
Exemplo n.º 5
0
        public async Task <IMediaCharacteristics> GetMedia(string mediaId)
        {
            IMediaCharacteristics media = null;

            InstaSharp.Models.Responses.OAuthResponse resp = GetOAuthResp();
            InstaSharp.Models.Responses.MediaResponse m    = null;
            var mEndPoint = new InstaSharp.Endpoints.Media(_configService.GetMediaConfig, resp);

            m = await mEndPoint.Get(mediaId);

            if (m != null && m.Data != null)
            {
                media = _mappers[MapperTypes.Media].Map <IMediaCharacteristics>(m.Data);
                #region Map Insta Media to Imedia
                if (m.Data.Attribution != null)
                {
                    media.Attribution = _mappers[MapperTypes.Attribution].Map <Attribution>(m.Data.Attribution);
                }

                media.Caption = _mappers[MapperTypes.Caption].Map <Caption>(m.Data.Caption);
                if (m.Data.Caption != null)
                {
                    media.Caption.From = _mappers[MapperTypes.UserInfo].Map <UserInfo>(m.Data.Caption.From);
                }
                media.Comments = _mappers[MapperTypes.Comments].Map <Domain.Media.Comments>(m.Data.Comments);

                media.Images                    = _mappers[MapperTypes.Image].Map <Domain.Media.Image>(m.Data.Images);
                media.Images.Thumbnail          = _mappers[MapperTypes.Resolution].Map <Domain.Media.Resolution>(m.Data.Images.Thumbnail);
                media.Images.LowResolution      = _mappers[MapperTypes.Resolution].Map <Domain.Media.Resolution>(m.Data.Images.LowResolution);
                media.Images.StandardResolution = _mappers[MapperTypes.Resolution].Map <Resolution>(m.Data.Images.StandardResolution);
                media.Likes = _mappers[MapperTypes.Likes].Map <Domain.Media.Likes>(m.Data.Likes);
                if (m.Data.Location != null)
                {
                    media.Location = _mappers[MapperTypes.Location].Map <Domain.Media.Location>(m.Data.Location);
                }

                media.User = _mappers[MapperTypes.UserInfo].Map <UserInfo>(m.Data.User);

                if (m.Data.GetType() == typeof(List <UserInPhoto>)) /// TODO Check if this works/necesssary
                {
                    foreach (var u in m.Data.UsersInPhoto)
                    {
                        media.UsersInPhoto.Add(_mappers[MapperTypes.UserInPhoto].Map <UserInPhoto>(u));
                    }
                }
                if (m.Data.Type == "video")
                {
                    media.Videos = _mappers[MapperTypes.Video].Map <Video>(m.Data.Videos);
                    media.Videos.LowResolution      = _mappers[MapperTypes.Resolution].Map <Resolution>(m.Data.Videos.LowResolution);
                    media.Videos.StandardResolution = _mappers[MapperTypes.Resolution].Map <Resolution>(m.Data.Videos.StandardResolution);
                }
                #endregion
            }
            return(media);
        }
Exemplo n.º 6
0
        private InstaSharp.Models.Responses.OAuthResponse GetOAuthResp()
        {
            InstaSharp.Models.Responses.OAuthResponse resp = new InstaSharp.Models.Responses.OAuthResponse();
            InstaSharp.Endpoints.Users user = new Users(_configService.GetMediaConfig);


            InstaSharp.Models.Responses.UserResponse a = await user.GetSelf();

            Task.WaitAll(user.GetSelf());
            resp.User = GetUser();

            resp.AccessToken = _configService.MediaToken();
            return(resp);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InstagramApi"/> class.
        /// </summary>
        /// <param name="endpoint">The endpoint.</param>
        /// <param name="instagramConfig">The instagram configuration.</param>
        /// <param name="oauthResponse">The oauth response.</param>
        protected InstagramApi(string endpoint, InstagramConfig instagramConfig, OAuthResponse oauthResponse)
        {
            InstagramConfig = instagramConfig;
            OAuthResponse = oauthResponse;

            var handler = new HttpClientHandler();
            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip |
                                                 DecompressionMethods.Deflate;
            }

            Client = new HttpClient(handler) { BaseAddress = new Uri(new Uri(InstagramConfig.ApiUri), endpoint) };
        }
Exemplo n.º 8
0
        public async Task <List <IMediaCharacteristics> > MyFeed()
        {
            List <IMediaCharacteristics> list = null;

            InstaSharp.Models.Responses.OAuthResponse resp = GetOAuthResp();

            Users usersEndPoint = new Users(_configService.GetMediaConfig, resp);

            var feed = await usersEndPoint.RecentSelf();

            var            key        = "instagram_" + feed.Data[0].Id;
            DateTimeOffset expiration = DateTimeOffset.Now.AddMinutes(20);

            if (!_cacheService.Contains(key))
            {
                if (feed != null && feed.Data != null)
                {
                    list = new List <IMediaCharacteristics>();
                    foreach (var item in feed.Data)
                    {
                        IMediaCharacteristics m = _mappers[MapperTypes.Media].Map <IMediaCharacteristics>(item);
                        m = IterateMedia(m, item);
                        list.Add(m);
                    }
                }

                if (key != null)
                {
                    _cacheService.Add(key, list, expiration);
                }

                return(list);
            }


            list = _cacheService.Get <List <IMediaCharacteristics> >(key);
            return(list);
        }
Exemplo n.º 9
0
        protected TestBase()
        {
            // test account client id
            Config = new InstagramConfig()
            {
                ClientId = "554dfe9286994bbe98417d8dc7b69a24"
            };

            ConfigWithSecret = new InstagramConfig()
            {
                ClientId = "554dfe9286994bbe98417d8dc7b69a24",
                CallbackUri = "https://instasharpapi.azurewebsites.net/Realtime/Callback",
                ClientSecret = "39de8776637b47d2829cd1a4708ae180"
            };


            // dummy account data. InstaSharpTest
            Auth = new OAuthResponse()
            {
                AccessToken = "1415228826.554dfe9.502432355f084ea581b679a2f94bb350",
                User = new Models.UserInfo { Id = 1415228826 }
            };
        }
Exemplo n.º 10
0
        public void InstaSharpGetTest()
        {
            UserInfo info = new UserInfo
            {
                Id = 1952620338,
                Username = "******"
            };

            OAuthResponse response = new OAuthResponse
            {
                AccessToken = ConfigurationManager.AppSettings["AccessToken"],
                User = info
            };

            InstagramConfig config = new InstagramConfig(ConfigurationManager.AppSettings["ClientId"], ConfigurationManager.AppSettings["ClientSecret"]);

            Users users = new Users(config, response);

            UsersResponse userResponse = users.Search("yoventura", 1).Result;

            int userId = userResponse.Data[0].Id;

            MediasResponse medias = users.Recent(userId.ToString(CultureInfo.InvariantCulture), Int64.MaxValue.ToString(), Int64.MinValue.ToString(), int.MaxValue, null, null).Result;
        }
Exemplo n.º 11
0
 /// <summary>
 /// Geographies Endpoints
 /// </summary>
 /// <param name="config">An instance of the InstagramConfig class.</param>
 /// <param name="auth">An instance of the OAuthResponse class.</param>
 public Geographies(InstagramConfig config, OAuthResponse auth = null)
     : base("geographies/", config, auth)
 {
 }
Exemplo n.º 12
0
 /// <summary>
 /// Comments Endpoints
 /// </summary>
 /// <param name="config">An instance of the InstagramConfig class.</param>
 /// <param name="authInfo">An instance of the AuthInfo class.</param>
 public Comments(InstagramConfig config, OAuthResponse authInfo)
     : base("media/", config, authInfo)
 {
 }
Exemplo n.º 13
0
 /// <summary>
 /// User Endpoints
 /// </summary>
 /// <param name="config">An instance of the InstagramConfiguration class</param>
 /// <param name="OAuthResponse">An instance of the AuthInfo class</param>
 public Users(InstagramConfig config, OAuthResponse OAuthResponse = null)
     : base("users/", config, OAuthResponse)
 {
 }
Exemplo n.º 14
0
 /// <summary>
 /// Relationships Endpoints
 /// </summary>
 /// <param name="config">An instance of the InstagramConfig class.</param>
 /// <param name="auth">An instance of the OAuthResponse class.</param>
 public Relationships(InstagramConfig config, OAuthResponse auth)
     : base("users/", config, auth)
 {
 }
Exemplo n.º 15
0
        public async Task ReadMedia(InstaConfig configData, int keywordIndex)
        {
            var clientId = configData.id;
            var clientSecret = configData.secret;

            InstagramConfig config = new InstagramConfig(clientId, clientSecret);

            OAuthResponse oauthResponse = new OAuthResponse();

            oauthResponse.Access_Token = configData.token;
            oauthResponse.User = new User() { FullName = "Dave Brown", Username = "******" };

            var tagEndpoint = new InstaSharp.Endpoints.Tags(config, oauthResponse);
            try
            {
                List<String> keywords = new List<string>() { "photoshoot", "fashion", "model", "modeling", "modelling", "models" };

                string currentKeyword = keywords[keywordIndex];

                SendToLoggerAndConsole("The keyword we're going to work through: " + currentKeyword + " For token: " + configData.token.ToString());
                MediasResponse recentMedia;
                try
                {
                    recentMedia = await tagEndpoint.Recent(currentKeyword);
                }
                catch (Exception ex)
                {
                    SendToLoggerAndConsole("There was a problem getting recent media.");
                    log.Error("Here's the exception", ex);
                    SendToLoggerAndConsole("Bailing out of this key: " + configData.token.ToString());
                    return;
                }

                var likesEndpoint = new InstaSharp.Endpoints.Likes(config, oauthResponse);
                var commentsEndpoint = new InstaSharp.Endpoints.Comments(config, oauthResponse);

                SendToLoggerAndConsole("We have " + recentMedia.Data.Count.ToString() + " images to work through");
                SendToLoggerAndConsole("Here's the amount of likes we have remaining: " + recentMedia.RateLimitRemaining.ToString() + " For token: " + configData.token.ToString());
                bool rateLimitExceeded = recentMedia.RateLimitRemaining < 4971;
                int badResponseCount = 1;
                foreach (var image in recentMedia.Data)
                {
                    if (!image.UserHasLiked.Value)
                    {
                        if (!rateLimitExceeded)
                        {
                            SendToLoggerAndConsole("About to start liking now picture id: " + image.Id);
                            try
                            {

                                var likeResponse = await likesEndpoint.Post(image.Id);
                                rateLimitExceeded = likeResponse.RateLimitRemaining < 4971;
                                SendToLoggerAndConsole("Like response: " + likeResponse.Meta.Code.ToString() + " For token: " + configData.token.ToString());
                                SendToLoggerAndConsole("You have : " + likeResponse.RateLimitRemaining.ToString() + " remaining on token: " + configData.token.ToString());
                                SendToLoggerAndConsole("You are working on keyword: " + currentKeyword);
                                SendToLoggerAndConsole("Currently on Index: " + configData.index.ToString());
                                if (likeResponse.Meta.Code != System.Net.HttpStatusCode.OK)
                                {
                                    SendToLoggerAndConsole("Because the like response was: " + likeResponse.Meta.Code.ToString() + " For token: " + configData.token.ToString());
                                    SendToLoggerAndConsole("We're going to wait: " + (30 * badResponseCount).ToString() + " minutes before we like another shot");
                                    await Task.Delay(new TimeSpan(0, 30 * badResponseCount, 0)).ConfigureAwait(continueOnCapturedContext: false);
                                    badResponseCount++;
                                }
                                else
                                {
                                    badResponseCount = 1;
                                    SendToLoggerAndConsole("Just liked " + image.Id + " For token: " + configData.token.ToString());
                                    await Task.Delay(new TimeSpan(0, 0, new Random(DateTime.Now.Millisecond).Next(200, 300))).ConfigureAwait(continueOnCapturedContext: false);
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
            catch
            {

            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Likes Endpoints
 /// </summary>
 /// <param name="config">An instance of the InstagramConfig class.</param>
 /// <param name="auth">An instance of the OAuthResponse class.</param>
 public Likes(InstagramConfig config, OAuthResponse auth)
     : base("media/", config, auth)
 {
 }
Exemplo n.º 17
0
 /// <summary>
 /// User Endpoints
 /// </summary>
 /// <param name="config">An instance of the InstagramConfiguration class</param>
 /// <param name="auth">An instance of the OAuthResponse class.</param>
 public Users(InstagramConfig config, OAuthResponse auth)
     : base("users/", config, auth)
 {
 }
Exemplo n.º 18
0
 public Media(InstagramConfig config, OAuthResponse oAuthResponse)
 {
     this.config = config;
     this.oAuthResponse = oAuthResponse;
 }
Exemplo n.º 19
0
 /// <summary>
 /// Locations Endpoints
 /// </summary>
 /// <param name="config">An instance of the InstaGram config class</param>
 /// <param name="auth">Optional: An instance of the AuthInfo class</param>
 public Locations(InstagramConfig config, OAuthResponse auth = null)
     : base("locations/", config, auth)
 {
 }
Exemplo n.º 20
0
        /// <summary>
        /// Tag Endpoints
        /// </summary>
        /// <param name="config">An instance of the InstagramConfig class</param>
        /// <param name="auth">An instance of the OAuthResponse class.</param>
        public Tags(InstagramConfig config, OAuthResponse auth) : base("tags/", config, auth)
        {

        }
Exemplo n.º 21
0
 /// <summary>
 /// Media Endpoints
 /// </summary>
 /// <param name="config">An instance of the InstagramConfig class.</param>
 /// <param name="auth">An instance of the AuthInfo class.</param>
 public Media(InstagramConfig config, OAuthResponse auth = null)
     : base("media/", config, auth)
 {
 }
Exemplo n.º 22
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Get the config used by InstaSharp
            InstagramConfig config = Dependencies.InstagramConfig;

            // Wire up Instagram authentication so that we can access the media published by a user.
            var options = new InstagramAuthenticationOptions()
            {
                ClientId = config.ClientId,
                ClientSecret = config.ClientSecret,
                Provider = new InstagramAuthenticationProvider
                {
                    OnAuthenticated = context =>
                    {
                        // Retrieve the OAuth access token to store for subsequent API calls
                        OAuthResponse response = new OAuthResponse
                        {
                            User = new UserInfo
                            {
                                Id = long.Parse(context.Id),
                                FullName = context.Name,
                                ProfilePicture = context.ProfilePicture,
                                Username = context.UserName,
                            },
                            AccessToken = context.AccessToken,
                        };

                        string userId = context.Id;
                        string accessToken = context.AccessToken;

                        // Store the token in memory so that we can use it for accessing media. In a real scenario
                        // this would be stored somewhere else.
                        Dependencies.Tokens[userId] = response;
                        return Task.FromResult(true);
                    }
                }
            };

            app.UseInstagramInAuthentication(options);
        }