Merge pull request #242 from Mbucari/master

Add option to download cover art & full-size cover art viewer
This commit is contained in:
rmcrackan 2022-05-11 10:53:11 -04:00 committed by GitHub
commit e0248c2d8e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 1352 additions and 1025 deletions

View File

@ -134,6 +134,9 @@ namespace AppScaffolding
if (!config.Exists(nameof(config.GridColumnsWidths)))
config.GridColumnsWidths = new Dictionary<string, int>();
if (!config.Exists(nameof(config.DownloadCoverArt)))
config.DownloadCoverArt = true;
}
/// <summary>Initialize logging. Run after migration</summary>

View File

@ -75,6 +75,9 @@ namespace FileLiberator
if (!movedAudioFile)
return new StatusHandler { "Cannot find final audio file after decryption" };
if (Configuration.Instance.DownloadCoverArt)
DownloadCoverArt(libraryBook);
libraryBook.Book.UserDefinedItem.BookStatus = LiberatedStatus.Liberated;
ApplicationServices.LibraryCommands.UpdateUserDefinedItem(libraryBook.Book);
@ -129,6 +132,7 @@ namespace FileLiberator
// REAL WORK DONE HERE
var success = await Task.Run(abDownloader.Run);
return success;
}
finally
@ -188,31 +192,27 @@ namespace FileLiberator
}
}
NAudio.Lame.LameConfig lameConfig = new();
lameConfig.Mode = NAudio.Lame.MPEGMode.Mono;
audiobookDlLic.LameConfig = new();
audiobookDlLic.LameConfig.Mode = NAudio.Lame.MPEGMode.Mono;
if (config.LameTargetBitrate)
{
if (config.LameConstantBitrate)
lameConfig.BitRate = config.LameBitrate;
audiobookDlLic.LameConfig.BitRate = config.LameBitrate;
else
{
lameConfig.ABRRateKbps = config.LameBitrate;
lameConfig.VBR = NAudio.Lame.VBRMode.ABR;
lameConfig.WriteVBRTag = true;
audiobookDlLic.LameConfig.ABRRateKbps = config.LameBitrate;
audiobookDlLic.LameConfig.VBR = NAudio.Lame.VBRMode.ABR;
audiobookDlLic.LameConfig.WriteVBRTag = true;
}
}
else
{
lameConfig.VBR = NAudio.Lame.VBRMode.Default;
lameConfig.VBRQuality = config.LameVBRQuality;
lameConfig.WriteVBRTag = true;
audiobookDlLic.LameConfig.VBR = NAudio.Lame.VBRMode.Default;
audiobookDlLic.LameConfig.VBRQuality = config.LameVBRQuality;
audiobookDlLic.LameConfig.WriteVBRTag = true;
}
audiobookDlLic.LameConfig = lameConfig;
return audiobookDlLic;
}
@ -278,5 +278,34 @@ namespace FileLiberator
return true;
}
private void DownloadCoverArt(LibraryBook libraryBook)
{
var destinationDir = AudibleFileStorage.Audio.GetDestinationDirectory(libraryBook);
var coverPath = AudibleFileStorage.Audio.GetBooksDirectoryFilename(libraryBook, ".jpg");
coverPath = Path.Combine(destinationDir, Path.GetFileName(coverPath));
try
{
if (File.Exists(coverPath))
FileUtility.SaferDelete(coverPath);
(string picId, PictureSize size) = libraryBook.Book.PictureLarge is null ?
(libraryBook.Book.PictureId, PictureSize.Native) :
(libraryBook.Book.PictureLarge, PictureSize.Native);
var picBytes = PictureStorage.GetPictureSynchronously(new PictureDefinition(picId, size));
if (picBytes.Length > 0)
File.WriteAllBytes(coverPath, picBytes);
}
catch (Exception ex)
{
//Failure to download cover art should not be
//considered a failure to download the book
Serilog.Log.Logger.Error(ex, $"Error downloading cover art of {libraryBook.Book.AudibleProductId} to {coverPath} catalog product.");
}
}
}
}

View File

@ -48,38 +48,9 @@ namespace FileLiberator
= (await ProcessAsync(libraryBook))
?? new StatusHandler { "Processable should never return a null status" };
if (status.IsSuccess)
DownloadCoverArt(libraryBook);
return status;
}
private void DownloadCoverArt(LibraryBook libraryBook)
{
var destinationDir = AudibleFileStorage.Audio.GetDestinationDirectory(libraryBook);
var coverPath = FileManager.FileUtility.GetValidFilename(System.IO.Path.Combine(destinationDir, "Cover.jpg"), "", true);
if (System.IO.File.Exists(coverPath)) return;
try
{
(string picId, PictureSize size) = libraryBook.Book.PictureLarge is null ?
(libraryBook.Book.PictureId, PictureSize.Native) :
(libraryBook.Book.PictureLarge, PictureSize.Native);
var picBytes = PictureStorage.GetPictureSynchronously(new PictureDefinition(picId, size));
if (picBytes.Length > 0)
System.IO.File.WriteAllBytes(coverPath, picBytes);
}
catch (Exception ex)
{
//Failure to download cover art should not be
//considered a failure to download the book
Serilog.Log.Logger.Error(ex.Message);
}
}
public async Task<StatusHandler> TryProcessAsync(LibraryBook libraryBook)
=> Validate(libraryBook)
? await ProcessAsync(libraryBook)

View File

@ -134,6 +134,7 @@ namespace FileManager
private void AddPath(string path)
{
if (!File.Exists(path)) return;
if (File.GetAttributes(path).HasFlag(FileAttributes.Directory))
AddUniqueFiles(FileUtility.SaferEnumerateFiles(path, SearchPattern, SearchOption));
else

View File

@ -200,6 +200,13 @@ namespace LibationFileManager
get => persistentDictionary.GetNonString<Dictionary<string,int>>(nameof(GridColumnsWidths));
set => persistentDictionary.SetNonString(nameof(GridColumnsWidths), value);
}
[Description("Save cover image alongside audiobook?")]
public bool DownloadCoverArt
{
get => persistentDictionary.GetNonString<bool>(nameof(DownloadCoverArt));
set => persistentDictionary.SetNonString(nameof(DownloadCoverArt), value);
}
public enum BadBookAction
{

File diff suppressed because it is too large Load Diff

View File

@ -44,6 +44,7 @@ namespace LibationWinForms.Dialogs
this.retainAaxFileCbox.Text = desc(nameof(config.RetainAaxFile));
this.stripUnabridgedCbox.Text = desc(nameof(config.StripUnabridged));
this.createCueSheetCbox.Text = desc(nameof(config.CreateCueSheet));
this.downloadCoverArtCbox.Text = desc(nameof(config.DownloadCoverArt));
booksSelectControl.SetSearchTitle("books location");
booksSelectControl.SetDirectoryItems(
@ -73,6 +74,7 @@ namespace LibationWinForms.Dialogs
lameConstantBitrateCbox.Checked = config.LameConstantBitrate;
LameMatchSourceBRCbox.Checked = config.LameMatchSourceBR;
lameVBRQualityTb.Value = config.LameVBRQuality;
downloadCoverArtCbox.Checked = config.DownloadCoverArt;
autoScanCb.Checked = config.AutoScan;
showImportedStatsCb.Checked = config.ShowImportedStats;
@ -196,6 +198,7 @@ namespace LibationWinForms.Dialogs
config.LameConstantBitrate = lameConstantBitrateCbox.Checked;
config.LameMatchSourceBR = LameMatchSourceBRCbox.Checked;
config.LameVBRQuality = lameVBRQualityTb.Value;
config.DownloadCoverArt = downloadCoverArtCbox.Checked;
config.AutoScan = autoScanCb.Checked;
config.ShowImportedStats = showImportedStatsCb.Checked;

View File

@ -0,0 +1,86 @@
namespace LibationWinForms
{
partial class ImageDisplay
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.savePictureToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.contextMenuStrip1.SuspendLayout();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.ContextMenuStrip = this.contextMenuStrip1;
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(522, 450);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.savePictureToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(139, 26);
//
// savePictureToolStripMenuItem
//
this.savePictureToolStripMenuItem.Name = "savePictureToolStripMenuItem";
this.savePictureToolStripMenuItem.Size = new System.Drawing.Size(138, 22);
this.savePictureToolStripMenuItem.Text = "Save Picture";
this.savePictureToolStripMenuItem.Click += new System.EventHandler(this.savePictureToolStripMenuItem_Click);
//
// ImageDisplay
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(522, 450);
this.Controls.Add(this.pictureBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.Name = "ImageDisplay";
this.Text = "ImageDisplay";
this.Shown += new System.EventHandler(this.ImageDisplay_Shown);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.contextMenuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem savePictureToolStripMenuItem;
}
}

View File

@ -0,0 +1,120 @@
using FileLiberator;
using LibationFileManager;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace LibationWinForms
{
public partial class ImageDisplay : Form
{
public string PictureFileName { get; set; }
public string BookSaveDirectory { get; set; }
public byte[] CoverPicture { get => _coverBytes; set => pictureBox1.Image = Dinah.Core.Drawing.ImageReader.ToImage(_coverBytes = value); }
private byte[] _coverBytes;
public ImageDisplay()
{
InitializeComponent();
lastWidth = Width;
lastHeight = Height;
}
#region Make the form's aspect ratio always match the picture's aspect ratio.
private bool detectedResizeDirection = false;
private bool resizingWidth = false;
private bool resizingHeight = false;
private int lastWidth;
private int lastHeight;
private int formExtraWidth;
private int formExtraHeight;
private double pictureAR = 1;
protected override void OnResizeBegin(EventArgs e)
{
detectedResizeDirection = false;
base.OnResizeBegin(e);
}
protected override void OnResizeEnd(EventArgs e)
{
base.OnResize(e);
base.OnResizeEnd(e);
}
protected override void OnResize(EventArgs e)
{
if (WindowState != FormWindowState.Normal)
{
base.OnResize(e);
return;
}
int width = this.Width, height = this.Height;
if (!detectedResizeDirection)
{
resizingWidth = lastWidth != width;
resizingHeight = lastHeight != height;
detectedResizeDirection = true;
}
if (resizingWidth && !resizingHeight)
height = CalculateARHeight(width);
else
width = CalculateARWidth(height);
pictureBox1.Size = new Size(width - formExtraWidth, height - formExtraHeight);
lastWidth = width;
lastHeight = height;
SetBoundsCore(Location.X, Location.Y, width, height, BoundsSpecified.Width | BoundsSpecified.Height);
}
private int CalculateARHeight(int width)
{
return (int)((width - formExtraWidth) * pictureAR) + formExtraHeight;
}
private int CalculateARWidth(int height)
{
return (int)((height - formExtraHeight) * pictureAR) + formExtraWidth;
}
#endregion
private void ImageDisplay_Shown(object sender, EventArgs e)
{
formExtraWidth = Width - pictureBox1.Width;
formExtraHeight = Height - pictureBox1.Height;
OnResize(e);
}
private void savePictureToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new();
saveFileDialog.Filter = "jpeg|*.jpg";
saveFileDialog.InitialDirectory = Directory.Exists(BookSaveDirectory) ? BookSaveDirectory : Path.GetDirectoryName(BookSaveDirectory);
saveFileDialog.FileName = PictureFileName;
if (saveFileDialog.ShowDialog() != DialogResult.OK)
return;
try
{
File.WriteAllBytes(saveFileDialog.FileName, CoverPicture);
}
catch (Exception ex)
{
Serilog.Log.Logger.Error(ex, $"Failed to save picture to {saveFileDialog.FileName}");
MessageBox.Show(this, $"An error was encountered while trying to save the picture\r\n\r\n{ex.Message}", "Failed to save picture", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
}
}

View File

@ -0,0 +1,63 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="contextMenuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -9,6 +9,7 @@ using Dinah.Core;
using Dinah.Core.DataBinding;
using Dinah.Core.Threading;
using Dinah.Core.Windows.Forms;
using FileLiberator;
using LibationFileManager;
using LibationWinForms.Dialogs;
@ -35,6 +36,8 @@ namespace LibationWinForms
public partial class ProductsGrid : UserControl
{
ImageDisplay imageDisplay;
public event EventHandler<int> VisibleCountChanged;
// alias
@ -68,14 +71,37 @@ namespace LibationWinForms
if (e.RowIndex < 0)
return;
var clickedColumn = _dataGridView.Columns[e.ColumnIndex];
if (clickedColumn == liberateGVColumn)
if (e.ColumnIndex == liberateGVColumn.Index)
await Liberate_Click(getGridEntry(e.RowIndex));
else if (clickedColumn == tagAndDetailsGVColumn)
else if (e.ColumnIndex == tagAndDetailsGVColumn.Index)
Details_Click(getGridEntry(e.RowIndex));
else if (clickedColumn == descriptionGVColumn)
else if (e.ColumnIndex == descriptionGVColumn.Index)
Description_Click(getGridEntry(e.RowIndex), _dataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false));
else if (e.ColumnIndex == coverGVColumn.Index)
await Cover_Click(getGridEntry(e.RowIndex));
}
private async Task Cover_Click(GridEntry liveGridEntry)
{
var picDefinition = new PictureDefinition(liveGridEntry.LibraryBook.Book.PictureLarge, PictureSize.Native);
var picDlTask = Task.Run(() => PictureStorage.GetPictureSynchronously(picDefinition));
(_, byte[] initialImageBts) = PictureStorage.GetPicture(new PictureDefinition(liveGridEntry.LibraryBook.Book.PictureId, PictureSize._80x80));
var windowTitle = $"{liveGridEntry.Title} - Cover";
if (imageDisplay is null || imageDisplay.IsDisposed || !imageDisplay.Visible)
{
imageDisplay = new ImageDisplay();
imageDisplay.RestoreSizeAndLocation(Configuration.Instance);
imageDisplay.FormClosed += (_, _) => imageDisplay.SaveSizeAndLocation(Configuration.Instance);
imageDisplay.Show(this);
}
imageDisplay.BookSaveDirectory = AudibleFileStorage.Audio.GetDestinationDirectory(liveGridEntry.LibraryBook);
imageDisplay.PictureFileName = System.IO.Path.GetFileName(AudibleFileStorage.Audio.GetBooksDirectoryFilename(liveGridEntry.LibraryBook, ".jpg"));
imageDisplay.Text = windowTitle;
imageDisplay.CoverPicture = initialImageBts;
imageDisplay.CoverPicture = await picDlTask;
}
private void Description_Click(GridEntry liveGridEntry, Rectangle cellDisplay)
@ -87,13 +113,13 @@ namespace LibationWinForms
BorderThickness = 2,
};
void CloseWindow (object o, EventArgs e)
void CloseWindow(object o, EventArgs e)
{
displayWindow.Close();
}
_dataGridView.Scroll += CloseWindow;
displayWindow.FormClosed += (_,_) => _dataGridView.Scroll -= CloseWindow;
displayWindow.FormClosed += (_, _) => _dataGridView.Scroll -= CloseWindow;
displayWindow.Show(this);
}
@ -154,40 +180,40 @@ namespace LibationWinForms
Filter();
}
private void bindToGrid(List<DataLayer.LibraryBook> orderedBooks)
{
bindingList = new SortableBindingList<GridEntry>(orderedBooks.Select(lb => toGridEntry(lb)));
gridEntryBindingSource.DataSource = bindingList;
}
private void bindToGrid(List<DataLayer.LibraryBook> orderedBooks)
{
bindingList = new SortableBindingList<GridEntry>(orderedBooks.Select(lb => toGridEntry(lb)));
gridEntryBindingSource.DataSource = bindingList;
}
private void updateGrid(List<DataLayer.LibraryBook> orderedBooks)
{
for (var i = orderedBooks.Count - 1; i >= 0; i--)
{
var libraryBook = orderedBooks[i];
var existingItem = bindingList.FirstOrDefault(i => i.AudibleProductId == libraryBook.Book.AudibleProductId);
private void updateGrid(List<DataLayer.LibraryBook> orderedBooks)
{
for (var i = orderedBooks.Count - 1; i >= 0; i--)
{
var libraryBook = orderedBooks[i];
var existingItem = bindingList.FirstOrDefault(i => i.AudibleProductId == libraryBook.Book.AudibleProductId);
// add new to top
if (existingItem is null)
bindingList.Insert(0, toGridEntry(libraryBook));
// update existing
else
existingItem.UpdateLibraryBook(libraryBook);
}
// add new to top
if (existingItem is null)
bindingList.Insert(0, toGridEntry(libraryBook));
// update existing
else
existingItem.UpdateLibraryBook(libraryBook);
}
// remove deleted from grid. note: actual deletion from db must still occur via the RemoveBook feature. deleting from audible will not trigger this
var oldIds = bindingList.Select(ge => ge.AudibleProductId).ToList();
var newIds = orderedBooks.Select(lb => lb.Book.AudibleProductId).ToList();
var remove = oldIds.Except(newIds).ToList();
foreach (var id in remove)
{
var oldItem = bindingList.FirstOrDefault(ge => ge.AudibleProductId == id);
if (oldItem is not null)
bindingList.Remove(oldItem);
}
}
// remove deleted from grid. note: actual deletion from db must still occur via the RemoveBook feature. deleting from audible will not trigger this
var oldIds = bindingList.Select(ge => ge.AudibleProductId).ToList();
var newIds = orderedBooks.Select(lb => lb.Book.AudibleProductId).ToList();
var remove = oldIds.Except(newIds).ToList();
foreach (var id in remove)
{
var oldItem = bindingList.FirstOrDefault(ge => ge.AudibleProductId == id);
if (oldItem is not null)
bindingList.Remove(oldItem);
}
}
private GridEntry toGridEntry(DataLayer.LibraryBook libraryBook)
private GridEntry toGridEntry(DataLayer.LibraryBook libraryBook)
{
var entry = new GridEntry(libraryBook);
entry.Committed += Filter;
@ -195,11 +221,11 @@ namespace LibationWinForms
return entry;
}
#endregion
#endregion
#region Filter
#region Filter
private string _filterSearchString;
private string _filterSearchString;
private void Filter(object _ = null, EventArgs __ = null) => Filter(_filterSearchString);
public void Filter(string searchString)
{
@ -346,6 +372,8 @@ namespace LibationWinForms
{
if (e.ColumnIndex == descriptionGVColumn.Index)
e.ToolTipText = "Click to see full description";
else if (e.ColumnIndex == coverGVColumn.Index)
e.ToolTipText = "Click to see full size";
}
#endregion