using Microsoft.Extensions.Logging; using System.Net.Http.Json; namespace File_Folder_Helper.Day.Q32023; internal static class Helper20230906 { internal static void SaveJson(ILogger log, string argsZero) { string[] lines; int? jsonBodyLine; string? userAgent; string[] segments; HttpClient httpClient; HttpRequestMessage httpRequestMessage; string[] files = Directory.GetFiles(argsZero, "*.post", SearchOption.TopDirectoryOnly); foreach (string file in files) { jsonBodyLine = null; userAgent = null; lines = File.ReadAllLines(file); if (lines.Length < 2) continue; httpRequestMessage = new(HttpMethod.Post, lines[1]); log.LogInformation("reading {fileName}", Path.GetFileName(file)); for (int i = 2; i < lines.Length; i++) { if (lines.Length < 1) continue; if (lines[i][0] == '#') continue; else if (lines[i][0] == '{') jsonBodyLine = i; else { segments = lines[i].Split(": "); if (segments.Length < 2) continue; if (segments[0] == "User-Agent") userAgent = segments[1]; else httpRequestMessage.Headers.Add(segments[0], segments[1]); } } #pragma warning disable IL2026, IL3050 if (jsonBodyLine is not null) httpRequestMessage.Content = JsonContent.Create(lines[jsonBodyLine.Value]); #pragma warning restore IL2026, IL3050 httpClient = new(new HttpClientHandler { UseCookies = false }) { BaseAddress = new Uri(lines[0]) }; if (userAgent is not null) httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent); Task httpResponseMessageTask = httpClient.SendAsync(httpRequestMessage); httpResponseMessageTask.Wait(); if (!httpResponseMessageTask.Result.IsSuccessStatusCode) throw new Exception(httpResponseMessageTask.Result.StatusCode.ToString()); Task streamTask = httpResponseMessageTask.Result.Content.ReadAsStreamAsync(); streamTask.Wait(); if (!streamTask.Result.CanRead) throw new NullReferenceException(nameof(streamTask)); using FileStream fileStream = new($"{file}.json", FileMode.CreateNew); Task task = streamTask.Result.CopyToAsync(fileStream); task.Wait(); } } }