Skip to content

Commit

Permalink
再重構
Browse files Browse the repository at this point in the history
  • Loading branch information
jim60105 committed Dec 20, 2022
1 parent 7c2d13a commit 4482f19
Show file tree
Hide file tree
Showing 6 changed files with 237 additions and 220 deletions.
17 changes: 10 additions & 7 deletions Downloader/LyricsDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ public LyricsDownloader(CloudMusicApi cloudMusicApi)
_cloudMusicApi = cloudMusicApi;
}

public async Task DownloadLyricAndWriteFileAsync(int songId)
public async Task<bool> DownloadLyricAndWriteFileAsync(int songId)
{
if (songId <= 0)
if (songId < 0)
{
throw new ArgumentException("SongId invalid.", nameof(songId));
}
Expand All @@ -25,7 +25,7 @@ public async Task DownloadLyricAndWriteFileAsync(int songId)
if (File.Exists($"Lyrics/{songId}.lrc"))
{
Console.WriteLine($"Lyric file {songId}.lrc already exists.");
return;
return true;
}

await Task.Delay(TimeSpan.FromMilliseconds(new Random().Next(500, 1500)));
Expand All @@ -35,7 +35,8 @@ public async Task DownloadLyricAndWriteFileAsync(int songId)

if (string.IsNullOrEmpty(lyricString))
{
throw new Exception("Can't find lyric.");
Console.Error.WriteLine("Can't find lyric.");
return false;
}

if (lyricString.Contains("纯音乐,请欣赏")
Expand All @@ -44,11 +45,13 @@ public async Task DownloadLyricAndWriteFileAsync(int songId)
// 小於6行
|| lyricString.Split('\n').Length < 6)
{
throw new Exception("Found an invalid lyric.");
Console.Error.WriteLine("Found an invalid lyric.");
return false;
}

await File.WriteAllTextAsync($"Lyrics/{songId}.lrc", lyricString, System.Text.Encoding.UTF8);
Console.WriteLine($"Write new lyric file {songId}.lrc.");
return true;
}

public async Task<(int songId, string songName)> GetSongIdAsync(ISong song, int offset = 0)
Expand All @@ -68,13 +71,13 @@ public async Task DownloadLyricAndWriteFileAsync(int songId)
if (!isOk || null == json)
{
Console.Error.WriteLine($"API response ${json?["code"] ?? "error"} while getting song id.");
return default;
return (0, string.Empty);
}

json = (JObject)json["result"];
return null == json
|| json["songs"] is not IEnumerable<JToken> result
? default
? (0, string.Empty)
: result.Select(t => ((int)t["id"], (string)t["name"]))
.FirstOrDefault();
}
Expand Down
65 changes: 57 additions & 8 deletions Processor/LyricsProcessor.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
using Lyrics.Models;
using Lyrics.Downloader;
using Lyrics.Models;

namespace Lyrics.Processor;

internal class LyricsProcessor
{
private readonly LyricsDownloader _lyricsDownloader;
private readonly List<ISong> _songs;
private readonly List<ILyric> _lyrics;
private readonly HashSet<string> _existsFiles;

public LyricsProcessor(ref List<ISong> songs, ref List<ILyric> lyrics)
public LyricsProcessor(LyricsDownloader lyricsDownloader, ref List<ISong> songs, ref List<ILyric> lyrics)
{
_lyricsDownloader = lyricsDownloader;
_songs = songs;
_lyrics = lyrics;
_existsFiles = new DirectoryInfo("Lyrics").GetFiles()
.Select(p => p.Name)
.ToHashSet();
}

public void ProcessLyricsFromENV(List<ILyric> lyricFromENV)
internal void ProcessLyricsFromENV(List<ILyric> lyricFromENV)
{
foreach (var item in lyricFromENV)
{
Expand All @@ -27,7 +34,7 @@ public void ProcessLyricsFromENV(List<ILyric> lyricFromENV)
}
}

public void RemoveExcludeSongs(List<(string VideoId, int StartTime)> excludeSongs)
internal void RemoveExcludeSongs(List<(string VideoId, int StartTime)> excludeSongs)
{
var hashSet = excludeSongs.ToHashSet();
var count = _songs.RemoveAll(p => hashSet.Contains((p.VideoId, p.StartTime)));
Expand All @@ -38,14 +45,14 @@ public void RemoveExcludeSongs(List<(string VideoId, int StartTime)> excludeSong
Console.WriteLine($"Exclude {count} songs from exclude list.");
}

public void RemoveSongsContainSpecifiedTitle(List<string> excludeTitles)
internal void RemoveSongsContainSpecifiedTitle(List<string> excludeTitles)
{
var count = _songs.RemoveAll(p => excludeTitles.Where(p1 => p.Title.Contains(p1, StringComparison.OrdinalIgnoreCase))
.Any());
Console.WriteLine($"Exclude {count} songs from specified title.");
}

public List<ILyric> RemoveLyricsNotContainsInSongs()
internal List<ILyric> RemoveLyricsNotContainsInSongs()
{
var songsHashSet = _songs.Select(p => (p.VideoId, p.StartTime))
.ToHashSet();
Expand All @@ -70,7 +77,7 @@ public List<ILyric> RemoveLyricsNotContainsInSongs()
/// Remove duplicate lyrics based on VideoId and StartTime. The first one will be used if duplicates.
/// </summary>
/// <returns></returns>
public List<ILyric> RemoveDuplicatesLyrics()
internal List<ILyric> RemoveDuplicatesLyrics()
{
HashSet<(string, int)> set = new();
List<ILyric> removed = new();
Expand All @@ -97,7 +104,7 @@ public List<ILyric> RemoveDuplicatesLyrics()
/// Filter out new songs that are not included in the lyrics.
/// </summary>
/// <returns></returns>
public List<ISong> FilterNewSongs()
internal List<ISong> FilterNewSongs()
{
if (Program.RETRY_FAILED_LYRICS) _lyrics.RemoveAll(p => p.LyricId < 0);

Expand All @@ -106,4 +113,46 @@ public List<ISong> FilterNewSongs()
return _songs.Where(p => !lyricsHashSet.Contains(p.VideoId + p.StartTime))
.ToList();
}

internal async Task DownloadMissingLyrics()
{
Console.WriteLine($"Start to download missing lyric files.");
HashSet<string> failedFiles = new();

foreach (var lyric in _lyrics)
{
if (lyric.LyricId <= 0) continue;
var filename = lyric.LyricId + ".lrc";

if (_existsFiles.Contains(filename)
|| failedFiles.Contains(filename)) continue;

if (await _lyricsDownloader.DownloadLyricAndWriteFileAsync(lyric.LyricId))
{
_existsFiles.Add(filename);
}
else
{
Console.Error.WriteLine($"Failed to download lyric {lyric.LyricId}");
failedFiles.Add(filename);
}
}
}

internal void RemoveLyricsNotInUsed()
{
HashSet<string> usedFiles = _lyrics.Where(p => p.LyricId >= 0)
.Select(p => p.LyricId + ".lrc")
.Distinct()
.ToHashSet();

foreach (var file in _existsFiles)
{
if (!usedFiles.Any(p => p == file))
{
File.Delete(Path.Combine("Lyrics", file));
Console.WriteLine($"Delete {file} because it is not in used.");
}
}
}
}
120 changes: 0 additions & 120 deletions Processor/NewSongProcessor.cs

This file was deleted.

76 changes: 0 additions & 76 deletions Processor/OldSongProcessor.cs

This file was deleted.

Loading

0 comments on commit 4482f19

Please sign in to comment.