file-folder-helper/Helpers/HelperDownload.cs

65 lines
2.6 KiB
C#

using Microsoft.Extensions.Logging;
using System.Net.Http.Json;
namespace File_Folder_Helper.Helpers;
internal static class HelperDownload
{
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]);
}
}
if (jsonBodyLine is not null)
httpRequestMessage.Content = JsonContent.Create(lines[jsonBodyLine.Value]);
httpClient = new(new HttpClientHandler { UseCookies = false }) { BaseAddress = new Uri(lines[0]) };
if (userAgent is not null)
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);
Task<HttpResponseMessage> httpResponseMessageTask = httpClient.SendAsync(httpRequestMessage);
httpResponseMessageTask.Wait();
if (!httpResponseMessageTask.Result.IsSuccessStatusCode)
throw new Exception(httpResponseMessageTask.Result.StatusCode.ToString());
Task<Stream> 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();
}
}
}