private async void Tell()
        {
            try
            {
                var posId = await ViewModelLocator.Vkontakte.Wall.Post(message: MainResources.AboutTellMessage, attachments:
                    new[] { new VkLinkAttachment() { Url = "http://meridianvk.com" } });

                if (posId != 0)
                {
                    var flyout = new FlyoutControl();
                    flyout.FlyoutContent = new TellResultView(posId);
                    flyout.Show();
                }
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);
            }
        }
Beispiel #2
0
        private void InitializeCommands()
        {
            AddSocietyCommand = new RelayCommand(async () =>
            {
                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new AddSocietyFlyout();
                var result = await flyout.ShowAsync();
                if (result != null)
                {
                    CancelAsync();

                    if (Societies.Count == 0)
                    {
                        _societies.Add(new VkGroup() { Name = MainResources.AllSocieties });
                    }

                    Societies.Add((VkGroup)result);
                    SaveSocieties();

                    if (SelectedSociety == null)
                        SelectedSociety = _societies.First();
                    else if (SelectedSociety.Id == 0)
                        LoadFeed(_cancellationToken.Token);
                }
            });

            RemoveSocietyCommand = new RelayCommand<VkGroup>(society =>
            {
                bool isActiveSociety = false;
                if (society == SelectedSociety)
                    isActiveSociety = true;

                CancelAsync();
                Societies.Remove(society);

                if (Societies.Count == 1)
                    Societies.Clear();

                SaveSocieties();

                if (!isActiveSociety && (SelectedSociety != null && SelectedSociety.Id != 0))
                {
                    return;
                }

                if (isActiveSociety)
                {
                    if (Societies.Any())
                        SelectedSociety = Societies.First();
                }

                //if (SelectedSociety != null && SelectedSociety.Id == 0)
                //{
                    CancelAsync();

                    LoadFeed(_cancellationToken.Token);
                //}

                //if (isActiveSociety && Societies.Any())
                //    SelectedSociety = Societies.First();
                //else if (isActiveSociety)
                //    LoadFeed(_cancellationToken.Token);
            });

            PlayAudioCommand = new RelayCommand<Audio>(audio =>
            {
                AudioService.Play(audio);
                AudioService.SetCurrentPlaylist(Tracks);
            });
        }
Beispiel #3
0
        private async void ValidateUser(Uri redirectUri)
        {
            var flyout = new FlyoutControl();
            flyout.FlyoutContent = new WebValidationView(redirectUri);
            var token = await flyout.ShowAsync() as AccessToken;
            if (token != null)
            {
                AccountManager.SetLoginVk(token);

                MessengerInstance.Send(new NavigateToPageMessage() { Page = "/Main.MusicView" });
            }
        }
Beispiel #4
0
        private void App_OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            LoggingService.Log(e.Exception);

            Dispatcher.Invoke(async () =>
            {
                e.Handled = true;

                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new CommonErrorView();
                var restart = (bool)await flyout.ShowAsync();
                if (restart)
                {
                    Process.Start(Application.ResourceAssembly.Location);
                }

                Shutdown();
            });

        }
        private void InitializeCommands()
        {
            PlayAudioCommand = new RelayCommand<Audio>(audio =>
            {
                AudioService.Play(audio);
                AudioService.SetCurrentPlaylist(AllTracks);
            });

            ShowAllTracksCommand = new RelayCommand(() =>
            {
                MessengerInstance.Send(new NavigateToPageMessage()
                {
                    Page = "/Search.ArtistAudioView",
                    Parameters = new Dictionary<string, object>()
                    {
                        {"viewModel", this}
                    }
                });
            });

            ShowAllAlbumsCommand = new RelayCommand(() =>
            {
                MessengerInstance.Send(new NavigateToPageMessage()
                {
                    Page = "/Search.ArtistAlbumsView",
                    Parameters = new Dictionary<string, object>()
                    {
                        {"viewModel", this}
                    }
                });
            });


            GoToAlbumCommand = new RelayCommand<LastFmAlbum>(album =>
            {
                MessengerInstance.Send(new NavigateToPageMessage()
                {
                    Page = "/Search.AlbumView",
                    Parameters = new Dictionary<string, object>()
                    {
                        {"album", album}
                    }
                });
            });

            GoToArtistCommand = new RelayCommand<LastFmArtist>(artist =>
            {
                MessengerInstance.Send(new NavigateToPageMessage()
                {
                    Page = "/Search.ArtistView",
                    Parameters = new Dictionary<string, object>()
                    {
                        {"artist", artist}
                    }
                });
            });

            ShareCommand = new RelayCommand(() =>
            {
                var shareViewModel = new ShareViewModel();
                if (Tracks != null && Tracks.Count > 0)
                {
                    foreach (var track in AllTracks.Take(15))
                    {
                        shareViewModel.Tracks.Add(track);
                    }
                }

                if (File.Exists(App.Root + "/Cache/artists/" + Artist.Name + ".jpg"))
                {
                    shareViewModel.ImagePath = App.Root + "/Cache/artists/" + Artist.Name + ".jpg";
                    shareViewModel.Image = new BitmapImage(new Uri(shareViewModel.ImagePath));
                }

                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new ShareView() { DataContext = shareViewModel };
                flyout.Show();

                shareViewModel.Activate();
            });
        }
        private void InitializeCommands()
        {
            CloseSettingsCommand = new RelayCommand(() =>
            {
                ViewModelLocator.Main.ShowSidebar = true;
                ViewModelLocator.Main.GoBackCommand.Execute(null);
            });

            SaveCommand = new RelayCommand(SaveSettings);

            SaveRestartCommand = new RelayCommand(() =>
            {
                SaveSettings();

                Process.Start(Application.ResourceAssembly.Location);
                Application.Current.Shutdown();
            });

            SignOutVkCommand = new RelayCommand(AccountManager.LogOutVk);

            LoginLastFmCommand = new RelayCommand(() =>
            {
                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new LoginLastFmView();
                flyout.Show();
            });

            SignOutLastFmCommand = new RelayCommand(AccountManager.LogoutLastFm);

            CheckUpdatesCommand = new RelayCommand(() => ViewModelLocator.UpdateService.CheckUpdates());

            ClearCacheCommand = new RelayCommand(() =>
            {
                if (!Directory.Exists("Cache"))
                    return;

                foreach (var file in Directory.EnumerateFiles("Cache"))
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex);
                    }
                }

                foreach (var dir in Directory.EnumerateDirectories("Cache"))
                {
                    try
                    {
                        Directory.Delete(dir, true);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex);
                    }
                }

                CacheSize = StringHelper.FormatSize(Math.Round(CalculateFolderSize("Cache"), 1));
            });

            TellCommand = new RelayCommand(Tell);
        }
Beispiel #7
0
        public void InitializeCommands()
        {
            CancelCommand = new RelayCommand(() =>
            {
                Tracks.Clear();
                ViewModelLocator.Main.ShowShareBar = false;
            });

            CloseCommand = new RelayCommand(() =>
            {
                Close();
            });

            GoNextCommand = new RelayCommand(() =>
            {
                ViewModelLocator.Main.ShowShareBar = false;

                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new ShareView() { DataContext = this };
                flyout.Show();

                Activate();
            });

            RemoveTrackCommand = new RelayCommand<VkAudio>(track => Tracks.Remove(track));

            PublishCommand = new RelayCommand(() =>
            {
                if (ShareToSociety && SelectedSociety == null)
                    return;

                if (ShareToUser && SelectedFriend == null)
                    return;

                var progress = new Progress<int>(p =>
                {
                    Progress += p;
                });

                Share(progress, _cancellationToken.Token);
            });

            ClearImageCommand = new RelayCommand(() =>
            {
                Image = null;
                ImagePath = null;
            });

            AddImageCommand = new RelayCommand(() =>
            {
                var fileOpenDialog = new OpenFileDialog();
                fileOpenDialog.Filter = "Images|*.png;*.jpg";
                if (fileOpenDialog.ShowDialog() == DialogResult.OK)
                {
                    ImagePath = fileOpenDialog.FileName;
                    Image = new BitmapImage(new Uri(ImagePath));
                }
            });
        }
Beispiel #8
0
        private void InitializeCommands()
        {
            CloseWindowCommand = new RelayCommand(() => Application.Current.MainWindow.Close());

            MinimizeWindowCommand = new RelayCommand(() => WindowState = WindowState.Minimized);

            MaximizeWindowCommand = new RelayCommand(() => WindowState = IsWindowMaximized ? WindowState.Normal : WindowState.Maximized);

            GoToPageCommand = new RelayCommand<string>(page => OnNavigateToPage(new NavigateToPageMessage() { Page = page }));

            GoToSettingsCommand = new RelayCommand(() =>
            {
                ShowSidebar = false;
                OnNavigateToPage(new NavigateToPageMessage() { Page = "/Settings.SettingsView" });
            });

            PrevAudioCommand = new RelayCommand(AudioService.Prev);

            NextAudioCommand = new RelayCommand(AudioService.SkipNext);

            PlayPauseCommand = new RelayCommand(() =>
            {
                if (IsPlaying)
                    AudioService.Pause();
                else
                    AudioService.Play();
            });

            GoBackCommand = new RelayCommand(() =>
            {
                var frame = Application.Current.MainWindow.GetVisualDescendents().OfType<Frame>().FirstOrDefault(f => f.Name == "RootFrame");
                if (frame == null)
                    return;

                if (frame.CanGoBack)
                    frame.GoBack();

                UpdateCanGoBack();
            });

            SearchCommand = new RelayCommand<string>(query =>
            {
                if (!string.IsNullOrWhiteSpace(query))
                {
                    MessengerInstance.Send(new NavigateToPageMessage()
                    {
                        Page = "/Search.SearchResultsView",
                        Parameters = new Dictionary<string, object>()
                                {
                                    {"query", query}
                                }
                    });
                }
            });

            RestartCommand = new RelayCommand(() =>
            {
                Process.Start(Application.ResourceAssembly.Location);
                Application.Current.Shutdown();
            });

            AddRemoveAudioCommand = new RelayCommand<Audio>(audio =>
            {
                audio.IsAddedByCurrentUser = !audio.IsAddedByCurrentUser;
                LikeDislikeAudio(audio);
            });

            EditAudioCommand = new RelayCommand<Audio>(audio =>
            {
                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new EditAudioView(audio);
                flyout.Show();
            });

            ShowLyricsCommand = new RelayCommand<Audio>(audio =>
            {
                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new LyricsView(audio);
                flyout.Show();
            });

            CopyInfoCommand = new RelayCommand<Audio>(audio =>
            {
                if (audio == null)
                    return;

                try
                {
                    Clipboard.SetData(DataFormats.UnicodeText, audio.Artist + " - " + audio.Title);
                }
                catch (Exception ex)
                {
                    LoggingService.Log(ex);
                }
            });

            PlayAudioNextCommand = new RelayCommand<Audio>(track =>
            {
                AudioService.PlayNext(track);
            });

            AddToNowPlayingCommand = new RelayCommand<Audio>(track =>
            {
                AudioService.Playlist.Add(track);
            });

            RemoveFromNowPlayingCommand = new RelayCommand<Audio>(track =>
            {
                AudioService.Playlist.Remove(track);
            });

            ShareAudioCommand = new RelayCommand<Audio>(audio =>
            {
                ShowShareBar = true;

                //костыль #2
                var shareControl = Application.Current.MainWindow.GetVisualDescendent<ShareBarControl>();
                if (shareControl == null)
                    return;

                var shareViewModel = ((ShareViewModel)((FrameworkElement)shareControl.Content).DataContext);
                shareViewModel.Tracks.Add(audio);
            });

            SwitchUIModeCommand = new RelayCommand(() =>
            {
                if (CurrentUIMode == UIMode.Normal)
                    SwitchUIMode(UIMode.Compact);
                else
                    SwitchUIMode(UIMode.Normal);
            });

            StartTrackRadioCommand = new RelayCommand<Audio>(track =>
            {
                RadioService.StartRadioFromSong(track.Title, track.Artist);
                MessengerInstance.Send(new NavigateToPageMessage() { Page = "/Main.NowPlayingView" });
            });

            ShowArtistInfoCommand = new RelayCommand<string>(async artist =>
            {
                NotificationService.Notify(MainResources.NotificationLookingArtist);

                try
                {
                    var artists = await DataService.SearchArtists(artist);
                    if (artists != null && artists.Count > 0)
                    {
                        var a = artists.First();
                        MessengerInstance.Send(new NavigateToPageMessage()
                        {
                            Page = "/Search.ArtistView",
                            Parameters = new Dictionary<string, object>()
                            {
                                {"artist", a}
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Log(ex);
                    NotificationService.Notify(MainResources.NotificationArtistNotFound);
                }
            });

            ShowLocalSearchCommand = new RelayCommand(() =>
            {
                var frame = Application.Current.MainWindow.GetVisualDescendents().OfType<Frame>().FirstOrDefault();
                if (frame == null)
                    return;

                var page = (Page)frame.Content;
                if (page != null)
                {
                    var localSearchBox = page.GetVisualDescendents().OfType<LocalSearchControl>().FirstOrDefault();
                    if (localSearchBox != null)
                        localSearchBox.IsActive = true;
                }
            });

            AddToAlbumCommand = new RelayCommand<Audio>(track =>
            {
                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new AddToAlbumView(track);
                flyout.Show();
            });
        }
Beispiel #9
0
        private async void EditAlbum(VkAudioAlbum album)
        {
            var flyout = new FlyoutControl();
            flyout.FlyoutContent = new EditAlbumView(album);

            var result = await flyout.ShowAsync();
            if (result != null && (bool)result)
            {
                try
                {
                    if (await ViewModelLocator.Vkontakte.Audio.EditAlbum(album.Id.ToString(), album.Title))
                    {
                        Albums[Albums.IndexOf(album)].Title = album.Title;
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Log(ex);
                }
            }
        }
Beispiel #10
0
        private async void AddNewAlbum()
        {
            var album = new VkAudioAlbum() { Title = "New album" };

            var flyout = new FlyoutControl();
            flyout.FlyoutContent = new EditAlbumView(album);
            var result = await flyout.ShowAsync();
            if ((bool)result)
            {
                try
                {
                    var newAlbumId = await ViewModelLocator.Vkontakte.Audio.AddAlbum(album.Title);
                    if (newAlbumId != 0)
                    {
                        album.Id = newAlbumId;
                        album.OwnerId = ViewModelLocator.Vkontakte.AccessToken.UserId;
                        Albums.Insert(5, album);
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Log(ex);
                }
            }
        }
Beispiel #11
0
        private void InitializeCommands()
        {
            CreateStationCommand = new RelayCommand(async () =>
            {
                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new CreateRadioStationView();
                var artists = await flyout.ShowAsync() as IList<EchoArtist>;

                if (artists != null)
                {
                    AddStation(artists);
                }
            });

            PlayStationCommand = new RelayCommand<RadioStation>(station =>
            {
                RadioService.PlayRadio(station);
                MessengerInstance.Send(new NavigateToPageMessage() { Page = "/Main.NowPlayingView" });
            });

            RemoveStationCommand = new RelayCommand<RadioStation>(station =>
            {
                Stations.Remove(station);
                RadioService.SaveStations(Stations);
            });

            EditStationCommand = new RelayCommand<RadioStation>(async station =>
            {
                var createRadioStationView = new CreateRadioStationView();
                createRadioStationView.Artists = new ObservableCollection<EchoArtist>(station.Artists);

                var flyout = new FlyoutControl();
                flyout.FlyoutContent = createRadioStationView;
                var artists = await flyout.ShowAsync() as IList<EchoArtist>;

                if (artists != null)
                {
                    var titleArtist = station.Artists.First();
                    station.Artists = artists.ToList();


                    //update image and title
                    station.Title = string.Join(", ", station.Artists.Select(s => s.Name));

                    if (station.Artists.First().Name != titleArtist.Name)
                    {
                        station.ImageUrl = null;

                        try
                        {
                            var artistImage = await DataService.GetArtistImage(station.Artists.First().Name, false);
                            if (artistImage != null)
                                station.ImageUrl = artistImage.OriginalString;
                        }
                        catch (Exception ex)
                        {
                            LoggingService.Log(ex);
                        }
                    }

                    RadioService.SaveStations(Stations);
                }
            });
        }
        private void InitializeCommands()
        {
            PlayAudioCommand = new RelayCommand<Audio>(audio =>
            {
                AudioService.Play(audio);
                AudioService.SetCurrentPlaylist(Tracks);
            });

            SaveCommand = new RelayCommand(Save);

            ShareCommand = new RelayCommand(() =>
            {
                var shareViewModel = new ShareViewModel();
                if (Tracks != null && Tracks.Count > 0)
                {
                    foreach (var track in Tracks.Take(15))
                    {
                        shareViewModel.Tracks.Add(track);

                    }
                }

                if (File.Exists(App.Root + "/Cache/artists/" + Album.Artist + ".jpg"))
                {
                    shareViewModel.ImagePath = App.Root + "/Cache/artists/" + Album.Artist + ".jpg";
                    shareViewModel.Image = new BitmapImage(new Uri(shareViewModel.ImagePath));
                }

                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new ShareView() { DataContext = shareViewModel };
                flyout.Show();

                shareViewModel.Activate();
            });
        }
        private async void Save()
        {
            var album = new VkAudioAlbum() { Title = _album.Artist + " - " + _album.Name };

            var flyout = new FlyoutControl();
            flyout.FlyoutContent = new EditAlbumView(album);
            var result = await flyout.ShowAsync();
            if ((bool)result)
            {
                try
                {
                    Debug.WriteLine("Creating new album...");


                    NotificationService.NotifyProgressStarted(MainResources.NotificationSaving);

                    var newAlbumId = await ViewModelLocator.Vkontakte.Audio.AddAlbum(album.Title);

                    Debug.WriteLine("Album created. Id: " + newAlbumId);
                    Debug.WriteLine("Gettings audios...");

                    var progress = new Progress<int>(p => NotificationService.NotifyProgressChanged((int)(p / 2.0f)));

                    var audios = await GetAudioList(progress);

                    Debug.WriteLine("Got audios. Count: " + audios.Count);
                    Debug.WriteLine("Saving audios.");

                    int requestsCount = 0;
                    var audioIds = new List<long>();

                    bool captchaNeeded = false;
                    string captchaImg = string.Empty;
                    string captchaSid = string.Empty;
                    string captchaKey = string.Empty;

                    int progressStep = (int)(100.0f / (audios.Count + 1));

                    for (var i = audios.Count - 1; i > 0; i--)
                    {
                        var vkAudio = audios[i];

                        try
                        {
                            var newAudioId = await ViewModelLocator.Vkontakte.Audio.Add(vkAudio.Id, vkAudio.OwnerId, captchaSid: captchaSid, captchaKey: captchaKey);
                            if (newAudioId != 0)
                            {
                                audioIds.Add(newAudioId);

                                captchaNeeded = false;
                                captchaKey = null;
                                captchaSid = null;
                            }
                        }
                        catch (VkCaptchaNeededException ex)
                        {
                            captchaNeeded = true;
                            captchaImg = ex.CaptchaImg;
                            captchaSid = ex.CaptchaSid;
                        }

                        if (captchaNeeded)
                        {
                            flyout = new FlyoutControl();
                            flyout.FlyoutContent = new CaptchaRequestView(captchaSid, captchaImg);
                            result = await flyout.ShowAsync();
                            if (!string.IsNullOrEmpty((string)result))
                            {
                                captchaKey = (string)result;
                                i = i - 1;
                                continue;
                            }
                            else
                            {
                                NotificationService.NotifyProgressFinished();
                                return;
                            }
                        }

                        NotificationService.NotifyProgressChanged((int)(progressStep / 2.0f));

                        requestsCount++;

                        if (requestsCount >= 2) //не больше 2-х запросов в секунду
                        {
                            requestsCount = 0;
                            await Task.Delay(1000);
                        }
                    }

                    Debug.WriteLine("Audios saved. Moving to album...");

                    if (audioIds.Count > 0)
                    {
                        if (await ViewModelLocator.Vkontakte.Audio.MoveToAlbum(newAlbumId, audioIds))
                        {
                            Debug.WriteLine("Album saved!");

                            NotificationService.NotifyProgressFinished(MainResources.NotificationSaved);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Log(ex);
                }
            }
        }
Beispiel #14
0
 private void TellFriendsRequest()
 {
     var flyout = new FlyoutControl();
     flyout.FlyoutContent = new TellFriendsRequestView();
     flyout.Show();
 }
Beispiel #15
0
        private static void MediaPlayerOnMediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            if (e.ErrorException is InvalidWmpVersionException)
            {
                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new CommonMessageView() { Header = ErrorResources.AudioFailedErrorHeaderCommon, Message = ErrorResources.WmpMissingError };
                flyout.Show();
                return;
            }

            if (CurrentAudio != null)
                LoggingService.Log("Media failed " + CurrentAudio.Artist + " - " + CurrentAudio.Title + ". " + e.ErrorException);

            _playFailsCount++;
            if (_playFailsCount < 5)
            {
                if (RadioService.CurrentRadio == null)
                    Next();
                else
                    RadioService.InvalidateCurrentSong();
            }
        }
        private async void Refresh()
        {
            await ServiceLocator.LocalMusicService.Clear();

            if (Tracks != null)
                Tracks.Clear();

            if (Artists != null)
                Artists.Clear();

            if (Albums != null)
                Albums.Clear();

            if (AlbumGroups != null)
                AlbumGroups.Clear();

            if (SelectedArtistAlbums != null)
                SelectedArtistAlbums.Clear();

            var flyout = new FlyoutControl();
            flyout.FlyoutContent = new MusicScanView();
            await flyout.ShowAsync();

            switch (SelectedTabIndex)
            {
                case 0:
                    LoadTracks();
                    break;
                case 1:
                    LoadAlbums();
                    break;

                case 2:
                    LoadArtists();
                    break;
            }
        }
Beispiel #17
0
        public async void Save()
        {
            try
            {
                var settings = new JsonSerializerSettings()
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };

                var json = JsonConvert.SerializeObject(this, settings);

                File.WriteAllText(SETTINGS_FILE, json);
            }
            catch (UnauthorizedAccessException ex)
            {
                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new CommonErrorView(ErrorResources.AccessDeniedErrorTitle, ErrorResources.AccessDeniedErrorDescription);
                flyout.ShowAsync().ContinueWith(t =>
                {
                    if ((bool)t.Result == true)
                    {
                        var info = new ProcessStartInfo();
                        info.UseShellExecute = true;
                        info.FileName = Application.ResourceAssembly.Location;
                        info.WorkingDirectory = Environment.CurrentDirectory;
                        info.Verb = "runas";

                        Process.Start(info);
                    }

                    Application.Current.Shutdown();

                    LoggingService.Log(ex);
                });
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);
            }
        }
Beispiel #18
0
        private async Task LikeDislikeAudio(Audio audio, bool captchaNeeded = false, string captchaSid = null, string captchaImg = null)
        {
            if (audio == null)
                return;

            IsWorking = true;

            string captchaKey = null;
            if (captchaNeeded)
            {
                var flyout = new FlyoutControl();
                flyout.FlyoutContent = new CaptchaRequestView(captchaSid, captchaImg);
                var result = await flyout.ShowAsync();
                if (string.IsNullOrEmpty((string)result))
                {
                    IsWorking = false;
                    return;
                }
                else
                {
                    captchaKey = (string)result;
                }
            }

            try
            {
                bool result;

                if (!audio.IsAddedByCurrentUser)
                {
                    result = await DataService.RemoveAudio(audio);
                }
                else
                    result = await DataService.AddAudio(audio, captchaSid, captchaKey);

                if (result)
                {
                    //нужно, чтобы обновить список треков пользователя, если он открыт в данный момент
                    MessengerInstance.Send(new UserTracksChangedMessage());
                }
                else
                {
                    audio.IsAddedByCurrentUser = !audio.IsAddedByCurrentUser;
                    LoggingService.Log("Can't add/remove audio " + audio.Id + " owner: " + audio.OwnerId + ".");
                }
            }
            catch (VkCaptchaNeededException ex)
            {
                LikeDislikeAudio(audio, true, ex.CaptchaSid, ex.CaptchaImg);
            }
            catch (Exception ex)
            {
                audio.IsAddedByCurrentUser = !audio.IsAddedByCurrentUser;
                LoggingService.Log(ex);
            }

            IsWorking = false;
        }
Beispiel #19
0
        public static async Task CopyAlbum(string title, long albumId, long ownerId)
        {
            var newAlbumId = await ViewModelLocator.Vkontakte.Audio.AddAlbum(title);

            var audio = await GetUserTracks(albumId: albumId, ownerId: ownerId);
            if (audio.Items != null && audio.Items.Count > 0)
            {

                NotificationService.NotifyProgressStarted(MainResources.NotificationSaving);
                int progressStep = (int)(100.0f / audio.Items.Count);


                bool captchaNeeded = false;
                string captchaImg = string.Empty;
                string captchaSid = string.Empty;
                string captchaKey = string.Empty;

                var audioIds = new List<long>();

                int count = 0;
                audio.Items.Reverse();
                for (int i = 0; i < audio.Items.Count; i++)
                {
                    var track = audio.Items[i];

                    if (count > 1)
                    {
                        count = 0;
                        await Task.Delay(1000); //не больше 2-х запросов в секунду
                    }

                    try
                    {
                        var newAudioId = await ViewModelLocator.Vkontakte.Audio.Add(track.Id, track.OwnerId, captchaSid: captchaSid, captchaKey: captchaKey);
                        audioIds.Add(newAudioId);

                        captchaNeeded = false;
                        captchaKey = null;
                        captchaSid = null;
                    }
                    catch (VkCaptchaNeededException ex)
                    {
                        captchaNeeded = true;
                        captchaImg = ex.CaptchaImg;
                        captchaSid = ex.CaptchaSid;
                    }

                    if (captchaNeeded)
                    {
                        var flyout = new FlyoutControl();
                        flyout.FlyoutContent = new CaptchaRequestView(captchaSid, captchaImg);
                        var result = await flyout.ShowAsync();
                        if (!string.IsNullOrEmpty((string)result))
                        {
                            captchaKey = (string)result;
                            i = i - 1;
                            continue;
                        }
                        else
                        {
                            NotificationService.NotifyProgressFinished();
                            return;
                        }
                    }

                    count++;

                    NotificationService.NotifyProgressChanged(progressStep);
                }

                await ViewModelLocator.Vkontakte.Audio.MoveToAlbum(newAlbumId, audioIds);

                NotificationService.NotifyProgressFinished(MainResources.NotificationSaved);
            }
        }