feat(desktop): 歌词页支持三种来源,加网易云扫码登录

歌词页原先只能扫本地目录。CLI 有三种来源 —— 本地、CSV、网易云歌单 —— 而
网易云那条路在界面上完全走不通。

现在页面有一个来源下拉,以及三行互斥的输入:

  本地文件夹 —— 沿用目录选择器
  CSV 文件   —— 选一个"歌名,歌手"两列的 .csv
  网易云     —— 粘贴一个或多个歌单 ID,用分号分隔

因为网易云那条路需要已登录的会话,这个提交同时加上二维码登录对话框:

- QrCodeLoginViewModel 用 QRCoder 把二维码内容渲染成真正的 PNG(CLI 是往日志里
  画 ASCII 艺术,在窗口里没法用),下方显示登录状态:等待扫码、已扫码待确认、
  成功。
- 关闭对话框即取消登录,而这次能真的停下来,因为扫描器已经接受
  CancellationToken(上一个提交)。
- cookie 持久化到 netease.session.json,重启不必重新扫码。页面显示当前是否
  已登录:未登录给"登录…"按钮,已登录给"退出登录",退出会同时清掉内存里的
  cookie 和文件,下次解析歌单重新扫码。
- 非本地来源还需要指定 .lrc 的落盘目录,因此多一行输出目录,默认
  <音乐>/DownloadedLrc。

扫描与下载拆成两步:"解析"把来源返回的歌曲填进表格,"开始下载"才写文件。
进度、逐行状态与取消按钮对三种来源一视同仁。
This commit is contained in:
aL1CesT committed 2026-11-09 04:27:44 +08:00
1 parent c614315601
commit c303705ab6
6 files changed
+880 -91

No files matched your search

@@ -8,28 +8,74 @@ using ZonyLrcTools.Common.Configuration;
using ZonyLrcTools.Common.Infrastructure.IO;
using ZonyLrcTools.Common.Infrastructure.Threading;
using ZonyLrcTools.Common.Lyrics;
using ZonyLrcTools.Common.MusicScanner;
using ZonyLrcTools.Common.TagInfo;
using ZonyLrcTools.Desktop.Infrastructure.Configuration;
using ZonyLrcTools.Desktop.Infrastructure.Localization;
using ZonyLrcTools.Desktop.Services;
namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>
/// Which source the lyrics page reads its song list from.
/// </summary>
public enum LyricsScannerKind
{
/// <summary>Scan a local folder for audio files.</summary>
Local = 0,
/// <summary>Read a CSV file containing "song,artist" rows.</summary>
Csv = 1,
/// <summary>Pull a NetEase Cloud Music playlist by id.</summary>
NetEase = 2
}
public partial class LyricsDownloadViewModel : ViewModelBase
{
private const string DefaultOutputDirectoryName = "DownloadedLrc";
private const string DefaultFileNamePattern = "{Artist} - {Name}.lrc";
private readonly ILyricsDownloader _lyricsDownloader;
private readonly IDialogService _dialogService;
private readonly IFileScanner _fileScanner;
private readonly ITagLoader _tagLoader;
private readonly CsvFileMusicScanner _csvFileMusicScanner;
private readonly NetEaseMusicSongListMusicScanner _neteaseMusicScanner;
private readonly NetEaseSessionStore _sessionStore;
private readonly GlobalOptions _options;
private readonly IUILocalizationService? _localization;
private CancellationTokenSource? _downloadCts;
private Dictionary<string, MusicFileViewModel> _musicFileMap = new();
private CancellationTokenSource? _scanCts;
private readonly Dictionary<string, MusicFileViewModel> _musicFileMap = new();
private List<MusicInfo> _scannedMusicInfos = new();
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyPropertyChangedFor(nameof(CanScan))]
private string? _selectedFolderPath;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyPropertyChangedFor(nameof(CanScan))]
private string? _selectedCsvFilePath;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyPropertyChangedFor(nameof(CanScan))]
private string? _songListIds;
[ObservableProperty]
private string? _outputDirectory;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsLocalScanner))]
[NotifyPropertyChangedFor(nameof(IsCsvScanner))]
[NotifyPropertyChangedFor(nameof(IsNetEaseScanner))]
[NotifyPropertyChangedFor(nameof(CanScan))]
private int _selectedScannerIndex;
[ObservableProperty]
private int _parallelCount = 2;
@@ -53,7 +99,11 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyPropertyChangedFor(nameof(CanStartDownload))]
[NotifyPropertyChangedFor(nameof(CanScan))]
private bool _isScanning;
[ObservableProperty]
@@ -65,6 +115,12 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[ObservableProperty]
private double _scanProgressPercentage;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(NetEaseAccountStatus))]
[NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))]
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
private bool _isNetEaseLoggedIn;
[ObservableProperty]
private string? _currentProcessingFile;
@@ -78,6 +134,33 @@ public partial class LyricsDownloadViewModel : ViewModelBase
public string LyricsStartDownload => _localization?["Lyrics_StartDownload"] ?? "Start Download";
public string LyricsStopDownload => _localization?["Lyrics_StopDownload"] ?? "Stop Download";
public string LyricsScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files...";
public string LyricsScannerLabel => _localization?["Lyrics_Scanner"] ?? "Source";
public string LyricsScan => _localization?["Lyrics_Scan"] ?? "Scan";
public string LyricsCsvLabel => _localization?["Lyrics_CsvLabel"] ?? "CSV File";
public string LyricsCsvSelect => _localization?["Lyrics_CsvSelect"] ?? "Select a CSV file...";
public string LyricsCsvBrowse => _localization?["Lyrics_CsvBrowse"] ?? "Choose...";
public string LyricsSongListLabel => _localization?["Lyrics_SongListLabel"] ?? "Playlist ID";
public string LyricsSongListWatermark => _localization?["Lyrics_SongListWatermark"] ?? "e.g. 7224428149 (separate multiple ids with ;)";
public string LyricsOutputLabel => _localization?["Lyrics_OutputLabel"] ?? "Save To";
public string LyricsOutputSelect => _localization?["Lyrics_OutputSelect"] ?? "Where the .lrc files should be written";
public string LyricsOutputBrowse => _localization?["Lyrics_OutputBrowse"] ?? "Choose...";
public string NetEaseSignOut => _localization?["NetEase_SignOut"] ?? "Sign out";
public string NetEaseSignOutHint => _localization?["NetEase_SignOutHint"] ??
"Forget the saved session and scan the QR code again next time.";
public string NetEaseSignIn => _localization?["NetEase_SignIn"] ?? "Sign in…";
public string NetEaseSignInHint => _localization?["NetEase_SignInHint"] ??
"Scan a QR code now instead of waiting until the next scan.";
/// <summary>
/// Human readable login state. The sign in / sign out buttons alone were not enough: a user
/// who had never signed in could not tell whether a session was stored, and a user who had
/// signed in had no way to notice the cookie was restored from disk.
/// </summary>
public string NetEaseAccountStatus => IsNetEaseLoggedIn
? _localization?["NetEase_LoggedIn"] ?? "Signed in. Scanning a playlist reuses this session."
: _localization?["NetEase_NotLoggedIn"] ?? "Not signed in. Scanning a playlist will show a QR code.";
public string NetEaseAccountLabel => _localization?["NetEase_AccountLabel"] ?? "Account";
public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
public string CommonFiles => _localization?["Common_Files"] ?? "files";
public string CommonSuccess => _localization?["Common_Success"] ?? "Success:";
@@ -87,6 +170,20 @@ public partial class LyricsDownloadViewModel : ViewModelBase
public string ColumnFilePath => _localization?["Column_FilePath"] ?? "File Path";
public string ColumnStatus => _localization?["Column_Status"] ?? "Status";
/// <summary>
/// Scanner display names, indexed the same way as <see cref="SelectedScannerIndex"/>.
/// </summary>
public string[] ScannerNames =>
[
_localization?["Scanner_Local"] ?? "Local Folder",
_localization?["Scanner_Csv"] ?? "CSV File",
_localization?["Scanner_NetEase"] ?? "NetEase Playlist"
];
public bool IsLocalScanner => SelectedScannerIndex == (int)LyricsScannerKind.Local;
public bool IsCsvScanner => SelectedScannerIndex == (int)LyricsScannerKind.Csv;
public bool IsNetEaseScanner => SelectedScannerIndex == (int)LyricsScannerKind.NetEase;
public bool CanStartDownload => !IsDownloading && !IsScanning && MusicFiles.Count > 0;
public bool HasNoFiles => MusicFiles.Count == 0;
@@ -100,6 +197,9 @@ public partial class LyricsDownloadViewModel : ViewModelBase
IDialogService dialogService,
IFileScanner fileScanner,
ITagLoader tagLoader,
CsvFileMusicScanner csvFileMusicScanner,
NetEaseMusicSongListMusicScanner neteaseMusicScanner,
NetEaseSessionStore sessionStore,
IOptions<GlobalOptions> options,
IUILocalizationService? localization = null)
{
@@ -107,18 +207,30 @@ public partial class LyricsDownloadViewModel : ViewModelBase
_dialogService = dialogService;
_fileScanner = fileScanner;
_tagLoader = tagLoader;
_csvFileMusicScanner = csvFileMusicScanner;
_neteaseMusicScanner = neteaseMusicScanner;
_sessionStore = sessionStore;
_options = options.Value;
_localization = localization;
OutputDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),
DefaultOutputDirectoryName);
if (_localization != null)
{
_localization.LanguageChanged += OnLanguageChanged;
}
// The scanner is a singleton, so a session restored by an earlier page visit is already
// in memory; reflect it right away instead of waiting for the first activation.
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
MusicFiles.CollectionChanged += (_, _) =>
{
OnPropertyChanged(nameof(HasNoFiles));
OnPropertyChanged(nameof(CanStartDownload));
StartDownloadCommand.NotifyCanExecuteChanged();
};
}
@@ -133,6 +245,22 @@ public partial class LyricsDownloadViewModel : ViewModelBase
OnPropertyChanged(nameof(LyricsStartDownload));
OnPropertyChanged(nameof(LyricsStopDownload));
OnPropertyChanged(nameof(LyricsScanning));
OnPropertyChanged(nameof(LyricsScannerLabel));
OnPropertyChanged(nameof(LyricsScan));
OnPropertyChanged(nameof(LyricsCsvLabel));
OnPropertyChanged(nameof(LyricsCsvSelect));
OnPropertyChanged(nameof(LyricsCsvBrowse));
OnPropertyChanged(nameof(LyricsSongListLabel));
OnPropertyChanged(nameof(LyricsSongListWatermark));
OnPropertyChanged(nameof(LyricsOutputLabel));
OnPropertyChanged(nameof(LyricsOutputSelect));
OnPropertyChanged(nameof(LyricsOutputBrowse));
OnPropertyChanged(nameof(NetEaseSignOut));
OnPropertyChanged(nameof(NetEaseSignOutHint));
OnPropertyChanged(nameof(NetEaseSignIn));
OnPropertyChanged(nameof(NetEaseSignInHint));
OnPropertyChanged(nameof(NetEaseAccountStatus));
OnPropertyChanged(nameof(NetEaseAccountLabel));
OnPropertyChanged(nameof(CommonTotal));
OnPropertyChanged(nameof(CommonFiles));
OnPropertyChanged(nameof(CommonSuccess));
@@ -142,8 +270,11 @@ public partial class LyricsDownloadViewModel : ViewModelBase
OnPropertyChanged(nameof(ColumnFilePath));
OnPropertyChanged(nameof(ColumnStatus));
OnPropertyChanged(nameof(EmptyStateText));
OnPropertyChanged(nameof(ScannerNames));
}
// ---------------------------------------------------------------- selection commands
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectFolderAsync()
{
@@ -157,21 +288,65 @@ public partial class LyricsDownloadViewModel : ViewModelBase
private bool CanSelectFolder => !IsScanning && !IsDownloading;
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectCsvFileAsync()
{
var file = await _dialogService.ShowFilePickerAsync(
_localization?["Lyrics_CsvSelect"] ?? "Select a CSV file", [".csv"]);
if (string.IsNullOrEmpty(file)) return;
SelectedCsvFilePath = file;
}
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectOutputFolderAsync()
{
var folder = await _dialogService.ShowFolderPickerAsync(
_localization?["Lyrics_OutputSelect"] ?? "Select Output Folder");
if (string.IsNullOrEmpty(folder)) return;
OutputDirectory = folder;
}
// ---------------------------------------------------------------- scanning
/// <summary>
/// Whether the current source has enough input to start reading a song list.
/// </summary>
public bool CanScan => !IsScanning && !IsDownloading && SelectedScannerIndex switch
{
(int)LyricsScannerKind.Local => !string.IsNullOrEmpty(SelectedFolderPath),
(int)LyricsScannerKind.Csv => !string.IsNullOrEmpty(SelectedCsvFilePath),
(int)LyricsScannerKind.NetEase => !string.IsNullOrWhiteSpace(SongListIds),
_ => false
};
/// <summary>
/// Re-read the song list using the currently selected source.
/// </summary>
[RelayCommand(CanExecute = nameof(CanScan))]
private async Task StartScanAsync()
{
switch ((LyricsScannerKind)SelectedScannerIndex)
{
case LyricsScannerKind.Csv:
await ScanCsvFileAsync();
break;
case LyricsScannerKind.NetEase:
await ScanNetEasePlaylistAsync();
break;
default:
await ScanFilesAsync();
break;
}
}
private async Task ScanFilesAsync()
{
if (string.IsNullOrEmpty(SelectedFolderPath)) return;
ResetCollections();
IsScanning = true;
MusicFiles.Clear();
_musicFileMap.Clear();
_scannedMusicInfos.Clear();
ScanProgressCount = 0;
ScanTotalCount = 0;
ScanProgressPercentage = 0;
TotalCount = 0;
CompletedCount = 0;
FailedCount = 0;
ProgressPercentage = 0;
try
{
@@ -180,11 +355,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
if (files.Count == 0)
{
await _dialogService.ShowMessageAsync(
_localization?["Common_Info"] ?? "Info",
_localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder.");
IsScanning = false;
OnPropertyChanged(nameof(CanStartDownload));
await ShowNoMusicFilesAsync();
return;
}
@@ -201,16 +372,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
if (musicInfo != null &&
(!string.IsNullOrEmpty(musicInfo.Name) || !string.IsNullOrEmpty(musicInfo.Artist)))
{
var vm = new MusicFileViewModel
{
FilePath = musicInfo.FilePath,
Name = musicInfo.Name,
Artist = musicInfo.Artist,
StatusMessage = _localization?["Status_Pending"] ?? "Pending"
};
MusicFiles.Add(vm);
_musicFileMap[musicInfo.FilePath] = vm;
_scannedMusicInfos.Add(musicInfo);
AddRow(musicInfo);
}
ScanProgressCount++;
@@ -224,17 +386,245 @@ public partial class LyricsDownloadViewModel : ViewModelBase
}
catch (Exception ex)
{
await _dialogService.ShowMessageAsync(
_localization?["Common_Error"] ?? "Error",
ex.Message);
await ShowErrorAsync(ex.Message);
}
finally
{
IsScanning = false;
OnPropertyChanged(nameof(CanStartDownload));
}
}
private async Task ScanCsvFileAsync()
{
if (string.IsNullOrEmpty(SelectedCsvFilePath)) return;
ResetCollections();
IsScanning = true;
try
{
var musicInfos = await _csvFileMusicScanner.GetMusicInfoFromCsvFileAsync(
SelectedCsvFilePath,
RequireOutputDirectory(),
DefaultFileNamePattern);
AppendScannedMusicInfos(musicInfos);
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message);
}
finally
{
IsScanning = false;
}
}
private async Task ScanNetEasePlaylistAsync()
{
if (string.IsNullOrWhiteSpace(SongListIds)) return;
ResetCollections();
IsScanning = true;
using var scanCts = new CancellationTokenSource();
_scanCts = scanCts;
try
{
await RestoreNetEaseSessionAsync();
if (!_neteaseMusicScanner.IsLoggedIn && !await LoginToNetEaseAsync())
{
return;
}
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
// 扫码等待与歌单请求都要能被打断,否则 Cookie 恰好失效时这里会一直挂着。
var musicInfos = await _neteaseMusicScanner.GetMusicInfoFromNetEaseMusicSongListAsync(
SongListIds,
RequireOutputDirectory(),
DefaultFileNamePattern,
onQrCodeReady: null,
onStateChanged: null,
cancellationToken: scanCts.Token);
await PersistNetEaseSessionAsync();
AppendScannedMusicInfos(musicInfos);
}
catch (OperationCanceledException)
{
// User closed the login dialog.
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message);
}
finally
{
_scanCts = null;
IsScanning = false;
// Whatever happened above - scan ok, user cancelled the QR dialog, request failed -
// the account row must reflect the scanner's real state. Without this the sign-in
// button kept saying "Sign out" after a successful login from the scan flow.
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
}
}
/// <summary>
/// Load a previously saved NetEase session so the QR dialog only appears on first use.
/// </summary>
private async Task RestoreNetEaseSessionAsync()
{
if (_neteaseMusicScanner.IsLoggedIn) return;
var session = await _sessionStore.LoadAsync();
if (session == null) return;
_neteaseMusicScanner.RestoreLoginState(session.Cookie, session.CsrfToken);
}
private async Task PersistNetEaseSessionAsync()
{
if (!_neteaseMusicScanner.IsLoggedIn) return;
await _sessionStore.SaveAsync(new NetEaseSession
{
Cookie = _neteaseMusicScanner.Cookie,
CsrfToken = _neteaseMusicScanner.CsrfToken,
SavedAt = DateTimeOffset.Now
});
}
/// <summary>
/// Show the QR dialog and wait for the scan-and-confirm flow to finish.
/// </summary>
private async Task<bool> LoginToNetEaseAsync()
{
var loginViewModel = new QrCodeLoginViewModel(_localization);
using var loginCts = new CancellationTokenSource();
loginViewModel.Cancelled += (_, _) => loginCts.Cancel();
var loginTask = Task.Run(async () =>
{
try
{
var isSuccess = await _neteaseMusicScanner.LoginAsync(
payload => Dispatcher.UIThread.Post(() => loginViewModel.SetPayload(payload)),
state => Dispatcher.UIThread.Post(() => loginViewModel.SetState(state)),
loginCts.Token);
if (isSuccess)
{
Dispatcher.UIThread.Post(() => loginViewModel.Complete());
}
return isSuccess;
}
catch (OperationCanceledException)
{
return false;
}
catch (Exception ex)
{
Dispatcher.UIThread.Post(() => loginViewModel.SetError(ex.Message));
return false;
}
});
// The dialog closes itself once the flow calls Complete(), so this await returns as soon
// as the user either confirms on the phone or gives up.
await _dialogService.ShowQrCodeLoginDialogAsync(loginViewModel);
var isSuccess = await loginTask;
if (isSuccess)
{
await PersistNetEaseSessionAsync();
}
return isSuccess;
}
// ---------------------------------------------------------------- shared helpers
private void ResetCollections()
{
MusicFiles.Clear();
_musicFileMap.Clear();
_scannedMusicInfos.Clear();
ScanProgressCount = 0;
ScanTotalCount = 0;
ScanProgressPercentage = 0;
TotalCount = 0;
CompletedCount = 0;
FailedCount = 0;
ProgressPercentage = 0;
}
private void AddRow(MusicInfo musicInfo)
{
var vm = new MusicFileViewModel
{
FilePath = musicInfo.FilePath,
Name = musicInfo.Name,
Artist = musicInfo.Artist,
StatusMessage = _localization?["Status_Pending"] ?? "Pending"
};
MusicFiles.Add(vm);
_musicFileMap[musicInfo.FilePath] = vm;
_scannedMusicInfos.Add(musicInfo);
}
/// <summary>
/// Fill the grid from a scanner that returns its list in one shot (CSV, NetEase).
/// </summary>
private void AppendScannedMusicInfos(List<MusicInfo> musicInfos)
{
foreach (var musicInfo in musicInfos.Where(info => !string.IsNullOrEmpty(info.Name)))
{
AddRow(musicInfo);
}
ScanTotalCount = MusicFiles.Count;
ScanProgressCount = ScanTotalCount;
ScanProgressPercentage = 100;
TotalCount = MusicFiles.Count;
}
private string RequireOutputDirectory()
{
if (!string.IsNullOrWhiteSpace(OutputDirectory))
{
return OutputDirectory;
}
var fallback = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),
DefaultOutputDirectoryName);
OutputDirectory = fallback;
return fallback;
}
private Task ShowNoMusicFilesAsync()
{
return _dialogService.ShowMessageAsync(
_localization?["Common_Info"] ?? "Info",
_localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder.");
}
private Task ShowErrorAsync(string message)
{
return _dialogService.ShowMessageAsync(_localization?["Common_Error"] ?? "Error", message);
}
// ---------------------------------------------------------------- download
[RelayCommand(CanExecute = nameof(CanStartDownload))]
private async Task StartDownloadAsync()
{
@@ -246,7 +636,6 @@ public partial class LyricsDownloadViewModel : ViewModelBase
ProgressPercentage = 0;
TotalCount = _scannedMusicInfos.Count;
// Reset all row statuses
foreach (var vm in MusicFiles)
{
vm.IsProcessed = false;
@@ -311,6 +700,57 @@ public partial class LyricsDownloadViewModel : ViewModelBase
{
_downloadCts?.Cancel();
}
/// <summary>
/// Clears the saved NetEase session so the next playlist scan asks for a fresh QR login.
/// <remarks>
/// Without this the only way to recover from an expired Cookie was to delete
/// <c>netease.session.json</c> by hand.
/// </remarks>
/// </summary>
[RelayCommand(CanExecute = nameof(IsNetEaseLoggedIn))]
private async Task SignOutNetEaseAsync()
{
_neteaseMusicScanner.ClearLoginState();
await _sessionStore.ClearAsync();
IsNetEaseLoggedIn = false;
await _dialogService.ShowMessageAsync(
_localization?["Common_Info"] ?? "Info",
_localization?["NetEase_SignedOut"] ?? "Signed out. The next playlist scan will ask for a QR login.");
}
private bool CanSignInNetEase => !IsNetEaseLoggedIn && !IsScanning && !IsDownloading;
/// <summary>
/// Let the user sign in from the page itself instead of discovering the QR dialog only after
/// pressing "Scan" - the button used to be hidden behind one specific scanner choice.
/// </summary>
[RelayCommand(CanExecute = nameof(CanSignInNetEase))]
private async Task SignInNetEaseAsync()
{
if (await LoginToNetEaseAsync())
{
IsNetEaseLoggedIn = true;
}
}
/// <summary>
/// Refresh the visible login state. Called on construction and every time the page is shown,
/// because the session may have been written by an earlier run of the app.
/// </summary>
private async Task RefreshNetEaseLoginStateAsync()
{
await RestoreNetEaseSessionAsync();
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
SignOutNetEaseCommand.NotifyCanExecuteChanged();
SignInNetEaseCommand.NotifyCanExecuteChanged();
}
public override async Task OnActivatedAsync()
{
await base.OnActivatedAsync();
await RefreshNetEaseLoginStateAsync();
}
}
public partial class MusicFileViewModel : ObservableObject
@@ -0,0 +1,134 @@
using Avalonia.Media.Imaging;
using CommunityToolkit.Mvvm.ComponentModel;
using QRCoder;
using ZonyLrcTools.Common.MusicScanner;
using ZonyLrcTools.Desktop.Infrastructure.Localization;
namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>
/// Drives the NetEase QR-code login dialog.
/// </summary>
/// <remarks>
/// Two events cross the dialog boundary in opposite directions: <see cref="CloseRequested"/>
/// lets the login flow close the window once it is done, and <see cref="Cancelled"/> fires when
/// the user closed the window first, so the caller can stop polling instead of waiting forever.
/// </remarks>
public partial class QrCodeLoginViewModel : ObservableObject
{
private readonly IUILocalizationService? _localization;
[ObservableProperty]
private Bitmap? _qrCodeImage;
[ObservableProperty]
private string _statusText = string.Empty;
[ObservableProperty]
private bool _hasImage;
/// <summary>
/// Raised when the login flow wants the dialog closed.
/// </summary>
public event EventHandler? CloseRequested;
/// <summary>
/// Raised when the user closed the dialog before logging in.
/// </summary>
public event EventHandler? Cancelled;
/// <summary>
/// True once the login succeeded; the dialog stays closable but no longer counts as a cancel.
/// </summary>
public bool IsCompleted { get; private set; }
public string LoginTitle => _localization?["NetEase_LoginTitle"] ?? "Sign in to NetEase Cloud Music";
public string LoginTip => _localization?["NetEase_LoginTip"] ?? "Scan the QR code with the NetEase Cloud Music app on your phone.";
public string CancelText => _localization?["Common_Cancel"] ?? "Cancel";
public QrCodeLoginViewModel(IUILocalizationService? localization = null)
{
_localization = localization;
_statusText = WaitText;
}
private string WaitText => _localization?["NetEase_LoginWaiting"] ?? "Waiting for you to scan...";
private string ScannedText => _localization?["NetEase_LoginScanned"] ?? "Scanned, please confirm on your phone.";
private string SuccessText => _localization?["NetEase_LoginSucceeded"] ?? "Signed in.";
/// <summary>
/// Render the QR payload the scanner produced.
/// </summary>
public void SetPayload(NetEaseQrCodePayload payload)
{
QrCodeImage = RenderQrCode(payload.Content);
HasImage = QrCodeImage != null;
StatusText = WaitText;
}
/// <summary>
/// Reflect a login-state change reported by the scanner.
/// </summary>
public void SetState(NetEaseLoginState state)
{
StatusText = state switch
{
NetEaseLoginState.ScanConfirmed => ScannedText,
NetEaseLoginState.Succeeded => SuccessText,
_ => WaitText
};
}
/// <summary>
/// Push an error message into the dialog.
/// </summary>
public void SetError(string message)
{
StatusText = message;
}
/// <summary>
/// Mark the flow as finished and close the dialog.
/// </summary>
public void Complete()
{
IsCompleted = true;
RequestClose();
}
/// <summary>
/// Ask the dialog to close.
/// </summary>
public void RequestClose()
{
CloseRequested?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Called by the dialog when its window closed, for whatever reason.
/// </summary>
public void NotifyClosed()
{
if (!IsCompleted)
{
Cancelled?.Invoke(this, EventArgs.Empty);
}
}
private static Bitmap? RenderQrCode(string content)
{
try
{
using var generator = new QRCodeGenerator();
using var data = generator.CreateQrCode(content, QRCodeGenerator.ECCLevel.M);
var pngBytes = new PngByteQRCode(data).GetGraphic(12);
return new Bitmap(new MemoryStream(pngBytes));
}
catch (Exception)
{
// A render failure shows up as the placeholder, not as a crash.
return null;
}
}
}
@@ -0,0 +1,55 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:ZonyLrcTools.Desktop.ViewModels"
x:Class="ZonyLrcTools.Desktop.Views.Dialogs.QrCodeLoginDialog"
x:DataType="vm:QrCodeLoginViewModel"
Width="380"
SizeToContent="Height"
CanResize="False"
WindowStartupLocation="CenterOwner"
ShowInTaskbar="False">
<StackPanel Margin="24" Spacing="16">
<TextBlock Text="{Binding LoginTitle}"
FontSize="16"
FontWeight="SemiBold"
TextWrapping="Wrap" />
<TextBlock Text="{Binding LoginTip}"
FontSize="12"
Opacity="0.65"
TextWrapping="Wrap" />
<!-- QR surface: fixed size so the dialog does not jump when the image arrives. -->
<Border Width="240" Height="240"
HorizontalAlignment="Center"
Background="White"
CornerRadius="8"
Padding="8">
<Panel>
<Image Source="{Binding QrCodeImage}"
Stretch="Uniform"
IsVisible="{Binding HasImage}" />
<TextBlock Text="..."
FontSize="24"
Opacity="0.3"
HorizontalAlignment="Center"
VerticalAlignment="Center"
IsVisible="{Binding !HasImage}" />
</Panel>
</Border>
<TextBlock Text="{Binding StatusText}"
FontSize="13"
HorizontalAlignment="Center"
TextWrapping="Wrap"
TextAlignment="Center" />
<Button Content="{Binding CancelText}"
HorizontalAlignment="Right"
MinWidth="88"
Click="OnCancelClick" />
</StackPanel>
</Window>
@@ -0,0 +1,47 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using ZonyLrcTools.Desktop.ViewModels;
namespace ZonyLrcTools.Desktop.Views.Dialogs;
public partial class QrCodeLoginDialog : Window
{
private QrCodeLoginViewModel? _viewModel;
public QrCodeLoginDialog()
{
InitializeComponent();
}
public QrCodeLoginDialog(QrCodeLoginViewModel viewModel) : this()
{
_viewModel = viewModel;
DataContext = viewModel;
Title = viewModel.LoginTitle;
viewModel.CloseRequested += OnCloseRequested;
Closed += OnClosed;
}
private void OnCloseRequested(object? sender, EventArgs e)
{
Close();
}
private void OnClosed(object? sender, EventArgs e)
{
if (_viewModel == null)
{
return;
}
_viewModel.CloseRequested -= OnCloseRequested;
_viewModel.NotifyClosed();
_viewModel = null;
}
private void OnCancelClick(object? sender, RoutedEventArgs e)
{
Close();
}
}
@@ -24,71 +24,181 @@
BoxShadow="0 2 8 0 #0D000000"
Padding="24,20"
Margin="0,0,0,16">
<Grid RowDefinitions="Auto,Auto,Auto,Auto" ColumnDefinitions="Auto,*,Auto"
>
<!-- Row 0: Folder Selection -->
<TextBlock Grid.Row="0" Grid.Column="0"
Text="{Binding LyricsFolderLabel}"
VerticalAlignment="Center"
FontSize="13"
FontWeight="Medium" />
<TextBox Grid.Row="0" Grid.Column="1"
Text="{Binding SelectedFolderPath}"
Watermark="{Binding LyricsSelectFolder}"
IsReadOnly="True"
Margin="16,0" />
<Button Grid.Row="0" Grid.Column="2"
Content="{Binding LyricsBrowse}"
Command="{Binding SelectFolderCommand}"
MinWidth="80"
HorizontalAlignment="Stretch" />
<StackPanel Spacing="0">
<!-- Separator -->
<Border Grid.Row="1" Grid.ColumnSpan="3"
Height="1"
<!-- Source selector -->
<Grid ColumnDefinitions="Auto,*,Auto">
<TextBlock Grid.Column="0"
Text="{Binding LyricsScannerLabel}"
VerticalAlignment="Center"
FontSize="13"
FontWeight="Medium" />
<ComboBox Grid.Column="1"
ItemsSource="{Binding ScannerNames}"
SelectedIndex="{Binding SelectedScannerIndex}"
MinWidth="200"
HorizontalAlignment="Left"
Margin="16,0" />
<Button Grid.Column="2"
Content="{Binding LyricsScan}"
Command="{Binding StartScanCommand}"
IsEnabled="{Binding CanScan}"
MinWidth="88" />
</Grid>
<Border Height="1"
Background="{DynamicResource SeparatorBrush}"
Opacity="0.5"
Margin="0,16" />
<!-- Row 2: Parallel Count + Download Button -->
<TextBlock Grid.Row="2" Grid.Column="0"
Text="{Binding LyricsParallel}"
VerticalAlignment="Center"
FontSize="13"
FontWeight="Medium" />
<NumericUpDown Grid.Row="2" Grid.Column="1"
Value="{Binding ParallelCount}"
Minimum="1"
Maximum="32"
Increment="1"
Width="100"
FormatString="0"
HorizontalAlignment="Left"
<!-- Input row: switches with the selected scanner -->
<Grid ColumnDefinitions="Auto,*,Auto" IsVisible="{Binding IsLocalScanner}">
<TextBlock Grid.Column="0"
Text="{Binding LyricsFolderLabel}"
VerticalAlignment="Center"
Margin="16,0" />
<StackPanel Grid.Row="2" Grid.Column="2"
Orientation="Horizontal" Spacing="8">
<Button Command="{Binding StartDownloadCommand}"
IsVisible="{Binding !IsDownloading}"
IsEnabled="{Binding CanStartDownload}"
Classes="accent"
MinWidth="120">
<StackPanel Orientation="Horizontal" Spacing="6">
<PathIcon Data="{StaticResource DownloadIcon}"
Width="14" Height="14" />
<TextBlock Text="{Binding LyricsStartDownload}"
VerticalAlignment="Center" />
</StackPanel>
</Button>
<Button Command="{Binding CancelDownloadCommand}"
Content="{Binding LyricsStopDownload}"
IsVisible="{Binding IsDownloading}"
MinWidth="100" />
FontSize="13"
FontWeight="Medium" />
<TextBox Grid.Column="1"
Text="{Binding SelectedFolderPath}"
Watermark="{Binding LyricsSelectFolder}"
IsReadOnly="True"
Margin="16,0" />
<Button Grid.Column="2"
Content="{Binding LyricsBrowse}"
Command="{Binding SelectFolderCommand}"
MinWidth="88"
HorizontalAlignment="Stretch" />
</Grid>
<Grid ColumnDefinitions="Auto,*,Auto" IsVisible="{Binding IsCsvScanner}">
<TextBlock Grid.Column="0"
Text="{Binding LyricsCsvLabel}"
VerticalAlignment="Center"
FontSize="13"
FontWeight="Medium" />
<TextBox Grid.Column="1"
Text="{Binding SelectedCsvFilePath}"
Watermark="{Binding LyricsCsvSelect}"
IsReadOnly="True"
Margin="16,0" />
<Button Grid.Column="2"
Content="{Binding LyricsCsvBrowse}"
Command="{Binding SelectCsvFileCommand}"
MinWidth="88"
HorizontalAlignment="Stretch" />
</Grid>
<StackPanel Spacing="8" IsVisible="{Binding IsNetEaseScanner}">
<Grid ColumnDefinitions="Auto,*,Auto">
<TextBlock Grid.Column="0"
Text="{Binding LyricsSongListLabel}"
VerticalAlignment="Center"
FontSize="13"
FontWeight="Medium" />
<TextBox Grid.Column="1"
Text="{Binding SongListIds}"
Watermark="{Binding LyricsSongListWatermark}"
Margin="16,0" />
<Button Grid.Column="2"
Classes="accent"
Content="{Binding NetEaseSignIn}"
Command="{Binding SignInNetEaseCommand}"
ToolTip.Tip="{Binding NetEaseSignInHint}"
IsVisible="{Binding !IsNetEaseLoggedIn}"
MinWidth="88" />
<Button Grid.Column="2"
Content="{Binding NetEaseSignOut}"
Command="{Binding SignOutNetEaseCommand}"
ToolTip.Tip="{Binding NetEaseSignOutHint}"
IsVisible="{Binding IsNetEaseLoggedIn}"
MinWidth="88" />
</Grid>
<!-- Account state stays visible even when this scanner is not selected, so the
sign-out entry is no longer hidden behind one dropdown value. -->
<Grid ColumnDefinitions="Auto,*,Auto">
<PathIcon Grid.Column="0"
Data="{StaticResource AccountIcon}"
Width="13"
Height="13"
VerticalAlignment="Center"
Opacity="0.55" />
<TextBlock Grid.Column="1"
Text="{Binding NetEaseAccountStatus}"
Margin="8,0,0,0"
FontSize="12"
Opacity="0.6"
TextWrapping="Wrap"
VerticalAlignment="Center" />
</Grid>
</StackPanel>
<!-- Row 3: Progress (spans all columns) -->
<StackPanel Grid.Row="3" Grid.ColumnSpan="3"
IsVisible="{Binding IsScanning}"
<!-- Output directory (only meaningful for csv / netease, but harmless for local) -->
<Grid ColumnDefinitions="Auto,*,Auto"
Margin="0,12,0,0"
IsVisible="{Binding !IsLocalScanner}">
<TextBlock Grid.Column="0"
Text="{Binding LyricsOutputLabel}"
VerticalAlignment="Center"
FontSize="13"
FontWeight="Medium" />
<TextBox Grid.Column="1"
Text="{Binding OutputDirectory}"
Watermark="{Binding LyricsOutputSelect}"
IsReadOnly="True"
Margin="16,0" />
<Button Grid.Column="2"
Content="{Binding LyricsOutputBrowse}"
Command="{Binding SelectOutputFolderCommand}"
MinWidth="88"
HorizontalAlignment="Stretch" />
</Grid>
<Border Height="1"
Background="{DynamicResource SeparatorBrush}"
Opacity="0.5"
Margin="0,16" />
<!-- Parallel count + download button -->
<Grid ColumnDefinitions="Auto,*,Auto">
<TextBlock Grid.Column="0"
Text="{Binding LyricsParallel}"
VerticalAlignment="Center"
FontSize="13"
FontWeight="Medium" />
<NumericUpDown Grid.Column="1"
Value="{Binding ParallelCount}"
Minimum="1"
Maximum="32"
Increment="1"
Width="100"
FormatString="0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="16,0" />
<StackPanel Grid.Column="2"
Orientation="Horizontal" Spacing="8">
<Button Command="{Binding StartDownloadCommand}"
IsVisible="{Binding !IsDownloading}"
IsEnabled="{Binding CanStartDownload}"
Classes="accent"
MinWidth="132">
<StackPanel Orientation="Horizontal" Spacing="6">
<PathIcon Data="{StaticResource DownloadIcon}"
Width="14" Height="14" />
<TextBlock Text="{Binding LyricsStartDownload}"
VerticalAlignment="Center" />
</StackPanel>
</Button>
<Button Command="{Binding CancelDownloadCommand}"
Content="{Binding LyricsStopDownload}"
IsVisible="{Binding IsDownloading}"
MinWidth="108" />
</StackPanel>
</Grid>
<!-- Scan progress -->
<StackPanel IsVisible="{Binding IsScanning}"
Spacing="8" Margin="0,16,0,0">
<ProgressBar Value="{Binding ScanProgressPercentage}"
Maximum="100" Height="6" />
@@ -100,8 +210,9 @@
<Run Text="{Binding ScanTotalCount}" />
</TextBlock>
</StackPanel>
<StackPanel Grid.Row="3" Grid.ColumnSpan="3"
IsVisible="{Binding IsDownloading}"
<!-- Download progress -->
<StackPanel IsVisible="{Binding IsDownloading}"
Spacing="8" Margin="0,16,0,0">
<ProgressBar Value="{Binding ProgressPercentage}"
Maximum="100" Height="6" />
@@ -111,7 +222,7 @@
<Run Text="{Binding TotalCount}" />
</TextBlock>
</StackPanel>
</Grid>
</StackPanel>
</Border>
<!-- Card 2: File List with Empty State -->
@@ -30,6 +30,8 @@
<PackageReference Include="System.Text.Encoding.CodePages" />
<!-- Localization -->
<PackageReference Include="Microsoft.Extensions.Localization" />
<!-- QR code rendering for the NetEase QR login dialog -->
<PackageReference Include="QRCoder" />
</ItemGroup>
<ItemGroup>