aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Providers/Lyric/DefaultLyricProvider.cs
blob: ae6350dd7df764c1fbed242b39b12fe06f5b993b (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
using System;
using System.IO;
using System.Threading.Tasks;
using Jellyfin.Extensions;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Resolvers;

namespace MediaBrowser.Providers.Lyric;

/// <inheritdoc />
public class DefaultLyricProvider : ILyricProvider
{
    private static readonly string[] _lyricExtensions = { ".lrc", ".elrc", ".txt" };

    /// <inheritdoc />
    public string Name => "DefaultLyricProvider";

    /// <inheritdoc />
    public ResolverPriority Priority => ResolverPriority.First;

    /// <inheritdoc />
    public bool HasLyrics(BaseItem item)
    {
        var path = GetLyricsPath(item);
        return path is not null;
    }

    /// <inheritdoc />
    public async Task<LyricFile?> GetLyrics(BaseItem item)
    {
        var path = GetLyricsPath(item);
        if (path is not null)
        {
            var content = await File.ReadAllTextAsync(path).ConfigureAwait(false);
            return new LyricFile(path, content);
        }

        return null;
    }

    private string? GetLyricsPath(BaseItem item)
    {
        // Ensure the path to the item is not null
        string? itemDirectoryPath = Path.GetDirectoryName(item.Path);
        if (itemDirectoryPath is null)
        {
            return null;
        }

        // Ensure the directory path exists
        if (!Directory.Exists(itemDirectoryPath))
        {
            return null;
        }

        foreach (var lyricFilePath in Directory.GetFiles(itemDirectoryPath, $"{Path.GetFileNameWithoutExtension(item.Path)}.*"))
        {
            if (_lyricExtensions.Contains(Path.GetExtension(lyricFilePath.AsSpan()), StringComparison.OrdinalIgnoreCase))
            {
                return lyricFilePath;
            }
        }

        return null;
    }
}