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
{
///
/// LRC File Lyric Provider.
///
public class LrcLyricsProvider : ILyricsProvider
{
///
/// Initializes a new instance of the class.
///
public LrcLyricsProvider()
{
FileExtensions = new Collection
{
"lrc"
};
}
///
/// Gets a value indicating the File Extenstions this provider works with.
///
public Collection? FileExtensions { get; }
///
/// Gets or Sets a value indicating whether Process() generated data.
///
/// true if data generated; otherwise, false.
public bool HasData { get; set; }
///
/// Gets or Sets Data object generated by Process() method.
///
/// Object with data if no error occured; otherwise, null.
public object? Data { get; set; }
///
/// Opens lyric file for [the specified item], and processes it for API return.
///
/// The item to to process.
public void Process(BaseItem item)
{
string? lyricFilePath = Helpers.ItemHelper.GetLyricFilePath(item.Path);
if (string.IsNullOrEmpty(lyricFilePath))
{
return;
}
List lyricsList = new List();
List sortedLyricData = new List();
var metaData = new ExpandoObject() as IDictionary;
string lrcFileContent = System.IO.File.ReadAllText(lyricFilePath);
try
{
// Parse and sort lyric rows
LyricParser lrcLyricParser = new LrcParser.Parser.Lrc.LrcParser();
Song lyricData = lrcLyricParser.Decode(lrcFileContent);
sortedLyricData = lyricData.Lyrics.Where(x => x.TimeTags.Count > 0).OrderBy(x => x.TimeTags.ToArray()[0].Value).ToList();
// Parse metadata rows
var metaDataRows = lyricData.Lyrics
.Where(x => x.TimeTags.Count == 0)
.Where(x => x.Text.StartsWith("[", StringComparison.Ordinal) && x.Text.EndsWith("]", StringComparison.Ordinal))
.Select(x => x.Text)
.ToList();
foreach (string metaDataRow in metaDataRows)
{
var metaDataField = metaDataRow.Split(":");
string metaDataFieldName = metaDataField[0].Replace("[", string.Empty, StringComparison.Ordinal);
string metaDataFieldValue = metaDataField[1].Replace("]", string.Empty, StringComparison.Ordinal);
metaData.Add(metaDataFieldName, metaDataFieldValue);
}
}
catch
{
return;
}
if (!sortedLyricData.Any())
{
return;
}
for (int i = 0; i < sortedLyricData.Count; i++)
{
var timeData = sortedLyricData[i].TimeTags.ToArray()[0].Value;
double ticks = Convert.ToDouble(timeData, new NumberFormatInfo()) * 10000;
lyricsList.Add(new Lyric { Start = Math.Ceiling(ticks), Text = sortedLyricData[i].Text });
}
this.HasData = true;
if (metaData.Any())
{
this.Data = new { MetaData = metaData, lyrics = lyricsList };
}
else
{
this.Data = new { lyrics = lyricsList };
}
}
}
}