Esempio n. 1
0
        public InstagramBot()
        {
            dynamic credentialJson = JsonConvert.DeserializeObject(File.ReadAllText("Credentials.json"));

            _userSessionData = new UserSessionData
            {
                UserName = credentialJson["INSTAGRAM_USER"],
                Password = credentialJson["INSTAGRAM_PASSWORD"]
            };

            var delay = RequestDelay.FromSeconds(2, 2);

            _instaApi = InstaApiBuilder.CreateBuilder()
                        .SetUser(_userSessionData)
                        .UseLogger(new DebugLogger(LogLevel.Exceptions))
                        .SetRequestDelay(delay)
                        .Build();

            try
            {
                if (File.Exists(stateFile))
                {
                    using (var fs = File.OpenRead(stateFile))
                    {
                        _instaApi.LoadStateDataFromStream(fs);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 2
0
        private static async Task <bool> IsUserSessionStored()
        {
            try
            {
                if (InstaApi != null)
                {
                    InstaApi = null;
                    return(false);
                }
                var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("UserSession.dat", CreationCollisionOption.OpenIfExists);

                var r = await FileIO.ReadTextAsync(file);

                string User = "******"; string Pass = "******";
                //LoadUserInfo(out User, out Pass);
                //if (User == null || Pass == null) return false;
                InstaApi = InstaApiBuilder.CreateBuilder()
                           .SetUser(new UserSessionData {
                    UserName = User, Password = Pass
                })
                           .UseLogger(new DebugLogger(LogLevel.Exceptions))
                           .Build();
                InstaApi.LoadStateDataFromStream(r);
                if (!InstaApi.IsUserAuthenticated)
                {
                    await InstaApi.LoginAsync();
                }
                return(true);
            }
            catch (Exception ex)
            {
                InstaApi = null;
                return(false);
            }
        }
Esempio n. 3
0
        public static async Task <bool> Initialization(Stream data, string uname = "Queen", string pword = "Saigon")
        {
            Err      = "";
            InstaApi = InstaSharper.API.Builder.InstaApiBuilder.CreateBuilder()
                       .SetUser(new UserSessionData()
            {
                UserName = uname, Password = pword
            })
                       .SetRequestDelay(RequestDelay.FromSeconds(1, 2))
                       .Build();
            InstaApi.LoadStateDataFromStream(data);
            if (InstaApi.IsUserAuthenticated)
            {
                var Result = await InstaApi.GetCurrentUserAsync();

                if (Result.Succeeded)
                {
                    Initialized = true;
                    Userid      = Result.Value.Pk;
                    Username    = Result.Value.UserName;

                    return(true);
                }
                else
                {
                    Err = "خطا در تایید هویت حساب لطفا دوباره سعی کنید یا دوباره وارد شوید";
                    return(false);
                }
            }
            else
            {
                Err = "خطا در تایید هویت حساب لطفا دوباره سعی کنید یا دوباره وارد شوید";
                return(false);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Вход в аккаунт
        /// </summary>
        /// <returns></returns>
        public async Task SignIn()
        {
            var delay       = RequestDelay.FromSeconds(2, 2);
            var relatedPath = Environment.CurrentDirectory + PathContract.pathAccount + userSession.UserName + PathContract.stateFile;

            try
            {
                if (File.Exists(relatedPath))
                {
                    Console.WriteLine("Loading state from file");
                    using (var fs = File.OpenRead(relatedPath))
                    {
                        InstaApi.LoadStateDataFromStream(fs);
                    }
                }
                else
                {
                    var currentUser = await InstaApi.LoginAsync();

                    if (currentUser.Succeeded)
                    {
                        SaveSession();
                    }
                    else
                    {
                        await GetChallenge();

                        SaveSession();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            LoadSession();
            if (!InstaApi.IsUserAuthenticated)
            {
                var currentUser = await InstaApi.LoginAsync();

                if (currentUser.Succeeded)
                {
                    SaveSession();
                }
                else
                {
                    await GetChallenge();

                    SaveSession();
                    LoadSession();
                }
            }
            else
            {
                Console.WriteLine("Session loaded!");
            }
        }
Esempio n. 5
0
        private async void LoginButton_Click(object sender, EventArgs e)
        {
            Size = NormalSize;
            var userSession = new UserSessionData
            {
                UserName = txtUsername.Text,
                Password = txtPassword.Text
            };

            InstaApi = InstaApiBuilder.CreateBuilder()
                       .SetUser(userSession)
                       .UseLogger(new DebugLogger(LogLevel.Exceptions))
                       .SetRequestDelay(RequestDelay.FromSeconds(0, 1))
                       .Build();
            Text = $"{AppName} Connecting";
            try
            {
                if (File.Exists(StateFile))
                {
                    Debug.WriteLine("Loading state from file");
                    using (var fs = File.OpenRead(StateFile))
                    {
                        InstaApi.LoadStateDataFromStream(fs);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            if (!InstaApi.IsUserAuthenticated)
            {
                var logInResult = await InstaApi.LoginAsync();

                Debug.WriteLine(logInResult.Value);
                if (logInResult.Succeeded)
                {
                    Text = $"{AppName} Connected";
                    // Save session
                    SaveSession();
                }
                else
                {
                    // two factor is required
                    if (logInResult.Value == InstaLoginResult.TwoFactorRequired)
                    {
                        // open a box so user can send two factor code
                        Size = TwoFactorSize;
                    }
                }
            }
            else
            {
                Text = $"{AppName} Connected";
            }
        }
Esempio n. 6
0
        //登录账号
        public static async System.Threading.Tasks.Task InsLoginAsync()
        {
            #region 登录Ins
            Console.WriteLine("登录Ins...");
            var userSession = new UserSessionData
            {
                UserName = "******",
                Password = "******"
            };

            var delay = RequestDelay.FromSeconds(2, 2);
            InstaApi = InstaApiBuilder.CreateBuilder()
                       .SetUser(userSession)
                       .UseLogger(new DebugLogger(LogLevel.All))
                       .SetRequestDelay(delay)
                       .Build();
            const string stateFile = "state.bin";
            try
            {
                if (System.IO.File.Exists(stateFile))
                {
                    Console.WriteLine("从文件加载登录.");
                    using (var fs = System.IO.File.OpenRead(stateFile))
                    {
                        InstaApi.LoadStateDataFromStream(fs);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            if (!InstaApi.IsUserAuthenticated)
            {
                // login
                Console.WriteLine($"Logging in as {userSession.UserName}");
                delay.Disable();
                var logInResult = await InstaApi.LoginAsync();

                delay.Enable();
                if (!logInResult.Succeeded)
                {
                    Console.WriteLine($"Unable to login: {logInResult.Info.Message}");
                }
            }
            var state = InstaApi.GetStateDataAsStream();
            using (var fileStream = System.IO.File.Create(stateFile))
            {
                state.Seek(0, SeekOrigin.Begin);
                state.CopyTo(fileStream);
            }
            Console.WriteLine("已登录");
            #endregion
        }
 private static void loadSessionData(IInstaApi api)
 {
     try
     {
         if (!File.Exists(stateFile))
         {
             return;
         }
         using var fs = File.OpenRead(stateFile);
         api.LoadStateDataFromStream(fs);
     }
     catch
     {
         //don't want to crash here
     }
 }
Esempio n. 8
0
 void LoadSession()
 {
     try
     {
         if (File.Exists(StateFile))
         {
             Debug.WriteLine("Loading state from file");
             using (var fs = File.OpenRead(StateFile))
             {
                 InstaApi.LoadStateDataFromStream(fs);
             }
         }
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex);
     }
 }
Esempio n. 9
0
        private void LoadSavedSession()
        {
            const string stateFile = "state.bin";

            try
            {
                loginProcessLbl.Text = "Loading previous session.";
                using (var fs = File.OpenRead(stateFile))
                {
                    _instaApiInstance = User.SessionApiBuilder();
                    _instaApiInstance.LoadStateDataFromStream(fs);
                }
            }

            catch (Exception e)
            {
                MessageBox.Show("Error: " + e.Message);
            }
        }
Esempio n. 10
0
        private void LoadState()
        {
            const string stateFile = "state.bin";

            try
            {
                if (File.Exists(stateFile))
                {
                    Console.WriteLine("Loading state from file");
                    using (var fs = File.OpenRead(stateFile))
                    {
                        _instaApi.LoadStateDataFromStream(fs);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
 private bool LoadSession()
 {
     try
     {
         string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), StateFile);
         if (File.Exists(fileName))
         {
             using (var fs = File.OpenRead(fileName))
             {
                 InstaApi.LoadStateDataFromStream(fs);
                 //DisplayAlert("Info", "State file found", "Ok");
                 return(true);
             }
         }
         //DisplayAlert("Info", "State file not found", "Ok");
         return(false);
     }
     catch (Exception ex)
     {
         DisplayAlert("Info", ex.ToString(), "Ok");
         return(false);
     }
 }
Esempio n. 12
0
        /// <summary>
        /// Вход в аккаунт
        /// </summary>
        /// <returns></returns>
        public async Task SignIn()
        {
            var delay       = RequestDelay.FromSeconds(2, 2);
            var relatedPath = Environment.CurrentDirectory + PathContract.pathAccount + userSession.UserName + PathContract.stateFile;

            try
            {
                if (File.Exists(relatedPath))
                {
                    Console.WriteLine("Loading state from file");
                    using (var fs = File.OpenRead(relatedPath))
                    {
                        InstaApi.LoadStateDataFromStream(fs);
                    }
                }
                else
                {
                    var currentUser = await InstaApi.LoginAsync();

                    if (currentUser.Succeeded)
                    {
                        SaveSession();
                    }
                    else
                    {
                        ExceptionUtils.SetState(Error.E_ACC_SIGNIN, ErrorsContract.ACC_SIGNIN);
                        await GetChallenge();

                        ExceptionUtils.Throw(Error.E_ACC_SIGNIN, ErrorsContract.ACC_SIGNIN);
                        //throw new BaseException(ErrorsContract.ACC_SIGNIN);
                    }
                }
            }
            catch (Exception ex)
            {
                var currentUser = await InstaApi.LoginAsync();

                if (!currentUser.Succeeded)
                {
                    Console.WriteLine(ex.Message);
                    ExceptionUtils.Throw(Error.E_ACC_SIGNIN, ErrorsContract.ACC_SIGNIN);
                }
                ExceptionUtils.SetState(Error.S_OK);
                SaveSession();
            }
            if (File.Exists(relatedPath))
            {
                LoadSession();
                if (!InstaApi.IsUserAuthenticated)
                {
                    var currentUser = await InstaApi.LoginAsync();

                    if (currentUser.Succeeded)
                    {
                        SaveSession();
                    }
                    else
                    {
                        await GetChallenge();

                        SaveSession();
                        LoadSession();
                        ExceptionUtils.SetState(Error.E_ACC_SIGNIN);
                    }
                }
                else
                {
                    ExceptionUtils.SetState(Error.S_OK);
                    Console.WriteLine("Session loaded!");
                }
            }
        }
Esempio n. 13
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral_ = taskInstance.GetDeferral();
            Debug.WriteLine("NotifyTask started");
            try
            {
                var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("UserSession.dat", CreationCollisionOption.OpenIfExists);

                var r = await FileIO.ReadTextAsync(file);

                if (string.IsNullOrEmpty(r))
                {
                    return;
                }
                if (r.Length < 100)
                {
                    return;
                }
                string User = "******"; string Pass = "******";
                InstaApi = InstaApiBuilder.CreateBuilder()
                           .SetUser(new UserSessionData {
                    UserName = User, Password = Pass
                })
                           .UseLogger(new DebugLogger(LogLevel.Exceptions))
                           .Build();
                InstaApi.LoadStateDataFromStream(r);
                if (!InstaApi.IsUserAuthenticated)
                {
                    await InstaApi.LoginAsync();
                }
                if (!InstaApi.IsUserAuthenticated)
                {
                    return;
                }
                var activities = await InstaApi.GetRecentActivityAsync(PaginationParameters.MaxPagesToLoad(1));

                Notifies = await Load();

                if (Notifies == null)
                {
                    Notifies = new NotifyList();
                }
                if (activities.Succeeded)
                {
                    const int MAX = 9;
                    int       ix  = 0;
                    foreach (var item in activities.Value.Items)
                    {
                        var text = item.Text;
                        if (item.Text.Contains(" "))
                        {
                            text = text.Substring(text.IndexOf(" ") + 1);
                            text = text.TrimStart();
                        }
                        if (!Notifies.IsExists(text))
                        {
                            try
                            {
                                var n = new NotifyClass
                                {
                                    IsShowing      = false,
                                    ProfileId      = item.ProfileId,
                                    ProfilePicture = item.ProfileImage,
                                    Text           = text,
                                    TimeStamp      = item.TimeStamp.ToString(),
                                    Type           = item.Type,
                                };

                                if (item.InlineFollow == null)
                                {
                                    var user = await InstaApi.GetUserInfoByIdAsync(item.ProfileId);

                                    if (user.Succeeded)
                                    {
                                        n.Username = user.Value.Username;
                                    }
                                }
                                else
                                {
                                    n.Username       = item.InlineFollow.User.UserName;
                                    n.IsFollowingYou = item.InlineFollow.IsFollowing;
                                }
                                Notifies.Add(n);
                            }
                            catch { }
                        }
                        ix++;
                        if (ix > MAX)
                        {
                            break;
                        }
                    }
                    var list = Notifies;
                    list.Reverse();
                    for (int i = 0; i < list.Count; i++)
                    {
                        var item = list[i];
                        if (!string.IsNullOrEmpty(item.Username))
                        {
                            if (!item.IsShowing)
                            {
                                NotifyHelper.CreateNotifyAction($"@{item.Username}",
                                                                item.Text,
                                                                item.ProfilePicture);
                                Notifies[i].IsShowing = true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Notify ex: " + ex.Message);
                Debug.WriteLine("Source: " + ex.Source);
                Debug.WriteLine("StackTrace: " + ex.StackTrace);
            }
            await Save();

            await Task.Delay(1000);

            deferral_.Complete();
        }
Esempio n. 14
0
        /// <summary>
        /// Main form load method - loads the settings from a file.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void frmMain_Load(object sender, EventArgs e)
        {
            Log(@"Successfully initialized form components and loaded software.", nameof(LogType.Success));
            try
            {
                Log(@"Attempting to load application settings...", nameof(LogType.Info));

                var settings = SettingsSerialization.Load();

                txtUserAgent.Text                = !String.IsNullOrEmpty(settings.UserAgent) ? settings.UserAgent : UserAgentGenerator.Generate();
                txtRequestTimeout.Text           = !String.IsNullOrEmpty(settings.RequestTimeout) ? settings.RequestTimeout : "150";
                txtThreads.Text                  = !String.IsNullOrEmpty(settings.Threads) ? settings.Threads : "1";
                txtProxy.Text                    = settings.Proxy;
                txtDownloadFolder.Text           = !String.IsNullOrEmpty(settings.DownloadFolder) ? settings.DownloadFolder : Application.StartupPath;
                cbCreateNewFolder.Checked        = settings.CreateNewFolder;
                cbSaveStats.Checked              = settings.SaveStats;
                txtDelimiter.Text                = settings.Delimiter;
                cbSkipMediaDescription.Checked   = settings.SkipDescription;
                cbSkipPhotos.Checked             = settings.SkipPhotos;
                cbSkipVideos.Checked             = settings.SkipVideos;
                cbSkipMediaLikes.Checked         = settings.SkipLikes;
                cbSkipMediaLikesMoreLess.Text    = settings.SkipLikesMoreLess;
                txtSkipMediaLikesCount.Text      = settings.SkipLikesCount;
                cbSkipMediaComments.Checked      = settings.SkipComments;
                cbSkipMediaCommentsMoreLess.Text = settings.SkipCommentsMoreLess;
                txtSkipMediaCommentsCount.Text   = settings.SkipCommentsCount;
                cbSkipMediaUploadDate.Checked    = settings.SkipUploadDate;
                cbTotalDownloads.Checked         = settings.TotalDownloadsEnabled;
                txtTotalDownloads.Text           = settings.TotalDownloads;
                cbSkipTopPosts.Checked           = settings.SkipTopPosts;
                //txtAccountUsername.Text = settings.AccountUsername;
                //txtAccountPassword.Text = settings.AccountPassword;
                cbHidePassword.Checked = settings.HidePassword;

                if (!string.IsNullOrEmpty(settings.AccountPassword) || !string.IsNullOrEmpty(settings.AccountPassword))
                {
                    _instaApi = InstaApiBuilder.CreateBuilder()
                                .UseHttpClientHandler(_httpClientHandler)
                                .SetUser(new UserSessionData
                    {
                        UserName = settings.AccountUsername,
                        Password = settings.AccountPassword
                    })
                                .Build();

                    txtAccountUsername.Text = settings.AccountUsername;
                    txtAccountPassword.Text = settings.AccountPassword;

                    if (settings.StateData != null)
                    {
                        _instaApi.LoadStateDataFromStream(settings.StateData);
                    }
                }

                if (_instaApi != null)
                {
                    gbDownload.Enabled = true;
                    _isLogged          = true;

                    lblAccountLoginStatus.Text      = @"Status: Successfully restored session.";
                    lblAccountLoginStatus.ForeColor = Color.Green;
                    Log($@"Successfully restored session as {settings.AccountUsername}.", nameof(LogType.Success));
                    btnAccountLogin.Enabled  = false;
                    btnAccountLogout.Enabled = true;
                }
                else
                {
                    lblAccountLoginStatus.Text      = @"Status: Failed to restore session.";
                    lblAccountLoginStatus.ForeColor = Color.Red;
                    Log($@"Failed to restore session.", nameof(LogType.Fail));
                    btnAccountLogin.Enabled  = true;
                    btnAccountLogout.Enabled = false;
                }

                Log(@"Successfully loaded application settings.", nameof(LogType.Success));
            }
            catch (Exception ex)
            {
                txtUserAgent.Text      = UserAgentGenerator.Generate();
                txtRequestTimeout.Text = @"150";
                txtThreads.Text        = @"1";
                txtDownloadFolder.Text = Application.StartupPath;
                Log(ex.Message, nameof(LogType.Error));
            }

            try
            {
                using (var request = new Request(txtUserAgent.Text, null, double.Parse(txtRequestTimeout.Text)))
                {
                    var response =
                        await request.GetRequestResponseAsync("http://imristo.com/download/igdownloader/changelog.txt");

                    if (response.IsSuccessStatusCode)
                    {
                        txtChangelog.Text = await response.Content.ReadAsStringAsync();
                    }

                    response = await request.GetRequestResponseAsync(
                        "http://imristo.com/download/igdownloader/version.txt");

                    if (response.IsSuccessStatusCode)
                    {
                        lblLatestVersion.Text += await response.Content.ReadAsStringAsync();
                    }

                    lblCurrentVersion.Text += Application.ProductVersion;
                }
            }
            catch (HttpRequestException)
            {
                Log(@"Failed to obtain changelog and latest version. Please check your Internet connection.", nameof(LogType.Error));
            }
        }
Esempio n. 15
0
        private async void LoginButton_Click(object sender, EventArgs e)
        {
            Size = NormalSize;
            var userSession = new UserSessionData
            {
                UserName = txtUser.Text,
                Password = txtPass.Text
            };

            InstaApi = InstaApiBuilder.CreateBuilder()
                       .SetUser(userSession)
                       .UseLogger(new DebugLogger(LogLevel.Exceptions))
                       .SetRequestDelay(RequestDelay.FromSeconds(0, 1))
                       .Build();
            Text = $"{AppName} Connecting";
            try
            {
                if (File.Exists(StateFile))
                {
                    Debug.WriteLine("Loading state from file");
                    using (var fs = File.OpenRead(StateFile))
                    {
                        InstaApi.LoadStateDataFromStream(fs);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            if (!InstaApi.IsUserAuthenticated)
            {
                var logInResult = await InstaApi.LoginAsync();

                Debug.WriteLine(logInResult.Value);
                if (logInResult.Succeeded)
                {
                    GetFeedButton.Visible = true;
                    Text = $"{AppName} Connected";
                    // Save session
                    SaveSession();
                }
                else
                {
                    if (logInResult.Value == InstaLoginResult.ChallengeRequired)
                    {
                        var challenge = await InstaApi.GetChallengeRequireVerifyMethodAsync();

                        if (challenge.Succeeded)
                        {
                            if (challenge.Value.StepData != null)
                            {
                                if (!string.IsNullOrEmpty(challenge.Value.StepData.PhoneNumber))
                                {
                                    RadioVerifyWithPhoneNumber.Checked = false;
                                    RadioVerifyWithPhoneNumber.Visible = true;
                                    RadioVerifyWithPhoneNumber.Text    = challenge.Value.StepData.PhoneNumber;
                                }
                                if (!string.IsNullOrEmpty(challenge.Value.StepData.Email))
                                {
                                    RadioVerifyWithEmail.Checked = false;
                                    RadioVerifyWithEmail.Visible = true;
                                    RadioVerifyWithEmail.Text    = challenge.Value.StepData.Email;
                                }

                                SelectMethodGroupBox.Visible = true;
                                Size = ChallengeSize;
                            }
                        }
                        else
                        {
                            MessageBox.Show(challenge.Info.Message, "ERR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            else
            {
                Text = $"{AppName} Connected";
                GetFeedButton.Visible = true;
            }
        }
Esempio n. 16
0
        public static async Task <bool> MainAsync()
        {
            try
            {
                Console.WriteLine("Starting demo of InstagramApiSharp project");
                // create user session data and provide login details
                var userSession = new UserSessionData
                {
                    UserName = "******",
                    Password = "******"
                };
                // if you want to set custom device (user-agent) please check this:
                // https://github.com/ramtinak/InstagramApiSharp/wiki/Set-custom-device(user-agent)

                var delay = RequestDelay.FromSeconds(2, 2);
                // create new InstaApi instance using Builder
                _instaApi = InstaApiBuilder.CreateBuilder()
                            .SetUser(userSession)
                            .UseLogger(new DebugLogger(LogLevel.Exceptions)) // use logger for requests and debug messages
                            .SetRequestDelay(delay)
                            .Build();
                // create account
                // to create new account please check this:
                // https://github.com/ramtinak/InstagramApiSharp/wiki/Create-new-account
                const string stateFile = "state.bin";
                try
                {
                    if (File.Exists(stateFile))
                    {
                        Console.WriteLine("Loading state from file");
                        using (var fs = File.OpenRead(stateFile))
                        {
                            _instaApi.LoadStateDataFromStream(fs);
                            // in .net core or uwp apps don't use LoadStateDataFromStream
                            // use this one:
                            // _instaApi.LoadStateDataFromString(new StreamReader(fs).ReadToEnd());
                            // you should pass json string as parameter to this function.
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                if (!_instaApi.IsUserAuthenticated)
                {
                    // login
                    Console.WriteLine($"Logging in as {userSession.UserName}");
                    delay.Disable();
                    var logInResult = await _instaApi.LoginAsync();

                    delay.Enable();
                    if (!logInResult.Succeeded)
                    {
                        Console.WriteLine($"Unable to login: {logInResult.Info.Message}");
                        return(false);
                    }
                }
                var state = _instaApi.GetStateDataAsStream();
                // in .net core or uwp apps don't use GetStateDataAsStream.
                // use this one:
                // var state = _instaApi.GetStateDataAsString();
                // this returns you session as json string.
                using (var fileStream = File.Create(stateFile))
                {
                    state.Seek(0, SeekOrigin.Begin);
                    state.CopyTo(fileStream);
                }

                Console.WriteLine("Press 1 to start basic demo samples");
                Console.WriteLine("Press 2 to start upload photo demo sample");
                Console.WriteLine("Press 3 to start comment media demo sample");
                Console.WriteLine("Press 4 to start stories demo sample");
                Console.WriteLine("Press 5 to start demo with saving state of API instance");
                Console.WriteLine("Press 6 to start messaging demo sample");
                Console.WriteLine("Press 7 to start location demo sample");
                Console.WriteLine("Press 8 to start collections demo sample");
                Console.WriteLine("Press 9 to start upload video demo sample");

                var samplesMap = new Dictionary <ConsoleKey, IDemoSample>
                {
                    [ConsoleKey.D1] = new Basics(_instaApi),
                    [ConsoleKey.D2] = new UploadPhoto(_instaApi),
                    [ConsoleKey.D3] = new CommentMedia(_instaApi),
                    [ConsoleKey.D4] = new Stories(_instaApi),
                    [ConsoleKey.D5] = new SaveLoadState(_instaApi),
                    [ConsoleKey.D6] = new Messaging(_instaApi),
                    [ConsoleKey.D7] = new LocationSample(_instaApi),
                    [ConsoleKey.D8] = new CollectionSample(_instaApi),
                    [ConsoleKey.D9] = new UploadVideo(_instaApi)
                };
                var key = Console.ReadKey();
                Console.WriteLine(Environment.NewLine);
                if (samplesMap.ContainsKey(key.Key))
                {
                    await samplesMap[key.Key].DoShow();
                }
                Console.WriteLine("Done. Press esc key to exit...");

                key = Console.ReadKey();
                return(key.Key == ConsoleKey.Escape);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                // perform that if user needs to logged out
                // var logoutResult = Task.Run(() => _instaApi.LogoutAsync()).GetAwaiter().GetResult();
                // if (logoutResult.Succeeded) Console.WriteLine("Logout succeed");
            }
            return(false);
        }
Esempio n. 17
0
        private async void LoginButtonClick(object sender, EventArgs e)
        {
            // NOTE 1: I've added a WebBrowser control to pass challenge url and verify your account
            // Yout need this because you have to get cookies and document source text from webbrowser
            // and pass it to SetCookiesAndHtmlForChallenge function.

            var userSession = new UserSessionData
            {
                UserName = txtUser.Text,
                Password = txtPass.Text
            };

            InstaApi = InstaApiBuilder.CreateBuilder()
                       .SetUser(userSession)
                       .UseLogger(new DebugLogger(LogLevel.Exceptions))
                       .SetRequestDelay(RequestDelay.FromSeconds(0, 1))
                       .Build();
            Text = $"{AppName} Connecting";
            try
            {
                if (File.Exists(StateFile))
                {
                    Debug.WriteLine("Loading state from file");
                    using (var fs = File.OpenRead(StateFile))
                    {
                        InstaApi.LoadStateDataFromStream(fs);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            if (!InstaApi.IsUserAuthenticated)
            {
                var logInResult = await InstaApi.LoginAsync();

                if (!logInResult.Succeeded)
                {
                    if (logInResult.Value == InstaLoginResult.ChallengeRequired)
                    {
                        // Get challenge information
                        var instaChallenge = InstaApi.GetChallenge();
                        IsWebBrowserInUse     = false;
                        WebBrowserRmt.Visible = true;
                        // Navigate to challenge Url
                        WebBrowserRmt.Navigate(instaChallenge.Url);
                        Size = ChallengeSize;
                    }
                }
                else
                {
                    Text = $"{AppName} Connected";
                    // Save session
                    var state = InstaApi.GetStateDataAsStream();
                    using (var fileStream = File.Create(StateFile))
                    {
                        state.Seek(0, SeekOrigin.Begin);
                        state.CopyTo(fileStream);
                    }
                }
            }
            else
            {
                Text = $"{AppName} Connected";
            }
        }
Esempio n. 18
0
        private async Task <bool> Loggin()
        {
            var userSession = new UserSessionData
            {
                UserName = "******",
                Password = "******"
            };

            var delay = RequestDelay.FromSeconds(2, 2);

            InstaApi = InstaApiBuilder.CreateBuilder()
                       .SetUser(userSession)
                       .UseLogger(new DebugLogger(LogLevel.All))
                       .SetRequestDelay(delay)
                       .Build();


            const string stateFile = "state.bin";

            try
            {
                if (File.Exists(stateFile))
                {
                    //var mesage = MessageBox.Show("Loading state from file\n");


                    using (var fs = File.OpenRead(stateFile))
                    {
                        InstaApi.LoadStateDataFromStream(fs);
                        // in .net core or uwp apps don't use LoadStateDataFromStream
                        // use this one:
                        // _instaApi.LoadStateDataFromString(new StreamReader(fs).ReadToEnd());
                        // you should pass json string as parameter to this function.
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }


            if (!InstaApi.IsUserAuthenticated)
            {
                // login
                //textBox1.Text += $"Logging in as {userSession.UserName}";
                delay.Disable();
                var logInResult = await InstaApi.LoginAsync();

                delay.Enable();
                if (!logInResult.Succeeded)
                {
                    //textBox1.Text += $"Unable to login: {logInResult.Info.Message}";
                    return(false);
                }
            }
            var state = InstaApi.GetStateDataAsStream();

            // in .net core or uwp apps don't use GetStateDataAsStream.
            // use this one:
            // var state = _instaApi.GetStateDataAsString();
            // this returns you session as json string.
            using (var fileStream = File.Create(stateFile))
            {
                state.Seek(0, SeekOrigin.Begin);
                state.CopyTo(fileStream);
            }

            lblStatus.Text = "Loggin Success!";

            return(true);
        }
Esempio n. 19
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            SetTheme(Resource.Style.MyTheme);
            base.OnCreate(savedInstanceState);

            ActionBar.Hide();
            ActionBar.SetDisplayShowTitleEnabled(false);
            ActionBar.SetDisplayShowHomeEnabled(false);

            appOpenManager = new AppOpenManager(this, this);

            SetContentView(Resource.Layout.Main);

            Platform.Init(this, savedInstanceState);
            // Batteries.Init();

            var button = FindViewById <Button>(Resource.Id.myButton);

            yuklemeBar = FindViewById <ProgressBar>(Resource.Id.progressBar1);

            txtEmail    = FindViewById <EditText>(Resource.Id.tbEmail);
            txtPassword = FindViewById <EditText>(Resource.Id.tbPassword);

            CrossPermissions.Current.CheckPermissionStatusAsync <StoragePermission>();

            MobileAds.Initialize(this, "ca-app-pub-9927527797473679~9358311233");


            userSession = new UserSessionData
            {
                UserName = "",
                Password = ""
            };


            //var delay = RequestDelay.FromSeconds(2, 2);
            // create new InstaApi instance using Builder
            _instaApi2 = InstaApiBuilder.CreateBuilder()
                         .SetRequestDelay(RequestDelay.FromSeconds(0, 0))
                         .Build();
            _instaApi2.SetTimeout(TimeSpan.FromMinutes(10));

            try
            {
                var status = CrossPermissions.Current.CheckPermissionStatusAsync <StoragePermission>();

                if (status.Result != PermissionStatus.Granted)
                {
                    if (CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage).Result)
                    {
                        Toast.MakeText(Application.Context, Resources.GetText(Resource.String.fileperrmisson),
                                       ToastLength.Long)
                        .Show();
                    }

                    status = CrossPermissions.Current.RequestPermissionAsync <StoragePermission>();
                }

                // load session file if exists
                if (File.Exists(stateFile))
                {
                    using var fs = File.OpenRead(stateFile);
                    _instaApi2.LoadStateDataFromStream(fs);
                    if (_instaApi2.IsUserAuthenticated)
                    {
                        // var result2 = Task.Run(async () => await _instaApi2.UserProcessor.GetUserFollowingAsync(
                        //     _instaApi2.GetLoggedUser().LoggedInUser.UserName,
                        //     PaginationParameters.MaxPagesToLoad(1))).Result;
                        // var following = result2.Value;

                        var result2   = Task.Run(async() => await _instaApi2.WebProcessor.GetAccountInfoAsync());
                        var following = result2.Result;

                        if (!following.Succeeded)
                        {
                            _instaApi2.LogoutAsync();
                            File.Delete(stateFile);
                            throw new InvalidOperationException("Oturum süreniz dolmuş");
                        }

                        girisYapti(button, _instaApi2);
                    }
                }
            }
            catch (Exception er)
            {
                HataGoster(er.Message);
            }


            button.Click += butonTiklandiAsync;
        }
Esempio n. 20
0
        private async Task <bool> AuthorizeBot(UserSettings settings)
        {
            try
            {
                var userSession = new UserSessionData
                {
                    UserName = settings.BotUserName,
                    Password = settings.BotPassword
                };

                var delay = RequestDelay.FromSeconds(2, 2);
                // create new InstaApi instance using Builder
                _instaApi = InstaApiBuilder.CreateBuilder()
                            .SetUser(userSession)
                            .UseLogger(new DebugLogger(LogLevel.Exceptions)) // use logger for requests and debug messages
                            .SetRequestDelay(delay)
                            .Build();

                const string stateFile = "state.bin";
                try
                {
                    if (File.Exists(stateFile))
                    {
                        Debug.WriteLine("Loading state from file");
                        using (var fs = File.OpenRead(stateFile))
                        {
                            _instaApi.LoadStateDataFromStream(fs);
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }

                if (!_instaApi.IsUserAuthenticated)
                {
                    // login
                    Debug.WriteLine($"Logging in as {userSession.UserName}");
                    delay.Disable();
                    var logInResult = await _instaApi.LoginAsync();

                    delay.Enable();
                    if (!logInResult.Succeeded)
                    {
                        Debug.WriteLine($"Unable to login: {logInResult.Info.Message}");
                        return(false);
                    }
                }

                var state = _instaApi.GetStateDataAsStream();
                using (var fileStream = File.Create(stateFile))
                {
                    state.Seek(0, SeekOrigin.Begin);
                    state.CopyTo(fileStream);
                }
                return(false);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                // perform that if user needs to logged out
                // var logoutResult = Task.Run(() => _instaApi.LogoutAsync()).GetAwaiter().GetResult();
                // if (logoutResult.Succeeded) Debug.WriteLine("Logout succeed");
            }
            return(false);
        }
Esempio n. 21
0
        public static async Task <bool> MainAsync()
        {
            var binFolder = configFile.AppSettings.Settings["BinFolder"].Value;

            Directory.CreateDirectory(binFolder);

            var hardFollows    = configFile.AppSettings.Settings["HardFollows"].Value;
            var hardFollowList = hardFollows.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToList();

            var userSession = new UserSessionData
            {
                UserName = configFile.AppSettings.Settings["UserName"].Value,
                Password = configFile.AppSettings.Settings["Password"].Value
            };
            var delay = RequestDelay.FromSeconds(2, 2);

            _instaApi = InstaApiBuilder.CreateBuilder().SetUser(userSession).SetRequestDelay(delay).Build();

            var stateFilePath = binFolder + stateFile;

            try
            {
                if (File.Exists(stateFilePath))
                {
                    //Console.WriteLine("Loading state from file");
                    using (var fs = File.OpenRead(stateFilePath))
                    {
                        _instaApi.LoadStateDataFromStream(fs);
                    }
                }
            }
            catch (Exception e)
            {
                return(false);
            }

            if (!_instaApi.IsUserAuthenticated)
            {
                //Console.WriteLine($"Logging in as {userSession.UserName}");
                delay.Disable();
                var logInResult = await _instaApi.LoginAsync();

                delay.Enable();
                if (!logInResult.Succeeded)
                {
                    //Console.WriteLine($"Unable to login: {logInResult.Info.Message}");
                    return(false);
                }
            }
            var state = _instaApi.GetStateDataAsStream();

            using (var fileStream = File.Create(stateFilePath))
            {
                state.Seek(0, SeekOrigin.Begin);
                state.CopyTo(fileStream);
            }

            var currentUser = await _instaApi.GetCurrentUserAsync();

            //Console.WriteLine($"Logged in: username - {currentUser.Value.UserName}, full name - {currentUser.Value.FullName}");
            //var followers = await _instaApi.GetCurrentUserFollowersAsync(PaginationParameters.MaxPagesToLoad(6));
            //Console.WriteLine($"Count of followers [{currentUser.Value.UserName}]:{followers.Value.Count}");

            var followers = await _instaApi.GetUserFollowersAsync(currentUser.Value.UserName, PaginationParameters.MaxPagesToLoad(6));

            var followersList = followers.Value.Select(p => p.UserName).ToList();

            var followersListPath = binFolder + @"FollowersLists\";

            Directory.CreateDirectory(followersListPath);
            var followerListFileFullName = followersListPath + "followersList" + now.ToString("yyyyMMddHHmmssFFFFFFF") + ".txt";

            File.WriteAllLines(followerListFileFullName, followersList);


            var following = await _instaApi.GetUserFollowingAsync(currentUser.Value.UserName, PaginationParameters.MaxPagesToLoad(6));

            var followingList     = following.Value.Select(p => p.UserName).ToList();
            var followingListPath = binFolder + @"FollowingLists\";

            Directory.CreateDirectory(followingListPath);
            var followingListFileFullName = followingListPath + "followingList" + now.ToString("yyyyMMddHHmmssFFFFFFF") + ".txt";

            File.WriteAllLines(followingListFileFullName, followingList);

            var msgBody = PrepareMsgBody(followingListPath, followersListPath);

            if (msgBody != string.Empty)
            {
                var subject = "Analiz! InstagramLooker - " + now.ToString("dd/MM/yyyy - HH:mm");
                SendMail(subject, msgBody);
            }

            DeleteOldestFile(followersListPath);
            DeleteOldestFile(followingListPath);

            //Console.WriteLine($"Count of following [{currentUser.Value.UserName}]:{following.Value.Count}");

            return(true);
        }
Esempio n. 22
0
        public static async Task <bool> MainAsync()
        {
            try
            {
                Console.WriteLine("Starting demo of InstagramApiSharp project");
                // create user session data and provide login details
                var userSession = new UserSessionData
                {
                    UserName = "******",
                    Password = "******"
                };

                var delay = RequestDelay.FromSeconds(2, 2);
                // create new InstaApi instance using Builder
                _instaApi = InstaApiBuilder.CreateBuilder()
                            .SetUser(userSession)
                            .UseLogger(new DebugLogger(LogLevel.Exceptions)) // use logger for requests and debug messages
                            .SetRequestDelay(delay)
                            .Build();
                //// create account
                //var username = "******";
                //var password = "******";
                //var email = "*****@*****.**";
                //var firstName = "Ramtin";
                //var accountCreation = await _instaApi.CreateNewAccount(username, password, email, firstName);

                const string stateFile = "state.bin";
                try
                {
                    if (File.Exists(stateFile))
                    {
                        Console.WriteLine("Loading state from file");
                        using (var fs = File.OpenRead(stateFile))
                        {
                            _instaApi.LoadStateDataFromStream(fs);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                if (!_instaApi.IsUserAuthenticated)
                {
                    // login
                    Console.WriteLine($"Logging in as {userSession.UserName}");
                    delay.Disable();
                    var logInResult = await _instaApi.LoginAsync();

                    delay.Enable();
                    if (!logInResult.Succeeded)
                    {
                        Console.WriteLine($"Unable to login: {logInResult.Info.Message}");
                        return(false);
                    }
                }
                var state = _instaApi.GetStateDataAsStream();
                using (var fileStream = File.Create(stateFile))
                {
                    state.Seek(0, SeekOrigin.Begin);
                    state.CopyTo(fileStream);
                }

                Console.WriteLine("Press 1 to start basic demo samples");
                Console.WriteLine("Press 2 to start upload photo demo sample");
                Console.WriteLine("Press 3 to start comment media demo sample");
                Console.WriteLine("Press 4 to start stories demo sample");
                Console.WriteLine("Press 5 to start demo with saving state of API instance");
                Console.WriteLine("Press 6 to start messaging demo sample");
                Console.WriteLine("Press 7 to start location demo sample");
                Console.WriteLine("Press 8 to start collections demo sample");
                Console.WriteLine("Press 9 to start upload video demo sample");

                var samplesMap = new Dictionary <ConsoleKey, IDemoSample>
                {
                    [ConsoleKey.D1] = new Basics(_instaApi),
                    [ConsoleKey.D2] = new UploadPhoto(_instaApi),
                    [ConsoleKey.D3] = new CommentMedia(_instaApi),
                    [ConsoleKey.D4] = new Stories(_instaApi),
                    [ConsoleKey.D5] = new SaveLoadState(_instaApi),
                    [ConsoleKey.D6] = new Messaging(_instaApi),
                    [ConsoleKey.D7] = new LocationSample(_instaApi),
                    [ConsoleKey.D8] = new CollectionSample(_instaApi),
                    [ConsoleKey.D9] = new UploadVideo(_instaApi)
                };
                var key = Console.ReadKey();
                Console.WriteLine(Environment.NewLine);
                if (samplesMap.ContainsKey(key.Key))
                {
                    await samplesMap[key.Key].DoShow();
                }
                Console.WriteLine("Done. Press esc key to exit...");

                key = Console.ReadKey();
                return(key.Key == ConsoleKey.Escape);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                // perform that if user needs to logged out
                // var logoutResult = Task.Run(() => _instaApi.LogoutAsync()).GetAwaiter().GetResult();
                // if (logoutResult.Succeeded) Console.WriteLine("Logout succeed");
            }
            return(false);
        }
Esempio n. 23
0
        public async Task <bool> LoginAsync(string userName, string password)
        {
            try
            {
                var userSession = new UserSessionData
                {
                    UserName = userName,
                    Password = password
                };

                var device = new AndroidDevice
                {
                    AndroidBoardName      = "HONOR",
                    DeviceBrand           = "HUAWEI",
                    HardwareManufacturer  = "HUAWEI",
                    DeviceModel           = "PRA-LA1",
                    DeviceModelIdentifier = "PRA-LA1",
                    FirmwareBrand         = "HWPRA-H",
                    HardwareModel         = "hi6250",
                    DeviceGuid            = new Guid("be897499-c663-492e-a125-f4c8d3785ebf"),
                    PhoneGuid             = new Guid("7b72321f-dd9a-425e-b3ee-d4aaf476ec52"),
                    DeviceId            = ApiRequestMessage.GenerateDeviceIdFromGuid(new Guid("be897499-c663-492e-a125-f4c8d3785ebf")),
                    Resolution          = "1080x1812",
                    Dpi                 = "480dpi",
                    FirmwareFingerprint = "HUAWEI/HONOR/PRA-LA1:7.0/hi6250/95414346:user/release-keys",
                    AndroidBootloader   = "4.23",
                    DeviceModelBoot     = "qcom",
                    FirmwareTags        = "release-keys",
                    FirmwareType        = "user"
                };

                var delay = RequestDelay.FromSeconds(1, 1);

                _instaApi = InstaApiBuilder.CreateBuilder()
                            .SetUser(userSession)
                            .UseLogger(new DebugLogger(LogLevel.Exceptions))
                            .SetRequestDelay(delay)
                            .Build();

                _instaApi.SetDevice(device);
                _instaApi.SetAcceptLanguage("tr-TR");

                const string stateFile = "state.bin";
                try
                {
                    if (File.Exists(stateFile))
                    {
                        using (var fs = File.OpenRead(stateFile))
                        {
                            _instaApi.LoadStateDataFromStream(fs);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                if (!_instaApi.IsUserAuthenticated)
                {
                    // login
                    Console.WriteLine($"Logging in as {userSession.UserName}");
                    delay.Disable();
                    var logInResult = await _instaApi.LoginAsync();

                    delay.Enable();
                    if (!logInResult.Succeeded)
                    {
                        Console.WriteLine($"Unable to login: {logInResult.Info.Message}");
                        return(false);
                    }
                }
                var state = _instaApi.GetStateDataAsStream();
                using (var fileStream = File.Create(stateFile))
                {
                    state.Seek(0, SeekOrigin.Begin);
                    state.CopyTo(fileStream);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return(false);
        }