public async Task DoShow() { var result = await InstaApi.GetCurrentUserAsync(); if (!result.Succeeded) { Console.WriteLine($"Unable to get current user using current API instance: {result.Info}"); return; } Console.WriteLine($"Got current user: {result.Value.UserName} using existing API instance"); var stream = InstaApi.GetStateDataAsStream(); //// for .net core you should use this method: // var json = _instaApi.GetStateDataAsString(); var anotherInstance = InstaApiBuilder.CreateBuilder() .SetUser(UserSessionData.Empty) .SetRequestDelay(RequestDelay.FromSeconds(2, 2)) .Build(); anotherInstance.LoadStateDataFromStream(stream); //// for .net core you should use this method: // anotherInstance.LoadStateDataFromString(json); var anotherResult = await anotherInstance.GetCurrentUserAsync(); if (!anotherResult.Succeeded) { Console.WriteLine($"Unable to get current user using current API instance: {result.Info}"); return; } Console.WriteLine( $"Got current user: {anotherResult.Value.UserName} using new API instance without re-login"); }
/// <summary> /// Main form closing - saves the settings to a file. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { var settings = new Settings { UserAgent = txtUserAgent.Text, RequestTimeout = txtRequestTimeout.Text, Proxy = txtProxy.Text, Threads = txtThreads.Text, DownloadFolder = txtDownloadFolder.Text, CreateNewFolder = cbCreateNewFolder.Checked, SaveStats = cbSaveStats.Checked, Delimiter = txtDelimiter.Text, SkipDescription = cbSkipMediaDescription.Checked, SkipPhotos = cbSkipPhotos.Checked, SkipVideos = cbSkipVideos.Checked, SkipLikes = cbSkipMediaLikes.Checked, SkipLikesMoreLess = cbSkipMediaLikesMoreLess.Text, SkipLikesCount = txtSkipMediaLikesCount.Text, SkipComments = cbSkipMediaComments.Checked, SkipCommentsMoreLess = cbSkipMediaCommentsMoreLess.Text, SkipCommentsCount = txtSkipMediaCommentsCount.Text, SkipUploadDate = cbSkipMediaUploadDate.Checked, TotalDownloadsEnabled = cbTotalDownloads.Checked, TotalDownloads = txtTotalDownloads.Text, SkipTopPosts = cbSkipTopPosts.Checked, AccountUsername = _isLogged == false ? string.Empty : txtAccountUsername.Text, AccountPassword = _isLogged == false ? string.Empty : txtAccountPassword.Text, HidePassword = cbHidePassword.Checked, StateData = _instaApi?.GetStateDataAsStream() }; SettingsSerialization.Save(settings); }
public async Task DoShow() { var result = await _instaApi.GetCurrentUserAsync(); if (!result.Succeeded) { Console.WriteLine($"Unable to get current user using current API instance: {result.Info}"); return; } Console.WriteLine($"Got current user: {result.Value.UserName} using existing API instance"); var stream = _instaApi.GetStateDataAsStream(); var anotherInstance = InstaApiBuilder.CreateBuilder() .SetRequestDelay(TimeSpan.FromSeconds(2)) .Build(); anotherInstance.LoadStateDataFromStream(stream); var anotherResult = await anotherInstance.GetCurrentUserAsync(); if (!anotherResult.Succeeded) { Console.WriteLine($"Unable to get current user using current API instance: {result.Info}"); return; } Console.WriteLine( $"Got current user: {anotherResult.Value.UserName} using new API instance without re-login"); }
private void SaveSession() { var state = _instaApiInstance.GetStateDataAsStream(); using (var fileStream = File.Create("state.bin")) { state.Seek(0, SeekOrigin.Begin); state.CopyTo(fileStream); } }
private void SaveState() { var state = _instaApi.GetStateDataAsStream(); using (var fileStream = File.Create(stateFile)) { state.Seek(0, SeekOrigin.Begin); state.CopyTo(fileStream); } }
//登录账号 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 }
public static async void UploadPhoto(string path) { const string stateFile = "state.bin"; var userSession = new UserSessionData { UserName = File.ReadAllLines("LoginInfo.txt")[0], Password = File.ReadAllLines("LoginInfo.txt")[1] }; Console.WriteLine("Initializing API"); _instaApi = InstaApiBuilder.CreateBuilder() .SetUser(userSession) .UseLogger(new DebugLogger(LogLevel.Exceptions)) .SetRequestDelay(TimeSpan.FromSeconds(2)) .Build(); Console.WriteLine($"Logging into {userSession.UserName}"); var logInResult = await _instaApi.LoginAsync(); if (!logInResult.Succeeded) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Login failed => {logInResult.Info.Message}"); return; } else { Console.WriteLine("Login successfull"); } var state = _instaApi.GetStateDataAsStream(); using (var fileStream = File.Create(stateFile)) { state.Seek(0, SeekOrigin.Begin); state.CopyTo(fileStream); } Console.WriteLine("API initialized succesfully "); var upl = new UploadPhoto(_instaApi); Console.WriteLine("Press ENTER and type optional caption (leave blank if undesired)"); string caption = Console.ReadLine(); Console.WriteLine($"Uploading with caption {caption}"); await upl.UploadImg(caption, path); }
void SaveSession() { if (InstaApi == null) { return; } var state = InstaApi.GetStateDataAsStream(); using (var fileStream = File.Create(StateFile)) { state.Seek(0, SeekOrigin.Begin); state.CopyTo(fileStream); } }
private static void UpdateLoginState(IInstaApi api) { var state = api.GetStateDataAsStream(); try { using var fileStream = File.Create(stateFile); state.Seek(0, SeekOrigin.Begin); state.CopyTo(fileStream); } catch { //don't want to crash here } }
void SaveSession() { if (InstaApi == null) { return; } var state = InstaApi.GetStateDataAsStream(); string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), StateFile); using (var fileStream = File.Create(fileName)) { state.Seek(0, SeekOrigin.Begin); state.CopyTo(fileStream); } //DisplayAlert("Info", fileName, "Ok"); }
private void WebBrowserRmtDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (sender == null) { return; } if (e == null) { return; } if (e.Url == null) { return; } if (e.Url.ToString() == InstagramUri.ToString() && !IsWebBrowserInUse) { // Get cookies from WebBrowser var cookies = GetUriCookies(InstagramUri); // Pass web browser document source and cookies to this function: // NOTE: Don't use WebBrowserRmt.Document.Cookie to get cookies because it's not getting full cookies var result = InstaApi.SetCookiesAndHtmlForChallenge(WebBrowserRmt.DocumentText, cookies); // You are logged in if (result.Succeeded) { Text = $"{AppName} Connected"; // Save session var state = InstaApi.GetStateDataAsStream(); using (var fileStream = File.Create(StateFile)) { state.Seek(0, SeekOrigin.Begin); state.CopyTo(fileStream); } } else { // there is an unknown error. Text = $"{AppName} couldn't login"; } Thread.Sleep(1500); WebBrowserRmt.Stop(); WebBrowserRmt.Visible = false; IsWebBrowserInUse = true; Size = NormalSize; } }
public bool TryAuthenticate(string username, string password, out byte[] instagramUserCookies) { bool isAuthenticated = false; _instaApi = CreateInstaApi(username, password, REQUEST_DELAY_MIN, REQUEST_DELAY_MAX); IResult <InstaLoginResult> logInResult = TryLogIn(_instaApi); instagramUserCookies = new byte[] { }; if (!logInResult.Succeeded) { isAuthenticated = false; } else { instagramUserCookies = ConvertStreamToByteArray(_instaApi.GetStateDataAsStream()); isAuthenticated = true; } return(isAuthenticated); }
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); }
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); }
public static async Task <bool> MainAsync() { try { Console.WriteLine("Starting project"); // create user session data and provide login details Console.Write("please Enter UserName:"******"please Enter Password:"******"kajokoleha"; //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); //} var commands = new Dictionary <ConsoleKey, ICommand> { [ConsoleKey.D1] = new Overview(_instaApi), [ConsoleKey.D2] = new UnFollowNonFollower(_instaApi), [ConsoleKey.D3] = new UnFollowAll(_instaApi), }; ConsoleKeyInfo key; do { Console.WriteLine("Press 1 to Show User Overview"); Console.WriteLine("Press 2 to UnFollow NonFollower"); Console.WriteLine("Press 3 to UnFollow All"); Console.WriteLine("Press esc key to exit"); key = Console.ReadKey(); Console.WriteLine(Environment.NewLine); if (commands.ContainsKey(key.Key)) { await commands[key.Key].Do(); } } while (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); }
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); }
private async void FacebookWebBrowserDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs args) { if (FacebookLoginHelper.FirstStep(args.Url)) { if (FacebookFirstTime) { FacebookFirstTime = false; FacebookTimer.Start(); } else { var cookies = GetUriCookies(FacebookLoginHelper.InstagramUriAddress); var html = FacebookWebBrowser.DocumentText; var response = FacebookLoginHelper.GetLoggedInUserResponse(html); if (response != null && response.Config != null && response.Config.Viewer != null) { var username = response.Config.Viewer.Username; // logged in successfully FacebookWebBrowser.Visible = false; // we don't have password so we fill it up with fake password var userSession = new UserSessionData { UserName = username, Password = "******" }; // note: you cannot change password while you logged in with facebook account. // build InstaApi InstaApi = InstaApiBuilder.CreateBuilder() .SetUser(userSession) .UseLogger(new DebugLogger(LogLevel.Exceptions)) .SetRequestDelay(RequestDelay.FromSeconds(0, 1)) .Build(); LoadingPanel.Visible = false; // pass information to InstaApi var result = await InstaApi.SetCookiesAndHtmlForFacebookLogin(response, cookies, true); if (result.Value) { // Save session var state = InstaApi.GetStateDataAsStream(); using (var fileStream = File.Create(StateFile)) { state.Seek(0, SeekOrigin.Begin); state.CopyTo(fileStream); } // save session as json //var str = InstaApi.GetStateDataAsString(); //File.WriteAllText("abc.json", str); // visible get some feed button GetFeedButton.Visible = true; } else { $"An error has occured.".Output(); } } } } }
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"; } }
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); }
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); }
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); }