Skip to content

Commit

Permalink
Fixed #36 Fixed #35
Browse files Browse the repository at this point in the history
  • Loading branch information
theweavrs committed Nov 14, 2016
1 parent 6145212 commit cf98968
Show file tree
Hide file tree
Showing 7 changed files with 106 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public async Task ShowAsync(string status, string heading = "Oops! Burnt!")
//if (!Show)
//{
// Show = true;
if(hideTimer == null) hideTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(5) };
if(hideTimer == null) hideTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(10) };
hideTimer.Start();
hideTimer.Tick += HideTimer_Tick;
//}
Expand Down
6 changes: 3 additions & 3 deletions BreadPlayer.Core/ViewModels/AlbumArtistViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ public async Task LoadAlbums()
/// </remarks>
public async Task AddAlbums()
{
List<Album> albums = new List<Album>();
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
List<Album> albums = new List<Album>();
foreach (var song in await LibVM.Database.GetTracks().ConfigureAwait(false))
{
Album alb = null;
Expand All @@ -76,10 +76,10 @@ public async Task AddAlbums()
}
if (albums.Any()) albums.FirstOrDefault(t => t.AlbumName == song.Album && t.Artist == song.LeadArtist).AlbumSongs.Add(song);
}
albumCollection.Insert(albums);
AlbumCollection.AddRange(albums);
}).AsTask().ConfigureAwait(false);

albumCollection.Insert(albums);
AlbumCollection.AddRange(albums);
}
RelayCommand _navigateCommand;
public ICommand NavigateToAlbumPageCommand
Expand Down
10 changes: 6 additions & 4 deletions BreadPlayer.Core/ViewModels/LibraryViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -693,8 +693,10 @@ async void AddToPlaylist(object file)
await AddPlaylist(dictPlaylist, true, songList);
}
else
{
await AddPlaylist(await ShowAddPlaylistDialog(), false);
{
var pList = await ShowAddPlaylistDialog();
if(pList != null)
await AddPlaylist(pList, false);
}
}

Expand All @@ -705,10 +707,10 @@ async Task<Playlist> ShowAddPlaylistDialog(string title = "Name this playlist",
Title = title,
Text = playlistName,
Description = desc
};
var Playlist = new Playlist();
};
if (await dialog.ShowAsync() == ContentDialogResult.Primary && dialog.Text != "")
{
var Playlist = new Playlist();
Playlist.Name = dialog.Text;
Playlist.Description = dialog.Description;
if (Database.playlists.Exists(t => t.Name == Playlist.Name))
Expand Down
24 changes: 14 additions & 10 deletions BreadPlayer.Core/ViewModels/PlaylistViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,17 +113,21 @@ void Delete(object para)
// LibVM.Database.Update(mediafile);
Refresh();
}
public void Refresh()
public async void Refresh()
{
TotalMinutes = string.Format("{0:0.0}", Math.Truncate(Songs.Elements.Sum(t => TimeSpan.ParseExact(t.Length, "mm\\:ss", CultureInfo.InvariantCulture).TotalMinutes) * 10) / 10) + " Minutes";
TotalSongs = Songs.Elements.Count.ToString() + " Songs";
if (Songs.Elements.Any(s => !string.IsNullOrEmpty(s.AttachedPicture)) && PlaylistArt == null)
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
BitmapImage image = new BitmapImage(new Uri(Songs.Elements.FirstOrDefault(s => !string.IsNullOrEmpty(s.AttachedPicture)).AttachedPicture, UriKind.RelativeOrAbsolute));
PlaylistArt = image;
}
var mp3 = PlaylistVM?.Songs?.Elements?.FirstOrDefault(t => t.Path == Player.CurrentlyPlayingFile?.Path);
if (mp3 != null) mp3.State = PlayerState.Playing;
TotalMinutes = string.Format("{0:0.0}", Math.Truncate(Songs.Elements.Sum(t => TimeSpan.ParseExact(t.Length, "mm\\:ss", CultureInfo.InvariantCulture).TotalMinutes) * 10) / 10) + " Minutes";
TotalSongs = Songs.Elements.Count.ToString() + " Songs";
if (Songs.Elements.Any(s => !string.IsNullOrEmpty(s.AttachedPicture)) && PlaylistArt == null)
{
BitmapImage image = new BitmapImage(new Uri(Songs.Elements.FirstOrDefault(s => !string.IsNullOrEmpty(s.AttachedPicture)).AttachedPicture, UriKind.RelativeOrAbsolute));
PlaylistArt = image;
}
var mp3 = PlaylistVM?.Songs?.Elements?.FirstOrDefault(t => t.Path == Player.CurrentlyPlayingFile?.Path);
if (mp3 != null) mp3.State = PlayerState.Playing;
});

}
RelayCommand _renamePlaylistCommand;
/// <summary>
Expand Down Expand Up @@ -195,7 +199,7 @@ public PlaylistViewModel()

private void Elements_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{

Refresh();
}

RelayCommand _initCommand;
Expand Down
111 changes: 64 additions & 47 deletions BreadPlayer.Core/ViewModels/SettingsViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,21 +167,24 @@ public async void Load()
LibraryFoldersCollection.Add(folder);
StorageApplicationPermissions.FutureAccessList.Add(folder);
//Get query options with which we search for files in the specified folder
var options = Common.DirectoryWalker.GetQueryOptions();
//var options = Common.DirectoryWalker.GetQueryOptions();
//var folderOptions = new QueryOptions();
// StorageFolderQueryResult folderResult = folder.CreateFolderQuery(CommonFolderQuery.DefaultQuery);
// LibraryFoldersCollection.AddRange(await folderResult.GetFoldersAsync());
//this is the query result which we recieve after querying in the folder
StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(options);
//StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(options);
//the event for files changed
queryResult.ContentsChanged += QueryResult_ContentsChanged;
await AddFolderToLibraryAsync(queryResult);

await AddFolderToLibraryAsync(folder);
}
}
public async Task AddFolderToLibraryAsync(StorageFileQueryResult queryResult)
public async Task AddFolderToLibraryAsync(StorageFolder folder)
{
if (queryResult != null)
if (folder != null)
{
var options = Common.DirectoryWalker.GetQueryOptions();
StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(options);
queryResult.ContentsChanged += QueryResult_ContentsChanged;
var stop = System.Diagnostics.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 = 100;
Expand All @@ -197,70 +200,84 @@ public async Task AddFolderToLibraryAsync(StorageFileQueryResult queryResult)
double i = 0;
//'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);
}
int failedCount = 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)
{
//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 a task that loads the next 100 files. Stepping forward 100 steps without increasing the index.
var fileTask = queryResult.GetFilesAsync(index, stepSize).AsTask();
try
{
//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 a task that loads the next 100 files. Stepping forward 100 steps without increasing the index.
var fileTask = queryResult.GetFilesAsync(index, stepSize).AsTask();

//A null Mediafile which we will use afterwards.
Mediafile mp3file = null;
//A null Mediafile which we will use afterwards.
Mediafile mp3file = null;

//A foreach loop to process each StorageFile
foreach (StorageFile file in files)
{
try
//A foreach loop to process each StorageFile
foreach (StorageFile file in files)
{

//we use 'if' conditional so that we don't add any duplicates
if (LibVM.TracksCollection.Elements.All(t => t.Path != file.Path))
try
{

i++; //Notice here that we are increasing the 'i' variable by one for each file.
LibVM.SongCount++; //we also increase the total no. of songs by one.
await Task.Run(async () =>
//we use 'if' conditional so that we don't add any duplicates
if (LibVM.TracksCollection.Elements.All(t => t.Path != file.Path))
{

i++; //Notice here that we are increasing the 'i' variable by one for each file.
LibVM.SongCount++; //we also increase the total no. of songs by one.
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 CoreMethods.CreateMediafile(file, false); //the core of the whole method.
mp3file.FolderPath = Path.GetDirectoryName(file.Path);
});
//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...");
});
//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);
//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++;
}
}
catch (Exception ex)
{
//we catch and report any exception without distrubing the 'foreach flow'.
await NotificationManager.ShowAsync(ex.Message + " || Occured on: " + file.Path);
continue;
}
//after the first 100 files have been added we enable the play button.
ShellVM.PlayPauseCommand.IsEnabled = true;
//now we add 100 songs directly into our TracksCollection which is an ObservableCollection. This is faster because only one event is invoked.
LibVM.TracksCollection.Elements.AddRange(tempList);
//now we load 100 songs into database.
LibVM.Database.Insert(tempList);
//we clear the 'tempList' so it can come with only 100 songs again.
tempList.Clear();
//here we reinitialize the 'files' variable (outside the while loop) so that it is never 0 and never contains the old files.
files = await fileTask.ConfigureAwait(false);
//consequently we have to increase the index by 100 so that songs are not repeated.
index += 100;
}
catch(Exception ex)
{
string message1 = ex.Message + "||" + ex.InnerException;
await NotificationManager.ShowAsync(message1);
}
//after the first 100 files have been added we enable the play button.
ShellVM.PlayPauseCommand.IsEnabled = true;
//now we add 100 songs directly into our TracksCollection which is an ObservableCollection. This is faster because only one event is invoked.
LibVM.TracksCollection.Elements.AddRange(tempList);
//now we load 100 songs into database.
LibVM.Database.Insert(tempList);
//here we reinitialize the 'files' variable (outside the while loop) so that it is never 0 and never contains the old files.
files = await fileTask.ConfigureAwait(false);
//consequently we have to increase the index by 100 so that songs are not repeated.
index += 100;
}
await SaveAllFolderAlbumArtsAsync(queryResult).ConfigureAwait(false);
//After all the songs are processed and loaded, we create albums of all those songs and load them using this method.
await AlbumArtistVM.AddAlbums().ConfigureAwait(false);
//we stop the stopwatch.
stop.Stop();
//and report the user how long it took.
await NotificationManager.ShowAsync(i.ToString() + " Song(s) loaded in " + Convert.ToInt32(stop.Elapsed.TotalSeconds).ToString() + " seconds", "Library loaded!");
//and report the user how long it took.
string message = string.Format("Library successfully loaded! Total Songs: {0} Failed: {1} Loaded: {2} Total Time Taken: {3} seconds", count, failedCount, i, Convert.ToInt32(stop.Elapsed.TotalSeconds).ToString());
await NotificationManager.ShowAsync(message);
}
}
public static async void RenameAddOrDeleteFiles(IEnumerable<StorageFile> files)
Expand Down
30 changes: 17 additions & 13 deletions BreadPlayer.Core/Views/LibraryView.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,28 +53,32 @@ private async void fileBox_Drop(object sender, DragEventArgs e)
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var files = await e.DataView.GetStorageItemsAsync();
if (files.Any())
if (files.Any() && files.All(t => t.IsOfType(StorageItemTypes.File)))
{
foreach(var file in files)
{
Mediafile mp3file = null;
string path = file.Path;
var tempList = new List<Mediafile>();
if (Core.CoreMethods.LibVM.TracksCollection.Elements.All(t => t.Path != path))
if(Path.GetExtension(file.Path) == ".mp3")
{
try
Mediafile mp3file = null;
string path = file.Path;
var tempList = new List<Mediafile>();
if (Core.CoreMethods.LibVM.TracksCollection.Elements.All(t => t.Path != path))
{
try
{

mp3file = await Core.CoreMethods.CreateMediafile(file as StorageFile);
Core.CoreMethods.LibVM.SongCount++;
}
catch { }
tempList.Add(mp3file);
mp3file = await Core.CoreMethods.CreateMediafile(file as StorageFile);
Core.CoreMethods.LibVM.SongCount++;
}
catch { }
tempList.Add(mp3file);

Core.CoreMethods.LibVM.TracksCollection.Elements.AddRange(tempList);
Core.CoreMethods.LibVM.Database.Insert(tempList);
Core.CoreMethods.LibVM.TracksCollection.Elements.AddRange(tempList);
Core.CoreMethods.LibVM.Database.Insert(tempList);
tempList.Clear();
}
}

}
await Core.CoreMethods.AlbumArtistVM.AddAlbums();
}
Expand Down
2 changes: 1 addition & 1 deletion BreadPlayer.Core/Views/SettingsView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@
<Button Content="Reset Everything" Grid.Column="0" Margin="0,10,10,0" HorizontalContentAlignment="Left" Command="{Binding ResetCommand}" Style="{StaticResource HyperlinkBtn}" Background="{x:Null}" Height="28" HorizontalAlignment="Stretch"/>
<MenuFlyoutSeparator Margin="10,10,10,0" x:Name="TopSeperator" />
<TextBlock Margin="10,10,10,0" Text="Version:" FontWeight="Bold"/>
<TextBlock Margin="10,10,10,0" Text="v0.1.6-alpha"/>
<TextBlock Margin="10,10,10,0" Text="v0.1.6.1-alpha"/>
<TextBlock Margin="10,10,10,0" Text="Developed by:" FontWeight="Bold"/>
<TextBlock Margin="10,10,10,0" Text="theweavr"/>
</StackPanel>
Expand Down

0 comments on commit cf98968

Please sign in to comment.