aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Api/Models/UserDtos/TxtLyricsProvider.cs
blob: 03cce1ffbb4e3f326f54f09e4b534da76d91766f (plain)
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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using LrcParser.Model;
using LrcParser.Parser;
using MediaBrowser.Controller.Entities;

namespace Jellyfin.Api.Models.UserDtos
{
    /// <summary>
    /// TXT File Lyric Provider.
    /// </summary>
    public class TxtLyricsProvider : ILyricsProvider
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="TxtLyricsProvider"/> class.
        /// </summary>
        public TxtLyricsProvider()
        {
            FileExtensions = new Collection<string>
            {
                "lrc", "txt"
            };
        }

        /// <summary>
        /// Gets a value indicating the File Extenstions this provider works with.
        /// </summary>
        public Collection<string>? FileExtensions { get; }

        /// <summary>
        /// Gets or Sets a value indicating whether Process() generated data.
        /// </summary>
        /// <returns><c>true</c> if data generated; otherwise, <c>false</c>.</returns>
        public bool HasData { get; set; }

        /// <summary>
        /// Gets or Sets Data object generated by Process() method.
        /// </summary>
        /// <returns><c>Object</c> with data if no error occured; otherwise, <c>null</c>.</returns>
        public object? Data { get; set; }

        /// <summary>
        /// Opens lyric file for [the specified item], and processes it for API return.
        /// </summary>
        /// <param name="item">The item to to process.</param>
        public void Process(BaseItem item)
        {
            string? lyricFilePath = Helpers.ItemHelper.GetLyricFilePath(item.Path);

            if (string.IsNullOrEmpty(lyricFilePath))
            {
                return;
            }

            List<Lyric> lyricsList = new List<Lyric>();

            string lyricData = System.IO.File.ReadAllText(lyricFilePath);

            // Splitting on Environment.NewLine caused some new lines to be missed in Windows.
            char[] newLinedelims = new[] { '\r', '\n' };
            string[] lyricTextLines = lyricData.Split(newLinedelims, StringSplitOptions.RemoveEmptyEntries);

            if (!lyricTextLines.Any())
            {
                return;
            }

            foreach (string lyricLine in lyricTextLines)
            {
                lyricsList.Add(new Lyric { Text = lyricLine });
            }

            this.HasData = true;
            this.Data = new { lyrics = lyricsList };
        }
    }
}