Esempio n. 1
0
        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");
        }
Esempio n. 2
0
        async Task Login()
        {
            api = InstaApiBuilder.CreateBuilder()
                  .SetUser(user)
                  .UseLogger(new DebugLogger(LogLevel.Exceptions))
                  .Build();

            var loginRequest = await api.LoginAsync();

            if (loginRequest.Succeeded)
            {
                IResult <InstaCurrentUser> result = await api.GetCurrentUserAsync();

                var    names      = result.Value.FullName.Split(' ');
                string firstname  = names[0];
                string secondName = secondName = names[1];
                string mail       = result.Value.Email;
                string telNumber  = result.Value.PhoneNumber;
                byte[] image;
                using (WebClient client = new WebClient())
                {
                    client.DownloadFile(new Uri(result.Value.HdProfilePicture.Uri), User.filename);
                }
                using (System.IO.FileStream fs = new System.IO.FileStream(User.filename, System.IO.FileMode.OpenOrCreate))
                {
                    image = new byte[fs.Length];
                    fs.Read(image, 0, image.Length);
                }

                string about = result.Value.FullName + "\n" + result.Value.Gender + "\n" + result.Value.UserName + "\n" + result.Value.CountryCode;
                tmp = new User(firstname, secondName, mail, telNumber, about, image);
            }
        }
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
        public async Task <int> RemoveSubscribersAsync(int count)
        {
            if (!_api.IsUserAuthenticated)
            {
                await _api.LoginAsync();
            }

            var type = _api.GetType();

            type.GetProperty("IsUserAuthenticated")?.SetValue(_api, true);

            var currentUser = await _api.GetCurrentUserAsync();

            var followings = await _api.GetUserFollowingAsync(currentUser.Value.UserName, PaginationParameters.MaxPagesToLoad(20));

            var iteration = 0;

            foreach (var following in followings.Value)
            {
                if (iteration == count)
                {
                    return(iteration);
                }

                await Task.Delay(TimeSpan.FromMilliseconds(new Random().Next(20, 200)));

                var unFollowResult = await _api.UnFollowUserAsync(following.Pk);

                Console.WriteLine($"{(unFollowResult.Succeeded ? $"Success unfollowed {following.UserName}" : unFollowResult.Info.Message)}");

                iteration++;
            }

            return(iteration);
        }
Esempio n. 5
0
        public async Task DoShow()
        {
            // get currently logged in user
            var currentUser = await _instaApi.GetCurrentUserAsync();

            Console.WriteLine(
                $"Logged in: username - {currentUser.Value.UserName}, full name - {currentUser.Value.FullName}");

            Console.WriteLine("See Samples/Live.cs to see how it's works");
            Console.WriteLine("Live functions: ");
            Console.WriteLine(@"GetHeartBeatAndViewerCountAsync
GetFinalViewerListAsync
GetSuggestedBroadcastsAsync
GetDiscoverTopLiveAsync
GetTopLiveStatusAsync
GetInfoAsync
GetViewerListAsync
GetPostLiveViewerListAsync
CommentAsync
PinCommentAsync
UnPinCommentAsync
GetCommentsAsync
EnableCommentsAsync
DisableCommentsAsync
LikeAsync
GetLikeCountAsync
AddToPostLiveAsync
DeletePostLiveAsync
CreateAsync
StartAsync
EndAsync");
        }
Esempio n. 6
0
        public async Task DoShow()
        {
            // get currently logged in user
            var currentUser = await InstaApi.GetCurrentUserAsync();

            Console.WriteLine(
                $"Logged in: username - {currentUser.Value.UserName}, full name - {currentUser.Value.FullName}");

            Console.WriteLine("See Samples/Account.cs to see how it's works");
            Console.WriteLine("Accounts functions: ");
            Console.WriteLine(@"EditProfileAsync
GetRequestForEditProfileAsync
SetNameAndPhoneNumberAsync
RemoveProfilePictureAsync
ChangeProfilePictureAsync
GetStorySettingsAsync
EnableSaveStoryToGalleryAsync
DisableSaveStoryToGalleryAsync
EnableSaveStoryToArchiveAsync
DisableSaveStoryToArchiveAsync
AllowStorySharingAsync
AllowStoryMessageRepliesAsync
CheckUsernameAsync
GetSecuritySettingsInfoAsync
DisableTwoFactorAuthenticationAsync
SendTwoFactorEnableSmsAsync
TwoFactorEnableAsync
SendConfirmEmailAsync
SendSmsCodeAsync
VerifySmsCodeAsync");
        }
Esempio n. 7
0
        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");
        }
        public async static Task <bool> Logout()
        {
            IResult <bool> logout_successful = await _instaApi.LogoutAsync();

            await _instaApi.GetCurrentUserAsync();

            return(logout_successful.Value);
        }
Esempio n. 9
0
        public async Task <UserInfo> GetCurrentUserInfo()
        {
            validateInstaClient();
            validateLoggedIn();

            IResult <InstaCurrentUser> user = await instaApi.GetCurrentUserAsync();

            return(user.Value.ToUserInfo());
        }
Esempio n. 10
0
        public async Task <IActionResult> Index()
        {
            _instaApi = await LoginHelper.GetApi();

            if (_instaApi != null && _instaApi.IsUserAuthenticated)
            {
                return(Redirect($"/{(await _instaApi.GetCurrentUserAsync()).Value.UserName}"));
            }
            return(View());
        }
        /// <summary>
        /// Cargar controles
        /// </summary>
        private async void CargarControles()
        {
            var currentUser = await _instaApi.GetCurrentUserAsync();

            lblUsuario.Text = currentUser.Value.UserName.ToString();
            var request = WebRequest.Create(currentUser.Value.ProfilePicture.ToString());

            using (var response = request.GetResponse())
                using (var stream = response.GetResponseStream())
                {
                    ImagenPerfil.Image = Bitmap.FromStream(stream);
                }
        }
Esempio n. 12
0
        public async Task DoShow()
        {
            // get currently logged in user
            var currentUser = await _instaApi.GetCurrentUserAsync();

            Console.WriteLine(
                $"Logged in: username - {currentUser.Value.UserName}, full name - {currentUser.Value.FullName}");

            Console.WriteLine("See Samples/Discover.cs to see how it's works");
            Console.WriteLine("Discover functions: ");
            Console.WriteLine(@"GetRecentSearchsAsync
ClearRecentSearchsAsync
GetSuggestedSearchesAsync
SearchPeopleAsync");
        }
        public async Task <List <InstagramPost> > GetPosts()
        {
            IInstaApi api = (IInstaApi)HttpContext.Current.Session["api"];

            if (api == null || !api.IsUserAuthenticated)
            {
                return(null);
            }

            List <InstagramPost> results = null;
            var user = await api.GetCurrentUserAsync();

            if (!user.Succeeded)
            {
                return(null);
            }

            var mediaCollections = await api.UserProcessor.GetUserMediaAsync(user.Value.UserName, InstagramApiSharp.PaginationParameters.MaxPagesToLoad(2));

            if (!mediaCollections.Succeeded)
            {
                return(null);
            }


            results = new List <InstagramPost>();
            for (int i = 0; i < mediaCollections.Value.Count; i++)
            {
                InstagramPost temp = new InstagramPost();
                //temp.ImageUri = mediacollections.Value[i].Images[1].Uri;
                //temp.ViewCount = mediacollections.Value[i].ViewCount;
                //temp.
                results.Add(new InstagramPost
                {
                    LikesCount    = mediaCollections.Value[i].LikesCount,
                    ViewCount     = mediaCollections.Value[i].ViewCount,
                    CommentsCount = mediaCollections.Value[i].CommentsCount,
                    ImageUriSmall = mediaCollections.Value[i].Images[1].Uri,
                    ImageUriLarge = mediaCollections.Value[i].Images[0].Uri,
                    DatePosted    = mediaCollections.Value[i].TakenAt.ToShortDateString(),
                    TimePosted    = mediaCollections.Value[i].TakenAt.ToShortTimeString(),
                    Description   = mediaCollections.Value[i].Caption.Text
                });
            }


            return(results);
        }
Esempio n. 14
0
        public async Task <IActionResult> Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("index", model));
            }
            await LoginHelper.Login(model.UserName, model.Password);

            _instaApi = await LoginHelper.GetApi();

            if (_instaApi == null)
            {
                return(View("Index", model));
            }
            return(Redirect($"/{(await _instaApi.GetCurrentUserAsync()).Value.UserName}"));
        }
Esempio n. 15
0
        public string GetCurrentUserPrimaryKey()
        {
            string primaryKey = string.Empty;

            Task <IResult <InstaCurrentUser> > currentUserTask = Task.Run(() => _instaApi.GetCurrentUserAsync());

            currentUserTask.Wait();
            IResult <InstaCurrentUser> currentUser = currentUserTask.Result;

            if (currentUser.Succeeded)
            {
                primaryKey = currentUser.Value.Pk.ToString();
            }

            return(primaryKey);
        }
Esempio n. 16
0
        async void ThreadMethod()
        {
            infoAcc = new InfoGridAutopost((await api.GetCurrentUserAsync()).Value.UserName, "История",
                                           post.FileNamePhoto, post.Time.ToString(), "Ожидает публикации", post.Number);
            EventUpdateGrid(this, new UpdateGridAutopost(infoAcc));

            while (delete == false)
            {
                if (DateTime.Now > post.Time || forcedStart)
                {
                    Posting();
                    break;;
                }
                Thread.Sleep(1000 * 60);
            }
        }
Esempio n. 17
0
        public async Task <MainLoginModel> UpdateLoginModel()
        {
            var info = await _instaApi.GetCurrentUserAsync();

            var model = new MainLoginModel {
                CurrentUser = info.Value
            };

            var followers =
                await _instaApi.GetUserFollowersAsync(info.Value.UserName, PaginationParameters.MaxPagesToLoad(15));

            model.Followers = followers.Value;
            var following = await _instaApi.GetUserFollowingAsync(info.Value.UserName, PaginationParameters.MaxPagesToLoad(15));

            model.Following = following.Value;
            return(model);
        }
Esempio n. 18
0
        public async Task DoShow2()
        {
            var currentUser = await InstaApi.GetCurrentUserAsync();


            var currentUserMedia = await InstaApi.UserProcessor.GetUserMediaAsync(currentUser.Value.UserName, PaginationParameters.MaxPagesToLoad(5));

            if (currentUserMedia.Succeeded)
            {
                Console.WriteLine($"Media count [{currentUser.Value.UserName}]: {currentUserMedia.Value.Count}");
                foreach (var media in currentUserMedia.Value)
                {
                    var likeResult = await InstaApi.MediaProcessor.LikeMediaAsync(media.InstaIdentifier);

                    var resultString = likeResult.Value ? "liked" : "not liked";
                    Console.WriteLine($"Media {media.Code} {resultString}");
                    ConsoleUtils.PrintMedia("Self media", media, _maxDescriptionLength);
                }
            }
        }
        protected override async Task Execute(CancellationToken token)
        {
            log.LogInformation("Starting...");
            var location    = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            var sessionFile = Path.Combine(location, $"{config.User}.session.dat");

            session.Load(sessionFile);
            api.Delay.Disable();
            if (!api.IsUserAuthenticated)
            {
                var logInResult = await api.LoginAsync().ConfigureAwait(false);

                if (!logInResult.Succeeded)
                {
                    log.LogError("Authentication failed: [{0}]", logInResult.Info.Message);
                    return;
                }

                session.Save(sessionFile);
            }
            else
            {
                log.LogInformation("User is already authenticated");
            }

            api.Delay.Enable();
            var currentUser = await api.GetCurrentUserAsync().ConfigureAwait(false);

            if (!currentUser.Succeeded)
            {
                log.LogError("Failed to retrieve user: {0}", currentUser.Info.Message);
                return;
            }

            log.LogInformation("Started for user: {0}...", currentUser.Value.FullName);
            await Internal(currentUser.Value, token).ConfigureAwait(false);

            session.Save(sessionFile);
            log.LogInformation("Completed");
        }
Esempio n. 20
0
        private static async void RunUnfollowTaskAsync(TaskModel t, IInstaApi api)
        {
            t = t.Refreshed;

            List <InstaUserShort> users = new List <InstaUserShort>();
            var _currentUser            = await api.GetCurrentUserAsync();

            if (_currentUser.Succeeded)
            {
                var _followers = await api.GetUserFollowersAsync(_currentUser.Value.UserName, PaginationParameters.MaxPagesToLoad(10));

                if (_followers.Succeeded)
                {
                    var filteredUsers = await Helper.GetFilteredUsersAsync(_followers.Value.ToList(), t.Searches, api, 5);

                    foreach (var user in filteredUsers)
                    {
                        if (user != null)
                        {
                            var result = await api.UnFollowUserAsync(user.Pk);

                            if (result.Succeeded)
                            {
                                if (!result.Value.Following)
                                {
                                    t.TaskExecuted();
                                    Helper.Log($"Task Executed: {t.Name} - {t.TaskType.ToString()} {Environment.NewLine} {JsonConvert.SerializeObject(result.Value)}");
                                }
                                else
                                {
                                    Helper.Log(JsonConvert.SerializeObject(result.Value));
                                }
                            }
                        }
                    }
                }
            }
        }
        public async Task <InstagramProfile> GetProfile()
        {
            IInstaApi        api    = (IInstaApi)HttpContext.Current.Session["api"];
            InstagramProfile result = null;

            if (api == null || !api.IsUserAuthenticated)
            {
                return(null);
            }

            var user = await api.GetCurrentUserAsync();

            result = new InstagramProfile
            {
                FullName        = user.Value.FullName,
                Username        = user.Value.UserName,
                ProfileImageUri = user.Value.ProfilePicture
            };



            return(result);
        }
        public async Task <IHttpActionResult> Login([FromBody] UserModel user)
        {
            UserSessionData data = new UserSessionData();


            data.UserName = user.Username;
            data.Password = user.Password;


            HttpClientHandler handler = new HttpClientHandler()
            {
                Proxy    = new WebProxy(),
                UseProxy = true,
            };


            IInstaApi api = InstaApiBuilder.CreateBuilder()
                            .UseHttpClientHandler(handler)
                            .SetUser(data)
                            .Build();

            var login_request = await api.LoginAsync();



            if (login_request.Succeeded)
            {
                var user_data = await api.GetCurrentUserAsync();

                HttpContext.Current.Session["api"] = api;
                return(Ok());
            }
            else
            {
                return(BadRequest());
            }
        }
Esempio n. 23
0
        public async Task DoShow()
        {
            // get currently logged in user
            var currentUser = await _instaApi.GetCurrentUserAsync();

            Console.WriteLine(
                $"Logged in: username - {currentUser.Value.UserName}, full name - {currentUser.Value.FullName}");

            // get self followers
            var followers = await _instaApi.GetUserFollowersAsync(currentUser.Value.UserName, 5);

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

            // get self folling
            var following = await _instaApi.GetUserFollowingAsync(currentUser.Value.UserName, 5);

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

            // get self user's media, latest 5 pages
            var currentUserMedia = await _instaApi.GetUserMediaAsync(currentUser.Value.UserName, 5);

            if (currentUserMedia.Succeeded)
            {
                Console.WriteLine($"Media count [{currentUser.Value.UserName}]: {currentUserMedia.Value.Count}");
                foreach (var media in currentUserMedia.Value)
                {
                    ConsoleUtils.PrintMedia("Self media", media, _maxDescriptionLength);
                }
            }

            //get user time line feed, latest 5 pages
            var userFeed = await _instaApi.GetUserTimelineFeedAsync(5);

            if (userFeed.Succeeded)
            {
                Console.WriteLine(
                    $"Feed items (in {userFeed.Value.MediaItemsCount} pages) [{currentUser.Value.UserName}]: {userFeed.Value.Medias.Count}");
                foreach (var media in userFeed.Value.Medias)
                {
                    ConsoleUtils.PrintMedia("Feed media", media, _maxDescriptionLength);
                }
                //like first 10 medias from user timeline feed
                foreach (var media in userFeed.Value.Medias.Take(10))
                {
                    var likeResult = await _instaApi.LikeMediaAsync(media.InstaIdentifier);

                    var resultString = likeResult.Value ? "liked" : "not liked";
                    Console.WriteLine($"Media {media.Code} {resultString}");
                }
            }

            // get tag feed, latest 5 pages
            var tagFeed = await _instaApi.GetTagFeedAsync("quadcopter", 5);

            if (tagFeed.Succeeded)
            {
                Console.WriteLine(
                    $"Tag feed items (in {tagFeed.Value.MediaItemsCount} pages) [{currentUser.Value.UserName}]: {tagFeed.Value.Medias.Count}");
                foreach (var media in tagFeed.Value.Medias)
                {
                    ConsoleUtils.PrintMedia("Tag feed", media, _maxDescriptionLength);
                }
            }
        }
Esempio n. 24
0
        async void MassLike()
        {
            Stat        = true;
            userInfoLog = await api.GetCurrentUserAsync();

            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Масслайкинг запущен"));
            EventFromMyClass(this,
                             new MyEventMessage(
                                 $"[{userInfoLog.Value.UserName}][{DateTime.Now:HH:mm:ss}][{Info()}] Загружаю базу."));
            try
            {
                foreach (string str in File.ReadAllLines(setting.FileNameBase))
                {
                    try
                    {
                        usersID.Add(Convert.ToInt64(str));
                        usersIDcopy.Add(Convert.ToInt64(str));
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            catch (Exception e)
            {
                EventFromMyClass(this,
                                 new MyEventMessage(
                                     $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] ОШИБКА: {e.Message}"));
            }
            EventUpdateGrid(this, new UpdateGridEvent(
                                $"{userInfoLog.Value.UserName}:Лайкинг:{CountLikes}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                $"Выполняется"));

            foreach (long id in usersID)
            {
                try
                {
                    if (_source == null || _source.IsCancellationRequested)
                    {
                        break;
                    }

                    if (setting.ChekedSkipSubscriber)
                    {
                        var x = await api.GetCurrentUserFollowersAsync(PaginationParameters.MaxPagesToLoad(10));

                        var o = new InstaUserShort();
                        o.Pk = id;
                        if (x.Value.IndexOf(o) != -1)
                        {
                            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Подписчик с id: {id} пропущен"));
                            usersIDcopy.Remove(id);
                            Thread.Sleep(500);
                            continue;
                        }
                    }

                    int pages    = (int)setting.LikeAtUserMax;
                    var userInfo = await api.GetUserInfoByIdAsync(id);

                    Thread.Sleep(100);
                    var media = await api.GetUserMediaAsync(
                        userInfo.Value.Username,
                        PaginationParameters.MaxPagesToLoad(pages % 18 == 0 ? pages : pages + 1));     //Учет загруки страаниц

                    var mediaList = media.Value.ToList();

                    int random = rnd.Next((int)setting.LikeAtUserMin - 1, (int)setting.LikeAtUserMax);

                    for (int i = 0; i < random; i++)                                                                                                               //Учет кол-во лайков на пользователя
                    {
                        if (mediaList.Count > i && setting.LikeUnderPublicMin <= mediaList[i].LikesCount && mediaList[i].LikesCount <= setting.LikeUnderPublicMax) //Учет настройки лайков под публикацией
                        {
                            if (_source == null || _source.IsCancellationRequested)
                            {
                                break;
                            }

                            await api.LikeMediaAsync(mediaList[i].Pk);

                            CountLikes++;
                            CountPause++;

                            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Поставил лайк пользователю {userInfo.Value.Username}. Кол-во лайков: {CountLikes}"));
                            EventUpdateGrid(this, new UpdateGridEvent(
                                                $"{userInfoLog.Value.UserName}:Лайкинг:{CountLikes}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                $"Выполняется"));

                            if (setting.ChekedDeleteInBaseAfterLike)
                            {
                                usersIDcopy.Remove(id);
                            }

                            Delay();

                            if (setting.ChekedPause)
                            {
                                if (CountPause >= setting.PauseLimit)
                                {
                                    CountPause = 0;
                                    EventUpdateGrid(this, new UpdateGridEvent($"{userInfoLog.Value.UserName}:Лайкинг:{CountLikes}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                                              $"Пауза"));
                                    EventFromMyClass(this,
                                                     new MyEventMessage(
                                                         $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Пауза на " +
                                                         setting.PauseTime + " минут "));
                                    if (timer != null)
                                    {
                                        timer.Dispose();
                                    }
                                    timer = new Timer(CancelDelay, null, 60000 * (int)setting.PauseTime, Timeout.Infinite);
                                    ew.Reset();
                                    ew.WaitOne();
                                }
                            }
                        }
                        else
                        {
                            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Недостаточно лайков под постом пользователя {userInfo.Value.Username}. Пропуск"));
                            if (setting.ChekedDeleteInBaseAfterLike)
                            {
                                usersIDcopy.Remove(id);
                            }
                            Thread.Sleep(1000);
                        }
                    }
                }
                catch (Exception e)
                {
                    EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] ОШИБКА : {e.Message}"));
                    continue;
                }
            }
            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Выполнено"));
            EventUpdateGrid(this, new UpdateGridEvent(
                                $"{userInfoLog.Value.UserName}:Лайкинг:{CountLikes}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                $"Завершено"));
            Stat = false;
            Save();
        }
Esempio n. 25
0
        async void ClearBots()
        {
            Stat        = true;
            userInfoLog = await api.GetCurrentUserAsync();

            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Чистка от ботов запущена"));
            try
            {
                if (setting.FileNameExceptionId.Length != 0)
                {
                    string[] stringID = System.IO.File.ReadAllLines(setting.FileNameExceptionId);
                    foreach (string str in stringID)
                    {
                        try
                        {
                            usersID.Add(Convert.ToInt64(str));
                        }
                        catch { continue; }
                    }
                }
            }
            catch (Exception e)
            {
                EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] ОШИБКА: {e.Message}"));
            }

            var userInfo = await api.GetCurrentUserAsync();

            IResult <InstaUserShortList> x = null;

            if (setting.WhomClear.Equals("Подписчиков"))
            {
                x = await api.GetUserFollowersAsync(userInfo.Value.UserName, PaginationParameters.MaxPagesToLoad(2));
            }
            if (setting.WhomClear.Equals("Подписки"))
            {
                x = await api.GetUserFollowingAsync(userInfo.Value.UserName, PaginationParameters.MaxPagesToLoad(2));
            }
            if (x.Succeeded)
            {
                count = x.Value.Count;
                EventUpdateGrid(this, new UpdateGridEvent(
                                    $"{userInfoLog.Value.UserName}:Чистка от ботов:{CountBlock}/{x.Value.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                    $"Выполняется"));

                foreach (InstaUserShort user in x.Value)
                {
                    try
                    {
                        if (_source == null || _source.IsCancellationRequested)
                        {
                            break;
                        }


                        if (usersID.Count != 0) //Учет не отписки от определнных пользователей
                        {
                            bool flag = false;
                            foreach (long id in usersID)
                            {
                                if (user.Pk == id)
                                {
                                    EventFromMyClass(this,
                                                     new MyEventMessage(
                                                         $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Пользователь {user.UserName} пропущен. Запрет на отписку."));

                                    Delay();

                                    flag = true;
                                    break;
                                }
                            }

                            if (flag)
                            {
                                continue;
                            }
                        }

                        if (setting.LimitBlock <= CountBlock) //Учет лимита блокировок
                        {
                            EventFromMyClass(this,
                                             new MyEventMessage(
                                                 $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Превышен лимит блокировок. Останавливаю процесс."));
                            EventUpdateGrid(this, new UpdateGridEvent(
                                                $"{userInfoLog.Value.UserName}:Чистка от ботов:{CountBlock}/{x.Value.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                $"Завершено"));
                            return;
                        }

                        if (setting.ChekedPause) //Учет паузы
                        {
                            if (setting.PauseLimit <= CountPause)
                            {
                                CountPause = 0;
                                EventFromMyClass(this,
                                                 new MyEventMessage(
                                                     $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Пауза на " +
                                                     setting.PauseTime + " минут"));
                                EventUpdateGrid(this, new UpdateGridEvent(
                                                    $"{userInfoLog.Value.UserName}:Чистка от ботов:{CountBlock}/{x.Value.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                    $"Пауза"));
                                if (timer != null)
                                {
                                    timer.Dispose();
                                }
                                timer = new Timer(CancelDelay, null, 60000 * (int)setting.PauseTime, Timeout.Infinite);
                                ew.Reset();
                                ew.WaitOne();
                            }
                        }


                        var info = await api.GetUserInfoByIdAsync(user.Pk);

                        if (info.Succeeded == false)
                        {
                            Thread.Sleep(500);
                            continue;
                        }

                        if (setting.CheckedNoAvatarUser) //Если нет автарки
                        {
                            if (info.Value.HasAnonymousProfilePicture)
                            {
                                await api.BlockUserAsync(user.Pk);

                                CountBlock++;
                                CountPause++;
                                EventFromMyClass(this,
                                                 new MyEventMessage(
                                                     $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Заблокирован пользователя с ником: {user.UserName}. Количество блокировок: {CountBlock}"));
                                EventUpdateGrid(this, new UpdateGridEvent(
                                                    $"{userInfoLog.Value.UserName}:Чистка от ботов:{CountBlock}/{x.Value.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                    $"Выполняется"));

                                if (!setting.ChekedUserBlock)
                                {
                                    await api.UnBlockUserAsync(user.Pk);

                                    EventFromMyClass(this,
                                                     new MyEventMessage(
                                                         $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Разблокирован пользователь с ником: {user.UserName}"));
                                }

                                Delay(); //Учет задержки
                                continue;
                            }
                        }

                        if (setting.CheckedPublicCountLess) //Публикаций меньше
                        {
                            int countPublic = Convert.ToInt32(info.Value.MediaCount);
                            if (countPublic < setting.PublicCountLess)
                            {
                                await api.BlockUserAsync(user.Pk);

                                CountBlock++;
                                CountPause++;
                                EventFromMyClass(this,
                                                 new MyEventMessage(
                                                     $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Заблокирован пользователь с ником: {user.UserName}. Количество блокировок: {CountBlock}"));
                                EventUpdateGrid(this, new UpdateGridEvent(
                                                    $"{userInfoLog.Value.UserName}:Чистка от ботов:{CountBlock}/{x.Value.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                    $"Выполняется"));
                                if (!setting.ChekedUserBlock)
                                {
                                    await api.UnBlockUserAsync(user.Pk);

                                    EventFromMyClass(this,
                                                     new MyEventMessage(
                                                         $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Разблокирован пользователь с ником: {user.UserName}"));
                                }

                                Delay(); //Учет задержки
                                continue;
                            }
                        }

                        if (setting.ChekedFollowsCountLess)
                        {
                            int countFollower = Convert.ToInt32(info.Value.FollowerCount);
                            if (countFollower < setting.FollowsCountLess)
                            {
                                await api.BlockUserAsync(user.Pk);

                                CountBlock++;
                                CountPause++;
                                EventFromMyClass(this,
                                                 new MyEventMessage(
                                                     $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Заблокирован пользователь с ником: {user.UserName}. Количество блокировок: {CountBlock}"));
                                EventUpdateGrid(this, new UpdateGridEvent(
                                                    $"{userInfoLog.Value.UserName}:Чистка от ботов:{CountBlock}/{x.Value.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                    $"Выполняется"));
                                if (!setting.ChekedUserBlock)
                                {
                                    await api.UnBlockUserAsync(user.Pk);

                                    EventFromMyClass(this,
                                                     new MyEventMessage(
                                                         $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Разблокирован пользователь с ником: {user.UserName}"));
                                }

                                Delay(); //Учет задержки
                                continue;
                            }
                        }

                        if (setting.ChekedSubscriptionsLess)
                        {
                            int countSubscriptions = Convert.ToInt32(info.Value.FollowingCount);
                            if (countSubscriptions < setting.SubscriptionsLess)
                            {
                                await api.BlockUserAsync(user.Pk);

                                CountBlock++;
                                CountPause++;
                                EventFromMyClass(this,
                                                 new MyEventMessage(
                                                     $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Заблокирован пользователь с ником: {user.UserName}. Количество блокировок: {CountBlock}"));
                                EventUpdateGrid(this, new UpdateGridEvent(
                                                    $"{userInfoLog.Value.UserName}:Чистка от ботов:{CountBlock}/{x.Value.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                    $"Выполняется"));
                                if (!setting.ChekedUserBlock)
                                {
                                    await api.UnBlockUserAsync(user.Pk);

                                    EventFromMyClass(this,
                                                     new MyEventMessage(
                                                         $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Разблокирован пользователь с ником: {user.UserName}"));
                                }

                                Delay(); //Учет задержки
                                continue;
                            }
                        }

                        if (setting.ChekedSubscriptionsMore)
                        {
                            int countSubscriptions = Convert.ToInt32(info.Value.FollowingCount);
                            if (countSubscriptions > setting.SubscriptionMore)
                            {
                                await api.BlockUserAsync(user.Pk);

                                CountBlock++;
                                CountPause++;
                                EventFromMyClass(this,
                                                 new MyEventMessage(
                                                     $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Заблокирован пользователь с ником: {user.UserName}. Количество блокировок: {CountBlock}"));
                                EventUpdateGrid(this, new UpdateGridEvent(
                                                    $"{userInfoLog.Value.UserName}:Чистка от ботов:{CountBlock}/{x.Value.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                    $"Выполняется"));
                                if (!setting.ChekedUserBlock)
                                {
                                    await api.UnBlockUserAsync(user.Pk);

                                    EventFromMyClass(this,
                                                     new MyEventMessage(
                                                         $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Разблокирован пользователь с ником: {user.UserName}"));
                                }

                                Delay(); //Учет задержки
                                continue;
                            }
                        }

                        Thread.Sleep(1000);
                    }

                    catch (Exception e)
                    {
                        EventFromMyClass(this,
                                         new MyEventMessage(
                                             $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] ОШИБКА: {e.Message}"));
                    }
                }
            }

            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{ DateTime.Now.ToString("HH:mm:ss")}] Выполнено."));
            EventUpdateGrid(this, new UpdateGridEvent(
                                $"{userInfoLog.Value.UserName}:Чистка от ботов:{CountBlock}/{x.Value.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                $"Завершено"));
            Stat = false;
        }
Esempio n. 26
0
        async System.Threading.Tasks.Task StartSubscribe()
        {
            Stat        = true;
            userInfoLog = await api.GetCurrentUserAsync();

            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now:HH:mm:ss}][{Info()}] Массфоловинг запущен."));
            EventFromMyClass(this,
                             new MyEventMessage(
                                 $"[{userInfoLog.Value.UserName}][{DateTime.Now:HH:mm:ss}][{Info()}] Загружаю базу."));
            try
            {
                string[] stringID = System.IO.File.ReadAllLines(setting.FileNameBaseId);
                foreach (string str in stringID)
                {
                    try
                    {
                        usersID.Add(Convert.ToInt64(str));
                        usersIDcopy.Add(Convert.ToInt64(str));
                    }
                    catch { continue; }
                }
                EventFromMyClass(this,
                                 new MyEventMessage(
                                     $"[{userInfoLog.Value.UserName}][{DateTime.Now:HH:mm:ss}][{Info()}] База загружена."));
            }
            catch (Exception e)
            {
                EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] ОШИБКА: {e.Message}"));
            }

            EventFromMyClass(this,
                             new MyEventMessage(
                                 $"[{userInfoLog.Value.UserName}][{DateTime.Now:HH:mm:ss}][{Info()}] Начинаю подписку."));
            foreach (long id in usersID)
            {
                try
                {
                    userInfoLog = await api.GetCurrentUserAsync();

                    var userInfo = await api.GetUserInfoByIdAsync(id);

                    if (_source == null || _source.IsCancellationRequested)
                    {
                        break;
                    }

                    if (setting.ChekedSkipSubscriber) //Пропуск подписчиков
                    {
                        var x = await api.GetCurrentUserFollowersAsync(PaginationParameters.MaxPagesToLoad(100));

                        var o = new InstaUserShort();
                        o.Pk = id;
                        if (x.Value.IndexOf(o) != -1)
                        {
                            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Подписчик с ником: {userInfo.Value.Username} пропущен"));
                            if (setting.ChekedDeleteAdfter)
                            {
                                usersIDcopy.Remove(id);
                            }

                            Delay();
                            continue;
                        }
                    }

                    if (!setting.ChekedSendPrivateUser) //Учет приватных пользователей
                    {
                        if (userInfo.Value.IsPrivate)
                        {
                            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Приватный аккаунт {userInfo.Value.Username} пропущен"));
                            Delay();
                            continue;
                        }
                    }

                    await api.FollowUserAsync(id); //Подписка

                    CountSubscribe++;
                    CountPause++;

                    EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] " +
                                                              $"Подписался на пользователя с ником {userInfo.Value.Username}. " +
                                                              $"Количество подписок: {CountSubscribe}"));

                    EventUpdateGrid(this, new UpdateGridEvent($"{userInfoLog.Value.UserName}:Подписка:{CountSubscribe}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                              $"Выполняется"));

                    Delay();
                    ew.WaitOne();

                    if (setting.ChekedLikingBySubscribe) //Учет лайков при подписке
                    {
                        int pages = setting.LikingMax;
                        var media = await api.GetUserMediaAsync(
                            userInfo.Value.Username,
                            PaginationParameters.MaxPagesToLoad(pages % 18 == 0 ? pages : pages + 1)); //Учет загруки страниц

                        var mediaList = media.Value.ToList();

                        int random = rnd.Next(setting.LikingMin, setting.LikingMax + 1);

                        for (int i = 0; i < random; i++)
                        {
                            if (_source == null || _source.IsCancellationRequested)
                            {
                                break;
                            }

                            await api.LikeMediaAsync(mediaList[i].Pk);

                            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Поставил лайк пользователю с ником {userInfo.Value.Username}"));

                            int randomLikeDelay = rnd.Next(setting.DelayLikeMin, setting.DelayLikeMax + 1);
                            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Задержка на {randomLikeDelay} сек"));
                            if (timer != null)
                            {
                                timer.Dispose();
                            }
                            timer = new Timer(CancelDelay, null, 1000 * randomLikeDelay, Timeout.Infinite);
                            ew.Reset();
                            ew.WaitOne();
                        }
                    }

                    if (setting.ChekedDeleteAdfter)
                    {
                        usersIDcopy.Remove(id);
                    }

                    if (setting.ChekedPause) //Учет паузы
                    {
                        if (CountPause >= setting.PauseLimit)
                        {
                            CountPause = 0;
                            EventUpdateGrid(this, new UpdateGridEvent($"{userInfoLog.Value.UserName}:Подписка:{CountSubscribe}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                                      $"Пауза"));
                            EventFromMyClass(this,
                                             new MyEventMessage(
                                                 $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Пауза на " +
                                                 setting.PauseTime + " минут "));
                            if (timer != null)
                            {
                                timer.Dispose();
                            }
                            timer = new Timer(CancelDelay, null, 60000 * setting.PauseTime, Timeout.Infinite);
                            ew.Reset();
                            ew.WaitOne();
                        }
                    }

                    if (CountSubscribe >= setting.LimitSubscribe) //Учет лимита подписок
                    {
                        EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now:HH:mm:ss}][{Info()}] Превышен лимит подписок"));
                        EventFromMyClass(this,
                                         new MyEventMessage(
                                             $"[{userInfoLog.Value.UserName}][{DateTime.Now:HH:mm:ss}] Выполнено"));
                        EventUpdateGrid(this, new UpdateGridEvent(
                                            $"{userInfoLog.Value.UserName}:Подписка:{CountSubscribe}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                            $"Завершено"));
                        return;
                    }
                }
                catch (Exception e)
                {
                    EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now:HH:mm:ss}][{Info()}] ОШИБКА: {e.Message}"));
                }
            }
            EventFromMyClass(this,
                             new MyEventMessage(
                                 $"[{userInfoLog.Value.UserName}][{DateTime.Now:HH:mm:ss}][{Info()}] Задача завершена"));
            EventUpdateGrid(this, new UpdateGridEvent(
                                $"{userInfoLog.Value.UserName}:Подписка:{CountSubscribe}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                $"Завершено"));
            Stat = false;
            Save();
        }
Esempio n. 27
0
        async void UnSubscribeToList(IInstaApi api, SettingTaskUnSubscribe setting)
        {
            userInfoLog = await api.GetCurrentUserAsync();

            EventFromMyClass(this, new MyEventMessage($"[{(await api.GetCurrentUserAsync()).Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Массотписка запущена"));
            EventUpdateGrid(this, new UpdateGridEvent($"{userInfoLog.Value.UserName}:Отписка:{CountUnSubscribe}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                      $"Выполняется"));
            try
            {
                string[] stringID = System.IO.File.ReadAllLines(setting.FileNameBaseId);
                foreach (string str in stringID)
                {
                    try
                    {
                        usersID.Add(Convert.ToInt64(str));
                        usersIDcopy.Add(Convert.ToInt64(str));
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            catch (Exception e)
            {
                EventFromMyClass(this, new MyEventMessage($"[{DateTime.Now.ToString("HH:mm:ss")}] ОШИБКА: {e.Message} {e.TargetSite} {DateTime.Now}"));
            }

            foreach (long id in usersID)
            {
                try
                {
                    if (_source == null || _source.IsCancellationRequested)
                    {
                        break;
                    }

                    var userInfo = await api.GetUserInfoByIdAsync(id);

                    if (setting.FileNameBaseId != null && setting.FileNameDontUnSubscribeId.Length != 0) //Учет не отписки от определнных пользователей
                    {
                        var stringId = setting.FileNameDontUnSubscribeId.Split(' ');
                        foreach (string idDont in stringId)
                        {
                            if (id == Convert.ToInt64(idDont))
                            {
                                EventFromMyClass(null, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Пропущен пользователь {userInfo.Value.Username}. Является исключением"));
                                Delay();
                                continue;
                            }
                        }
                    }

                    if (setting.ChekedUnSubscribeBlock) //Учёт отписки через блокировку
                    {
                        await api.BlockUserAsync(id);
                    }
                    else
                    {
                        await api.UnFollowUserAsync(id);
                    }
                    CountUnSubscribe++;
                    CountPause++;
                    EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Отписался от пользователя с ником {userInfo.Value.Username}. Kоличество отписок: {CountUnSubscribe}"));

                    EventUpdateGrid(this, new UpdateGridEvent($"{userInfoLog.Value.UserName}:Отписка:{CountUnSubscribe}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                              $"Выполняется"));

                    if (_source == null || _source.IsCancellationRequested)
                    {
                        break;
                    }

                    Delay();

                    if (setting.LimitUnSubscribe <= CountUnSubscribe) //Учет лимита отписок
                    {
                        EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Превышен лимит подписок"));
                        EventUpdateGrid(this, new UpdateGridEvent($"{userInfoLog.Value.UserName}:Отписка:{CountUnSubscribe}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                                  $"Завершено"));
                        Save();
                        return;
                    }

                    if (setting.CheckedPause) //Учет паузы
                    {
                        if (setting.PauseLimit <= CountPause)
                        {
                            CountPause = 0;
                            EventUpdateGrid(this, new UpdateGridEvent($"{userInfoLog.Value.UserName}:Отписка:{CountUnSubscribe}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                                      $"Пауза"));
                            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Пауза на " + setting.PauseTime + " минут"));
                            if (timer != null)
                            {
                                timer.Dispose();
                            }
                            timer = new Timer(CancelDelay, null, 60000 * setting.PauseTime, Timeout.Infinite);
                            ew.Reset();
                            ew.WaitOne();
                        }
                    }
                }
                catch (Exception e)
                {
                    EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] ОШИБКА: {e.Message}"));
                }
            }
            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Выполнено"));
            EventUpdateGrid(this, new UpdateGridEvent($"{userInfoLog.Value.UserName}:Отписка:{CountUnSubscribe}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                      $"Завершено"));
            Save();
            Stat = false;
        }
Esempio n. 28
0
        async void UnSubscribeDontFollow(IInstaApi api, SettingTaskUnSubscribe setting)
        {
            userInfoLog = await api.GetCurrentUserAsync();

            var follow = await api.GetCurrentUserFollowersAsync(PaginationParameters.MaxPagesToLoad(2));

            var x = await api.GetUserFollowingAsync(userInfoLog.Value.UserName, PaginationParameters.MaxPagesToLoad(2));

            var z = await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk);

            EventUpdateGrid(this, new UpdateGridEvent(
                                $"{userInfoLog.Value.UserName}:Отписка(кто не подписан):{CountUnSubscribe}/{z.Value.FollowingCount}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                $"Выполняется"));
            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Массотписка запущена"));

            foreach (InstaUserShort user in x.Value)
            {
                try
                {
                    if (_source == null || _source.IsCancellationRequested)
                    {
                        break;
                    }


                    if (setting.FileNameBaseId != null && setting.FileNameDontUnSubscribeId.Length != 0) //Учет не отписки от определнных пользователей
                    {
                        var stringId = setting.FileNameDontUnSubscribeId.Split(' ');
                        foreach (string id in stringId)
                        {
                            if (user.Pk == Convert.ToInt64(id))
                            {
                                EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Пропущен пользователь {user.UserName}. Является исключением"));
                                Delay();
                                continue;
                            }
                        }
                    }
                    var userShort = new InstaUserShort();
                    userShort.Pk = user.Pk;

                    if (follow.Value.IndexOf(userShort) == -1)
                    {
                        if (setting.ChekedUnSubscribeBlock) //Учёт отписки через блокировку
                        {
                            await api.BlockUserAsync(user.Pk);
                        }
                        else
                        {
                            await api.UnFollowUserAsync(user.Pk);
                        }
                        CountUnSubscribe++;
                        CountPause++;
                        EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Отписался от пользователя с ником: {user.UserName}. Kоличество отписок: {CountUnSubscribe}"));
                        EventUpdateGrid(this, new UpdateGridEvent(
                                            $"{userInfoLog.Value.UserName}:Отписка(кто не подписан):{CountUnSubscribe}/{z.Value.FollowingCount}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                            $"Выполняется"));

                        if (_source == null || _source.IsCancellationRequested)
                        {
                            break;
                        }

                        Delay();                                          // Учет задержки

                        if (CountUnSubscribe >= setting.LimitUnSubscribe) //Учет лимита отписок
                        {
                            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{ DateTime.Now.ToString("HH:mm:ss") }] Превышен лимит подписок"));
                            EventUpdateGrid(this, new UpdateGridEvent(
                                                $"{userInfoLog.Value.UserName}:Отписка(кто не подписан):{CountUnSubscribe}/{z.Value.FollowingCount}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                $"Завершено"));
                            return;
                        }

                        if (setting.CheckedPause) //Учет паузы
                        {
                            if (setting.PauseLimit <= CountUnSubscribe)
                            {
                                CountPause = 0;
                                EventUpdateGrid(this, new UpdateGridEvent(
                                                    $"{userInfoLog.Value.UserName}:Отписка(кто не подписан):{CountUnSubscribe}/{z.Value.FollowingCount}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                    $"Пауза"));
                                EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Пауза на " + setting.PauseTime + " минут"));
                                if (timer != null)
                                {
                                    timer.Dispose();
                                }
                                timer = new Timer(CancelDelay, null, 60000 * setting.PauseTime, Timeout.Infinite);
                                ew.Reset();
                                ew.WaitOne();
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] ОШИБКА: {e.Message}"));
                }
            }
            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] Выполнено"));
            EventUpdateGrid(this, new UpdateGridEvent(
                                $"{userInfoLog.Value.UserName}:Отписка(кто не подписан):{CountUnSubscribe}/{z.Value.FollowingCount}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                $"Завершено"));
            Stat = false;
        }
Esempio n. 29
0
        public async Task DoShow()
        {
            // get currently logged in user
            var currentUser = await InstaApi.GetCurrentUserAsync();

            Console.WriteLine(
                $"Logged in: username - {currentUser.Value.UserName}, full name - {currentUser.Value.FullName}");

            // get followers of user 'elonmusk'
            var followers = await InstaApi.UserProcessor.GetUserFollowersAsync("elonmusk",
                                                                               PaginationParameters.MaxPagesToLoad(5)
                                                                               .StartFromMaxId("AQAC8w90POWyM7zMjHWmO9vsZNL_TuLp6FR506_C_y3fUAjlCclrIDI2RdSGvur5UjLrq4Cq7NJN8QUhHG-vpbT6pCLB5X9crDxBOHUEuNJ4fA"));

            Console.WriteLine($"Count of followers [elonmusk]:{followers.Value.Count}");
            Console.WriteLine($"Next id will be: '{followers.Value.NextMaxId}'");

            // get self folling
            var following = await InstaApi.UserProcessor.GetUserFollowingAsync(currentUser.Value.UserName, PaginationParameters.MaxPagesToLoad(5));

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

            // get self user's media, latest 5 pages
            var currentUserMedia = await InstaApi.UserProcessor.GetUserMediaAsync(currentUser.Value.UserName, PaginationParameters.MaxPagesToLoad(5));

            if (currentUserMedia.Succeeded)
            {
                Console.WriteLine($"Media count [{currentUser.Value.UserName}]: {currentUserMedia.Value.Count}");
                foreach (var media in currentUserMedia.Value)
                {
                    ConsoleUtils.PrintMedia("Self media", media, _maxDescriptionLength);
                }
            }

            //get user time line feed, latest 5 pages
            var userFeed = await InstaApi.FeedProcessor.GetUserTimelineFeedAsync(PaginationParameters.MaxPagesToLoad(5));

            if (userFeed.Succeeded)
            {
                Console.WriteLine(
                    $"Feed items (in {userFeed.Value.MediaItemsCount} pages) [{currentUser.Value.UserName}]: {userFeed.Value.Medias.Count}");
                foreach (var media in userFeed.Value.Medias)
                {
                    ConsoleUtils.PrintMedia("Feed media", media, _maxDescriptionLength);
                }
                //like first 10 medias from user timeline feed
                foreach (var media in userFeed.Value.Medias.Take(10))
                {
                    var likeResult = await InstaApi.MediaProcessor.LikeMediaAsync(media.InstaIdentifier);

                    var resultString = likeResult.Value ? "liked" : "not liked";
                    Console.WriteLine($"Media {media.Code} {resultString}");
                }
            }

            // get tag feed, latest 5 pages
            var tagFeed = await InstaApi.FeedProcessor.GetTagFeedAsync("quadcopter", PaginationParameters.MaxPagesToLoad(5));

            if (tagFeed.Succeeded)
            {
                Console.WriteLine(
                    $"Tag feed items (in {tagFeed.Value.MediaItemsCount} pages) [{currentUser.Value.UserName}]: {tagFeed.Value.Medias.Count}");
                foreach (var media in tagFeed.Value.Medias)
                {
                    ConsoleUtils.PrintMedia("Tag feed", media, _maxDescriptionLength);
                }
            }
        }
Esempio n. 30
0
        async System.Threading.Tasks.Task MassDirect()
        {
            Stat        = true;
            userInfoLog = await api.GetCurrentUserAsync();

            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Рассылка сообщений запущена"));
            EventFromMyClass(this,
                             new MyEventMessage(
                                 $"[{userInfoLog.Value.UserName}][{DateTime.Now:HH:mm:ss}][{Info()}] Загружаю базу."));
            try
            {
                string[] stringID = System.IO.File.ReadAllLines(setting.FileNameBaseId);
                foreach (string str in stringID)
                {
                    try
                    {
                        usersID.Add(Convert.ToInt64(str));
                        usersIDcopy.Add(Convert.ToInt64(str));
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            catch (Exception e)
            {
                EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}] ОШИБКА: {e.Message}"));
            }
            EventUpdateGrid(this, new UpdateGridEvent($"{userInfoLog.Value.UserName}:МассДирект:{CountMessage}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                      $"Выполняется"));

            foreach (long id in usersID)
            {
                try
                {
                    if (_source == null || _source.IsCancellationRequested)
                    {
                        break;
                    }

                    int random = rnd.Next(0, setting.Messages.Count);
                    var x      = await api.SendDirectMessage(id.ToString(), null, setting.Messages[random]);

                    CountMessage++;
                    CountPause++;
                    EventFromMyClass(this,
                                     new MyEventMessage(
                                         $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Oтправил сообщение пользователю {(await api.GetUserInfoByIdAsync(id)).Value.Username}. Kоличество сообщений: {CountMessage}"));
                    EventUpdateGrid(this, new UpdateGridEvent(
                                        $"{userInfoLog.Value.UserName}:МассДирект:{CountMessage}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                        $"Выполняется"));
                    if (setting.ChekedDeleteBase)
                    {
                        usersIDcopy.Remove(id);
                    }
                    Delay();

                    if (setting.CheckedPause) //Учет паузы
                    {
                        if (setting.PauseLimit <= CountPause)
                        {
                            CountPause = 0;
                            EventFromMyClass(this,
                                             new MyEventMessage(
                                                 $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Пауза на " +
                                                 setting.PauseTime + " минут"));
                            EventUpdateGrid(this, new UpdateGridEvent(
                                                $"{userInfoLog.Value.UserName}:МассДирект:{CountMessage}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                $"Пауза"));
                            if (timer != null)
                            {
                                timer.Dispose();
                            }
                            timer = new Timer(CancelDelay, null, 60000 * setting.PauseTime, Timeout.Infinite);
                            ew.Reset();
                            ew.WaitOne();
                        }
                    }
                }
                catch (Exception e)
                {
                    EventFromMyClass(this,
                                     new MyEventMessage(
                                         $"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] ОШИБКА: {e.Message}"));
                }
            }

            EventFromMyClass(this, new MyEventMessage($"[{userInfoLog.Value.UserName}][{DateTime.Now.ToString("HH:mm:ss")}][{Info()}] Выполнено"));
            EventUpdateGrid(this, new UpdateGridEvent($"{userInfoLog.Value.UserName}:МассДирект:{CountMessage}/{usersID.Count}:{UpdateInfoUser(await api.GetUserInfoByIdAsync(userInfoLog.Value.Pk))}:" +
                                                      $"Завершено"));
            Stat = false;
            Save();
        }