using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; namespace axXez.TS3.Protocol { /// Parsed result of a ServerQuery command — includes the error code, error message, raw response text, and all key-value entries. public class QueryResponse : TsMessage { private static readonly Regex _parseRegex = new(@"error id=(?[0-9]+) msg=(?.*)", RegexOptions.Compiled); /// ServerQuery error code string; "0" means success. public string ErrorCode { get; private set; } /// Human-readable error message; "ok" on success. public string ErrorMsg { get; private set; } /// Stack trace captured at the call site when the response has an error. null on success. public StackTrace StackTrace { get; private set; } /// Whether the response contains an error (i.e. is not "0"). public bool HasError { get; private set; } internal QueryResponse(string commandName, string data, string errorCode, string errorMsg) : base(commandName, data) { ErrorCode = errorCode; ErrorMsg = errorMsg; if (!ErrorCode.Equals("0")) { StackTrace = new StackTrace(); HasError = true; } } internal static QueryResponse Parse(string commandName, params IEnumerable lines) { var groups = _parseRegex.Match(lines.Last()).Groups; var errorCode = groups["id"].Value; var errorMsg = groups["msg"].Value.FromTsFormat(); var data = string.Join("\n", lines.SkipLast(1)); return new(commandName, data, errorCode, errorMsg); } internal void SetStackTrace(StackTrace stackTrace) { StackTrace = stackTrace; } //internal Dictionary ToDictionary() //{ // var dict = new Dictionary // { // ["errorCode"] = ErrorCode, // ["errorMessage"] = ErrorMsg // }; // if (HasData) // foreach (var kvp in Entries[0].ToDictionary()) // dict.TryAdd(kvp.Key, kvp.Value); // return dict; //} } }