-
Notifications
You must be signed in to change notification settings - Fork 8
/
LyricProcessor.cs
82 lines (71 loc) · 2.92 KB
/
LyricProcessor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.RegularExpressions;
namespace MusicBeePlugin
{
[SuppressMessage("ReSharper", "InconsistentNaming")]
internal static class LyricProcessor
{
private static readonly Regex LyricLineRegex = new Regex(@"((\[.+?])+)(.*)", RegexOptions.Compiled);
public static string InjectTranslation(string originalLrc, string translationLrc)
{
var originalEntries = ExpandEntries(Parse(originalLrc));
var translationEntries = ExpandEntries(Parse(translationLrc));
foreach (var originalEntry in originalEntries)
{
var translationEntry = translationEntries.FirstOrDefault(entry => entry.timeLabel == originalEntry.timeLabel);
if (translationEntry != null)
originalEntry.content += "/" + translationEntry.content;
}
originalEntries.Sort();
return string.Join("\n", originalEntries);
}
private static List<LyricEntry> Parse(string lrc)
{
var result = lrc.Split('\n')
.Where(line => !string.IsNullOrWhiteSpace(line))
.Select(line => LyricLineRegex.Matches(line))
.Where(matches => matches.Count >= 1)
.Select(matches => matches[0])
.Where(match => match.Groups.Count >= 3)
.SelectMany(match => match.Groups[1].Captures.Cast<Capture>(),
(match, capture) => new LyricEntry(capture.Value, match.Groups[3].Value))
.ToList();
return result;
}
private static List<LyricEntry> ExpandEntries(List<LyricEntry> entries)
{
return entries.SelectMany(entry => entry.ExpandTimeLabel()).ToList();
}
}
[SuppressMessage("ReSharper", "InconsistentNaming")]
internal class LyricEntry : IComparable<LyricEntry>
{
private static readonly Regex LyricTimeRegex = new Regex(@"(\[[0-9.:]*])", RegexOptions.Compiled);
public string timeLabel;
public string content;
public LyricEntry(string timeLabel, string content)
{
this.timeLabel = timeLabel;
this.content = content;
}
public override string ToString()
{
return timeLabel + content;
}
public IEnumerable<LyricEntry> ExpandTimeLabel()
{
var matches = LyricTimeRegex.Matches(timeLabel);
foreach (var match in matches.Cast<Match>())
yield return new LyricEntry(match.Value, content);
}
public int CompareTo(LyricEntry other)
{
if (ReferenceEquals(this, other)) return 0;
if (ReferenceEquals(null, other)) return 1;
return string.Compare(timeLabel, other.timeLabel, StringComparison.Ordinal);
}
}
}