LrcLyricProvider.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using LrcParser.Model;
  7. using LrcParser.Parser;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Lyrics;
  10. using MediaBrowser.Controller.Resolvers;
  11. using Microsoft.Extensions.Logging;
  12. namespace MediaBrowser.Providers.Lyric;
  13. /// <summary>
  14. /// LRC Lyric Provider.
  15. /// </summary>
  16. public class LrcLyricProvider : ILyricProvider
  17. {
  18. private readonly ILogger<LrcLyricProvider> _logger;
  19. private readonly LyricParser _lrcLyricParser;
  20. private static readonly string[] _acceptedTimeFormats = { "HH:mm:ss", "H:mm:ss", "mm:ss", "m:ss" };
  21. /// <summary>
  22. /// Initializes a new instance of the <see cref="LrcLyricProvider"/> class.
  23. /// </summary>
  24. /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
  25. public LrcLyricProvider(ILogger<LrcLyricProvider> logger)
  26. {
  27. _logger = logger;
  28. _lrcLyricParser = new LrcParser.Parser.Lrc.LrcParser();
  29. }
  30. /// <inheritdoc />
  31. public string Name => "LrcLyricProvider";
  32. /// <summary>
  33. /// Gets the priority.
  34. /// </summary>
  35. /// <value>The priority.</value>
  36. public ResolverPriority Priority => ResolverPriority.First;
  37. /// <inheritdoc />
  38. public IReadOnlyCollection<string> SupportedMediaTypes { get; } = new[] { "lrc", "elrc" };
  39. /// <summary>
  40. /// Opens lyric file for the requested item, and processes it for API return.
  41. /// </summary>
  42. /// <param name="item">The item to to process.</param>
  43. /// <returns>If provider can determine lyrics, returns a <see cref="LyricResponse"/> with or without metadata; otherwise, null.</returns>
  44. public LyricResponse? GetLyrics(BaseItem item)
  45. {
  46. string? lyricFilePath = this.GetLyricFilePath(item.Path);
  47. if (string.IsNullOrEmpty(lyricFilePath))
  48. {
  49. return null;
  50. }
  51. var fileMetaData = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  52. string lrcFileContent = File.ReadAllText(lyricFilePath);
  53. Song lyricData;
  54. try
  55. {
  56. lyricData = _lrcLyricParser.Decode(lrcFileContent);
  57. }
  58. catch (Exception ex)
  59. {
  60. _logger.LogError(ex, "Error parsing lyric file {LyricFilePath} from {Provider}", lyricFilePath, Name);
  61. return null;
  62. }
  63. List<LrcParser.Model.Lyric> sortedLyricData = lyricData.Lyrics.Where(x => x.TimeTags.Count > 0).OrderBy(x => x.TimeTags.First().Value).ToList();
  64. // Parse metadata rows
  65. var metaDataRows = lyricData.Lyrics
  66. .Where(x => x.TimeTags.Count == 0)
  67. .Where(x => x.Text.StartsWith('[') && x.Text.EndsWith(']'))
  68. .Select(x => x.Text)
  69. .ToList();
  70. foreach (string metaDataRow in metaDataRows)
  71. {
  72. var index = metaDataRow.IndexOf(':', StringComparison.OrdinalIgnoreCase);
  73. if (index == -1)
  74. {
  75. continue;
  76. }
  77. // Remove square bracket before field name, and after field value
  78. // Example 1: [au: 1hitsong]
  79. // Example 2: [ar: Calabrese]
  80. var metaDataFieldNameSpan = metaDataRow.AsSpan(1, index - 1).Trim();
  81. var metaDataFieldValueSpan = metaDataRow.AsSpan(index + 1, metaDataRow.Length - index - 2).Trim();
  82. if (metaDataFieldValueSpan.IsEmpty || metaDataFieldValueSpan.IsEmpty)
  83. {
  84. continue;
  85. }
  86. fileMetaData[metaDataFieldNameSpan.ToString()] = metaDataFieldValueSpan.ToString();
  87. }
  88. if (sortedLyricData.Count == 0)
  89. {
  90. return null;
  91. }
  92. List<LyricLine> lyricList = new();
  93. for (int i = 0; i < sortedLyricData.Count; i++)
  94. {
  95. var timeData = sortedLyricData[i].TimeTags.First().Value;
  96. if (timeData is null)
  97. {
  98. continue;
  99. }
  100. long ticks = TimeSpan.FromMilliseconds(timeData.Value).Ticks;
  101. lyricList.Add(new LyricLine(sortedLyricData[i].Text, ticks));
  102. }
  103. if (fileMetaData.Count != 0)
  104. {
  105. // Map metaData values from LRC file to LyricMetadata properties
  106. LyricMetadata lyricMetadata = MapMetadataValues(fileMetaData);
  107. return new LyricResponse { Metadata = lyricMetadata, Lyrics = lyricList };
  108. }
  109. return new LyricResponse { Lyrics = lyricList };
  110. }
  111. /// <summary>
  112. /// Converts metadata from an LRC file to LyricMetadata properties.
  113. /// </summary>
  114. /// <param name="metaData">The metadata from the LRC file.</param>
  115. /// <returns>A lyricMetadata object with mapped property data.</returns>
  116. private static LyricMetadata MapMetadataValues(IDictionary<string, string> metaData)
  117. {
  118. LyricMetadata lyricMetadata = new();
  119. if (metaData.TryGetValue("ar", out var artist) && !string.IsNullOrEmpty(artist))
  120. {
  121. lyricMetadata.Artist = artist;
  122. }
  123. if (metaData.TryGetValue("al", out var album) && !string.IsNullOrEmpty(album))
  124. {
  125. lyricMetadata.Album = album;
  126. }
  127. if (metaData.TryGetValue("ti", out var title) && !string.IsNullOrEmpty(title))
  128. {
  129. lyricMetadata.Title = title;
  130. }
  131. if (metaData.TryGetValue("au", out var author) && !string.IsNullOrEmpty(author))
  132. {
  133. lyricMetadata.Author = author;
  134. }
  135. if (metaData.TryGetValue("length", out var length) && !string.IsNullOrEmpty(length))
  136. {
  137. if (DateTime.TryParseExact(length, _acceptedTimeFormats, null, DateTimeStyles.None, out var value))
  138. {
  139. lyricMetadata.Length = value.TimeOfDay.Ticks;
  140. }
  141. }
  142. if (metaData.TryGetValue("by", out var by) && !string.IsNullOrEmpty(by))
  143. {
  144. lyricMetadata.By = by;
  145. }
  146. if (metaData.TryGetValue("offset", out var offset) && !string.IsNullOrEmpty(offset))
  147. {
  148. if (int.TryParse(offset, out var value))
  149. {
  150. lyricMetadata.Offset = TimeSpan.FromMilliseconds(value).Ticks;
  151. }
  152. }
  153. if (metaData.TryGetValue("re", out var creator) && !string.IsNullOrEmpty(creator))
  154. {
  155. lyricMetadata.Creator = creator;
  156. }
  157. if (metaData.TryGetValue("ve", out var version) && !string.IsNullOrEmpty(version))
  158. {
  159. lyricMetadata.Version = version;
  160. }
  161. return lyricMetadata;
  162. }
  163. }