Exemple #1
0
        public static async Task <LoginData?> LoadSession()
        {
            LoginData loginData = new LoginData();

            try
            {
                var file = await SecureStorage.GetAsync(StateFileName);

                if (string.IsNullOrEmpty(file))
                {
                    return(null);
                }

                InstaApi = InstaApiBuilder.CreateBuilder()
                           .SetUser(UserSessionData.Empty)
                           .UseLogger(new DebugLogger(LogLevel.All))
                           .Build();
                InstaApi.LoadStateDataFromString(file);
                if (!InstaApi.IsUserAuthenticated)
                {
                    InstaApi = null;
                    return(null);
                }
                loginData.UserName = InstaApi.GetLoggedUser().UserName;
                loginData.Password = InstaApi.GetLoggedUser().Password;


                return(loginData);
            }
            catch { InstaApi = null; return(null); }
        }
        public async System.Threading.Tasks.Task <bool> UploadVideo(IInstaApi instaApi, string filePath, string thumbnailPath, string caption)
        {
            try
            {
                var mediaVideo = new InstaVideoUpload
                {
                    Video          = new InstaVideo(filePath, 0, 0),
                    VideoThumbnail = new InstaImage(thumbnailPath, 0, 0)
                };

                var result = await instaApi.MediaProcessor.UploadVideoAsync(mediaVideo, caption);

                if (!result.Succeeded)
                {
                    InfoFormat("Unable to upload video: {0}", result.Info.Message);
                    return(false);
                }

                InfoFormat("Media created: {0}, {1}", result.Value.Pk, result.Value.Caption.Text);
                return(true);
            }
            catch (Exception e)
            {
                ErrorFormat("An error occured while uploading the video: {0}", e, filePath);
                return(false);
            }
        }
Exemple #3
0
 public UserProfil(ref IInstaApi instaApi, ref UserSessionData userSessionData)
 {
     InitializeComponent();
     _instaApi    = instaApi;
     _userSession = userSessionData;
     UpdateProfilInfo();
 }
Exemple #4
0
        public static async void Subs(string userExp, string userName, string password)
        {
            user          = new UserSessionData();
            user.UserName = userName;
            user.Password = password;

            api = InstaApiBuilder.CreateBuilder()
                  .SetUser(user)
                  .UseLogger(new DebugLogger(LogLevel.Exceptions))
                  //.SetRequestDelay(TimeSpan.FromSeconds(1))
                  .Build();
            var loginRequest = await api.LoginAsync();

            IResult <InstaUser> userSearch = await api.GetUserAsync(userExp);

            IResult <InstaUserShortList> followers = await api.GetUserFollowersAsync(userSearch.Value.UserName, PaginationParameters.MaxPagesToLoad(5));

            var followlist       = followers.Value;
            int count_followlist = followlist.ToArray().Length;

            for (int i = 0; i < count_followlist; i++)
            {
                var res = await api.FollowUserAsync(followlist[i].Pk);

                string result = res.Succeeded.ToString();
            }
        }
Exemple #5
0
        public async void Dogrula(IInstaApi api)
        {
            try
            {
                var verifyLogin = await api.VerifyCodeForChallengeRequireAsync(txtDogrulama.Text);

                if (verifyLogin.Succeeded)
                {
                    MessageBox.Show("doğrulandı");
                    timer1.Start();
                }
                else
                {
                    MessageBox.Show("Yanlış kod");
                    if (verifyLogin.Value == InstaLoginResult.TwoFactorRequired)
                    {
                        MessageBox.Show("iki faktörlü doğrulama gerekiyor.");
                    }
                    else
                    {
                        listBox1.Items.Add("[" + DateTime.Now.ToString("HH:mm") + "]" + verifyLogin.Info.Message);
                    }
                    label4.Text      = "Bir hata oluştu, loglara bakın.";
                    label4.ForeColor = Color.Red;
                }
            }
            catch (Exception ex)
            {
                listBox1.Items.Add("[" + DateTime.Now.ToString("HH:mm") + "]" + ex.Message);
                label4.Text      = "Bir hata oluştu, loglara bakın.";
                label4.ForeColor = Color.Red;
            }
        }
        /// <summary>
        /// Load InstaApi session
        /// </summary>
        async void LoadSession()
        {
            try
            {
                var file = await LocalFolder.GetFileAsync(StateFileName);

                var json = await FileIO.ReadTextAsync(file);

                if (string.IsNullOrEmpty(json))
                {
                    return;
                }

                InstaApi = InstaApiBuilder.CreateBuilder()
                           .SetUser(UserSessionData.Empty)
                           .Build();
                InstaApi.LoadStateDataFromString(json);
                if (!InstaApi.IsUserAuthenticated)
                {
                    InstaApi = null;
                    return;
                }
                UsernameText.Text     = InstaApi.GetLoggedUser().UserName;
                PasswordText.Password = InstaApi.GetLoggedUser().Password;
                "Connected".ChangeAppTitle();
            }
            catch { InstaApi = null; }
        }
Exemple #7
0
        public InstagramService(
            IConfigurationService <InstagramServiceConfig> instaConfig,
            ILogger <InstagramService> logger,
            IUnitOfWork unitOfWork)
        {
            _instaConfig = instaConfig;
            _logger      = logger;
            _userSession = new UserSessionData();
            _unitOfWork  = unitOfWork;

            var data = _instaConfig.GetSettingsAsync().Result;

            if (data.Password != null || data.Username != null)
            {
                _userSession.UserName = data.Username;
                _userSession.Password = data.Password;
            }
            else
            {
                _logger.LogError("password or username empty");
            }

            _instaApi = InstaApiBuilder.CreateBuilder()
                        .SetUser(_userSession)
                        .UseLogger(new DebugLogger(LogLevel.Exceptions))
                        .Build();
        }
Exemple #8
0
        public PushClient(List <IInstaApi> apis, IInstaApi api /*, bool tryLoadData = true*/)
        {
            _runningTokenSource = new CancellationTokenSource();

            ApiList   = apis;
            _instaApi = api ?? throw new ArgumentException("Api can't be null", nameof(api));
        }
Exemple #9
0
        private void PSetApi()
        {
            //Find last login user
            using (var db = new DivxModel())
            {
                var user = db.Users.FirstOrDefault();
                if (user != null)
                {
                    //Create user info
                    var userSession = new UserSessionData
                    {
                        UserName = user.Username,
                        Password = "******"
                    };

                    //Create api
                    APi = InstaApiBuilder.CreateBuilder()
                          .SetUser(userSession)
                          .UseLogger(new DebugLogger(LogLevel.Exceptions))
                          .Build();

                    //Set Session
                    APi.LoadStateDataFromString(user.Session);
                }
                //Not user here, please login first
                else
                {
                    MainPage.mainFrame.Navigate(typeof(View.LoginPage));
                }
            }
        }
Exemple #10
0
 public TaskClearBots(IInstaApi api, SettingTaskClearBots setting)
 {
     this.api     = api;
     this.setting = setting;
     ew           = new ManualResetEvent(true);
     count        = 0;
 }
Exemple #11
0
        public List <InstagramPost> GetUserPostsByUsername(string username, byte[] instagramCookies)
        {
            IInstaApi instaApi = CreateInstaApi(instagramCookies, REQUEST_DELAY_MIN, REQUEST_DELAY_MAX);

            List <InstagramPost> posts = new List <InstagramPost>();

            PaginationParameters pageParams = PaginationParameters.Empty;

            Task <IResult <InstaMediaList> > mediaListTask = Task.Run(() => instaApi.UserProcessor.GetUserMediaAsync(username, pageParams));

            mediaListTask.Wait();
            IResult <InstaMediaList> mediaList = mediaListTask.Result;

            if (mediaList.Succeeded)
            {
                Parallel.ForEach(mediaList.Value, media =>
                {
                    InstagramPost post   = new InstagramPost();
                    post.CountOfComments = Convert.ToInt32(media.CommentsCount);
                    post.Commenters      = GetPostCommenters(media);
                    post.CountOfLikes    = Convert.ToInt32(media.LikesCount);
                    post.Likers          = GetPostLikers(media);
                    post.MediaFileUri    = GetUri(media);
                    posts.Add(post);
                });
            }

            return(posts);
        }
Exemple #12
0
        public async Task <IInstaApi> Create()
        {
            if (_api != null)
            {
                return(_api);
            }

            var api = InstaApiBuilder.CreateBuilder()
                      .SetUser(new UserSessionData
            {
                UserName = _config.Username,
                Password = _config.Password
            })
                      //.UseLogger(_logger)
                      .SetRequestDelay(RequestDelay.FromSeconds(2, 2))
                      .Build();

            var status = await api.LoginAsync();

            if (!status.Succeeded)
            {
                throw new InstaException($"Login failed with username '{_config.Username}'.");
            }

            _api = api;
            return(_api);
        }
        public async static Task Login(string username, string password)
        {
            var userSession = new UserSessionData
            {
                UserName = username,
                Password = password
            };

            _instaApi = InstaApiBuilder.CreateBuilder()
                        .SetUser(userSession)
                        .UseLogger(new DebugLogger(LogLevel.All)) // use logger for requests and debug messages
                        .SetRequestDelay(TimeSpan.FromSeconds(0))
                        .Build();

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

                if (!logInResult.Succeeded)
                {
                    Console.WriteLine($"Unable to login: {logInResult.Info.Message}");
                }
            }
        }
Exemple #14
0
        private static void RunTask(TaskModel t, IInstaApi Api)
        {
            //MessageBox.Show($"Task Type: {t.TaskType.ToString()} {Environment.NewLine}Task Name: {t.Name}", "Task Running", MessageBoxButton.OK, MessageBoxImage.Information);

            switch (t.TaskType)
            {
            case TaskType.Comment:
                RunCommentTaskAsync(t, Api);
                break;

            case TaskType.DM:
                RunDMTaskAsync(t, Api);
                break;

            case TaskType.Follow:
                RunFollowTaskAsync(t, Api);
                break;

            case TaskType.Like:
                RunLikeTaskAsync(t, Api);
                break;

            case TaskType.Post:
                RunPostTaskAsync(t, Api);
                break;

            case TaskType.Unfollow:
                RunUnfollowTaskAsync(t, Api);
                break;

            case TaskType.Unlike:
                RunUnlikeTaskAsync(t, Api);
                break;
            }
        }
Exemple #15
0
        public MainForm(ref IInstaApi InstaApi)
        {
            InitializeComponent();
            instaApi  = InstaApi;
            dbContext = new InstaMarketDbContext();

            List <Model.Good>                       goods                       = dbContext.Goods.ToList();
            List <Model.Dimension>                  dimensions                  = dbContext.Dimensions.ToList();
            List <Model.Good_Dimension>             good_Dimensions             = dbContext.Good_Dimensions.ToList();
            List <Model.Good_Dimension_Publication> good_Dimension_Publications = dbContext.Good_Dimension_Publications.ToList();
            List <Model.Shop>                       shops                       = dbContext.Shops.ToList();
            List <Model.Publication>                publications                = dbContext.Publications.ToList();
            List <Model.Order>                      orders                      = dbContext.Orders.ToList();
            List <Model.Order_Status>               order_Statuses              = dbContext.Order_Statuses.ToList();
            List <Model.Receipt>                    receipts                    = dbContext.Receipts.ToList();
            List <Model.Delivery>                   deliveries                  = dbContext.Deliveries.ToList();
            List <Model.Publication_Image>          publication_Images          = dbContext.Publication_Images.ToList();
            List <Model.Publication_Video>          publication_Videos          = dbContext.Publication_Videos.ToList();
            List <Model.Chat>                       chats                       = dbContext.Chats.ToList();
            List <Model.Chat_Status>                chat_Statuses               = dbContext.Chat_Statuses.ToList();
            List <Model.User>                       users                       = dbContext.Users.ToList();
            List <Model.Comment>                    comments                    = dbContext.Comments.ToList();

            // Order panel
            var orderStatuses = dbContext.Order_Statuses.ToList();

            orderStatuses.Add(new Model.Order_Status {
                Order_Status_Id = 0, Name = "All"
            });
            orderPanelOrderStatusComboBox.DataSource   = orderStatuses;
            orderPanelOrderStatusComboBox.SelectedItem = orderStatuses.First(os => os.Order_Status_Id == 0);

            // Publication panel
            publicationComboBox.SelectedIndex = 0;
        }
Exemple #16
0
        public async Task Process()
        {
            while (IsEnabled)
            {
                using (var db = new InstaBotContext())
                {
                    var activeQueues = await db.Queues
                                       .Where(x => x.LastActivity < DateTime.UtcNow - TimeSpan.FromSeconds(x.DelayInSeconds) &&
                                              x.QueueState == QueueState.InProgress && x.IsActive)
                                       .Include(x => x.LoginData)
                                       .ToListAsync();

                    foreach (var queue in activeQueues)
                    {
                        try
                        {
                            IInstaApi instaApi = await InstagramApiFactory.GetInstaApiAsync(new InstagramUser(queue.LoginData.Name, queue.LoginData.Password));

                            IInstagramExecutor instagramExecutor = InstagramServiceFactory.CreateExecutor(queue.QueueType, instaApi);
                            await instagramExecutor.Execute(queue, db);

                            Console.WriteLine(DateTime.Now);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            //throw;
                        }
                    }
                }
            }
        }
        private static async Task <InstaUserShortList> GetUnfollowers(IInstaApi api, string username)
        {
            var followersListTask = GetFollowersList(api, username);
            var followingListTask = GetFollowingList(api, username);

            await Task.WhenAll(followersListTask, followingListTask);

            var followersList = await followersListTask;
            var followingList = await followingListTask;

            if (followersList.Count == 0 && followingList.Count == 0)
            {
                throw new Exception("Please check your username!");
            }

            InstaUserShortList unfollowers = new InstaUserShortList();

            foreach (var user in followingList)
            {
                if (followersList.Where(x => x.UserName == user.UserName).FirstOrDefault() == null)
                {
                    unfollowers.Add(user);
                }
            }

            return(unfollowers);
        }
        /// <summary>
        /// Load InstaApi session
        /// </summary>
        async void LoadSession()
        {
            try
            {
                var file = await LocalFolder.GetFileAsync(StateFileName);

                var json = await FileIO.ReadTextAsync(file);

                if (string.IsNullOrEmpty(json))
                {
                    return;
                }

                var userSession = new UserSessionData
                {
                    // no need to set username password
                    // but we have to set something in it
                    UserName = "******",
                    Password = "******"
                };
                InstaApi = InstaApiBuilder.CreateBuilder()
                           .SetUser(userSession)
                           .Build();
                InstaApi.LoadStateDataFromString(json);
                if (!InstaApi.IsUserAuthenticated)
                {
                    InstaApi = null;
                    return;
                }
                UsernameText.Text     = InstaApi.GetLoggedUser().UserName;
                PasswordText.Password = InstaApi.GetLoggedUser().Password;
                "Connected".ChangeAppTitle();
            }
            catch { InstaApi = null; }
        }
        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;
            }
        }
Exemple #20
0
        private async Task <bool> LoginAsync(string username, string password)
        {
            if (_api != null && _api.IsUserAuthenticated)
            {
                return(true);
            }
            var userSession = new UserSessionData {
                UserName = username, Password = password
            };

            _api = InstaApiBuilder.CreateBuilder()
                   .SetUser(userSession)
                   .UseLogger(new DebugLogger(LogLevel.Exceptions)).Build();

            var loginRequest = await _api.LoginAsync();

            if (loginRequest.Succeeded)
            {
                Console.WriteLine("Logged in!");
            }
            else
            {
                var errorMsg = loginRequest.Info.Message;
                Console.WriteLine("Error Logging in!" + Environment.NewLine + errorMsg);
                if (errorMsg == "Please wait a few minutes before you try again.")
                {
                    Thread.Sleep(TimeSpan.FromMinutes(5));
                }
            }

            return(loginRequest.Succeeded);
        }
Exemple #21
0
        public static async void Like(string userExp, string userName, string password)
        {
            user          = new UserSessionData();
            user.UserName = userName;
            user.Password = password;

            api = InstaApiBuilder.CreateBuilder()
                  .SetUser(user)
                  .UseLogger(new DebugLogger(LogLevel.Exceptions))
                  //.SetRequestDelay(TimeSpan.FromSeconds(1))
                  .Build();
            var loginRequest = await api.LoginAsync();

            IResult <InstaUser> userSearch = await api.GetUserAsync(userExp);

            IResult <InstaMediaList> media = await api.GetUserMediaAsync(userExp, PaginationParameters.MaxPagesToLoad(5));

            var mediaList       = media.Value;
            int count_mediaList = mediaList.ToArray().Length;

            for (int i = 0; i < count_mediaList; i++)
            {
                var res = await api.LikeMediaAsync(mediaList[i].InstaIdentifier);

                string result = res.Succeeded.ToString();
            }
        }
Exemple #22
0
 public HandleChallengeForm(IInstaApi api)
 {
     InitializeComponent();
     this.api   = api;
     CountTimer = 60;
     timerTime  = new Timer();
 }
Exemple #23
0
        public async System.Threading.Tasks.Task <bool> UploadImage(IInstaApi instaApi, string filePath, string caption)
        {
            try
            {
                var mediaImage = new InstaImageUpload
                {
                    // leave zero, if you don't know how height and width is it.
                    Height = 0,
                    Width  = 0,
                    Uri    = filePath
                };

                var result = await instaApi.MediaProcessor.UploadPhotoAsync(mediaImage, caption);

                if (!result.Succeeded)
                {
                    InfoFormat("Unable to upload image: {0}", result.Info.Message);
                    return(false);
                }

                InfoFormat("Media created: {0}, {1}", result.Value.Pk, result.Value.Caption.Text);
                return(true);
            }
            catch (Exception e)
            {
                ErrorFormat("An error occured while uploading the image: {0}", e, filePath);
                return(false);
            }
        }
Exemple #24
0
 public ShopAddSubForm(ref InstaMarketDbContext dbContext, ref Shop shop, ref IInstaApi instaApi)
 {
     InitializeComponent();
     this.instaApi  = instaApi;
     this.dbContext = dbContext;
     this.shop      = shop;
 }
Exemple #25
0
 public AudienceConvert(IInstaApi api, SettingAudience setting)
 {
     ew           = new ManualResetEvent(true);
     this.api     = api;
     this.setting = setting;
     info         = new InfoStatisticsGrid(Info(), "-", setting.DeleteDouble_OriginalFileName, "Готов");
 }
Exemple #26
0
        public async Task <NotFollowingViewModel> NotFollowinBack(string userId, string username)
        {
            this.instaApi = this.api.GetInstance(userId, username);

            var followers = await this.instaApi.UserProcessor.GetUserFollowersAsync(username, PaginationParameters.Empty);

            var following = await this.instaApi.UserProcessor.GetUserFollowingAsync(username, PaginationParameters.Empty);

            var notFollowing = new List <InstaUserShort>();

            foreach (var user in following.Value)
            {
                if (!followers.Value.Contains(user))
                {
                    notFollowing.Add(user);
                }
            }

            var viewModel = new NotFollowingViewModel
            {
                Users = notFollowing,
            };

            return(viewModel);
        }
 public AutoPostUploadHistory(IInstaApi api, Post post)
 {
     this.api    = api;
     this.post   = post;
     delete      = false;
     forcedStart = false;
 }
Exemple #28
0
        public async Task <string> Login(string userId, string username, string password)
        {
            if (username == "system")
            {
                this.instaApi = this.api.GetInstance("system");
                var guest_username = this.instaApi.GetLoggedUser().UserName;
                var guest          = this.api.GetByName(guest_username);
                this.instaApi = await this.api.Login(userId, guest.UserName, guest.Password);

                await this.Add(userId, guest);

                return(string.Empty);
            }

            this.instaApi = await this.api.Login(userId, username, password);

            // challange needed (Two Factor Authentication)
            if (!this.instaApi.IsUserAuthenticated)
            {
                var challenge = await this.instaApi.GetChallengeRequireVerifyMethodAsync();

                await this.instaApi.RequestVerifyCodeToSMSForChallengeRequireAsync();

                return(challenge.Value.StepData.PhoneNumber);
            }

            // succsefull login
            var user = this.api.GetByName(username);

            await this.Add(userId, user);

            return(string.Empty);
        }
Exemple #29
0
        public async void TotalDePublicacoes(string username, IInstaApi api)
        {
            IResult <InstaUser> userSearch = await api.GetUserAsync(username);

            Console.WriteLine($"USER:{userSearch.Value.FullName}\n\tFollowers: {userSearch.Value.FollowersCount}\n\t {userSearch.Value.IsVerified}");

            IResult <InstaMediaList> media = await api.GetUserMediaAsync(username, PaginationParameters.MaxPagesToLoad(5));

            List <InstaMedia> mediaList = mediaList = media.Value.ToList();

            for (int i = 0; i < mediaList.Count; i++)
            {
                InstaMedia m = mediaList[i];
                if (m != null && m.Caption != null)
                {
                    string captionText = m.Caption.Text;
                    if (captionText != null)
                    {
                        if (m.MediaType == InstaMediaType.Image)
                        {
                            for (int X = 0; X < m.Images.Count; X++)
                            {
                                if (m.Images[X] != null && m.Images[X].URI != null)
                                {
                                    Console.WriteLine($"\n\t{captionText}");
                                    string uri = m.Images[X].URI;

                                    Console.Write($"{uri}\n\t");
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #30
0
        private async void Login()
        {
            try
            {
                // создаем  обьект, через который происходит основная работа
                api = InstaApiBuilder.CreateBuilder()
                      .SetUser(user)
                      .UseLogger(new DebugLogger(LogLevel.Exceptions))
                      .SetRequestDelay(RequestDelay.FromSeconds(7, 9))
                      .Build();
                var loginRequest = await api.LoginAsync();

                if (loginRequest.Succeeded)
                {
                    logBox.Items.Add("Logged in succes, press Start");
                    btn_start.Enabled    = true;
                    btn_unfollow.Enabled = true;
                }
                else
                {
                    logBox.Items.Add("Logged in failed! " + loginRequest.Info.Message);
                }
            }
            catch (Exception ex) {
                logger.CloseLog();
                MessageBox.Show(ex.ToString());
            }
        }