TxtLyricsProvider.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Dynamic;
  5. using System.Globalization;
  6. using System.Linq;
  7. using LrcParser.Model;
  8. using LrcParser.Parser;
  9. using MediaBrowser.Controller.Entities;
  10. namespace Jellyfin.Api.Models.UserDtos
  11. {
  12. /// <summary>
  13. /// TXT File Lyric Provider.
  14. /// </summary>
  15. public class TxtLyricsProvider : ILyricsProvider
  16. {
  17. /// <summary>
  18. /// Initializes a new instance of the <see cref="TxtLyricsProvider"/> class.
  19. /// </summary>
  20. public TxtLyricsProvider()
  21. {
  22. FileExtensions = new Collection<string>
  23. {
  24. "lrc", "txt"
  25. };
  26. }
  27. /// <summary>
  28. /// Gets a value indicating the File Extenstions this provider works with.
  29. /// </summary>
  30. public Collection<string>? FileExtensions { get; }
  31. /// <summary>
  32. /// Gets or Sets a value indicating whether Process() generated data.
  33. /// </summary>
  34. /// <returns><c>true</c> if data generated; otherwise, <c>false</c>.</returns>
  35. public bool HasData { get; set; }
  36. /// <summary>
  37. /// Gets or Sets Data object generated by Process() method.
  38. /// </summary>
  39. /// <returns><c>Object</c> with data if no error occured; otherwise, <c>null</c>.</returns>
  40. public object? Data { get; set; }
  41. /// <summary>
  42. /// Opens lyric file for [the specified item], and processes it for API return.
  43. /// </summary>
  44. /// <param name="item">The item to to process.</param>
  45. public void Process(BaseItem item)
  46. {
  47. string? lyricFilePath = Helpers.ItemHelper.GetLyricFilePath(item.Path);
  48. if (string.IsNullOrEmpty(lyricFilePath))
  49. {
  50. return;
  51. }
  52. List<Lyric> lyricsList = new List<Lyric>();
  53. string lyricData = System.IO.File.ReadAllText(lyricFilePath);
  54. // Splitting on Environment.NewLine caused some new lines to be missed in Windows.
  55. char[] newLinedelims = new[] { '\r', '\n' };
  56. string[] lyricTextLines = lyricData.Split(newLinedelims, StringSplitOptions.RemoveEmptyEntries);
  57. if (!lyricTextLines.Any())
  58. {
  59. return;
  60. }
  61. foreach (string lyricLine in lyricTextLines)
  62. {
  63. lyricsList.Add(new Lyric { Text = lyricLine });
  64. }
  65. this.HasData = true;
  66. this.Data = new { lyrics = lyricsList };
  67. }
  68. }
  69. }