/// <summary>
/// Loops through the Media table to set the FileName, Length, Width and Height fields.
/// </summary>
/// <param name="progress">Reports the progress of the operation. First report is the amount of files to process, then subsequent reports represent the quantity done.</param>
/// <returns>Whether some data was modified.</returns>
public async Task<bool> LoadMediaInfoAsync(IProgress<int> progress) {
// Calling this method when it is already running allows listening to the progress.
if (progress != null) {
loadingMediaInfoProgress = progress;
// First progress report is total count.
if (isLoadingMediaInfo)
loadingMediaInfoProgress.Report(loadingMediaInfoCount);
}
if (isLoadingMediaInfo)
return false;
isLoadingMediaInfo = true;
bool HasChanges = false;
using (Entities context = new Entities()) {
// Loop through all media items with missing Length, Width or Height.
var Query = (from v in context.Media
where v.FileName == null || v.Length == null ||
((v.MediaTypeId == (int)MediaType.Video || v.MediaTypeId == (int)MediaType.Image) && v.Height == null)
select v);
// First progress report contains the total count. Subsequent reports contain the quantity completed.
loadingMediaInfoCount = Query.Count();
if (loadingMediaInfoProgress != null)
loadingMediaInfoProgress.Report(loadingMediaInfoCount);
int ItemsCompleted = 0;
string DefaultFileName;
string FilePath;
DefaultMediaPath PathCalc = new DefaultMediaPath();
PathCalc.LoadData();
MediaInfoReader MediaInfo = new MediaInfoReader();
foreach (Media item in Query) {
// Try to auto-attach file if default file name exists.
if (item.FileName == null) {
DefaultFileName = PathCalc.GetDefaultFileName(item.Artist, item.Title, item.MediaCategoryId, item.MediaType);
foreach (string ext in Settings.GetMediaTypeExtensions(item.MediaType)) {
FilePath = Settings.NaturalGroundingFolder + DefaultFileName + ext;
if (File.Exists(FilePath)) {
item.FileName = DefaultFileName + ext;
HasChanges = true;
await Task.Delay(1);
break;
}
}
}
// Load media file to set Length, Width and Height.
if (item.FileName != null && await MediaInfo.LoadInfoAsync(item))
HasChanges = true;
// Send update with the quantity of files completed.
if (loadingMediaInfoProgress != null)
loadingMediaInfoProgress.Report(++ItemsCompleted);
}
MediaInfo.Dispose();
if (HasChanges)
context.SaveChanges();
}
isLoadingMediaInfo = false;
loadingMediaInfoCount = 0;
loadingMediaInfoProgress = null;
return HasChanges;
}