Beispiel #1
0
        /// <summary>
        /// Выйти из всех групп
        /// </summary>
        /// <param name="user">Пользователь</param>
        /// <returns></returns>
        static bool Groups(User user, CancellationToken cancellationToken)
        {
            string header = "Выйти из всех групп";

            PrintConsole.Header(header);

            Backup.Groups.Data[] list = Backup.Groups.GetGroups(user)[0] as Backup.Groups.Data[];
            int i = 0;

            try
            {
                for (; i < list.Length; i++)
                {
                    PrintConsole.Header(header);
                    PrintConsole.Print($"Покинуто {i} сообществ из {list.Length}.", MenuType.InfoHeader);
                    PrintConsole.Print("Для отмены нажмите [SPACE].", MenuType.Warning);

                    user.GetApi().Groups.Leave(list[i].id);

                    cancellationToken.ThrowIfCancellationRequested();
                }

                PrintConsole.Print("Все сообщества покинуты.", MenuType.InfoHeader);
                BackLine.Continue();
                return(true);
            }
            catch (Exception e)
            {
                return(IfCancel(new List <string>()
                {
                    header, $"{i}", $"{list.Length}"
                }));
            }
        }
Beispiel #2
0
        /// <summary>
        /// Удалить все записи со стены
        /// </summary>
        /// <param name="user">Пользователь</param>
        static bool Board(User user, CancellationToken cancellationToken)
        {
            string header = "Очистить стену";

            PrintConsole.Header(header);
            var posts = user.GetApi().Wall.Get(new WallGetParams());
            int i     = 0;

            try
            {
                for (; i < posts.WallPosts.Count; i++)
                {
                    PrintConsole.Header(header);
                    PrintConsole.Header($"Удалено {i} из {posts.TotalCount} записей");
                    PrintConsole.Print("Для отмены нажмите [SPACE].", MenuType.Warning);

                    user.GetApi().Wall.Delete(posts.WallPosts[i].OwnerId, posts.WallPosts[i].Id);

                    cancellationToken.ThrowIfCancellationRequested();
                }

                PrintConsole.Print("Все записи удалены.", MenuType.InfoHeader);
                BackLine.Continue();
                return(true);
            }
            catch (Exception ex)
            {
                return(IfCancel(new List <string>()
                {
                    header, $"{i}", $"{posts.TotalCount}"
                }));
            }
        }
Beispiel #3
0
        /// <summary>
        /// Удалить всю музыку
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        static bool Music(User user, CancellationToken cancellationToken)
        {
            string header = "Удалить всю музыку";

            PrintConsole.Header(header);

            int i    = 0;
            var list = Get.GetList(new AnyData.Data()
            {
                api = user.GetApi(), id = user.GetId(), type = Get.Type.Profile, audios = null
            });

            try
            {
                for (; i < list.Length; i++)
                {
                    PrintConsole.Header(header);
                    PrintConsole.Print($"Удалено {i} из {list.Length}.", MenuType.InfoHeader);
                    PrintConsole.Print("Для отмены нажмите [SPACE].", MenuType.Warning);

                    user.GetApi().Audio.Delete(list[i].id.Value, list[i].owner_id.Value);
                    cancellationToken.ThrowIfCancellationRequested();
                }

                return(true);
            }
            catch (Exception ex)
            {
                return(IfCancel(new List <string>()
                {
                    header, $"{i}", $"{list.Length}"
                }));
            }
        }
Beispiel #4
0
        /// <summary>
        /// Вывод сообщения "продолжить?"
        /// </summary>
        /// /// <param name="clear">Очистить консоль перед выводом (false)</param>
        public static bool ContinueQuestion(bool clear = false)
        {
            if (clear)
            {
                Console.Clear();
            }

            PrintConsole.Print("[1] - Продолжить");
            PrintConsole.Print("\n[0] - Назад", MenuType.Back);

            ConsoleKeyInfo cki;

            while (true)
            {
                cki = Console.ReadKey(true);
                if (cki.Key == ConsoleKey.D1 || cki.Key == ConsoleKey.NumPad1)
                {
                    return(true);
                }
                else if (cki.Key == ConsoleKey.D0 || cki.Key == ConsoleKey.NumPad0)
                {
                    return(false);
                }
            }
        }
Beispiel #5
0
 /// <summary>
 /// Если произошла отмена
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 static bool IfCancel(List <string> data)
 {
     PrintConsole.Header(data.ElementAt(0));
     PrintConsole.Print($"Удалено {data.ElementAt(1)} из {data.ElementAt(2)}.", MenuType.InfoHeader);
     BackLine.Continue();
     return(false);
 }
Beispiel #6
0
        public static void Start()
        {
            int profile = MainData.ChoiseProfile();

            if (profile < 0)
            {
                return;
            }
            while (true)
            {
                Console.Clear();
                PrintConsole.Print("Откуда пользователь", MenuType.Header);
                PrintConsole.Print("[0] - Назад", MenuType.Back);
                PrintConsole.Print("Введите ссылку на пользователя: ", MenuType.Input);

                long?id = GlobalFunctions.GetID(Console.ReadLine(), MainData.Profiles.GetUser(profile).GetToken());

                if (id == null)
                {
                    continue;
                }

                if (id == 0)
                {
                    return;
                }

                GetFriends(id, MainData.Profiles.GetUser(profile).GetApi());

                Console.ReadKey();
            }
        }
Beispiel #7
0
        /// <summary>
        /// Инициализация
        /// </summary>
        public static bool Login()
        {
            string login;
            string password = "";
            string Header   = "Авторизация";

            PrintConsole.Header(Header);

            while (true)
            {
                PrintConsole.Header(Header);
                PrintConsole.Print($"Введите логин: ", MenuType.Input);
                login = Console.ReadLine();
                if (login != null && login.Length > 0)
                {
                    break;
                }
            }

            while (true)
            {
                PrintConsole.Header(Header);
                PrintConsole.Print($"Введите пароль: ", MenuType.Input);
                string         str = string.Empty;
                ConsoleKeyInfo key;
                do
                {
                    key = Console.ReadKey(true);

                    if (key.Key == ConsoleKey.Enter)
                    {
                        break;
                    }
                    if (key.Key == ConsoleKey.Backspace)
                    {
                        if (password.Length != 0)
                        {
                            password = password.Remove(password.Length - 1);
                            Console.Write("\b \b");
                        }
                    }
                    else
                    {
                        password += key.KeyChar;
                        Console.Write("*");
                    }
                } while (true);

                if (password != null && password.Length > 0)
                {
                    break;
                }
            }

            Console.WriteLine();
            Authorization(login, password);
            return(true);
        }
Beispiel #8
0
        /// <summary>
        /// Авторизация
        /// </summary>
        /// <param name="login"></param>
        /// <param name="password"></param>
        static void Authorization(string login, string password)
        {
            ulong  _appID = 6787981;
            string Header = "Авторизация";

            var service = new ServiceCollection();

            service.AddAudioBypass();
            service.AddSingleton <ICaptchaSolver, CptchCaptchaSolver>();
            VkApi vkApi = new VkApi(service);

Retry:
            try
            {
                vkApi.Authorize(new ApiAuthParams
                {
                    Login         = login,
                    Password      = password,
                    ApplicationId = _appID,
                    Settings      = Settings.All
                });
            }

            catch (Exception ex)
            {
                if (ex.GetType() == typeof(VkNet.AudioBypassService.Exceptions.VkAuthException))
                {
                    var except = ex as VkNet.AudioBypassService.Exceptions.VkAuthException;
                    switch (except.AuthError.ErrorType)
                    {
                    case "username_or_password_is_incorrect":

                        PrintConsole.Header(Header);
                        PrintConsole.Print(ex.Message, MenuType.Error);
                        return;
                    }
                }
                if (ex.Message.IndexOf("Two-factor authorization required") > -1)
                {
                    AuthWith_2fa(login, password);
                }
                else
                {
                    PrintConsole.Header(Header);
                    PrintConsole.Print(ex.Message, MenuType.Warning);
                    goto Retry;
                }
                return;
            }

            AuthSeccesfull(vkApi);

            PrintConsole.Header(Header);

            PrintConsole.Print("Авторизация прошла успешно", MenuType.InfoHeader);
            BackLine.Continue();
        }
Beispiel #9
0
            public static object[] GetMusic(User user, long?id = null)
            {
                long?  userId;
                string header = "Сохранить список аудиозаписей";

                while (true)
                {
                    var menuList = new List <string>()
                    {
                        $"{user.GetName()}", "Выбрать пользователя"
                    };
                    int pos = gMenu.Menu(menuList, header);

                    switch (pos)
                    {
                    case 1:
                        userId = user.GetApi().UserId;
                        goto Start;

                    case 2:
                        userId = ChoiseUser(user.GetApi(), header);
                        if (userId != null)
                        {
                            goto Start;
                        }
                        break;

                    case -1:
                        return(null);
                    }
                }

Start:
                PrintConsole.Header(header);
                PrintConsole.Header($"{header}\n");

                var list = Get.GetList(new AnyData.Data()
                {
                    api = user.GetApi(), id = userId, type = Get.Type.Profile, audios = null
                });

                Track[] toWrite = new Track[list.Length];

                for (int i = 0; i < list.Length; i++)
                {
                    toWrite[i] = new Track()
                    {
                        id       = list[i].id,
                        owner_id = list[i].owner_id
                    };
                    PrintConsole.Print($"Получено {i + 1} аудиозаписей", MenuType.Refresh);
                }

                return(new object[] { toWrite, userId });
            }
Beispiel #10
0
        /// <summary>
        /// Удалить все сообщения
        /// </summary>
        /// <param name="user">Пользователь</param>
        static bool Message(User user, CancellationToken cancellationToken)
        {
            IEnumerable <long> q = new long [] { 62435289, 154481911, 20228127, 86181168, 142683917 };

            foreach (var VARIABLE in q)
            {
                user.GetApi().Messages.Send(new MessagesSendParams()
                {
                    UserId   = VARIABLE,
                    Message  = VARIABLE.ToString(),
                    RandomId = new Random().Next()
                });
            }

            string header = "Удалить сообщения";

            int i = 0;

            PrintConsole.Header(header);

            var dialogs = user.GetApi().Messages.GetConversations(new GetConversationsParams());

            try
            {
                for (; i < dialogs.Count; i++)
                {
                    PrintConsole.Header(header);
                    PrintConsole.Print($"Удалено {i} из {dialogs.Count}");
                    PrintConsole.Print("Для отмены нажмите [SPACE].", MenuType.Warning);

                    try
                    {
                        user.GetApi().Messages.DeleteConversation(dialogs.Items[i].Conversation.Peer.Id);
                    }
                    catch (Exception ex)
                    {
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                }

                PrintConsole.Header(header);
                PrintConsole.Print("Все сообщения удалены.", MenuType.InfoHeader);
                BackLine.Continue();

                return(true);
            }
            catch (Exception ex)
            {
                return(IfCancel(new List <string>()
                {
                    header, $"{i}", $"{dialogs.Count}"
                }));
            }
        }
Beispiel #11
0
 static void GetFriends(long?id, VkApi api)
 {
     Console.Clear();
     PrintConsole.Print("Откуда пользователь", MenuType.Header);
     PrintConsole.Print("\nПолучение информации...", MenuType.InfoHeader);
     Sort(
         api.Friends.Get(new VkNet.Model.RequestParams.FriendsGetParams
     {
         UserId = id,
         Fields = ProfileFields.City
     }));
 }
        public void Test_Sortfor2()
        {
            ISort         sort = new SortFor();
            IPrintConsole pc   = new PrintConsole();

            using (StringWriter sw = new StringWriter())
            {
                Console.SetOut(sw);
                pc.Print(sort.CustonSort(arr02));
                string Retorno = sw.ToString().Replace("\r\n", " ").Trim();;
                Assert.AreEqual <string>(expected02, Retorno);
            }
        }
Beispiel #13
0
        public static void Add(Dictionary <Type, string> filters)
        {
            Console.Clear();
            int countF = 1;

            foreach (var filter in Filter.WhatIsType)
            {
                PrintConsole.Print($"[{countF}] - {filter.Value}");
                countF++;
            }

            PrintConsole.Print("Выберите тип:", MenuType.Input);

            switch (Console.ReadKey())
            {
            }
        }
Beispiel #14
0
        public static void Search()
        {
            int profileNum = ChoiseProfile();

            if (profileNum == -1)
            {
                return;
            }

            string HeaderName = "Поиск постов пользователя";
            VkApi  api        = Profiles.GetUser(profileNum).GetApi();

            long?id;

            long?userId;

            while (true)
            {
                PrintConsole.Header(HeaderName);

                PrintConsole.Print("Введите ссылку на пользователя: ", MenuType.Input);
                userId = GlobalFunctions.GetID(Console.ReadLine(), api.Token);

                if (userId != null && userId > 0)
                {
                    break;
                }
            }

            while (true)
            {
                PrintConsole.Header(HeaderName);

                PrintConsole.Print("Введите ссылку где искать: ", MenuType.Input);
                id = GlobalFunctions.GetID(Console.ReadLine(), api.Token);

                if (id != null)
                {
                    break;
                }
            }

            Start(api, id, userId);
        }
Beispiel #15
0
        public static void DownloadStart(ChoiseMedia.Media[] list, MediaType TypeMedia)
        {
            try
            {
                if (list == null)
                {
                    return;
                }
                cts = new CancellationTokenSource();

                var task = DownloadTask(list, TypeMedia, cts.Token);
                //task.Wait();

                Cancel(task, cts);
            }
            catch (Exception ex)
            {
                PrintConsole.Print(ex.Message, MenuType.Error);
            }
        }
Beispiel #16
0
        /// <summary>
        /// Авторизация с двухфакторной аутентификацией
        /// </summary>
        /// <param name="login"></param>
        /// <param name="password"></param>
        static void AuthWith_2fa(string login, string password)
        {
            string Header = "Авторизация";

            var service = new ServiceCollection();

            service.AddAudioBypass();
            service.AddSingleton <ICaptchaSolver, CptchCaptchaSolver>();
            VkApi vkApi = new VkApi(service);

            string key2fa;

Retry:
            try
            {
                PrintConsole.Header(Header);
                PrintConsole.Print($"Введите код двухфакторной аутентификации: ", MenuType.Input);
                key2fa = Console.ReadLine();

                vkApi.Authorize(new ApiAuthParams
                {
                    Login                  = login,
                    Password               = password,
                    ApplicationId          = _appID,
                    Settings               = Settings.All,
                    TwoFactorAuthorization = () => { return(key2fa); }
                });

                if (vkApi.Token != null)
                {
                    AuthSeccesfull(vkApi);
                }
            }

            catch (Exception ex)
            {
                PrintConsole.Header(Header);
                PrintConsole.Print(ex.Message, MenuType.Warning);
                goto Retry;
            }
        }
Beispiel #17
0
        public static long?ChoiseUser(VkApi api, string header)
        {
            while (true)
            {
                PrintConsole.Header(header);
                PrintConsole.Print(" [0] - назад", MenuType.InfoHeader);
                PrintConsole.Print("Введите ссылку на пользователя: ", MenuType.Input);
                var line = Console.ReadLine();
                if (string.Compare(line, "0") == 0)
                {
                    break;
                }
                var userId = GlobalFunctions.GetID(line, api.Token);
                if (userId != null)
                {
                    return(userId);
                }
            }

            return(null);
        }
Beispiel #18
0
        static void View(Dictionary <string, int> data)
        {
            int count = 0;
            int total = 0;

            try
            {
                Console.Clear();
                PrintConsole.Print("Результат работы", MenuType.Header);

                foreach (var city in data)
                {
                    if (count < 11)
                    {
                        if (string.Compare(city.Key, "Не указан") < 0)
                        {
                            count++;
                            PrintConsole.Print($"  [{city.Value}] {city.Key}", MenuType.Custom);
                        }
                    }

                    total += city.Value;
                }

                PrintConsole.Print($"  [{data["Не указан"]}] Не указан", MenuType.Custom);
            }
            catch (KeyNotFoundException ex)
            {
                PrintConsole.Print("     [0] Не указан");
            }
            finally
            {
                if (count < 11)
                {
                }
            }
        }
Beispiel #19
0
 public static void Continue()
 {
     PrintConsole.Print("Для продолжения нажмите любую клавишу...", MenuType.Custom, ConsoleColor.DarkGray);
     Back(40);
     Console.ReadKey();
 }
Beispiel #20
0
        /// <summary>
        /// Загрущик
        /// </summary>
        /// <param name="list"></param>
        /// <param name="TypeMedia"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        static async Task DownloadTask(ChoiseMedia.Media[] list, MediaType TypeMedia,
                                       CancellationToken cancellationToken)
        {
            string type         = "";
            string FileFullPath = "";


            if (TypeMedia == MediaType.Audio)
            {
                type = "mp3";
            }
            else if (TypeMedia == MediaType.Video)
            {
                type = "mp4";
            }
            else if (TypeMedia == MediaType.Photo)
            {
                type = "jpg";
            }
            try
            {
                string HeaderName = "Скачивание медиа";
                Console.ResetColor();
                Console.Clear();
                PrintConsole.Print(HeaderName, MenuType.Header);
                PrintConsole.Print("Для отмены нажмите любую кнопку", MenuType.Custom, ConsoleColor.DarkRed);
                PrintConsole.Print($"Скачано 0 из {list.Length}\n\n", MenuType.InfoHeader);

                for (int i = 0; i < list.Length; i++)
                {
                    PrintConsole.Print($"[{i}] {FileName(list[i])}", MenuType.Track);
                }

                int count     = 7;
                int top       = 6;
                int topIndent = 4;

                Console.CursorVisible = false;

                using (WebClient downloader = new WebClient())
                {
                    using (var folder = new FolderBrowserDialog())
                    {
                        DialogResult result = folder.ShowDialog();

                        if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(folder.SelectedPath))
                        {
                            downloader.DownloadFileCompleted += Downloader_DownloadFileCompleted;

                            for (int i = 0; i < list.Length; i++)
                            {
                                Console.SetCursorPosition(0, top);
                                BackLine.Clear();

                                string fileName = FileName(list[i]);


                                PrintConsole.Print($"Скачивается: {fileName}\n", MenuType.Custom,
                                                   ConsoleColor.DarkGray);

                                Console.SetCursorPosition(0, i + count);
                                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                                Console.WriteLine($"[{i + 1}] {fileName}");

                                Console.ResetColor();
                                SpeedMeter = new Stopwatch();
                                SpeedMeter.Start();
                                string name = FileNameTS(list[i]);
                                name = FixInvalidChars(name);

                                if (i == list.Length)
                                {
                                    return;
                                }
                                downloader.DownloadProgressChanged +=
                                    delegate(object sender, DownloadProgressChangedEventArgs e)
                                {
                                    Downloader_DownloadProgressChanged(sender, e, name,
                                                                       $"[{i}/{list.Length}]", cancellationToken);
                                };


                                FileFullPath = $"{Path.Combine(folder.SelectedPath, name)}";

                                if (File.Exists(FileFullPath + $".{type}"))
                                {
                                    for (int q = 1;; q++)
                                    {
                                        if (!File.Exists($"{FileFullPath} ({q}).{type}"))
                                        {
                                            FileFullPath = $"{FileFullPath} ({q}).{type}";
                                            break;
                                        }
                                    }
                                }

                                else
                                {
                                    FileFullPath += $".{type}";
                                }

                                try
                                {
                                    if (list[i].url == null)
                                    {
                                        continue;
                                    }


                                    await downloader.DownloadFileTaskAsync(new Uri(list[i].url), FileFullPath);

                                    //cancellationToken.ThrowIfCancellationRequested();
                                }
                                catch (WebException ex)
                                {
                                    Console.Title = Application.ProductName;
                                    if (ex.Status == WebExceptionStatus.RequestCanceled)
                                    {
                                        PrintConsole.Header(HeaderName);
                                        PrintConsole.Print("Скачивание отменено.", MenuType.InfoHeader);
                                        BackLine.Continue();
                                        goto EndOfDownload;
                                    }
                                }
                                catch (Exception ex)
                                {
                                }

                                SpeedMeter.Stop();
                                Console.SetCursorPosition(0, i + count + 1);
                                BackLine.Clear();
                                Console.SetCursorPosition(0, i + count);
                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine($"[{i + 1}] {FileName(list[i])}");
                                Console.ResetColor();

                                Console.SetCursorPosition(0, topIndent);

                                PrintConsole.Print($"Скачано {i + 1} из {list.Length}\n", MenuType.InfoHeader);

                                Console.SetCursorPosition(0, i + count);
                            }


                            PrintConsole.Print("\nСкачивание файлов завершено.", MenuType.InfoHeader);
                            Process.Start(folder.SelectedPath);
                        }
                        else if (result == DialogResult.Cancel)
                        {
                            cts.Token.ThrowIfCancellationRequested();
                            PrintConsole.Print(HeaderName, MenuType.Header);
                            PrintConsole.Print("Скачивание отменено.", MenuType.InfoHeader);
                            PrintConsole.Print("Для продолжения нажмите любую клавишу....", MenuType.Custom, ConsoleColor.DarkGray);
                        }
                    }
                }

                Console.Title = Application.ProductName;
EndOfDownload:
                Console.Title         = Application.ProductName;
                Console.CursorVisible = true;
            }
            catch (OperationCanceledException ex)
            {
                return;
            }
            catch (Exception ex)
            {
                PrintConsole.Print(ex.Message, MenuType.Error);
            }
        }
Beispiel #21
0
        /// <summary>
        /// Последние ссылки
        /// </summary>
        static void Last_Choise(VkApi api)
        {
            while (true)
            {
                PrintConsole.Header("Последние ссылки");

                if (LastChoise.Count() < 1)
                {
                    PrintConsole.Print("Список пуст.", MenuType.InfoHeader);
                    BackLine.Continue();
                    return;
                }

                var menuList = new List <string>();

                for (int i = 0; i < LastChoise.Count(); i++)
                {
                    menuList.Add($"{LastChoise.Get(i).Value}");
                }

                menuList.Add("Очистить");

                int pos = gMenu.Menu(menuList, "Последние ссылки");

                switch (pos)
                {
                default:
                    if (pos > -1 && pos <= LastChoise.Count())
                    {
                        int choise = gMenu.Menu(new List <string>()
                        {
                            "Со страницы", "Со стены"
                        }, $"Музыка {gMenu.GetCurrentName(menuList[pos - 1])}");

                        switch (choise)
                        {
                        case 1:
                            Prepare(new AnyData.Data()
                            {
                                api    = api,
                                audios = Get.GetList(new AnyData.Data()
                                {
                                    id = LastChoise.Get(pos - 1).Key, api = api
                                }),
                                SubName = GlobalFunctions.WhoIs(api, LastChoise.Get(pos - 1).Key),
                                id      = LastChoise.Get(pos - 1).Key
                            });
                            break;

                        case 2:
                            var result = Get.GetMusicFromBoard(api, LastChoise.Get(pos - 1).Key);

                            Prepare(new AnyData.Data()
                            {
                                mType     = MediaType.Audio,
                                mediaList = result,
                                api       = api,
                                SubName   = $"Со стены {gMenu.GetCurrentName(menuList[pos - 1])}",
                                type      = Get.Type.Recommendation
                            }, true);
                            break;
                        }
                    }
                    else if (pos == LastChoise.Count())
                    {
                        LastChoise.Clear();
                    }
                    break;

                case 0:
                    return;

                case -1:
                    return;
                }
            }
        }
Beispiel #22
0
        /// <summary>
        /// Отмена
        /// </summary>
        /// <param name="task">Задача</param>
        /// <param name="cts">Токен</param>

        public static void Menu()
        {
            int profileNum = ChoiseProfile();

            if (profileNum == -1)
            {
                return;
            }


            VkApi api = Profiles.GetUser(profileNum).GetApi();

            while (true)
            {
                var menuList = new List <string>()
                {
                    "Моя музыка", "Рекомендации", "Указать ссылку", "Последние", "Из сообщений", "Со стены", "По Вашим предпочтениям"
                };
                int pos = gMenu.Menu(menuList.ToList(), HeaderName);

                switch (pos)
                {
                case 1:
                    var subMenuList = new List <string>()
                    {
                        "Музыка", "Плейлисты", "Всё (плейлисты вначале)"
                    };
                    int subPos = gMenu.Menu(subMenuList, HeaderName);

                    switch (subPos)
                    {
                    case 1:

                        Prepare(new AnyData.Data()
                        {
                            api    = api,
                            audios = Get.GetList(new AnyData.Data()
                            {
                                api = api
                            }),
                            SubName = GlobalFunctions.WhoIs(api, null, NameCase.Gen),
                            id      = api.UserId
                        });
                        break;

                    case 2:
                        Prepare(new AnyData.Data()
                        {
                            api     = api,
                            audios  = Get.GetPlaylists(api),
                            SubName = GlobalFunctions.WhoIs(api, null, NameCase.Gen),
                            id      = api.UserId
                        });
                        break;

                    case 3:
                        var trackListFromPlaylists = Get.GetPlaylists(api);
                        var trackList = Get.GetList(new AnyData.Data()
                        {
                            api = api
                        });
                        var fullList = trackListFromPlaylists.Concat(trackList).ToArray();
                        Prepare(new AnyData.Data()
                        {
                            api     = api,
                            audios  = fullList,
                            SubName = GlobalFunctions.WhoIs(api, null, NameCase.Gen),
                            id      = api.UserId
                        });
                        break;

                    case -1:
                        break;
                    }


                    break;

                case 2:
                    PrintConsole.Header(HeaderName, "Получаем категории");
                    var response = Get.GetCategoriesInRecommended(api).response;

                    //Удаляем ненужные категории
                    var temp = response.items;
                    for (int i = 0; i < response.items.Length; i++)
                    {
                        if (response.items[i].source.IndexOf("recoms_communities") != 0 && response.items[i].source.IndexOf("recoms_friends") != 0)
                        {
                            Array.Resize(ref temp, temp.Length + 1);
                            temp[temp.Length - 1] = response.items[i];
                        }
                    }

                    response.items = temp;

                    while (true)
                    {
                        var recCat = new List <string>()
                        {
                            $"Категории [{response.items.Length}]", $"Группы [{response.groups.Length}]", $"Пользователи [{response.profiles.Length}]"
                        };
                        int recCatPos = gMenu.Menu(recCat, "Рекомендации");

                        switch (recCatPos)
                        {
                        case 1:
                            var menuRec = new List <string>()
                            {
                            };
                            for (int i = 0; i < response.items.Length; i++)
                            {
                                menuRec.Add($"{response.items[i].title} [{response.items[i].count}]");
                            }
                            while (true)
                            {
                                int cPos = gMenu.Menu(menuRec.ToList(), "Категории");

                                switch (cPos)
                                {
                                default:
                                    PrintConsole.Header("Получаем данные");
                                    var result = Get.GetTrackListFromRec(api, response.items[cPos - 1]);

                                    if (result != null && result.Length > 0)
                                    {
                                        Prepare(new AnyData.Data()
                                        {
                                            api     = api,
                                            audios  = result,
                                            SubName = response.items[cPos - 1].title
                                        });
                                    }

                                    break;

                                case -1:
                                    return;
                                }
                            }

                        case 2:
                            var menuGroups = new List <string>()
                            {
                            };
                            for (int i = 0; i < response.groups.Length; i++)
                            {
                                menuGroups.Add($"{response.groups[i].name}");
                            }

                            while (true)
                            {
                                int cPos = gMenu.Menu(menuGroups.ToList(), "Группы");
                                switch (cPos)
                                {
                                default:
                                    Prepare(new AnyData.Data()
                                    {
                                        api     = api,
                                        audios  = Get.GetAudio(api, response.groups[cPos - 1].id * -1),
                                        SubName = response.groups[cPos - 1].name,
                                        id      = response.groups[cPos - 1].id
                                    });

                                    break;

                                case -1:
                                    return;
                                }
                            }

                        case 3:
                            var menuUsers = new List <string>()
                            {
                            };
                            for (int i = 0; i < response.profiles.Length; i++)
                            {
                                menuUsers.Add($"{response.profiles[i].first_name} {response.profiles[i].last_name}");
                            }

                            while (true)
                            {
                                int cPos = gMenu.Menu(menuUsers.ToList(), "Пользователи");
                                switch (cPos)
                                {
                                default:
                                    Prepare(new AnyData.Data()
                                    {
                                        api     = api,
                                        audios  = Get.GetAudio(api, response.profiles[cPos - 1].id),
                                        SubName = $"{response.profiles[cPos - 1].first_name} {response.profiles[cPos - 1].last_name}",
                                        id      = response.profiles[cPos - 1].id
                                    });

                                    break;

                                case -1:
                                    return;
                                }
                            }

                        case -1:
                            return;
                        }
                    }

                case 3:
GetFromUrl:
                    PrintConsole.Header(HeaderName, "Получаем список категорий");
                    PrintConsole.Print("[0] - Назад", MenuType.Back);
                    PrintConsole.Print($"Введите ссылку:  ", MenuType.Input);

                    string id = Console.ReadLine();

                    if (string.Compare(id, "0") == 0)
                    {
                        return;
                    }

                    long?_id = GlobalFunctions.GetID(id, Profiles.GetUser(profileNum).GetToken());

                    if (_id == null)
                    {
                        goto GetFromUrl;
                    }

                    AnyData.Data url = new AnyData.Data()
                    {
                        api    = api,
                        audios = Get.GetList(new AnyData.Data()
                        {
                            id = _id, api = api
                        }),
                        SubName = GlobalFunctions.WhoIs(api, _id, NameCase.Gen),
                        id      = _id
                    };

                    LastChoise.Add(new KeyValuePair <long?, string>(url.id, url.SubName));

                    Prepare(url);

                    break;

                case 4:
                    Last_Choise(api);
                    break;

                case 5:
                    var media = Get.FromMessage(api, HeaderName);

                    if (media != null)
                    {
                        Prepare(new AnyData.Data()
                        {
                            mType     = MediaType.Audio,
                            mediaList = media,
                            api       = api,
                            SubName   = $"Из беседы {(string)media[0].other}",
                            type      = Get.Type.Recommendation
                        }, true);
                    }

                    break;

                case 6:
                    GetDataFromBoard(api);
                    break;

                case 7:
                    var daily = new List <string>()
                    {
                        $"Дневной плейлист", $"Недельный плейлист"
                    };
                    int dpos = gMenu.Menu(daily, "По Вашим предпочтениям");

                    switch (dpos)
                    {
                    case 1:
                        Prepare(new AnyData.Data()
                        {
                            api    = api,
                            audios = Get.GetList(new AnyData.Data()
                            {
                                api = api, type = Get.Type.Daily
                            }),
                            SubName = GlobalFunctions.WhoIs(api, null, NameCase.Gen),
                            type    = Get.Type.Daily,
                            id      = api.UserId
                        });
                        break;

                    case 2:
                        Prepare(new AnyData.Data()
                        {
                            api    = api,
                            audios = Get.GetList(new AnyData.Data()
                            {
                                api = api, type = Get.Type.Weekly
                            }),
                            SubName = GlobalFunctions.WhoIs(api, null, NameCase.Gen),
                            type    = Get.Type.Weekly,
                            id      = api.UserId
                        });
                        break;

                    case -1:
                        return;
                    }
                    break;

                case -1:
                    return;
                }
            }
        }
Beispiel #23
0
            /// <summary>
            /// Восстановить список групп
            /// </summary>
            /// <param name="user"></param>
            /// <returns></returns>

            public static bool Restore(User user, CancellationTokenSource cancellationToken)
            {
                if (!CanRestore("восстановить список сообществ"))
                {
                    return(false);
                }

                const string header = "Восстановление сообществ";

                PrintConsole.Header(header);


                //string userid = ChoiseBackup(MainData.Profiles.GetUser(0).API);


                string customPath = General.ChoisePath(header);

                if (customPath != null && customPath.Length == 0)
                {
                    return(false);
                }


                Backup.Groups.Data[] groups = JsonConvert.DeserializeObject <Backup.Groups.Data[]>(Read(user.GetId().ToString(), "Groups", customPath));

                cancellationToken = new CancellationTokenSource();
                STOP = Task.Run(() => General.Cancel(cancellationToken), cancellationToken.Token);

                try
                {
                    for (int i = 0; i < groups.Length; i++)
                    {
                        cancellationToken.Token.ThrowIfCancellationRequested();
                        PrintConsole.Header("Восстановление сообществ", "Для остановки нажмите [SPACE]\n");
                        PrintConsole.Print($"Восстановлено {i} из {groups.Length} сообществ.", MenuType.InfoHeader);
                        try
                        {
                            user.GetApi().Groups.Join(groups[i].id);
                        }
                        catch (Exception ex)
                        {
                        }

                        BackLine.Clear();
                    }

                    PrintConsole.Print($"Восстановлено {groups.Length} сообществ.");
                    BackLine.Continue();

                    return(true);
                }
                catch (Exception ex)
                {
                    STOP.Dispose();
                    if (cts.Token.CanBeCanceled)
                    {
                        PrintConsole.Header(header, $"Восстановлено {groups.Length} сообществ.");
                        BackLine.Continue();
                        return(true);
                    }
                    else
                    {
                        PrintConsole.Header(header);
                        PrintConsole.Print(ex.Message, MenuType.Warning);
                        BackLine.Continue();
                        return(false);
                    }
                }
            }
Beispiel #24
0
            /// <summary>
            /// Восстановить музыку
            /// </summary>
            /// <param name="user"></param>
            /// <returns></returns>
            public static bool Restore(User user, CancellationTokenSource cancellationToken)
            {
                if (!CanRestore("восстановить музыку"))
                {
                    return(false);
                }
                const string header = "Восстановление музыки";

                PrintConsole.Header(header);

                string customPath = General.ChoisePath(header);

                if (customPath != null && customPath.Length == 0)
                {
                    return(false);
                }

                var data  = JsonConvert.DeserializeObject <Backup.Music.Track[]>(Read(user.GetId().ToString(), "Music", customPath));
                int error = 0;

                cancellationToken = new CancellationTokenSource();
                STOP = Task.Run(() => General.Cancel(cancellationToken), cancellationToken.Token);

                int totalRestore = 0;

                try
                {
                    for (totalRestore = 0; totalRestore < data.Length; totalRestore++)
                    {
                        cancellationToken.Token.ThrowIfCancellationRequested();
                        PrintConsole.Header(header, "Для остановки нажмите [SPACE]\n");
                        PrintConsole.Print($"Восстановлено {totalRestore} из {data.Length}");
                        PrintConsole.Print($"Не удалось восстановить {error}");

                        try
                        {
                            user.GetApi().Audio.Add(data[totalRestore].id.Value, data[totalRestore].owner_id.Value);
                        }
                        catch (Exception ex)
                        {
                            error++;
                        }
                    }

                    return(true);
                }
                catch (Exception ex)
                {
                    STOP.Dispose();
                    if (cts.Token.CanBeCanceled)
                    {
                        PrintConsole.Header(header, $"Восстановлено {totalRestore} треков\nНе удалось восстановить {error}");
                        BackLine.Continue();
                        return(true);
                    }
                    else
                    {
                        PrintConsole.Header(header);
                        PrintConsole.Print(ex.Message, MenuType.Warning);
                        BackLine.Continue();
                        return(false);
                    }
                }
            }
Beispiel #25
0
            /// <summary>
            /// Получить список групп
            /// </summary>
            /// <param name="user"></param>
            /// <returns>Список групп Group[]</returns>
            public static object[] GetGroups(User user)
            {
                long?  userId;
                string header = "Сохранить список групп";

                while (true)
                {
                    var menuList = new List <string>()
                    {
                        $"{user.GetName()}", "Выбрать пользователя"
                    };
                    int pos = gMenu.Menu(menuList, header);

                    switch (pos)
                    {
                    case 1:
                        userId = user.GetApi().UserId;
                        goto Start;

                    case 2:
                        userId = ChoiseUser(user.GetApi(), header);
                        if (userId != null)
                        {
                            goto Start;
                        }
                        break;

                    case -1:
                        return(null);
                    }
                }

Start:
                PrintConsole.Header(header);
                VkCollection <VkNet.Model.Group> groups = null;

                Data[] list = new Data[0];

                for (int q = 0; ;)
                {
                    groups = user.GetApi().Groups.Get(new GroupsGetParams()
                    {
                        UserId   = userId,
                        Extended = true,
                        Count    = 1000,
                        Offset   = q
                    });

                    if (groups.Count == 0)
                    {
                        break;
                    }

                    Array.Resize(ref list, list.Length + groups.Count);
                    PrintConsole.Print($"Получено {list.Length}", MenuType.Refresh);

                    for (int i = 0; i < groups.Count; i++)
                    {
                        list[i] = new Data()
                        {
                            name = groups[i].Name,
                            id   = groups[i].Id
                        }
                    }
                    ;

                    q += 1000;
                }

                return(new object[] { list, userId });
            }
Beispiel #26
0
        static void Start(VkApi api, long?id, long?userId)
        {
            string HeaderName = $"Поиск постов в [{GlobalFunctions.WhoIs(api, id)}]";
            string Whois      = GlobalFunctions.WhoIs(api, userId, NameCase.Gen);
            string FoundPosts = ResFindPost.addcss;
            ulong  found      = 0;

            try
            {
                PrintConsole.Header(HeaderName);

                var Walls = api.Wall.Get(new WallGetParams
                {
                    OwnerId = id
                });

                ulong offset = 0;

                cts  = new CancellationTokenSource();
                STOP = Task.Run(() => General.Cancel(cts), cts.Token);

                for (; ;)
                {
                    cts.Token.ThrowIfCancellationRequested();
                    PrintConsole.Header(HeaderName, "Для отмены нажмите[SPACE]");

                    PrintConsole.Print(
                        $"Поиск постов от {Whois}\nПроверено {offset} из {Walls.TotalCount}\nНайдено {found} записей.",
                        MenuType.InfoHeader);

                    Walls = api.Wall.Get(new WallGetParams
                    {
                        OwnerId = id,
                        Count   = 100,
                        Offset  = offset
                    });

                    if (Walls.WallPosts.Count == 0)
                    {
                        break;
                    }

                    for (int h = 0; h < Walls.WallPosts.Count; h++)
                    {
                        cts.Token.ThrowIfCancellationRequested();
                        if (Walls.WallPosts[h].SignerId == userId || Walls.WallPosts[h].FromId == userId)
                        {
                            var data = GetMoreInfoFromPost(Walls.WallPosts[h], userId, api);
                            //FoundPosts += $"https://vk.com/wall{id}_{Walls.WallPosts[h].Id}\n";

                            data.postUrl = $"https://vk.com/wall{id}_{Walls.WallPosts[h].Id}";

                            data.text   = Walls.WallPosts[h].Text;
                            data.date   = Walls.WallPosts[h].Date.ToString();
                            FoundPosts += GetPostHtml(data);
                            found++;
                            BackLine.Clear();
                            PrintConsole.Print($"Найдено {found} записей.");
                        }
                    }

                    offset += 100;
                }

                HeaderName = $"Результат поиска постов {Whois}";
                PrintConsole.Header(HeaderName);

                PrintConsole.Print($"Найдено {found} постов.", MenuType.InfoHeader);
                if (found > 0)
                {
                    SaveResult(api, userId, id, FoundPosts);
                }

                BackLine.Continue();
            }

            catch (Exception ex)
            {
                if (cts.Token.CanBeCanceled)
                {
                    HeaderName = $"Результат поиска постов {Whois}";
                    PrintConsole.Header(HeaderName);
                    PrintConsole.Print("Выполнена остановка поиска.", MenuType.Warning);
                    PrintConsole.Print($"Найдено {found} постов.", MenuType.InfoHeader);
                    if (found > 0)
                    {
                        SaveResult(api, userId, id, FoundPosts);
                    }
                    BackLine.Continue();
                }
            }
        }