mirror of
https://github.com/real-zony/ZonyLrcToolsX.git
synced 2026-11-25 04:17:46 +08:00
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:
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user