Luski.Net/Luski.net/JsonTypes/SocketMessage.cs

88 lines
2.8 KiB
C#
Executable File

using Luski.net.Interfaces;
using Luski.net.JsonTypes.BaseTypes;
using System;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace Luski.net.JsonTypes;
public class SocketMessage : IncomingHTTP
{
[JsonPropertyName("id")]
[JsonInclude]
public long Id { get; internal set; } = default!;
[JsonPropertyName("user_id")]
[JsonInclude]
public long AuthorID { get; internal set; } = default!;
[JsonPropertyName("content")]
[JsonInclude]
public string Context { get; internal set; } = default!;
[JsonPropertyName("channel_id")]
[JsonInclude]
public long ChannelID { get; internal set; } = default!;
[JsonPropertyName("files")]
[JsonInclude]
public File[]? Files { get; internal set; } = default!;
public async Task<SocketTextChannel> GetChannel()
{
if (Server.chans.Any(s => s.Id == ChannelID))
{
return (SocketTextChannel)Server.chans.Where(s => s.Id == ChannelID).First();
}
else
{
SocketTextChannel ch = await SocketChannel.GetChannel(ChannelID, SocketTextChannelContext.Default.SocketTextChannel);
Server.chans.Add(ch);
return ch;
}
}
public async Task<IUser> GetAuthor()
{
if (Server._user!.Id != AuthorID) return await SocketUserBase.GetUser(AuthorID, SocketRemoteUserContext.Default.SocketRemoteUser);
else return Server._user;
}
internal void decrypt(string? key)
{
if (string.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key));
Context = Encryption.Encoder.GetString(Encryption.Decrypt(Convert.FromBase64String(Context), key));
if (Files is not null && Files.Length > 0)
{
for (int i = 0; i < Files.Length; i++)
{
Files[i].key = key;
Files[i].decrypt();
}
}
}
internal static async Task<SocketMessage> GetMessage(long id)
{
SocketMessage message;
while (true)
{
if (Server.CanRequest)
{
message = await Server.GetFromServer("socketmessage",
SocketMessageContext.Default.SocketMessage,
new System.Collections.Generic.KeyValuePair<string, string?>("msg_id", id.ToString()));
break;
}
}
if (message is not null) return message;
throw new Exception("Server did not return a message");
}
}
[JsonSerializable(typeof(SocketMessage))]
[JsonSourceGenerationOptions(
GenerationMode = JsonSourceGenerationMode.Default,
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
WriteIndented = false)]
public partial class SocketMessageContext : JsonSerializerContext
{
}