mirror of
https://github.com/real-zony/ZonyLrcToolsX.git
synced 2025-09-05 04:56:52 +00:00
Compare commits
106 Commits
Alpha.2022
...
ZonyLrcToo
Author | SHA1 | Date | |
---|---|---|---|
![]() |
8d5a45c9ef | ||
![]() |
6b538f3e0a | ||
![]() |
d7e11af3ba | ||
![]() |
f25ba90b9a | ||
![]() |
bc5afad599 | ||
![]() |
34e8cf74f3 | ||
![]() |
18338d5989 | ||
![]() |
691cfa159f | ||
![]() |
7dce16fe1f | ||
![]() |
fd86a98995 | ||
![]() |
2f2e67f3e6 | ||
![]() |
a46abba2f9 | ||
![]() |
fdc5f27692 | ||
![]() |
430c66786a | ||
![]() |
75fd004c56 | ||
![]() |
ca40728387 | ||
![]() |
acb9142e5f | ||
![]() |
2c1b5ce533 | ||
![]() |
5d1e90f638 | ||
![]() |
b7b1f36bf5 | ||
![]() |
6b72f919b8 | ||
![]() |
64d26cbc4c | ||
![]() |
f9570508c2 | ||
![]() |
6d37d81015 | ||
![]() |
7778b7be09 | ||
![]() |
7adda14713 | ||
![]() |
7d17fc0b97 | ||
![]() |
3e27e18098 | ||
![]() |
895f68184d | ||
![]() |
d19b1d8d2a | ||
![]() |
a11ef70021 | ||
![]() |
6554be6b6d | ||
![]() |
0ed21ed997 | ||
![]() |
740e8f4c63 | ||
![]() |
ecab0e0f5c | ||
![]() |
aa90e232f7 | ||
![]() |
9f96aa0186 | ||
![]() |
bccfaaaa5b | ||
![]() |
f57afd4238 | ||
![]() |
775e6140ee | ||
![]() |
2ccf4f9da6 | ||
![]() |
dbc1e44d2a | ||
![]() |
cde1d32d33 | ||
![]() |
62777e44bd | ||
![]() |
6c25483f1e | ||
![]() |
b64f83d56b | ||
![]() |
6ad154a62b | ||
![]() |
32adab68b6 | ||
![]() |
ba91108ca4 | ||
![]() |
f597e24ff7 | ||
![]() |
d453d520d4 | ||
![]() |
9f254aae8e | ||
![]() |
c9fa0de95f | ||
![]() |
6d7ee04b74 | ||
![]() |
f519eb1251 | ||
![]() |
85f325b300 | ||
![]() |
140043db79 | ||
![]() |
c583a9c278 | ||
![]() |
8385f6f118 | ||
![]() |
be4380c744 | ||
![]() |
87f6a98668 | ||
![]() |
83fcc91fb8 | ||
![]() |
b4c229ccca | ||
![]() |
71302c7262 | ||
![]() |
1bec50e409 | ||
![]() |
f7cae8062c | ||
![]() |
c73f0d8eea | ||
![]() |
fe7c9115d5 | ||
![]() |
e13fb47aeb | ||
![]() |
32891d4208 | ||
![]() |
770d246787 | ||
![]() |
589151a77d | ||
![]() |
65af048f72 | ||
![]() |
99fd3b5021 | ||
![]() |
e4420e749a | ||
![]() |
5f22dafb1e | ||
![]() |
c2d8ee4341 | ||
![]() |
6a4435eb0d | ||
![]() |
346e07e9e7 | ||
![]() |
efdb3e8441 | ||
![]() |
0438433284 | ||
![]() |
d34a830660 | ||
![]() |
975f61a8e7 | ||
![]() |
8ba78c2681 | ||
![]() |
019bdb571c | ||
![]() |
a2aeed021d | ||
![]() |
0e8d361ed9 | ||
![]() |
c3b381a5f7 | ||
![]() |
8acba586b0 | ||
![]() |
5905d4b384 | ||
![]() |
2ad771e62e | ||
![]() |
403d7b151d | ||
![]() |
5c8c9af9ab | ||
![]() |
bfd23fc14e | ||
![]() |
81271a5aa5 | ||
![]() |
80a0bcdcee | ||
![]() |
172174d9e3 | ||
![]() |
d4a6a46078 | ||
![]() |
0772f5888f | ||
![]() |
950652c040 | ||
![]() |
55f720c1a1 | ||
![]() |
7463709a39 | ||
![]() |
07e660e13b | ||
![]() |
a51b399a6c | ||
![]() |
279eba48f8 | ||
![]() |
f3b1dacb0c |
63
.gitattributes
vendored
Normal file
63
.gitattributes
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
###############################################################################
|
||||
# Set default behavior to automatically normalize line endings.
|
||||
###############################################################################
|
||||
* text=auto
|
||||
|
||||
###############################################################################
|
||||
# Set default behavior for command prompt diff.
|
||||
#
|
||||
# This is need for earlier builds of msysgit that does not have it on by
|
||||
# default for csharp files.
|
||||
# Note: This is only used by command line
|
||||
###############################################################################
|
||||
#*.cs diff=csharp
|
||||
|
||||
###############################################################################
|
||||
# Set the merge driver for project and solution files
|
||||
#
|
||||
# Merging from the command prompt will add diff markers to the files if there
|
||||
# are conflicts (Merging from VS is not affected by the settings below, in VS
|
||||
# the diff markers are never inserted). Diff markers may cause the following
|
||||
# file extensions to fail to load in VS. An alternative would be to treat
|
||||
# these files as binary and thus will always conflict and require user
|
||||
# intervention with every merge. To do so, just uncomment the entries below
|
||||
###############################################################################
|
||||
#*.sln merge=binary
|
||||
#*.csproj merge=binary
|
||||
#*.vbproj merge=binary
|
||||
#*.vcxproj merge=binary
|
||||
#*.vcproj merge=binary
|
||||
#*.dbproj merge=binary
|
||||
#*.fsproj merge=binary
|
||||
#*.lsproj merge=binary
|
||||
#*.wixproj merge=binary
|
||||
#*.modelproj merge=binary
|
||||
#*.sqlproj merge=binary
|
||||
#*.wwaproj merge=binary
|
||||
|
||||
###############################################################################
|
||||
# behavior for image files
|
||||
#
|
||||
# image files are treated as binary by default.
|
||||
###############################################################################
|
||||
#*.jpg binary
|
||||
#*.png binary
|
||||
#*.gif binary
|
||||
|
||||
###############################################################################
|
||||
# diff behavior for common document formats
|
||||
#
|
||||
# Convert binary document formats to text before diffing them. This feature
|
||||
# is only available from the command line. Turn it on by uncommenting the
|
||||
# entries below.
|
||||
###############################################################################
|
||||
#*.doc diff=astextplain
|
||||
#*.DOC diff=astextplain
|
||||
#*.docx diff=astextplain
|
||||
#*.DOCX diff=astextplain
|
||||
#*.dot diff=astextplain
|
||||
#*.DOT diff=astextplain
|
||||
#*.pdf diff=astextplain
|
||||
#*.PDF diff=astextplain
|
||||
#*.rtf diff=astextplain
|
||||
#*.RTF diff=astextplain
|
64
.github/workflows/dotnet.yml
vendored
64
.github/workflows/dotnet.yml
vendored
@@ -3,23 +3,61 @@ name: .NET
|
||||
on:
|
||||
push:
|
||||
branches: [ dev ]
|
||||
paths:
|
||||
- "versions/release.md"
|
||||
pull_request:
|
||||
branches: [ dev ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v2
|
||||
with:
|
||||
dotnet-version: 6.0.x
|
||||
- name: Restore dependencies
|
||||
run: dotnet restore
|
||||
- name: Build
|
||||
run: dotnet build --no-restore
|
||||
# - name: Test
|
||||
# run: dotnet test --no-build --verbosity normal
|
||||
- name: Get build version
|
||||
id: date
|
||||
run: echo "::set-output name=date::$(date +'%Y%m%d')${{github.run_number}}"
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: true
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v2
|
||||
with:
|
||||
dotnet-version: 7.0.x
|
||||
- name: Restore dependencies
|
||||
run: dotnet restore
|
||||
- name: Publish
|
||||
working-directory: ./src/ZonyLrcTools.Cli
|
||||
run: |
|
||||
ls -a
|
||||
chmod +x ./publish.sh
|
||||
./publish.sh
|
||||
mv ./TempFiles ../../
|
||||
shell: bash
|
||||
env:
|
||||
PUBLISH_VERSION: ${{ steps.date.outputs.date }}
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: release-files
|
||||
path: |
|
||||
./TempFiles
|
||||
./versions/release.md
|
||||
outputs:
|
||||
version: ${{ steps.date.outputs.date }}
|
||||
release:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Download artifact
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: release-files
|
||||
path: .
|
||||
- name: Upload Release
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
artifacts: "./TempFiles/*.zip"
|
||||
token: ${{ secrets.GITHUBACTIONS }}
|
||||
tag: ZonyLrcToolsX_Alpha.${{ needs.build.outputs.version }}
|
||||
commit: dev
|
||||
bodyFile: ./versions/release.md
|
454
.gitignore
vendored
Normal file
454
.gitignore
vendored
Normal file
@@ -0,0 +1,454 @@
|
||||
# Created by .ignore support plugin (hsz.mobi)
|
||||
### VisualStudioCode template
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
*.code-workspace
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
### VisualStudio template
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Ww][Ii][Nn]32/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUnit
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# ASP.NET Scaffolding
|
||||
ScaffoldingReadMe.txt
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_h.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Coverlet is a free, cross platform Code Coverage Tool
|
||||
coverage*.json
|
||||
coverage*.xml
|
||||
coverage*.info
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
node_modules/
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# Ionide (cross platform F# VS Code tools) working folder
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
|
||||
### JetBrains template
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
# User-specific stuff
|
||||
.idea/**/workspace.xml
|
||||
.idea/**/tasks.xml
|
||||
.idea/**/usage.statistics.xml
|
||||
.idea/**/dictionaries
|
||||
.idea/**/shelf
|
||||
|
||||
# Generated files
|
||||
.idea/**/contentModel.xml
|
||||
|
||||
# Sensitive or high-churn files
|
||||
.idea/**/dataSources/
|
||||
.idea/**/dataSources.ids
|
||||
.idea/**/dataSources.local.xml
|
||||
.idea/**/sqlDataSources.xml
|
||||
.idea/**/dynamic.xml
|
||||
.idea/**/uiDesigner.xml
|
||||
.idea/**/dbnavigator.xml
|
||||
|
||||
# Gradle
|
||||
.idea/**/gradle.xml
|
||||
.idea/**/libraries
|
||||
|
||||
# Gradle and Maven with auto-import
|
||||
# When using Gradle or Maven with auto-import, you should exclude module files,
|
||||
# since they will be recreated, and may cause churn. Uncomment if using
|
||||
# auto-import.
|
||||
# .idea/artifacts
|
||||
# .idea/compiler.xml
|
||||
# .idea/jarRepositories.xml
|
||||
# .idea/modules.xml
|
||||
# .idea/*.iml
|
||||
# .idea/modules
|
||||
# *.iml
|
||||
# *.ipr
|
||||
|
||||
# CMake
|
||||
cmake-build-*/
|
||||
|
||||
# Mongo Explorer plugin
|
||||
.idea/**/mongoSettings.xml
|
||||
|
||||
# File-based project format
|
||||
*.iws
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Cursive Clojure plugin
|
||||
.idea/replstate.xml
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
||||
|
||||
# Editor-based Rest Client
|
||||
.idea/httpRequests
|
||||
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
.idea/
|
||||
/.idea
|
||||
/src/ZonyLrcTools.Cli/TempFiles/
|
||||
|
||||
src/ZonyLrcTools.LocalServer/UiStaticResources/*
|
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
[submodule "vendor/MusicDecrypto"]
|
||||
path = vendor/MusicDecrypto
|
||||
url = https://github.com/davidxuang/MusicDecrypto
|
55
README.md
55
README.md
@@ -24,39 +24,44 @@ macOS 和 Linux 用户请打开终端,切换到软件目录,一样执行命
|
||||
|
||||
### 子命令
|
||||
|
||||
#### 歌曲下载
|
||||
#### 歌词下载
|
||||
|
||||
子命令为 `download`,可用于下载歌词数据和专辑图像,支持多个下载器进行下载。
|
||||
|
||||
```shell
|
||||
./ZonyLrcTools.Cli.exe download -d|dir <WAIT_SCAN_DIRECTORY> [-l|--lyric] [-a|--album] [-n|--number]
|
||||
.\ZonyLrcTools.Cli.exe download -d|dir <WAIT_SCAN_DIRECTORY> [-l|--lyric] [-a|--album] [-n|--number]
|
||||
|
||||
./ZonyLrcTools.Cli.exe download -h|--help
|
||||
.\ZonyLrcTools.Cli.exe download -h|--help
|
||||
```
|
||||
|
||||
**例子**
|
||||
|
||||
```shell
|
||||
# 下载歌词
|
||||
./ZonyLrcTools.Cli.exe download -d "C:\歌曲目录" -l -n 2
|
||||
.\ZonyLrcTools.Cli.exe download -d "C:\歌曲目录" -l -n 2
|
||||
|
||||
# 下载专辑封面
|
||||
./ZonyLrcTools.Cli.exe download -d "C:\歌曲目录" -a -n 2
|
||||
.\ZonyLrcTools.Cli.exe download -d "C:\歌曲目录" -a -n 2
|
||||
```
|
||||
|
||||
#### 加密格式转换
|
||||
|
||||
子命令为 `util`,可用于转换部分加密歌曲,**仅供个人研究学习使用,思路与源码都来自于网络**。
|
||||
|
||||
目前软件支持 NCM、QCM(开发中...🚧) 格式的音乐文件转换,命令如下。
|
||||
具体支持的格式请参考项目 [MusicDecrypto](https://github.com/davidxuang/MusicDecrypto/blob/master/MusicDecrypto.Library/DecryptoFactory.cs#L23),本工具仅做一个集成,替换掉原本自己的一些实现。现在不需要指定对应的类型参数,程序会自动根据文件后缀选择适合的解密算法。
|
||||
|
||||
命令只需要一个参数 `-s`,指定需要转换的文件夹或者是文件路径。
|
||||
|
||||
```shell
|
||||
./ZonyLrcTools.Cli.exe util -t=Ncm D:\CloudMusic
|
||||
.\ZonyLrcTools.Cli.exe util -s D:\CloudMusic
|
||||
```
|
||||
|
||||
### 配置文件
|
||||
|
||||
程序的所有的配置信息,都在 `config.yaml` 进行更改,下面标注了各个配置的说明。
|
||||
|
||||
其中是否开启的可选项为 `true` 或者 `false`,等同于中文的是和否。
|
||||
|
||||
```yaml
|
||||
globalOption:
|
||||
# 允许扫描的歌曲文件后缀名。
|
||||
@@ -69,6 +74,7 @@ globalOption:
|
||||
isEnable: false # 是否启用代理。
|
||||
ip: 127.0.0.1 # 代理服务 IP 地址。
|
||||
port: 4780 # 代理服务端口号。
|
||||
updateUrl: https://api.myzony.com/lrc-tools/update # 更新检查地址。
|
||||
|
||||
# 下载器的相关参数配置。
|
||||
provider:
|
||||
@@ -95,18 +101,39 @@ globalOption:
|
||||
plugin:
|
||||
- name: NetEase # 基于网易云音乐的歌词下载器。
|
||||
priority: 1 # 优先级,升序排列,改为 -1 时禁用。
|
||||
depth: 10 # 搜索深度,值越大搜索结果越多,但搜索时间越长。
|
||||
- name: QQ # 基于 QQ 音乐的歌词下载器。
|
||||
priority: 2
|
||||
# depth: 10 # 暂时不支持。
|
||||
- name: KuGou # 基于酷狗音乐的歌词下载器。
|
||||
priority: 3
|
||||
depth: 10
|
||||
- name: KuWo # 基于酷我音乐的歌词下载器。
|
||||
priority: 4
|
||||
depth: 10
|
||||
# 歌词下载的一些共有配置参数。
|
||||
config:
|
||||
isOneLine: true # 双语歌词是否合并为一行展示。
|
||||
lineBreak: "\n" # 换行符的类型,记得使用双引号指定。
|
||||
isEnableTranslation: true # 是否启用翻译歌词。
|
||||
isSkipExistLyricFiles: false # 如果歌词文件已经存在,是否跳过这些文件。
|
||||
isOneLine: true # 双语歌词是否合并为一行展示。
|
||||
lineBreak: "\n" # 换行符的类型,记得使用双引号指定。
|
||||
isEnableTranslation: true # 是否启用翻译歌词。
|
||||
isOnlyOutputTranslation: false # 是否只输出翻译歌词。
|
||||
isSkipExistLyricFiles: false # 如果歌词文件已经存在,是否跳过这些文件。
|
||||
fileEncoding: 'utf-8' # 歌词文件的编码格式。
|
||||
```
|
||||
|
||||
#### 支持的编码格式
|
||||
|
||||
详细信息请参考: [MSDN Encoding 列表](https://learn.microsoft.com/en-us/dotnet/api/System.Text.Encoding.GetEncodings?view=net-6.0#examples),使用 `identifier and name` 作为参数值填入 `config.yaml` 文件当中的 `fileEncoding`。
|
||||
|
||||
#### 支持的歌词源
|
||||
|
||||
| 歌词源 | 默认优先级 |
|
||||
| ---------- | ---------- |
|
||||
| 网易云音乐 | 1 |
|
||||
| QQ 音乐 | 2 |
|
||||
| 酷狗音乐 | 3 |
|
||||
| 酷我音乐 | 4 |
|
||||
|
||||
### 屏蔽字典
|
||||
|
||||
屏蔽字典适用于网易云音乐歌词下载,针对某些单词,网易云音乐使用了 * 号进行屏蔽,这个时候可以使用屏蔽字典,设置歌曲名的关键词替换。例如有一首歌曲叫做 *Fucking ABC* ,这个时候网易云实际的名字是 *Fu****ing* ,用户只需要在屏蔽字典加入替换逻辑即可,例如:
|
||||
@@ -123,8 +150,12 @@ globalOption:
|
||||
|
||||
<img src="./docs/img/alipay.jpg" width="200"/><img src="./docs/img/wechat.jpg" width="200"/>
|
||||
|
||||
## Star History
|
||||
|
||||
[](https://star-history.com/#real-zony/ZonyLrcToolsX&Timeline)
|
||||
|
||||
## 路线图
|
||||
|
||||
- [x] 支持跨平台的 CLI 工具。
|
||||
- [ ] 基于 Web GUI 的操作站点。
|
||||
- [x] 基于 Web GUI 的操作站点。
|
||||
- [ ] 支持插件系统(Lua 引擎)。
|
||||
|
@@ -11,7 +11,13 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZonyLrcTools.Cli", "src\Zon
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZonyLrcTools.Tests", "tests\ZonyLrcTools.Tests\ZonyLrcTools.Tests.csproj", "{FFBD3200-568F-455B-8390-5E76C51D522C}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZonyLrcTools.LocalServer", "src\ZonyLrcTools.LocalServer\ZonyLrcTools.LocalServer.csproj", "{312A9DEF-0888-49AB-A963-64C7A2A2AF05}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZonyLrcTools.LocalServer", "src\ZonyLrcTools.LocalServer\ZonyLrcTools.LocalServer.csproj", "{2875A08A-FFD6-4863-B815-5384DCFE88FC}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZonyLrcTools.Common", "src\ZonyLrcTools.Common\ZonyLrcTools.Common.csproj", "{9B42E4CA-61AA-4798-8D2B-2D8A7035EB67}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "vendor", "vendor", "{AB0E3F21-DDBF-459D-995C-04C177BF8995}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MusicDecrypto.Library", "vendor\MusicDecrypto\MusicDecrypto.Library\MusicDecrypto.Library.csproj", "{6BB67593-38CD-42E4-8409-EDAC3C138A6B}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@@ -27,10 +33,18 @@ Global
|
||||
{FFBD3200-568F-455B-8390-5E76C51D522C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{FFBD3200-568F-455B-8390-5E76C51D522C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{FFBD3200-568F-455B-8390-5E76C51D522C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{312A9DEF-0888-49AB-A963-64C7A2A2AF05}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{312A9DEF-0888-49AB-A963-64C7A2A2AF05}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{312A9DEF-0888-49AB-A963-64C7A2A2AF05}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{312A9DEF-0888-49AB-A963-64C7A2A2AF05}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{2875A08A-FFD6-4863-B815-5384DCFE88FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{2875A08A-FFD6-4863-B815-5384DCFE88FC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{2875A08A-FFD6-4863-B815-5384DCFE88FC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2875A08A-FFD6-4863-B815-5384DCFE88FC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{9B42E4CA-61AA-4798-8D2B-2D8A7035EB67}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{9B42E4CA-61AA-4798-8D2B-2D8A7035EB67}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9B42E4CA-61AA-4798-8D2B-2D8A7035EB67}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{9B42E4CA-61AA-4798-8D2B-2D8A7035EB67}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{6BB67593-38CD-42E4-8409-EDAC3C138A6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{6BB67593-38CD-42E4-8409-EDAC3C138A6B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{6BB67593-38CD-42E4-8409-EDAC3C138A6B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{6BB67593-38CD-42E4-8409-EDAC3C138A6B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -41,6 +55,8 @@ Global
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{55D74323-ABFA-4A73-A3BF-F3E8D5DE6DE8} = {C29FB05C-54B1-4020-94D2-87E192EB2F98}
|
||||
{FFBD3200-568F-455B-8390-5E76C51D522C} = {AF8ADB2F-E46C-4DEE-8316-652D9FE1A69B}
|
||||
{312A9DEF-0888-49AB-A963-64C7A2A2AF05} = {C29FB05C-54B1-4020-94D2-87E192EB2F98}
|
||||
{2875A08A-FFD6-4863-B815-5384DCFE88FC} = {C29FB05C-54B1-4020-94D2-87E192EB2F98}
|
||||
{9B42E4CA-61AA-4798-8D2B-2D8A7035EB67} = {C29FB05C-54B1-4020-94D2-87E192EB2F98}
|
||||
{6BB67593-38CD-42E4-8409-EDAC3C138A6B} = {AB0E3F21-DDBF-459D-995C-04C177BF8995}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
@@ -1,55 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using McMaster.Extensions.CommandLineUtils;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZonyLrcTools.Cli.Config;
|
||||
using ZonyLrcTools.Cli.Infrastructure;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Album;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Extensions;
|
||||
using ZonyLrcTools.Cli.Infrastructure.IO;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Lyric;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Tag;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Threading;
|
||||
using ZonyLrcTools.Common;
|
||||
using ZonyLrcTools.Common.Album;
|
||||
using ZonyLrcTools.Common.Lyrics;
|
||||
|
||||
// ReSharper disable UnusedAutoPropertyAccessor.Global
|
||||
// ReSharper disable MemberCanBePrivate.Global
|
||||
|
||||
namespace ZonyLrcTools.Cli.Commands.SubCommand
|
||||
{
|
||||
[Command("download", Description = "下载歌词文件或专辑图像。")]
|
||||
public class DownloadCommand : ToolCommandBase
|
||||
{
|
||||
private readonly ILogger<DownloadCommand> _logger;
|
||||
private readonly IFileScanner _fileScanner;
|
||||
private readonly ITagLoader _tagLoader;
|
||||
private readonly IEnumerable<ILyricDownloader> _lyricDownloaderList;
|
||||
private readonly IEnumerable<IAlbumDownloader> _albumDownloaderList;
|
||||
private readonly ILyricsDownloader _lyricsDownloader;
|
||||
private readonly IAlbumDownloader _albumDownloader;
|
||||
private readonly IMusicInfoLoader _musicInfoLoader;
|
||||
|
||||
private readonly ToolOptions _options;
|
||||
|
||||
public DownloadCommand(ILogger<DownloadCommand> logger,
|
||||
IFileScanner fileScanner,
|
||||
IOptions<ToolOptions> options,
|
||||
ITagLoader tagLoader,
|
||||
IEnumerable<ILyricDownloader> lyricDownloaderList,
|
||||
IEnumerable<IAlbumDownloader> albumDownloaderList)
|
||||
public DownloadCommand(ILyricsDownloader lyricsDownloader,
|
||||
IMusicInfoLoader musicInfoLoader,
|
||||
IAlbumDownloader albumDownloader)
|
||||
{
|
||||
_logger = logger;
|
||||
_fileScanner = fileScanner;
|
||||
_tagLoader = tagLoader;
|
||||
_lyricDownloaderList = lyricDownloaderList;
|
||||
_albumDownloaderList = albumDownloaderList;
|
||||
_options = options.Value;
|
||||
_lyricsDownloader = lyricsDownloader;
|
||||
_musicInfoLoader = musicInfoLoader;
|
||||
_albumDownloader = albumDownloader;
|
||||
}
|
||||
|
||||
#region > Options <
|
||||
|
||||
[Option("-d|--dir", CommandOptionType.SingleValue, Description = "指定需要扫描的目录。")]
|
||||
[DirectoryExists]
|
||||
public string Directory { get; set; }
|
||||
public string SongsDirectory { get; set; }
|
||||
|
||||
[Option("-l|--lyric", CommandOptionType.NoValue, Description = "指定程序需要下载歌词文件。")]
|
||||
public bool DownloadLyric { get; set; }
|
||||
@@ -64,202 +44,17 @@ namespace ZonyLrcTools.Cli.Commands.SubCommand
|
||||
|
||||
protected override async Task<int> OnExecuteAsync(CommandLineApplication app)
|
||||
{
|
||||
var files = await ScanMusicFilesAsync();
|
||||
var musicInfos = await LoadMusicInfoAsync(files);
|
||||
|
||||
if (DownloadLyric)
|
||||
{
|
||||
await DownloadLyricFilesAsync(musicInfos);
|
||||
await _lyricsDownloader.DownloadAsync(await _musicInfoLoader.LoadAsync(SongsDirectory, ParallelNumber), ParallelNumber);
|
||||
}
|
||||
|
||||
if (DownloadAlbum)
|
||||
{
|
||||
await DownloadAlbumAsync(musicInfos);
|
||||
await _albumDownloader.DownloadAsync(await _musicInfoLoader.LoadAsync(SongsDirectory, ParallelNumber), ParallelNumber);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async Task<List<string>> ScanMusicFilesAsync()
|
||||
{
|
||||
var files = (await _fileScanner.ScanAsync(Directory, _options.SupportFileExtensions))
|
||||
.SelectMany(t => t.FilePaths)
|
||||
.ToList();
|
||||
|
||||
if (files.Count == 0)
|
||||
{
|
||||
_logger.LogError("没有找到任何音乐文件。");
|
||||
throw new ErrorCodeException(ErrorCodes.NoFilesWereScanned);
|
||||
}
|
||||
|
||||
files = RemoveExistLyricFiles(files);
|
||||
|
||||
_logger.LogInformation($"已经扫描到了 {files.Count} 个音乐文件。");
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
private List<string> RemoveExistLyricFiles(List<string> filePaths)
|
||||
{
|
||||
if (!_options.Provider.Lyric.Config.IsSkipExistLyricFiles)
|
||||
{
|
||||
return filePaths;
|
||||
}
|
||||
|
||||
return filePaths
|
||||
.Where(path =>
|
||||
{
|
||||
if (!File.Exists(Path.ChangeExtension(path, ".lrc")))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
_logger.LogWarning($"已经存在歌词文件 {path},跳过。");
|
||||
return false;
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private async Task<ImmutableList<MusicInfo>> LoadMusicInfoAsync(IReadOnlyCollection<string> files)
|
||||
{
|
||||
_logger.LogInformation("开始加载音乐文件的标签信息...");
|
||||
|
||||
var warpTask = new WarpTask(ParallelNumber);
|
||||
var warpTaskList = files.Select(file => warpTask.RunAsync(() => Task.Run(async () => await _tagLoader.LoadTagAsync(file))));
|
||||
var result = (await Task.WhenAll(warpTaskList))
|
||||
.Where(m => m != null)
|
||||
.Where(m => !string.IsNullOrEmpty(m.Name) || !string.IsNullOrEmpty(m.Artist));
|
||||
|
||||
_logger.LogInformation($"已成功加载 {files.Count} 个音乐文件的标签信息。");
|
||||
|
||||
return result.ToImmutableList();
|
||||
}
|
||||
|
||||
private IEnumerable<ILyricDownloader> GetLyricDownloaderList()
|
||||
{
|
||||
var downloader = _options.Provider.Lyric.Plugin
|
||||
.Where(op => op.Priority != -1)
|
||||
.OrderBy(op => op.Priority)
|
||||
.Join(_lyricDownloaderList,
|
||||
op => op.Name,
|
||||
loader => loader.DownloaderName,
|
||||
(op, loader) => loader);
|
||||
|
||||
return downloader;
|
||||
}
|
||||
|
||||
#region > Lyric download logic <
|
||||
|
||||
private async ValueTask DownloadLyricFilesAsync(ImmutableList<MusicInfo> musicInfos)
|
||||
{
|
||||
_logger.LogInformation("开始下载歌词文件数据...");
|
||||
|
||||
var downloaderList = GetLyricDownloaderList();
|
||||
var warpTask = new WarpTask(ParallelNumber);
|
||||
var warpTaskList = musicInfos.Select(info =>
|
||||
warpTask.RunAsync(() => Task.Run(async () => await DownloadLyricTaskLogicAsync(downloaderList, info))));
|
||||
|
||||
await Task.WhenAll(warpTaskList);
|
||||
|
||||
_logger.LogInformation($"歌词数据下载完成,成功: {musicInfos.Count} 失败{musicInfos.Count - musicInfos.Count(m => m.IsSuccessful)}。");
|
||||
}
|
||||
|
||||
private async Task DownloadLyricTaskLogicAsync(IEnumerable<ILyricDownloader> downloaderList, MusicInfo info)
|
||||
{
|
||||
async Task InternalDownloadLogicAsync(ILyricDownloader downloader)
|
||||
{
|
||||
try
|
||||
{
|
||||
var lyric = await downloader.DownloadAsync(info.Name, info.Artist);
|
||||
var lyricFilePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!,
|
||||
$"{Path.GetFileNameWithoutExtension(info.FilePath)}.lrc");
|
||||
|
||||
if (File.Exists(lyricFilePath))
|
||||
{
|
||||
File.Delete(lyricFilePath);
|
||||
}
|
||||
|
||||
if (lyric.IsPruneMusic)
|
||||
{
|
||||
info.IsSuccessful = true;
|
||||
}
|
||||
|
||||
await using var stream = new FileStream(lyricFilePath, FileMode.Create);
|
||||
await using var sw = new StreamWriter(stream);
|
||||
await sw.WriteAsync(lyric.ToString());
|
||||
await sw.FlushAsync();
|
||||
}
|
||||
catch (ErrorCodeException ex)
|
||||
{
|
||||
if (ex.ErrorCode == ErrorCodes.NoMatchingSong)
|
||||
{
|
||||
info.IsSuccessful = false;
|
||||
}
|
||||
|
||||
_logger.LogWarningInfo(ex);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"下载歌词文件时发生错误:{ex.Message},歌曲名: {info.Name},歌手: {info.Artist}。");
|
||||
info.IsSuccessful = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
info.IsSuccessful = true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var downloader in downloaderList)
|
||||
{
|
||||
await InternalDownloadLogicAsync(downloader);
|
||||
|
||||
if (info.IsSuccessful)
|
||||
{
|
||||
_logger.LogSuccessful(info);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region > Ablum image download logic <
|
||||
|
||||
private async ValueTask DownloadAlbumAsync(ImmutableList<MusicInfo> musicInfos)
|
||||
{
|
||||
_logger.LogInformation("开始下载专辑图像数据...");
|
||||
|
||||
var downloader = _albumDownloaderList.FirstOrDefault(d => d.DownloaderName == InternalAlbumDownloaderNames.NetEase);
|
||||
var warpTask = new WarpTask(ParallelNumber);
|
||||
var warpTaskList = musicInfos.Select(info =>
|
||||
warpTask.RunAsync(() => Task.Run(async () => await DownloadAlbumTaskLogicAsync(downloader, info))));
|
||||
|
||||
await Task.WhenAll(warpTaskList);
|
||||
|
||||
_logger.LogInformation($"专辑数据下载完成,成功: {musicInfos.Count(m => m.IsSuccessful)} 失败{musicInfos.Count(m => !m.IsSuccessful)}。");
|
||||
}
|
||||
|
||||
private async Task DownloadAlbumTaskLogicAsync(IAlbumDownloader downloader, MusicInfo info)
|
||||
{
|
||||
_logger.LogSuccessful(info);
|
||||
|
||||
try
|
||||
{
|
||||
var album = await downloader.DownloadAsync(info.Name, info.Artist);
|
||||
var filePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!, $"{Path.GetFileNameWithoutExtension(info.FilePath)}.png");
|
||||
if (File.Exists(filePath) || album.Length <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await new FileStream(filePath, FileMode.Create).WriteBytesToFileAsync(album, 1024);
|
||||
}
|
||||
catch (ErrorCodeException ex)
|
||||
{
|
||||
_logger.LogWarningInfo(ex);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
29
src/ZonyLrcTools.Cli/Commands/SubCommand/SearchCommand.cs
Normal file
29
src/ZonyLrcTools.Cli/Commands/SubCommand/SearchCommand.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using System.Threading.Tasks;
|
||||
using McMaster.Extensions.CommandLineUtils;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Commands.SubCommand;
|
||||
|
||||
[Command("search", Description = "手动指定信息,用于搜索歌词数据。")]
|
||||
public class SearchCommand : ToolCommandBase
|
||||
{
|
||||
private readonly ILogger<SearchCommand> _logger;
|
||||
|
||||
#region > Options <
|
||||
|
||||
public string Name { get; set; }
|
||||
|
||||
public string Artist { get; set; }
|
||||
|
||||
#endregion
|
||||
|
||||
public SearchCommand(ILogger<SearchCommand> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override Task<int> OnExecuteAsync(CommandLineApplication app)
|
||||
{
|
||||
return base.OnExecuteAsync(app);
|
||||
}
|
||||
}
|
@@ -1,24 +1,16 @@
|
||||
using System;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using McMaster.Extensions.CommandLineUtils;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Cli.Infrastructure.IO;
|
||||
using ZonyLrcTools.Cli.Infrastructure.MusicDecryption;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Threading;
|
||||
using MusicDecrypto.Library;
|
||||
using ZonyLrcTools.Common.Infrastructure.IO;
|
||||
using ZonyLrcTools.Common.Infrastructure.Threading;
|
||||
using ZonyLrcTools.Common.MusicDecryption;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Commands.SubCommand
|
||||
{
|
||||
public enum SupportFileType
|
||||
{
|
||||
Ncm = 1,
|
||||
Qcm = 2
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 工具类相关命令。
|
||||
/// </summary>
|
||||
@@ -28,13 +20,9 @@ namespace ZonyLrcTools.Cli.Commands.SubCommand
|
||||
private readonly ILogger<UtilityCommand> _logger;
|
||||
private readonly IMusicDecryptor _musicDecryptor;
|
||||
|
||||
[Required(ErrorMessage = "音乐格式为必须参数,请指定 -t 参数。")]
|
||||
[Option("-t|--type", CommandOptionType.SingleValue, Description = "需要转换的文件格式,参数[Ncm、Qcm]。", ShowInHelpText = true)]
|
||||
public SupportFileType Type { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "文件路径为必须按参数,请传入有效路径。")]
|
||||
[Argument(0, "FilePath", "指定需要转换的音乐文件路径,支持目录和文件路径。")]
|
||||
public string FilePath { get; set; }
|
||||
[Required(ErrorMessage = "请指定需要解密的歌曲文件或文件夹路径。")]
|
||||
[Option("-s|--source", CommandOptionType.SingleValue, Description = "需要解密的歌曲文件或文件夹路径。", ShowInHelpText = true)]
|
||||
public string Source { get; set; }
|
||||
|
||||
private readonly IFileScanner _fileScanner;
|
||||
|
||||
@@ -49,57 +37,41 @@ namespace ZonyLrcTools.Cli.Commands.SubCommand
|
||||
|
||||
protected override async Task<int> OnExecuteAsync(CommandLineApplication app)
|
||||
{
|
||||
if (Directory.Exists(FilePath))
|
||||
if (Directory.Exists(Source))
|
||||
{
|
||||
_logger.LogInformation("开始扫描文件夹,请稍等...");
|
||||
|
||||
var files = (await _fileScanner.ScanAsync(FilePath, new[] { "*.ncm" }))
|
||||
var files = (await _fileScanner.ScanAsync(Source, DecryptoFactory.KnownExtensions.Select(x => $"*{x}")))
|
||||
.SelectMany(f => f.FilePaths)
|
||||
.ToList();
|
||||
|
||||
_logger.LogInformation($"扫描完成,共 {files.Count} 个文件,准备转换。");
|
||||
|
||||
var wrapTask = new WarpTask(4);
|
||||
var tasks = files.Select(path => wrapTask.RunAsync(() => Convert(path)));
|
||||
var tasks = files.Select(path => wrapTask.RunAsync(async () =>
|
||||
{
|
||||
_logger.LogInformation($"开始转换文件:{path}");
|
||||
var result = await _musicDecryptor.ConvertMusicAsync(path);
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
_logger.LogInformation($"转换完成,文件保存在:{result.OutputFilePath}");
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError($"转换失败,原因:{result.ErrorMessage}");
|
||||
}
|
||||
}));
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
else if (File.Exists(FilePath))
|
||||
else if (File.Exists(Source))
|
||||
{
|
||||
await Convert(FilePath);
|
||||
await _musicDecryptor.ConvertMusicAsync(Source);
|
||||
}
|
||||
|
||||
_logger.LogInformation("所有文件已经转换完成...");
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async Task Convert(string filePath)
|
||||
{
|
||||
if (Type != SupportFileType.Ncm)
|
||||
{
|
||||
throw new ErrorCodeException(ErrorCodes.OnlySupportNcmFormatFile);
|
||||
}
|
||||
|
||||
var memoryStream = new MemoryStream();
|
||||
await using var file = File.Open(filePath, FileMode.Open);
|
||||
{
|
||||
var buffer = new Memory<byte>(new byte[2048]);
|
||||
while (await file.ReadAsync(buffer) > 0)
|
||||
{
|
||||
// TODO: Large Object Issue!!!!!
|
||||
await memoryStream.WriteAsync(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Large Object Issue!!!!!
|
||||
var result = await _musicDecryptor.ConvertMusic(memoryStream.ToArray());
|
||||
var newFileName = Path.Combine(Path.GetDirectoryName(filePath),
|
||||
$"{Path.GetFileNameWithoutExtension(filePath)}.{((JObject)result.ExtensionObjects["JSON"]).SelectToken("$.format").Value<string>()}");
|
||||
|
||||
await using var musicFileStream = File.Create(newFileName);
|
||||
await musicFileStream.WriteAsync(result.Data);
|
||||
await musicFileStream.FlushAsync();
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,17 +0,0 @@
|
||||
using ZonyLrcTools.Cli.Infrastructure.Lyric;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Tag;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Config;
|
||||
|
||||
public class ProviderOption
|
||||
{
|
||||
/// <summary>
|
||||
/// 标签加载器相关的配置属性。
|
||||
/// </summary>
|
||||
public TagOption Tag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 歌词下载相关的配置信息。
|
||||
/// </summary>
|
||||
public LyricOption Lyric { get; set; }
|
||||
}
|
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Logging;
|
||||
|
||||
public class SerilogWarpLogger : IWarpLogger, ITransientDependency
|
||||
{
|
||||
private readonly ILogger<SerilogWarpLogger> _logger;
|
||||
|
||||
public SerilogWarpLogger(ILogger<SerilogWarpLogger> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task DebugAsync(string message, Exception exception = null)
|
||||
{
|
||||
_logger.LogDebug(message, exception);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task InfoAsync(string message, Exception exception = null)
|
||||
{
|
||||
_logger.LogInformation(message, exception);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task WarnAsync(string message, Exception exception = null)
|
||||
{
|
||||
_logger.LogWarning(message, exception);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task ErrorAsync(string message, Exception exception = null)
|
||||
{
|
||||
_logger.LogError(message, exception);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
@@ -1,23 +0,0 @@
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
{
|
||||
/// <summary>
|
||||
/// 构建 <see cref="LyricItemCollection"/> 对象的工厂。
|
||||
/// </summary>
|
||||
public interface ILyricItemCollectionFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// 根据指定的歌曲数据构建新的 <see cref="LyricItemCollection"/> 实例。
|
||||
/// </summary>
|
||||
/// <param name="sourceLyric">原始歌词数据。</param>
|
||||
/// <returns>构建完成的 <see cref="LyricItemCollection"/> 对象。</returns>
|
||||
LyricItemCollection Build(string sourceLyric);
|
||||
|
||||
/// <summary>
|
||||
/// 根据指定的歌曲数据构建新的 <see cref="LyricItemCollection"/> 实例。
|
||||
/// </summary>
|
||||
/// <param name="sourceLyric">原始歌词数据。</param>
|
||||
/// <param name="translationLyric">翻译歌词数据。</param>
|
||||
/// <returns>构建完成的 <see cref="LyricItemCollection"/> 对象。</returns>
|
||||
LyricItemCollection Build(string sourceLyric, string translationLyric);
|
||||
}
|
||||
}
|
@@ -1,7 +0,0 @@
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
{
|
||||
public interface ILyricTextResolver
|
||||
{
|
||||
LyricItemCollection Resolve(string lyricText);
|
||||
}
|
||||
}
|
@@ -1,15 +0,0 @@
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
{
|
||||
public class LyricDownloaderArgs
|
||||
{
|
||||
public string SongName { get; set; }
|
||||
|
||||
public string Artist { get; set; }
|
||||
|
||||
public LyricDownloaderArgs(string songName, string artist)
|
||||
{
|
||||
SongName = songName;
|
||||
Artist = artist;
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,63 +0,0 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZonyLrcTools.Cli.Config;
|
||||
using ZonyLrcTools.Cli.Infrastructure.DependencyInject;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
{
|
||||
/// <summary>
|
||||
/// <see cref="ILyricItemCollectionFactory"/> 的默认实现。
|
||||
/// </summary>
|
||||
public class LyricItemCollectionFactory : ILyricItemCollectionFactory, ITransientDependency
|
||||
{
|
||||
private readonly ToolOptions _options;
|
||||
|
||||
public LyricItemCollectionFactory(IOptions<ToolOptions> options)
|
||||
{
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
public LyricItemCollection Build(string sourceLyric)
|
||||
{
|
||||
var lyric = new LyricItemCollection(_options.Provider.Lyric.Config);
|
||||
if (string.IsNullOrEmpty(sourceLyric))
|
||||
{
|
||||
return lyric;
|
||||
}
|
||||
|
||||
InternalBuildLyricObject(lyric, sourceLyric);
|
||||
|
||||
return lyric;
|
||||
}
|
||||
|
||||
public LyricItemCollection Build(string sourceLyric, string translationLyric)
|
||||
{
|
||||
var lyric = new LyricItemCollection(_options.Provider.Lyric.Config);
|
||||
if (string.IsNullOrEmpty(sourceLyric))
|
||||
{
|
||||
return lyric;
|
||||
}
|
||||
|
||||
lyric = InternalBuildLyricObject(lyric, sourceLyric);
|
||||
|
||||
if (_options.Provider.Lyric.Config.IsEnableTranslation && !string.IsNullOrEmpty(translationLyric))
|
||||
{
|
||||
var translatedLyric = InternalBuildLyricObject(new LyricItemCollection(_options.Provider.Lyric.Config), translationLyric);
|
||||
return lyric + translatedLyric;
|
||||
}
|
||||
|
||||
return lyric;
|
||||
}
|
||||
|
||||
private LyricItemCollection InternalBuildLyricObject(LyricItemCollection lyric, string sourceText)
|
||||
{
|
||||
var regex = new Regex(@"\[\d+:\d+.\d+\].+\n?");
|
||||
foreach (Match match in regex.Matches(sourceText))
|
||||
{
|
||||
lyric.Add(new LyricItem(match.Value));
|
||||
}
|
||||
|
||||
return lyric;
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,42 +0,0 @@
|
||||
using System.Text;
|
||||
using System.Web;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.QQMusic.JsonModel
|
||||
{
|
||||
public class SongSearchRequest
|
||||
{
|
||||
[JsonProperty("remoteplace")] public string RemotePlace { get; set; }
|
||||
|
||||
[JsonProperty("p")] public int Page { get; set; }
|
||||
|
||||
[JsonProperty("n")] public int Limit { get; set; }
|
||||
|
||||
[JsonProperty("w")] public string Keyword { get; set; }
|
||||
|
||||
[JsonProperty("format")] public string ResultFormat { get; set; }
|
||||
|
||||
[JsonProperty("inCharset")] public string InCharset { get; set; }
|
||||
|
||||
[JsonProperty("outCharset")] public string OutCharset { get; set; }
|
||||
|
||||
[JsonProperty("platform")] public string Platform { get; set; }
|
||||
|
||||
|
||||
protected SongSearchRequest()
|
||||
{
|
||||
RemotePlace = "txt.yqq.song";
|
||||
Page = 1;
|
||||
Limit = 5;
|
||||
ResultFormat = "json";
|
||||
InCharset = "utf8";
|
||||
OutCharset = "utf8";
|
||||
Platform = "yqq";
|
||||
}
|
||||
|
||||
public SongSearchRequest(string musicName, string artistName) : this()
|
||||
{
|
||||
Keyword = HttpUtility.UrlEncode($"{musicName}+{artistName}", Encoding.UTF8);
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,16 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.MusicDecryption
|
||||
{
|
||||
public class DecryptionResult
|
||||
{
|
||||
public byte[] Data { get; protected set; }
|
||||
|
||||
public Dictionary<string, object> ExtensionObjects { get; set; }
|
||||
|
||||
public DecryptionResult(byte[] data)
|
||||
{
|
||||
Data = data;
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,17 +0,0 @@
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// 音乐解密器,用于将加密的歌曲数据,转换为可识别的歌曲格式。
|
||||
/// </summary>
|
||||
public interface IMusicDecryptor
|
||||
{
|
||||
/// <summary>
|
||||
/// 将加密数据转换为可识别的歌曲格式。
|
||||
/// </summary>
|
||||
/// <param name="sourceBytes">源加密的歌曲数据。</param>
|
||||
/// <returns>解密完成的歌曲数据。</returns>
|
||||
Task<DecryptionResult> ConvertMusic(byte[] sourceBytes);
|
||||
}
|
||||
}
|
@@ -1,184 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using ZonyLrcTools.Cli.Infrastructure.DependencyInject;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// NCM 音乐转换器,用于将 NCM 格式的音乐转换为可播放的格式。
|
||||
/// </summary>
|
||||
public class NcmMusicDecryptor : IMusicDecryptor, ITransientDependency
|
||||
{
|
||||
protected readonly byte[] AesCoreKey = { 0x68, 0x7A, 0x48, 0x52, 0x41, 0x6D, 0x73, 0x6F, 0x35, 0x6B, 0x49, 0x6E, 0x62, 0x61, 0x78, 0x57 };
|
||||
protected readonly byte[] AesModifyKey = { 0x23, 0x31, 0x34, 0x6C, 0x6A, 0x6B, 0x5F, 0x21, 0x5C, 0x5D, 0x26, 0x30, 0x55, 0x3C, 0x27, 0x28 };
|
||||
|
||||
public async Task<DecryptionResult> ConvertMusic(byte[] sourceBytes)
|
||||
{
|
||||
var stream = new MemoryStream(sourceBytes);
|
||||
var streamReader = new BinaryReader(stream);
|
||||
|
||||
var lengthBytes = new byte[4];
|
||||
lengthBytes = streamReader.ReadBytes(4);
|
||||
if (BitConverter.ToInt32(lengthBytes) != 0x4e455443)
|
||||
{
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
lengthBytes = streamReader.ReadBytes(4);
|
||||
if (BitConverter.ToInt32(lengthBytes) != 0x4d414446)
|
||||
{
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
stream.Seek(2, SeekOrigin.Current);
|
||||
stream.Read(lengthBytes);
|
||||
|
||||
var keyBytes = new byte[BitConverter.ToInt32(lengthBytes)];
|
||||
stream.Read(keyBytes);
|
||||
|
||||
// 对已经加密的数据进行异或操作。
|
||||
for (int i = 0; i < keyBytes.Length; i++)
|
||||
{
|
||||
keyBytes[i] ^= 0x64;
|
||||
}
|
||||
|
||||
var coreKeyBytes = GetBytesByOffset(DecryptAes128Ecb(AesCoreKey, keyBytes), 17);
|
||||
|
||||
var modifyDataBytes = new byte[streamReader.ReadInt32()];
|
||||
stream.Read(modifyDataBytes);
|
||||
for (int i = 0; i < modifyDataBytes.Length; i++)
|
||||
{
|
||||
modifyDataBytes[i] ^= 0x63;
|
||||
}
|
||||
|
||||
var decryptBase64Bytes = Convert.FromBase64String(Encoding.UTF8.GetString(GetBytesByOffset(modifyDataBytes, 22)));
|
||||
var decryptModifyData = DecryptAes128Ecb(AesModifyKey, decryptBase64Bytes);
|
||||
|
||||
var musicInfoJson = JObject.Parse(Encoding.UTF8.GetString(GetBytesByOffset(decryptModifyData, 6)));
|
||||
|
||||
// CRC 校验
|
||||
stream.Seek(4, SeekOrigin.Current);
|
||||
stream.Seek(5, SeekOrigin.Current);
|
||||
|
||||
GetAlbumImageBytes(stream, streamReader);
|
||||
|
||||
var sBox = BuildKeyBox(coreKeyBytes);
|
||||
return new DecryptionResult(GetMusicBytes(sBox, stream).ToArray())
|
||||
{
|
||||
ExtensionObjects = new Dictionary<string, object>
|
||||
{
|
||||
{ "JSON", musicInfoJson }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private byte[] GetBytesByOffset(byte[] srcBytes, int offset = 0)
|
||||
{
|
||||
var resultBytes = new byte[srcBytes.Length - offset];
|
||||
Array.Copy(srcBytes, offset, resultBytes, 0, srcBytes.Length - offset);
|
||||
return resultBytes;
|
||||
}
|
||||
|
||||
private byte[] DecryptAes128Ecb(byte[] keyBytes, byte[] data)
|
||||
{
|
||||
var aes = Aes.Create();
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
aes.Mode = CipherMode.ECB;
|
||||
using var decryptor = aes.CreateDecryptor(keyBytes, null);
|
||||
var result = decryptor.TransformFinalBlock(data, 0, data.Length);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// RC4 加密,生成 KeyBox。
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
private byte[] BuildKeyBox(byte[] key)
|
||||
{
|
||||
byte[] box = new byte[256];
|
||||
for (int i = 0; i < 256; ++i)
|
||||
{
|
||||
box[i] = (byte)i;
|
||||
}
|
||||
|
||||
byte keyLength = (byte)key.Length;
|
||||
byte c;
|
||||
byte lastByte = 0;
|
||||
byte keyOffset = 0;
|
||||
byte swap;
|
||||
|
||||
for (int i = 0; i < 256; ++i)
|
||||
{
|
||||
swap = box[i];
|
||||
c = (byte)((swap + lastByte + key[keyOffset++]) & 0xff);
|
||||
|
||||
if (keyOffset >= keyLength)
|
||||
{
|
||||
keyOffset = 0;
|
||||
}
|
||||
|
||||
box[i] = box[c];
|
||||
box[c] = swap;
|
||||
lastByte = c;
|
||||
}
|
||||
|
||||
return box;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获得歌曲的专辑图像信息。
|
||||
/// </summary>
|
||||
/// <param name="stream">原始文件流。</param>
|
||||
/// <param name="streamReader">二进制读取器。</param>
|
||||
private byte[] GetAlbumImageBytes(Stream stream, BinaryReader streamReader)
|
||||
{
|
||||
var imgLength = streamReader.ReadInt32();
|
||||
|
||||
if (imgLength <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var imgBuffer = streamReader.ReadBytes(imgLength);
|
||||
|
||||
return imgBuffer;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获得歌曲的完整数据。
|
||||
/// </summary>
|
||||
/// <param name="sBox"></param>
|
||||
/// <param name="stream">原始文件流。</param>
|
||||
private MemoryStream GetMusicBytes(byte[] sBox, Stream stream)
|
||||
{
|
||||
var n = 0x8000;
|
||||
var memoryStream = new MemoryStream();
|
||||
|
||||
while (true)
|
||||
{
|
||||
var tb = new byte[n];
|
||||
var result = stream.Read(tb);
|
||||
if (result <= 0) break;
|
||||
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var j = (byte)((i + 1) & 0xff);
|
||||
tb[i] ^= sBox[sBox[j] + sBox[(sBox[j] + j) & 0xff] & 0xff];
|
||||
}
|
||||
|
||||
memoryStream.Write(tb);
|
||||
}
|
||||
|
||||
memoryStream.Flush();
|
||||
|
||||
return memoryStream;
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,25 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using YamlDotNet.Serialization;
|
||||
using ZonyLrcTools.Cli.Config;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Tag
|
||||
{
|
||||
public class TagInfoProviderOption
|
||||
{
|
||||
public string Name { get; set; }
|
||||
|
||||
public int Priority { get; set; }
|
||||
|
||||
public Dictionary<string, string> Extensions { get; set; }
|
||||
}
|
||||
|
||||
public class TagOption
|
||||
{
|
||||
public IEnumerable<TagInfoProviderOption> Plugin { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 屏蔽词功能相关配置。
|
||||
/// </summary>
|
||||
public BlockWordOption BlockWord { get; set; }
|
||||
}
|
||||
}
|
26
src/ZonyLrcTools.Cli/Infrastructure/UpdaterHostedService.cs
Normal file
26
src/ZonyLrcTools.Cli/Infrastructure/UpdaterHostedService.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using ZonyLrcTools.Common.Updater;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure;
|
||||
|
||||
public class UpdaterHostedService : IHostedService
|
||||
{
|
||||
private readonly IUpdater _updater;
|
||||
|
||||
public UpdaterHostedService(IUpdater updater)
|
||||
{
|
||||
_updater = updater;
|
||||
}
|
||||
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await _updater.CheckUpdateAsync();
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using McMaster.Extensions.CommandLineUtils;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@@ -10,9 +11,11 @@ using Serilog.Events;
|
||||
using Serilog.Sinks.SystemConsole.Themes;
|
||||
using ZonyLrcTools.Cli.Commands;
|
||||
using ZonyLrcTools.Cli.Commands.SubCommand;
|
||||
using ZonyLrcTools.Cli.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Cli.Infrastructure;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Logging;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
|
||||
namespace ZonyLrcTools.Cli
|
||||
{
|
||||
@@ -23,6 +26,8 @@ namespace ZonyLrcTools.Cli
|
||||
{
|
||||
public static async Task<int> Main(string[] args)
|
||||
{
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
|
||||
ConfigureLogger();
|
||||
ConfigureErrorMessage();
|
||||
|
||||
@@ -83,8 +88,10 @@ namespace ZonyLrcTools.Cli
|
||||
{
|
||||
services.AddSingleton(PhysicalConsole.Singleton);
|
||||
services.BeginAutoDependencyInject<Program>();
|
||||
services.BeginAutoDependencyInject<IWarpHttpClient>();
|
||||
services.ConfigureConfiguration();
|
||||
services.ConfigureToolService();
|
||||
services.AddHostedService<UpdaterHostedService>();
|
||||
})
|
||||
.RunCommandLineApplicationAsync<Program>(args);
|
||||
}
|
||||
@@ -94,7 +101,8 @@ namespace ZonyLrcTools.Cli
|
||||
switch (ex)
|
||||
{
|
||||
case ErrorCodeException exception:
|
||||
Log.Logger.Error($"出现了未处理的异常。\n错误代码: {exception.ErrorCode}\n错误信息: {ErrorCodeHelper.GetMessage(exception.ErrorCode)}\n原始信息:{exception.Message}\n调用栈:{exception.StackTrace}");
|
||||
Log.Logger.Error(
|
||||
$"出现了未处理的异常。\n错误代码: {exception.ErrorCode}\n错误信息: {ErrorCodeHelper.GetMessage(exception.ErrorCode)}\n原始信息:{exception.Message}\n调用栈:{exception.StackTrace}");
|
||||
Environment.Exit(exception.ErrorCode);
|
||||
return exception.ErrorCode;
|
||||
case { } unknownException:
|
||||
|
@@ -3,7 +3,8 @@
|
||||
"10001": "待搜索的后缀不能为空。",
|
||||
"10002": "需要扫描的目录不存在,请确认路径是否正确。",
|
||||
"10003": "不能获取文件的后缀信息。",
|
||||
"10004": "没有扫描到任何音乐文件。"
|
||||
"10004": "没有扫描到任何音乐文件。",
|
||||
"10005": "指定的编码不受支持,请检查配置,所有受支持的编码名称,请参考: https://docs.microsoft.com/en-us/dotnet/api/system.text.encodinginfo.codepage?view=net-6.0#system-text-encodinginfo-codepage。"
|
||||
},
|
||||
"Warning": {
|
||||
"50001": "扫描文件时出现了错误。",
|
||||
|
@@ -1,41 +1,45 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AssemblyVersion>0.0.0.1</AssemblyVersion>
|
||||
<FileVersion>0.0.0.1</FileVersion>
|
||||
<PackageVersion>0.0.0.1</PackageVersion>
|
||||
<Version>0.0.0.1</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="4.0.1" />
|
||||
<PackageReference Include="McMaster.Extensions.Hosting.CommandLine" Version="4.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
|
||||
<PackageReference Include="NetEscapades.Configuration.Yaml" Version="2.2.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||
<PackageReference Include="Refit" Version="6.3.2" />
|
||||
<PackageReference Include="Refit.HttpClientFactory" Version="6.3.2" />
|
||||
<PackageReference Include="Refit.Newtonsoft.Json" Version="6.3.2" />
|
||||
<PackageReference Include="Serilog.Extensions.Hosting" Version="4.2.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
<PackageReference Include="TagLibSharp" Version="2.2.0" />
|
||||
<PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="4.0.2" />
|
||||
<PackageReference Include="McMaster.Extensions.Hosting.CommandLine" Version="4.0.2" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
<PackageReference Include="System.Text.Encoding.CodePages" Version="7.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="appsettings.json" />
|
||||
<None Remove="Resources\error_msg.json" />
|
||||
<Content Include="Resources\error_msg.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
<None Remove="BlockWords.json" />
|
||||
<Content Include="BlockWords.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
<None Remove="config.yaml" />
|
||||
<Content Include="config.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
<None Remove="appsettings.json" />
|
||||
<None Remove="Resources\error_msg.json" />
|
||||
<Content Include="Resources\error_msg.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
<None Remove="BlockWords.json" />
|
||||
<Content Include="BlockWords.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
<None Remove="config.yaml" />
|
||||
<Content Include="config.yaml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ZonyLrcTools.Common\ZonyLrcTools.Common.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
@@ -9,6 +9,7 @@ globalOption:
|
||||
isEnable: false # 是否启用代理。
|
||||
ip: 127.0.0.1 # 代理服务 IP 地址。
|
||||
port: 4780 # 代理服务端口号。
|
||||
updateUrl: https://api.myzony.com/lrc-tools/update # 更新检查地址。
|
||||
|
||||
# 下载器的相关参数配置。
|
||||
provider:
|
||||
@@ -35,13 +36,23 @@ globalOption:
|
||||
plugin:
|
||||
- name: NetEase # 基于网易云音乐的歌词下载器。
|
||||
priority: 1 # 优先级,升序排列,改为 -1 时禁用。
|
||||
depth: 10 # 搜索深度,值越大搜索结果越多,但搜索时间越长。
|
||||
additional:
|
||||
isEnableRomanOutput: false # 是否启用罗马音输出,本参数仅当对应歌曲有罗马音歌词时有效。
|
||||
- name: QQ # 基于 QQ 音乐的歌词下载器。
|
||||
priority: 2
|
||||
# depth: 10 # 暂时不支持。
|
||||
- name: KuGou # 基于酷狗音乐的歌词下载器。
|
||||
priority: 3
|
||||
depth: 10
|
||||
- name: KuWo # 基于酷我音乐的歌词下载器。
|
||||
priority: 4
|
||||
depth: 10
|
||||
# 歌词下载的一些共有配置参数。
|
||||
config:
|
||||
isOneLine: true # 双语歌词是否合并为一行展示。
|
||||
lineBreak: "\n" # 换行符的类型,记得使用双引号指定。
|
||||
isEnableTranslation: true # 是否启用翻译歌词。
|
||||
isSkipExistLyricFiles: false # 如果歌词文件已经存在,是否跳过这些文件。
|
||||
isOneLine: true # 双语歌词是否合并为一行展示。
|
||||
lineBreak: "\n" # 换行符的类型,记得使用双引号指定。
|
||||
isEnableTranslation: true # 是否启用翻译歌词。
|
||||
isOnlyOutputTranslation: false # 是否只输出翻译歌词。
|
||||
isSkipExistLyricFiles: false # 如果歌词文件已经存在,是否跳过这些文件。
|
||||
fileEncoding: 'utf-8' # 歌词文件的编码格式。
|
@@ -1,5 +1,4 @@
|
||||
#!/bin/bash
|
||||
read -r -p "请输入版本号:" Version
|
||||
Platforms=('win-x64' 'linux-x64' 'osx-x64')
|
||||
|
||||
if ! [ -d './TempFiles' ];
|
||||
@@ -11,11 +10,11 @@ rm -rf ./TempFiles/*
|
||||
|
||||
for platform in "${Platforms[@]}"
|
||||
do
|
||||
dotnet publish -r "$platform" -c Release -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained true
|
||||
|
||||
cd ./bin/Release/net5.0/"$platform"/publish/
|
||||
zip -r ./ZonyLrcTools_"$platform"_"$Version".zip ./
|
||||
cd ../../../../../
|
||||
dotnet publish -r "$platform" -c Release -p:PublishSingleFile=true --self-contained true || exit 1
|
||||
|
||||
mv ./bin/Release/net5.0/"$platform"/publish/ZonyLrcTools_"$platform"_"$Version".zip ./TempFiles
|
||||
cd ./bin/Release/net7.0/"$platform"/publish/ || exit 1
|
||||
zip -r ./ZonyLrcTools_"$platform"_"${PUBLISH_VERSION}".zip ./ || exit 1
|
||||
cd ../../../../../ || exit 1
|
||||
|
||||
mv ./bin/Release/net7.0/"$platform"/publish/ZonyLrcTools_"$platform"_"$PUBLISH_VERSION".zip ./TempFiles
|
||||
done
|
68
src/ZonyLrcTools.Common/Album/AlbumDownloader.cs
Normal file
68
src/ZonyLrcTools.Common/Album/AlbumDownloader.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Extensions;
|
||||
using ZonyLrcTools.Common.Infrastructure.IO;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
using ZonyLrcTools.Common.Infrastructure.Threading;
|
||||
|
||||
namespace ZonyLrcTools.Common.Album;
|
||||
|
||||
public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
|
||||
{
|
||||
private readonly IEnumerable<IAlbumProvider> _albumProviders;
|
||||
|
||||
public IEnumerable<IAlbumProvider> AvailableProviders => new Lazy<IEnumerable<IAlbumProvider>>(() =>
|
||||
{
|
||||
return _albumProviders.Where(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
|
||||
}).Value;
|
||||
|
||||
private readonly IWarpLogger _logger;
|
||||
|
||||
public AlbumDownloader(IEnumerable<IAlbumProvider> albumProviders,
|
||||
IWarpLogger logger)
|
||||
{
|
||||
_albumProviders = albumProviders;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos,
|
||||
int parallelCount = 2,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _logger.InfoAsync("开始下载专辑图像数据...");
|
||||
|
||||
var provider = AvailableProviders.FirstOrDefault(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
|
||||
if (provider == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var warpTask = new WarpTask(parallelCount);
|
||||
var warpTaskList = needDownloadMusicInfos.Select(info =>
|
||||
warpTask.RunAsync(() =>
|
||||
Task.Run(async () =>
|
||||
{
|
||||
_logger.LogSuccessful(info);
|
||||
|
||||
try
|
||||
{
|
||||
var album = await provider.DownloadAsync(info.Name, info.Artist);
|
||||
var filePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!, $"{Path.GetFileNameWithoutExtension(info.FilePath)}.png");
|
||||
if (File.Exists(filePath) || album.Length <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await new FileStream(filePath, FileMode.Create).WriteBytesToFileAsync(album);
|
||||
}
|
||||
catch (ErrorCodeException ex)
|
||||
{
|
||||
_logger.LogWarningInfo(ex);
|
||||
}
|
||||
}, cancellationToken), cancellationToken));
|
||||
|
||||
await Task.WhenAll(warpTaskList);
|
||||
|
||||
await _logger.InfoAsync($"专辑数据下载完成,成功: {needDownloadMusicInfos.Count(m => m.IsSuccessful)} 失败{needDownloadMusicInfos.Count(m => m.IsSuccessful == false)}。");
|
||||
}
|
||||
}
|
10
src/ZonyLrcTools.Common/Album/IAlbumDownloader.cs
Normal file
10
src/ZonyLrcTools.Common/Album/IAlbumDownloader.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace ZonyLrcTools.Common.Album;
|
||||
|
||||
public interface IAlbumDownloader
|
||||
{
|
||||
Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos,
|
||||
int parallelCount = 2,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
IEnumerable<IAlbumProvider> AvailableProviders { get; }
|
||||
}
|
@@ -1,11 +1,9 @@
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Album
|
||||
namespace ZonyLrcTools.Common.Album
|
||||
{
|
||||
/// <summary>
|
||||
/// 专辑封面下载器,用于匹配并下载歌曲的专辑封面。
|
||||
/// </summary>
|
||||
public interface IAlbumDownloader
|
||||
public interface IAlbumProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// 下载器的名称。
|
@@ -1,9 +1,9 @@
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Album
|
||||
namespace ZonyLrcTools.Common.Album
|
||||
{
|
||||
/// <summary>
|
||||
/// 定义了程序默认提供的专辑图像下载器。
|
||||
/// </summary>
|
||||
public static class InternalAlbumDownloaderNames
|
||||
public static class InternalAlbumProviderNames
|
||||
{
|
||||
/// <summary>
|
||||
/// 网易云音乐专辑图像下载器。
|
@@ -1,18 +1,15 @@
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
using System.Net.Http.Headers;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using ZonyLrcTools.Cli.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.Lyrics.Providers.NetEase.JsonModel;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Album.NetEase
|
||||
namespace ZonyLrcTools.Common.Album.NetEase
|
||||
{
|
||||
public class NetEaseAlbumDownloader : IAlbumDownloader, ITransientDependency
|
||||
public class NetEaseAlbumProvider : IAlbumProvider, ITransientDependency
|
||||
{
|
||||
public string DownloaderName => InternalAlbumDownloaderNames.NetEase;
|
||||
public string DownloaderName => InternalAlbumProviderNames.NetEase;
|
||||
|
||||
private readonly IWarpHttpClient _warpHttpClient;
|
||||
private readonly Action<HttpRequestMessage> _defaultOption;
|
||||
@@ -21,7 +18,7 @@ namespace ZonyLrcTools.Cli.Infrastructure.Album.NetEase
|
||||
private const string GetMusicInfoApi = @"https://music.163.com/api/song/detail";
|
||||
private const string DefaultReferer = @"https://music.163.com";
|
||||
|
||||
public NetEaseAlbumDownloader(IWarpHttpClient warpHttpClient)
|
||||
public NetEaseAlbumProvider(IWarpHttpClient warpHttpClient)
|
||||
{
|
||||
_warpHttpClient = warpHttpClient;
|
||||
_defaultOption = message =>
|
||||
@@ -51,7 +48,7 @@ namespace ZonyLrcTools.Cli.Infrastructure.Album.NetEase
|
||||
|
||||
var songDetailJsonStr = await _warpHttpClient.GetAsync(
|
||||
GetMusicInfoApi,
|
||||
new GetSongDetailsRequest(searchResult.GetFirstMatchSongId(songName)),
|
||||
new GetSongDetailsRequest(searchResult.GetFirstMatchSongId(songName, null)),
|
||||
_defaultOption);
|
||||
|
||||
var url = JObject.Parse(songDetailJsonStr).SelectToken("$.songs[0].album.picUrl")?.Value<string>();
|
@@ -1,16 +1,13 @@
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
using ZonyLrcTools.Cli.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Lyric.QQMusic.JsonModel;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.Lyrics.Providers.QQMusic.JsonModel;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Album.QQMusic
|
||||
namespace ZonyLrcTools.Common.Album.QQMusic
|
||||
{
|
||||
public class QQMusicAlbumDownloader : IAlbumDownloader, ITransientDependency
|
||||
public class QQMusicAlbumProvider : IAlbumProvider, ITransientDependency
|
||||
{
|
||||
public string DownloaderName => InternalAlbumDownloaderNames.QQ;
|
||||
public string DownloaderName => InternalAlbumProviderNames.QQ;
|
||||
|
||||
private readonly IWarpHttpClient _warpHttpClient;
|
||||
|
||||
@@ -27,7 +24,7 @@ namespace ZonyLrcTools.Cli.Infrastructure.Album.QQMusic
|
||||
private const string SearchApi = "https://c.y.qq.com/soso/fcgi-bin/client_search_cp";
|
||||
private const string DefaultReferer = "https://y.qq.com";
|
||||
|
||||
public QQMusicAlbumDownloader(IWarpHttpClient warpHttpClient)
|
||||
public QQMusicAlbumProvider(IWarpHttpClient warpHttpClient)
|
||||
{
|
||||
_warpHttpClient = warpHttpClient;
|
||||
}
|
@@ -1,9 +1,9 @@
|
||||
namespace ZonyLrcTools.Cli.Config
|
||||
namespace ZonyLrcTools.Common.Configuration
|
||||
{
|
||||
/// <summary>
|
||||
/// 屏蔽词选项类。
|
||||
/// </summary>
|
||||
public class BlockWordOption
|
||||
public class BlockWordOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否启用本功能。
|
@@ -1,16 +1,8 @@
|
||||
using System.Collections.Generic;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Lyric;
|
||||
using ZonyLrcTools.Common.Lyrics;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Config;
|
||||
namespace ZonyLrcTools.Common.Configuration;
|
||||
|
||||
public class LyricOption
|
||||
{
|
||||
public IEnumerable<LyricProviderOption> Plugin { get; set; }
|
||||
|
||||
public LyricConfigOption Config { get; set; }
|
||||
}
|
||||
|
||||
public class LyricConfigOption
|
||||
public class GlobalLyricsConfigOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 双语歌词是否合并为一行。
|
||||
@@ -31,4 +23,14 @@ public class LyricConfigOption
|
||||
/// 如果歌词文件已经存在,是否跳过这些文件
|
||||
/// </summary>
|
||||
public bool IsSkipExistLyricFiles { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 歌词文件的编码格式。
|
||||
/// </summary>
|
||||
public string FileEncoding { get; set; } = "utf-8";
|
||||
|
||||
/// <summary>
|
||||
/// 是否只输出翻译歌词。
|
||||
/// </summary>
|
||||
public bool IsOnlyOutputTranslation { get; set; } = false;
|
||||
}
|
@@ -1,12 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using YamlDotNet.Serialization;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Lyric;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Network;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Tag;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Config
|
||||
namespace ZonyLrcTools.Common.Configuration
|
||||
{
|
||||
public class ToolOptions
|
||||
public class GlobalOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 支持的音乐文件后缀集合。
|
||||
@@ -21,6 +15,6 @@ namespace ZonyLrcTools.Cli.Config
|
||||
/// <summary>
|
||||
/// 定义下载器的相关配置信息。
|
||||
/// </summary>
|
||||
public ProviderOption Provider { get; set; }
|
||||
public ProviderOptions Provider { get; set; }
|
||||
}
|
||||
}
|
13
src/ZonyLrcTools.Common/Configuration/LyricsOptions.cs
Normal file
13
src/ZonyLrcTools.Common/Configuration/LyricsOptions.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
namespace ZonyLrcTools.Common.Configuration;
|
||||
|
||||
public class LyricsOptions
|
||||
{
|
||||
public IEnumerable<LyricsProviderOptions> Plugin { get; set; }
|
||||
|
||||
public GlobalLyricsConfigOptions Config { get; set; }
|
||||
|
||||
public LyricsProviderOptions GetLyricProviderOption(string name)
|
||||
{
|
||||
return Plugin.FirstOrDefault(x => x.Name == name);
|
||||
}
|
||||
}
|
@@ -1,6 +1,6 @@
|
||||
namespace ZonyLrcTools.Cli.Config
|
||||
namespace ZonyLrcTools.Common.Configuration
|
||||
{
|
||||
public class LyricProviderOption
|
||||
public class LyricsProviderOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 歌词下载器的唯一标识。
|
||||
@@ -11,5 +11,10 @@
|
||||
/// 歌词下载时的优先级,当值为 -1 时是禁用。
|
||||
/// </summary>
|
||||
public int Priority { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 搜索深度,值越大搜索结果越多,但搜索时间越长。
|
||||
/// </summary>
|
||||
public int Depth { get; set; }
|
||||
}
|
||||
}
|
@@ -1,4 +1,4 @@
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Network
|
||||
namespace ZonyLrcTools.Common.Configuration
|
||||
{
|
||||
/// <summary>
|
||||
/// 工具网络相关的设定。
|
14
src/ZonyLrcTools.Common/Configuration/ProviderOptions.cs
Normal file
14
src/ZonyLrcTools.Common/Configuration/ProviderOptions.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace ZonyLrcTools.Common.Configuration;
|
||||
|
||||
public class ProviderOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 标签加载器相关的配置属性。
|
||||
/// </summary>
|
||||
public TagInfoOptions Tag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 歌词下载相关的配置信息。
|
||||
/// </summary>
|
||||
public LyricsOptions Lyric { get; set; }
|
||||
}
|
11
src/ZonyLrcTools.Common/Configuration/TagInfoOptions.cs
Normal file
11
src/ZonyLrcTools.Common/Configuration/TagInfoOptions.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace ZonyLrcTools.Common.Configuration;
|
||||
|
||||
public class TagInfoOptions
|
||||
{
|
||||
public IEnumerable<TagInfoProviderOptions> Plugin { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 屏蔽词功能相关配置。
|
||||
/// </summary>
|
||||
public BlockWordOptions BlockWord { get; set; }
|
||||
}
|
@@ -0,0 +1,11 @@
|
||||
namespace ZonyLrcTools.Common.Configuration
|
||||
{
|
||||
public class TagInfoProviderOptions
|
||||
{
|
||||
public string Name { get; set; }
|
||||
|
||||
public int Priority { get; set; }
|
||||
|
||||
public Dictionary<string, string> Extensions { get; set; }
|
||||
}
|
||||
}
|
12
src/ZonyLrcTools.Common/IMusicInfoLoader.cs
Normal file
12
src/ZonyLrcTools.Common/IMusicInfoLoader.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
namespace ZonyLrcTools.Common;
|
||||
|
||||
public interface IMusicInfoLoader
|
||||
{
|
||||
Task<List<MusicInfo?>> LoadAsync(string dirPath,
|
||||
int parallelCount = 2,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<List<MusicInfo?>> LoadAsync(IReadOnlyCollection<string> filePaths,
|
||||
int parallelCount = 2,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
@@ -1,11 +1,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Reflection;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Extensions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Extensions;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.DependencyInject
|
||||
namespace ZonyLrcTools.Common.Infrastructure.DependencyInject
|
||||
{
|
||||
public static class AutoDependencyInjectExtensions
|
||||
{
|
@@ -1,4 +1,4 @@
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.DependencyInject
|
||||
namespace ZonyLrcTools.Common.Infrastructure.DependencyInject
|
||||
{
|
||||
/// <summary>
|
||||
/// 继承了本接口的类都会以单例的形式注入到 IoC 容器当中。
|
@@ -1,4 +1,4 @@
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.DependencyInject
|
||||
namespace ZonyLrcTools.Common.Infrastructure.DependencyInject
|
||||
{
|
||||
/// <summary>
|
||||
/// 继承了本接口的类都会以瞬时的形式注入到 IoC 容器当中。
|
@@ -1,13 +1,11 @@
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZonyLrcTools.Cli.Config;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.DependencyInject
|
||||
namespace ZonyLrcTools.Common.Infrastructure.DependencyInject
|
||||
{
|
||||
/// <summary>
|
||||
/// Service 注入的扩展方法。
|
||||
@@ -27,7 +25,7 @@ namespace ZonyLrcTools.Cli.Infrastructure.DependencyInject
|
||||
services.AddHttpClient(DefaultWarpHttpClient.HttpClientNameConstant)
|
||||
.ConfigurePrimaryHttpMessageHandler(provider =>
|
||||
{
|
||||
var option = provider.GetRequiredService<IOptions<ToolOptions>>().Value;
|
||||
var option = provider.GetRequiredService<IOptions<GlobalOptions>>().Value;
|
||||
|
||||
return new HttpClientHandler
|
||||
{
|
||||
@@ -49,7 +47,7 @@ namespace ZonyLrcTools.Cli.Infrastructure.DependencyInject
|
||||
.AddYamlFile("config.yaml")
|
||||
.Build();
|
||||
|
||||
services.Configure<ToolOptions>(configuration.GetSection("globalOption"));
|
||||
services.Configure<GlobalOptions>(configuration.GetSection("globalOption"));
|
||||
|
||||
return services;
|
||||
}
|
@@ -1,6 +1,4 @@
|
||||
using System;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Exceptions
|
||||
namespace ZonyLrcTools.Common.Infrastructure.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 带错误码的异常实现。
|
||||
@@ -17,7 +15,7 @@ namespace ZonyLrcTools.Cli.Infrastructure.Exceptions
|
||||
/// <param name="errorCode">错误码,参考 <see cref="ErrorCodes"/> 类的定义。</param>
|
||||
/// <param name="message">错误信息。</param>
|
||||
/// <param name="attachObj">附加的对象数据。</param>
|
||||
public ErrorCodeException(int errorCode, string message = null, object attachObj = null) : base(message)
|
||||
public ErrorCodeException(int errorCode, string? message = null, object attachObj = null) : base(message)
|
||||
{
|
||||
ErrorCode = errorCode;
|
||||
AttachObject = attachObj;
|
@@ -1,10 +1,7 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Exceptions
|
||||
namespace ZonyLrcTools.Common.Infrastructure.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 错误码相关的帮助类。
|
@@ -1,4 +1,4 @@
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Exceptions
|
||||
namespace ZonyLrcTools.Common.Infrastructure.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 错误码。
|
||||
@@ -27,6 +27,11 @@ namespace ZonyLrcTools.Cli.Infrastructure.Exceptions
|
||||
/// </summary>
|
||||
public const int NoFilesWereScanned = 10004;
|
||||
|
||||
/// <summary>
|
||||
/// 文本: 指定的编码不受支持,请检查配置,所有受支持的编码名称。
|
||||
/// </summary>
|
||||
public const int NotSupportedFileEncoding = 10005;
|
||||
|
||||
#endregion
|
||||
|
||||
#region > 警告信息 <
|
@@ -1,7 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Extensions
|
||||
namespace ZonyLrcTools.Common.Infrastructure.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Linq 相关的扩展方法。
|
@@ -1,15 +1,15 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Extensions
|
||||
namespace ZonyLrcTools.Common.Infrastructure.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 日志记录相关的扩展方法。
|
||||
/// </summary>
|
||||
public static class LoggerExtensions
|
||||
public static class LoggerHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用 <see cref="LogLevel.Warning"/> 级别打印错误日志,并记录异常堆栈。
|
||||
@@ -17,9 +17,9 @@ namespace ZonyLrcTools.Cli.Infrastructure.Extensions
|
||||
/// <param name="logger">日志记录器实例。</param>
|
||||
/// <param name="errorCode">错误码,具体请参考 <see cref="ErrorCodes"/> 类的定义。</param>
|
||||
/// <param name="e">异常实例,可为空。</param>
|
||||
public static void LogWarningWithErrorCode(this ILogger logger, int errorCode, Exception e = null)
|
||||
public static void LogWarningWithErrorCode(this IWarpLogger logger, int errorCode, Exception e = null)
|
||||
{
|
||||
logger.LogWarning($"错误代码: {errorCode}\n堆栈异常: {e?.StackTrace}");
|
||||
logger.WarnAsync($"错误代码: {errorCode}\n堆栈异常: {e?.StackTrace}").GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -27,7 +27,7 @@ namespace ZonyLrcTools.Cli.Infrastructure.Extensions
|
||||
/// </summary>
|
||||
/// <param name="logger">日志记录器的实例。</param>
|
||||
/// <param name="exception">错误码异常实例。</param>
|
||||
public static void LogWarningInfo(this ILogger logger, ErrorCodeException exception)
|
||||
public static void LogWarningInfo(this IWarpLogger logger, ErrorCodeException exception)
|
||||
{
|
||||
if (exception.ErrorCode < 50000)
|
||||
{
|
||||
@@ -37,7 +37,7 @@ namespace ZonyLrcTools.Cli.Infrastructure.Extensions
|
||||
var sb = new StringBuilder();
|
||||
sb.Append($"错误代码: {exception.ErrorCode},信息: {ErrorCodeHelper.GetMessage(exception.ErrorCode)}");
|
||||
sb.Append($"\n附加信息:\n {JsonConvert.SerializeObject(exception.AttachObject)}");
|
||||
logger.LogWarning(sb.ToString());
|
||||
logger.WarnAsync(sb.ToString()).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -45,9 +45,9 @@ namespace ZonyLrcTools.Cli.Infrastructure.Extensions
|
||||
/// </summary>
|
||||
/// <param name="logger">日志记录器的实例。</param>
|
||||
/// <param name="musicInfo">需要打印的歌曲信息。</param>
|
||||
public static void LogSuccessful(this ILogger logger, MusicInfo musicInfo)
|
||||
public static void LogSuccessful(this IWarpLogger logger, MusicInfo musicInfo)
|
||||
{
|
||||
logger.LogInformation($"歌曲名: {musicInfo.Name}, 艺术家: {musicInfo.Artist}, 下载成功.");
|
||||
logger.InfoAsync($"歌曲名: {musicInfo.Name}, 艺术家: {musicInfo.Artist}, 下载成功.").GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,6 +1,4 @@
|
||||
using System;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Extensions
|
||||
namespace ZonyLrcTools.Common.Infrastructure.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 字符串处理相关的工具方法。
|
@@ -1,24 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using ZonyLrcTools.Cli.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Extensions;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Extensions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.IO
|
||||
namespace ZonyLrcTools.Common.Infrastructure.IO
|
||||
{
|
||||
public class FileScanner : IFileScanner, ITransientDependency
|
||||
{
|
||||
public ILogger<FileScanner> Logger { get; set; }
|
||||
private readonly IWarpLogger _logger;
|
||||
|
||||
public FileScanner()
|
||||
public FileScanner(IWarpLogger logger)
|
||||
{
|
||||
Logger = NullLogger<FileScanner>.Instance;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task<List<FileScannerResult>> ScanAsync(string path, IEnumerable<string> extensions)
|
||||
@@ -63,7 +59,7 @@ namespace ZonyLrcTools.Cli.Infrastructure.IO
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.LogWarningWithErrorCode(ErrorCodes.ScanFileError, e);
|
||||
_logger.LogWarningWithErrorCode(ErrorCodes.ScanFileError, e);
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,15 @@
|
||||
namespace ZonyLrcTools.Common.Infrastructure.IO;
|
||||
|
||||
public static class FileScannerExtensions
|
||||
{
|
||||
public static async Task<IEnumerable<string>> ScanMusicFilesAsync(this IFileScanner fileScanner,
|
||||
string dirPath,
|
||||
IEnumerable<string> extensions)
|
||||
{
|
||||
var files = (await fileScanner.ScanAsync(dirPath, extensions))
|
||||
.SelectMany(t => t.FilePaths)
|
||||
.ToList();
|
||||
|
||||
return files;
|
||||
}
|
||||
}
|
@@ -1,6 +1,4 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.IO
|
||||
namespace ZonyLrcTools.Common.Infrastructure.IO
|
||||
{
|
||||
/// <summary>
|
||||
/// 文件扫描结果对象。
|
@@ -1,7 +1,4 @@
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.IO
|
||||
namespace ZonyLrcTools.Common.Infrastructure.IO
|
||||
{
|
||||
public static class FileStreamExtensions
|
||||
{
|
@@ -1,7 +1,4 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.IO
|
||||
namespace ZonyLrcTools.Common.Infrastructure.IO
|
||||
{
|
||||
/// <summary>
|
||||
/// 音乐文件扫描器,用于扫描音乐文件。
|
@@ -0,0 +1,12 @@
|
||||
namespace ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// 日志记录器,包装了 CLI 和网页日志的两种输出方式。
|
||||
/// </summary>
|
||||
public interface IWarpLogger
|
||||
{
|
||||
Task DebugAsync(string message, Exception? exception = null);
|
||||
Task InfoAsync(string message, Exception? exception = null);
|
||||
Task WarnAsync(string message, Exception? exception = null);
|
||||
Task ErrorAsync(string message, Exception? exception = null);
|
||||
}
|
@@ -1,14 +1,11 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using ZonyLrcTools.Cli.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Network
|
||||
namespace ZonyLrcTools.Common.Infrastructure.Network
|
||||
{
|
||||
public class DefaultWarpHttpClient : IWarpHttpClient, ITransientDependency
|
||||
{
|
@@ -1,8 +1,4 @@
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Network
|
||||
namespace ZonyLrcTools.Common.Infrastructure.Network
|
||||
{
|
||||
/// <summary>
|
||||
/// 基于 <see cref="IHttpClientFactory"/> 封装的 HTTP 请求客户端。
|
@@ -1,8 +1,4 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Threading
|
||||
namespace ZonyLrcTools.Common.Infrastructure.Threading
|
||||
{
|
||||
/// <summary>
|
||||
/// 针对 Task 的包装类,基于信号量 <see cref="SemaphoreSlim"/> 限定并行度。
|
10
src/ZonyLrcTools.Common/Lyrics/ILyricsDownloader.cs
Normal file
10
src/ZonyLrcTools.Common/Lyrics/ILyricsDownloader.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace ZonyLrcTools.Common.Lyrics;
|
||||
|
||||
public interface ILyricsDownloader
|
||||
{
|
||||
Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos,
|
||||
int parallelCount = 2,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
IEnumerable<ILyricsProvider> AvailableProviders { get; }
|
||||
}
|
@@ -0,0 +1,23 @@
|
||||
namespace ZonyLrcTools.Common.Lyrics
|
||||
{
|
||||
/// <summary>
|
||||
/// 构建 <see cref="LyricsItemCollection"/> 对象的工厂。
|
||||
/// </summary>
|
||||
public interface ILyricsItemCollectionFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// 根据指定的歌曲数据构建新的 <see cref="LyricsItemCollection"/> 实例。
|
||||
/// </summary>
|
||||
/// <param name="sourceLyric">原始歌词数据。</param>
|
||||
/// <returns>构建完成的 <see cref="LyricsItemCollection"/> 对象。</returns>
|
||||
LyricsItemCollection Build(string? sourceLyric);
|
||||
|
||||
/// <summary>
|
||||
/// 根据指定的歌曲数据构建新的 <see cref="LyricsItemCollection"/> 实例。
|
||||
/// </summary>
|
||||
/// <param name="sourceLyric">原始歌词数据。</param>
|
||||
/// <param name="translationLyric">翻译歌词数据。</param>
|
||||
/// <returns>构建完成的 <see cref="LyricsItemCollection"/> 对象。</returns>
|
||||
LyricsItemCollection Build(string sourceLyric, string translationLyric);
|
||||
}
|
||||
}
|
@@ -1,19 +1,18 @@
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
namespace ZonyLrcTools.Common.Lyrics
|
||||
{
|
||||
/// <summary>
|
||||
/// 歌词数据下载器,用于匹配并下载歌曲的歌词。
|
||||
/// </summary>
|
||||
public interface ILyricDownloader
|
||||
public interface ILyricsProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// 下载歌词数据。
|
||||
/// </summary>
|
||||
/// <param name="songName">歌曲的名称。</param>
|
||||
/// <param name="artist">歌曲的作者。</param>
|
||||
/// <param name="duration">歌曲的时长。</param>
|
||||
/// <returns>歌曲的歌词数据对象。</returns>
|
||||
ValueTask<LyricItemCollection> DownloadAsync(string songName, string artist);
|
||||
ValueTask<LyricsItemCollection> DownloadAsync(string? songName, string? artist, long? duration = null);
|
||||
|
||||
/// <summary>
|
||||
/// 下载器的名称。
|
7
src/ZonyLrcTools.Common/Lyrics/ILyricsTextResolver.cs
Normal file
7
src/ZonyLrcTools.Common/Lyrics/ILyricsTextResolver.cs
Normal file
@@ -0,0 +1,7 @@
|
||||
namespace ZonyLrcTools.Common.Lyrics
|
||||
{
|
||||
public interface ILyricsTextResolver
|
||||
{
|
||||
LyricsItemCollection Resolve(string lyricText);
|
||||
}
|
||||
}
|
@@ -1,9 +1,9 @@
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
namespace ZonyLrcTools.Common.Lyrics
|
||||
{
|
||||
/// <summary>
|
||||
/// 定义了程序默认提供的歌词下载器。
|
||||
/// </summary>
|
||||
public static class InternalLyricDownloaderNames
|
||||
public static class InternalLyricsProviderNames
|
||||
{
|
||||
/// <summary>
|
||||
/// 网易云音乐歌词下载器。
|
||||
@@ -19,5 +19,10 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
/// 酷狗音乐歌词下载器。
|
||||
/// </summary>
|
||||
public const string KuGou = nameof(KuGou);
|
||||
|
||||
/// <summary>
|
||||
/// 酷我音乐歌词下载器。
|
||||
/// </summary>
|
||||
public const string KuWo = nameof(KuWo);
|
||||
}
|
||||
}
|
@@ -1,4 +1,4 @@
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
namespace ZonyLrcTools.Common.Lyrics
|
||||
{
|
||||
/// <summary>
|
||||
/// 换行符格式定义。
|
127
src/ZonyLrcTools.Common/Lyrics/LyricsDownloader.cs
Normal file
127
src/ZonyLrcTools.Common/Lyrics/LyricsDownloader.cs
Normal file
@@ -0,0 +1,127 @@
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Extensions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
using ZonyLrcTools.Common.Infrastructure.Threading;
|
||||
|
||||
namespace ZonyLrcTools.Common.Lyrics;
|
||||
|
||||
public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
|
||||
{
|
||||
private readonly IEnumerable<ILyricsProvider> _lyricsProviders;
|
||||
private readonly IWarpLogger _logger;
|
||||
private readonly GlobalOptions _options;
|
||||
|
||||
public IEnumerable<ILyricsProvider> AvailableProviders => new Lazy<IEnumerable<ILyricsProvider>>(() =>
|
||||
{
|
||||
return _options.Provider.Lyric.Plugin
|
||||
.Where(op => op.Priority != -1)
|
||||
.OrderBy(op => op.Priority)
|
||||
.Join(_lyricsProviders,
|
||||
op => op.Name,
|
||||
loader => loader.DownloaderName,
|
||||
(_, loader) => loader);
|
||||
}).Value;
|
||||
|
||||
public LyricsDownloader(IEnumerable<ILyricsProvider> lyricsProviders,
|
||||
IOptions<GlobalOptions> options,
|
||||
IWarpLogger logger)
|
||||
{
|
||||
_lyricsProviders = lyricsProviders;
|
||||
_logger = logger;
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
public async Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos,
|
||||
int parallelCount = 2,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _logger.InfoAsync("开始下载歌词文件数据...");
|
||||
|
||||
if (parallelCount <= 0)
|
||||
{
|
||||
parallelCount = 1;
|
||||
}
|
||||
|
||||
var warpTask = new WarpTask(parallelCount);
|
||||
var downloadTasks = needDownloadMusicInfos.Select(info =>
|
||||
warpTask.RunAsync(() =>
|
||||
Task.Run(async () =>
|
||||
{
|
||||
// Try to download lyrics from all available providers.
|
||||
foreach (var lyricsProvider in AvailableProviders)
|
||||
{
|
||||
await DownloadAndWriteLyricsAsync(lyricsProvider, info);
|
||||
|
||||
if (info.IsSuccessful)
|
||||
{
|
||||
_logger.LogSuccessful(info);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}, cancellationToken), cancellationToken));
|
||||
|
||||
await Task.WhenAll(downloadTasks);
|
||||
|
||||
await _logger.InfoAsync($"歌词数据下载完成,成功: {needDownloadMusicInfos.Count(m => m.IsSuccessful)} 失败{needDownloadMusicInfos.Count(m => m.IsSuccessful == false)}。");
|
||||
}
|
||||
|
||||
private async Task DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info)
|
||||
{
|
||||
try
|
||||
{
|
||||
var lyrics = await provider.DownloadAsync(info.Name, info.Artist);
|
||||
|
||||
if (lyrics.IsPruneMusic)
|
||||
{
|
||||
info.IsSuccessful = true;
|
||||
return;
|
||||
}
|
||||
|
||||
var newLyricsFilePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!,
|
||||
$"{Path.GetFileNameWithoutExtension(info.FilePath)}.lrc");
|
||||
|
||||
if (File.Exists(newLyricsFilePath))
|
||||
{
|
||||
File.Delete(newLyricsFilePath);
|
||||
}
|
||||
|
||||
// Write lyrics to file.
|
||||
await using (var fileStream = new FileStream(newLyricsFilePath, FileMode.CreateNew, FileAccess.Write))
|
||||
{
|
||||
await using (var binaryWriter = new BinaryWriter(fileStream, Encoding.UTF8))
|
||||
{
|
||||
binaryWriter.Write(Utf8ToSelectedEncoding(lyrics));
|
||||
binaryWriter.Flush();
|
||||
}
|
||||
}
|
||||
|
||||
info.IsSuccessful = true;
|
||||
}
|
||||
catch (ErrorCodeException ex)
|
||||
{
|
||||
_logger.LogWarningInfo(ex);
|
||||
info.IsSuccessful = false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _logger.ErrorAsync($"下载歌词文件时发生错误:{ex.Message},歌曲名: {info.Name},歌手: {info.Artist}。");
|
||||
info.IsSuccessful = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Convert UTF-8 to selected encoding.
|
||||
private byte[] Utf8ToSelectedEncoding(LyricsItemCollection lyrics)
|
||||
{
|
||||
var supportEncodings = Encoding.GetEncodings();
|
||||
if (supportEncodings.All(x => x.Name != _options.Provider.Lyric.Config.FileEncoding))
|
||||
{
|
||||
throw new ErrorCodeException(ErrorCodes.NotSupportedFileEncoding);
|
||||
}
|
||||
|
||||
return Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding(_options.Provider.Lyric.Config.FileEncoding), lyrics.GetUtf8Bytes());
|
||||
}
|
||||
}
|
@@ -1,12 +1,11 @@
|
||||
using System;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
namespace ZonyLrcTools.Common.Lyrics
|
||||
{
|
||||
/// <summary>
|
||||
/// 歌词的行对象,是 <see cref="LyricItemCollection"/> 的最小单位。。
|
||||
/// 歌词的行对象,是 <see cref="LyricsItemCollection"/> 的最小单位。。
|
||||
/// </summary>
|
||||
public class LyricItem : IComparable<LyricItem>
|
||||
public class LyricsItem : IComparable<LyricsItem>
|
||||
{
|
||||
/// <summary>
|
||||
/// 原始时间轴,格式类似于 [01:55.12]。
|
||||
@@ -34,10 +33,10 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
public double SortScore => Minute * 60 + Second;
|
||||
|
||||
/// <summary>
|
||||
/// 构建新的 <see cref="LyricItem"/> 对象。
|
||||
/// 构建新的 <see cref="LyricsItem"/> 对象。
|
||||
/// </summary>
|
||||
/// <param name="lyricText">原始的 Lyric 歌词。</param>
|
||||
public LyricItem(string lyricText)
|
||||
public LyricsItem(string lyricText)
|
||||
{
|
||||
var timeline = new Regex(@"\[\d+:\d+.\d+\]").Match(lyricText)
|
||||
.Value.Replace("]", string.Empty)
|
||||
@@ -51,19 +50,19 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构造新的 <see cref="LyricItem"/> 对象。
|
||||
/// 构造新的 <see cref="LyricsItem"/> 对象。
|
||||
/// </summary>
|
||||
/// <param name="minute">歌词所在的时间(分)。</param>
|
||||
/// <param name="second">歌词所在的时间(秒)。</param>
|
||||
/// <param name="lyricText">歌词文本数据。</param>
|
||||
public LyricItem(int minute, double second, string lyricText)
|
||||
public LyricsItem(int minute, double second, string lyricText)
|
||||
{
|
||||
Minute = minute;
|
||||
Second = second;
|
||||
LyricText = lyricText;
|
||||
}
|
||||
|
||||
public int CompareTo(LyricItem other)
|
||||
public int CompareTo(LyricsItem other)
|
||||
{
|
||||
if (SortScore > other.SortScore)
|
||||
{
|
||||
@@ -78,32 +77,32 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static bool operator >(LyricItem left, LyricItem right)
|
||||
public static bool operator >(LyricsItem left, LyricsItem right)
|
||||
{
|
||||
return left.SortScore > right.SortScore;
|
||||
}
|
||||
|
||||
public static bool operator <(LyricItem left, LyricItem right)
|
||||
public static bool operator <(LyricsItem left, LyricsItem right)
|
||||
{
|
||||
return left.SortScore < right.SortScore;
|
||||
}
|
||||
|
||||
public static bool operator ==(LyricItem left, LyricItem right)
|
||||
public static bool operator ==(LyricsItem left, LyricsItem right)
|
||||
{
|
||||
return (int?)left?.SortScore == (int?)right?.SortScore;
|
||||
}
|
||||
|
||||
public static bool operator !=(LyricItem item1, LyricItem item2)
|
||||
public static bool operator !=(LyricsItem item1, LyricsItem item2)
|
||||
{
|
||||
return !(item1 == item2);
|
||||
}
|
||||
|
||||
public static LyricItem operator +(LyricItem src, LyricItem dist)
|
||||
public static LyricsItem operator +(LyricsItem src, LyricsItem dist)
|
||||
{
|
||||
return new LyricItem(src.Minute, src.Second, $"{src.LyricText} {dist.LyricText}");
|
||||
return new LyricsItem(src.Minute, src.Second, $"{src.LyricText} {dist.LyricText}");
|
||||
}
|
||||
|
||||
protected bool Equals(LyricItem other)
|
||||
protected bool Equals(LyricsItem other)
|
||||
{
|
||||
return LyricText == other.LyricText && Minute == other.Minute && Second.Equals(other.Second);
|
||||
}
|
||||
@@ -113,7 +112,7 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
if (ReferenceEquals(null, obj)) return false;
|
||||
if (ReferenceEquals(this, obj)) return true;
|
||||
if (obj.GetType() != this.GetType()) return false;
|
||||
return Equals((LyricItem)obj);
|
||||
return Equals((LyricsItem)obj);
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
@@ -1,38 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ZonyLrcTools.Cli.Config;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Extensions;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.Extensions;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
namespace ZonyLrcTools.Common.Lyrics
|
||||
{
|
||||
/// <summary>
|
||||
/// 歌词数据,包含多条歌词行对象(<see cref="LyricItem"/>)。
|
||||
/// 歌词数据,包含多条歌词行对象(<see cref="LyricsItem"/>)。
|
||||
/// </summary>
|
||||
public class LyricItemCollection : List<LyricItem>
|
||||
public class LyricsItemCollection : List<LyricsItem>
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否为纯音乐,当没有任何歌词数据的时候,属性值为 True。
|
||||
/// </summary>
|
||||
public bool IsPruneMusic => Count == 0;
|
||||
|
||||
public LyricConfigOption Option { get; private set; }
|
||||
public GlobalLyricsConfigOptions? Options { get; private set; }
|
||||
|
||||
public LyricItemCollection(LyricConfigOption option)
|
||||
public LyricsItemCollection(GlobalLyricsConfigOptions? options)
|
||||
{
|
||||
Option = option;
|
||||
Options = options;
|
||||
}
|
||||
|
||||
public static LyricItemCollection operator +(LyricItemCollection left, LyricItemCollection right)
|
||||
public static LyricsItemCollection operator +(LyricsItemCollection left, LyricsItemCollection right)
|
||||
{
|
||||
if (right.IsPruneMusic)
|
||||
{
|
||||
return left;
|
||||
}
|
||||
|
||||
var option = left.Option;
|
||||
var newCollection = new LyricItemCollection(option);
|
||||
var option = left.Options;
|
||||
var newCollection = new LyricsItemCollection(option);
|
||||
var indexDiff = left.Count - right.Count;
|
||||
if (!option.IsOneLine)
|
||||
{
|
||||
@@ -94,7 +91,7 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
/// 这个索引字典用于标识每个索引的歌词是否被处理,为 True 则为已处理,为 False 为未处理。
|
||||
/// </remarks>
|
||||
/// <param name="items">等待构建的歌词集合实例。</param>
|
||||
private static Dictionary<int, bool> BuildMarkDictionary(LyricItemCollection items)
|
||||
private static Dictionary<int, bool> BuildMarkDictionary(LyricsItemCollection items)
|
||||
{
|
||||
return items
|
||||
.Select((item, index) => new { index, item })
|
||||
@@ -104,8 +101,13 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
public override string ToString()
|
||||
{
|
||||
var lyricBuilder = new StringBuilder();
|
||||
ForEach(lyric => lyricBuilder.Append(lyric).Append(Option.LineBreak));
|
||||
return lyricBuilder.ToString().TrimEnd(Option.LineBreak);
|
||||
ForEach(lyric => lyricBuilder.Append(lyric).Append(Options.LineBreak));
|
||||
return lyricBuilder.ToString().TrimEnd(Options.LineBreak);
|
||||
}
|
||||
|
||||
public byte[] GetUtf8Bytes()
|
||||
{
|
||||
return Encoding.UTF8.GetBytes(ToString());
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,68 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
|
||||
namespace ZonyLrcTools.Common.Lyrics
|
||||
{
|
||||
/// <summary>
|
||||
/// <see cref="ILyricsItemCollectionFactory"/> 的默认实现。
|
||||
/// </summary>
|
||||
public class LyricsItemCollectionFactory : ILyricsItemCollectionFactory, ITransientDependency
|
||||
{
|
||||
private readonly GlobalOptions _options;
|
||||
|
||||
public LyricsItemCollectionFactory(IOptions<GlobalOptions> options)
|
||||
{
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
public LyricsItemCollection Build(string? sourceLyric)
|
||||
{
|
||||
var lyric = new LyricsItemCollection(_options.Provider.Lyric.Config);
|
||||
if (string.IsNullOrEmpty(sourceLyric))
|
||||
{
|
||||
return lyric;
|
||||
}
|
||||
|
||||
InternalBuildLyricObject(lyric, sourceLyric);
|
||||
|
||||
return lyric;
|
||||
}
|
||||
|
||||
public LyricsItemCollection Build(string sourceLyric, string translationLyric)
|
||||
{
|
||||
var lyric = new LyricsItemCollection(_options.Provider.Lyric.Config);
|
||||
if (string.IsNullOrEmpty(sourceLyric))
|
||||
{
|
||||
return lyric;
|
||||
}
|
||||
|
||||
lyric = InternalBuildLyricObject(lyric, sourceLyric);
|
||||
|
||||
if (_options.Provider.Lyric.Config.IsEnableTranslation && !string.IsNullOrEmpty(translationLyric))
|
||||
{
|
||||
var translatedLyric = InternalBuildLyricObject(new LyricsItemCollection(_options.Provider.Lyric.Config), translationLyric);
|
||||
if (_options.Provider.Lyric.Config.IsOnlyOutputTranslation)
|
||||
{
|
||||
return translatedLyric;
|
||||
}
|
||||
|
||||
return lyric + translatedLyric;
|
||||
}
|
||||
|
||||
return lyric;
|
||||
}
|
||||
|
||||
private LyricsItemCollection InternalBuildLyricObject(LyricsItemCollection lyrics, string sourceText)
|
||||
{
|
||||
var regex = new Regex(@"\[\d+:\d+.\d+\].+\n?");
|
||||
foreach (Match match in regex.Matches(sourceText))
|
||||
{
|
||||
lyrics.Add(new LyricsItem(match.Value));
|
||||
}
|
||||
|
||||
return lyrics;
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,13 +1,12 @@
|
||||
using System.Threading.Tasks;
|
||||
using ZonyLrcTools.Cli.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
namespace ZonyLrcTools.Common.Lyrics
|
||||
{
|
||||
/// <summary>
|
||||
/// 歌词下载器的基类,定义了歌词下载器的常规逻辑。
|
||||
/// </summary>
|
||||
public abstract class LyricDownloader : ILyricDownloader, ITransientDependency
|
||||
public abstract class LyricsProvider : ILyricsProvider, ITransientDependency
|
||||
{
|
||||
public abstract string DownloaderName { get; }
|
||||
|
||||
@@ -16,20 +15,21 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
/// </summary>
|
||||
/// <param name="songName">歌曲名称。</param>
|
||||
/// <param name="artist">歌曲作者/艺术家。</param>
|
||||
/// <param name="duration">歌曲的时长。</param>
|
||||
/// <returns>下载完成的歌曲数据。</returns>
|
||||
public virtual async ValueTask<LyricItemCollection> DownloadAsync(string songName, string artist)
|
||||
public virtual async ValueTask<LyricsItemCollection> DownloadAsync(string songName, string artist, long? duration = null)
|
||||
{
|
||||
var args = new LyricDownloaderArgs(songName, artist);
|
||||
var args = new LyricsProviderArgs(songName, artist, duration ?? 0);
|
||||
await ValidateAsync(args);
|
||||
var downloadDataBytes = await DownloadDataAsync(args);
|
||||
return await GenerateLyricAsync(downloadDataBytes, args);
|
||||
var downloadDataObject = await DownloadDataAsync(args);
|
||||
return await GenerateLyricAsync(downloadDataObject, args);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通用的验证逻辑,验证基本参数是否正确。
|
||||
/// </summary>
|
||||
/// <param name="args">歌词下载时需要的参数信息。</param>
|
||||
protected virtual ValueTask ValidateAsync(LyricDownloaderArgs args)
|
||||
protected virtual ValueTask ValidateAsync(LyricsProviderArgs args)
|
||||
{
|
||||
if (string.IsNullOrEmpty(args.SongName))
|
||||
{
|
||||
@@ -47,12 +47,13 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric
|
||||
/// <summary>
|
||||
/// 根据指定的歌曲参数,下载歌词数据。
|
||||
/// </summary>
|
||||
protected abstract ValueTask<byte[]> DownloadDataAsync(LyricDownloaderArgs args);
|
||||
protected abstract ValueTask<object> DownloadDataAsync(LyricsProviderArgs args);
|
||||
|
||||
/// <summary>
|
||||
/// 根据指定的歌词二进制数据,生成歌词数据。
|
||||
/// 根据指定的歌词对象,生成歌词数据,常用于处理不同格式的歌词数据。
|
||||
/// </summary>
|
||||
/// <param name="data">歌词的原始二进制数据。</param>
|
||||
protected abstract ValueTask<LyricItemCollection> GenerateLyricAsync(byte[] data, LyricDownloaderArgs args);
|
||||
/// <param name="lyricsObject">当 <see cref="DownloadDataAsync"/> 完成后,传递的歌词数据对象。</param>
|
||||
/// <param name="args">生成歌词时,提供的歌曲信息参数。</param>
|
||||
protected abstract ValueTask<LyricsItemCollection> GenerateLyricAsync(object lyricsObject, LyricsProviderArgs args);
|
||||
}
|
||||
}
|
18
src/ZonyLrcTools.Common/Lyrics/LyricsProviderArgs.cs
Normal file
18
src/ZonyLrcTools.Common/Lyrics/LyricsProviderArgs.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace ZonyLrcTools.Common.Lyrics
|
||||
{
|
||||
public class LyricsProviderArgs
|
||||
{
|
||||
public string SongName { get; set; }
|
||||
|
||||
public string Artist { get; set; }
|
||||
|
||||
public long Duration { get; set; }
|
||||
|
||||
public LyricsProviderArgs(string songName, string artist, long duration)
|
||||
{
|
||||
SongName = songName;
|
||||
Artist = artist;
|
||||
Duration = duration;
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,6 +1,6 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.KuGou.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.KuGou.JsonModel
|
||||
{
|
||||
public class GetLyricAccessKeyRequest
|
||||
{
|
@@ -1,7 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.KuGou.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.KuGou.JsonModel
|
||||
{
|
||||
public class GetLyricAccessKeyResponse
|
||||
{
|
@@ -1,6 +1,6 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.KuGou.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.KuGou.JsonModel
|
||||
{
|
||||
public class GetLyricRequest
|
||||
{
|
@@ -2,7 +2,7 @@
|
||||
using System.Web;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.KuGou.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.KuGou.JsonModel
|
||||
{
|
||||
public class SongSearchRequest
|
||||
{
|
||||
@@ -12,11 +12,17 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.KuGou.JsonModel
|
||||
|
||||
[JsonProperty("keyword")] public string Keyword { get; }
|
||||
|
||||
public SongSearchRequest(string musicName, string artistName)
|
||||
[JsonProperty("pagesize")] public int PageSize { get; }
|
||||
|
||||
[JsonProperty("page")] public int Page { get; }
|
||||
|
||||
public SongSearchRequest(string musicName, string artistName, int pageSize = 30)
|
||||
{
|
||||
Filter = 2;
|
||||
Platform = "WebFilter";
|
||||
Keyword = HttpUtility.UrlEncode($"{musicName}+{artistName}", Encoding.UTF8);
|
||||
PageSize = pageSize;
|
||||
Page = 1;
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,7 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.KuGou.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.KuGou.JsonModel
|
||||
{
|
||||
public class SongSearchResponse
|
||||
{
|
@@ -1,35 +1,38 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Lyric.KuGou.JsonModel;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.Lyrics.Providers.KuGou.JsonModel;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.KuGou
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.KuGou
|
||||
{
|
||||
public class KuGourLyricDownloader : LyricDownloader
|
||||
public class KuGourLyricsProvider : LyricsProvider
|
||||
{
|
||||
public override string DownloaderName => InternalLyricDownloaderNames.KuGou;
|
||||
public override string DownloaderName => InternalLyricsProviderNames.KuGou;
|
||||
|
||||
private readonly IWarpHttpClient _warpHttpClient;
|
||||
private readonly ILyricItemCollectionFactory _lyricItemCollectionFactory;
|
||||
private readonly ILyricsItemCollectionFactory _lyricsItemCollectionFactory;
|
||||
private readonly GlobalOptions _options;
|
||||
|
||||
private const string KuGouSearchMusicUrl = @"https://songsearch.kugou.com/song_search_v2";
|
||||
private const string KuGouGetLyricAccessKeyUrl = @"http://lyrics.kugou.com/search";
|
||||
private const string KuGouGetLyricUrl = @"http://lyrics.kugou.com/download";
|
||||
|
||||
public KuGourLyricDownloader(IWarpHttpClient warpHttpClient,
|
||||
ILyricItemCollectionFactory lyricItemCollectionFactory)
|
||||
public KuGourLyricsProvider(IWarpHttpClient warpHttpClient,
|
||||
ILyricsItemCollectionFactory lyricsItemCollectionFactory,
|
||||
IOptions<GlobalOptions> options)
|
||||
{
|
||||
_warpHttpClient = warpHttpClient;
|
||||
_lyricItemCollectionFactory = lyricItemCollectionFactory;
|
||||
_lyricsItemCollectionFactory = lyricsItemCollectionFactory;
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
protected override async ValueTask<byte[]> DownloadDataAsync(LyricDownloaderArgs args)
|
||||
protected override async ValueTask<object> DownloadDataAsync(LyricsProviderArgs args)
|
||||
{
|
||||
var searchResult = await _warpHttpClient.GetAsync<SongSearchResponse>(KuGouSearchMusicUrl,
|
||||
new SongSearchRequest(args.SongName, args.Artist));
|
||||
new SongSearchRequest(args.SongName, args.Artist, _options.Provider.Lyric.GetLyricProviderOption(DownloaderName).Depth));
|
||||
|
||||
ValidateSongSearchResponse(searchResult, args);
|
||||
|
||||
@@ -38,26 +41,24 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.KuGou
|
||||
new GetLyricAccessKeyRequest(searchResult.Data.List[0].FileHash));
|
||||
|
||||
var accessKeyObject = accessKeyResponse.AccessKeyDataObjects[0];
|
||||
var lyricResponse = await _warpHttpClient.GetAsync(KuGouGetLyricUrl,
|
||||
return await _warpHttpClient.GetAsync(KuGouGetLyricUrl,
|
||||
new GetLyricRequest(accessKeyObject.Id, accessKeyObject.AccessKey));
|
||||
|
||||
return Encoding.UTF8.GetBytes(lyricResponse);
|
||||
}
|
||||
|
||||
protected override async ValueTask<LyricItemCollection> GenerateLyricAsync(byte[] data, LyricDownloaderArgs args)
|
||||
protected override async ValueTask<LyricsItemCollection> GenerateLyricAsync(object data, LyricsProviderArgs args)
|
||||
{
|
||||
await ValueTask.CompletedTask;
|
||||
var lyricJsonObj = JObject.Parse(Encoding.UTF8.GetString(data));
|
||||
var lyricJsonObj = JObject.Parse((data as string)!);
|
||||
if (lyricJsonObj.SelectToken("$.status").Value<int>() != 200)
|
||||
{
|
||||
throw new ErrorCodeException(ErrorCodes.NoMatchingSong, attachObj: args);
|
||||
}
|
||||
|
||||
var lyricText = Encoding.UTF8.GetString(Convert.FromBase64String(lyricJsonObj.SelectToken("$.content").Value<string>()));
|
||||
return _lyricItemCollectionFactory.Build(lyricText);
|
||||
return _lyricsItemCollectionFactory.Build(lyricText);
|
||||
}
|
||||
|
||||
protected virtual void ValidateSongSearchResponse(SongSearchResponse response, LyricDownloaderArgs args)
|
||||
protected virtual void ValidateSongSearchResponse(SongSearchResponse response, LyricsProviderArgs args)
|
||||
{
|
||||
if (response.ErrorCode != 0 && response.Status != 1 || response.Data.List == null)
|
||||
{
|
@@ -0,0 +1,13 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.KuWo.JsonModel;
|
||||
|
||||
public class GetLyricsRequest
|
||||
{
|
||||
[JsonProperty("musicId")] public long MusicId { get; }
|
||||
|
||||
public GetLyricsRequest(long musicId)
|
||||
{
|
||||
MusicId = musicId;
|
||||
}
|
||||
}
|
@@ -0,0 +1,26 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.KuWo.JsonModel;
|
||||
|
||||
public class GetLyricsResponse
|
||||
{
|
||||
[JsonProperty("status")] public int Status { get; set; }
|
||||
|
||||
[JsonProperty("data")] public GetLyricsResponseInnerData Data { get; set; }
|
||||
|
||||
[JsonProperty("msg")] public string? ErrorMessage { get; set; }
|
||||
|
||||
[JsonProperty("msgs")] public string? ErrorMessage2 { get; set; }
|
||||
}
|
||||
|
||||
public class GetLyricsResponseInnerData
|
||||
{
|
||||
[JsonProperty("lrclist")] public ICollection<GetLyricsItem> Lyrics { get; set; }
|
||||
}
|
||||
|
||||
public class GetLyricsItem
|
||||
{
|
||||
[JsonProperty("lineLyric")] public string Text { get; set; }
|
||||
|
||||
[JsonProperty("time")] public string Position { get; set; }
|
||||
}
|
@@ -0,0 +1,19 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.KuWo.JsonModel;
|
||||
|
||||
public class SongSearchRequest
|
||||
{
|
||||
[JsonProperty("key")] public string Keyword { get; set; }
|
||||
|
||||
[JsonProperty("pn")] public int PageNumber { get; }
|
||||
|
||||
[JsonProperty("rn")] public int PageSize { get; }
|
||||
|
||||
public SongSearchRequest(string name, string artist, int pageNumber = 1, int pageSize = 20)
|
||||
{
|
||||
Keyword = $"{name} {artist}";
|
||||
PageNumber = pageNumber;
|
||||
PageSize = pageSize;
|
||||
}
|
||||
}
|
@@ -0,0 +1,46 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.KuWo.JsonModel;
|
||||
|
||||
public class SongSearchResponse
|
||||
{
|
||||
[JsonProperty("code")] public int Code { get; set; }
|
||||
|
||||
[JsonProperty("data")] public SongSearchResponseInnerData InnerData { get; set; }
|
||||
|
||||
[JsonProperty("msg")] public string? ErrorMessage { get; set; }
|
||||
|
||||
public long GetMatchedMusicId(string musicName, string artistName, long? duration)
|
||||
{
|
||||
var prefectMatch = InnerData.SongItems.FirstOrDefault(x => x.Name == musicName && x.Artist == artistName);
|
||||
if (prefectMatch != null)
|
||||
{
|
||||
return prefectMatch.MusicId;
|
||||
}
|
||||
|
||||
if (duration is null or 0)
|
||||
{
|
||||
return InnerData.SongItems.First().MusicId;
|
||||
}
|
||||
|
||||
return InnerData.SongItems.OrderBy(t => Math.Abs(t.Duration - duration.Value)).First().MusicId;
|
||||
}
|
||||
}
|
||||
|
||||
public class SongSearchResponseInnerData
|
||||
{
|
||||
[JsonProperty("total")] public string Total { get; set; }
|
||||
|
||||
[JsonProperty("list")] public ICollection<SongSearchResponseDetail> SongItems { get; set; }
|
||||
}
|
||||
|
||||
public class SongSearchResponseDetail
|
||||
{
|
||||
[JsonProperty("artist")] public string? Artist { get; set; }
|
||||
|
||||
[JsonProperty("name")] public string? Name { get; set; }
|
||||
|
||||
[JsonProperty("rid")] public long MusicId { get; set; }
|
||||
|
||||
[JsonProperty("duration")] public long Duration { get; set; }
|
||||
}
|
@@ -0,0 +1,87 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Newtonsoft.Json;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.Lyrics.Providers.KuWo.JsonModel;
|
||||
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.KuWo;
|
||||
|
||||
public class KuWoLyricsProvider : LyricsProvider
|
||||
{
|
||||
public override string DownloaderName => InternalLyricsProviderNames.KuWo;
|
||||
|
||||
private const string KuWoSearchMusicUrl = @"https://www.kuwo.cn/api/www/search/searchMusicBykeyWord";
|
||||
private const string KuWoSearchLyricsUrl = @"https://m.kuwo.cn/newh5/singles/songinfoandlrc";
|
||||
private const string KuWoDefaultToken = "ABCDE12345";
|
||||
|
||||
private readonly IWarpHttpClient _warpHttpClient;
|
||||
private readonly ILyricsItemCollectionFactory _lyricsItemCollectionFactory;
|
||||
private readonly GlobalOptions _options;
|
||||
|
||||
private static readonly ProductInfoHeaderValue UserAgent = new("Chrome", "81.0.4044.138");
|
||||
|
||||
public KuWoLyricsProvider(IWarpHttpClient warpHttpClient,
|
||||
ILyricsItemCollectionFactory lyricsItemCollectionFactory,
|
||||
IOptions<GlobalOptions> options)
|
||||
{
|
||||
_warpHttpClient = warpHttpClient;
|
||||
_lyricsItemCollectionFactory = lyricsItemCollectionFactory;
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
protected override async ValueTask<object> DownloadDataAsync(LyricsProviderArgs args)
|
||||
{
|
||||
var songSearchResponse = await _warpHttpClient.GetAsync<SongSearchResponse>(KuWoSearchMusicUrl,
|
||||
new SongSearchRequest(args.SongName, args.Artist, pageSize: _options.Provider.Lyric.GetLyricProviderOption(DownloaderName).Depth),
|
||||
op =>
|
||||
{
|
||||
op.Headers.UserAgent.Add(UserAgent);
|
||||
op.Headers.Referrer = new Uri("https://kuwo.cn");
|
||||
op.Headers.Add("csrf", KuWoDefaultToken);
|
||||
op.Headers.Add("Cookie", $"kw_token={KuWoDefaultToken}");
|
||||
});
|
||||
|
||||
ValidateSongSearchResponse(songSearchResponse, args);
|
||||
|
||||
return await _warpHttpClient.GetAsync<GetLyricsResponse>(KuWoSearchLyricsUrl,
|
||||
new GetLyricsRequest(songSearchResponse.GetMatchedMusicId(args.SongName, args.Artist, args.Duration)),
|
||||
op =>
|
||||
{
|
||||
op.Headers.UserAgent.Add(UserAgent);
|
||||
op.Headers.Referrer = new Uri("https://m.kuwo.cn/yinyue/");
|
||||
});
|
||||
}
|
||||
|
||||
protected override async ValueTask<LyricsItemCollection> GenerateLyricAsync(object lyricsObject, LyricsProviderArgs args)
|
||||
{
|
||||
await ValueTask.CompletedTask;
|
||||
|
||||
var lyricsResponse = (GetLyricsResponse)lyricsObject;
|
||||
var items = lyricsResponse.Data.Lyrics.Select(l =>
|
||||
{
|
||||
var position = double.Parse(l.Position);
|
||||
var positionSpan = TimeSpan.FromSeconds(position);
|
||||
return new LyricsItem(positionSpan.Minutes, double.Parse($"{positionSpan.Seconds}.{positionSpan.Milliseconds}"), l.Text);
|
||||
});
|
||||
|
||||
var lyricsItemCollection = new LyricsItemCollection(_options.Provider.Lyric.Config);
|
||||
lyricsItemCollection.AddRange(items);
|
||||
return lyricsItemCollection;
|
||||
}
|
||||
|
||||
protected virtual void ValidateSongSearchResponse(SongSearchResponse response, LyricsProviderArgs args)
|
||||
{
|
||||
if (response.Code != 200)
|
||||
{
|
||||
throw new ErrorCodeException(ErrorCodes.TheReturnValueIsIllegal, response.ErrorMessage, args);
|
||||
}
|
||||
|
||||
if (response.InnerData.SongItems.Count == 0)
|
||||
{
|
||||
throw new ErrorCodeException(ErrorCodes.NoMatchingSong, attachObj: args);
|
||||
}
|
||||
}
|
||||
}
|
@@ -2,15 +2,15 @@ using Newtonsoft.Json;
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.NetEase.JsonModel
|
||||
{
|
||||
public class GetLyricRequest
|
||||
{
|
||||
public GetLyricRequest(long songId)
|
||||
{
|
||||
OS = "osx";
|
||||
OS = "ios";
|
||||
Id = songId;
|
||||
Lv = Kv = Tv = -1;
|
||||
Lv = Kv = Tv = Rv = -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -30,5 +30,9 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel
|
||||
[JsonProperty("kv")] public int Kv { get; }
|
||||
|
||||
[JsonProperty("tv")] public int Tv { get; }
|
||||
|
||||
[JsonProperty("rv")] public int Rv { get; set; }
|
||||
|
||||
[JsonProperty("crypto")] public string Protocol { get; set; } = "api";
|
||||
}
|
||||
}
|
@@ -1,6 +1,6 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.NetEase.JsonModel
|
||||
{
|
||||
public class GetLyricResponse
|
||||
{
|
||||
@@ -22,6 +22,12 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel
|
||||
[JsonProperty("tlyric")]
|
||||
public InnerLyric TranslationLyric { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 如果存在罗马音歌词,则本项内容为罗马音歌词。
|
||||
/// </summary>
|
||||
[JsonProperty("romalrc")]
|
||||
public InnerLyric RomaLyric { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 状态码。
|
||||
/// </summary>
|
@@ -1,6 +1,6 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.NetEase.JsonModel
|
||||
{
|
||||
public class GetSongDetailsRequest
|
||||
{
|
@@ -1,8 +1,9 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Web;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.NetEase.JsonModel
|
||||
{
|
||||
public class SongSearchRequest
|
||||
{
|
||||
@@ -42,18 +43,25 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel
|
||||
[JsonProperty("limit")]
|
||||
public int Limit { get; set; }
|
||||
|
||||
[JsonProperty("crypto")] public string Crypto { get; set; } = "weapi";
|
||||
|
||||
public SongSearchRequest()
|
||||
{
|
||||
CsrfToken = string.Empty;
|
||||
Type = 1;
|
||||
Offset = 0;
|
||||
IsTotal = true;
|
||||
Limit = 5;
|
||||
Limit = 10;
|
||||
}
|
||||
|
||||
public SongSearchRequest(string musicName, string artistName) : this()
|
||||
public SongSearchRequest(string musicName, string artistName, int limit = 10) : this()
|
||||
{
|
||||
// Remove all the brackets and the content inside them.
|
||||
var regex = new Regex(@"\([^)]*\)");
|
||||
musicName = regex.Replace(musicName, string.Empty);
|
||||
|
||||
SearchKey = HttpUtility.UrlEncode($"{musicName}+{artistName}", Encoding.UTF8);
|
||||
Limit = limit;
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,8 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.NetEase.JsonModel
|
||||
{
|
||||
public class SongSearchResponse
|
||||
{
|
||||
@@ -10,10 +8,20 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel
|
||||
|
||||
[JsonProperty("code")] public int StatusCode { get; set; }
|
||||
|
||||
public int GetFirstMatchSongId(string songName)
|
||||
public int GetFirstMatchSongId(string songName, long? duration)
|
||||
{
|
||||
var item = Items.SongItems.FirstOrDefault(x => x.Name == songName);
|
||||
return item?.Id ?? Items.SongItems[0].Id;
|
||||
var perfectMatch = Items.SongItems.FirstOrDefault(x => x.Name == songName);
|
||||
if (perfectMatch != null)
|
||||
{
|
||||
return perfectMatch.Id;
|
||||
}
|
||||
|
||||
if (duration is null or 0)
|
||||
{
|
||||
return Items.SongItems.First().Id;
|
||||
}
|
||||
|
||||
return Items.SongItems.OrderBy(t => Math.Abs(t.Duration - duration.Value)).First().Id;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +57,12 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel
|
||||
/// </summary>
|
||||
[JsonProperty("album")]
|
||||
public SongAlbumModel Album { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 歌曲的实际长度。
|
||||
/// </summary>
|
||||
[JsonProperty("duration")]
|
||||
public long Duration { get; set; }
|
||||
}
|
||||
|
||||
public class SongArtistModel
|
@@ -1,4 +1,4 @@
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.NetEase.JsonModel
|
||||
{
|
||||
public static class SongSearchResponseStatusCode
|
||||
{
|
@@ -1,20 +1,20 @@
|
||||
using System;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Newtonsoft.Json;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase.JsonModel;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.Lyrics.Providers.NetEase.JsonModel;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.NetEase
|
||||
{
|
||||
public class NetEaseLyricDownloader : LyricDownloader
|
||||
public class NetEaseLyricsProvider : LyricsProvider
|
||||
{
|
||||
public override string DownloaderName => InternalLyricDownloaderNames.NetEase;
|
||||
public override string DownloaderName => InternalLyricsProviderNames.NetEase;
|
||||
|
||||
private readonly IWarpHttpClient _warpHttpClient;
|
||||
private readonly ILyricItemCollectionFactory _lyricItemCollectionFactory;
|
||||
private readonly ILyricsItemCollectionFactory _lyricsItemCollectionFactory;
|
||||
private readonly GlobalOptions _options;
|
||||
|
||||
private const string NetEaseSearchMusicUrl = @"https://music.163.com/api/search/get/web";
|
||||
private const string NetEaseGetLyricUrl = @"https://music.163.com/api/song/lyric";
|
||||
@@ -22,18 +22,20 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase
|
||||
private const string NetEaseRequestReferer = @"https://music.163.com";
|
||||
private const string NetEaseRequestContentType = @"application/x-www-form-urlencoded";
|
||||
|
||||
public NetEaseLyricDownloader(IWarpHttpClient warpHttpClient,
|
||||
ILyricItemCollectionFactory lyricItemCollectionFactory)
|
||||
public NetEaseLyricsProvider(IWarpHttpClient warpHttpClient,
|
||||
ILyricsItemCollectionFactory lyricsItemCollectionFactory,
|
||||
IOptions<GlobalOptions> options)
|
||||
{
|
||||
_warpHttpClient = warpHttpClient;
|
||||
_lyricItemCollectionFactory = lyricItemCollectionFactory;
|
||||
_lyricsItemCollectionFactory = lyricsItemCollectionFactory;
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
protected override async ValueTask<byte[]> DownloadDataAsync(LyricDownloaderArgs args)
|
||||
protected override async ValueTask<object> DownloadDataAsync(LyricsProviderArgs args)
|
||||
{
|
||||
var searchResult = await _warpHttpClient.PostAsync<SongSearchResponse>(
|
||||
NetEaseSearchMusicUrl,
|
||||
new SongSearchRequest(args.SongName, args.Artist),
|
||||
new SongSearchRequest(args.SongName, args.Artist, _options.Provider.Lyric.GetLyricProviderOption(DownloaderName).Depth),
|
||||
true,
|
||||
msg =>
|
||||
{
|
||||
@@ -46,35 +48,33 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.NetEase
|
||||
|
||||
ValidateSongSearchResponse(searchResult, args);
|
||||
|
||||
var lyricResponse = await _warpHttpClient.GetAsync(
|
||||
return await _warpHttpClient.GetAsync(
|
||||
NetEaseGetLyricUrl,
|
||||
new GetLyricRequest(searchResult.GetFirstMatchSongId(args.SongName)),
|
||||
new GetLyricRequest(searchResult.GetFirstMatchSongId(args.SongName, args.Duration)),
|
||||
msg => msg.Headers.Referrer = new Uri(NetEaseRequestReferer));
|
||||
|
||||
return Encoding.UTF8.GetBytes(lyricResponse);
|
||||
}
|
||||
|
||||
protected override async ValueTask<LyricItemCollection> GenerateLyricAsync(byte[] data, LyricDownloaderArgs args)
|
||||
protected override async ValueTask<LyricsItemCollection> GenerateLyricAsync(object lyricsObject, LyricsProviderArgs args)
|
||||
{
|
||||
await ValueTask.CompletedTask;
|
||||
|
||||
var json = JsonConvert.DeserializeObject<GetLyricResponse>(Encoding.UTF8.GetString(data));
|
||||
var json = JsonConvert.DeserializeObject<GetLyricResponse>((lyricsObject as string)!);
|
||||
if (json?.OriginalLyric == null || string.IsNullOrEmpty(json.OriginalLyric.Text))
|
||||
{
|
||||
return new LyricItemCollection(null);
|
||||
return new LyricsItemCollection(null);
|
||||
}
|
||||
|
||||
if (json.OriginalLyric.Text.Contains("纯音乐,请欣赏"))
|
||||
{
|
||||
return new LyricItemCollection(null);
|
||||
return new LyricsItemCollection(null);
|
||||
}
|
||||
|
||||
return _lyricItemCollectionFactory.Build(
|
||||
return _lyricsItemCollectionFactory.Build(
|
||||
json.OriginalLyric.Text,
|
||||
json.TranslationLyric.Text);
|
||||
}
|
||||
|
||||
protected virtual void ValidateSongSearchResponse(SongSearchResponse response, LyricDownloaderArgs args)
|
||||
protected virtual void ValidateSongSearchResponse(SongSearchResponse response, LyricsProviderArgs args)
|
||||
{
|
||||
if (response?.StatusCode != SongSearchResponseStatusCode.Success)
|
||||
{
|
@@ -1,12 +1,12 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.QQMusic.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.QQMusic.JsonModel
|
||||
{
|
||||
public class GetLyricRequest
|
||||
{
|
||||
[JsonProperty("nobase64")] public int IsNoBase64Encoding { get; set; }
|
||||
|
||||
[JsonProperty("songmid")] public string SongId { get; set; }
|
||||
[JsonProperty("songmid")] public string? SongId { get; set; }
|
||||
|
||||
[JsonProperty("platform")] public string ClientPlatform { get; set; }
|
||||
|
||||
@@ -20,7 +20,7 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.QQMusic.JsonModel
|
||||
{
|
||||
}
|
||||
|
||||
public GetLyricRequest(string songId)
|
||||
public GetLyricRequest(string? songId)
|
||||
{
|
||||
IsNoBase64Encoding = 1;
|
||||
SongId = songId;
|
@@ -0,0 +1,36 @@
|
||||
using System.Text;
|
||||
using System.Web;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.QQMusic.JsonModel
|
||||
{
|
||||
public class SongSearchRequest
|
||||
{
|
||||
[JsonProperty("format")]
|
||||
public string Format { get; protected set; }
|
||||
|
||||
[JsonProperty("inCharset")]
|
||||
public string InCharset { get; protected set; }
|
||||
|
||||
[JsonProperty("outCharset")]
|
||||
public string OutCharset { get; protected set; }
|
||||
|
||||
[JsonProperty("platform")]
|
||||
public string Platform { get; protected set; }
|
||||
|
||||
[JsonProperty("key")]
|
||||
public string Keyword { get; protected set; }
|
||||
|
||||
protected SongSearchRequest()
|
||||
{
|
||||
Format = "json";
|
||||
InCharset = OutCharset = "utf-8";
|
||||
Platform = "yqq.json";
|
||||
}
|
||||
|
||||
public SongSearchRequest(string musicName, string artistName) : this()
|
||||
{
|
||||
Keyword = HttpUtility.UrlEncode($"{musicName}+{artistName}", Encoding.UTF8);
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,7 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.QQMusic.JsonModel
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.QQMusic.JsonModel
|
||||
{
|
||||
public class SongSearchResponse
|
||||
{
|
||||
@@ -17,11 +16,11 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.QQMusic.JsonModel
|
||||
|
||||
public class QQMusicInnerSongModel
|
||||
{
|
||||
[JsonProperty("list")] public List<QQMusicInnerSongItem> SongItems { get; set; }
|
||||
[JsonProperty("itemlist")] public List<QQMusicInnerSongItem> SongItems { get; set; }
|
||||
}
|
||||
|
||||
public class QQMusicInnerSongItem
|
||||
{
|
||||
[JsonProperty("songmid")] public string SongId { get; set; }
|
||||
[JsonProperty("mid")] public string SongId { get; set; }
|
||||
}
|
||||
}
|
@@ -1,35 +1,32 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Lyric.QQMusic.JsonModel;
|
||||
using ZonyLrcTools.Cli.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.Lyrics.Providers.QQMusic.JsonModel;
|
||||
|
||||
namespace ZonyLrcTools.Cli.Infrastructure.Lyric.QQMusic
|
||||
namespace ZonyLrcTools.Common.Lyrics.Providers.QQMusic
|
||||
{
|
||||
public class QQLyricDownloader : LyricDownloader
|
||||
public class QQLyricsProvider : LyricsProvider
|
||||
{
|
||||
public override string DownloaderName => InternalLyricDownloaderNames.QQ;
|
||||
public override string DownloaderName => InternalLyricsProviderNames.QQ;
|
||||
|
||||
private readonly IWarpHttpClient _warpHttpClient;
|
||||
private readonly ILyricItemCollectionFactory _lyricItemCollectionFactory;
|
||||
private readonly ILyricsItemCollectionFactory _lyricsItemCollectionFactory;
|
||||
|
||||
private const string QQSearchMusicUrl = @"https://c.y.qq.com/soso/fcgi-bin/client_search_cp";
|
||||
// private const string QQSearchMusicUrl = @"https://c.y.qq.com/soso/fcgi-bin/client_search_cp";
|
||||
private const string QQSearchMusicUrl = @"https://c.y.qq.com/splcloud/fcgi-bin/smartbox_new.fcg";
|
||||
private const string QQGetLyricUrl = @"https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg";
|
||||
|
||||
private const string QQMusicRequestReferer = @"https://y.qq.com/";
|
||||
|
||||
public QQLyricDownloader(IWarpHttpClient warpHttpClient,
|
||||
ILyricItemCollectionFactory lyricItemCollectionFactory)
|
||||
public QQLyricsProvider(IWarpHttpClient warpHttpClient,
|
||||
ILyricsItemCollectionFactory lyricsItemCollectionFactory)
|
||||
{
|
||||
_warpHttpClient = warpHttpClient;
|
||||
_lyricItemCollectionFactory = lyricItemCollectionFactory;
|
||||
_lyricsItemCollectionFactory = lyricsItemCollectionFactory;
|
||||
}
|
||||
|
||||
protected override async ValueTask<byte[]> DownloadDataAsync(LyricDownloaderArgs args)
|
||||
protected override async ValueTask<object> DownloadDataAsync(LyricsProviderArgs args)
|
||||
{
|
||||
var searchResult = await _warpHttpClient.GetAsync<SongSearchResponse>(
|
||||
QQSearchMusicUrl,
|
||||
@@ -37,18 +34,16 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.QQMusic
|
||||
|
||||
ValidateSongSearchResponse(searchResult, args);
|
||||
|
||||
var lyricJsonString = await _warpHttpClient.GetAsync(QQGetLyricUrl,
|
||||
return await _warpHttpClient.GetAsync(QQGetLyricUrl,
|
||||
new GetLyricRequest(searchResult.Data.Song.SongItems.FirstOrDefault()?.SongId),
|
||||
op => op.Headers.Referrer = new Uri(QQMusicRequestReferer));
|
||||
|
||||
return Encoding.UTF8.GetBytes(lyricJsonString);
|
||||
}
|
||||
|
||||
protected override async ValueTask<LyricItemCollection> GenerateLyricAsync(byte[] data, LyricDownloaderArgs args)
|
||||
protected override async ValueTask<LyricsItemCollection> GenerateLyricAsync(object lyricsObject, LyricsProviderArgs args)
|
||||
{
|
||||
await ValueTask.CompletedTask;
|
||||
|
||||
var lyricJsonString = Encoding.UTF8.GetString(data);
|
||||
var lyricJsonString = (lyricsObject as string)!;
|
||||
lyricJsonString = lyricJsonString.Replace(@"MusicJsonCallback(", string.Empty).TrimEnd(')');
|
||||
|
||||
if (lyricJsonString.Contains("\"code\":-1901"))
|
||||
@@ -58,17 +53,17 @@ namespace ZonyLrcTools.Cli.Infrastructure.Lyric.QQMusic
|
||||
|
||||
if (lyricJsonString.Contains("此歌曲为没有填词的纯音乐,请您欣赏"))
|
||||
{
|
||||
return _lyricItemCollectionFactory.Build(null);
|
||||
return _lyricsItemCollectionFactory.Build(null);
|
||||
}
|
||||
|
||||
var lyricJsonObj = JObject.Parse(lyricJsonString);
|
||||
var sourceLyric = HttpUtility.HtmlDecode(HttpUtility.HtmlDecode(lyricJsonObj.SelectToken("$.lyric").Value<string>()));
|
||||
var translateLyric = HttpUtility.HtmlDecode(HttpUtility.HtmlDecode(lyricJsonObj.SelectToken("$.trans").Value<string>()));
|
||||
|
||||
return _lyricItemCollectionFactory.Build(sourceLyric, translateLyric);
|
||||
return _lyricsItemCollectionFactory.Build(sourceLyric, translateLyric);
|
||||
}
|
||||
|
||||
protected virtual void ValidateSongSearchResponse(SongSearchResponse response, LyricDownloaderArgs args)
|
||||
protected virtual void ValidateSongSearchResponse(SongSearchResponse response, LyricsProviderArgs args)
|
||||
{
|
||||
if (response is not { StatusCode: 0 } || response.Data.Song.SongItems == null)
|
||||
{
|
29
src/ZonyLrcTools.Common/MusicDecryption/DecryptionResult.cs
Normal file
29
src/ZonyLrcTools.Common/MusicDecryption/DecryptionResult.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
namespace ZonyLrcTools.Common.MusicDecryption
|
||||
{
|
||||
public sealed class DecryptionResult
|
||||
{
|
||||
public bool IsSuccess { get; set; } = false;
|
||||
|
||||
public string? OutputFilePath { get; set; } = default;
|
||||
|
||||
public string? ErrorMessage { get; set; } = default;
|
||||
|
||||
public static DecryptionResult Failed(string errorMessage)
|
||||
{
|
||||
return new DecryptionResult
|
||||
{
|
||||
IsSuccess = false,
|
||||
ErrorMessage = errorMessage
|
||||
};
|
||||
}
|
||||
|
||||
public static DecryptionResult Success(string outputFilePath)
|
||||
{
|
||||
return new DecryptionResult
|
||||
{
|
||||
IsSuccess = true,
|
||||
OutputFilePath = outputFilePath
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,44 @@
|
||||
using MusicDecrypto.Library;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
|
||||
namespace ZonyLrcTools.Common.MusicDecryption
|
||||
{
|
||||
/// <inheritdoc cref="ZonyLrcTools.Common.MusicDecryption.IMusicDecryptor" />
|
||||
public class DefaultMusicDecryptor : IMusicDecryptor, ITransientDependency
|
||||
{
|
||||
private readonly IWarpLogger _warpLogger;
|
||||
|
||||
public DefaultMusicDecryptor(IWarpLogger warpLogger)
|
||||
{
|
||||
_warpLogger = warpLogger;
|
||||
}
|
||||
|
||||
public async Task<DecryptionResult> ConvertMusicAsync(string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var buffer = new MarshalMemoryStream();
|
||||
await using var file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
|
||||
buffer.SetLengthWithPadding(file.Length);
|
||||
await file.CopyToAsync(buffer);
|
||||
|
||||
using var decrypto = DecryptoFactory.Create(buffer, Path.GetFileName(filePath), message => { });
|
||||
var outFileName = decrypto.Decrypt().NewName;
|
||||
var outFilePath = Path.Combine(Path.GetDirectoryName(filePath)!, outFileName);
|
||||
|
||||
if (!File.Exists(outFilePath))
|
||||
{
|
||||
await using var outFile = new FileStream(outFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||
await buffer.CopyToAsync(outFile);
|
||||
}
|
||||
|
||||
return DecryptionResult.Success(outFilePath);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return DecryptionResult.Failed(e.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
20
src/ZonyLrcTools.Common/MusicDecryption/IMusicDecryptor.cs
Normal file
20
src/ZonyLrcTools.Common/MusicDecryption/IMusicDecryptor.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using MusicDecrypto.Library;
|
||||
|
||||
namespace ZonyLrcTools.Common.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// 音乐解密器,用于将加密的歌曲数据,转换为可识别的歌曲格式。
|
||||
/// <remarks>
|
||||
/// 这个类型仅仅是对 <see cref="DecryptoFactory"/> 相关功能的封装,方便在本工具进行单元测试。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
public interface IMusicDecryptor
|
||||
{
|
||||
/// <summary>
|
||||
/// 将加密数据歌曲文件转换为可识别的歌曲格式。
|
||||
/// </summary>
|
||||
/// <param name="filePath">加密歌曲文件的路径。</param>
|
||||
/// <returns>转换结果。</returns>
|
||||
Task<DecryptionResult> ConvertMusicAsync(string filePath);
|
||||
}
|
||||
}
|
@@ -1,4 +1,4 @@
|
||||
namespace ZonyLrcTools.Cli.Infrastructure
|
||||
namespace ZonyLrcTools.Common
|
||||
{
|
||||
/// <summary>
|
||||
/// 歌曲信息的承载类,携带歌曲的相关数据。
|
||||
@@ -10,6 +10,11 @@ namespace ZonyLrcTools.Cli.Infrastructure
|
||||
/// </summary>
|
||||
public string FilePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 歌曲的实际歌曲长度。
|
||||
/// </summary>
|
||||
public long? TotalTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 歌曲的名称。
|
||||
/// </summary>
|
91
src/ZonyLrcTools.Common/MusicInfoLoader.cs
Normal file
91
src/ZonyLrcTools.Common/MusicInfoLoader.cs
Normal file
@@ -0,0 +1,91 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.IO;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
using ZonyLrcTools.Common.Infrastructure.Threading;
|
||||
using ZonyLrcTools.Common.TagInfo;
|
||||
|
||||
namespace ZonyLrcTools.Common;
|
||||
|
||||
public class MusicInfoLoader : IMusicInfoLoader, ITransientDependency
|
||||
{
|
||||
private readonly IWarpLogger _logger;
|
||||
private readonly IFileScanner _fileScanner;
|
||||
private readonly ITagLoader _tagLoader;
|
||||
private readonly GlobalOptions _options;
|
||||
|
||||
public MusicInfoLoader(IWarpLogger logger,
|
||||
ITagLoader tagLoader,
|
||||
IFileScanner fileScanner,
|
||||
IOptions<GlobalOptions> options)
|
||||
{
|
||||
_logger = logger;
|
||||
_tagLoader = tagLoader;
|
||||
_fileScanner = fileScanner;
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
public async Task<List<MusicInfo?>> LoadAsync(string dirPath,
|
||||
int parallelCount = 2,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var files = RemoveExistLyricFiles(await _fileScanner.ScanMusicFilesAsync(dirPath, _options.SupportFileExtensions));
|
||||
|
||||
if (files.Count == 0)
|
||||
{
|
||||
await _logger.ErrorAsync("没有找到任何音乐文件。");
|
||||
throw new ErrorCodeException(ErrorCodes.NoFilesWereScanned);
|
||||
}
|
||||
|
||||
await _logger.InfoAsync($"已经扫描到了 {files.Count} 个音乐文件。");
|
||||
|
||||
return await LoadAsync(files, parallelCount, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<List<MusicInfo?>> LoadAsync(IReadOnlyCollection<string> filePaths,
|
||||
int parallelCount = 2,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _logger.InfoAsync("开始加载音乐文件的标签信息...");
|
||||
|
||||
var warpTask = new WarpTask(parallelCount);
|
||||
var warpTaskList = filePaths.Select(file =>
|
||||
warpTask.RunAsync(() =>
|
||||
Task.Run(async () =>
|
||||
await _tagLoader.LoadTagAsync(file),
|
||||
cancellationToken),
|
||||
cancellationToken));
|
||||
|
||||
var result = (await Task.WhenAll(warpTaskList))
|
||||
.Where(m => m != null)
|
||||
.Where(m => !string.IsNullOrEmpty(m?.Name) || !string.IsNullOrEmpty(m?.Artist))
|
||||
.ToList();
|
||||
|
||||
await _logger.InfoAsync($"已成功加载 {filePaths.Count} 个音乐文件的标签信息。");
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<string> RemoveExistLyricFiles(IEnumerable<string> filePaths)
|
||||
{
|
||||
if (!_options.Provider.Lyric.Config.IsSkipExistLyricFiles)
|
||||
{
|
||||
return filePaths.ToList();
|
||||
}
|
||||
|
||||
return filePaths
|
||||
.Where(path =>
|
||||
{
|
||||
if (!File.Exists(Path.ChangeExtension(path, ".lrc")))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
_logger.WarnAsync($"已经存在歌词文件 {path},跳过。").GetAwaiter().GetResult();
|
||||
return false;
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user