Luski.Net/Luski.net/Server.old.cs

281 lines
15 KiB
C#
Raw Normal View History

/*using Luski.net.Enums;
using Luski.net.Interfaces;
using Luski.net.JsonTypes;
using Luski.net.JsonTypes.BaseTypes;
using Luski.net.JsonTypes.HTTP;
using Luski.net.Sockets;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
namespace Luski.net;
public sealed partial class Serverold
{
#pragma warning disable CA1822 // Mark members as static
public async Task<MainSocketRemoteUser> SendFriendResult(long user, bool answer, CancellationToken CancellationToken)
{
FriendRequestResult json = await SendServer(_user!.Servers.First(),"FriendRequestResult",
new FriendRequestResultOut()
{
Id = user,
Result = answer
},
FriendRequestResultOutContext.Default.FriendRequestResultOut,
FriendRequestResultContext.Default.FriendRequestResult,
CancellationToken);
if (json is not null && json.Error is null && json.ErrorMessage is null && answer && json.Channel is not null)
{
SocketDMChannel chan = await SocketChannel.GetChannel((long)json.Channel, SocketDMChannelContext.Default.SocketDMChannel, CancellationToken, _user!.Servers.First());
_ = chan.StartKeyProcessAsync(CancellationToken);
chans.Add(chan);
}
else
{
throw new Exception(json?.Error.ToString());
}
return SocketUserBase.GetUser(user, SocketRemoteUserContext.Default.SocketRemoteUser, CancellationToken, _user!.Servers.First()).Result;
}
public async Task<MainSocketRemoteUser> SendFriendRequest(long code, CancellationToken CancellationToken)
{
string ccode = Convert.ToBase64String(Encryption.Hash(Encryption.Encoder.GetBytes(code.ToString())));
FriendRequestResult? json = await SendServer(_user!.Servers.First(),"FriendRequest", new FriendRequest() { code = ccode}, FriendRequestContext.Default.FriendRequest, FriendRequestResultContext.Default.FriendRequestResult, CancellationToken);
if (json.StatusCode != HttpStatusCode.Accepted)
{
if (json is not null && json.Error is not null)
{
switch ((ErrorCode)(int)json.Error)
{
case ErrorCode.InvalidToken:
throw new Exception("Your current token is no longer valid");
case ErrorCode.ServerError:
throw new Exception($"Error from server: {json.ErrorMessage}");
case ErrorCode.InvalidPostData:
throw new Exception("The post data dent to the server is not the correct format. This may be because you app is couropt or you are using the wron API version");
case ErrorCode.Forbidden:
throw new Exception("You already have an outgoing request or the persone is not real");
}
}
if (json is not null && json.Channel is not null)
{
SocketDMChannel chan = await SocketChannel.GetChannel((long)json.Channel, (JsonTypeInfo<SocketDMChannel>)SocketDMChannelContext.Default.SocketDMChannel, CancellationToken, _user!.Servers.First());
_ = chan.StartKeyProcessAsync(CancellationToken);
chans.Add(chan);
}
}
MainSocketRemoteUser b = await SocketUserBase.GetUser(code, SocketRemoteUserContext.Default.SocketRemoteUser, CancellationToken, _user!.Servers.First());
if (json.Channel is not null)
b.FriendStatus = FriendStatus.Friends;
else
b.FriendStatus = FriendStatus.PendingOut;
return b;
}
/// <summary>
/// Sends the server a request to update the <paramref name="Status"/> of you account
/// </summary>
/// <param name="Status">The <see cref="UserStatus"/> you want to set your status to</param>
/// <exception cref="Exception"></exception>
public async Task<Task> UpdateStatus(UserStatus Status, CancellationToken CancellationToken)
{
if (_user is null) throw new Exception("You must login to make a request");
IncomingHTTP? data = await SendServer(_user!.Servers.First(),"SocketUserProfile/Status", new Status() { UserStatus = Status }, StatusContext.Default.Status, IncomingHTTPContext.Default.IncomingHTTP, CancellationToken);
if (data.Error is not null && ((int)data.StatusCode < 200 || (int)data.StatusCode > 299))
{
if (data?.ErrorMessage is not null) throw new Exception(data.ErrorMessage);
if (data?.Error is not null) throw new Exception(((int)data.Error).ToString());
else throw new Exception("Something went worng");
}
_user.Status = Status;
return Task.CompletedTask;
}
public async Task ChangeChannel(long Channel, CancellationToken CancellationToken, SocketServer Server)
{
if (_user is null) throw new Exception("You must login to make a request");
IncomingHTTP? data = await SendServer(Server, "ChangeChannel", new Channel() { Id = Channel }, ChannelContext.Default.Channel, IncomingHTTPContext.Default.IncomingHTTP, CancellationToken);
if (data.StatusCode != HttpStatusCode.Accepted)
{
if (data?.Error is not null)
{
switch (data.Error)
{
case ErrorCode.InvalidToken:
throw new Exception("Your current token is no longer valid");
case ErrorCode.ServerError:
throw new Exception("Error from server: " + data.ErrorMessage);
}
}
else throw new Exception("Something went worng");
}
_user.SelectedChannel = Channel;
}
public Task SendMessage(string Message, long Channel, SocketServer Server, CancellationToken CancellationToken, params JsonTypes.File[] Files)
{
try
{
_ = GetChannel<SocketTextChannel>(Channel, CancellationToken, Server).Result.SendMessage(Message, CancellationToken, Files);
}
catch (Exception e)
{
if (OnError is not null) _ = OnError.Invoke(e);
else throw e;
}
return Task.CompletedTask;
}
public void SetMultiThreadPercent(double num)
{
if (num < 1 || num > 100) throw new Exception("Number must be from 1 - 100");
Percent = num / 100;
}
public async Task<SocketMessage> GetMessage(long MessageId, CancellationToken CancellationToken, SocketServer Server) => await SocketMessage.GetMessage(MessageId, CancellationToken, Server);
public async Task<MainSocketRemoteUser> GetUser(long UserID, CancellationToken CancellationToken, SocketServer Server) => await SocketUserBase.GetUser(UserID, SocketRemoteUserContext.Default.SocketRemoteUser, CancellationToken, Server);
public async Task<TChannel> GetChannel<TChannel>(long Channel, CancellationToken CancellationToken, SocketServer Server) where TChannel : SocketChannel, new()
{
TChannel Return = new();
switch (Return)
{
case SocketDMChannel:
Return = (await SocketChannel.GetChannel(Channel, SocketDMChannelContext.Default.SocketDMChannel, CancellationToken, Server) as TChannel)!;
break;
case SocketGroupChannel:
Return = (await SocketChannel.GetChannel(Channel, SocketGroupChannelContext.Default.SocketGroupChannel, CancellationToken, Server) as TChannel)!;
break;
case SocketTextChannel:
Return = (await SocketChannel.GetChannel(Channel, SocketTextChannelContext.Default.SocketTextChannel, CancellationToken, Server) as TChannel)!;
break;
case SocketChannel:
Return = (await SocketChannel.GetChannel(Channel, SocketChannelContext.Default.SocketChannel, CancellationToken, Server) as TChannel)!;
break;
case null:
throw new NullReferenceException(nameof(TChannel));
default:
throw new Exception("Unknown channel type");
}
return Return;
}
public SocketAppUser CurrentUser
{
get
{
if (_user is null) throw new Exception("You must Login first");
return _user;
}
}
#pragma warning restore CA1822 // Mark members as static
private void ServerOut_OnError(object? sender, WebSocketSharp.ErrorEventArgs e)
{
if (OnError is not null) OnError.Invoke(new Exception(e.Message));
}
[Obsolete("Move to new Data layout")]
internal static void SendServer(string data)
{
ServerOut?.Send(data);
}
internal static void SendServer<Tvalue>(Tvalue Payload, JsonTypeInfo<Tvalue> jsonTypeInfo) where Tvalue : IncomingWSS
{
ServerOut?.Send(JsonSerializer.Serialize(Payload, jsonTypeInfo));
}
internal static HttpResponseMessage GetFromServer(SocketServer Server, string Path, CancellationToken CancellationToken, params KeyValuePair<string, string?>[] Headers)
{
using HttpClient web = new();
web.Timeout = TimeSpan.FromSeconds(10);
if (!login) web.DefaultRequestHeaders.Add("token", Token);
if (Headers is not null && Headers.Length > 0) foreach (KeyValuePair<string, string?> header in Headers) web.DefaultRequestHeaders.Add(header.Key, header.Value);
return web.GetAsync($"https://{Server.Domain}/{Server.ApiVersion}/{Path}", cancellationToken: CancellationToken).Result;
}
internal static Task GetFromServer(SocketServer Server, string Path, string File, CancellationToken CancellationToken, params KeyValuePair<string, string?>[] Headers)
{
using HttpClient web = new();
web.Timeout = TimeSpan.FromMinutes(10);
if (!login) web.DefaultRequestHeaders.Add("token", Token);
if (Headers is not null && Headers.Length > 0) foreach (KeyValuePair<string, string?> header in Headers) web.DefaultRequestHeaders.Add(header.Key, header.Value);
HttpResponseMessage Response = web.GetAsync($"https://{Server.Domain}/{Server.ApiVersion}/{Path}", CancellationToken).Result;
Stream stream = Response.Content.ReadAsStreamAsync(CancellationToken).Result;
using FileStream fs = System.IO.File.Create(File);
stream.CopyTo(fs);
return Task.CompletedTask;
}
internal static async Task<Tresult> GetFromServer<Tresult>(SocketServer Server, string Path, JsonTypeInfo<Tresult> Type, CancellationToken CancellationToken, params KeyValuePair<string, string?>[] Headers) where Tresult : IncomingHTTP, new()
{
HttpResponseMessage ServerResponce = GetFromServer(Server, Path, CancellationToken, Headers);
if (!ServerResponce.IsSuccessStatusCode) return new Tresult() { StatusCode = ServerResponce.StatusCode, Error = ErrorCode.ServerError, ErrorMessage = $"Server responded with status code {(int)ServerResponce.StatusCode}:{ServerResponce.StatusCode}" };
Tresult? temp = JsonSerializer.Deserialize(ServerResponce.Content.ReadAsStreamAsync(CancellationToken).Result, Type);
if (temp is null) return new Tresult() { StatusCode = ServerResponce.StatusCode, Error = ErrorCode.ServerError, ErrorMessage = $"Server responded with empty data" };
return temp;
}
internal static async Task<Tresult> SendServer<Tvalue, Tresult>(SocketServer Server, string Path, Tvalue Payload, JsonTypeInfo<Tvalue> jsonTypeInfo, JsonTypeInfo<Tresult> ReturnjsonTypeInfo, CancellationToken CancellationToken, params KeyValuePair<string, string?>[] Headers) where Tvalue : IWebRequest where Tresult : IncomingHTTP, new()
{
using HttpClient web = new();
if (!login) web.DefaultRequestHeaders.Add("token", Token);
if (Headers is not null && Headers.Length > 0) foreach (KeyValuePair<string, string?> header in Headers) web.DefaultRequestHeaders.Add(header.Key, header.Value);
HttpResponseMessage ServerResponce = web.PostAsJsonAsync($"https://{Server.Domain}/{Server.ApiVersion}/{Path}", Payload, jsonTypeInfo, CancellationToken).Result;
if (!ServerResponce.IsSuccessStatusCode) return new Tresult() { StatusCode = ServerResponce.StatusCode, Error = ErrorCode.ServerError, ErrorMessage = $"Server responded with status code {(int)ServerResponce.StatusCode}:{ServerResponce.StatusCode}" };
Tresult error = new() { StatusCode = ServerResponce.StatusCode, Error = ErrorCode.ServerError, ErrorMessage = $"Server responded with empty data" };
if (string.IsNullOrWhiteSpace(ServerResponce.Content.ReadAsStringAsync(CancellationToken).Result)) return error;
try
{
Tresult? temp = JsonSerializer.Deserialize(ServerResponce.Content.ReadAsStreamAsync(CancellationToken).Result, ReturnjsonTypeInfo);
if (temp is null) return error;
return temp;
}
catch { return error; }
}
internal static async Task<Tresult> SendServer<Tresult>(SocketServer Server, string Path, string File, JsonTypeInfo<Tresult> ReturnjsonTypeInfo, CancellationToken CancellationToken, params KeyValuePair<string, string?>[] Headers) where Tresult : IncomingHTTP, new()
{
var fs = System.IO.File.OpenRead(File);
try
{
using HttpClient web = new();
if (!login) web.DefaultRequestHeaders.Add("token", Token);
web.Timeout = new TimeSpan(0, 10, 0);
if (Headers is not null && Headers.Length > 0) foreach (KeyValuePair<string, string?> header in Headers) web.DefaultRequestHeaders.Add(header.Key, header.Value);
HttpResponseMessage ServerResponce = web.PostAsync($"https://{Server.Domain}/{Server.ApiVersion}/{Path}", new StreamContent(fs), CancellationToken).Result;
if (!ServerResponce.IsSuccessStatusCode) return new Tresult() { StatusCode = ServerResponce.StatusCode, Error = ErrorCode.ServerError, ErrorMessage = $"Server responded with status code {(int)ServerResponce.StatusCode}:{ServerResponce.StatusCode}" };
try
{
Tresult? temp = JsonSerializer.Deserialize(ServerResponce.Content.ReadAsStreamAsync(CancellationToken).Result, ReturnjsonTypeInfo);
if (temp is null) return new Tresult() { StatusCode = ServerResponce.StatusCode, Error = ErrorCode.ServerError, ErrorMessage = $"Server responded with empty data" };
return temp;
}
catch { return new Tresult() { StatusCode = ServerResponce.StatusCode, Error = ErrorCode.ServerError, ErrorMessage = $"Server responded with empty data" }; }
}
finally
{
fs.Close();
}
}
}
*/