using System; using System.Buffers; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using TwitchDownloaderCore.Extensions; using TwitchDownloaderCore.Tools; using TwitchDownloaderCore.TwitchObjects; namespace TwitchDownloaderCore.Chat { public static class ChatJson { private static readonly JsonSerializerOptions _jsonSerializerOptions = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, NumberHandling = JsonNumberHandling.AllowReadingFromString, AllowTrailingCommas = true }; /// /// Asynchronously deserializes a chat json file. /// /// A representation the deserialized chat json file. /// The file does not exist. /// The file is not a valid chat format. public static async Task DeserializeAsync(string filePath, bool getComments = true, bool onlyFirstAndLastComments = false, bool getEmbeds = true, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(filePath, nameof(filePath)); if (!File.Exists(filePath)) throw new IOException("Json file does not exist"); ChatRoot returnChatRoot = new(); JsonDocument jsonDocument; JsonDocumentOptions deserializationOptions = new() { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }; await using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { jsonDocument = await GetJsonDocumentAsync(fs, filePath, deserializationOptions, cancellationToken); } if (jsonDocument.RootElement.TryGetProperty("FileInfo", out JsonElement fileInfoElement)) { returnChatRoot.FileInfo = fileInfoElement.Deserialize(options: _jsonSerializerOptions); } if (jsonDocument.RootElement.TryGetProperty("streamer", out JsonElement streamerElement)) { returnChatRoot.streamer = streamerElement.Deserialize(options: _jsonSerializerOptions); } if (jsonDocument.RootElement.TryGetProperty("video", out JsonElement videoElement)) { returnChatRoot.video = videoElement.Deserialize