Skip to content

Commit

Permalink
修复登录失败
Browse files Browse the repository at this point in the history
更新api
代码清理
  • Loading branch information
wwh1004 committed Feb 20, 2021
1 parent dfa291c commit 0696aad
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 74 deletions.
4 changes: 2 additions & 2 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ root = true

[*]
charset = utf-8
end_of_line = crlf
end_of_line = crlf
indent_style = tab
trim_trailing_whitespace = true
insert_final_newline = true
Expand Down Expand Up @@ -77,7 +77,7 @@ csharp_style_expression_bodied_properties = true:suggestion
# Pattern matching preferences
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_prefer_switch_expression = true:suggestion
csharp_style_prefer_switch_expression = false:suggestion

# Null-checking preferences
csharp_style_conditional_delegate_call = true:suggestion
Expand Down
15 changes: 7 additions & 8 deletions NLyric/ChineseConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,13 @@ internal static class ChineseConverter {

private static Dictionary<char, char> GetTraditionalToSimplifiedMap() {
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("NLyric.TraditionalToSimplified.map"))
using (var reader = new BinaryReader(stream)) {
int count = (int)stream.Length / 4;
var map = new Dictionary<char, char>(count);
for (int i = 0; i < count; i++)
map.Add((char)reader.ReadUInt16(), (char)reader.ReadUInt16());
return map;
}
using var stream = assembly.GetManifestResourceStream("NLyric.TraditionalToSimplified.map");
using var reader = new BinaryReader(stream);
int count = (int)stream.Length / 4;
var map = new Dictionary<char, char>(count);
for (int i = 0; i < count; i++)
map.Add((char)reader.ReadUInt16(), (char)reader.ReadUInt16());
return map;
}

public static string TraditionalToSimplified(string s) {
Expand Down
20 changes: 9 additions & 11 deletions NLyric/Lyrics/Lrc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,11 @@ public static Lrc Parse(string text) {
throw new ArgumentNullException(nameof(text));

var lrc = new Lrc();
using (var reader = new StringReader(text)) {
string line;
while (!((line = reader.ReadLine()?.Trim()) is null) && !string.IsNullOrEmpty(line)) {
if (!TryParseLine(line, lrc))
throw new FormatException();
}
using var reader = new StringReader(text);
string line;
while (!((line = reader.ReadLine()?.Trim()) is null) && !string.IsNullOrEmpty(line)) {
if (!TryParseLine(line, lrc))
throw new FormatException();
}
return lrc;
}
Expand All @@ -101,11 +100,10 @@ public static Lrc UnsafeParse(string text) {
throw new ArgumentNullException(nameof(text));

var lrc = new Lrc();
using (var reader = new StringReader(text)) {
string line;
while (!((line = reader.ReadLine()?.Trim()) is null))
TryParseLine(line.Trim(), lrc);
}
using var reader = new StringReader(text);
string line;
while (!((line = reader.ReadLine()?.Trim()) is null))
TryParseLine(line.Trim(), lrc);
return lrc;
}

Expand Down
7 changes: 4 additions & 3 deletions NLyric/NLyric.csproj
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Title>$(ProjectName)</Title>
<Version>2.6.0.1</Version>
<Copyright>Copyright © 2019-2020 Wwh</Copyright>
<Version>2.6.1.0</Version>
<Copyright>Copyright © 2019-2021 Wwh</Copyright>
</PropertyGroup>
<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks>
<LangVersion>8.0</LangVersion>
<OutputPath>..\bin\$(Configuration)</OutputPath>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NeteaseCloudMusicApi" Version="3.25.3" />
<PackageReference Include="NeteaseCloudMusicApi" Version="3.25.3.9999" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="TagLibSharp" Version="2.2.0" />
</ItemGroup>
Expand Down
40 changes: 20 additions & 20 deletions NLyric/NLyricImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public static class NLyricImpl {
private static readonly FuzzySettings _fuzzySettings = AllSettings.Default.Fuzzy;
private static readonly MatchSettings _matchSettings = AllSettings.Default.Match;
private static readonly LyricSettings _lyricSettings = AllSettings.Default.Lyric;
private static readonly CloudMusic _cloudMusic = new CloudMusic();
private static readonly HashSet<string> _failMatchAlbums = new HashSet<string>();
// AlbumName
private static readonly Dictionary<int, NcmTrack[]> _cachedNcmTrackses = new Dictionary<int, NcmTrack[]>();
Expand Down Expand Up @@ -57,7 +58,7 @@ private static async Task LoginIfNeedAsync(Arguments arguments) {
}
else {
FastConsole.WriteLine("登录中...", ConsoleColor.Green);
if (await CloudMusic.LoginAsync(arguments.Account, arguments.Password)) {
if (await _cloudMusic.LoginAsync(arguments.Account, arguments.Password)) {
FastConsole.WriteLine("登录成功!", ConsoleColor.Green);
}
else {
Expand Down Expand Up @@ -245,7 +246,7 @@ private static async Task<AlbumInfo> SearchAlbumAsync(Album album) {
private static async Task<NcmTrack[]> GetAlbumTracksAsync(AlbumInfo albumInfo) {
if (!_cachedNcmTrackses.TryGetValue(albumInfo.Id, out var ncmTracks)) {
var list = new List<NcmTrack>();
foreach (var item in await CloudMusic.GetTracksAsync(albumInfo.Id)) {
foreach (var item in await _cloudMusic.GetTracksAsync(albumInfo.Id)) {
if ((await GetLyricAsync(item.Id)).IsCollected)
list.Add(item);
}
Expand Down Expand Up @@ -305,7 +306,7 @@ private static async Task<NcmAlbum> MapToAsync(Album album) {
private static async Task<NcmTrack> MapToAsync(Track track, bool withArtists) {
var ncmTracks = default(NcmTrack[]);
try {
ncmTracks = await CloudMusic.SearchTrackAsync(track, _searchSettings.Limit, withArtists);
ncmTracks = await _cloudMusic.SearchTrackAsync(track, _searchSettings.Limit, withArtists);
}
catch (KeywordForbiddenException ex1) {
FastConsole.WriteError(ex1.Message);
Expand Down Expand Up @@ -333,7 +334,7 @@ private static async Task<NcmTrack> MapToAsync(Track track, bool withArtists) {
private static async Task<NcmAlbum> MapToAsync(Album album, bool withArtists) {
var ncmAlbums = default(NcmAlbum[]);
try {
ncmAlbums = await CloudMusic.SearchAlbumAsync(album, _searchSettings.Limit, withArtists);
ncmAlbums = await _cloudMusic.SearchAlbumAsync(album, _searchSettings.Limit, withArtists);
}
catch (KeywordForbiddenException ex1) {
FastConsole.WriteError(ex1.Message);
Expand Down Expand Up @@ -389,19 +390,18 @@ private static void SortDatabase() {
}

private static void SaveDatabaseCore(string databasePath) {
using (var stream = new FileStream(databasePath, FileMode.OpenOrCreate))
using (var writer = new StreamWriter(stream))
writer.Write(FormatJson(JsonConvert.SerializeObject(_database)));
using var stream = new FileStream(databasePath, FileMode.OpenOrCreate);
using var writer = new StreamWriter(stream);
writer.Write(FormatJson(JsonConvert.SerializeObject(_database)));
}

private static string FormatJson(string json) {
using (var writer = new StringWriter())
using (var jsonWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented })
using (var reader = new StringReader(json))
using (var jsonReader = new JsonTextReader(reader)) {
jsonWriter.WriteToken(jsonReader);
return writer.ToString();
}
using var writer = new StringWriter();
using var jsonWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented };
using var reader = new StringReader(json);
using var jsonReader = new JsonTextReader(reader);
jsonWriter.WriteToken(jsonReader);
return writer.ToString();
}
#endregion

Expand Down Expand Up @@ -498,7 +498,7 @@ private static TSource Select<TSource, TTarget>(TSource[] sources, TTarget targe
FastConsole.WriteInfo("已选择:" + result.ToString());
return result;

string TrackOrAlbumToString(ITrackOrAlbum trackOrAlbum) {
static string TrackOrAlbumToString(ITrackOrAlbum trackOrAlbum) {
if (trackOrAlbum.Artists.Count == 0)
return trackOrAlbum.Name;
return trackOrAlbum.Name + " by " + string.Join(",", trackOrAlbum.Artists);
Expand Down Expand Up @@ -598,7 +598,7 @@ private static async Task<bool> TryDownloadLyricAsync(AudioInfo audioInfo) {

private static async Task<NcmLyric> GetLyricAsync(int trackId) {
if (!_cachedNcmLyrics.TryGetValue(trackId, out var lyric)) {
lyric = await CloudMusic.GetLyricAsync(trackId);
lyric = await _cloudMusic.GetLyricAsync(trackId);
lock (((ICollection)_cachedNcmLyrics).SyncRoot)
_cachedNcmLyrics[trackId] = lyric;
}
Expand Down Expand Up @@ -701,12 +701,12 @@ private static Task AccelerateAllTracksAsync(AudioInfo[] audioInfos) {
}

private static async Task AccelerateAllLyricsAsync(AudioInfo[] audioInfos) {
const int STEP = 100;
const int STEP = 50;

int[] trackIds = audioInfos.Select(t => t.TrackInfo.Id).ToArray();
for (int i = 0; i < trackIds.Length; i += STEP) {
var trackIdMap = new Dictionary<string, int>(STEP);
var queries = new Dictionary<string, string>(STEP);
var queries = new Dictionary<string, object>(STEP);
int kMax = i + STEP <= trackIds.Length ? STEP : trackIds.Length % STEP;
for (int k = 0; k < kMax; k++) {
string route = "/api/song/lyric" + new string('/', k);
Expand All @@ -718,7 +718,7 @@ private static async Task AccelerateAllLyricsAsync(AudioInfo[] audioInfos) {
["tv"] = -1
});
}
var (isOk, json) = await CloudMusic.Api.RequestAsync(CloudMusicApiProviders.Batch, queries);
var (isOk, json) = await _cloudMusic.Api.RequestAsync(CloudMusicApiProviders.Batch, queries);
if (!isOk) {
FastConsole.WriteError($"[Experimental] 歌词 {i}+{STEP} 加速失败!");
continue;
Expand All @@ -730,7 +730,7 @@ private static async Task AccelerateAllLyricsAsync(AudioInfo[] audioInfos) {
FastConsole.WriteError($"[Experimental] 歌词 {trackId} at {i}+{STEP} 加速失败!");
continue;
}
_cachedNcmLyrics[trackId] = CloudMusic.ParseLyric(trackId, lyricJson);
_cachedNcmLyrics[trackId] = _cloudMusic.ParseLyric(trackId, lyricJson);
}
}
}
Expand Down
56 changes: 28 additions & 28 deletions NLyric/Ncm/CloudMusic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,21 @@
using NLyric.Lyrics;

namespace NLyric.Ncm {
public static class CloudMusic {
private static readonly CloudMusicApi _api = new CloudMusicApi();
public sealed class CloudMusic {
private readonly CloudMusicApi _api = new CloudMusicApi();

public static CloudMusicApi Api => _api;
public CloudMusicApi Api => _api;

public static async Task<bool> LoginAsync(string account, string password) {
var queries = new Dictionary<string, string>();
public async Task<bool> LoginAsync(string account, string password) {
var queries = new Dictionary<string, object>();
bool isPhone = Regex.Match(account, "^[0-9]+$").Success;
queries[isPhone ? "phone" : "email"] = account;
queries["password"] = password;
var (result, _) = await _api.RequestAsync(isPhone ? CloudMusicApiProviders.LoginCellphone : CloudMusicApiProviders.Login, queries);
return result;
}

public static async Task<NcmTrack[]> SearchTrackAsync(Track track, int limit, bool withArtists) {
public async Task<NcmTrack[]> SearchTrackAsync(Track track, int limit, bool withArtists) {
var keywords = new List<string>();
if (track.Name.Length != 0)
keywords.Add(track.Name);
Expand All @@ -33,10 +33,10 @@ public static async Task<NcmTrack[]> SearchTrackAsync(Track track, int limit, bo
throw new ArgumentException("歌曲信息无效");
for (int i = 0; i < keywords.Count; i++)
keywords[i] = keywords[i].WholeWordReplace();
var (isOk, json) = await _api.RequestAsync(CloudMusicApiProviders.Search, new Dictionary<string, string> {
var (isOk, json) = await _api.RequestAsync(CloudMusicApiProviders.Search, new Dictionary<string, object> {
{ "keywords", string.Join(" ", keywords) },
{ "type", "1" },
{ "limit", limit.ToString() }
{ "type", 1 },
{ "limit", limit }
});
if (!isOk)
throw new ApplicationException(nameof(CloudMusicApiProviders.Search) + " API错误");
Expand All @@ -45,14 +45,14 @@ public static async Task<NcmTrack[]> SearchTrackAsync(Track track, int limit, bo
return ParseSearchTracks(json);
}

public static NcmTrack[] ParseSearchTracks(JObject json) {
public NcmTrack[] ParseSearchTracks(JObject json) {
json = (JObject)json["result"];
if (!(json["songs"] is JArray songs))
return Array.Empty<NcmTrack>();
return songs.Select(t => ParseTrack(t, false)).ToArray();
}

public static async Task<NcmAlbum[]> SearchAlbumAsync(Album album, int limit, bool withArtists) {
public async Task<NcmAlbum[]> SearchAlbumAsync(Album album, int limit, bool withArtists) {
var keywords = new List<string>();
if (album.Name.Length != 0)
keywords.Add(album.Name);
Expand All @@ -62,10 +62,10 @@ public static async Task<NcmAlbum[]> SearchAlbumAsync(Album album, int limit, bo
throw new ArgumentException("专辑信息无效");
for (int i = 0; i < keywords.Count; i++)
keywords[i] = keywords[i].WholeWordReplace();
var (isOk, json) = await _api.RequestAsync(CloudMusicApiProviders.Search, new Dictionary<string, string> {
var (isOk, json) = await _api.RequestAsync(CloudMusicApiProviders.Search, new Dictionary<string, object> {
{ "keywords", string.Join(" ", keywords) },
{ "type", "10" },
{ "limit", limit.ToString() }
{ "type", 10 },
{ "limit", limit }
});
if (!isOk)
throw new ApplicationException(nameof(CloudMusicApiProviders.Search) + " API错误");
Expand All @@ -74,37 +74,37 @@ public static async Task<NcmAlbum[]> SearchAlbumAsync(Album album, int limit, bo
return ParseSearchAlbums(json);
}

public static NcmAlbum[] ParseSearchAlbums(JObject json) {
public NcmAlbum[] ParseSearchAlbums(JObject json) {
json = (JObject)json["result"];
if (!(json["albums"] is JArray albums))
return Array.Empty<NcmAlbum>();
// albumCount不可信,搜索"U-87 陈奕迅"返回albums有内容,但是albumCount为0
return albums.Select(t => ParseAlbum(t)).ToArray();
}

public static async Task<NcmTrack[]> GetTracksAsync(int albumId) {
var (isOk, json) = await _api.RequestAsync(CloudMusicApiProviders.Album, new Dictionary<string, string> {
{ "id", albumId.ToString() }
public async Task<NcmTrack[]> GetTracksAsync(int albumId) {
var (isOk, json) = await _api.RequestAsync(CloudMusicApiProviders.Album, new Dictionary<string, object> {
{ "id", albumId }
});
if (!isOk)
throw new ApplicationException(nameof(CloudMusicApiProviders.Album) + " API错误");
return ParseTracks(json);
}

public static NcmTrack[] ParseTracks(JObject json) {
public NcmTrack[] ParseTracks(JObject json) {
return json["songs"].Select(t => ParseTrack(t, true)).ToArray();
}

public static async Task<NcmLyric> GetLyricAsync(int trackId) {
var (isOk, json) = await _api.RequestAsync(CloudMusicApiProviders.Lyric, new Dictionary<string, string> {
{ "id", trackId.ToString() }
public async Task<NcmLyric> GetLyricAsync(int trackId) {
var (isOk, json) = await _api.RequestAsync(CloudMusicApiProviders.Lyric, new Dictionary<string, object> {
{ "id", trackId }
});
if (!isOk)
throw new ApplicationException(nameof(CloudMusicApiProviders.Lyric) + " API错误");
return ParseLyric(trackId, json);
}

public static NcmLyric ParseLyric(int trackId, JObject json) {
public NcmLyric ParseLyric(int trackId, JObject json) {
if (json is null)
throw new ArgumentNullException(nameof(json));

Expand All @@ -119,26 +119,26 @@ public static NcmLyric ParseLyric(int trackId, JObject json) {
return new NcmLyric(trackId, true, false, rawLrc, rawVersion, translatedLrc, translatedVersion);
}

private static NcmAlbum ParseAlbum(JToken json) {
private NcmAlbum ParseAlbum(JToken json) {
var album = new Album((string)json["name"], ParseNames(json["artists"]));
var ncmAlbum = new NcmAlbum(album, (int)json["id"]);
return ncmAlbum;
}

private static NcmTrack ParseTrack(JToken json, bool isShortName) {
private NcmTrack ParseTrack(JToken json, bool isShortName) {
var track = new Track((string)json["name"], ParseNames(json[isShortName ? "ar" : "artists"]));
var ncmTrack = new NcmTrack(track, (int)json["id"]);
return ncmTrack;
}

private static string[] ParseNames(JToken json) {
private string[] ParseNames(JToken json) {
return json.Select(t => (string)t["name"]).ToArray();
}

private static (Lrc, int) ParseLyric(JToken json) {
private (Lrc, int) ParseLyric(JToken json) {
string lyric = (string)json["lyric"];
var lrc = string.IsNullOrEmpty(lyric) ? null : Lrc.UnsafeParse(lyric);
var version = (int)json["version"];
int version = (int)json["version"];
return (lrc, version);
}
}
Expand Down
4 changes: 2 additions & 2 deletions NLyric/The163KeyHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ public static bool TryGetTrackId(Tag tag, out int trackId) {
try {
the163Key = the163Key.Substring(22);
byte[] byt163Key = Convert.FromBase64String(the163Key);
using (var cryptoTransform = _aes.CreateDecryptor())
byt163Key = cryptoTransform.TransformFinalBlock(byt163Key, 0, byt163Key.Length);
using var cryptoTransform = _aes.CreateDecryptor();
byt163Key = cryptoTransform.TransformFinalBlock(byt163Key, 0, byt163Key.Length);
trackId = (int)JObject.Parse(Encoding.UTF8.GetString(byt163Key).Substring(6))["musicId"];
}
catch {
Expand Down

0 comments on commit 0696aad

Please sign in to comment.