public Task <bool> ConvertAudioToVKSaverFormat(StorageFile file, VKSaverAudio metadata) { if (metadata == null) { return(Task.FromResult(false)); } return(_converterQueue.Enqueue(() => ConvertAudioToVKSaverFormatInternal(file, metadata))); }
private async Task ProcessFileAsync(StorageFile file, StorageFolder folder) { if (file.FileType == TEMP_FILES_EXTENSION) { try { await file.DeleteAsync(StorageDeleteOption.PermanentDelete); } catch (Exception ex) { _logService.LogException(ex); } return; } else if (file.FileType != MusicCacheService.FILES_EXTENSION) { return; } StorageFile newFile = null; try { VKSaverAudio metadata = null; using (var audioFile = new VKSaverAudioFile(file)) { metadata = await audioFile.GetMetadataAsync(); using (var sourceStream = await audioFile.GetContentStreamAsync()) { newFile = await folder.CreateFileAsync( Path.GetFileNameWithoutExtension(file.Name) + TEMP_FILES_EXTENSION, CreationCollisionOption.ReplaceExisting); using (var fileStream = await newFile.OpenStreamForWriteAsync()) { await CopyStreamAsync(sourceStream, fileStream); } } } await newFile.RenameAsync(GetSafeFileName(metadata.Track.Title) + MP3_FILES_EXTENSION, NameCollisionOption.GenerateUniqueName); await file.DeleteAsync(StorageDeleteOption.PermanentDelete); } catch (Exception ex) { _logService.LogException(ex); await newFile?.DeleteAsync(StorageDeleteOption.PermanentDelete); } }
private async Task PostprocessAudioInternal(StorageFile file, VKSaverAudio metadata) { if (metadata == null) { return; } var fileProperties = await file.Properties.GetMusicPropertiesAsync(); metadata.Track.Duration = fileProperties.Duration.Ticks; await _libraryDatabseService.InsertDownloadedTrack(metadata, Path.GetDirectoryName(file.Path), file.Path); }
/// <summary> /// Возвращает название операции загрузки из файла. /// </summary> /// <param name="file">Результирующий файл.</param> private string GetOperationNameFromFile(IStorageFile file) { string fileName = file.Name.Split(new char[] { '.' })[0]; var type = GetContentTypeFromExtension(file.FileType); switch (type) { case FileContentType.Music: VKSaverAudio metadata = null; _musicDownloads.TryGetValue(fileName, out metadata); if (metadata != null) { return(metadata.Track.Title); } break; } return(fileName); }
public async Task InsertDownloadedTrack(VKSaverAudio audio, string folderPath, string filePath) { string artistName = null; string capatibleFolderPath = MusicFilesPathHelper.GetCapatibleSource(folderPath); string genreKey = audio.VK.Genre == 0 ? UNKNOWN_GENRE_NAME : audio.VK.Genre.ToString(); string vkInfoKey = $"{audio.VK.OwnerID} {audio.VK.ID}"; if (String.IsNullOrEmpty(audio.Track.Artist)) { artistName = UNKNOWN_ARTIST_NAME; } else { artistName = audio.Track.Artist; } string albumKey = $"{artistName}-{UNKNOWN_ALBUM_NAME}"; var dbFolder = await _database.FindItem <VKSaverFolder>(capatibleFolderPath); if (dbFolder == null) { dbFolder = new VKSaverFolder { Path = capatibleFolderPath, Name = Path.GetFileName(folderPath), Tracks = new List <VKSaverTrack>() }; await _database.InsertItem(dbFolder); } else { dbFolder = null; } var dbAlbum = await _database.FindItem <VKSaverAlbum>(albumKey); if (dbAlbum == null) { dbAlbum = new VKSaverAlbum { DbKey = albumKey, Name = UNKNOWN_ALBUM_NAME, ArtistName = artistName, Tracks = new List <VKSaverTrack>() }; await _database.InsertItem(dbAlbum); } else { dbAlbum = null; } var dbArtist = await _database.FindItem <VKSaverArtist>(artistName); if (dbArtist == null) { dbArtist = new VKSaverArtist { DbKey = artistName, Name = artistName, Tracks = new List <VKSaverTrack>(), Albums = new List <VKSaverAlbum>() }; await _database.InsertItem(dbArtist); } else if (dbAlbum != null) { dbArtist = await _database.GetItemWithChildrens <VKSaverArtist>(artistName); } else { dbArtist = null; } var dbGenre = await _database.FindItem <VKSaverGenre>(genreKey); if (dbGenre == null) { dbGenre = new VKSaverGenre { DbKey = genreKey, Name = genreKey, Tracks = new List <VKSaverTrack>() }; await _database.InsertItem(dbGenre); } else { dbGenre = null; } var dbVkInfo = await _database.FindItem <VKSaverAudioVKInfo>(vkInfoKey); if (dbVkInfo == null) { dbVkInfo = audio.VK; dbVkInfo.DbKey = vkInfoKey; await _database.InsertItem(dbVkInfo); } else { dbVkInfo = null; } var track = new VKSaverTrack { Title = audio.Track.Title.Trim(), Artist = artistName, Duration = TimeSpan.FromTicks(audio.Track.Duration), Source = MusicFilesPathHelper.GetCapatibleSource(filePath), GenreKey = genreKey, FolderKey = capatibleFolderPath, AlbumKey = albumKey, VKInfoKey = vkInfoKey }; await _database.InsertItem(track); if (dbAlbum != null) { dbAlbum.Tracks.Add(track); await _database.UpdateItemChildrens(dbAlbum); } if (dbArtist != null) { if (dbAlbum != null) { dbArtist.Albums.Add(dbAlbum); } dbArtist.Tracks.Add(track); await _database.UpdateItemChildrens(dbArtist); } if (dbFolder != null) { dbFolder.Tracks.Add(track); await _database.UpdateItemChildrens(dbFolder); } if (dbGenre != null) { dbGenre.Tracks.Add(track); await _database.UpdateItemChildrens(dbGenre); } if (dbVkInfo != null) { await _database.UpdateItemChildrens(dbVkInfo); } NeedReloadLibraryView = true; }
public Task PostprocessAudioAsync(StorageFile file, VKSaverAudio metadata) { return(_converterQueue.Enqueue(() => PostprocessAudioInternal(file, metadata))); }
private async Task <bool> ConvertAudioToVKSaverFormatInternal(StorageFile file, VKSaverAudio metadata) { StorageFile zipFile = null; Stream zipFileStream = null; Stream fileStream = null; try { var cacheFolder = await GetCacheFolder(); zipFile = await cacheFolder.CreateFileAsync(file.Name.Split(new char[] { '.' })[0] + FILES_EXTENSION, CreationCollisionOption.ReplaceExisting); zipFileStream = (await zipFile.OpenAsync(FileAccessMode.ReadWrite)).AsStream(); fileStream = (await file.OpenAsync(FileAccessMode.Read)).AsStreamForRead(); var propertiesToRetrieve = new List <string>(); propertiesToRetrieve.Add(PROPERTY_SAMPLE_RATE); propertiesToRetrieve.Add(PROPERTY_CHANNEL_COUNT); propertiesToRetrieve.Add(PROPERTY_ENCODING_BITRATE); var encodingProperties = await file.Properties.RetrievePropertiesAsync(propertiesToRetrieve); metadata.Track.SampleRate = (uint)encodingProperties[PROPERTY_SAMPLE_RATE]; metadata.Track.ChannelCount = (uint)encodingProperties[PROPERTY_CHANNEL_COUNT]; metadata.Track.EncodingBitrate = (uint)encodingProperties[PROPERTY_ENCODING_BITRATE]; var fileProperties = await file.Properties.GetMusicPropertiesAsync(); metadata.Track.Duration = fileProperties.Duration.Ticks; using (var zipStream = new ZipOutputStream(zipFileStream)) { zipStream.SetLevel(0); var contentEntry = new ZipEntry(FILES_CONTENT_NAME); contentEntry.CompressionMethod = CompressionMethod.Stored; WriteEntry(zipStream, contentEntry, fileStream); var metadataEntry = new ZipEntry(FILES_METADATA_NAME); metadataEntry.CompressionMethod = CompressionMethod.Stored; WriteEntry(zipStream, metadataEntry, new MemoryStream( Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(metadata)))); zipStream.Finish(); } await _libraryDatabseService.InsertDownloadedTrack(metadata, cacheFolder.Path, zipFile.Path); return(true); } catch (Exception ex) { _logService.LogException(ex); zipFileStream?.Dispose(); zipFileStream = null; await zipFile?.DeleteAsync(StorageDeleteOption.PermanentDelete); return(false); } finally { fileStream?.Dispose(); } }
private async void HandleDownloadAsync(DownloadOperation operation, bool start = true) { var tokenSource = new CancellationTokenSource(); var callback = new Progress <DownloadOperation>(OnDownloadProgressChanged); _downloads.Add(operation); _cts[operation.Guid] = tokenSource; OnDownloadProgressChanged(operation); try { if (start) { await operation.StartAsync().AsTask(tokenSource.Token, callback); } else { await operation.AttachAsync().AsTask(tokenSource.Token, callback); } } catch (OperationCanceledException) { } catch (Exception ex) { _logService.LogException(ex); DownloadError?.Invoke(this, new TransferOperationErrorEventArgs( operation.Guid, GetOperationNameFromFile(operation.ResultFile), GetContentTypeFromExtension(operation.ResultFile.FileType), ex)); } string fileName = operation.ResultFile.Name.Split(new char[] { '.' })[0]; try { if (operation.Progress.Status == BackgroundTransferStatus.Completed) { var type = GetContentTypeFromExtension(operation.ResultFile.FileType); if (type == FileContentType.Music) { VKSaverAudio metadata = null; _musicDownloads.TryGetValue(fileName, out metadata); // TODO! await _musicCacheService.PostprocessAudioAsync((StorageFile)operation.ResultFile, metadata); //await _musicCacheService.ConvertAudioToVKSaverFormat((StorageFile)operation.ResultFile, metadata); } } } catch (Exception ex) { _logService.LogException(ex); } OnDownloadProgressChanged(operation); _cts.Remove(operation.Guid); _downloads.Remove(operation); _musicDownloads.Remove(fileName); if (_downloads.Count == 0) { DownloadsCompleted?.Invoke(this, EventArgs.Empty); await GetMetadataFileAsync(true); } }