示例#1
0
        /// <summary>
        /// Deletes a song from the FileCollection. <seealso cref="DeleteCommand"/>
        /// </summary>
        /// <param name="path"><see cref="BreadPlayer.Models.Mediafile"/> to delete.</param>
        public async void Delete(object path)
        {
            try
            {
                int index = 0;
                if (SelectedItems.Count > 0)
                {
                    foreach (var item in SelectedItems)
                    {
                        index = TracksCollection.Elements.IndexOf(item);
                        TracksCollection.RemoveItem(item);
                        LibraryService.RemoveMediafile(item);
                    }
                }

                if (TracksCollection.Elements.Count > 0)
                {
                    await Task.Delay(100);

                    SelectedItem = index < TracksCollection.Elements.Count ? TracksCollection.Elements.ElementAt(index) : TracksCollection.Elements.ElementAt(index - 1);
                }
            }
            catch (Exception ex)
            {
                BLogger.Logger.Error("Error occured while deleting a song from collection and list.", ex);
            }
        }
示例#2
0
 public async Task SplitList(int nSize = 30)
 {
     for (int i = 0; i < service.SongCount; i += nSize)
     {
         TracksCollection.AddRange(await service.GetRangeOfMediafiles(i, Math.Min(nSize, service.SongCount - i)).ConfigureAwait(false), false, false);
     }
 }
        private Mediafile GetNextOrPrevSongInGroup(bool prev = false)
        {
            //get current group (the group in which current song is playing).
            Grouping <IGroupKey, Mediafile> currentGroup = TracksCollection.GetCurrentlyPlayingGroup();

            //get the index of the song playing in the currentGroup (with reference to the currentGroup)
            int currentSongIndex = currentGroup.GetPlayingSongIndexInGroup();

            //get next song index (depending on the parameters).
            int nextSongIndex = prev ? currentSongIndex - 1 : currentSongIndex + 1;

            //get condition for next/prev group.
            bool nextGroupCondition = nextSongIndex.Equals(prev ? -1 : currentGroup.Count);

            //get next/prev group index
            int nextGroupIndex = prev ? TracksCollection.IndexOf(currentGroup) - 1 : TracksCollection.IndexOf(currentGroup) + 1;

            //get next/prev group.
            Grouping <IGroupKey, Mediafile> nextGroup = nextGroupCondition ? TracksCollection.ElementAt(nextGroupIndex) : currentGroup;

            //get nextSong index depending on if the group is new or old.
            int toPlaySongIndex = nextGroup.Equals(currentGroup) ? nextSongIndex : 0;

            return(nextGroup.ElementAt(toPlaySongIndex));
        }
        /// <summary>
        /// Deletes a song from the FileCollection. <seealso cref="DeleteCommand"/>
        /// </summary>
        /// <param name="path"><see cref="BreadPlayer.Models.Mediafile"/> to delete.</param>
        public async void Delete(object path)
        {
            try
            {
                int index = 0;
                if (SelectedItems.Count > 0)
                {
                    foreach (var item in SelectedItems)
                    {
                        index = TracksCollection.Elements.IndexOf(item);
                        TracksCollection.RemoveItem(item);
                        LibraryService.RemoveMediafile(item);
                        // SongCount--;
                    }
                }

                if (TracksCollection.Elements.Count > 0)
                {
                    await Task.Delay(100);

                    SelectedItem = index < TracksCollection.Elements.Count ? TracksCollection.Elements.ElementAt(index) : TracksCollection.Elements.ElementAt(index - 1);
                }
            }
            catch
            {
            }
        }
 async Task <object> Search()
 {
     if (QueryWord.Length > 0)
     {
         TracksCollection.Clear();
         TracksCollection.AddRange(await service.Query("Title", QueryWord).ConfigureAwait(false), true);
     }
     return(null);
 }
示例#6
0
        private Mediafile GetNextSongInGroup()
        {
            var currentGroup     = TracksCollection.FirstOrDefault(t => t.Any(c => c.Path == Player.CurrentlyPlayingFile.Path));
            var currentSongIndex = currentGroup.IndexOf(currentGroup.FirstOrDefault(t => t.Path == Player.CurrentlyPlayingFile.Path));
            var nextGroup        = currentSongIndex + 1 == currentGroup.Count ? TracksCollection.ElementAt(TracksCollection.IndexOf(currentGroup) + 1) : currentGroup;
            var toPlaySongIndex  = nextGroup == currentGroup ? currentSongIndex + 1 : 0;

            return(nextGroup.ElementAt(toPlaySongIndex));
        }
示例#7
0
 public void Reset()
 {
     PlaylistSongCollection?.Clear();
     TracksCollection?.Clear();
     DontUpdatePosition = true;
     CurrentPosition    = 0;
     UpcomingSong       = null;
     timer.Stop();
     ShuffledList?.Clear();
     PlayPauseIcon = new SymbolIcon(Symbol.Play);
 }
示例#8
0
 public void Dispose()
 {
     Database.Dispose();
     TracksCollection.Clear();
     RecentlyPlayedCollection.Clear();
     ShellVM.PlaylistsItems.Clear();
     OldItems = null;
     PlaylistCollection.Clear();
     OptionItems.Clear();
     GenreCollection.Clear();
 }
示例#9
0
 async Task <object> Search()
 {
     if (QueryWord.Length > 2)
     {
         TracksCollection.Clear();
         TracksCollection.AddRange((await service.Query("Title", QueryWord).ConfigureAwait(false)), false, false);
         if (TracksCollection.Elements.Count <= 0)
         {
             Messenger.Instance.NotifyColleagues(MessageTypes.MSG_SEARCH_STARTED, "Nothing found for keyword \"" + QueryWord + "\"");
         }
     }
     return(null);
 }
示例#10
0
 async Task Reload()
 {
     if (cache == null || TracksCollection.Elements.Count < service.SongCount)
     {
         TracksCollection.Clear();
         TracksCollection.AddRange(await service.GetAllMediafiles().ConfigureAwait(false), true);
         cache = new ThreadSafeObservableCollection <Mediafile>(TracksCollection.Elements);
     }
     else
     {
         TracksCollection.Clear();
         TracksCollection.AddRange(cache, false, true);
     }
 }
示例#11
0
        public IEnumerable <Track> GetUnheardTracks()
        {
            var playHistory = HistoryManager.Items;

            if (!playHistory.Any())
            {
                return(TracksCollection);
            }

            return(TracksCollection
                   .Where(t => !playHistory.
                          Any(h => h.TrackHashName == t.Model.HashName))
                   .ToList());
        }
示例#12
0
 public void Reset()
 {
     LibraryService.Dispose();
     LibraryService = null;
     TracksCollection.Clear();
     RecentlyPlayedCollection.Clear();
     GenreFlyout?.Items.Clear();
     PlaylistsItems?.Clear();
     OldItems = null;
     PlaylistCollection.Clear();
     OptionItems.Clear();
     GenreCollection.Clear();
     SongCount = -1;
 }
示例#13
0
        public IEnumerable <Track> SearchTracks(string searchText)
        {
            var results = TracksCollection
                          .Select(x => new
            {
                Track = x,
                Score = GetSearchScore(x.DisplayName, searchText)
            })
                          .Where(x => x.Score > 0)
                          .OrderByDescending(x => x.Score)
                          .Select(x => x.Track);

            return(results
                   .Take(50));
        }
示例#14
0
        /// <summary>
        /// Deletes a song from the FileCollection. <seealso cref="DeleteCommand"/>
        /// </summary>
        /// <param name="path"><see cref="BreadPlayer.Models.Mediafile"/> to delete.</param>
        public async void Delete(object path)
        {
            int index = 0;

            foreach (var item in SelectedItems)
            {
                index = TracksCollection.Elements.IndexOf(item);
                TracksCollection.RemoveItem(item);
                Database.Remove(item);
                SongCount--;
            }
            await Task.Delay(100);

            SelectedItem = index < TracksCollection.Elements.Count ? TracksCollection.Elements.ElementAt(index) : TracksCollection.Elements.ElementAt(index - 1);
        }
示例#15
0
        private async void HandleImportFolder(Message message)
        {
            if (message.Payload is IEnumerable <Mediafile> songs)
            {
                message.HandledStatus = MessageHandledStatus.HandledCompleted;

                await SharedLogic.Instance.NotificationManager.ShowMessageAsync("Adding songs into library. Please wait...");

                TracksCollection.AddRange(songs);
                await SharedLogic.Instance.NotificationManager.ShowMessageAsync("Saving songs into database. Please wait...");

                await LibraryService.AddMediafiles(songs).ConfigureAwait(false);

                IsLibraryLoading = false;
                await BreadDispatcher.InvokeAsync(() =>
                {
                    MusicLibraryLoaded?.Invoke(this, new RoutedEventArgs());
                });
            }
        }
示例#16
0
        /// <summary>
        /// Loads songs from a specified folder into the library. <seealso cref="LoadCommand"/>
        /// </summary>
        public async void Load()
        {
            FolderPicker picker = new FolderPicker()
            {
                SuggestedStartLocation = PickerLocationId.MusicLibrary
            };

            picker.FileTypeFilter.Add(".mp3");
            StorageFolder folder = await picker.PickSingleFolderAsync();

            if (folder != null)
            {
                var filelist = await Macalifa.Common.DirectoryWalker.GetFiles(folder.Path);

                foreach (var x in filelist)
                {
                    StorageFile file = await StorageFile.GetFileFromPathAsync(x);

                    Path = file.Path;
                    using (var stream = await Dispatcher.RunTaskAsync(GetFileAsStream))
                    {
                        if (stream != null)
                        {
                            var path = file.Path;
                            if (TracksCollection.Elements.All(t => t.Path != path))
                            {
                                var m = await CreateMediafile(stream);

                                TracksCollection.AddItem(m);
                                //TracksCollection.Elements.Add(m);
                                //ByStringGroupedCollection.AddItem(Mediafile);
                                db.Insert(m);
                            }
                        }
                    }
                }
            }
        }
示例#17
0
        /// <summary>
        /// Deletes a song from the FileCollection. <seealso cref="DeleteCommand"/>
        /// </summary>
        /// <param name="path"><see cref="Macalifa.Models.Mediafile"/> to delete.</param>
        public void Delete(object path)
        {
            if (path is ListBox)
            {
                if (FileListBox == null)
                {
                    FileListBox = path as ListBox;
                }
            }
            else
            {
                var menu = path as MenuFlyoutItem;
                if (FileListBox == null)
                {
                    FileListBox = (menu.Tag as ListBoxItem).GetAncestorsOfType <ListBox>().ToList()[0];
                }
            }
            var       index   = FileListBox.SelectedIndex;
            Mediafile mp3File = FileListBox.SelectedItem as Mediafile;

            TracksCollection.RemoveItem(mp3File);
            FileListBox.SelectedIndex = index - 1;
            FileListBox.Focus(FocusState.Programmatic);
        }
示例#18
0
        /// <summary>
        /// Add folder to Library asynchronously.
        /// </summary>
        /// <param name="queryResult">The query result after querying in a specific folder.</param>
        /// <returns></returns>
        public async Task AddFolderToLibraryAsync(StorageFileQueryResult queryResult)
        {
            if (queryResult != null)
            {
                //so that no new event is raised. We want to focus on loading.
                isLibraryLoading = true;

                //this is a temporary list to collect all the processed Mediafiles. We use List because it is fast. Faster than using ObservableCollection directly because of the events firing on every add.
                var tempList = new List <Mediafile>();

                //'count' is for total files got after querying.
                var count = await queryResult.GetItemCountAsync().AsTask().ConfigureAwait(false);

                if (count == 0)
                {
                    string error = "No songs found!";
                    BLogger.Logger.Error("No songs were found!");
                    await NotificationManager.ShowMessageAsync(error);

                    return;
                }

                AlbumArtistViewModel model   = new AlbumArtistViewModel();
                LibraryService       service = new LibraryService(new DatabaseService());
                int failedCount = 0;
                //'i' is a variable for the index of currently processing file
                short i = 0;

                try
                {
                    foreach (StorageFile file in await queryResult.GetFilesAsync().AsTask().ConfigureAwait(false))
                    {
                        try
                        {
                            //A null Mediafile which we will use afterwards.
                            Mediafile mp3file = null;
                            i++; //Notice here that we are increasing the 'i' variable by one for each file.
                                 //we send a message to anyone listening relaying that song count has to be updated.
                            Messenger.Instance.NotifyColleagues(MessageTypes.MSG_UPDATE_SONG_COUNT, i);
                            await Task.Run(async() =>
                            {
                                //here we load into 'mp3file' variable our processed Song. This is a long process, loading all the properties and the album art.
                                mp3file            = await CreateMediafile(file, false); //the core of the whole method.
                                mp3file.FolderPath = Path.GetDirectoryName(file.Path);
                                await SaveSingleFileAlbumArtAsync(mp3file).ConfigureAwait(false);
                            });

                            //this methods notifies the Player that one song is loaded. We use both 'count' and 'i' variable here to report current progress.
                            await NotificationManager.ShowMessageAsync(i.ToString() + "\\" + count.ToString() + " Song(s) Loaded");

                            //we then add the processed song into 'tempList' very silently without anyone noticing and hence, efficiently.
                            tempList.Add(mp3file);
                        }
                        catch (Exception ex)
                        {
                            BLogger.Logger.Error("Loading of a song in folder failed.", ex);
                            //we catch and report any exception without distrubing the 'foreach flow'.
                            await NotificationManager.ShowMessageAsync(ex.Message + " || Occured on: " + file.Path);

                            failedCount++;
                        }
                    }
                    BLogger.Logger.Info(string.Format("{0} out of {1} songs loaded. {2} is iteration count.", tempList.Count, count, i));
                }
                catch (Exception ex)
                {
                    BLogger.Logger.Error("Failed to import songs in library.", ex);
                    string message1 = ex.Message + "||" + ex.InnerException;
                    await NotificationManager.ShowMessageAsync(message1);
                }
                //now we add 100 songs directly into our TracksCollection which is an ObservableCollection. This is faster because only one event is invoked.
                tempList.Sort();
                TracksCollection.AddRange(tempList);
                //now we load 100 songs into database.
                service.AddMediafiles(tempList);
                Messenger.Instance.NotifyColleagues(MessageTypes.MSG_ADD_ALBUMS, tempList);
                Messenger.Instance.NotifyColleagues(MessageTypes.MSG_UPDATE_SONG_COUNT, "Done!");
                //we send the message to load the album. This comes first so there is enough time to load all albums before new list come up.
                isLibraryLoading = false;
                string message = string.Format("Songs successfully imported! Total Songs: {0}; Failed: {1}; Loaded: {2}", count, failedCount, i);

                BLogger.Logger.Info(message);
                await NotificationManager.ShowMessageAsync(message);

                service.Dispose();
                model = null;
                await DeleteDuplicates(tempList).ConfigureAwait(false);

                tempList.Clear();
            }
        }
示例#19
0
        /// <summary>
        /// Add folder to Library asynchronously.
        /// </summary>
        /// <param name="queryResult">The query result after querying in a specific folder.</param>
        /// <returns></returns>
        public static async Task AddFolderToLibraryAsync(StorageFileQueryResult queryResult)
        {
            if (queryResult != null)
            {
                var stop = Stopwatch.StartNew();
                //we create two uints. 'index' for the index of current block/batch of files and 'stepSize' for the size of the block. This optimizes the loading operation tremendously.
                uint index = 0, stepSize = 200;
                //a list containing the files we recieved after querying using the two uints we created above.
                IReadOnlyList <StorageFile> files = await queryResult.GetFilesAsync(index, stepSize);

                //we move forward the index 100 steps because first 100 files are loaded when we called the above method.
                index += 200;

                //this is a temporary list to collect all the processed Mediafiles. We use List because it is fast. Faster than using ObservableCollection directly because of the events firing on every add.
                var tempList = new List <Mediafile>();

                //'count' is for total files got after querying.
                var count = await queryResult.GetItemCountAsync();

                if (count == 0)
                {
                    string error = "No songs found!";
                    await NotificationManager.ShowAsync(error);

                    return;
                }

                AlbumArtistViewModel model   = new AlbumArtistViewModel();
                LibraryService       service = new LibraryService(new DatabaseService());
                int failedCount = 0;
                //'i' is a variable for the index of currently processing file
                short i = 0;
                //using while loop until number of files become 0. This is to confirm that we process all files without leaving anything out.
                while (files.Count != 0)
                {
                    try
                    {
                        foreach (StorageFile file in files)
                        {
                            try
                            {
                                //we use 'if' conditional so that we don't add any duplicates
                                if (TracksCollection.Elements.All(t => t.Path != file.Path))
                                {
                                    //A null Mediafile which we will use afterwards.
                                    Mediafile mp3file = null;
                                    i++; //Notice here that we are increasing the 'i' variable by one for each file.
                                    //we send a message to anyone listening relaying that song count has to be updated.
                                    Messenger.Instance.NotifyColleagues(MessageTypes.MSG_UPDATE_SONG_COUNT, i);
                                    await Task.Run(async() =>
                                    {
                                        //here we load into 'mp3file' variable our processed Song. This is a long process, loading all the properties and the album art.
                                        mp3file            = await CreateMediafile(file, false); //the core of the whole method.
                                        mp3file.FolderPath = Path.GetDirectoryName(file.Path);
                                        await SaveSingleFileAlbumArtAsync(mp3file).ConfigureAwait(false);
                                    });

                                    //this methods notifies the Player that one song is loaded. We use both 'count' and 'i' variable here to report current progress.
                                    await NotificationManager.ShowAsync(i.ToString() + "\\" + count.ToString() + " Song(s) Loaded", "Loading...");

                                    //we then add the processed song into 'tempList' very silently without anyone noticing and hence, efficiently.
                                    tempList.Add(mp3file);
                                }
                            }
                            catch (Exception ex)
                            {
                                //we catch and report any exception without distrubing the 'foreach flow'.
                                await NotificationManager.ShowAsync(ex.Message + " || Occured on: " + file.Path);

                                failedCount++;
                            }
                        }
                        //await SaveMultipleAlbumArtsAsync(tempList).ConfigureAwait(false);
                        //we send the message to load the album. This comes first so there is enough time to load all albums before new list come up.
                        Messenger.Instance.NotifyColleagues(MessageTypes.MSG_ADD_ALBUMS, tempList);
                        //now we add 100 songs directly into our TracksCollection which is an ObservableCollection. This is faster because only one event is invoked.
                        TracksCollection.AddRange(tempList);
                        //now we load 100 songs into database.
                        service.AddMediafiles(tempList);
                        //we clear the 'tempList' so it can come with only 100 songs again.
                        tempList.Clear();
                        //Since the no. of files in 'files' list is 100, only 100 files will be loaded after which we will step out of while loop.
                        //To avoid this, we create and run a task that loads the next 100 files. Stepping forward 100 steps without increasing the index.
                        files = await queryResult.GetFilesAsync(index, stepSize).AsTask().ConfigureAwait(false);

                        //consequently we have to increase the index by 100 so that songs are not repeated.
                        index += 200;
                    }
                    catch (Exception ex)
                    {
                        string message1 = ex.Message + "||" + ex.InnerException;
                        await NotificationManager.ShowAsync(message1);
                    }
                }
                stop.Stop();
                string message = string.Format("Library successfully loaded! Total Songs: {0}; Failed: {1}; Loaded: {2}; Time Taken: {3}", count, failedCount, i, stop.Elapsed.TotalSeconds);
                await NotificationManager.ShowAsync(message);

                service.Dispose();
                model = null;
            }
        }