1
0
mirror of https://github.com/ZetaKebab/MpcNET.git synced 2024-09-16 05:30:09 +00:00
MpcNET/LibMpc/Message/MpdMessage.cs

69 lines
2.3 KiB
C#
Raw Normal View History

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
2016-12-06 11:53:49 +00:00
namespace LibMpc
{
public interface IMpdMessage<T>
2016-12-06 11:53:49 +00:00
{
IMpdRequest<T> Request { get; }
IMpdResponse<T> Response { get; }
2016-12-06 11:53:49 +00:00
}
public class MpdMessage<T> : IMpdMessage<T>
2016-12-06 11:53:49 +00:00
{
private readonly Regex _linePattern = new Regex("^(?<key>[A-Za-z_]*):[ ]{0,1}(?<value>.*)$");
private readonly IList<string> _rawResponse;
public MpdMessage(IMpcCommand<T> command, bool connected, IReadOnlyCollection<string> response)
2016-12-06 11:53:49 +00:00
{
Request = new MpdRequest<T>(command);
var endLine = response.Skip(response.Count - 1).Single();
_rawResponse = response.Take(response.Count - 1).ToList();
var values = Request.Command.FormatResponse(GetValuesFromResponse());
Response = new MpdResponse<T>(endLine, values, connected);
2016-12-06 11:53:49 +00:00
}
public IMpdRequest<T> Request { get; }
public IMpdResponse<T> Response { get; }
private IReadOnlyDictionary<string, IList<string>> GetValuesFromResponse()
{
var result = new Dictionary<string, IList<string>>();
foreach (var line in _rawResponse)
{
var match = _linePattern.Match(line);
if (match.Success)
{
var mpdKey = match.Result("${key}");
if (!string.IsNullOrEmpty(mpdKey))
{
var mpdValue = match.Result("${value}");
if (!string.IsNullOrEmpty(mpdValue))
{
if (!result.ContainsKey(mpdKey))
{
result.Add(mpdKey, new List<string>() { mpdValue });
}
else
{
result[mpdKey].Add(mpdValue);
}
}
}
}
}
return result;
2016-12-06 11:53:49 +00:00
}
public override string ToString()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
2016-12-06 11:53:49 +00:00
}
}