diff --git a/Source/AppScaffolding/LicenseRecoveryGuidance.cs b/Source/AppScaffolding/LicenseRecoveryGuidance.cs index e022f2d0..b3a27db3 100644 --- a/Source/AppScaffolding/LicenseRecoveryGuidance.cs +++ b/Source/AppScaffolding/LicenseRecoveryGuidance.cs @@ -44,30 +44,27 @@ public static class LicenseRecoveryGuidance public static string BuildSteps(Locale? locale, VersionCheckOutcome updateStatus, bool cli = false, bool hasAdditionalMarketplaces = false) { var steps = new List(); - var unknown = string.IsNullOrWhiteSpace(locale?.CountryCode); - var caveat = unknown - ? " (US link; account region is unknown). For other regions, use your regional Amazon site: Manage Your Content and Devices > Devices > Audible." - : !locale!.CountryCode.Equals("us", StringComparison.OrdinalIgnoreCase) - ? " (regional link is unverified). If it does not work, use your regional Amazon site: Manage Your Content and Devices > Devices > Audible." - : "."; - steps.Add($"Open {DeviceManagementUrl(locale)}{caveat} Deregister entries named 'Libation'."); if (updateStatus != VersionCheckOutcome.UpToDate) steps.Add((updateStatus == VersionCheckOutcome.UpdateAvailable ? "Upgrade to the latest Libation: " : "If you're not on the latest version, upgrade: ") + ReleasesUrl); if (cli) { - steps.Add(hasAdditionalMarketplaces ? "Before deleting the account, run list-accounts and record its registration region (Locale) and all additional marketplaces (Also scans). Stop Libation and any running CLI/Docker jobs. Back up AccountsSettings.json, including the affected account's AdditionalLocaleNames array, then remove only that account object from its Accounts array and save. This preserves your library and downloaded files." : "Stop Libation and any running CLI/Docker jobs. Back up AccountsSettings.json, then remove only the affected account object from its Accounts array and save. This preserves your library and downloaded files."); - steps.Add("Run list-accounts to verify the old account is absent. Run login-external --account --locale to re-add it and sign in."); - if (hasAdditionalMarketplaces) - steps.Add("After login-external finishes, with Libation and CLI/Docker jobs stopped, copy the saved AdditionalLocaleNames array into the newly created account object in AccountsSettings.json (for example, \"AdditionalLocaleNames\": [\"us\"] for a UK account that also scans the US). Keep the new identity tokens; do not restore the old account object. Save, then run list-accounts and verify Locale and Also scans match your notes before scanning or retrying."); + var localeParam = string.IsNullOrWhiteSpace(locale?.Name) ? "" : locale.Name; + var extra = hasAdditionalMarketplaces + ? " (Your library and configured additional marketplaces will be preserved automatically.)" + : " (This preserves your library and account configuration.)"; + steps.Add($"Run login-external --account --locale {localeParam} to re-authenticate and establish a fresh device registration.{extra}"); steps.Add("Run scan, then retry with liberate ."); } else { - steps.Add(hasAdditionalMarketplaces ? "Go to Settings > Accounts. Before deleting the account, record its registration region and all additional marketplaces checked under its Marketplaces button. Then remove the affected account. This preserves your library and downloaded files. Save the removal, then close Libation." : "Go to Settings > Accounts and remove the affected account. This preserves your library and downloaded files. Save the removal, then close Libation."); - steps.Add("Reopen Libation. In Settings > Accounts, verify the old account is absent, then re-add the account using the same registration region and save."); - steps.Add(hasAdditionalMarketplaces ? "Scan and sign in once to enable the Marketplaces button. Before retrying downloads, return to Settings > Accounts > Marketplaces for this account, check every recorded additional marketplace, and save both dialogs. Scan again with all marketplaces restored, then retry the download (mark it Download Pending if needed)." : "Scan and sign in, then retry the download (mark it Download Pending if needed)."); + var extra = hasAdditionalMarketplaces + ? " (Your library and configured additional marketplaces under Marketplaces are preserved.)" + : " (This preserves your library and account configuration.)"; + steps.Add($"Go to Settings > Accounts, uncheck the \"Signed in?\" checkbox for the affected account, and click Save.{extra}"); + steps.Add("Scan and sign in when prompted to establish a fresh device registration."); + steps.Add("Retry the download (mark it Download Pending if needed)."); } return string.Join(Environment.NewLine + Environment.NewLine, steps.Select((step, index) => $"{index + 1}. {step}")); } diff --git a/Source/AudibleUtilities/Account.cs b/Source/AudibleUtilities/Account.cs index 3d814bde..937fd688 100644 --- a/Source/AudibleUtilities/Account.cs +++ b/Source/AudibleUtilities/Account.cs @@ -1,4 +1,4 @@ -using AudibleApi; +using AudibleApi; using AudibleApi.Authorization; using Dinah.Core; using Dinah.Core.Security; @@ -88,6 +88,44 @@ public class Account : IUpdatable, ILogMasked } } + /// + /// True when this account must obtain a new device registration and token set before next use + /// (e.g. after switching to Widevine or encountering CustomerThrottled on an obsolete device). + /// + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool RequiresReRegistration + { + get => field; + set + { + if (field == value) + return; + field = value; + update(); + } + } + + /// + /// True when the account has tokens registered with a non-Android device type (e.g. Mkb79IPhone) + /// or a legacy device serial format that is incompatible with modern Widevine downloads. + /// + public bool HasObsoleteDeviceRegistration() + { + if (IdentityTokens is null) + return false; + + if (IdentityTokens.DeviceType != AudibleApi.Resources.DeviceType) + return true; + + var serial = IdentityTokens.DeviceSerialNumber; + if (string.IsNullOrEmpty(serial) + || serial.Length != 20 + || !serial.All(char.IsAsciiHexDigit)) + return true; + + return false; + } + /// /// The marketplace this account is registered with: where it logs in, and the only place its tokens can be /// refreshed. Every account has exactly one. diff --git a/Source/AudibleUtilities/AccountCredentialStatus.cs b/Source/AudibleUtilities/AccountCredentialStatus.cs index 54090177..d0d6ba91 100644 --- a/Source/AudibleUtilities/AccountCredentialStatus.cs +++ b/Source/AudibleUtilities/AccountCredentialStatus.cs @@ -11,7 +11,10 @@ public static class AccountCredentialStatus /// public static bool LooksLikeMissingCredentials(Account? account) { - if (account?.IdentityTokens is not { } tokens) + if (account is null || account.RequiresReRegistration) + return true; + + if (account.IdentityTokens is not { } tokens) return true; if (tokens.IsValid) diff --git a/Source/AudibleUtilities/ApiExtended.cs b/Source/AudibleUtilities/ApiExtended.cs index 83e00213..798ecace 100644 --- a/Source/AudibleUtilities/ApiExtended.cs +++ b/Source/AudibleUtilities/ApiExtended.cs @@ -1,4 +1,4 @@ -using AudibleApi; +using AudibleApi; using AudibleApi.Common; using Dinah.Core; using LibationFileManager; @@ -44,6 +44,9 @@ public class ApiExtended try { + if (account.RequiresReRegistration) + throw new AuthenticationRequiredException(account, "Account requires a fresh login and device registration."); + Serilog.Log.Logger.Information("{@DebugInfo}", new { AccountMaskedLogEntry = account.MaskedLogEntry, @@ -82,7 +85,9 @@ public class ApiExtended throw new AuthenticationRequiredException( account, message: $"Stored credentials for {account.MaskedLogEntry} " - + (missingCredentials ? "are missing or incomplete" : "could not be used") + + (account.RequiresReRegistration + ? "require a new login and device registration" + : missingCredentials ? "are missing or incomplete" : "could not be used") + (LoginChoiceFactory is null ? " and interactive login is not available in this context (CLI/Docker)." : " and interactive login was not allowed.") @@ -100,6 +105,16 @@ public class ApiExtended LocaleName = locale.Name }); + if (account.RequiresReRegistration) + { + account.IdentityTokens?.Invalidate(); + using (var persister = AudibleApiStorage.GetAccountsSettingsPersister()) + { + var matching = persister.AccountsSettings.GetAccount(account.AccountId, account.Locale?.Name); + matching?.IdentityTokens?.Invalidate(); + } + } + var api = await EzApiCreator.GetApiAsync( LoginChoiceFactory(account), locale, @@ -107,6 +122,14 @@ public class ApiExtended account.GetIdentityTokensJsonPath(), Configuration.Instance.GetDeviceRegistrationProfile()); + account.RequiresReRegistration = false; + using (var persister = AudibleApiStorage.GetAccountsSettingsPersister()) + { + var matching = persister.AccountsSettings.GetAccount(account.AccountId, account.Locale?.Name); + if (matching is not null) + matching.RequiresReRegistration = false; + } + // login happens against the account's own marketplace, so the api it hands back reads that one. // re-create once the tokens exist if some other marketplace is the one actually wanted. if (storeLocale is not null && storeLocale.Name != locale.Name) diff --git a/Source/AudibleUtilities/ThrottledDeviceRecovery.cs b/Source/AudibleUtilities/ThrottledDeviceRecovery.cs new file mode 100644 index 00000000..582559c8 --- /dev/null +++ b/Source/AudibleUtilities/ThrottledDeviceRecovery.cs @@ -0,0 +1,122 @@ +using AudibleApi; +using LibationFileManager; +using System; +using System.Collections.Generic; + +namespace AudibleUtilities; + +public record ThrottledRecoveryResult( + bool WidevineEnabled, + bool DeviceRegistrationUpdated, + IReadOnlyList MarkedAccounts); + +/// +/// Recovers accounts from Audible download throttling caused by legacy device registrations +/// or missing Widevine configuration by switching settings to Android + Widevine and marking +/// accounts for a fresh device registration without deleting their library or account configuration. +/// +public static class ThrottledDeviceRecovery +{ + /// + /// Returns true when a download denial indicates throttling under a legacy registration or non-Widevine profile. + /// + public static bool ShouldRecover(ContentLicenseDeniedException ex, Account? account, Configuration config) + { + ArgumentNullException.ThrowIfNull(ex); + ArgumentNullException.ThrowIfNull(config); + + if (!ex.IsCustomerThrottled) + return false; + + return !config.UseWidevine + || config.DeviceRegistrationKind != DeviceRegistrationKind.CurrentAndroid + || (account?.HasObsoleteDeviceRegistration() == true); + } + + /// + /// Thunks settings to CurrentAndroid and Widevine, and marks affected accounts as requiring re-registration. + /// Note: When Widevine is enabled, ALL accounts require re-registration regardless of whether their device type was already Android. + /// + public static ThrottledRecoveryResult ApplyRecovery( + AccountsSettings accountsSettings, + Configuration config, + Account? throttledAccount = null) + { + ArgumentNullException.ThrowIfNull(accountsSettings); + ArgumentNullException.ThrowIfNull(config); + + bool widevineWasDisabled = !config.UseWidevine; + bool deviceKindWasNotCurrentAndroid = config.DeviceRegistrationKind != DeviceRegistrationKind.CurrentAndroid; + + // Thunk global settings + config.UseWidevine = true; + config.DeviceRegistrationKind = DeviceRegistrationKind.CurrentAndroid; + + var markedAccounts = new List(); + + if (throttledAccount is not null) + { + throttledAccount.RequiresReRegistration = true; + markedAccounts.Add(throttledAccount); + } + + foreach (var account in accountsSettings.GetAll()) + { + if (account == throttledAccount) + continue; + + // If Widevine was newly enabled, every account needs a relogin. + // If Widevine was already enabled, any account with an obsolete registration needs a relogin. + if (widevineWasDisabled || account.HasObsoleteDeviceRegistration()) + { + account.RequiresReRegistration = true; + markedAccounts.Add(account); + } + } + + return new ThrottledRecoveryResult( + WidevineEnabled: widevineWasDisabled, + DeviceRegistrationUpdated: deviceKindWasNotCurrentAndroid, + MarkedAccounts: markedAccounts); + } + + public const string WidevinePromptTitle = "Widevine Re-registration Required"; + public const string WidevinePromptMessage = + "In order to enable Widevine content, Libation will need to log into your accounts again with a fresh device registration.\r\n\r\n" + + "Do you want Libation to mark your accounts to prompt for login before the next download?\r\n\r\n" + + "(All of your account settings and marketplaces will be preserved.)"; + + /// + /// Marks all accounts as requiring re-registration when Widevine is enabled, and sets DeviceRegistrationKind to CurrentAndroid. + /// + public static void MarkAllAccountsForWidevine(AccountsSettings accountsSettings, Configuration config) + { + ArgumentNullException.ThrowIfNull(accountsSettings); + ArgumentNullException.ThrowIfNull(config); + + config.DeviceRegistrationKind = DeviceRegistrationKind.CurrentAndroid; + foreach (var account in accountsSettings.GetAll()) + { + account.RequiresReRegistration = true; + } + } + + /// + /// Marks any accounts with obsolete device registrations as requiring re-registration. + /// + public static int MarkObsoleteAccounts(AccountsSettings accountsSettings) + { + ArgumentNullException.ThrowIfNull(accountsSettings); + + int markedCount = 0; + foreach (var account in accountsSettings.GetAll()) + { + if (account.HasObsoleteDeviceRegistration()) + { + account.RequiresReRegistration = true; + markedCount++; + } + } + return markedCount; + } +} diff --git a/Source/FileLiberator/WidevineRecommendation.cs b/Source/FileLiberator/WidevineRecommendation.cs index fda84346..84f8a012 100644 --- a/Source/FileLiberator/WidevineRecommendation.cs +++ b/Source/FileLiberator/WidevineRecommendation.cs @@ -6,7 +6,9 @@ namespace FileLiberator; /// /// Detects a rare Audible API failure mode where ADRM licenserequest returns Sable error 000307 -/// with acr:null. Some titles (e.g. B08XDZCH78 in the US marketplace) only deliver via Widevine. +/// with acr:null (or where the subsequent AAX workaround fails with missing codecs). +/// Some titles (e.g. B08XDZCH78 in the US marketplace, or non-US titles where legacy AAX is disabled) +/// only deliver via Widevine. /// Keep all detection here so this edge case does not spread through download or UI code. /// public static class WidevineRecommendation @@ -23,6 +25,18 @@ public static class WidevineRecommendation /// public const string SableAcrNullMarker = "acr:null"; + /// + /// Fallback error message substring thrown by AudibleApi when the AAX workaround + /// cannot find codecs for a title whose primary ADRM licenserequest failed. + /// + public const string NoCodecSpecifiedMarker = "Book has no codec specified"; + + /// + /// Alternate fallback error message substring thrown by AudibleApi when the AAX workaround + /// finds zero available codecs. + /// + public const string NoAvailableCodecsMarker = "Book has no available codecs"; + /// /// True when matches the rare ADRM licenserequest / Sable acr:null pattern. /// @@ -41,19 +55,55 @@ public static class WidevineRecommendation && json.Contains(SableAcrNullMarker, StringComparison.Ordinal); } + /// + /// True when indicates the AAX download workaround failed + /// because the title has no legacy AAX audio codecs available. + /// + public static bool IsAaxFallbackMissingCodecError(Exception ex) + { + ArgumentNullException.ThrowIfNull(ex); + + if (ex.Message.Contains(NoCodecSpecifiedMarker, StringComparison.OrdinalIgnoreCase) + || ex.Message.Contains(NoAvailableCodecsMarker, StringComparison.OrdinalIgnoreCase)) + return true; + + return ex.InnerException is not null && IsAaxFallbackMissingCodecError(ex.InnerException); + } + + /// + /// True when matches either the primary Sable acr:null pattern + /// or the secondary AAX fallback missing-codec pattern. + /// + public static bool IsAdrmOrAaxFallbackUnavailable(Exception ex) + { + ArgumentNullException.ThrowIfNull(ex); + + if (ex is ApiErrorException apiEx && IsAdrmLicenseUnavailableError(apiEx)) + return true; + + return IsAaxFallbackMissingCodecError(ex); + } + /// /// True when Libation should suggest enabling Widevine for this failure. /// - public static bool ShouldRecommendWidevine(ApiErrorException ex, Configuration config) + public static bool ShouldRecommendWidevine(Exception ex, Configuration config) { ArgumentNullException.ThrowIfNull(ex); ArgumentNullException.ThrowIfNull(config); - return !config.UseWidevine && IsAdrmLicenseUnavailableError(ex); + return !config.UseWidevine && IsAdrmOrAaxFallbackUnavailable(ex); } - /// One line for logs and CLI when applies. - public static string BuildLogSummary(string bookTitleWithSubtitle) - => $"{bookTitleWithSubtitle}: Audible returned no ADRM license (Sable acr:null). " - + "Some rare titles only download with Widevine — try Settings > Audio File Options > Use Widevine DRM."; + /// Overload preserving binary / source compatibility for ApiErrorException callers. + public static bool ShouldRecommendWidevine(ApiErrorException ex, Configuration config) + => ShouldRecommendWidevine((Exception)ex, config); + + /// One line for logs and CLI when applies. + public static string BuildLogSummary(string bookTitleWithSubtitle, string? accountId = null) + { + var accountSuffix = string.IsNullOrWhiteSpace(accountId) ? "" : $" for account '{accountId}'"; + return $"{bookTitleWithSubtitle}: Standard (ADRM) license unavailable. " + + $"Libation enabled Widevine DRM and marked account{accountSuffix} for re-registration. Sign in to complete setup."; + } } diff --git a/Source/LibationAvalonia/Controls/Settings/Audio.axaml b/Source/LibationAvalonia/Controls/Settings/Audio.axaml index 74d0b4b6..f9bc7fe3 100644 --- a/Source/LibationAvalonia/Controls/Settings/Audio.axaml +++ b/Source/LibationAvalonia/Controls/Settings/Audio.axaml @@ -51,7 +51,7 @@ diff --git a/Source/LibationAvalonia/Controls/Settings/Audio.axaml.cs b/Source/LibationAvalonia/Controls/Settings/Audio.axaml.cs index 9b604a14..e9c69813 100644 --- a/Source/LibationAvalonia/Controls/Settings/Audio.axaml.cs +++ b/Source/LibationAvalonia/Controls/Settings/Audio.axaml.cs @@ -22,42 +22,40 @@ public partial class Audio : UserControl } } - private async void UseWidevine_IsCheckedChanged(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private async void UseWidevine_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { if (sender is CheckBox cbox && cbox.IsChecked is true) { using var accounts = AudibleApiStorage.GetAccountsSettingsPersister(); - if (!accounts.AccountsSettings.Accounts.All(a => a.IdentityTokens?.DeviceType == AudibleApi.Resources.DeviceType)) + if (accounts.AccountsSettings.Accounts.Count > 0) { var choice = await MessageBox.Show(this.GetParentWindow(), - "In order to enable widevine content, Libation will need to log into your accounts again.\r\n\r\n" + - "Do you want Libation to clear your current account settings and prompt you to login before the next download?", - "Widevine Content Unavailable", - MessageBoxButtons.YesNo, - MessageBoxIcon.Question, - MessageBoxDefaultButton.Button2); + ThrottledDeviceRecovery.WidevinePromptMessage, + ThrottledDeviceRecovery.WidevinePromptTitle, + MessageBoxButtons.YesNo, + MessageBoxIcon.Question, + MessageBoxDefaultButton.Button1); if (choice == DialogResult.Yes) { - foreach (var account in accounts.AccountsSettings.Accounts.ToArray()) - { - if (account.Locale is not null && account.IdentityTokens?.DeviceType != AudibleApi.Resources.DeviceType) - { - accounts.AccountsSettings.Delete(account); - var acc = accounts.AccountsSettings.Upsert(account.AccountId, account.Locale.Name); - acc.AccountName = account.AccountName; - } - } + ThrottledDeviceRecovery.MarkAllAccountsForWidevine(accounts.AccountsSettings, Configuration.Instance); return; } - _viewModel?.UseWidevine = false; + cbox.IsChecked = false; + if (_viewModel is not null) + _viewModel.UseWidevine = false; + } + else + { + Configuration.Instance.DeviceRegistrationKind = AudibleApi.DeviceRegistrationKind.CurrentAndroid; } } else { - _viewModel?.Request_xHE_AAC = _viewModel.RequestSpatial = false; + if (_viewModel is not null) + _viewModel.Request_xHE_AAC = _viewModel.RequestSpatial = false; } } diff --git a/Source/LibationAvalonia/Dialogs/AccountsDialog.axaml b/Source/LibationAvalonia/Dialogs/AccountsDialog.axaml index 1dc81128..55e52029 100644 --- a/Source/LibationAvalonia/Dialogs/AccountsDialog.axaml +++ b/Source/LibationAvalonia/Dialogs/AccountsDialog.axaml @@ -59,6 +59,19 @@ Binding="{Binding LibraryScan, Mode=TwoWay}" Header="Include in library scan?"/> + + + + + + + + public List AdditionalLocaleNames { get; } = new(); + public bool SignedIn + { + get => field; + set + { + this.RaiseAndSetIfChanged(ref field, value); + this.RaisePropertyChanged(nameof(SignedInToolTip)); + } + } + + public bool CanToggleSignedIn + { + get => field; + private set + { + this.RaiseAndSetIfChanged(ref field, value); + this.RaisePropertyChanged(nameof(SignedInToolTip)); + } + } + + public string SignedInToolTip + => !CanToggleSignedIn + ? "Account has not been authenticated yet. Run a scan to sign in." + : SignedIn + ? "Account is signed in. Uncheck and save to require a fresh sign-in and device registration on the next scan or liberate." + : "Account requires a fresh sign-in. Check and save to keep existing registration."; + public bool CanExport { get => field; @@ -106,6 +133,8 @@ public partial class AccountsDialog : DialogWindow private void RefreshCanExportFromAccount(Account account) { CanExport = account.IdentityTokens?.IsValid == true; + CanToggleSignedIn = CanExport; + SignedIn = CanExport && !account.RequiresReRegistration; RaiseDerivedFromCanExport(); } @@ -114,6 +143,8 @@ public partial class AccountsDialog : DialogWindow this.RaisePropertyChanged(nameof(ExportButtonToolTip)); this.RaisePropertyChanged(nameof(CanCheckMarketplaces)); this.RaisePropertyChanged(nameof(MarketplacesButtonToolTip)); + this.RaisePropertyChanged(nameof(CanToggleSignedIn)); + this.RaisePropertyChanged(nameof(SignedInToolTip)); } private void RefreshCanExport() @@ -121,6 +152,8 @@ public partial class AccountsDialog : DialogWindow if (string.IsNullOrEmpty(AccountId) || SelectedLocale is null) { CanExport = false; + CanToggleSignedIn = false; + SignedIn = false; RaiseDerivedFromCanExport(); return; } @@ -129,6 +162,8 @@ public partial class AccountsDialog : DialogWindow var account = persister.AccountsSettings.Accounts.FirstOrDefault(a => a.AccountId == AccountId && a.Locale?.Name == SelectedLocale.Name); CanExport = account?.IdentityTokens?.IsValid == true; + CanToggleSignedIn = CanExport; + SignedIn = CanExport && account?.RequiresReRegistration != true; RaiseDerivedFromCanExport(); } } @@ -177,6 +212,7 @@ public partial class AccountsDialog : DialogWindow { // only user-editable fields; skip derived props like CanExport / button tooltips if (e.PropertyName is nameof(AccountDto.LibraryScan) + or nameof(AccountDto.SignedIn) or nameof(AccountDto.AccountId) or nameof(AccountDto.SelectedLocale) or nameof(AccountDto.AccountName)) @@ -363,6 +399,15 @@ public partial class AccountsDialog : DialogWindow ? $"{dto.AccountId} - {dto.SelectedLocale?.Name}" : dto.AccountName.Trim(); + if (!dto.SignedIn && acct.IdentityTokens?.IsValid == true) + { + acct.RequiresReRegistration = true; + } + else if (dto.SignedIn && acct.RequiresReRegistration) + { + acct.RequiresReRegistration = false; + } + // drop every marketplace before assigning any, so that moving one from one account to another in a // single sitting cannot trip the "no two accounts scan one marketplace" rule halfway through acct.SetAdditionalMarketplaces([]); diff --git a/Source/LibationAvalonia/Dialogs/FindBetterQualityBooksDialog.axaml.cs b/Source/LibationAvalonia/Dialogs/FindBetterQualityBooksDialog.axaml.cs index 64751402..f92b759c 100644 --- a/Source/LibationAvalonia/Dialogs/FindBetterQualityBooksDialog.axaml.cs +++ b/Source/LibationAvalonia/Dialogs/FindBetterQualityBooksDialog.axaml.cs @@ -132,7 +132,11 @@ public partial class FindBetterQualityBooksDialog : DialogWindow (sender as Button)?.IsEnabled = false; try { - await VM.MarkBooksAsync(); + var result = await VM.MarkBooksAsync(); + if (result.GetSummaryMessage() is string message) + { + await MessageBox.Show(this, message, "Books Marked for Download", MessageBoxButtons.OK, MessageBoxIcon.Information); + } } catch (Exception ex) { diff --git a/Source/LibationCli/Options/ListAccountsOptions.cs b/Source/LibationCli/Options/ListAccountsOptions.cs index 7e475dac..f6d51a8a 100644 --- a/Source/LibationCli/Options/ListAccountsOptions.cs +++ b/Source/LibationCli/Options/ListAccountsOptions.cs @@ -30,7 +30,9 @@ internal class ListAccountsOptions : OptionsBase a.AccountName ?? "", a.Locale?.Name ?? "", a.LibraryScan ? "yes" : "no", - a.IdentityTokens?.IsValid == true ? "yes" : "no", + a.RequiresReRegistration + ? (Bare ? "no" : "re-login needed") + : (a.IdentityTokens?.IsValid == true ? "yes" : "no"), string.Join(", ", a.AdditionalLocales.Select(l => l.Name)))) .ToArray(); diff --git a/Source/LibationCli/Options/LoginExternalOptions.cs b/Source/LibationCli/Options/LoginExternalOptions.cs index e7ccff67..006cde53 100644 --- a/Source/LibationCli/Options/LoginExternalOptions.cs +++ b/Source/LibationCli/Options/LoginExternalOptions.cs @@ -24,6 +24,9 @@ internal class LoginExternalOptions : OptionsBase [Option("device-registration", Required = false, HelpText = "CurrentAndroid, RetailAndroid, or Mkb79IPhone. Defaults to Settings. Only used for a new sign-in; remove the account first.")] public string? DeviceRegistration { get; set; } + internal static bool NeedsReRegistration(Account? account) + => account?.RequiresReRegistration == true || account?.HasObsoleteDeviceRegistration() == true; + protected override async Task ProcessAsync() { var accountId = AccountId?.Trim(); @@ -57,18 +60,45 @@ internal class LoginExternalOptions : OptionsBase return; } - using var persister = AudibleApiStorage.GetAccountsSettingsPersister(); - // Persist by canonical locale name ("germany"), not the user input ("de"). - var account = persister.AccountsSettings.Upsert(accountId, locale.Name); - - if (account.IdentityTokens?.IsValid == true) + string jsonPath; + using (var persister = AudibleApiStorage.GetAccountsSettingsPersister()) { - Console.WriteLine( - $"Account '{accountId}' ({locale.Name}) is already authenticated. No browser login needed."); - if (!string.IsNullOrWhiteSpace(DeviceRegistration)) + // Persist by canonical locale name ("germany"), not the user input ("de"). + var account = persister.AccountsSettings.Upsert(accountId, locale.Name); + jsonPath = account.GetIdentityTokensJsonPath(); + + bool needsReRegistration = NeedsReRegistration(account); + + if (account.IdentityTokens?.IsValid == true && !needsReRegistration) + { Console.WriteLine( - "Device registration only applies to a new sign-in. Remove the account first, then run login-external again."); - return; + $"Account '{accountId}' ({locale.Name}) is already authenticated. No browser login needed."); + if (!string.IsNullOrWhiteSpace(DeviceRegistration)) + Console.WriteLine( + "Device registration only applies to a new sign-in. Remove the account first, then run login-external again."); + return; + } + + if (account.RequiresReRegistration) + { + Console.WriteLine($"Account '{accountId}' ({locale.Name}) is marked as requiring re-registration. Proceeding with sign-in..."); + } + else if (account.HasObsoleteDeviceRegistration()) + { + Console.WriteLine($"Account '{accountId}' ({locale.Name}) has an obsolete or legacy device registration. Proceeding with sign-in..."); + } + + if (needsReRegistration) + { + account.IdentityTokens?.Invalidate(); + + if (string.IsNullOrWhiteSpace(DeviceRegistration)) + { + Configuration.Instance.UseWidevine = true; + Configuration.Instance.DeviceRegistrationKind = DeviceRegistrationKind.CurrentAndroid; + registrationProfile = DeviceRegistrationProfile.CurrentAndroid; + } + } } var presetResponse = ResponseUrl?.Trim(); @@ -87,8 +117,13 @@ internal class LoginExternalOptions : OptionsBase loginExternal, locale, AudibleApiStorage.AccountsSettingsFile, - account.GetIdentityTokensJsonPath(), + jsonPath, registrationProfile); + + using var persister = AudibleApiStorage.GetAccountsSettingsPersister(); + var account = persister.AccountsSettings.GetAccount(accountId, locale.Name); + if (account is not null) + account.RequiresReRegistration = false; } catch (Exception ex) { diff --git a/Source/LibationCli/Options/_ProcessableOptionsBase.cs b/Source/LibationCli/Options/_ProcessableOptionsBase.cs index b7dacfd0..72b0a43f 100644 --- a/Source/LibationCli/Options/_ProcessableOptionsBase.cs +++ b/Source/LibationCli/Options/_ProcessableOptionsBase.cs @@ -1,5 +1,6 @@ -using ApplicationServices; +using ApplicationServices; using AudibleApi; +using AudibleUtilities; using CommandLine; using DataLayer; using FileLiberator; @@ -327,17 +328,55 @@ public abstract class ProcessableOptionsBase : OptionsBase Serilog.Log.Logger.Error(errorMessage); } } - catch (ApiErrorException ex) when (WidevineRecommendation.ShouldRecommendWidevine(ex, Configuration.Instance)) + catch (Exception ex) when (WidevineRecommendation.ShouldRecommendWidevine(ex, Configuration.Instance)) { - Console.Error.WriteLine(WidevineRecommendation.BuildLogSummary(libraryBook.Book.TitleWithSubtitle)); - Serilog.Log.Logger.Error(ex, "ADRM license unavailable (Sable acr:null) {@DebugInfo}", new { Book = libraryBook.LogFriendly() }); + string? accountId = null; + string? localeName = null; + if (System.IO.File.Exists(AudibleApiStorage.AccountsSettingsFile)) + { + using var persister = AudibleApiStorage.GetAccountsSettingsPersister(); + var account = persister.AccountsSettings.GetAccount(libraryBook.Account, libraryBook.Book.Locale); + accountId = account?.AccountId ?? libraryBook.Account; + localeName = account?.Locale?.Name ?? libraryBook.Book.Locale; + ThrottledDeviceRecovery.ApplyRecovery(persister.AccountsSettings, Configuration.Instance, account); + } + + Console.Error.WriteLine(WidevineRecommendation.BuildLogSummary(libraryBook.Book.TitleWithSubtitle, accountId)); + if (!string.IsNullOrWhiteSpace(accountId)) + { + Console.Error.WriteLine( + $"Run 'libationcli login-external --account {accountId} --locale {localeName}' to sign in and register for Widevine credentials."); + } + + Serilog.Log.Logger.Error(ex, "ADRM license unavailable (Sable acr:null or AAX fallback without codecs) {@DebugInfo}", new { Book = libraryBook.LogFriendly() }); ReportNextAttempt(libraryBook); } catch (ContentLicenseDeniedException clEx) { - var (locale, hasAdditionalMarketplaces) = AppScaffolding.LicenseRecoveryGuidance.GetAccountContext(libraryBook); - foreach (var line in ContentLicenseDeniedCliSummary.Lines(clEx, locale, AppScaffolding.LibationScaffolding.LastVersionCheckOutcome, hasAdditionalMarketplaces)) - Console.Error.WriteLine(line); + bool recovered = false; + if (System.IO.File.Exists(AudibleApiStorage.AccountsSettingsFile)) + { + using var persister = AudibleApiStorage.GetAccountsSettingsPersister(); + var account = persister.AccountsSettings.GetAccount(libraryBook.Account, libraryBook.Book.Locale); + + if (ThrottledDeviceRecovery.ShouldRecover(clEx, account, Configuration.Instance)) + { + ThrottledDeviceRecovery.ApplyRecovery(persister.AccountsSettings, Configuration.Instance, account); + Console.Error.WriteLine( + $"Audible reported CustomerThrottled on a legacy or non-Widevine device registration. Libation has updated settings to Android emulator with Widevine enabled, and marked account '{account?.AccountId ?? libraryBook.Account}' for re-registration."); + Console.Error.WriteLine( + $"Run 'libationcli login-external --account {account?.AccountId ?? libraryBook.Account} --locale {account?.Locale?.Name ?? libraryBook.Book.Locale}' to sign in and register a fresh device."); + recovered = true; + } + } + + if (!recovered) + { + var (locale, hasAdditionalMarketplaces) = AppScaffolding.LicenseRecoveryGuidance.GetAccountContext(libraryBook); + foreach (var line in ContentLicenseDeniedCliSummary.Lines(clEx, locale, AppScaffolding.LibationScaffolding.LastVersionCheckOutcome, hasAdditionalMarketplaces)) + Console.Error.WriteLine(line); + } + Serilog.Log.Logger.Error(clEx, "Content license denied {@DebugInfo}", new { Book = libraryBook.LogFriendly() }); ReportNextAttempt(libraryBook); } diff --git a/Source/LibationUiBase/ContentLicenseDeniedUserMessage.cs b/Source/LibationUiBase/ContentLicenseDeniedUserMessage.cs index a1293d53..1c74abcb 100644 --- a/Source/LibationUiBase/ContentLicenseDeniedUserMessage.cs +++ b/Source/LibationUiBase/ContentLicenseDeniedUserMessage.cs @@ -25,6 +25,13 @@ public static class ContentLicenseDeniedUserMessage => BuildBody(bookTitleWithSubtitle, "Audible says this account is being throttled. This can also happen with an old device registration. Try these recovery steps first.", locale, updateStatus, hasAdditionalMarketplaces); + /// Audible throttled on legacy or non-Widevine registration; settings updated and account marked for re-registration. + public static string BuildDialogBodyForThrottlingRecovered(string bookTitleWithSubtitle) + => $"You were denied a content license for {bookTitleWithSubtitle}\n\n" + + "Audible reported throttling on your account's legacy device registration.\n\n" + + "Libation has automatically updated your settings to Android emulator and Widevine DRM, and marked your account for a fresh sign-in.\n\n" + + "No accounts need to be deleted. Next time you Scan or Liberate, you will be prompted to sign in once to establish the new device registration."; + /// Plus denials may indicate registration trouble, rate limits, or lost access. public static string BuildDialogBodyForPlusCatalog(string bookTitleWithSubtitle, AudibleApi.Locale? locale = null, AppScaffolding.VersionCheckOutcome updateStatus = AppScaffolding.VersionCheckOutcome.UnableToDetermine, bool hasAdditionalMarketplaces = false) diff --git a/Source/LibationUiBase/FindBetterQualityBooksViewModel.cs b/Source/LibationUiBase/FindBetterQualityBooksViewModel.cs index 904d4ef2..8e81a2f5 100644 --- a/Source/LibationUiBase/FindBetterQualityBooksViewModel.cs +++ b/Source/LibationUiBase/FindBetterQualityBooksViewModel.cs @@ -1,5 +1,6 @@ using AaxDecrypter; using ApplicationServices; +using AudibleUtilities; using DataLayer; using Dinah.Core; using Dinah.Core.Net.Http; @@ -15,6 +16,34 @@ using System.Threading.Tasks; namespace LibationUiBase; +public record MarkBooksResult( + int MarkedCount, + bool WidevineEnabled, + bool XHeAacRequested, + bool AccountsMarkedForReRegistration) +{ + public string? GetSummaryMessage() + { + if (MarkedCount == 0) + return null; + + var message = MarkedCount == 1 + ? "Marked 1 book as Download Pending." + : $"Marked {MarkedCount} books as Download Pending."; + + if (WidevineEnabled || AccountsMarkedForReRegistration) + { + message += "\r\n\r\nLibation has automatically configured your download settings for higher-quality audio and marked your accounts for a fresh sign-in on your next scan or download so that the higher-quality audio can be acquired."; + } + else if (XHeAacRequested) + { + message += "\r\n\r\nLibation has automatically enabled xHE-AAC audio requests in your settings."; + } + + return message; + } +} + public class FindBetterQualityBooksViewModel : ReactiveObject { public const string StartScanBtnText = "Scan Audible for Higher Quality Audio"; @@ -32,9 +61,11 @@ public class FindBetterQualityBooksViewModel : ReactiveObject Click 'Scan Audible for Higher Quality Audio' to begin. - When done, click the 'Mark X books as Download Pending' to allow Libation to re-download those books in the higher. + When done, click 'Mark X books as Download Pending' to allow Libation to re-download those books in the higher quality format. - Note: make sure you adjust your download quality settings before re-liberating the books. + Marking books will automatically configure Widevine and xHE-AAC settings and prompt for a fresh account sign-in if needed, ensuring the upgraded audio streams are downloaded. + + Note: If you have a large library, downloading many higher-quality audiobooks in quick succession may trigger Audible's daily download limits. You can configure a daily download limit or download delay in Settings > Network if needed. Display this help message again in the future? """; @@ -76,14 +107,50 @@ public class FindBetterQualityBooksViewModel : ReactiveObject cts?.Cancel(); } - public async Task MarkBooksAsync() + public async Task MarkBooksAsync() { var significant = Books?.Where(b => b.IsSignificant).ToArray() ?? []; + if (significant.Length == 0) + return new MarkBooksResult(0, false, false, false); await significant.Select(b => b.LibraryBook).UpdateBookStatusAsync(LiberatedStatus.NotLiberated); Array.ForEach(significant, b => Books?.Remove(b)); SignificantCount = Books?.Count(b => b.IsSignificant) ?? 0; + + bool widevineNewlyEnabled = false; + bool xHeAacNewlyRequested = false; + bool accountsMarked = false; + + bool requiresWidevine = ScanWidevine || significant.Any(b => b.AvailableCodec is "xHE-AAC" or "EC-3" or "AC-4"); + if (File.Exists(AudibleApiStorage.AccountsSettingsFile)) + { + using var persister = AudibleApiStorage.GetAccountsSettingsPersister(); + if (requiresWidevine) + { + var recovery = ThrottledDeviceRecovery.ApplyRecovery(persister.AccountsSettings, Configuration.Instance); + widevineNewlyEnabled = recovery.WidevineEnabled; + accountsMarked = recovery.MarkedAccounts.Count > 0; + } + else + { + accountsMarked = ThrottledDeviceRecovery.MarkObsoleteAccounts(persister.AccountsSettings) > 0; + } + } + else if (requiresWidevine) + { + widevineNewlyEnabled = !Configuration.Instance.UseWidevine; + Configuration.Instance.UseWidevine = true; + Configuration.Instance.DeviceRegistrationKind = AudibleApi.DeviceRegistrationKind.CurrentAndroid; + } + + if (requiresWidevine && significant.Any(b => b.AvailableCodec == "xHE-AAC") && !Configuration.Instance.Request_xHE_AAC) + { + Configuration.Instance.Request_xHE_AAC = true; + xHeAacNewlyRequested = true; + } + + return new MarkBooksResult(significant.Length, widevineNewlyEnabled, xHeAacNewlyRequested, accountsMarked); } public async Task ScanAsync() diff --git a/Source/LibationUiBase/ProcessQueue/ProcessBookViewModel.cs b/Source/LibationUiBase/ProcessQueue/ProcessBookViewModel.cs index 0fc62427..87c0542b 100644 --- a/Source/LibationUiBase/ProcessQueue/ProcessBookViewModel.cs +++ b/Source/LibationUiBase/ProcessQueue/ProcessBookViewModel.cs @@ -1,6 +1,7 @@ -using ApplicationServices; +using ApplicationServices; using AudibleApi; using AudibleApi.Common; +using AudibleUtilities; using DataLayer; using Dinah.Core; using Dinah.Core.ErrorHandling; @@ -27,6 +28,8 @@ public enum ProcessBookResult LicenseDeniedPossibleOutage, /// Audible named CustomerThrottled on the license denial. LicenseDeniedThrottled, + /// Audible throttled on legacy/non-Widevine registration; settings thunked to Android+Widevine and account marked for re-registration. + LicenseDeniedThrottledRecovered, /// ADRM licenserequest failed with Sable acr:null; Widevine may work (see WidevineRecommendation). WidevineRecommended, /// Volume full on write; queue should stop (see ProcessQueueViewModel queue loop). @@ -89,6 +92,7 @@ public class ProcessBookViewModel : ReactiveObject (ProcessBookResult.LicenseDenied, false) => "License Denied", (ProcessBookResult.LicenseDeniedPossibleOutage, _) => "Possible Service Interruption", (ProcessBookResult.LicenseDeniedThrottled, _) => "License denied (throttled)", + (ProcessBookResult.LicenseDeniedThrottledRecovered, _) => "License denied (re-login needed)", (ProcessBookResult.WidevineRecommended, _) => WidevineRecommendationUserMessage.QueueStatusText, (ProcessBookResult.DiskFull, _) => "Disk full, queue stopped", _ => Status.ToString(), @@ -231,10 +235,16 @@ public class ProcessBookViewModel : ReactiveObject } } } - catch (ApiErrorException ex) when (WidevineRecommendation.ShouldRecommendWidevine(ex, Configuration)) + catch (Exception ex) when (WidevineRecommendation.ShouldRecommendWidevine(ex, Configuration)) { - Serilog.Log.Logger.Error(ex, "ADRM license unavailable (Sable acr:null) for {Book}", LibraryBook.LogFriendly()); - LogInfo($"{procName}: {WidevineRecommendationUserMessage.BuildLogSummary(LibraryBook.Book.TitleWithSubtitle)}"); + Serilog.Log.Logger.Error(ex, "ADRM license unavailable (Sable acr:null or AAX fallback without codecs) for {Book}", LibraryBook.LogFriendly()); + if (System.IO.File.Exists(AudibleApiStorage.AccountsSettingsFile)) + { + using var persister = AudibleApiStorage.GetAccountsSettingsPersister(); + var account = persister.AccountsSettings.GetAccount(LibraryBook.Account, LibraryBook.Book.Locale); + ThrottledDeviceRecovery.ApplyRecovery(persister.AccountsSettings, Configuration, account); + } + LogInfo($"{procName}: {WidevineRecommendationUserMessage.BuildLogSummary(LibraryBook.Book.TitleWithSubtitle, LibraryBook.Account.ToMask())}"); result = ProcessBookResult.WidevineRecommended; } catch (ContentLicenseDeniedException ldex) @@ -242,8 +252,25 @@ public class ProcessBookViewModel : ReactiveObject Serilog.Log.Logger.Error(ldex, "Content license was denied for {Book}", LibraryBook.LogFriendly()); if (ldex.IsCustomerThrottled) { - LogInfo($"{procName}: Audible reports throttling. Try deregistering Libation devices and recreating the account first. Recovery steps: {AppScaffolding.LicenseRecoveryGuidance.DocumentationUrl}. If it persists, wait 24 to 48 hours, sometimes a few days. - {LibraryBook.Book}"); - result = ProcessBookResult.LicenseDeniedThrottled; + bool recovered = false; + if (System.IO.File.Exists(AudibleApiStorage.AccountsSettingsFile)) + { + using var persister = AudibleApiStorage.GetAccountsSettingsPersister(); + var account = persister.AccountsSettings.GetAccount(LibraryBook.Account, LibraryBook.Book.Locale); + if (ThrottledDeviceRecovery.ShouldRecover(ldex, account, Configuration.Instance)) + { + ThrottledDeviceRecovery.ApplyRecovery(persister.AccountsSettings, Configuration.Instance, account); + LogInfo($"{procName}: Audible reports throttling on a legacy or non-Widevine registration. Libation updated settings to Android + Widevine and marked account '{LibraryBook.Account.ToMask()}' for re-registration. Sign in on next scan or liberate to complete setup. - {LibraryBook.Book}"); + result = ProcessBookResult.LicenseDeniedThrottledRecovered; + recovered = true; + } + } + + if (!recovered) + { + LogInfo($"{procName}: Audible reports throttling. Try deregistering Libation devices and recreating the account first. Recovery steps: {AppScaffolding.LicenseRecoveryGuidance.DocumentationUrl}. If it persists, wait 24 to 48 hours, sometimes a few days. - {LibraryBook.Book}"); + result = ProcessBookResult.LicenseDeniedThrottled; + } } else if (ldex.AYCL?.RejectionReason is null or RejectionReason.GenericError) { diff --git a/Source/LibationUiBase/ProcessQueue/ProcessQueueViewModel.cs b/Source/LibationUiBase/ProcessQueue/ProcessQueueViewModel.cs index e8fc414b..51f962cc 100644 --- a/Source/LibationUiBase/ProcessQueue/ProcessQueueViewModel.cs +++ b/Source/LibationUiBase/ProcessQueue/ProcessQueueViewModel.cs @@ -1,4 +1,4 @@ -using ApplicationServices; +using ApplicationServices; using DataLayer; using FileLiberator; using LibationFileManager; @@ -815,6 +815,7 @@ public class ProcessQueueViewModel : ReactiveObject } else if (result == ProcessBookResult.LicenseDeniedPossibleOutage || result == ProcessBookResult.LicenseDeniedThrottled + || result == ProcessBookResult.LicenseDeniedThrottledRecovered || (result == ProcessBookResult.LicenseDenied && book.LibraryBook.IsAudiblePlus)) { bool show; @@ -828,6 +829,7 @@ public class ProcessQueueViewModel : ReactiveObject { ProcessBookResult.LicenseDeniedPossibleOutage => ContentLicenseDeniedUserMessage.BuildDialogBodyForPossibleOutage(title, locale, updateStatus, hasAdditionalMarketplaces), ProcessBookResult.LicenseDeniedThrottled => ContentLicenseDeniedUserMessage.BuildDialogBodyForThrottling(title, locale, updateStatus, hasAdditionalMarketplaces), + ProcessBookResult.LicenseDeniedThrottledRecovered => ContentLicenseDeniedUserMessage.BuildDialogBodyForThrottlingRecovered(title), _ => ContentLicenseDeniedUserMessage.BuildDialogBodyForPlusCatalog(title, locale, updateStatus, hasAdditionalMarketplaces) }; await MessageBoxBase.Show( diff --git a/Source/LibationUiBase/WidevineRecommendationUserMessage.cs b/Source/LibationUiBase/WidevineRecommendationUserMessage.cs index 7e71bccb..33970f04 100644 --- a/Source/LibationUiBase/WidevineRecommendationUserMessage.cs +++ b/Source/LibationUiBase/WidevineRecommendationUserMessage.cs @@ -3,28 +3,28 @@ using FileLiberator; namespace LibationUiBase; /// -/// User-facing copy when ADRM licenserequest fails with Sable acr:null (rare; Widevine may work). +/// User-facing copy when ADRM licenserequest fails with Sable acr:null or AAX fallback has no codecs (Widevine required). /// Shared by WinForms, Avalonia, and the process queue. /// public static class WidevineRecommendationUserMessage { - public const string DialogCaption = "Download license unavailable"; + public const string DialogCaption = "Widevine DRM Enabled"; - public const string QueueStatusText = "License unavailable; try Widevine DRM"; + public const string QueueStatusText = "Widevine enabled (re-login needed)"; /// One line for the per-book process log in the queue UI. - public static string BuildLogSummary(string bookTitleWithSubtitle) - => WidevineRecommendation.BuildLogSummary(bookTitleWithSubtitle); + public static string BuildLogSummary(string bookTitleWithSubtitle, string? maskedAccount = null) + => WidevineRecommendation.BuildLogSummary(bookTitleWithSubtitle, maskedAccount); - /// Shown once per queue run when the pattern is detected and Widevine is off. + /// Shown once per queue run when the pattern is detected and Widevine was enabled. public static string BuildDialogBody(string bookTitleWithSubtitle) => $""" Libation could not get a download license for {bookTitleWithSubtitle} using the standard (ADRM) format. - This is uncommon. A small number of titles — including some Audible Plus catalog books — only deliver when Widevine DRM is enabled. Enabling it has fixed this for other users with the same error. + This title delivers only via Widevine DRM. Libation has automatically enabled Widevine DRM in Settings and marked your account for a fresh sign-in to obtain Widevine credentials. - Try Settings > Audio File Options > Use Widevine DRM, then log into your accounts again when prompted and liberate this title again. + Please sign into your account when prompted, then liberate this title again. - If it still fails, open an issue on Libation's GitHub and include your logs. + (All of your account settings and marketplaces are preserved.) """; } diff --git a/Source/LibationWinForms/Dialogs/AccountsDialog.Designer.cs b/Source/LibationWinForms/Dialogs/AccountsDialog.Designer.cs index d84cec88..d90305f8 100644 --- a/Source/LibationWinForms/Dialogs/AccountsDialog.Designer.cs +++ b/Source/LibationWinForms/Dialogs/AccountsDialog.Designer.cs @@ -34,6 +34,7 @@ namespace LibationWinForms.Dialogs this.DeleteAccount = new DeleteColumn(); this.ExportAccount = new ExportColumn(); this.LibraryScan = new System.Windows.Forms.DataGridViewCheckBoxColumn(); + this.SignedIn = new System.Windows.Forms.DataGridViewCheckBoxColumn(); this.AccountId = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Locale = new LocaleColumn(); this.Marketplaces = new MarketplacesColumn(); @@ -78,6 +79,7 @@ namespace LibationWinForms.Dialogs this.DeleteAccount, this.ExportAccount, this.LibraryScan, + this.SignedIn, this.AccountId, this.Locale, this.Marketplaces, @@ -112,6 +114,14 @@ namespace LibationWinForms.Dialogs this.LibraryScan.Name = "LibraryScan"; this.LibraryScan.Width = 94; // + // SignedIn + // + this.SignedIn.HeaderText = "Signed in?"; + this.SignedIn.Name = "SignedIn"; + this.SignedIn.Resizable = System.Windows.Forms.DataGridViewTriState.True; + this.SignedIn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic; + this.SignedIn.Width = 83; + // // AccountId // this.AccountId.HeaderText = "Audible email/login"; @@ -177,6 +187,7 @@ namespace LibationWinForms.Dialogs private DeleteColumn DeleteAccount; private ExportColumn ExportAccount; private System.Windows.Forms.DataGridViewCheckBoxColumn LibraryScan; + private System.Windows.Forms.DataGridViewCheckBoxColumn SignedIn; private System.Windows.Forms.DataGridViewTextBoxColumn AccountId; private LocaleColumn Locale; private MarketplacesColumn Marketplaces; diff --git a/Source/LibationWinForms/Dialogs/AccountsDialog.cs b/Source/LibationWinForms/Dialogs/AccountsDialog.cs index 1f4e65e3..37611789 100644 --- a/Source/LibationWinForms/Dialogs/AccountsDialog.cs +++ b/Source/LibationWinForms/Dialogs/AccountsDialog.cs @@ -16,6 +16,7 @@ public partial class AccountsDialog : Form private const string COL_Delete = nameof(DeleteAccount); private const string COL_Export = nameof(ExportAccount); private const string COL_LibraryScan = nameof(LibraryScan); + private const string COL_SignedIn = nameof(SignedIn); private const string COL_AccountId = nameof(AccountId); private const string COL_AccountName = nameof(AccountName); private const string COL_Locale = nameof(Locale); @@ -87,11 +88,13 @@ public partial class AccountsDialog : Form private void AddAccountToGrid(Account account) { var additional = account.AdditionalLocales.Select(l => l.Name).ToList(); + bool signedIn = account.IdentityTokens?.IsValid == true && !account.RequiresReRegistration; var row = dataGridView1.Rows.Add( "X", "Export", account.LibraryScan, + signedIn, account.AccountId, account.Locale?.Name ?? "", MarketplacesUi.ButtonText(additional.Count + 1), @@ -108,6 +111,8 @@ public partial class AccountsDialog : Form { e.Row.Cells[COL_Delete].Value = "X"; e.Row.Cells[COL_LibraryScan].Value = true; + e.Row.Cells[COL_SignedIn].Value = false; + e.Row.Cells[COL_SignedIn].ReadOnly = true; e.Row.Cells[COL_Export].ReadOnly = true; e.Row.Cells[COL_Marketplaces].Value = MarketplacesUi.ButtonText(1); e.Row.Cells[COL_Marketplaces].ReadOnly = true; @@ -130,7 +135,7 @@ public partial class AccountsDialog : Form return; var colName = dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name; // combo and checkbox do not commit until leave-cell unless we force it here - if (colName is COL_Locale or COL_LibraryScan) + if (colName is COL_Locale or COL_LibraryScan or COL_SignedIn) dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit); } @@ -161,6 +166,16 @@ public partial class AccountsDialog : Form ? "Export account authorization to audible-cli" : "Authenticate this account (e.g. library scan) before exporting to audible-cli."; + if (dataGridView1.Columns.Contains(COL_SignedIn)) + { + row.Cells[COL_SignedIn].ReadOnly = !canExport; + if (!canExport) + row.Cells[COL_SignedIn].Value = false; + row.Cells[COL_SignedIn].ToolTipText = canExport + ? "Uncheck to require a fresh sign-in and device registration on the next scan or liberate." + : "Account has not been authenticated yet. Run a scan to sign in."; + } + if (!dataGridView1.Columns.Contains(COL_Marketplaces)) return; @@ -230,6 +245,7 @@ public partial class AccountsDialog : Form string? AccountName, string LocaleName, bool LibraryScan, + bool SignedIn, IReadOnlyList AdditionalLocaleNames); /// Opens the marketplaces dialog for one row and takes the result back into the row. @@ -331,6 +347,15 @@ public partial class AccountsDialog : Form ? $"{dto.AccountId} - {dto.LocaleName}" : dto.AccountName.Trim(); + if (!dto.SignedIn && acct.IdentityTokens?.IsValid == true) + { + acct.RequiresReRegistration = true; + } + else if (dto.SignedIn && acct.RequiresReRegistration) + { + acct.RequiresReRegistration = false; + } + // drop every marketplace before assigning any, so that moving one from one account to another in a // single sitting cannot trip the "no two accounts scan one marketplace" rule halfway through acct.SetAdditionalMarketplaces([]); @@ -367,11 +392,14 @@ public partial class AccountsDialog : Form private static IReadOnlyList GetAdditionalLocaleNames(DataGridViewRow row) => row.Tag as List ?? []; + private static bool? GetSignedIn(DataGridViewRow row) + => row.Cells[COL_SignedIn]?.Value as bool?; + private static AccountDto? RowToAccountDto(DataGridViewRow row) => GetAccountId(row) is string accountId && GetLocale(row) is string localeName && GetLibraryScan(row) is bool libraryScan - ? new AccountDto(accountId, GetAccountName(row), localeName, libraryScan, GetAdditionalLocaleNames(row)) + ? new AccountDto(accountId, GetAccountName(row), localeName, libraryScan, GetSignedIn(row) ?? false, GetAdditionalLocaleNames(row)) : null; private string GetAudibleCliAppDataPath() diff --git a/Source/LibationWinForms/Dialogs/FindBetterQualityBooksDialog.cs b/Source/LibationWinForms/Dialogs/FindBetterQualityBooksDialog.cs index 40519449..f55e7c0c 100644 --- a/Source/LibationWinForms/Dialogs/FindBetterQualityBooksDialog.cs +++ b/Source/LibationWinForms/Dialogs/FindBetterQualityBooksDialog.cs @@ -154,7 +154,11 @@ public partial class FindBetterQualityBooksDialog : Form btnMarkBooks.Enabled = false; try { - await VM.MarkBooksAsync(); + var result = await VM.MarkBooksAsync(); + if (result.GetSummaryMessage() is string message) + { + MessageBox.Show(this, message, "Books Marked for Download", MessageBoxButtons.OK, MessageBoxIcon.Information); + } } catch (Exception ex) { diff --git a/Source/LibationWinForms/Dialogs/SettingsDialog.AudioSettings.cs b/Source/LibationWinForms/Dialogs/SettingsDialog.AudioSettings.cs index 492ccca7..8a1726e7 100644 --- a/Source/LibationWinForms/Dialogs/SettingsDialog.AudioSettings.cs +++ b/Source/LibationWinForms/Dialogs/SettingsDialog.AudioSettings.cs @@ -1,4 +1,4 @@ -using AudibleUtilities; +using AudibleUtilities; using LibationFileManager; using LibationFileManager.Templates; using LibationUiBase; @@ -72,7 +72,9 @@ partial class SettingsDialog downloadCoverArtCbox.Checked = config.DownloadCoverArt; downloadClipsBookmarksCbox.Checked = config.DownloadClipsBookmarks; fileDownloadQualityCb.SelectedItem = config.FileDownloadQuality; + useWidevineCbox.CheckedChanged -= useWidevineCbox_CheckedChanged; useWidevineCbox.Checked = config.UseWidevine; + useWidevineCbox.CheckedChanged += useWidevineCbox_CheckedChanged; request_xHE_AAC_Cbox.Checked = config.Request_xHE_AAC; clipsBookmarksFormatCb.SelectedItem = config.ClipsBookmarksFileFormat; @@ -191,40 +193,34 @@ partial class SettingsDialog } } - private void useWidevineCbox_CheckedChanged(object sender, EventArgs e) + private void useWidevineCbox_CheckedChanged(object? sender, EventArgs e) { if (useWidevineCbox.Checked) { using var accounts = AudibleApiStorage.GetAccountsSettingsPersister(); - if (!accounts.AccountsSettings.Accounts.All(a => a.IdentityTokens?.DeviceType == AudibleApi.Resources.DeviceType)) + if (accounts.AccountsSettings.Accounts.Count > 0) { var choice = MessageBox.Show(this, - "In order to enable widevine content, Libation will need to log into your accounts again.\r\n\r\n" + - "Do you want Libation to clear your current account settings and prompt you to login before the next download?", - "Widevine Content Unavailable", + ThrottledDeviceRecovery.WidevinePromptMessage, + ThrottledDeviceRecovery.WidevinePromptTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question, - MessageBoxDefaultButton.Button2); + MessageBoxDefaultButton.Button1); if (choice == DialogResult.Yes) { - foreach (var account in accounts.AccountsSettings.Accounts.ToArray()) - { - if (account.Locale is not null && account.IdentityTokens?.DeviceType != AudibleApi.Resources.DeviceType) - { - accounts.AccountsSettings.Delete(account); - var acc = accounts.AccountsSettings.Upsert(account.AccountId, account.Locale.Name); - acc.AccountName = account.AccountName; - } - } - + ThrottledDeviceRecovery.MarkAllAccountsForWidevine(accounts.AccountsSettings, Configuration.Instance); return; } useWidevineCbox.Checked = false; return; } + else + { + Configuration.Instance.DeviceRegistrationKind = AudibleApi.DeviceRegistrationKind.CurrentAndroid; + } } else { diff --git a/Source/_Tests/AudibleUtilities.Tests/AccountCredentialStatusTests.cs b/Source/_Tests/AudibleUtilities.Tests/AccountCredentialStatusTests.cs index e604e41c..b093091f 100644 --- a/Source/_Tests/AudibleUtilities.Tests/AccountCredentialStatusTests.cs +++ b/Source/_Tests/AudibleUtilities.Tests/AccountCredentialStatusTests.cs @@ -53,6 +53,14 @@ public class AccountCredentialStatusTests public void a_registered_account_does_not_look_like_missing_credentials() => AccountCredentialStatus.LooksLikeMissingCredentials(registeredAccount()).Should().BeFalse(); + [TestMethod] + public void an_account_requiring_re_registration_looks_like_missing_credentials() + { + var account = registeredAccount(); + account.RequiresReRegistration = true; + AccountCredentialStatus.LooksLikeMissingCredentials(account).Should().BeTrue(); + } + [TestMethod] public void the_label_pairs_a_friendly_name_with_the_id() => AccountCredentialStatus.FormatAccountLabel(new Account("user@example.com") { AccountName = "Jade" }) diff --git a/Source/_Tests/AudibleUtilities.Tests/AccountTests.cs b/Source/_Tests/AudibleUtilities.Tests/AccountTests.cs index 09f95acb..bbab1f38 100644 --- a/Source/_Tests/AudibleUtilities.Tests/AccountTests.cs +++ b/Source/_Tests/AudibleUtilities.Tests/AccountTests.cs @@ -1,4 +1,4 @@ -using AssertionHelper; +using AssertionHelper; using Dinah.Core.Security; using AudibleApi; using AudibleApi.Authorization; @@ -1135,6 +1135,30 @@ public class SerializedShape : AccountsTestBase .Values().Should().BeEquivalentTo(["us"]); } + [TestMethod] + public void requires_re_registration_is_written_only_when_true() + { + var settings = new AccountsSettings(); + var account = new Account("user@example.com") + { + AccountName = "Main", + IdentityTokens = new Identity(Localization.Get("ca")) + }; + settings.Add(account); + + ((JObject)JObject.Parse(settings.ToJson())["Accounts"]![0]!) + .ContainsKey(nameof(Account.RequiresReRegistration)).Should().BeFalse(); + + account.RequiresReRegistration = true; + + var parsed = JObject.Parse(settings.ToJson())["Accounts"]![0]![nameof(Account.RequiresReRegistration)]!; + parsed.Value().Should().BeTrue(); + + var reloaded = AccountsSettings.FromJson(settings.ToJson()); + reloaded.BeNotNull(); + reloaded.Accounts[0].RequiresReRegistration.Should().BeTrue(); + } + [TestMethod] public void a_stray_property_from_an_older_file_is_dropped_on_the_next_save() { diff --git a/Source/_Tests/AudibleUtilities.Tests/ThrottledDeviceRecoveryTests.cs b/Source/_Tests/AudibleUtilities.Tests/ThrottledDeviceRecoveryTests.cs new file mode 100644 index 00000000..245b7109 --- /dev/null +++ b/Source/_Tests/AudibleUtilities.Tests/ThrottledDeviceRecoveryTests.cs @@ -0,0 +1,350 @@ +using AssertionHelper; +using AudibleApi; +using AudibleApi.Authorization; +using AudibleApi.Common; +using AudibleApi.Cryptography; +using AudibleUtilities; +using Dinah.Core.Security; +using LibationFileManager; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace AudibleUtilities.Tests; + +[TestClass] +[DoNotParallelize] +public class ThrottledDeviceRecoveryTests +{ + private const string SamplePrivateKey = @" +-----BEGIN RSA PRIVATE KEY----- +MIIEpgIBAAKCAQEA5nPbGSVDmlEH2tJa6kz/P2HI8IeirhfPHdmi+X/nsb9i3WNf +tmEdZxfK26IValQDXvBH17a1gr0HD6pYse1XsV2w0HxiW1RW+ZnjL8/fzPdkSOb+ +4xKlqRopCueBSdDGgAF06spZ3IeHLfEFOJX4dO1Y73pFBUkA0k53LT12L2Tjay/r +buZHJqIzxmwja7/nkiWL0Xo7UySHtQACYsKEatu6yHBS+cPTlGR/qeUpeJTHwDLP +7ZQ7kWzJGY1mfInYekjlZLsMsWswso3pg1vPyHgxzM2BWhY8m6mlXQ9G/USxBTib +MNuMtpR73XsgamneFCc+Uv1cxw7ofZ41YOOAbQIDAQABAoIBAQDIre8HkKm0Aggj +B7df/TjxCsgenR6PF/Cmf9UqC7XJ1W3UeCrq+NrP4aonZJfdhdeBnyAQuuyJMu6p +N6ARISuSKpJEm2xTN7idluJ9yjmLlYtg6LbhKmXUQhGniz3M999DrQERTLDAF80h +tpbjVcWMnPsrX4AnQBFVEjs5zCHU1hD+X463EmUHBWyT975jbZ8Fy7/fTzkdzLnn +qE5lROALr2MCAAwQRFbRE6dd52vnXaBrVcAtRzjATts3WG3+SNi2Fm/OrYqQcY9e +lBexNviT8VcldOAMrO10E2u0d+tvxFzwB3ABMvaVamrEZky4XSfB6aLzpD0JJj1s +UHnIiVwJAoGBAPl8nLll/J9rud/N2HiAX2YkP0MC0HW4yM3KxLtXKyXrP5qBpaci +wTDUmSWEEE3GUJMM1Z4d9tl9Lz2MhU2KqkEvLI3kQ7aUu33PYUBGMVcUzhFQ49lU +Nzz8YB183iqo31o/DKk2Cr5gI7SykQZ0gn/urZkEJeErLzlhPXcyeY5jAoGBAOx4 +CGucVdv5MbdXZP8jVzxuvUlSp7BIQJ2phQXDFBNApFKnZn7yBYBx7dqzleymGm+R +INZAurg3SNw4nvbQc3Z2dJ8I+n5ErjFCKp1IedVxx1eMEfecTwrQZuUwLISIyjqF +czSJNwcNqzCx67z397/Cg5K/0pu6uIe0r7xozcbvAoGBAOOvZ9CDVPOg+rdXQvFm +Jqou9lUPonNtOkUlgjl+qfAnK5q0KxvHSgxoWYO1bLOuAybQlbuBmSCPcKd5MMa9 +f/eRN9YetfVQ83Mz6YshBDJ22EFRUz+p7eeIY6dFp/PCvmO8Gq/qlA996dglBtmf +RuG+T0vQT0mZgbWaGuBHfkwFAoGBAMOLg1MRxgKRMKavk6pU3EfyP3+J5XemWCDI +1WLtbgV5uClNmzmxBBGypQHs7jbzKPtHpULn5kB+HzdVb0clG8ZDsK7u6s5OF0pO +sBS+oVl7rF/eSeFcFhUYP26ZhsbWo3z/bERuj926VO2AxDPRTsP5o3pQPGZhY0V9 +irGgbUJrAoGBAOseS3J4BqYM4R3Hr7cRAhvzSjIkeTcDF1zTOa4FZDHBxZ6g2PNq +8ekhtfn1zPczsPTF1vNuqEISKLxaPkVPiw0mtaZQjVwpF/IOxMNjWVLp6oJf8Mm2 +BxlXqPnQ4mG66oqSFQgDEmFdMhRb2of6xL1gYYL62C80G2T7QtmPfSab +-----END RSA PRIVATE KEY----- +"; + + private const string SampleAccessToken = "Atna|_CHAR_ACCESS_"; + private const string SampleRefreshToken = "Atnr|_CHAR_REFRESH_"; + private const string SampleAdpToken = "{enc:abcdefg}{key:1234}{iv:56789}{name:QURQVG9rZW5FbmNyeXB0aW9uS2V5}{serial:Mg==}"; + + [TestInitialize] + public void Initialize() => Configuration.CreateMockInstance(); + + [TestCleanup] + public void Cleanup() => Configuration.RestoreSingletonInstance(); + + private static Identity CreateIdentity(string deviceType, string? serialNumber) + { + var identity = new Identity(Localization.Get("us")); + identity.Update( + new PrivateKey(SamplePrivateKey), + new AdpToken(SampleAdpToken), + new AccessToken(SampleAccessToken, DateTime.UtcNow.AddHours(1)), + new RefreshToken(SampleRefreshToken), + new List> { new("session-id", new SecretString("cookie-val")) }, + deviceSerialNumber: serialNumber, + deviceType: deviceType, + amazonAccountId: "amzn-123", + deviceName: "dev-name", + storeAuthenticationCookie: new SecretString("store-cookie")); + return identity; + } + + private static ContentLicenseDeniedException CreateDeniedException(bool isThrottled) + { + var rejectionReason = isThrottled ? RejectionReason.CustomerThrottled : RejectionReason.GenericError; + var license = new ContentLicense + { + Asin = "B002V5B8OY", + StatusCode = "Denied", + LicenseDenialReasons = + [ + new LicenseDenialReason + { + ValidationType = "Ownership", + RejectionReason = rejectionReason, + Message = isThrottled ? "Customer is throttled" : "Denied" + } + ] + }; + return new ContentLicenseDeniedException(new Uri("https://audible.com/licenserequest"), license); + } + + [TestMethod] + public void HasObsoleteDeviceRegistration_returns_false_for_null_tokens() + { + var account = new Account("user@example.com"); + account.HasObsoleteDeviceRegistration().Should().BeFalse(); + } + + [TestMethod] + public void HasObsoleteDeviceRegistration_detects_non_android_device_types() + { + var iphoneAccount = new Account("iphone@example.com") + { + IdentityTokens = CreateIdentity("A2CZJZGLK2JJVM", "0123456789abcdef0123") + }; + iphoneAccount.HasObsoleteDeviceRegistration().Should().BeTrue(); + + var retailAndroidAccount = new Account("retail@example.com") + { + IdentityTokens = CreateIdentity("A2L54JJ0LGZZ85", "0123456789abcdef0123") + }; + retailAndroidAccount.HasObsoleteDeviceRegistration().Should().BeTrue(); + } + + [TestMethod] + public void HasObsoleteDeviceRegistration_detects_non_20_char_or_invalid_serials() + { + // Old 32-character hex serial + var oldHexAccount = new Account("old32@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "0123456789abcdef0123456789abcdef") + }; + oldHexAccount.HasObsoleteDeviceRegistration().Should().BeTrue(); + + // Old 16-character hex serial + var old16Account = new Account("old16@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "0123456789abcdef") + }; + old16Account.HasObsoleteDeviceRegistration().Should().BeTrue(); + + // Old 40-character hex serial + var old40Account = new Account("old40@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "0123456789abcdef0123456789abcdef01234567") + }; + old40Account.HasObsoleteDeviceRegistration().Should().BeTrue(); + + // Non-hex serial + var nonHexAccount = new Account("nonhex@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "not-a-hex-serial-here") + }; + nonHexAccount.HasObsoleteDeviceRegistration().Should().BeTrue(); + + // Empty serial + var emptySerialAccount = new Account("empty@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "") + }; + emptySerialAccount.HasObsoleteDeviceRegistration().Should().BeTrue(); + } + + [TestMethod] + public void HasObsoleteDeviceRegistration_returns_false_for_valid_current_android() + { + var modernAccount = new Account("modern@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "0123456789abcdef0123") + }; + modernAccount.HasObsoleteDeviceRegistration().Should().BeFalse(); + } + + [TestMethod] + public void ShouldRecover_returns_false_when_not_CustomerThrottled() + { + var ex = CreateDeniedException(isThrottled: false); + var account = new Account("user@example.com") + { + IdentityTokens = CreateIdentity("A2CZJZGLK2JJVM", "0123456789abcdef0123") + }; + Configuration.Instance.UseWidevine = false; + + ThrottledDeviceRecovery.ShouldRecover(ex, account, Configuration.Instance).Should().BeFalse(); + } + + [TestMethod] + public void ShouldRecover_returns_true_when_throttled_and_widevine_disabled() + { + var ex = CreateDeniedException(isThrottled: true); + var modernAccount = new Account("user@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "0123456789abcdef0123") + }; + Configuration.Instance.UseWidevine = false; + Configuration.Instance.DeviceRegistrationKind = DeviceRegistrationKind.CurrentAndroid; + + ThrottledDeviceRecovery.ShouldRecover(ex, modernAccount, Configuration.Instance).Should().BeTrue(); + } + + [TestMethod] + public void ShouldRecover_returns_true_when_throttled_and_device_profile_is_iphone() + { + var ex = CreateDeniedException(isThrottled: true); + var modernAccount = new Account("user@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "0123456789abcdef0123") + }; + Configuration.Instance.UseWidevine = true; + Configuration.Instance.DeviceRegistrationKind = DeviceRegistrationKind.Mkb79IPhone; + + ThrottledDeviceRecovery.ShouldRecover(ex, modernAccount, Configuration.Instance).Should().BeTrue(); + } + + [TestMethod] + public void ShouldRecover_returns_true_when_throttled_and_account_has_obsolete_registration() + { + var ex = CreateDeniedException(isThrottled: true); + var obsoleteAccount = new Account("user@example.com") + { + IdentityTokens = CreateIdentity("A2CZJZGLK2JJVM", "0123456789abcdef0123") + }; + Configuration.Instance.UseWidevine = true; + Configuration.Instance.DeviceRegistrationKind = DeviceRegistrationKind.CurrentAndroid; + + ThrottledDeviceRecovery.ShouldRecover(ex, obsoleteAccount, Configuration.Instance).Should().BeTrue(); + } + + [TestMethod] + public void ShouldRecover_returns_false_for_throttled_modern_widevine_account() + { + // True rate-limit on a modern account should not trigger registration thunking + var ex = CreateDeniedException(isThrottled: true); + var modernAccount = new Account("user@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "0123456789abcdef0123") + }; + Configuration.Instance.UseWidevine = true; + Configuration.Instance.DeviceRegistrationKind = DeviceRegistrationKind.CurrentAndroid; + + ThrottledDeviceRecovery.ShouldRecover(ex, modernAccount, Configuration.Instance).Should().BeFalse(); + } + + [TestMethod] + public void ApplyRecovery_when_widevine_disabled_thunks_settings_and_marks_all_accounts() + { + var config = Configuration.Instance; + config.UseWidevine = false; + config.DeviceRegistrationKind = DeviceRegistrationKind.Mkb79IPhone; + + var settings = new AccountsSettings(); + var primary = new Account("primary@example.com") + { + IdentityTokens = CreateIdentity("A2CZJZGLK2JJVM", "0123456789abcdef0123") + }; + var second = new Account("second@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "0123456789abcdef0123") + }; + settings.Add(primary); + settings.Add(second); + + var result = ThrottledDeviceRecovery.ApplyRecovery(settings, config, primary); + + result.WidevineEnabled.Should().BeTrue(); + result.DeviceRegistrationUpdated.Should().BeTrue(); + config.UseWidevine.Should().BeTrue(); + Assert.AreEqual(DeviceRegistrationKind.CurrentAndroid, config.DeviceRegistrationKind); + + // When Widevine is changed from disabled to enabled, ALL accounts must re-login + primary.RequiresReRegistration.Should().BeTrue(); + second.RequiresReRegistration.Should().BeTrue(); + CollectionAssert.Contains(result.MarkedAccounts.ToList(), primary); + CollectionAssert.Contains(result.MarkedAccounts.ToList(), second); + } + + [TestMethod] + public void ApplyRecovery_when_widevine_already_enabled_only_marks_throttled_and_obsolete_accounts() + { + var config = Configuration.Instance; + config.UseWidevine = true; + config.DeviceRegistrationKind = DeviceRegistrationKind.CurrentAndroid; + + var settings = new AccountsSettings(); + var throttled = new Account("throttled@example.com") + { + IdentityTokens = CreateIdentity("A2CZJZGLK2JJVM", "0123456789abcdef0123") + }; + var otherObsolete = new Account("other_old@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "old-32-char-serial-0123456789012") + }; + var modern = new Account("modern@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "0123456789abcdef0123") + }; + settings.Add(throttled); + settings.Add(otherObsolete); + settings.Add(modern); + + var result = ThrottledDeviceRecovery.ApplyRecovery(settings, config, throttled); + + result.WidevineEnabled.Should().BeFalse(); + result.DeviceRegistrationUpdated.Should().BeFalse(); + + throttled.RequiresReRegistration.Should().BeTrue(); + otherObsolete.RequiresReRegistration.Should().BeTrue(); + modern.RequiresReRegistration.Should().BeFalse(); + + CollectionAssert.Contains(result.MarkedAccounts.ToList(), throttled); + CollectionAssert.Contains(result.MarkedAccounts.ToList(), otherObsolete); + Assert.IsFalse(result.MarkedAccounts.Contains(modern)); + } + + [TestMethod] + public void MarkAllAccountsForWidevine_marks_all_accounts_and_sets_CurrentAndroid() + { + var config = Configuration.Instance; + config.DeviceRegistrationKind = DeviceRegistrationKind.Mkb79IPhone; + + var settings = new AccountsSettings(); + var acc1 = new Account("one@example.com"); + var acc2 = new Account("two@example.com"); + settings.Add(acc1); + settings.Add(acc2); + + ThrottledDeviceRecovery.MarkAllAccountsForWidevine(settings, config); + + Assert.AreEqual(DeviceRegistrationKind.CurrentAndroid, config.DeviceRegistrationKind); + acc1.RequiresReRegistration.Should().BeTrue(); + acc2.RequiresReRegistration.Should().BeTrue(); + } + + [TestMethod] + public void MarkObsoleteAccounts_only_marks_accounts_with_obsolete_registrations() + { + var settings = new AccountsSettings(); + var obsolete = new Account("obsolete@example.com") + { + IdentityTokens = CreateIdentity("A2CZJZGLK2JJVM", "0123456789abcdef0123") + }; + var modern = new Account("modern@example.com") + { + IdentityTokens = CreateIdentity(AudibleApi.Resources.DeviceType, "0123456789abcdef0123") + }; + settings.Add(obsolete); + settings.Add(modern); + + var marked = ThrottledDeviceRecovery.MarkObsoleteAccounts(settings); + + marked.Should().Be(1); + obsolete.RequiresReRegistration.Should().BeTrue(); + modern.RequiresReRegistration.Should().BeFalse(); + } +} diff --git a/Source/_Tests/FileLiberator.Tests/WidevineRecommendationTests.cs b/Source/_Tests/FileLiberator.Tests/WidevineRecommendationTests.cs index 5a8d9752..47617084 100644 --- a/Source/_Tests/FileLiberator.Tests/WidevineRecommendationTests.cs +++ b/Source/_Tests/FileLiberator.Tests/WidevineRecommendationTests.cs @@ -79,4 +79,58 @@ public class WidevineRecommendationTests Assert.IsFalse(WidevineRecommendation.ShouldRecommendWidevine(ex, config)); } + + [TestMethod] + public void IsAaxFallbackMissingCodecError_matches_codec_missing_errors() + { + var ex1 = new System.ApplicationException("Book has no codec specified. Cannot continue with download. Full book data:\r\n[1782836926] Together"); + Assert.IsTrue(WidevineRecommendation.IsAaxFallbackMissingCodecError(ex1)); + + var ex2 = new System.ApplicationException("Book has no available codecs. Cannot continue with download."); + Assert.IsTrue(WidevineRecommendation.IsAaxFallbackMissingCodecError(ex2)); + + var wrapped = new System.InvalidOperationException("Outer wrapper", ex1); + Assert.IsTrue(WidevineRecommendation.IsAaxFallbackMissingCodecError(wrapped)); + } + + [TestMethod] + public void IsAaxFallbackMissingCodecError_rejects_unrelated_errors() + { + var ex = new System.ApplicationException("Some other download error occurred."); + Assert.IsFalse(WidevineRecommendation.IsAaxFallbackMissingCodecError(ex)); + } + + [TestMethod] + public void ShouldRecommendWidevine_matches_aax_fallback_missing_codec_when_widevine_disabled() + { + var ex = new System.ApplicationException("Book has no codec specified. Cannot continue with download. Full book data:\r\n[1409167399] Starsight"); + var config = Configuration.CreateMockInstance(); + config.UseWidevine = false; + + Assert.IsTrue(WidevineRecommendation.ShouldRecommendWidevine(ex, config)); + } + + [TestMethod] + public void ShouldRecommendWidevine_rejects_aax_fallback_missing_codec_when_widevine_enabled() + { + var ex = new System.ApplicationException("Book has no codec specified. Cannot continue with download. Full book data:\r\n[1409167399] Starsight"); + var config = Configuration.CreateMockInstance(); + config.UseWidevine = true; + + Assert.IsFalse(WidevineRecommendation.ShouldRecommendWidevine(ex, config)); + } + + [TestMethod] + public void BuildLogSummary_includes_account_when_provided() + { + var summaryWithAccount = WidevineRecommendation.BuildLogSummary("Starsight", "user@example.com"); + Assert.IsTrue(summaryWithAccount.Contains("Starsight")); + Assert.IsTrue(summaryWithAccount.Contains("user@example.com")); + Assert.IsTrue(summaryWithAccount.Contains("enabled Widevine DRM")); + + var summaryWithoutAccount = WidevineRecommendation.BuildLogSummary("Starsight"); + Assert.IsTrue(summaryWithoutAccount.Contains("Starsight")); + Assert.IsFalse(summaryWithoutAccount.Contains("for account")); + Assert.IsTrue(summaryWithoutAccount.Contains("enabled Widevine DRM")); + } } diff --git a/Source/_Tests/LibationCli.Tests/ContentLicenseDeniedCliSummaryTests.cs b/Source/_Tests/LibationCli.Tests/ContentLicenseDeniedCliSummaryTests.cs index 0234532d..929c652a 100644 --- a/Source/_Tests/LibationCli.Tests/ContentLicenseDeniedCliSummaryTests.cs +++ b/Source/_Tests/LibationCli.Tests/ContentLicenseDeniedCliSummaryTests.cs @@ -43,7 +43,6 @@ public class ContentLicenseDeniedCliSummaryTests StringAssert.Contains(lines[0], "throttled"); Assert.IsTrue(lines.Any(l => l.Contains("24 to 48 hours"))); Assert.IsTrue(lines.Any(l => l.Contains("login-external --account", StringComparison.Ordinal))); - Assert.IsTrue(lines.Any(l => l.Contains("AccountsSettings.json", StringComparison.Ordinal))); Assert.IsFalse(lines.Any(l => l.Contains("Settings > Accounts"))); Assert.IsFalse(lines.Any(l => l.Contains("not a Libation bug"))); Assert.IsTrue(lines.Any(l => l.StartsWith("Ownership:", StringComparison.Ordinal))); @@ -57,10 +56,9 @@ public class ContentLicenseDeniedCliSummaryTests { var ex = Denied(("Ownership", RejectionReason.CustomerThrottled, "throttled")); var body = string.Join("\n", ContentLicenseDeniedCliSummary.Lines(ex, Localization.Get("uk"), status)); - StringAssert.Contains(body, "https://www.amazon.co.uk/"); - StringAssert.Contains(body, "regional link is unverified"); + StringAssert.Contains(body, "--locale uk"); Assert.AreEqual(upgrade, body.Contains(AppScaffolding.LicenseRecoveryGuidance.ReleasesUrl)); - Assert.IsTrue(body.IndexOf("Deregister") < body.IndexOf("24 to 48 hours")); + Assert.IsTrue(body.IndexOf("login-external") < body.IndexOf("24 to 48 hours")); } [TestMethod] @@ -71,8 +69,7 @@ public class ContentLicenseDeniedCliSummaryTests var ex = Denied(("Ownership", RejectionReason.CustomerThrottled, "throttled")); var body = string.Join("\n", ContentLicenseDeniedCliSummary.Lines(ex, Localization.Get("uk"), AppScaffolding.VersionCheckOutcome.UpToDate, hasAdditional)); - Assert.AreEqual(hasAdditional, body.Contains("AdditionalLocaleNames")); - Assert.AreEqual(hasAdditional, body.Contains("Also scans")); + Assert.AreEqual(hasAdditional, body.Contains("additional marketplaces")); } [TestMethod] diff --git a/Source/_Tests/LibationCli.Tests/LoginExternalOptionsTests.cs b/Source/_Tests/LibationCli.Tests/LoginExternalOptionsTests.cs index 5dd8f2af..8eb31ccd 100644 --- a/Source/_Tests/LibationCli.Tests/LoginExternalOptionsTests.cs +++ b/Source/_Tests/LibationCli.Tests/LoginExternalOptionsTests.cs @@ -45,4 +45,23 @@ public class LoginExternalOptionsTests StringAssert.Contains(error, "WindowsPhone"); StringAssert.Contains(error, "CurrentAndroid"); } + + [TestMethod] + public void NeedsReRegistration_returns_true_when_RequiresReRegistration_is_true() + { + var account = new AudibleUtilities.Account("user@example.com") + { + RequiresReRegistration = true + }; + + Assert.IsTrue(LoginExternalOptions.NeedsReRegistration(account)); + } + + [TestMethod] + public void NeedsReRegistration_returns_false_for_normal_unmarked_account() + { + var account = new AudibleUtilities.Account("user@example.com"); + + Assert.IsFalse(LoginExternalOptions.NeedsReRegistration(account)); + } } diff --git a/Source/_Tests/LibationUiBase.Tests/ContentLicenseDeniedUserMessageTests.cs b/Source/_Tests/LibationUiBase.Tests/ContentLicenseDeniedUserMessageTests.cs index 19b86a59..e7ba1b58 100644 --- a/Source/_Tests/LibationUiBase.Tests/ContentLicenseDeniedUserMessageTests.cs +++ b/Source/_Tests/LibationUiBase.Tests/ContentLicenseDeniedUserMessageTests.cs @@ -23,8 +23,8 @@ public class ContentLicenseDeniedUserMessageTests Assert.IsFalse(body.Contains("not a Libation bug")); Assert.IsFalse(body.Contains("experimental device registration")); Assert.IsFalse(body.Contains("audible-cli")); - Assert.IsTrue(body.IndexOf("Deregister") < body.IndexOf("24 to 48 hours")); - AssertSuggestsRemoveSaveReAdd(body); + Assert.IsTrue(body.IndexOf("Settings > Accounts") < body.IndexOf("24 to 48 hours")); + AssertSuggestsUncheckSaveAndScan(body); } [TestMethod] @@ -39,7 +39,6 @@ public class ContentLicenseDeniedUserMessageTests ContentLicenseDeniedUserMessage.BuildDialogBodyForPlusCatalog("Title", null, status, hasAdditional) }) { Assert.AreEqual(hasAdditional, body.Contains("additional marketplaces")); - Assert.AreEqual(hasAdditional, body.Contains("save both dialogs")); } } @@ -50,7 +49,7 @@ public class ContentLicenseDeniedUserMessageTests StringAssert.Contains(body, "temporary interruption of service"); Assert.IsFalse(body.Contains("account is being throttled", StringComparison.Ordinal)); - AssertSuggestsRemoveSaveReAdd(body); + AssertSuggestsUncheckSaveAndScan(body); } [TestMethod] @@ -60,13 +59,13 @@ public class ContentLicenseDeniedUserMessageTests StringAssert.Contains(body, "Audible Plus catalog"); Assert.IsFalse(body.Contains("account is being throttled", StringComparison.Ordinal)); - AssertSuggestsRemoveSaveReAdd(body); + AssertSuggestsUncheckSaveAndScan(body); } - private static void AssertSuggestsRemoveSaveReAdd(string body) + private static void AssertSuggestsUncheckSaveAndScan(string body) { - StringAssert.Contains(body, "remove the affected account", StringComparison.OrdinalIgnoreCase); - StringAssert.Contains(body, "Save the removal, then close Libation"); - StringAssert.Contains(body, "re-add the account"); + StringAssert.Contains(body, "Settings > Accounts"); + StringAssert.Contains(body, "Signed in?"); + StringAssert.Contains(body, "Scan and sign in"); } } diff --git a/Source/_Tests/LibationUiBase.Tests/FindBetterQualityBooksViewModelTests.cs b/Source/_Tests/LibationUiBase.Tests/FindBetterQualityBooksViewModelTests.cs new file mode 100644 index 00000000..9cb5dfec --- /dev/null +++ b/Source/_Tests/LibationUiBase.Tests/FindBetterQualityBooksViewModelTests.cs @@ -0,0 +1,237 @@ +using AudibleApi; +using AudibleApi.Authorization; +using AudibleApi.Common; +using AudibleApi.Cryptography; +using AudibleUtilities; +using ApplicationServices; +using DataLayer; +using Dinah.Core.Security; +using LibationFileManager; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace LibationUiBase.Tests; + +[TestClass] +[DoNotParallelize] +public class FindBetterQualityBooksViewModelTests +{ + private const string SamplePrivateKey = @" +-----BEGIN RSA PRIVATE KEY----- +MIIEpgIBAAKCAQEA5nPbGSVDmlEH2tJa6kz/P2HI8IeirhfPHdmi+X/nsb9i3WNf +tmEdZxfK26IValQDXvBH17a1gr0HD6pYse1XsV2w0HxiW1RW+ZnjL8/fzPdkSOb+ +4xKlqRopCueBSdDGgAF06spZ3IeHLfEFOJX4dO1Y73pFBUkA0k53LT12L2Tjay/r +buZHJqIzxmwja7/nkiWL0Xo7UySHtQACYsKEatu6yHBS+cPTlGR/qeUpeJTHwDLP +7ZQ7kWzJGY1mfInYekjlZLsMsWswso3pg1vPyHgxzM2BWhY8m6mlXQ9G/USxBTib +MNuMtpR73XsgamneFCc+Uv1cxw7ofZ41YOOAbQIDAQABAoIBAQDIre8HkKm0Aggj +B7df/TjxCsgenR6PF/Cmf9UqC7XJ1W3UeCrq+NrP4aonZJfdhdeBnyAQuuyJMu6p +N6ARISuSKpJEm2xTN7idluJ9yjmLlYtg6LbhKmXUQhGniz3M999DrQERTLDAF80h +tpbjVcWMnPsrX4AnQBFVEjs5zCHU1hD+X463EmUHBWyT975jbZ8Fy7/fTzkdzLnn +qE5lROALr2MCAAwQRFbRE6dd52vnXaBrVcAtRzjATts3WG3+SNi2Fm/OrYqQcY9e +lBexNviT8VcldOAMrO10E2u0d+tvxFzwB3ABMvaVamrEZky4XSfB6aLzpD0JJj1s +UHnIiVwJAoGBAPl8nLll/J9rud/N2HiAX2YkP0MC0HW4yM3KxLtXKyXrP5qBpaci +wTDUmSWEEE3GUJMM1Z4d9tl9Lz2MhU2KqkEvLI3kQ7aUu33PYUBGMVcUzhFQ49lU +Nzz8YB183iqo31o/DKk2Cr5gI7SykQZ0gn/urZkEJeErLzlhPXcyeY5jAoGBAOx4 +CGucVdv5MbdXZP8jVzxuvUlSp7BIQJ2phQXDFBNApFKnZn7yBYBx7dqzleymGm+R +INZAurg3SNw4nvbQc3Z2dJ8I+n5ErjFCKp1IedVxx1eMEfecTwrQZuUwLISIyjqF +czSJNwcNqzCx67z397/Cg5K/0pu6uIe0r7xozcbvAoGBAOOvZ9CDVPOg+rdXQvFm +Jqou9lUPonNtOkUlgjl+qfAnK5q0KxvHSgxoWYO1bLOuAybQlbuBmSCPcKd5MMa9 +f/eRN9YetfVQ83Mz6YshBDJ22EFRUz+p7eeIY6dFp/PCvmO8Gq/qlA996dglBtmf +RuG+T0vQT0mZgbWaGuBHfkwFAoGBAMOLg1MRxgKRMKavk6pU3EfyP3+J5XemWCDI +1WLtbgV5uClNmzmxBBGypQHs7jbzKPtHpULn5kB+HzdVb0clG8ZDsK7u6s5OF0pO +sBS+oVl7rF/eSeFcFhUYP26ZhsbWo3z/bERuj926VO2AxDPRTsP5o3pQPGZhY0V9 +irGgbUJrAoGBAOseS3J4BqYM4R3Hr7cRAhvzSjIkeTcDF1zTOa4FZDHBxZ6g2PNq +8ekhtfn1zPczsPTF1vNuqEISKLxaPkVPiw0mtaZQjVwpF/IOxMNjWVLp6oJf8Mm2 +BxlXqPnQ4mG66oqSFQgDEmFdMhRb2of6xL1gYYL62C80G2T7QtmPfSab +-----END RSA PRIVATE KEY----- +"; + + private const string SampleAccessToken = "Atna|_CHAR_ACCESS_"; + private const string SampleRefreshToken = "Atnr|_CHAR_REFRESH_"; + private const string SampleAdpToken = "{enc:abcdefg}{key:1234}{iv:56789}{name:QURQVG9rZW5FbmNyeXB0aW9uS2V5}{serial:Mg==}"; + + private string tempDir = string.Empty; + + [TestInitialize] + public void Initialize() + { + SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); + tempDir = Path.Combine(Path.GetTempPath(), $"libation-vm-test-{Guid.NewGuid():N}"); + Directory.CreateDirectory(tempDir); + Environment.SetEnvironmentVariable(LibationFiles.LIBATION_FILES_DIR, tempDir); + Configuration.CreateMockInstance(); + } + + [TestCleanup] + public void Cleanup() + { + Configuration.RestoreSingletonInstance(); + Environment.SetEnvironmentVariable(LibationFiles.LIBATION_FILES_DIR, null); + SynchronizationContext.SetSynchronizationContext(null); + try + { + Directory.Delete(tempDir, recursive: true); + } + catch + { + } + } + + private static Identity CreateIdentity(string deviceType, string? serialNumber) + { + var identity = new Identity(Localization.Get("us")); + identity.Update( + new PrivateKey(SamplePrivateKey), + new AdpToken(SampleAdpToken), + new AccessToken(SampleAccessToken, DateTime.UtcNow.AddHours(1)), + new RefreshToken(SampleRefreshToken), + new List> { new("session-id", new SecretString("cookie-val")) }, + deviceSerialNumber: serialNumber, + deviceType: deviceType, + amazonAccountId: "amzn-123", + deviceName: "dev-name", + storeAuthenticationCookie: new SecretString("store-cookie")); + return identity; + } + + private static Account CreateAccount(string email, string serialNumber, string? deviceType = null) + { + return new Account(email) + { + IdentityTokens = CreateIdentity(deviceType ?? AudibleApi.Resources.DeviceType, serialNumber) + }; + } + + private static LibraryBook InsertBook(string title, LiberatedStatus bookStatus = LiberatedStatus.Liberated) + { + var libraryBook = MockLibraryBook.CreateBook(title: title, bookStatus: bookStatus); + + using (var context = DbContexts.GetContext()) + { + context.LibraryBooks.Add(new LibraryBook(libraryBook.Book, libraryBook.DateAdded, libraryBook.Account)); + context.SaveChanges(); + } + + return DbContexts.GetLibraryBook_Flat_NoTracking(libraryBook.Book.AudibleProductId)!; + } + + [TestMethod] + public async Task MarkBooksAsync_NoSignificantBooks_ReturnsZeroAndDoesNotModifyConfig() + { + Configuration.Instance.UseWidevine = false; + Configuration.Instance.Request_xHE_AAC = false; + + var vm = new FindBetterQualityBooksViewModel + { + Books = new List() + }; + + var result = await vm.MarkBooksAsync(); + + Assert.AreEqual(0, result.MarkedCount); + Assert.IsFalse(result.WidevineEnabled); + Assert.IsFalse(result.XHeAacRequested); + Assert.IsFalse(result.AccountsMarkedForReRegistration); + Assert.IsNull(result.GetSummaryMessage()); + + Assert.IsFalse(Configuration.Instance.UseWidevine); + Assert.IsFalse(Configuration.Instance.Request_xHE_AAC); + } + + [TestMethod] + public async Task MarkBooksAsync_SignificantWidevineBooks_EnablesWidevineAndMarksAccounts() + { + Configuration.Instance.UseWidevine = false; + Configuration.Instance.Request_xHE_AAC = false; + AudibleApiStorage.EnsureAccountsSettingsFileExists(); + + var account = CreateAccount("test@example.com", "0123456789abcdef0123"); + using (var persister = AudibleApiStorage.GetAccountsSettingsPersister()) + { + persister.AccountsSettings.Add(account); + } + + var book = InsertBook("High Quality Book"); + var bookVm = new BookDataViewModel(book) + { + Bitrate = 64, + AvailableBitrate = 128, + AvailableCodec = "xHE-AAC" + }; + Assert.IsTrue(bookVm.IsSignificant); + + var vm = new FindBetterQualityBooksViewModel + { + Books = new List { bookVm }, + ScanWidevine = true + }; + + var result = await vm.MarkBooksAsync(); + + Assert.AreEqual(1, result.MarkedCount); + Assert.IsTrue(result.WidevineEnabled); + Assert.IsTrue(result.XHeAacRequested); + Assert.IsTrue(result.AccountsMarkedForReRegistration); + Assert.IsNotNull(result.GetSummaryMessage()); + StringAssert.Contains(result.GetSummaryMessage()!, "Marked 1 book as Download Pending."); + StringAssert.Contains(result.GetSummaryMessage()!, "Libation has automatically configured your download settings"); + + Assert.IsTrue(Configuration.Instance.UseWidevine); + Assert.IsTrue(Configuration.Instance.Request_xHE_AAC); + Assert.AreEqual(DeviceRegistrationKind.CurrentAndroid, Configuration.Instance.DeviceRegistrationKind); + Assert.AreEqual(0, vm.Books.Count); + + using (var persister = AudibleApiStorage.GetAccountsSettingsPersister()) + { + var reloaded = persister.AccountsSettings.Accounts[0]; + Assert.IsTrue(reloaded.RequiresReRegistration); + } + } + + [TestMethod] + public async Task MarkBooksAsync_AlreadyWidevine_OnlyMarksObsoleteAccounts() + { + Configuration.Instance.UseWidevine = true; + Configuration.Instance.Request_xHE_AAC = true; + AudibleApiStorage.EnsureAccountsSettingsFileExists(); + + var obsoleteAccount = CreateAccount("legacy@example.com", "0123456789abcdef"); // 16 hex: obsolete + var modernAccount = CreateAccount("modern@example.com", "0123456789abcdef0123"); // 20 hex: modern + using (var persister = AudibleApiStorage.GetAccountsSettingsPersister()) + { + persister.AccountsSettings.Add(obsoleteAccount); + persister.AccountsSettings.Add(modernAccount); + } + + var book = InsertBook("Another High Quality Book"); + var bookVm = new BookDataViewModel(book) + { + Bitrate = 64, + AvailableBitrate = 128, + AvailableCodec = "xHE-AAC" + }; + + var vm = new FindBetterQualityBooksViewModel + { + Books = new List { bookVm }, + ScanWidevine = true + }; + + var result = await vm.MarkBooksAsync(); + + Assert.AreEqual(1, result.MarkedCount); + Assert.IsFalse(result.WidevineEnabled); // was already true + Assert.IsFalse(result.XHeAacRequested); // was already true + Assert.IsTrue(result.AccountsMarkedForReRegistration); + + using (var persister = AudibleApiStorage.GetAccountsSettingsPersister()) + { + Assert.IsTrue(persister.AccountsSettings.Accounts[0].RequiresReRegistration); + Assert.IsFalse(persister.AccountsSettings.Accounts[1].RequiresReRegistration); + } + } +} diff --git a/Source/_Tests/LibationUiBase.Tests/LicenseRecoveryGuidanceTests.cs b/Source/_Tests/LibationUiBase.Tests/LicenseRecoveryGuidanceTests.cs index c1488f28..6af56425 100644 --- a/Source/_Tests/LibationUiBase.Tests/LicenseRecoveryGuidanceTests.cs +++ b/Source/_Tests/LibationUiBase.Tests/LicenseRecoveryGuidanceTests.cs @@ -12,27 +12,21 @@ namespace LibationUiBase.Tests; public class LicenseRecoveryGuidanceTests { [TestMethod] - [DataRow("us", "com", false)] - [DataRow("uk", "co.uk", true)] - [DataRow("germany", "de", true)] - public void Regional_links_use_locale_metadata_with_non_US_caveat(string name, string domain, bool caveat) + [DataRow("us", "com")] + [DataRow("uk", "co.uk")] + [DataRow("germany", "de")] + public void Regional_device_management_urls_use_locale_metadata(string name, string domain) { var locale = Localization.Get(name); Assert.AreEqual($"https://www.amazon.{domain}/hz/mycd/digital-console/devicedetails?deviceFamily=AUDIBLE_APP", LicenseRecoveryGuidance.DeviceManagementUrl(locale)); - var body = LicenseRecoveryGuidance.BuildSteps(locale, VersionCheckOutcome.UpToDate); - Assert.AreEqual(caveat, body.Contains("regional link is unverified")); - Assert.AreEqual(caveat, body.Contains("Manage Your Content and Devices")); } [TestMethod] - public void Missing_or_empty_locale_uses_labeled_US_link_and_manual_route() + public void Missing_or_empty_locale_uses_fallback_device_management_url() { foreach (var locale in new Locale?[] { null, Locale.Empty }) { - var body = LicenseRecoveryGuidance.BuildSteps(locale, VersionCheckOutcome.UpToDate); - StringAssert.Contains(body, "https://www.amazon.com/"); - StringAssert.Contains(body, "US link; account region is unknown"); - StringAssert.Contains(body, "Manage Your Content and Devices"); + Assert.AreEqual("https://www.amazon.com/hz/mycd/digital-console/devicedetails?deviceFamily=AUDIBLE_APP", LicenseRecoveryGuidance.DeviceManagementUrl(locale)); } } @@ -45,7 +39,7 @@ public class LicenseRecoveryGuidanceTests var body = LicenseRecoveryGuidance.BuildSteps(Localization.Get("us"), status, hasAdditionalMarketplaces: true); Assert.AreEqual(upgrade, body.Contains(LicenseRecoveryGuidance.ReleasesUrl)); Assert.AreEqual(conditional, body.Contains("If you're not on the latest version")); - var ordered = new[] { "Deregister", "record its registration region", "all additional marketplaces", "remove the affected account", "Save the removal", "close Libation", "Reopen Libation", "verify the old account is absent", "re-add the account", "Scan and sign in", "check every recorded additional marketplace", "save both dialogs", "Scan again with all marketplaces restored", "retry the download" }; + var ordered = new[] { "Settings > Accounts", "Signed in?", "Save", "Scan and sign in", "Retry the download" }; var previous = -1; foreach (var instruction in ordered) { @@ -53,17 +47,17 @@ public class LicenseRecoveryGuidanceTests Assert.IsTrue(position > previous, instruction); previous = position; } - StringAssert.Contains(body, "preserves your library and downloaded files"); - StringAssert.Contains(body, upgrade ? "5. Scan" : "4. Scan"); + StringAssert.Contains(body, "additional marketplaces under Marketplaces are preserved"); + StringAssert.Contains(body, upgrade ? "3. Scan" : "2. Scan"); if (upgrade) - Assert.IsTrue(body.IndexOf(LicenseRecoveryGuidance.ReleasesUrl) < body.IndexOf("remove the affected account")); + Assert.IsTrue(body.IndexOf(LicenseRecoveryGuidance.ReleasesUrl) < body.IndexOf("Settings > Accounts")); } [TestMethod] - public void Cli_instructions_record_and_restore_marketplaces_before_scanning() + public void Cli_instructions_use_login_external_and_preserve_marketplaces() { var body = LicenseRecoveryGuidance.BuildSteps(Localization.Get("uk"), VersionCheckOutcome.UpToDate, cli: true, hasAdditionalMarketplaces: true); - var ordered = new[] { "record its registration region", "all additional marketplaces", "Back up AccountsSettings.json", "remove only that account object", "Run login-external", "copy the saved AdditionalLocaleNames array", "Keep the new identity tokens", "verify Locale and Also scans", "Run scan" }; + var ordered = new[] { "login-external --account", "--locale uk", "additional marketplaces will be preserved", "Run scan", "retry with liberate" }; var previous = -1; foreach (var instruction in ordered) { @@ -71,7 +65,8 @@ public class LicenseRecoveryGuidanceTests Assert.IsTrue(position > previous, instruction); previous = position; } - StringAssert.Contains(body, "\"AdditionalLocaleNames\": [\"us\"]"); + StringAssert.Contains(body, "1. Run login-external"); + StringAssert.Contains(body, "2. Run scan"); } [TestMethod] @@ -90,8 +85,6 @@ public class LicenseRecoveryGuidanceTests Assert.AreEqual(hasAdditional, context.HasAdditionalMarketplaces); var body = LicenseRecoveryGuidance.BuildSteps(context.Locale, VersionCheckOutcome.UpToDate, cli, context.HasAdditionalMarketplaces); Assert.AreEqual(hasAdditional, body.Contains("additional marketplaces")); - Assert.AreEqual(cli && hasAdditional, body.Contains("AdditionalLocaleNames")); - Assert.AreEqual(!cli && hasAdditional, body.Contains("save both dialogs")); StringAssert.Contains(body, cli ? "Run scan" : "Scan and sign in"); Assert.IsFalse(LicenseRecoveryGuidance.GetAccountContext(accounts, "missing", "uk").HasAdditionalMarketplaces); } diff --git a/docs/advanced/advanced.md b/docs/advanced/advanced.md index d9bda5fb..67ab085f 100644 --- a/docs/advanced/advanced.md +++ b/docs/advanced/advanced.md @@ -14,7 +14,7 @@ To make upgrades and reinstalls easier, Libation separates all of its responsibi - Check for new Libation versions at startup. Enabled by default: each time Libation starts it asks GitHub whether a newer release exists, and offers it to you if there is one. Turn it off if something else keeps Libation up to date, such as a package manager or an AppImage updater. Turning it off only stops the automatic check - Settings > About still has a "Check for Upgrade" button that works either way. -- Device registration (experimental). Which virtual device Libation registers with Amazon when you sign in. The corrected Android registration is the default and supports Widevine; the iPhone/audible-cli alternative does not. Changing it or updating Libation does not convert existing accounts, so affected accounts must be removed and re-added. See [Device registration](./device-registration.md). +- Device registration. Which virtual device Libation registers with Amazon when you sign in. The Android registration (`CurrentAndroid`) is the default and supports Widevine; the iPhone/audible-cli alternative does not. If an account requires a fresh registration, Libation prompts to sign in on the next scan or download without needing to delete the account. See [Device registration](./device-registration.md). - Allow Libation to fix up audiobook metadata. After decrypting a title, Libation attempts to fix details like chapters and cover art. Some power users and/or control freaks prefer to manage this themselves. By unchecking this setting, Libation will only decrypt the book and will leave metadata as-is, warts and all. diff --git a/docs/advanced/command-line-interface.md b/docs/advanced/command-line-interface.md index 08a284ae..ec271638 100644 --- a/docs/advanced/command-line-interface.md +++ b/docs/advanced/command-line-interface.md @@ -113,9 +113,9 @@ Non-interactive use (stdin redirected, Docker without `-t`, scripts): pass the p libationcli login-external -a you@example.com -l us --response-url "https://www.amazon.com/ap/maplanding?..." ``` -If the account row already has valid saved tokens, the CLI reports that no browser login is needed and exits without opening the flow. +If the account row already has valid saved tokens and does not require re-registration, the CLI reports that no browser login is needed and exits without opening the flow. If the account is marked as requiring re-registration (or has an obsolete registration profile), `login-external` automatically proceeds with sign-in to register a fresh device and clears the flag—no account removal or manual configuration editing required. -Optional `--device-registration` picks which virtual device to register as on a **new** sign-in: `CurrentAndroid` (the corrected default) or `Mkb79IPhone` (experimental; no Widevine). It does nothing to an account that is already authenticated; remove the account first. See [Device registration](/docs/advanced/device-registration). +Optional `--device-registration` picks which virtual device to register as on a **new** sign-in: `CurrentAndroid` (the default, Widevine-capable) or `Mkb79IPhone` (experimental; no Widevine). See [Device registration](/docs/advanced/device-registration). ```console libationcli login-external --account you@example.com --locale us --device-registration Mkb79IPhone diff --git a/docs/advanced/device-registration.md b/docs/advanced/device-registration.md index 54fec88d..71718852 100644 --- a/docs/advanced/device-registration.md +++ b/docs/advanced/device-registration.md @@ -1,78 +1,51 @@ -# Device registration (experimental) +# Device registration -When you sign in, Libation registers a virtual device with Amazon. Audible then ties download licenses to that device. The default is an Android emulator, which is required for [Widevine](/docs/features/audio-file-formats#use-widevine-drm). +When you sign in, Libation registers a virtual device with Amazon. Audible then ties download licenses to that device. The default is an Android emulator (`CurrentAndroid`), which is required for [Widevine](/docs/features/audio-file-formats#use-widevine-drm). -Older Libation versions generated an Android device serial that was twice the expected length. Audible began refusing licenses (`License Denied` / `CustomerThrottled`) for some of those registrations even when the same title still played in the official Audible app. Current versions use the corrected Android registration. +## Understanding Throttling: Registration vs. Volume -Registration data is stored with the account, so updating Libation alone does **not** repair an existing registration. For throttling or license refusals, follow the [full recovery procedure](#how-to-register-an-account-again) first. Keep the corrected Android default unless you specifically need an alternative. +When Audible denies a content license with `License Denied` or `CustomerThrottled`, it is typically caused by one of two distinct situations: -## Where to find it +1. **Obsolete or incompatible device registration:** + - In early September 2026, Audible began refusing licenses for device registrations using non-Android profiles (e.g. `Mkb79IPhone`), registrations created when Widevine was disabled, or older registrations with legacy device serial numbers (which were 20 bytes / 40 hex characters rather than the modern 10 bytes / 20 hex characters). + - In this situation, the official Audible mobile app can still play the title, but Libation cannot obtain a download license. + - **Libation now resolves this automatically:** See [Automatic Registration Recovery](#automatic-registration-recovery) below. + +2. **Ordinary volume rate limiting:** + - Downloading a large number of titles in a short window—such as downloading dozens of Audible Plus catalog titles, or running [Scan for Better Quality Audiobooks](/docs/features/audio-file-formats#upgrading-existing-audiobooks-and-rate-limiting) to re-download a large portion of your library—can trigger Audible's server-side rate limits. + - In this situation, your device registration is healthy, but Audible temporarily blocks license issuance for 24 to 48 hours (and sometimes a few days). + - **Solution:** Wait 24 to 48 hours for the limit to expire, and turn on the [Daily download limit](/docs/features/daily-download-limit) (set to "All books" when performing bulk re-downloads) to pace your downloads. + +## Automatic Registration Recovery + +If Audible reports `CustomerThrottled` on an obsolete registration profile or while Widevine is disabled, Libation automatically intervenes without requiring you to delete your accounts or lose your configuration: + +1. **Automatic Settings Update:** Libation automatically enables Widevine DRM and sets the device profile to Android emulator (`CurrentAndroid`). +2. **Account Preservation:** Your accounts, library records, download history, and configured secondary marketplaces (`AdditionalLocaleNames`) are **completely preserved**. No accounts need to be deleted. +3. **Re-registration Prompt:** + - **In the GUI (Chardonnay & Classic):** Libation marks the account as needing a fresh device registration and will prompt you to complete a browser sign-in on your next library scan or download attempt. Signing in registers the new virtual Android device with Amazon and clears the prompt. You can also trigger this manually at any time by going to **Settings > Accounts**, unchecking the **Signed in?** checkbox, and clicking **Save**. + - **In the CLI / Docker:** Running `libationcli list-accounts` will show `re-login needed` under the **Authenticated** column. Simply run `libationcli login-external --account --locale ` to complete the sign-in. The CLI automatically invalidates the old device tokens, establishes the new registration, and clears the re-login flag. + - **In Settings:** If you manually check **Use Widevine DRM** in Settings, Libation will ask whether you want to mark your accounts for re-registration on their next sign-in, keeping all your account settings intact. + +## Where to Find Device Registration Settings - **Chardonnay:** Settings -> Import library -> **Device registration (experimental)** - **Classic:** Settings -> Import library -> **Device registration (experimental)** - **CLI / Docker:** `DeviceRegistrationKind` in `Settings.json`, or `--device-registration` on `login-external`. See [Command Line Interface](/docs/advanced/command-line-interface#log-in-with-an-external-browser-login-external). -## The two profiles +## The Two Profiles | Setting value | Label in Settings | Widevine | What it registers | |---------------|-------------------|----------|-------------------| -| `CurrentAndroid` | Android emulator (default) | Yes | The corrected Android Audible app registration | -| `Mkb79IPhone` | iPhone / audible-cli (experimental; no Widevine) | No | The virtual iPhone used by audible-cli | +| `CurrentAndroid` | Android emulator (default) | Yes | The corrected Android Audible app registration (recommended) | +| `Mkb79IPhone` | iPhone / audible-cli (experimental; no Widevine) | No | The virtual iPhone profile used by audible-cli | -`RetailAndroid` appeared briefly in Libation 14.1 but is no longer a separate option. Existing `RetailAndroid` values are treated as `CurrentAndroid`. +`RetailAndroid` appeared briefly in Libation 14.1 but is treated as `CurrentAndroid`. -## How to register an account again +## Manual Troubleshooting Fallback -Audible changed something in early September 2026. For `CustomerThrottled`, or a license refusal when the official Audible app can still play the title, this is our recommended workaround. We cannot be certain every step is necessary, and it is not a guaranteed fix. +If automatic recovery does not resolve a persistent license refusal: -1. Open [Amazon's Audible device-management page (United States)](https://www.amazon.com/hz/mycd/digital-console/devicedetails?deviceFamily=AUDIBLE_APP) and **deregister entries named "Libation"**. For other regions, use your regional Amazon site and go to **Manage Your Content and Devices > Devices > Audible**. The app constructs a regional link, but links outside the US are unverified; use the manual route if yours does not work. -2. Upgrade to [the latest version of Libation](https://github.com/rmcrackan/Libation/releases/latest). -3. Go to **Settings > Accounts** and remove the affected account. **This preserves your library and downloaded files.** Save the removal, then close Libation. -4. Reopen Libation. Go to **Settings > Accounts**, verify the old account is absent, then re-add it using the same account and registration region. Save. -5. Scan and sign in, then retry the download. If the title is deferred, mark it **Download Pending** to try sooner. - -
-Only if this login scans additional marketplaces - -Before deleting the account in step 3, record its registration region and every additional marketplace checked under its **Marketplaces** button. After recreating the account, scan/sign in once to enable that button. Before retrying downloads, return to **Settings > Accounts**, click **Marketplaces** on that account's row, check every recorded additional marketplace, and save both dialogs. Scan again with all marketplaces restored, then retry the download. - -The initial GUI scan is needed to sign in; the Marketplaces button is disabled until credentials exist. Recreating the account alone does not restore its additional marketplaces. For example, a UK registration that also scans the US needs the US checked again, or US downloads can fail with "No account found". - -
- -### CLI / Docker - -Follow steps 1 and 2 above. Run `list-accounts` to note the affected account's registration region (**Locale**). Stop Libation and any running CLI/Docker jobs. Back up `AccountsSettings.json`, then remove **only the affected account object** from its `Accounts` array, keeping valid JSON and all other entries. Save it. For Docker, edit the persistent configuration mounted into the container, not a temporary internal copy. - -Run `list-accounts` to verify the old account is absent. Then run `login-external --account --locale ` and complete sign-in. Run `scan`, then `liberate `. LibationCli has no remove-account command; `login-external` alone skips sign-in when existing credentials are still valid. - -
-Only if this login scans additional marketplaces - -Before deleting the account, also record **Also scans** from `list-accounts` and preserve the account's `AdditionalLocaleNames` array in your backup. After `login-external` finishes, with Libation and CLI/Docker jobs stopped, copy that array into the **newly created account object** in `AccountsSettings.json` before any scan or retry. For a UK registration with the US as an additional marketplace, that property is `"AdditionalLocaleNames": ["us"]`. Restore all recorded entries, not just the marketplace of the failed title. **Keep the new identity tokens; do not restore the old account object or credentials.** Save, then run `list-accounts` and verify **Locale** and **Also scans** match your notes. Only then run `scan` and `liberate `. There is no CLI verb for adding marketplaces. - -
- -### If registration recovery does not help - -Audible also has temporary outages and rate limits, especially after heavy Plus use. **Wait 24 to 48 hours, sometimes a few days**, before retrying. You may still be able to listen through Audible's app or website. If the title no longer plays there either, check whether you still have access to it. - -As a secondary option, try **iPhone / audible-cli** and repeat the account removal and sign-in steps, or import credentials from [audible-cli](https://github.com/mkb79/audible-cli) with `import-account`. This experimental alternative does not support Widevine. Imported audible-cli credentials already use its iPhone registration. - -## Widevine - -**Use Widevine DRM** only works when the account was registered with `CurrentAndroid`. The iPhone profile cannot use Widevine. If you need Widevine later, remove the account and sign in again with the Android profile. - -## Settings.json (Docker and CLI) - -```json -{ - "DeviceRegistrationKind": "Mkb79IPhone" -} -``` - -Supported choices are `CurrentAndroid` and `Mkb79IPhone`. Then remove the account and sign in again. `login-external --device-registration Mkb79IPhone` overrides Settings for that one sign-in. A legacy `RetailAndroid` value behaves as `CurrentAndroid`. - -## If it still fails - -If the recovery procedure and waiting a few days do not help, open a GitHub issue and attach your log. See also [Daily download limit](/docs/features/daily-download-limit) and [Retrying titles Audible refuses](/docs/features/retrying-refused-downloads). +1. Open [Amazon's Audible device-management page (United States)](https://www.amazon.com/hz/mycd/digital-console/devicedetails?deviceFamily=AUDIBLE_APP) (or your regional Amazon site: **Manage Your Content and Devices > Devices > Audible**) and deregister old entries named "Libation". +2. If you are experiencing volume throttling, **wait 24 to 48 hours** before attempting further downloads, and configure a [Daily download limit](/docs/features/daily-download-limit). +3. If issues persist after several days, open a GitHub issue and attach your log. See also [Retrying titles Audible refuses](/docs/features/retrying-refused-downloads). diff --git a/docs/advanced/spatial-audio.md b/docs/advanced/spatial-audio.md index 1abc9e5e..42194a84 100644 --- a/docs/advanced/spatial-audio.md +++ b/docs/advanced/spatial-audio.md @@ -62,7 +62,7 @@ Download and decrypt titles while Libation still supports the format Audible del 1. Open **Settings** and enable **Use Widevine DRM**. 2. Enable **Request xHE-AAC Codec**. -3. Re-add your account if Libation prompts you (Widevine requires an Android device registration; the experimental iPhone profile cannot use it). See [Device registration](./device-registration.md). +3. Re-register your account if Libation prompts you (Widevine requires an Android device registration; Libation will prompt you to sign in to establish the registration without needing to delete the account). See [Device registration](./device-registration.md). 4. Re-download the title. See [Audio File Formats](../features/audio-file-formats.md) for codec details and [Supported Media Players](../features/audio-file-formats.md#supported-media-players) if you have trouble playing xHE-AAC. diff --git a/docs/advanced/troubleshoot.md b/docs/advanced/troubleshoot.md index 766c003d..382d79a8 100644 --- a/docs/advanced/troubleshoot.md +++ b/docs/advanced/troubleshoot.md @@ -263,9 +263,9 @@ Symptoms include a crash on startup that mentions `LibationContext.db` under a p These errors come from Audible refusing to grant a download license. Common causes: -1. **Device-registration trouble after Audible's early September 2026 changes** -- for `CustomerThrottled`, or when Audible's app plays the title, try the [full recovery procedure](/docs/advanced/device-registration#how-to-register-an-account-again): deregister Libation devices, upgrade to the [latest release](https://github.com/rmcrackan/Libation/releases/latest), remove/save the account, restart, verify removal, re-add, and scan/sign in. The full procedure includes extra steps only for logins that scan additional marketplaces. Your library and files are preserved. This is a recommended workaround, not a guaranteed fix. -2. **Temporary Audible outage or Plus throttling** -- if recovery does not help, wait 24 to 48 hours, sometimes a few days. Heavy Plus downloading can still trigger genuine rate limits. -3. **Title requires Widevine** -- some Plus titles no longer download as AAXC; enable **Use Widevine DRM** in Settings and re-add your account if prompted. The iPhone registration cannot use Widevine. See [issue #1580](https://github.com/rmcrackan/Libation/issues/1580) and [Device registration](/docs/advanced/device-registration#widevine). +1. **Device-registration trouble (`CustomerThrottled` on obsolete profiles)** -- Libation automatically detects when `CustomerThrottled` is caused by an obsolete device profile or disabled Widevine. It automatically configures Android + Widevine and prompts you to sign in to re-register on your next scan or download, preserving all your account settings and marketplaces. See [Device registration](/docs/advanced/device-registration). +2. **Volume rate limiting (`CustomerThrottled` after mass downloads)** -- downloading dozens of Plus titles in a short window or running [Scan for Better Quality Audiobooks](/docs/features/audio-file-formats#upgrading-existing-audiobooks-and-rate-limiting) to re-download your library can trigger Audible's server-side rate limits. Wait 24 to 48 hours for the block to expire, and turn on the [Daily download limit](/docs/features/daily-download-limit) (set to "All books" for bulk re-downloads) to pace your downloads. +3. **Title requires Widevine** -- some titles no longer download as AAXC; enable **Use Widevine DRM** in Settings. Libation will prompt you to re-register your accounts if needed, without deleting them. See [Device registration](/docs/advanced/device-registration). 4. **Spatial / Dolby Atmos requested (older Libation versions)** -- Audible now requires Widevine L1 for many spatial titles. Libation 13.1.3+ no longer offers spatial download. See [Spatial Audio & DRM](/docs/advanced/spatial-audio). 5. **You no longer have rights to the title** -- it was returned, it left the Plus catalog, or the account that owned it is no longer active. Check the title in the Audible app or website. diff --git a/docs/features/audio-file-formats.md b/docs/features/audio-file-formats.md index f5f2b15e..efb23057 100644 --- a/docs/features/audio-file-formats.md +++ b/docs/features/audio-file-formats.md @@ -18,7 +18,7 @@ Audiobooks can be requested from Audible as "Normal" quality or "High" quality, ### Use Widevine DRM When this setting is disabled, all audiobooks will be downloaded using Audible's in-house DRM (AAX(C)) in the [AAC-LC](#aac-lc) format. -When this setting is enabled, Libation will request audio files protected by Google's Widevine DRM scheme. This unlocks [Request xHE-AAC Codec](#request-xhe-aac-codec) for higher-quality stereo downloads on titles where Audible delivers them via Widevine L3. Widevine requires an Android device registration; the experimental iPhone profile cannot use it. See [Device registration](/docs/advanced/device-registration#widevine). +When this setting is enabled, Libation will request audio files protected by Google's Widevine DRM scheme. This unlocks [Request xHE-AAC Codec](#request-xhe-aac-codec) for higher-quality stereo downloads on titles where Audible delivers them via Widevine L3. Widevine requires an Android device registration; the experimental iPhone profile cannot use it. See [Device registration](/docs/advanced/device-registration). If you don't enable **Request xHE-AAC Codec**, then enabling **Use Widevine DRM** will have no practical effect in nearly all circumstances. Audiobooks will be downloaded in the same [AAC-LC](#aac-lc) format with the same bitrate and the same number of audio channels. On rare occasions, enabling **Use Widevine DRM** without xHE-AAC will result in audio files with a different bitrate. @@ -26,6 +26,27 @@ If you don't enable **Request xHE-AAC Codec**, then enabling **Use Widevine DRM* Enable this setting to request audiobooks in the [xHE-AAC](#xhe-aac) format. This codec is generally better quality than the [AAC-LC](#aac-lc) codec at the same bitrate, but it isn't as commonly supported by media players, so you may have some difficulty playing these audiobooks. The highest bitrate version of some audiobooks is only available as [xHE-AAC](#xhe-aac). +### Upgrading Existing Audiobooks and Rate Limiting + +If you enable Widevine or xHE-AAC after already liberating books, existing audio files on disk remain in their original formats unless you choose to re-download them. + +Libation includes a built-in scanner to help upgrade your library: +- **Chardonnay:** Top menu -> **Scan for Better Quality Audiobooks** +- **Classic:** Menu bar -> **Tools** -> **Scan Audible for Higher Quality Audio** + +This tool inspects your liberated audiobooks against Audible's servers, reports which titles have a higher bitrate or superior codec available, and lets you mark those titles as **Download Pending** with one click. + +> [!WARNING] +> **Pace Bulk Re-downloads to Avoid Throttling:** +> Re-downloading dozens or hundreds of books in a short span will easily trigger Audible's server-side rate limits (`CustomerThrottled`), locking your account out of downloading licenses for 24 to 48 hours. +> +> Before liberating a large batch of upgraded titles, enable a [Daily download limit](/docs/features/daily-download-limit): +> 1. Go to **Settings > Download/Decrypt > Daily download limit**. +> 2. Select **All books** (so the limit applies to owned titles being re-downloaded, not just Plus catalog titles). +> 3. Set a sustainable volume (e.g. 30 to 50 books per 24 hours). +> +> Libation will pace the re-downloads automatically across multiple days without triggering Audible's throttling mechanisms. + ### Download My Books in the Original Audio Format (Lossless) If selected, Audiobooks will be downloaded and saved in the format delivered by audible (which depends on the settings explained above). Libation will not change the audio. diff --git a/docs/features/daily-download-limit.md b/docs/features/daily-download-limit.md index 60395285..54135af4 100644 --- a/docs/features/daily-download-limit.md +++ b/docs/features/daily-download-limit.md @@ -4,7 +4,7 @@ Libation can pace itself, downloading only so much in any 24 hour period. The li Two different reasons to use it: -- **Audible throttling.** Downloading a lot of Audible Plus titles in a short time can lead Audible to deny content licenses for a day or two ("license denied"). That limit is Audible's, not Libation's, and Audible does not publish a number, but community reports put it in the dozens of titles. Capping your Plus downloads can help reduce that risk. However, `CustomerThrottled` can also reflect device-registration trouble after Audible's early September 2026 changes. Try the [registration recovery procedure](/docs/advanced/device-registration#how-to-register-an-account-again), including upgrading to the [latest release](https://github.com/rmcrackan/Libation/releases/latest). If that does not help, waiting 24 to 48 hours, sometimes a few days, remains valid advice for rate limits or outages. +- **Audible throttling.** Downloading a large volume of titles in a short time—such as downloading dozens of Audible Plus titles or re-downloading books in bulk after running [Scan for Better Quality Audiobooks](/docs/features/audio-file-formats#upgrading-existing-audiobooks-and-rate-limiting)—can lead Audible to deny content licenses for 24 to 48 hours ("license denied" / `CustomerThrottled`). That limit is enforced by Audible's servers, not Libation. Setting a daily download limit (using "Plus titles only" for regular use, or "All books" when performing a library upgrade) paces your downloads to stay below Audible's throttling thresholds. Note that `CustomerThrottled` can also stem from an obsolete device registration; Libation handles registration issues automatically (see [Device registration](/docs/advanced/device-registration)). - **Disk space.** A large library can fill a drive. A limit in MB or GB stops a long run before your disk does. ## Turning it on @@ -74,4 +74,6 @@ A container that liberates on a schedule combines well with a limit: each run do ## When a license is denied anyway -If Audible refuses a license despite the limit, Libation waits before asking about that title again instead of re-requesting it on every run. See [Retrying titles Audible refuses](/docs/features/retrying-refused-downloads). If the official Audible app can still play the title, remove and re-add the account to get the corrected Android registration. See [Device registration](/docs/advanced/device-registration) for the experimental iPhone alternative and audible-cli import. +If Audible refuses a license despite the limit, Libation waits before asking about that title again instead of re-requesting it on every run. See [Retrying titles Audible refuses](/docs/features/retrying-refused-downloads). + +If Audible reports `CustomerThrottled` because of a legacy or non-Widevine device registration, Libation will automatically migrate your settings and prompt you to sign in to re-register on your next scan or download. See [Device registration](/docs/advanced/device-registration) for details. For true volume rate limits, wait 24 to 48 hours for Audible's temporary lockout to clear. diff --git a/docs/frequently-asked-questions.md b/docs/frequently-asked-questions.md index ae257435..beb4dfbe 100644 --- a/docs/frequently-asked-questions.md +++ b/docs/frequently-asked-questions.md @@ -70,9 +70,11 @@ Full steps: [Troubleshooting - Failed to decrypt ExistingAccessToken](/docs/adva ## Downloads fail with "Content license denied" but the Audible app still plays the title -Audible's early September 2026 changes can cause license refusals, including `CustomerThrottled`, for existing device registrations. Try the [full registration recovery procedure](/docs/advanced/device-registration#how-to-register-an-account-again): deregister Amazon devices named "Libation", upgrade to the [latest Libation](https://github.com/rmcrackan/Libation/releases/latest), remove and save the affected account, close and reopen Libation, verify it is gone, then re-add it and scan/sign in. The full procedure includes extra steps only for logins that scan additional marketplaces. Removing the account preserves your library and downloaded files. We recommend the full sequence, although we cannot be certain every step is necessary. +Audible can deny content licenses (`CustomerThrottled` or generic errors) for two main reasons: an obsolete device registration or volume rate limiting. -If that does not help, waiting **24 to 48 hours, sometimes a few days**, can still resolve real rate limits or outages, especially after heavy Plus use. The recovery page also covers non-US links, CLI/Docker instructions, and secondary experimental registration options. If failures persist after several days, report an issue with logs. +If caused by an obsolete registration profile or disabled Widevine, Libation automatically detects this, configures Android emulator + Widevine, and prompts you to sign in to re-register on your next scan or download—preserving your library, accounts, and extra marketplaces without requiring manual account removal. See [Device registration](/docs/advanced/device-registration). + +If caused by volume rate limiting (such as downloading dozens of Plus titles or running [Scan for Better Quality Audiobooks](/docs/features/audio-file-formats#upgrading-existing-audiobooks-and-rate-limiting) to re-download your library), wait **24 to 48 hours** for Audible's temporary lockout to expire, and turn on the [Daily download limit](/docs/features/daily-download-limit) to pace future runs. See [Troubleshooting](/docs/advanced/troubleshoot#download-fails-with-drm-license-response-not-ok-or-content-license-denied). diff --git a/docs/getting-started.md b/docs/getting-started.md index 05d7594b..81f16d83 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -49,6 +49,15 @@ Create your account(s): Most people use a normal region and their Audible **email**. If your account predates Amazon and still signs in with a **username**, choose a **pre-amazon** locale and put that username in the Audible email/login field. ::: +### Account Settings Columns + +The Accounts table in **Settings > Accounts** contains the following options for each account: + +- **Scan**: When checked, this account will be automatically included whenever you run a library scan. +- **Signed in?**: Indicates whether the account currently holds valid login tokens. If you need to re-authenticate or refresh your device registration without deleting your account or losing your additional marketplaces, simply uncheck **Signed in?** and click **Save**. Libation preserves your account settings and prompts you for a fresh sign-in on your next scan or download. +- **Marketplaces**: Lets you scan and import titles from secondary Audible marketplaces associated with this account (see below). +- **Delete (`x`)**: Removes the account from Libation. (Your downloaded audiobooks and library database are preserved). + ### Titles bought from another country Audible keeps a **separate library for each marketplace**. If you have ever changed your Amazon address to another country to buy a title that was not sold in your own - a common way to get around region-locked titles - that title stayed in that country's library. Scanning your usual marketplace will never find it, and nothing in Libation will suggest it is missing. diff --git a/docs/index.md b/docs/index.md index 58f62d39..e3b8bb3a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -32,7 +32,7 @@ Learn about Libation's powerful features: - **[Advanced Topics](/docs/advanced/advanced)** - Deep dives and configuration details - **[Command Line Interface](/docs/advanced/command-line-interface)** - CLI usage and commands -- **[Device registration](/docs/advanced/device-registration)** - Re-register affected accounts and choose the experimental iPhone alternative +- **[Device registration](/docs/advanced/device-registration)** - Virtual device profiles, Widevine compatibility, and automatic recovery - **[Troubleshooting](/docs/advanced/troubleshoot)** - Common errors and solutions - **[Spatial Audio & DRM](/docs/advanced/spatial-audio)** - Why Dolby Atmos download is not available and what still works diff --git a/docs/installation/docker.md b/docs/installation/docker.md index cd1cfdda..432884ca 100644 --- a/docs/installation/docker.md +++ b/docs/installation/docker.md @@ -52,7 +52,7 @@ If you run Libation on a server or in Docker and do not want to copy `AccountsSe - `login-external` — Browser-based sign-in: the CLI prints an Audible login URL; you open it in a normal browser, sign in, then paste the final URL from the address bar back into the terminal. Example: `LibationCli login-external --account you@example.com --locale us` If standard input is not a TTY (for example in some automation), pass the final URL with `--response-url "https://..."` instead of pasting interactively. - Optional `--device-registration CurrentAndroid|Mkb79IPhone` applies only to a new sign-in; remove the account first. Android is the corrected default and supports Widevine; iPhone is experimental and does not. See [Device registration](/docs/advanced/device-registration). + Optional `--device-registration CurrentAndroid|Mkb79IPhone` chooses which virtual device to register. Android is the default and supports Widevine; iPhone is experimental and does not. See [Device registration](/docs/advanced/device-registration). - `list-accounts` — List configured accounts and whether each has valid stored credentials (and scan-on/off). Example: `LibationCli list-accounts` or `LibationCli list-accounts --bare` for tab-separated output.