public async Task StartDownloadAsync(Song song) { song.SongState = SongState.Downloading; try { var path = string.Format("songs/{0}.mp3", song.Id); var destinationFile = await WinRtStorageHelper.CreateFileAsync(path, ApplicationData.Current.LocalFolder, CreationCollisionOption.ReplaceExisting).ConfigureAwait(false); var downloader = new BackgroundDownloader(); var download = downloader.CreateDownload(new Uri(song.AudioUrl), destinationFile); download.Priority = BackgroundTransferPriority.High; song.DownloadId = download.Guid.ToString(); await sqlService.UpdateItemAsync(song).ConfigureAwait(false); dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => HandleDownload(song, download, true)); } catch (Exception e) { if (e.Message.Contains("there is not enough space on the disk")) { dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => CurtainPrompt.ShowError("Not enough disk space to download.")); } dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => song.SongState = SongState.None); sqlService.UpdateItemAsync(song).ConfigureAwait(false); } }
/// <summary> /// Call internally to report a finished BackgroundDownload /// </summary> /// <param name="song"> /// The song that just finished downloading. /// </param> /// <returns> /// Task. /// </returns> private async Task DownloadFinishedForAsync(Song song) { var downloadOperation = (DownloadOperation)song.Download.DownloadOperation; await UpdateId3TagsAsync(song, downloadOperation.ResultFile); var filename = song.Name.CleanForFileName("Invalid Song Name"); if (song.ArtistName != song.Album.PrimaryArtist.Name) { filename = song.ArtistName.CleanForFileName("Invalid Artist Name") + "-" + filename; } var path = string.Format( AppConstant.SongPath, song.Album.PrimaryArtist.Name.CleanForFileName("Invalid Artist Name"), song.Album.Name.CleanForFileName("Invalid Album Name"), filename); var newDestination = await WinRtStorageHelper.CreateFileAsync(path, KnownFolders.MusicLibrary); downloadOperation.ResultFile.MoveAndReplaceAsync(newDestination); song.AudioUrl = newDestination.Path; song.SongState = SongState.Downloaded; song.DownloadId = null; await sqlService.UpdateItemAsync(song); }
private async Task DownloadFinishedForAsync(Song song, DownloadOperation download) { var downloadOperation = download; bool _isSuccessfull = await UpdateId3TagsAsync(song, downloadOperation.ResultFile); if (_isSuccessfull) { var filename = song.Name.CleanForFileName("Invalid Song Name"); if (song.ArtistName != song.Album.PrimaryArtist.Name) { filename = song.ArtistName.CleanForFileName("Invalid Artist Name") + "-" + filename; } var path = string.Format( AppConstant.SongPath, song.Album.PrimaryArtist.Name.CleanForFileName("Invalid Artist Name"), song.Album.Name.CleanForFileName("Invalid Album Name"), filename); var newDestination = await WinRtStorageHelper.CreateFileAsync(path, KnownFolders.MusicLibrary, CreationCollisionOption.ReplaceExisting); //MessageHelpers.ShowError("Saving file... if progress bar doesn't collapse after some time change the default music download location to your device instead of your sd card.", // "Important"); //C:\Data\Users\Public\Music\Airstem\The Chainsmokers\Unknown Album\All We Know.mp3 try { await downloadOperation.ResultFile.MoveAndReplaceAsync(newDestination); } catch { } song.AudioUrl = newDestination.Path; song.SongState = SongState.Downloaded; song.DownloadId = null; await sqlService.UpdateItemAsync(song); if (App.Locator.Setting.Notification) { ToastNotifications(song.ArtistName, song.Name); } } else { song.SongState = SongState.NoMatch; sqlService.UpdateItem(song); ToastManager.ShowError("Cannot update tags."); await downloadOperation.ResultFile.DeleteAsync(); } }
public async Task StartDownloadAsync(Song song) { if (!App.Locator.Network.IsActive) { ToastManager.ShowError("No internet connection."); return; } Uri source; if (!Uri.TryCreate(song.AudioUrl.Trim(), UriKind.Absolute, out source)) { ToastManager.ShowError("Uri seems to be broken."); return; } song.SongState = SongState.Downloading; StorageFile destinationFile; try { //chnaged local folder to temp folder var path = string.Format("songs/{0}.mp3", song.Id); destinationFile = await WinRtStorageHelper.CreateFileAsync(path, ApplicationData.Current.TemporaryFolder, CreationCollisionOption.ReplaceExisting).ConfigureAwait(false); } catch (Exception) { ToastManager.ShowError("Error while creating file."); return; } try { BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(new Uri(song.AudioUrl), destinationFile); download.Priority = BackgroundTransferPriority.Default; song.DownloadId = download.Guid.ToString(); id.Add(song.DownloadId); await sqlService.UpdateItemAsync(song).ConfigureAwait(false); //try //{ // List<DownloadOperation> requestOperations = new List<DownloadOperation>(); // requestOperations.Add(download); // await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations); //} //catch //{ // //ignored... //} //run even if battery saver in on await DispatcherHelper.RunAsync(async() => await HandleDownload(song, download, true)); } catch (Exception e) { if (e.Message.Contains("there is not enough space on the disk")) { ToastManager.ShowError("No space."); } ExceptionHelper(song); } }
private async void LoadWallpaperArt() { if (_loaded || !App.Locator.AppSettingsHelper.Read("WallpaperArt", true, SettingsStrategy.Roaming)) { return; } var wait = App.Locator.AppSettingsHelper.Read <int>("WallpaperDayWait"); var created = App.Locator.AppSettingsHelper.ReadJsonAs <DateTime>("WallpaperCreated"); // Set the image brush var imageBrush = new ImageBrush { Opacity = .25, Stretch = Stretch.UniformToFill, AlignmentY = AlignmentY.Top }; LayoutGrid.Background = imageBrush; if (created != DateTime.MinValue) { // Not the first time, so there must already be one created imageBrush.ImageSource = new BitmapImage(new Uri("ms-appdata:/local/wallpaper.jpg")); } // Once a week remake the wallpaper if ((DateTime.Now - created).TotalDays > wait) { var albums = App.Locator.CollectionService.Albums.ToList() .Where(p => p.HasArtwork) .ToList(); var albumCount = albums.Count; if (albumCount < 10) { return; } var h = Window.Current.Bounds.Height; var rows = (int)Math.Ceiling(h / (ActualWidth / 5)); const int collumns = 5; var albumSize = (int)Window.Current.Bounds.Width / collumns; var numImages = rows * 5; var imagesNeeded = numImages - albumCount; var shuffle = await Task.FromResult(albums .Shuffle() .Take(numImages > albumCount ? albumCount : numImages) .ToList()); if (imagesNeeded > 0) { var repeatList = new List <Album>(); while (imagesNeeded > 0) { var takeAmmount = imagesNeeded > albumCount ? albumCount : imagesNeeded; await Task.Run(() => repeatList.AddRange(shuffle.Shuffle().Take(takeAmmount))); imagesNeeded -= shuffle.Count; } shuffle.AddRange(repeatList); } // Initialize an empty WriteableBitmap. var destination = new WriteableBitmap((int)Window.Current.Bounds.Width, (int)Window.Current.Bounds.Height); var col = 0; // Current Column Position var row = 0; // Current Row Position destination.Clear(Colors.Black); // Set the background color of the image to black // will be copied foreach (var artworkPath in shuffle.Select(album => string.Format(AppConstant.ArtworkPath, album.Id))) { var file = await WinRtStorageHelper.GetFileAsync(artworkPath); // Read the image file into a RandomAccessStream using (var fileStream = await file.OpenReadAsync()) { try { // Now that you have the raw bytes, create a Image Decoder var decoder = await BitmapDecoder.CreateAsync(fileStream); // Get the first frame from the decoder because we are picking an image var frame = await decoder.GetFrameAsync(0); // Convert the frame into pixels var pixelProvider = await frame.GetPixelDataAsync(); // Convert pixels into byte array var srcPixels = pixelProvider.DetachPixelData(); var wid = (int)frame.PixelWidth; var hgt = (int)frame.PixelHeight; // Create an in memory WriteableBitmap of the same size var bitmap = new WriteableBitmap(wid, hgt); // Temporary bitmap into which the source using (var pixelStream = bitmap.PixelBuffer.AsStream()) { pixelStream.Seek(0, SeekOrigin.Begin); // Push the pixels from the original file into the in-memory bitmap await pixelStream.WriteAsync(srcPixels, 0, srcPixels.Length); bitmap.Invalidate(); // Resize the in-memory bitmap and Blit (paste) it at the correct tile // position (row, col) destination.Blit(new Rect(col * albumSize, row * albumSize, albumSize, albumSize), bitmap.Resize(albumSize, albumSize, WriteableBitmapExtensions.Interpolation.Bilinear), new Rect(0, 0, albumSize, albumSize)); col++; if (col < collumns) { continue; } row++; col = 0; } } catch { // ignored } } } var wallpaper = await WinRtStorageHelper.CreateFileAsync("wallpaper.jpg", ApplicationData.Current.LocalFolder); using (var rndWrite = await wallpaper.OpenAsync(FileAccessMode.ReadWrite)) { await destination.ToStreamAsJpeg(rndWrite); } App.Locator.AppSettingsHelper.WriteAsJson("WallpaperCreated", DateTime.Now); // If there are 30 or less albums then recreate in one day, else wait a week App.Locator.AppSettingsHelper.Write("WallpaperDayWait", albums.Count < 30 ? 1 : 7); imageBrush.ImageSource = null; imageBrush.ImageSource = new BitmapImage(new Uri("ms-appdata:/local/wallpaper.jpg")); } _loaded = true; }