|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Net.Http; |
| 4 | +using System.Net.Http.Headers; |
| 5 | +using System.Text; |
| 6 | +using Serilog; |
| 7 | + |
| 8 | +namespace OpenUtau.Core.Voicevox { |
| 9 | + class VoicevoxClient : Util.SingletonBase<VoicevoxClient> { |
| 10 | + internal Tuple<string, byte[]> SendRequest(VoicevoxURL voicevoxURL) { |
| 11 | + try { |
| 12 | + using (var client = new HttpClient()) { |
| 13 | + using (var request = new HttpRequestMessage(new HttpMethod(voicevoxURL.method.ToUpper()), this.RequestURL(voicevoxURL))) { |
| 14 | + request.Headers.TryAddWithoutValidation("accept", voicevoxURL.accept); |
| 15 | + |
| 16 | + request.Content = new StringContent(voicevoxURL.body); |
| 17 | + request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); |
| 18 | + |
| 19 | + Log.Information($"VoicevoxProcess sending {request}"); |
| 20 | + var response = client.SendAsync(request); |
| 21 | + Log.Information($"VoicevoxProcess received"); |
| 22 | + string str = response.Result.Content.ReadAsStringAsync().Result; |
| 23 | + //May not fit json format |
| 24 | + if (!str.StartsWith("{") || !str.EndsWith("}")) { |
| 25 | + str = "{ \"json\":" + str + "}"; |
| 26 | + } |
| 27 | + return new Tuple<string, byte[]>(str, response.Result.Content.ReadAsByteArrayAsync().Result); |
| 28 | + } |
| 29 | + } |
| 30 | + } catch (Exception ex) { |
| 31 | + Log.Error(@"{ex}"); |
| 32 | + } |
| 33 | + return new Tuple<string, byte[]>("", new byte[0]); |
| 34 | + } |
| 35 | + |
| 36 | + public string RequestURL(VoicevoxURL voicevoxURL) { |
| 37 | + StringBuilder queryStringBuilder = new StringBuilder(); |
| 38 | + foreach (var parameter in voicevoxURL.query) { |
| 39 | + queryStringBuilder.Append($"{parameter.Key}={parameter.Value}&"); |
| 40 | + } |
| 41 | + |
| 42 | + // Remove extra "&" at the end |
| 43 | + string queryString = "?" + queryStringBuilder.ToString().TrimEnd('&'); |
| 44 | + |
| 45 | + string str = $"{voicevoxURL.protocol}{voicevoxURL.host}{voicevoxURL.path}{queryString}"; |
| 46 | + return str; |
| 47 | + } |
| 48 | + } |
| 49 | + public class VoicevoxURL { |
| 50 | + public string method = string.Empty; |
| 51 | + public string protocol = "http://"; |
| 52 | + //Currently fixed port 50021 to connect to |
| 53 | + public string host = "127.0.0.1:50021"; |
| 54 | + public string path = string.Empty; |
| 55 | + public Dictionary<string, string> query = new Dictionary<string, string>(); |
| 56 | + public string body = string.Empty; |
| 57 | + public string accept = "application/json"; |
| 58 | + } |
| 59 | +} |
0 commit comments