public async Task StartLoading(string blockId, string titleBlock)
        {
            try
            {
                Title = titleBlock;
                Changed("Title");
                IsLoading = true;
                Changed("IsLoading");
                var block = await MusicX.Core.VKontakte.Music.Block.GetById(blockId);

                Title = block.Title;
                Changed("Title");
                var tracksVk = block.Audios.ToIAudioFileList();
                var tracks   = await MusicService.ConvertToAudioFile(tracksVk);

                Tracks = new ObservableCollection <AudioFile>(tracks);
                Changed("Tracks");
                IsLoading = false;
                Changed("IsLoading");
            }catch (Exception e)
            {
                IsLoading = false;
                Changed("IsLoading");
                await ContentDialogService.Show(new ExceptionDialog("Ошибка при загрузке треков", "Возможно, ВКонтакте не вернул необходимую информацию", e));
            }
        }
示例#2
0
        public ArtistViewModel()
        {
            ShowPopularTracksCommand = new RelayCommand(() =>
            {
                StaticContent.NavigationContentService.Go(typeof(ArtistAllPopularTracks), Artist.BlockPoularTracksId);
            });

            ShowAblumsCommand = new RelayCommand((() =>
            {
                StaticContent.NavigationContentService.Go(typeof(ArtistAllAlbums), Artist.BlockAlbumsId);
            }));

            LikeArtist = new RelayCommand(async() =>
            {
                try
                {
                    await LikedArtistsService.AddLikedArtist(Artist.Id, Artist.Name, Artist.Banner);
                    var msg = new MessageDialog("Музыкант был добавлен в избранное!");
                    await msg.ShowAsync();
                }catch (Exception e)
                {
                    await ContentDialogService.Show(new ExceptionDialog("Невозможно добавить исполнителя в избранное", "Повторите позже, если это не поможет перезапустите приложение.", e));
                }
            });
        }
        public async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (StaticContent.OpenFiles)
                {
                    StaticContent.OpenFiles = false;
                    if (StaticContent.NowPlay != null)
                    {
                        await PlayMusicService.PlayMusicForLibrary(StaticContent.NowPlay, 2);

                        Changed("Playlists");
                    }

                    if (StaticContent.NowPlayPlaylist != null)
                    {
                        await PlayMusicService.PlayMusicForLibrary(StaticContent.NowPlayPlaylist.TracksFiles[0], 3, StaticContent.NowPlayPlaylist);

                        Changed("Playlists");
                    }
                }
            }catch (Exception ee)
            {
                await ContentDialogService.Show(new ExceptionDialog("Ошибка при загрузке домашней страницы", "Music X не смог запустить последний файл, который играл у Вас на компьютере.", ee));
            }

            Changed("Playlists");
            Changed("Music");
        }
        private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            Task.Run(async() =>
            {
                try
                {
                    var file = track.Source;

                    var mp3FileAbs = new FileMp3Abstraction()
                    {
                        Name        = file.Name,
                        ReadStream  = await file.OpenStreamForReadAsync(),
                        WriteStream = await file.OpenStreamForWriteAsync(),
                    };
                    using (var mp3File = TagLib.File.Create(mp3FileAbs))
                    {
                        mp3File.Tag.AlbumArtists = new string[] { ArtistName };
                        mp3File.Tag.Album        = AlbumName;
                        mp3File.Tag.Title        = TitleTrack;
                        mp3File.Tag.Year         = uint.Parse(YearAlbum);
                        mp3File.Tag.Genres       = new string[] { Genre };
                        mp3File.Save();
                    }
                }
                catch (Exception e)
                {
                    await ContentDialogService.Show(new ExceptionDialog("Ошибка при сохранении данных о треке", "Music X не смог сохранить информацию. Возможно, трек недоступен или Вы использовали запрещенные символы", e));
                }
            });
        }
        private async void Timer2_Tick(object sender, object e)
        {
            await ContentDialogService.Show(new TelegramContentDialog());

            _timer2.Stop();
            //throw new NotImplementedException();
        }
示例#6
0
        public async Task <List <PlaylistFile> > GetMorePlaylist(CancellationToken token, uint offset)
        {
            if (InternetService.Connected)
            {
                try
                {
                    IList <IPlaylistFile> playlistsVk;
                    List <PlaylistFile>   playlists = new List <PlaylistFile>();
                    try
                    {
                        IsLoading = true;
                        Changed("IsLoading");
                        playlistsVk = await Library.Playlists(20, Playlists.Count);

                        foreach (var playlist in playlistsVk)
                        {
                            playlists.Add(await Services.VKontakte.PlaylistsService.ConvertToPlaylistFile(playlist));
                        }
                    }
                    catch (Flurl.Http.FlurlHttpException)
                    {
                        IsLoading = false;
                        Changed("IsLoading");
                        hasMorePlaylists = false;
                        await ContentDialogService.Show(new ErrorConnectContentDialog());

                        InternetService.GoToOfflineMode();
                    }

                    if (playlists.Count == 0)
                    {
                        VisibilityNoPlaylists = Visibility.Visible;
                        Changed("VisibilityNoPlaylists");
                    }

                    if (playlists.Count < 20)
                    {
                        hasMorePlaylists = false;
                    }
                    IsLoading = false;
                    Changed("IsLoading");
                    return(playlists);
                }catch (Exception e)
                {
                    IsLoading = false;
                    Changed("IsLoading");
                    await ContentDialogService.Show(new ExceptionDialog("Неизвестная ошибка при получении плейлистов", "Мы не смогли получить информацию о Ваших плейлистах", e));

                    return(new List <PlaylistFile>());
                }
            }
            else
            {
                IsLoading = false;
                Changed("IsLoading");
                InternetService.GoToOfflineMode();
                return(new List <PlaylistFile>());
            }
        }
示例#7
0
 private async void Button_Click_1(object sender, RoutedEventArgs e)
 {
     try
     {
         StaticContent.NavigationContentService.Go(typeof(HomeLocalView));
     }catch (Exception ee)
     {
         await ContentDialogService.Show(new ExceptionDialog("Невозможно попасть на домашнюю страницу", "Эта проблема скоро будет исправлена", ee));
     }
 }
示例#8
0
        public async Task <List <AudioFile> > GetMoreAudio(CancellationToken token, uint offset)
        {
            if (InternetService.Connected)
            {
                try
                {
                    if (firstLoading)
                    {
                        IsLoading = true;
                        Changed("IsLoading");
                    }
                    IList <IAudioFile> tracks = new List <IAudioFile>();
                    List <AudioFile>   music  = new List <AudioFile>();
                    try
                    {
                        tracks = await Popular.Tracks(20, Tracks.Count);

                        music = await MusicService.ConvertToAudioFile(tracks);
                    }
                    catch (Flurl.Http.FlurlHttpException)
                    {
                        music          = new List <AudioFile>();
                        hasMoreLoading = false;

                        await ContentDialogService.Show(new ErrorConnectContentDialog());

                        InternetService.GoToOfflineMode();
                    }

                    if (music.Count < 20)
                    {
                        hasMoreLoading = false;
                    }

                    firstLoading = false;

                    IsLoading = false;
                    Changed("IsLoading");
                    return(music);
                }catch (Exception e)
                {
                    await ContentDialogService.Show(new ExceptionDialog("Неизвестная ошибка при получении списка популярного", "Мы не смогли получить нужную нам информацию о треках", e));

                    return(new List <AudioFile>());
                }
            }
            else
            {
                hasMoreLoading = false;
                InternetService.GoToOfflineMode();
                return(new List <AudioFile>());
            }
        }
        public async void MusicListView_Tapped(object sender, TappedRoutedEventArgs e)
        {
            try
            {
                if (SelectedAudioFile != StaticContent.NowPlay)
                {
                    await PlayMusicService.PlayMusicForLibrary(SelectedAudioFile, 1);

                    Changed("Playlists");
                }
            }catch (Exception ee)
            {
                await ContentDialogService.Show(new ExceptionDialog("Ошибка при клике на трек", "Произошла неизвестная ошибка", ee));
            }
        }
        private DownloadsViewModel()
        {
            Service = DownloaderService.GetService;
            Service.CurrentDownloadFileChanged += Service_CurrentDownloadFileChanged;
            Service.DownloadProgressChanged    += Service_DownloadProgressChanged;
            Service.DownloadQueueComplete      += Service_DownloadQueueComplete;
            Service.DownloadComplete           += Service_DownloadComplete;

            if (Service.CurrentDownloadTrack != null)
            {
                CurrentDownloadFile = Service.CurrentDownloadTrack;
                Changed("CurrentDownloadFile");
                MaximumValue            = Service.Maximum;
                VisibilityNoNowDownload = Visibility.Collapsed;
                VisibilityNowDownload   = Visibility.Visible;
                Changed("VisibilityNoNowDownload");
                Changed("VisibilityNowDownload");
                Changed("TitleString");
                Changed("MaximumValue");
                Changed("ArtistString");
                Changed("AlbumString");
                Changed("YearAlbumString");
            }
            else
            {
                VisibilityNoNowDownload = Visibility.Visible;
                VisibilityNowDownload   = Visibility.Collapsed;
                Changed("VisibilityNoNowDownload");
                Changed("VisibilityNowDownload");
            }

            playlistCurrent = new PlaylistFile()
            {
                Artist  = "",
                Cover   = "ms-appx:///Assets/Images/playlist-placeholder.png",
                Id      = 778,
                IsLocal = true,
                Year    = "2019",
                IsAlbum = false,
                Genre   = "без жанра",
                Name    = "Загруженное"
            };

            ShowQueueCommand = new RelayCommand(async() =>
            {
                await ContentDialogService.Show(new QueueDownloadContentDialog(Service.QueueTracks));
            });
        }
示例#11
0
 public LikedArtistsViewModel()
 {
     DeleteCommand = new RelayCommand <LikedArtist>(async(artist) =>
     {
         try
         {
             await LikedArtistsService.RemoveArtist(artist.Id);
             var msg = new MessageDialog($"Исполнитель {artist.Name} больше не находится в Ваших любимчиках!");
             Artists.Remove(SelectArtist);
             Changed("Artists");
         }catch (Exception e)
         {
             await ContentDialogService.Show(new ExceptionDialog("Невозможно удалить артиста", "Пока что нет возможности удалить, но скоро все будет хорооооошо :)", e));
         }
     });
 }
示例#12
0
        private PlaylistViewModel()
        {
            DownloadIsActive = true;

            EditPlaylist = new RelayCommand(async() =>
            {
                if (Playlist.Id != 1 & Playlist.Id != 2 & Playlist.Id != 1000 && Playlist.IsLocal)
                {
                    await ContentDialogService.Show(new EditPlaylistContentDialog(Playlist));
                    Changed("Playlist");
                }
                else
                {
                    await new MessageDialog("Этот плейлист невозможно изменить", "Ошибка редактирования плейлиста").ShowAsync();
                }
            });
        }
示例#13
0
        public async Task LoadingInfo()
        {
            try
            {
                var user = await Fooxboy.MusicX.Core.VKontakte.Users.Info.CurrentUser();

                NameUser  = $"{user.FirstName} {user.LastName}";
                ImageUser = await ImagesService.AvatarUser(user.PhotoUser);

                Changed("NameUser");
                Changed("ImageUser");
            }catch (Flurl.Http.FlurlHttpException)
            {
                await ContentDialogService.Show(new ErrorConnectContentDialog());

                InternetService.GoToOfflineMode();
            }catch (Exception e)
            {
                await ContentDialogService.Show(new ExceptionDialog("Невозможно получить информацию о вашем аккаунте", "", e));
            }
        }
示例#14
0
        async void AddToPlaylist(PlaylistFile playlist)
        {
            try
            {
                if (playlist.TracksFiles.Any(t => t == Track))
                {
                    return;
                }
                Track.PlaylistId = playlist.Id;
                playlist.TracksFiles.Add(Track);
                await Services.PlaylistsService.SavePlaylist(playlist);

                var index = StaticContent.Music.IndexOf(Track);
                var track = StaticContent.Music[index];
                track.PlaylistId = playlist.Id;
                await MusicFilesService.UpdateMusicCollection();
            }catch (Exception e)
            {
                await ContentDialogService.Show(new ExceptionDialog("Невозможно добавить трек в плейлист", "Возможно, плейлиста не существует или трек был удален", e));
            }
        }
示例#15
0
        public async Task StartDownloadAudio(AudioFile audio)
        {
            try
            {
                var track = new DownloadAudioFile()
                {
                    Title     = audio.Title.Replace("*", "").Replace(".", "").Replace("\"", "").Replace("\\", "").Replace("/", "").Replace("[", "").Replace("]", "").Replace(":", "").Replace(";", "").Replace("|", "").Replace("=", "").Replace(",", ""),
                    AlbumName = audio.Title.Replace("*", "").Replace(".", "").Replace("\"", "").Replace("\\", "").Replace("/", "").Replace("[", "").Replace("]", "").Replace(":", "").Replace(";", "").Replace("|", "").Replace("=", "").Replace(",", ""),
                    AlbumYear = "2019",
                    Artist    = audio.Artist.Replace("*", "").Replace(".", "").Replace("\"", "").Replace("\\", "").Replace("/", "").Replace("[", "").Replace("]", "").Replace(":", "").Replace(";", "").Replace("|", "").Replace("=", "").Replace(",", ""),
                    Cover     = audio.Cover,
                    Url       = audio.SourceString,
                    FromAlbum = false,
                    AudioFile = audio
                };
                AddToQueue(track);

                StorageFolder folder = await KnownFolders.MusicLibrary.TryGetItemAsync("Music X") == null ?
                                       await KnownFolders.MusicLibrary.CreateFolderAsync("Music X")
                    : await KnownFolders.MusicLibrary.GetFolderAsync("Music X");


                if ((await folder.TryGetItemAsync($"{track.Artist} - {track.Title} (Music X).mp3")) != null)
                {
                    return;
                }

                if (CurrentDownloadTrack == null)
                {
                    var task = Task.Run(async() =>
                    {
                        await DownloadAudio(track);
                    });
                }
            }catch (Exception e)
            {
                await ContentDialogService.Show(new ExceptionDialog("Невозможно начать загрузку трека", "Попробуйте чуть-чуть позже", e));
            }
        }
        public async Task StartLoading(string blockId, string titleBlock)
        {
            try
            {
                Title = titleBlock;
                Changed("Title");
                IsLoading = true;
                Changed("IsLoading");
                var block = await MusicX.Core.VKontakte.Music.Block.GetById(blockId);

                Title = block.Title;
                Changed("Title");
                var almbs    = block.Playlists;
                var albumsVk = new List <IPlaylistFile>();
                foreach (var al in almbs)
                {
                    albumsVk.Add(al.ToIPlaylistFile(new List <IAudioFile>(), "Различные исполнители"));
                }
                var albums = new List <PlaylistFile>();

                foreach (var album in albumsVk)
                {
                    Albums.Add(await Services.VKontakte.PlaylistsService.ConvertToPlaylistFile(album));
                }

                IsLoading = false;
                Changed("Albums");
                Changed("IsLoading");
            }catch (Exception e)
            {
                IsLoading = false;
                Changed("IsLoading");

                await ContentDialogService.Show(new ExceptionDialog("Ошибка при загрузке плейлистов", "Попробуйте ещё раз", e));
            }
        }
示例#17
0
        public async Task StartLoading(long artistId, string artistName)
        {
            try
            {
                IsLoading = true;
                Changed("IsLoading");
                NameArtist = artistName;
                Changed("NameArtist");
                var artist = await Fooxboy.MusicX.Core.VKontakte.Music.Artists.GetById(artistId);

                Artist     = artist;
                NameArtist = artist.Name;
                Changed("NameArtist");
                var tracks = new List <IAudioFile>();
                for (int i = 0; i < 6; i++)
                {
                    tracks.Add(artist.PopularTracks[i]);
                }

                PopularTracks = await MusicService.ConvertToAudioFile(tracks);

                PopularTracksVisibility = Visibility.Visible;
                Changed("PopularTracksVisibility");
                Changed("PopularTracks");
                var albums = new List <PlaylistFile>();
                foreach (var plist in artist.Albums)
                {
                    albums.Add(await PlaylistsService.ConvertToPlaylistFile(plist));
                }

                Albums           = albums;
                AlbumsVisibility = Visibility.Visible;
                Changed("AlbumsVisibility");
                Changed("Albums");
                if (artist.Banner != "no")
                {
                    Banner = await ImagesService.BannerArtist(artist.Banner);

                    Changed("Banner");
                }
                else
                {
                    //Assets/Images/placeholder-artist.jpg
                }

                if (artist.LastRelease != null)
                {
                    LastRelease = await PlaylistsService.ConvertToPlaylistFile(artist.LastRelease);

                    LastAlbumVisibility = Visibility.Visible;
                    Changed("LastAlbumVisibility");
                    Changed("LastRelease");
                }

                if (await LikedArtistsService.IsLikedArtist(artist.Id))
                {
                    EnableAddToLikedArtists = false;
                    Changed("EnableAddToLikedArtists");
                }
                else
                {
                    EnableAddToLikedArtists = true;
                    Changed("EnableAddToLikedArtists");
                }

                IsLoading = false;
                Changed("IsLoading");
            }
            catch (Exception e)
            {
                await ContentDialogService.Show(new ExceptionDialog("Ошибка при загрузке карточки исполнителя",
                                                                    "Возможно, исполнитель недоступен в Вашей стране или ВКонтакте не вернул необходимую информацию",
                                                                    e));
            }
        }
示例#18
0
        public TrackControl()
        {
            this.InitializeComponent();

            PlayCommand = new RelayCommand(async() =>
            {
                if (Track.IsLocal)
                {
                    await PlayMusicService.PlayMusicForLibrary(Track, 1);
                }
                else
                {
                    await MusicService.PlayMusic(Track, 1);
                }
            });



            DeleteCommand = new RelayCommand(async() =>
            {
                try
                {
                    if (Track.IsLocal)
                    {
                        StaticContent.Music.Remove(Track);
                        AudioFile trackByPlaylist = null;
                        if (Track.PlaylistId != 0)
                        {
                            var playlist    = await Services.PlaylistsService.GetById(Track.PlaylistId);
                            trackByPlaylist = playlist.TracksFiles.Single(t => t.SourceString == Track.SourceString);
                            playlist.TracksFiles.Remove(trackByPlaylist);
                            await Services.PlaylistsService.SavePlaylist(playlist);
                        }
                        if (trackByPlaylist != null)
                        {
                            if (trackByPlaylist.Source == null)
                            {
                                trackByPlaylist.Source = await StorageFile.GetFileFromPathAsync(Track.SourceString);
                            }
                            await trackByPlaylist.Source.DeleteAsync();
                        }
                        else
                        {
                            if (Track.Source == null)
                            {
                                Track.Source = await StorageFile.GetFileFromPathAsync(Track.SourceString);
                            }
                            await Track.Source.DeleteAsync();
                        }

                        await MusicFilesService.UpdateMusicCollection();
                    }
                    else
                    {
                        //TODO: удаление трека ебаный врот
                    }
                }catch (Exception e)
                {
                    await ContentDialogService.Show(new ExceptionDialog("Невозможно удалить этот трек", "Возможно, этот трек был уже удален.", e));
                }
            });

            AddToFavoriteCommand = new RelayCommand(async() =>
            {
                try
                {
                    if (Track.IsLocal)
                    {
                        var playlist = await Services.PlaylistsService.GetById(2);
                        if (playlist.TracksFiles.Any(t => t.SourceString == Track.SourceString))
                        {
                            var dialog = new MessageDialog("Данный трек уже добавлен в избранное", "Ошибка при добавлении в избранное");
                            await dialog.ShowAsync();
                        }
                        else
                        {
                            Like.Visibility    = Visibility.Collapsed;
                            LikeAdd.Visibility = Visibility.Visible;
                            Track.IsFavorite   = true;
                            playlist.TracksFiles.Add(Track);
                            await Services.PlaylistsService.SavePlaylist(playlist);
                        }
                    }
                    else
                    {
                    }
                }catch (Exception e)
                {
                    await ContentDialogService.Show(new ExceptionDialog("Невозможно добавить трек в избранное", "Возможно, этот трек поврежден или не существует плейлиста, если ошибка будет повторяться, переустановите приложение.", e));
                }
            });

            RemoveFavoriteCommand = new RelayCommand(() =>
            {
            });

            AddOnLibraryCommand = new RelayCommand(async() =>
            {
                try
                {
                    await Fooxboy.MusicX.Core.VKontakte.Music.Add.ToLibrary(Track.Id, Track.AccessKey);
                    await new MessageDialog("Трек добавлен в Вашу библиотеку").ShowAsync();
                }catch (Flurl.Http.FlurlHttpException)
                {
                    InternetService.GoToOfflineMode();
                }
                catch (Exception e)
                {
                    await ContentDialogService.Show(new ExceptionDialog("Ошибка при добавлении трека", "Возникла ошибка при добавлении трека в Вашу библиотеку", e));
                }
            });

            GetPropertyCommand = new RelayCommand(async() =>
            {
                await ContentDialogService.Show(new PropertiesTrackContentDialog(Track));
            });

            GoToArtistCommand = new RelayCommand(() =>
            {
                StaticContent.NavigationContentService.Go(typeof(ArtistView), new ArtistParameter()
                {
                    Id   = Track.ArtistId,
                    Name = Track.Artist
                });
            });
        }
示例#19
0
        private CreatePlaylistViewModel()
        {
            CreatePlaylist = new RelayCommand(async() =>
            {
                if (StaticContent.Playlists.Count >= 15 && StaticContent.IsPro == false)
                {
                    await new MessageDialog("У Вас уже есть 15 плейлистов. Для того, чтобы создать больше 15 плейлистов, необходимо купить MusicX Pro", "Купите MusicX Pro").ShowAsync();
                }
                else
                {
                    try
                    {
                        var playlist = new PlaylistFile()
                        {
                            Artist      = "Music X",
                            Cover       = ImagePlaylist,
                            Id          = new Random().Next(10, 1234),
                            Name        = NamePlaylist,
                            TracksFiles = new List <AudioFile>(),
                            IsLocal     = true
                        };

                        await PlaylistsService.SavePlaylist(playlist);
                        StaticContent.Playlists.Add(playlist);
                        VisibilityGridCreate = Visibility.Collapsed;
                        VisibilityGridDone   = Visibility.Visible;
                        NamePlaylist         = "";
                        Changed("NamePlaylist");
                    }
                    catch (Exception e)
                    {
                        await ContentDialogService.Show(new ExceptionDialog("Невозможно создать плейлист", "Возможно, такой плейлист уже существует. Попробуйте ещё раз.", e));
                    }
                }
            });

            SelectCover = new RelayCommand(async() =>
            {
                try
                {
                    var picker      = new Windows.Storage.Pickers.FileOpenPicker();
                    picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
                    picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
                    picker.FileTypeFilter.Add(".jpg");
                    picker.FileTypeFilter.Add(".png");

                    Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
                    if (file != null)
                    {
                        StorageFile cover;
                        try
                        {
                            cover = await file.CopyAsync(StaticContent.CoversFolder);
                        }
                        catch
                        {
                            cover = await StaticContent.CoversFolder.GetFileAsync(file.Name);
                            await file.CopyAndReplaceAsync(cover);
                        }

                        ImagePlaylist = cover.Path;
                    }
                    else
                    {
                    }
                }catch (Exception e)
                {
                    await ContentDialogService.Show(new ExceptionDialog("Ошибка при выборе файла", "Неизвестная ошибка", e));
                }
            });

            visibilityGridCreate = Visibility.Visible;
            visibilityGridDone   = Visibility.Collapsed;
        }
示例#20
0
        private AuthViewModel()
        {
            IsActiveProgressRing = false;
            VisibilityButton     = Visibility.Visible;
            LoginCommand         = new RelayCommand(async() =>
            {
                IsActiveProgressRing = true;
                VisibilityButton     = Visibility.Collapsed;
                Changed("IsActiveProgressRing");
                Changed("VisibilityButton");

                if (Login == null || Password == null)
                {
                    await new MessageDialog("Вы не указали логин или пароль").ShowAsync();
                    IsActiveProgressRing = false;
                    VisibilityButton     = Visibility.Visible;
                    Changed("IsActiveProgressRing");
                    Changed("VisibilityButton");
                    return;
                }

                string token = null;

                try
                {
                    token = await AuthService.FirstAuth(Login, Password);
                }
                catch (VkNet.Exception.UserAuthorizationFailException)
                {
                    await ContentDialogService.Show(new IncorrectLoginOrPasswordContentDialog());
                }
                catch (VkNet.Exception.VkAuthorizationException)
                {
                    await ContentDialogService.Show(new IncorrectLoginOrPasswordContentDialog());
                }
                catch (VkNet.Exception.VkApiAuthorizationException)
                {
                    await ContentDialogService.Show(new IncorrectLoginOrPasswordContentDialog());
                }
                catch (VkNet.Exception.UserDeletedOrBannedException)
                {
                    await ContentDialogService.Show(new IncorrectLoginOrPasswordContentDialog());
                }
                catch (Flurl.Http.FlurlHttpException)
                {
                    await ContentDialogService.Show(new ErrorConnectContentDialog());
                }catch (Exception e)
                {
                    await ContentDialogService.Show(new ExceptionDialog("Неизвестная ошибка авторизации", "", e));
                }

                if (token != null)
                {
                    try
                    {
                        PlayerMenuViewModel.Instanse.VkontaktePages = Visibility.Visible;
                        await TokenService.Save(token);
                        StaticContent.IsAuth = true;
                        StaticContent.CurrentSessionIsAuth = true;
                        StaticContent.NavigationContentService.Go(typeof(HomeView));
                    }catch (Exception e)
                    {
                        await ContentDialogService.Show(new ExceptionDialog("Неизвестная ошибка после авторизации", "Возможно, ошибка навигации или сохранения", e));
                        PlayerMenuViewModel.Instanse.VkontaktePages = Visibility.Collapsed;
                        StaticContent.IsAuth = false;
                        StaticContent.CurrentSessionIsAuth = false;
                    }
                }
                else
                {
                    IsActiveProgressRing = false;
                    VisibilityButton     = Visibility.Visible;
                    Changed("IsActiveProgressRing");
                    Changed("VisibilityButton");
                }
            });
        }
示例#21
0
        private async void CheckProgress(object sender, object o)
        {
            if (CurrentDownloadOperation != null && CurrentDownloadTrack != null)
            {
                var a = CurrentDownloadOperation.Progress.BytesReceived;
                DownloadProgressChanged?.Invoke(this, a);
                if (CurrentDownloadOperation.Progress.Status == BackgroundTransferStatus.Completed && DownloadAccess)
                {
                    DownloadAccess = false;
                    var trackFile = currentFileAudio;
                    var track     = CurrentDownloadTrack;


                    var mp3FileAbs = new FileMp3Abstraction()
                    {
                        Name        = trackFile.Name,
                        ReadStream  = await trackFile.OpenStreamForReadAsync(),
                        WriteStream = await trackFile.OpenStreamForWriteAsync(),
                    };

                    var task = Task.Run(() =>
                    {
                        using (var mp3File = TagLib.File.Create(mp3FileAbs))
                        {
                            mp3File.Tag.AlbumArtists = new string[] { track.Artist };
                            mp3File.Tag.Title        = track.Title;
                            mp3File.Tag.Album        = track.AlbumName;
                            mp3File.Tag.Year         = uint.Parse(track.AlbumYear);
                            mp3File.Tag.Lyrics       = "Загружено с ВКонтакте с помощью Music X Player (UWP)";
                            mp3File.Tag.Copyright    = "Music X Player (UWP)";
                            mp3File.Tag.Conductor    = "Music X Player";
                            mp3File.Tag.Comment      = "Загружено с ВКонтакте с помощью Music X Player (UWP)";
                            mp3File.Save();
                        }
                    });

                    var task2 = task.ContinueWith((b) =>
                    {
                        var currentDownloadedTrack = new DownloadAudioFile()
                        {
                            AlbumName = CurrentDownloadTrack.AlbumName,
                            FromAlbum = CurrentDownloadTrack.FromAlbum,
                            AudioFile = CurrentDownloadTrack.AudioFile,
                            AlbumYear = CurrentDownloadTrack.AlbumYear,
                            Artist    = CurrentDownloadTrack.Artist,
                            Cover     = CurrentDownloadTrack.Cover,
                            Title     = CurrentDownloadTrack.Title,
                            Url       = CurrentDownloadTrack.Url
                        };

                        currentDownloadedTrack.AudioFile.SourceString = currentFileAudio.Path;
                        currentDownloadedTrack.AudioFile.Source       = currentFileAudio;
                        currentDownloadedTrack.AudioFile.IsLocal      = true;

                        DispatcherHelper.CheckBeginInvokeOnUI(() =>
                        {
                            DownloadComplete?.Invoke(this, currentDownloadedTrack);
                        });
                    });
                }
                else if (CurrentDownloadOperation.Progress.Status == BackgroundTransferStatus.Idle && DownloadAccess)
                {
                    try
                    {
                        await CurrentDownloadOperation.StartAsync();
                    }
                    catch
                    {
                        //ниче не делаем, операция уже запущена
                    }
                }
                else if (CurrentDownloadOperation.Progress.Status == BackgroundTransferStatus.Error && DownloadAccess)
                {
                    DownloadAccess = false;
                    await ContentDialogService.Show(new ExceptionDialog("Возникла ошибка при загрузке трека", "Возможно, ссылка недоступна", new Exception("BackgroundTransferStatus.Error")));

                    DownloadComplete?.Invoke(this, CurrentDownloadTrack);
                }
            }
        }
        private async void Timer_Tick(object sender, object e)
        {
            await ContentDialogService.Show(new FeedbackMeContentDialog());

            _timer.Stop();
        }
示例#23
0
        /// <summary>
        /// Приватный конструкор
        /// </summary>
        private PlayerViewModel()
        {
            StaticContent.AudioService.PlayStateChanged    += AudioServicePlayStateChanged;
            StaticContent.AudioService.PositionChanged     += AudioServicePositionChanged;
            StaticContent.AudioService.CurrentAudioChanged += AudioServiceCurrentAudioChanged;

            RemoveToFavoriteButtonVisibility = Visibility.Visible;
            AddToFavoriteButtonVisibility    = Visibility.Collapsed;
            DownloadButtonVisibility         = Visibility.Collapsed;

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

                Changed("VisibilityTextPlay");
                Changed("VisibilityTextPause");
            }
                );

            SwitchNextCommand = new RelayCommand(() =>
            {
                PositionSeconds = 0;
                StaticContent.AudioService.SwitchNext(skip: true);
            });

            SwitchPrevCommand = new RelayCommand(() =>
            {
                PositionSeconds = 0;
                StaticContent.AudioService.SwitchPrev();
            });

            RepeatSwitch = new RelayCommand(() =>
            {
            });

            ShuffleSwitch = new RelayCommand(() =>
            {
                Shuffle = !Shuffle;

                StaticContent.Shuffle = Shuffle;
            });

            DownloadCommand = new RelayCommand(() =>
            {
                ContentDialogService.Show(new ExceptionDialog("Загрузок больше нет.", "Ждите обновлений и они обязательно вернуться!", new Exception("Раздел с загрузками жеско избили и теперь они находятся в больнице. Доктор говорит, что их выпишут только через несколько апдейтов.")), 1);
            });

            AddToFavoriteCommand = new RelayCommand(async() =>
            {
                var playlist = await Services.PlaylistsService.GetById(2);
                if (playlist.TracksFiles.Any(t => t.SourceString == CurrentAudio.SourceString))
                {
                    AddToFavoriteButtonVisibility = Visibility.Collapsed;
                    Changed("AddToFavoriteButtonVisibility");
                    RemoveToFavoriteButtonVisibility = Visibility.Visible;
                    Changed("RemoveToFavoriteButtonVisibility");
                    var dialog = new MessageDialog("Данный трек уже добавлен в избранное", "Ошибка при добавлении в избранное");
                    await dialog.ShowAsync();
                }
                else
                {
                    AddToFavoriteButtonVisibility = Visibility.Collapsed;
                    Changed("AddToFavoriteButtonVisibility");
                    RemoveToFavoriteButtonVisibility = Visibility.Visible;
                    Changed("RemoveToFavoriteButtonVisibility");

                    CurrentAudio.IsFavorite = true;
                    playlist.TracksFiles.Add(CurrentAudio);
                    await Services.PlaylistsService.SavePlaylist(playlist);
                }
            });

            Changed("Repeat");
            Changed("Volume");
        }
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            goPro.Visibility = StaticContent.IsPro ? Visibility.Collapsed : Visibility.Visible;
            if (!StaticContent.OpenFiles)
            {
                Models.LastPlay  lastPlayMusic = null;
                Models.AudioFile track         = null;

                try
                {
                    lastPlayMusic = await MusicFilesService.GetLastPlayAudio();

                    track = lastPlayMusic.Track;
                }catch
                {
                }

                if (track != null)
                {
                    try
                    {
                        if (track.IsLocal)
                        {
                            try
                            {
                                track.Source = await StorageFile.GetFileFromPathAsync(track.SourceString);

                                track.Duration = TimeSpan.FromSeconds(track.DurationSeconds);
                            }
                            catch (Exception)
                            {
                                track.Source = await StorageFile.GetFileFromApplicationUriAsync(new Uri(track.SourceString));

                                track.Duration = TimeSpan.FromSeconds(track.DurationSeconds);
                            }

                            if (lastPlayMusic.Playlist != null)
                            {
                                var playlist = lastPlayMusic.Playlist.ToAudioPlaylist();
                                playlist.CurrentItem = track;
                                StaticContent.AudioService.SetCurrentPlaylist(playlist);
                            }
                            else
                            {
                                StaticContent.AudioService.CurrentPlaylist.CurrentItem = track;
                            }
                        }
                        else
                        {
                            track.Duration = TimeSpan.FromSeconds(track.DurationSeconds);
                            if (lastPlayMusic.Playlist != null)
                            {
                                var playlist = lastPlayMusic.Playlist.ToAudioPlaylist();
                                playlist.CurrentItem = track;
                                StaticContent.AudioService.SetCurrentPlaylist(playlist);
                            }
                            else
                            {
                                StaticContent.AudioService.CurrentPlaylist.CurrentItem = track;
                            }
                        }
                    }catch (Exception ee)
                    {
                        await ContentDialogService.Show(new ExceptionDialog("Ошибка при инициализации страницы плеера", "Возможно, трек, который последний раз играл - был удален или поврежден или к нему нет доступа.", ee));
                    }

                    StaticContent.Volume = lastPlayMusic.Volume;
                    if (StaticContent.AudioService.IsPlaying)
                    {
                        StaticContent.AudioService.Pause();
                    }
                }
            }
        }
示例#25
0
        public async static Task PlayMusic(AudioFile audioFile, int typePlay, PlaylistFile playlistPlay = null)
        {
            if (StaticContent.Config.StreamMusic)
            {
                await MusicX.Core.VKontakte.Music.Library.StreamToStatus(audioFile.Id, audioFile.OwnerId);
            }
            try
            {
                //type play:
                //1 - проигрования из списка треков
                //2 - проигрование трека из плейлиста
                StaticContent.AudioService.Seek(TimeSpan.Zero);
                var playlistNowPlay = new PlaylistFile()
                {
                    Artist      = "Music X",
                    Cover       = "ms-appx:///Assets/Images/now.png",
                    Id          = 1000,
                    Name        = "Сейчас играет",
                    TracksFiles = new List <AudioFile>(),
                    IsLocal     = false
                };


                if (typePlay == 1)
                {
                    foreach (var trackMusic in StaticContent.MusicVKontakte)
                    {
                        playlistNowPlay.TracksFiles.Add(trackMusic);
                    }
                    var index = playlistNowPlay.TracksFiles.IndexOf(playlistNowPlay.TracksFiles.Single(t => t.Id == audioFile.Id));

                    if (index != 0)
                    {
                        StaticContent.AudioService.SetCurrentPlaylist(playlistNowPlay.ToAudioPlaylist(), false);
                        StaticContent.AudioService.CurrentPlaylist.CurrentItem = audioFile;
                    }
                    else
                    {
                        StaticContent.AudioService.SetCurrentPlaylist(playlistNowPlay.ToAudioPlaylist(), true);
                        StaticContent.AudioService.SwitchNext();
                    }

                    StaticContent.NowPlayPlaylist = playlistNowPlay;
                }
                else if (typePlay == 2)
                {
                    StaticContent.NowPlayPlaylist = playlistPlay;
                    playlistNowPlay.TracksFiles   = playlistPlay.TracksFiles;
                    playlistNowPlay.Tracks        = playlistPlay.Tracks;

                    var index = playlistPlay.TracksFiles.IndexOf(playlistPlay.TracksFiles.Single(t => t.Id == audioFile.Id));

                    if (index != 0)
                    {
                        StaticContent.AudioService.SetCurrentPlaylist(playlistPlay.ToAudioPlaylist(), false);
                        StaticContent.AudioService.CurrentPlaylist.CurrentItem = audioFile;
                    }
                    else
                    {
                        StaticContent.AudioService.SetCurrentPlaylist(playlistPlay.ToAudioPlaylist(), true);
                        StaticContent.AudioService.SwitchNext();
                    }
                }

                if (!(StaticContent.PlaylistsVKontakte.Any(p => p.Id == 1000)))
                {
                    StaticContent.PlaylistsVKontakte.Insert(0, playlistNowPlay);
                }
            }catch (Flurl.Http.FlurlHttpException)
            {
                InternetService.GoToOfflineMode();
            } catch (HttpRequestException)
            {
                InternetService.GoToOfflineMode();
            }catch (Exception e)
            {
                await ContentDialogService.Show(new ExceptionDialog("Ошибка при воспроизведении трека", "Произошла неизвестная ошибка.", e));
            }
        }