public static async Task SavePlaylist(PlaylistFile playlist) { var pathPlaylists = await ApplicationData.Current.LocalFolder.GetFolderAsync("Playlists"); StorageFile filePlaylist; try { filePlaylist = await pathPlaylists.GetFileAsync($"Id{playlist.Id}.json"); } catch { filePlaylist = await pathPlaylists.CreateFileAsync($"Id{playlist.Id}.json"); } var jsonString = JsonConvert.SerializeObject(playlist); try { await FileIO.WriteTextAsync(filePlaylist, jsonString); }catch (Exception e) { await ContentDialogService.Show(new ExceptionDialog("Невозможно сохранить плейлист", "Возможно, этот плейлист уже существует.", e)); } }
private async Task <DbOperationResult> Delete_R(PlaylistFile playlistFile) { var stopWatch = new Stopwatch(); stopWatch.Start(); try { using (var conn = DbConnection()) { conn.Open(); conn.Execute( @"DELETE FROM PlaylistFiles WHERE Id = @Id", new { playlistFile.Id }); conn.Close(); } stopWatch.Stop(); return(await Task.FromResult(DbOperationResult.Success(-1, stopWatch.Elapsed))); } catch (Exception e) { stopWatch.Stop(); return(await Task.FromResult(DbOperationResult.Fail(e.Message, stopWatch.Elapsed))); } }
private async Task <DbOperationResult> Update_R(PlaylistFile playlistFile) { var stopWatch = new Stopwatch(); stopWatch.Start(); try { using (var conn = DbConnection()) { conn.Open(); playlistFile.Id = (int)conn.Query <long>( @"UPDATE PlaylistFiles SET Title = @Title, Description = @Description, PlaylistId = @PlaylistId, Path = @Path, LastModifiedDate = @LastModifiedDate, LastUpload = @LastUpload WHERE Id = @Id; SELECT last_insert_rowid()", playlistFile).First(); conn.Close(); } stopWatch.Stop(); return(await Task.FromResult(DbOperationResult.Success(playlistFile.Id, stopWatch.Elapsed))); } catch (Exception e) { stopWatch.Stop(); return(await Task.FromResult(DbOperationResult.Fail(e.Message, stopWatch.Elapsed))); } }
public async Task StartDownloadPlaylist(PlaylistFile playlist) { foreach (var audio in playlist.TracksFiles) { var track = new DownloadAudioFile() { Title = audio.Title.Replace("*", "").Replace(".", "").Replace("\"", "").Replace("\\", "").Replace("/", "").Replace("[", "").Replace("]", "").Replace(":", "").Replace(";", "").Replace("|", "").Replace("=", "").Replace(",", ""), AlbumName = playlist.Name.Replace("*", "").Replace(".", "").Replace("\"", "").Replace("\\", "").Replace("/", "").Replace("[", "").Replace("]", "").Replace(":", "").Replace(";", "").Replace("|", "").Replace("=", "").Replace(",", ""), AlbumYear = playlist.Year, Artist = audio.Artist.Replace("*", "").Replace(".", "").Replace("\"", "").Replace("\\", "").Replace("/", "").Replace("[", "").Replace("]", "").Replace(":", "").Replace(";", "").Replace("|", "").Replace("=", "").Replace(",", ""), Cover = audio.Cover, Url = audio.SourceString, FromAlbum = true, 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"); var playlistName = playlist.Name.Replace("*", "").Replace(".", "").Replace("\"", "").Replace("\\", "").Replace("/", "").Replace("[", "").Replace("]", "").Replace(":", "").Replace(";", "").Replace("|", "").Replace("=", "").Replace(",", ""); StorageFolder playlistFolder = await folder.TryGetItemAsync(playlistName) == null ? await folder.CreateFolderAsync(playlistName) : await folder.GetFolderAsync(playlistName); var task = Task.Run(async() => { await DownloadAudio(QueueTracks.First()); }); }
public void Play(PlaylistFile playlist = null, AudioFile audio = null) { try { StaticContentService.NowPlay = playlist?.TracksFiles; MainService.Play(playlist, audio); }catch (Exception e) { Toast.MakeText(Application.Context, $"Произошла ошибка: {e.ToString()}", ToastLength.Long).Show(); } }
public PlaylistFile Parse(Stream playlistStream) { PlaylistFile playlist = new PlaylistFile(); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(playlistStream); FillMusicFileCollection(xmlDocument, playlist); return(playlist); }
public ArtistAllPopularTracksViewModel() { Tracks = new ObservableCollection <AudioFile>(); SelectPlaylist = new PlaylistFile() { Artist = "", Cover = "ms-appx:///Assets/Images/playlist-placeholder.png", Id = 990, IsLocal = false, Name = "Попопулярные треки исполнителя" }; }
public AllTracksViewModel() { Tracks = new ObservableCollection <AudioFile>(); SelectPlaylist = new PlaylistFile() { Artist = "", Cover = "ms-appx:///Assets/Images/playlist-placeholder.png", Id = 990, IsLocal = false, Name = "amm" }; }
/// <summary> /// Delete a PlayListFile entry from the database /// </summary> /// <param name="playlistFile">PlaylistFile object to delete</param> /// <returns>DbOperationResult - Showing success or fail, with messages and stats</returns> public async Task <DbOperationResult> Delete(PlaylistFile playlistFile) { try { return(await Delete_R(playlistFile)); } catch { ThreadHelper.SafeSleep(50); return(await Delete_R(playlistFile)); } }
private RecommendationsViewModel() { Tracks = new LoadingCollection <AudioFile>(); Tracks.HasMoreItemsRequested = HasMoreLoading; Tracks.OnMoreItemsRequested = GetMoreAudio; playlistCurrent = new PlaylistFile() { Artist = "", Cover = "ms-appx:///Assets/Images/playlist-placeholder.png", Id = 666, IsLocal = false, Name = "Рекомендации" }; }
public EditPlaylistContentDialog(PlaylistFile playlist) { this.InitializeComponent(); Playlist = playlist; if (playlist.TracksFiles.Count == 0) { AddMusicToPlaylist.Visibility = Visibility.Visible; } else { AddMusicToPlaylist.Visibility = Visibility.Collapsed; } }
private SearchViewModel() { Music = new LoadingCollection <AudioFile>(); Music.HasMoreItemsRequested = HasMoreLoading; Music.OnMoreItemsRequested = GetMoreAudio; playlistCurrent = new PlaylistFile() { Artist = "", Cover = "ms-appx:///Assets/Images/playlist-placeholder.png", Id = 666, IsLocal = false, Name = "Результаты поиска" }; }
public void CreatePlaylistFile(string path, IMedia media, IEnumerable <TrackFile> trackFiles, PlaylistFileType type) { try { var playlistFile = PlaylistFile .Create(type) .BuildContent(trackFiles); var fileName = Path.Combine(path, PathHelpers.CreateDefaultFileName(media)); AthameWriter.Write(fileName, playlistFile); } catch (Exception ex) { Log.Warning(ex, "Exception occurred when writing playlist file"); } }
private PopularViewModel() { Tracks = new LoadingCollection <AudioFile>(); Tracks.HasMoreItemsRequested = HasMoreLoading; Tracks.OnMoreItemsRequested = GetMoreAudio; playlistCurrent = new PlaylistFile() { Artist = "", Cover = "ms-appx:///Assets/Images/playlist-placeholder.png", Id = 999, IsLocal = false, Name = "Популярное" }; }
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)); }); }
public static AudioPlaylist ToAudioPlaylist(this PlaylistFile source, AudioFile fileNow) { var audioPlaylist = new AudioPlaylist() { Shuffle = false, Cover = source.Cover, CurrentItem = fileNow, Id = source.Id, Items = source.TracksFiles.Count != 0 ? source.TracksFiles : new List <AudioFile>(), Repeat = Enums.RepeatMode.None, Artist = source.Artist, Name = source.Name }; return(audioPlaylist); }
private static void FillMusicFileCollection(XmlDocument xmlDocument, PlaylistFile playlist) { XmlNodeList mediaNodeList = xmlDocument.DocumentElement.SelectNodes("/smil/body/seq/media"); foreach (XmlNode mediaNode in mediaNodeList) { MusicFile musicFile = new MusicFile() { RelativePath = mediaNode.Attributes["src"].Value }; playlist.MusicFileCollection.Add(musicFile); } Trace.TraceInformation($"Playlist contains {playlist.MusicFileCollection.Count} entries."); }
public static AudioPlaylist ToAudioPlaylist(this PlaylistFile source) { var audioPlaylist = new AudioPlaylist() { Shuffle = StaticContent.Shuffle, Cover = source.Cover, CurrentItem = source.TracksFiles.Count != 0? source.TracksFiles[0]: null, Id = source.Id, Items = source.TracksFiles.Count != 0 ? source.TracksFiles: new List <AudioFile>(), Repeat = StaticContent.Repeat, Artist = source.Artist, Name = source.Name }; return(audioPlaylist); }
private void AdapterOnItemClick(object sender, AudioInBlock args) { Toast.MakeText(Application.Context, $"{args.track.Title} в блоке {args.blockID}", ToastLength.Long).Show(); var tracks = this.Blocks.First(b => b.Title == args.blockID).Tracks; var tracksfiles = MusicService.ConvertToAudioFile(tracks); var playlist = new PlaylistFile(); playlist.Artist = "Music X"; playlist.Cover = "playlist_placeholder"; playlist.Genre = ""; playlist.Id = 1000; playlist.IsAlbum = false; playlist.TracksFiles = tracksfiles; var player = PlayerService.Instanse; player.Play(playlist, playlist.TracksFiles.First(t => t.SourceString == args.track.SourceString)); }
public async void UIElement_OnTappedTracks(object sender, TappedRoutedEventArgs e) { if (SelectPopularAudioFile != null) { var playlistCurrent = new PlaylistFile() { Artist = NameArtist, Cover = "ms-appx:///Assets/Images/playlist-placeholder.png", Id = 666, IsLocal = false, Name = "Популярные треки исполнителя" }; playlistCurrent.TracksFiles = PopularTracks; await MusicService.PlayMusic(SelectPopularAudioFile, 2, playlistCurrent); } }
public async static Task <PlaylistFile> ConvertToPlaylistFile(IPlaylistFile playlist) { string cover; if (playlist.Cover == "no") { cover = "ms-appx:///Assets/Images/playlist-placeholder.png"; } else { cover = await ImagesService.CoverPlaylist(playlist); } List <AudioFile> tracksFiles; if (playlist.IsAlbum) { tracksFiles = await MusicService.ConvertToAudioFile(playlist.Tracks, cover); } else { tracksFiles = await MusicService.ConvertToAudioFile(playlist.Tracks); } var playlistFile = new PlaylistFile() { Artist = playlist.Artist, Cover = cover, IsLocal = false, Tracks = playlist.Tracks, Id = playlist.Id, Name = playlist.Name, TracksFiles = tracksFiles, OnRequest = playlist.OnRequest, AccessKey = playlist.AccessKey, OwnerId = playlist.OwnerId, Genre = playlist.Genre, IsAlbum = playlist.IsAlbum, Year = playlist.Year, Description = playlist.Description }; return(playlistFile); }
public static PlaylistFile ConvertToPlaylistFile(this IPlaylistFile playlist) { string cover; if (playlist.Cover == "no") { cover = "playlist_placeholder"; } else { cover = ImagesService.CoverPlaylist(playlist); } List <AudioFile> tracksFiles; if (playlist.IsAlbum) { tracksFiles = MusicService.ConvertToAudioFile(playlist.Tracks, cover); } else { tracksFiles = MusicService.ConvertToAudioFile(playlist.Tracks); } var playlistFile = new PlaylistFile() { AccessKey = playlist.AccessKey, OwnerId = playlist.OwnerId, Artist = playlist.Artist, Cover = cover, IsLocal = false, Tracks = playlist.Tracks, Id = playlist.Id, Name = playlist.Name, TracksFiles = tracksFiles, Genre = playlist.Genre, IsAlbum = playlist.IsAlbum, Year = playlist.Year, Description = playlist.Description }; return(playlistFile); }
private void AdapterOnItemClick(object sender, AudioFile args) { try { Toast.MakeText(Application.Context, $"Ты тыкнул: {args.Artist} - {args.Title} ", ToastLength.Long).Show(); //Создание плейлиста из локальных трекаф var playlist = new PlaylistFile(); playlist.Artist = "Music X"; playlist.Cover = "playlist_placeholder"; playlist.Genre = ""; playlist.Id = 1000; playlist.IsAlbum = false; playlist.TracksFiles = tracksInResult; var player = PlayerService.Instanse; player.Play(playlist, playlist.TracksFiles.First(t => t.SourceString == args.SourceString)); } catch (System.Exception e) { Toast.MakeText(Application.Context, $"Произошла ошибка: {e.ToString()}", ToastLength.Long).Show(); } }
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)); } }
private void AddPlaylistFileToDB(SQLiteConnection conn, PlaylistFile playlistFile) { // Not using the standard Repos namespace so we don't have to keep creating and // opening new connections try { int?id = conn.ExecuteScalar <int?>( @"SELECT Id FROM PlaylistFiles WHERE Path = @Path LIMIT 1", new { playlistFile.Path }); if (id == null || id == 0) { conn.Execute( @"INSERT INTO PlaylistFiles ( Path, LastModifiedDate) SELECT @Path, @LastModifiedDate", new { playlistFile.Path, playlistFile.LastModifiedDate }); } else { conn.Execute( @"UPDATE PlaylistFiles SET Path = @Path, LastModifiedDate = @LastModifiedDate WHERE Id = @Id", new { playlistFile.Path, playlistFile.LastModifiedDate, id }); } } catch (Exception e) { Console.Out.WriteLine(e.Message); } }
private async Task <DbOperationResult> Insert_R(PlaylistFile playlistFile) { var stopWatch = new Stopwatch(); stopWatch.Start(); try { using (var conn = DbConnection()) { conn.Open(); playlistFile.Id = (int)conn.Query <long>( @"INSERT INTO PlaylisFiles ( Title, Description, PlaylistId, Path, LastModifiedDate, LastUpload) VALUES @Title, @Description, @PlaylistId, @Path, @LastModifiedDate, @LastUpload); SELECT last_insert_rowid()", playlistFile).First(); conn.Close(); } stopWatch.Stop(); return(await Task.FromResult(DbOperationResult.Success(playlistFile.Id, stopWatch.Elapsed))); } catch (Exception e) { stopWatch.Stop(); return(await Task.FromResult(DbOperationResult.Fail(e.Message, stopWatch.Elapsed))); } }
public static async Task DeletePlaylist(PlaylistFile playlist) { try { if (playlist.Id == 1 || playlist.Id == 1000) { var dialog = new MessageDialog("Данный плейлист невозможно удалить.", "Невозможно удалить плейлист"); await dialog.ShowAsync(); return; } var folder = StaticContent.PlaylistsFolder; StaticContent.Playlists.Remove(playlist); var file = await folder.GetFileAsync($"Id{playlist.Id}.json"); await file.DeleteAsync(); }catch (Exception e) { await ContentDialogService.Show(new ExceptionDialog("Невозможно удалить плейлист", "Возможно, этот плейлист уже был удален или он поврежден.", e)); } }
public static async Task PlayPlaylist(PlaylistFile playlist) { try { if (playlist.TracksFiles.Count == 0) { var dialog = new MessageDialog("В данном плейлисте отсутсвуют треки. Пожалуйста, добавте в него треки.", "Невозможно возпроизвести плейлист"); await dialog.ShowAsync(); return; } var folder = StaticContent.PlaylistsFolder; if (StaticContent.NowPlayPlaylist == playlist) { return; } await PlayMusicService.PlayMusicForLibrary(playlist.TracksFiles[0], 3, playlist); }catch (Exception e) { await ContentDialogService.Show(new ExceptionDialog("Невозможно воспроизвести плейлист", "Возможно, он поврежден или он не существует", e)); } }
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; }
async void chimneyMpdServer_OnPlaylistAdd(object sender, ResponseEventArgs e) { bool suc = false; string playlistName = string.Empty; string uri = string.Empty; bool addasuri = false; if (e.arguments.Count > 1) { playlistName = e.arguments[0]; uri = e.arguments[1]; } var playlistToAddTo = await Dbconnection.FindAsync<Playlist>(o => o.Name == playlistName); if (playlistToAddTo == null) { Playlist newStoredPlaylist = new Playlist() { Name = playlistName, LastModified = DateTime.Now.ToString("s") }; await Dbconnection.InsertAsync(newStoredPlaylist); playlistToAddTo = await Dbconnection.FindAsync<Playlist>(o => o.Name == playlistName); } var fileToAdd = await Dbconnection.FindAsync<File>(o => o.RelativePath == uri); if (fileToAdd == null) addasuri = true; if(playlistToAddTo != null) { PlaylistFile newPlaylistFile = new PlaylistFile() { FileId = (addasuri) ? -1 : fileToAdd.FileId, IsUri = addasuri, Uri = (addasuri) ? uri : fileToAdd.FilePath, Position = await Dbconnection.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM PlaylistFiles WHERE PlaylistId = " + playlistToAddTo.PlaylistId), PlaylistId = playlistToAddTo.PlaylistId }; await Dbconnection.InsertAsync(newPlaylistFile); playlistToAddTo.LastModified = DateTime.Now.ToString("s"); await Dbconnection.UpdateAsync(playlistToAddTo); } chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position); if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("stored_playlist")); }
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)); } }