Migration starts

• A lot of work needs to be done to make sure this works.
• I already know this push won't work, but it will build.
• I need to come up with a new way of storing local info. This will also bee needed to fix the very broken key system in this rushed commit.
This commit is contained in:
JacobTech 2023-07-03 23:24:35 -04:00
parent 2eb1abe526
commit 106d0d6078
58 changed files with 1428 additions and 3458 deletions

View File

@ -5,8 +5,6 @@ VisualStudioVersion = 17.0.31717.71
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Luski.net", "Luski.net\Luski.net.csproj", "{3DF9B870-51B3-4338-84EC-75E4B8802F0C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Luski.net.tests", "Luski.net.tests\Luski.net.tests.csproj", "{FCA149C8-379B-454A-962A-856F30965C4E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -17,10 +15,6 @@ Global
{3DF9B870-51B3-4338-84EC-75E4B8802F0C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3DF9B870-51B3-4338-84EC-75E4B8802F0C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3DF9B870-51B3-4338-84EC-75E4B8802F0C}.Release|Any CPU.Build.0 = Release|Any CPU
{FCA149C8-379B-454A-962A-856F30965C4E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FCA149C8-379B-454A-962A-856F30965C4E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FCA149C8-379B-454A-962A-856F30965C4E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FCA149C8-379B-454A-962A-856F30965C4E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

36
Luski.net/API.cs Normal file
View File

@ -0,0 +1,36 @@
using System.Collections.Generic;
using System.Linq;
using Luski.net.Structures.Main;
using Luski.net.Structures.Public;
namespace Luski.net;
public class API
{
public Server<MainSocketAppUser> MainServer { get; internal set; }
internal List<Server<PublicSocketAppUser>> InternalServers { get; } = new();
public IReadOnlyList<Server<PublicSocketAppUser>> LoadedServers => InternalServers.AsReadOnly();
public Server<PublicSocketAppUser> GetPublicServer(string Domain, string Version = "v1")
{
IEnumerable<Server<PublicSocketAppUser>> isl = InternalServers.Where(a => (a.Domain == Domain && a.ApiVersion == Version));
if (isl.Any()) return isl.First();
Server<PublicSocketAppUser> s = new()
{
Domain = Domain,
ApiVersion = Version,
};
InternalServers.Add(s);
return s;
}
public Server<MainSocketAppUser> GetMainServer(string Domain, string Version = "v1")
{
MainServer = new()
{
Domain = Domain,
ApiVersion = Version,
};
return MainServer;
}
}

View File

@ -3,15 +3,16 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using JacobTechEncryption;
namespace Luski.net
{
public static class Encryption
public static class ClientEncryption
{
internal static string? MyPublicKey;
internal static readonly UnicodeEncoding Encoder = new();
@ -23,15 +24,7 @@ namespace Luski.net
internal static string? outofkey = null;
internal static string pw = "";
public static int NewKeySize = 4096;
internal static string ServerPublicKey
{
get
{
if (_serverpublickey is null) _serverpublickey = new HttpClient().GetAsync($"https://{Server.InternalDomain}/{Server.API_Ver}/Keys/PublicKey").Result.Content.ReadAsStringAsync().Result;
return _serverpublickey;
}
}
public static void GenerateKeys()
{
if (!Generating)
@ -43,7 +36,7 @@ namespace Luski.net
}
}
internal static void GenerateNewKeys(out string Public, out string Private)
public static void GenerateNewKeys(out string Public, out string Private)
{
using RSACryptoServiceProvider r = new(NewKeySize);
Private = r.ToXmlString(true);
@ -55,16 +48,22 @@ namespace Luski.net
{
internal static void SetOfflineKey(string key)
{
MakeFile(Server.GetKeyFilePath, pw);
LuskiDataFile? fileLayout = JsonSerializer.Deserialize<LuskiDataFile>(FileString(Server.GetKeyFilePath, pw));
MakeFile("Server.GetKeyFilePath", pw);
LuskiDataFile? fileLayout = JsonSerializer.Deserialize<LuskiDataFile>(FileString("Server.GetKeyFilePath", pw));
fileLayout.OfflineKey = key;
fileLayout.Save(Server.GetKeyFilePath, pw);
fileLayout.Save("Server.GetKeyFilePath", pw);
}
public static LuskiDataFile GetFile()
{
MakeFile("Server.GetKeyFilePath", pw);
return JsonSerializer.Deserialize<LuskiDataFile>(FileString("Server.GetKeyFilePath", pw))!;
}
internal static string? GetOfflineKey()
{
MakeFile(Server.GetKeyFilePath, pw);
LuskiDataFile? fileLayout = JsonSerializer.Deserialize<LuskiDataFile>(FileString(Server.GetKeyFilePath, pw));
MakeFile("Server.GetKeyFilePath", pw);
LuskiDataFile? fileLayout = JsonSerializer.Deserialize<LuskiDataFile>(FileString("Server.GetKeyFilePath", pw));
return fileLayout?.OfflineKey;
}
@ -122,32 +121,13 @@ namespace Luski.net
#pragma warning disable CS8603 // Possible null reference return.
if (channel == 0) return myPrivateKey;
#pragma warning restore CS8603 // Possible null reference return.
MakeFile(Server.GetKeyFilePath, pw);
fileLayout = JsonSerializer.Deserialize<LuskiDataFile>(FileString(Server.GetKeyFilePath, pw));
MakeFile("Server.GetKeyFilePath", pw);
fileLayout = JsonSerializer.Deserialize<LuskiDataFile>(FileString("Server.GetKeyFilePath", pw));
lis = fileLayout?.channels?.Where(s => s.id == channel);
if (lis?.Count() > 0)
{
return lis.First().key;
}
foreach (Branch b in (Branch[])Enum.GetValues(typeof(Branch)))
{
if (b != Server.Branch)
{
try
{
string temp = GetKeyBranch(channel, b);
if (temp is not null)
{
AddKey(channel, temp);
return temp;
}
}
catch
{
}
}
}
throw new Exception("You dont have a key for that channel");
}
finally
@ -157,7 +137,7 @@ namespace Luski.net
}
}
internal static string GetKeyBranch(long channel, Branch branch)
internal static string GetKeyBranch(long channel)
{
LuskiDataFile? fileLayout;
IEnumerable<ChannelLayout>? lis;
@ -166,8 +146,8 @@ namespace Luski.net
#pragma warning disable CS8603 // Possible null reference return.
if (channel == 0) return myPrivateKey;
#pragma warning restore CS8603 // Possible null reference return.
MakeFile(Server.GetKeyFilePathBr(branch.ToString()), pw);
fileLayout = JsonSerializer.Deserialize<LuskiDataFile>(FileString(Server.GetKeyFilePathBr(branch.ToString()), pw));
MakeFile("Server.GetKeyFilePathBr(branch.ToString())", pw);
fileLayout = JsonSerializer.Deserialize<LuskiDataFile>(FileString("", pw));
lis = fileLayout?.channels?.Where(s => s.id == channel);
if (lis?.Count() > 0)
{
@ -184,10 +164,10 @@ namespace Luski.net
public static void AddKey(long channel, string key)
{
MakeFile(Server.GetKeyFilePath, pw);
LuskiDataFile? fileLayout = JsonSerializer.Deserialize<LuskiDataFile>(FileString(Server.GetKeyFilePath, pw));
MakeFile("Server.GetKeyFilePath", pw);
LuskiDataFile? fileLayout = JsonSerializer.Deserialize<LuskiDataFile>(FileString("Server.GetKeyFilePath", pw));
fileLayout?.Addchannelkey(channel, key);
fileLayout?.Save(Server.GetKeyFilePath, pw);
fileLayout?.Save("Server.GetKeyFilePath", pw);
}
}
@ -210,9 +190,9 @@ namespace Luski.net
internal static LuskiDataFile GetDefualtDataFile()
{
return GetDataFile(Server.GetKeyFilePath, pw);
return GetDataFile("Server.GetKeyFilePath", pw);
}
public ChannelLayout[]? channels { get; set; } = default!;
public string? OfflineKey { get; set; } = default!;
@ -273,6 +253,17 @@ namespace Luski.net
chans?.Add(l);
channels = chans?.ToArray();
}
else
{
chans.Remove(chans.Where(s => s.id == chan).First());
ChannelLayout l = new()
{
id = chan,
key = Key
};
chans?.Add(l);
channels = chans?.ToArray();
}
}
}
@ -282,7 +273,7 @@ namespace Luski.net
public string key { get; set; } = default!;
}
}
/*
public class AES
{
public static string Encrypt(string path, string Password)
@ -353,7 +344,7 @@ namespace Luski.net
cs.Dispose();
fsCrypt.Close();
fsCrypt.Dispose();
NewPath = p;*/
NewPath = p;
}
public static void Decrypt(byte[] data, string Password, string File)
@ -387,7 +378,7 @@ namespace Luski.net
fsOut.Dispose();
}
}
*/
internal const int PasswordVersion = 0;
internal static byte[] LocalPasswordEncrypt(byte[] Password, int PasswordVersion = PasswordVersion)
@ -403,10 +394,15 @@ namespace Luski.net
{
return PasswordVersion switch
{
0 => Convert.ToBase64String(Encrypt(LocalPasswordEncrypt(Password, PasswordVersion))),
0 => Convert.ToBase64String(Encryption.RSA.Encrypt(LocalPasswordEncrypt(Password, PasswordVersion), MyPublicKey)),
_ => throw new ArgumentException("The value provided was not accepted", nameof(PasswordVersion)),
};
}
/*
public static byte[] Hash(byte[] data)
{
return SHA256.Create().ComputeHash(data);
}
internal static byte[] Encrypt(string data)
{
@ -427,7 +423,7 @@ namespace Luski.net
{
using RSACryptoServiceProvider rsa = new();
rsa.FromXmlString(key);
int size = rsa.KeySize / 8;
int size = ((rsa.KeySize - 384) / 8) + 7;
double x = data.Length / (double)size;
int bbb = int.Parse(x.ToString().Split('.')[0]);
if (x.ToString().Contains('.')) bbb++;
@ -443,7 +439,7 @@ namespace Luski.net
MaxDegreeOfParallelism = num
}, i =>
{
decccc[i] = rsa.Encrypt(data.Skip(i * size).Take(size).ToArray(), false);
decccc[i] = rsa.Encrypt(data.Skip(i * size).Take(size).ToArray(), true);
});
foreach (byte[] dataa in decccc)
{
@ -495,7 +491,7 @@ namespace Luski.net
MaxDegreeOfParallelism = num
}, i =>
{
decccc[i] = rsa.Decrypt(EncryptedText.Skip(i * size).Take(size).ToArray(), false);
decccc[i] = rsa.Decrypt(EncryptedText.Skip(i * size).Take(size).ToArray(), true);
});
foreach (byte[] data in decccc)
{
@ -510,6 +506,6 @@ namespace Luski.net
}
}
return datasplitout;
}
}*/
}
}

View File

@ -1,8 +0,0 @@
namespace Luski.net.Enums;
public enum Branch : short
{
Dev,
Beta,
Master,
}

View File

@ -1,6 +1,6 @@
namespace Luski.net.Enums;
internal enum DataType
public enum DataType
{
Message_Create,
Status_Update,

View File

@ -1,4 +1,4 @@
namespace Luski.net.Enums;
namespace Luski.net.Enums.Main;
public enum ChannelType : short
{

View File

@ -1,4 +1,4 @@
namespace Luski.net.Enums;
namespace Luski.net.Enums.Main;
public enum FriendStatus
{

View File

@ -1,6 +1,6 @@
using System;
namespace Luski.net.Enums;
namespace Luski.net.Enums.Main;
[Flags]
public enum UserFlag : short

View File

@ -0,0 +1,6 @@
namespace Luski.net.Enums.Public;
public enum ChannelType : short
{
TextAndVoice = 0
}

View File

@ -0,0 +1,9 @@
namespace Luski.net.Enums;
public enum ServerType : byte
{
Public = 0,
Main = 1,
PublicSub = 2,
MainSub = 3
}

View File

@ -0,0 +1,11 @@
using Luski.net.Enums;
using Luski.net.Structures.Public;
namespace Luski.net.Interfaces;
public interface IAppUser : IUser
{
public ErrorCode? Error { get; }
public string? ErrorMessage { get; }
public string Username { get; }
}

View File

@ -1,48 +0,0 @@
using Luski.net.Sound;
using System;
using System.Threading.Tasks;
using static Luski.net.Exceptions;
namespace Luski.net.Interfaces;
public interface IAudioClient
{
/// <summary>
/// the event is fired when your <see cref="IAudioClient"/> has joined the call
/// </summary>
event Func<Task> Connected;
/// <summary>
/// Tells you if you are muted
/// </summary>
bool Muted { get; }
/// <summary>
/// Tells you if you are deafned
/// </summary>
bool Deafened { get; }
/// <summary>
/// Toggles if you are speaking to your friends
/// </summary>
void ToggleMic();
/// <summary>
/// Toggles if you can hear audio
/// </summary>
void ToggleAudio();
/// <summary>
/// Changes what <see cref="RecordingDevice"/> the call gets its data from
/// </summary>
/// <param name="Device">This is the <see cref="RecordingDevice"/> you want to recored from</param>
/// <exception cref="NotConnectedException"></exception>
void RecordSoundFrom(RecordingDevice Device);
/// <summary>
/// Changes what <see cref="PlaybackDevice"/> the call gets its data from
/// </summary>
/// <param name="Device">This is the <see cref="PlaybackDevice"/> you want to heare outhers</param>
/// <exception cref="NotConnectedException"></exception>
void PlaySoundTo(PlaybackDevice Device);
/// <summary>
/// Joins the Voice call
/// </summary>
/// <exception cref="MissingEventException"></exception>
void JoinCall();
void LeaveCall();
}

View File

@ -1,32 +0,0 @@
using Luski.net.Enums;
using Luski.net.JsonTypes;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Luski.net.Interfaces;
/// <summary>
/// <see cref="ITextChannel"/> contains a list of variables that all channels from luski have
/// </summary>
public interface ITextChannel
{
long Id { get; }
string Title { get; }
string Description { get; }
string Key { get; }
/// <summary>
/// <see cref="ITextChannel.Type"/> returns the current <see cref="ChannelType"/> of the <see cref="ITextChannel"/>
/// </summary>
ChannelType Type { get; }
/// <summary>
/// Sends a <paramref name="Message"/> to the server for the currently selected <see cref="ITextChannel"/>
/// </summary>
/// <param name="Message">The messate you want to send to the server</param>
Task<Task> SendMessage(string Message, params File[] Files);
Task<Task> SendKeysToUsers();
Task<SocketMessage> GetMessage(long ID);
Task<IReadOnlyList<SocketMessage>> GetMessages(long Message_Id, int count = 50);
Task<IReadOnlyList<SocketMessage>> GetMessages(int count = 50);
Task<byte[]> GetPicture();
IReadOnlyList<IUser> Members { get; }
}

View File

@ -0,0 +1,38 @@
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
using Luski.net.JsonTypes.BaseTypes;
using Luski.net.Structures;
using Luski.net.Structures.Public;
namespace Luski.net.Interfaces;
public interface IServer
{
public IAppUser IAppUser { get; }
public string Cache { get; }
public void SendServer<Tvalue>(Tvalue Payload, JsonTypeInfo<Tvalue> jsonTypeInfo) where Tvalue : IncomingWSS;
public HttpResponseMessage GetFromServer(string Path, CancellationToken CancellationToken,
params KeyValuePair<string, string?>[] Headers);
public Task GetFromServer(string Path, string File, CancellationToken CancellationToken,
params KeyValuePair<string, string?>[] Headers);
public Task<Tresult> GetFromServer<Tresult>(string Path, JsonTypeInfo<Tresult> Type,
CancellationToken CancellationToken, params KeyValuePair<string, string?>[] Headers)
where Tresult : IncomingHTTP, new();
public Task<Tresult> SendServer<Tvalue, Tresult>(string Path, Tvalue Payload,
JsonTypeInfo<Tvalue> jsonTypeInfo, JsonTypeInfo<Tresult> ReturnjsonTypeInfo,
CancellationToken CancellationToken, params KeyValuePair<string, string?>[] Headers)
where Tvalue : IWebRequest where Tresult : IncomingHTTP, new();
public Task<Tresult> SendServer<Tresult>(string Path, string File, JsonTypeInfo<Tresult> ReturnjsonTypeInfo,
CancellationToken CancellationToken, params KeyValuePair<string, string?>[] Headers)
where Tresult : IncomingHTTP, new();
public Task<Tuser> GetUser<Tuser>(long UserID, CancellationToken CancellationToken) where Tuser : SocketUserBase, new();
}

View File

@ -1,5 +1,7 @@
using Luski.net.Enums;
using System.Threading;
using Luski.net.Enums;
using System.Threading.Tasks;
using Luski.net.JsonTypes;
namespace Luski.net.Interfaces;
@ -15,12 +17,7 @@ public interface IUser
/// <summary>
/// The cerrent username of the user
/// </summary>
string Username { get; }
/// <summary>
/// The current tag for the user
/// <para>Ex: #1234</para>
/// </summary>
//short Tag { get; }
string DisplayName { get; }
/// <summary>
/// The current status of the user
/// </summary>
@ -30,16 +27,16 @@ public interface IUser
/// </summary>
PictureType PictureType { get; }
/// <summary>
/// the current flags of a user
/// </summary>
UserFlag Flags { get; }
/// <summary>
/// Gets the current avatar of the user
/// </summary>
Task<byte[]> GetAvatar();
Task<byte[]> GetAvatar(CancellationToken CancellationToken);
/// <summary>
/// Gets the current user key
/// </summary>
/// <returns></returns>
Task<string> GetUserKey();
Task<long> GetUserKey(CancellationToken CancellationToken);
/// <summary>
/// The server that the user comes from
/// </summary>
IServer Server { get; }
}

View File

@ -0,0 +1,6 @@
namespace Luski.net.Interfaces;
public interface IWebRequest
{
}

View File

@ -1,9 +1,10 @@
using System.Text.Json.Serialization;
using Luski.net.Enums;
using Luski.net.Interfaces;
namespace Luski.net.JsonTypes.BaseTypes;
internal class HTTPRequest
internal class HTTPRequest : IWebRequest
{
[JsonPropertyName("data_type")]
[JsonInclude]

View File

@ -3,7 +3,7 @@ using System.Text.Json.Serialization;
namespace Luski.net.JsonTypes.BaseTypes;
internal class IncomingWSS
public class IncomingWSS
{
[JsonPropertyName("type")]
[JsonInclude]
@ -18,7 +18,7 @@ internal class IncomingWSS
GenerationMode = JsonSourceGenerationMode.Default,
PropertyNamingPolicy = JsonKnownNamingPolicy.Unspecified,
WriteIndented = false)]
internal partial class IncomingWSSContext : JsonSerializerContext
public partial class IncomingWSSContext : JsonSerializerContext
{
}

View File

@ -1,118 +0,0 @@
using Luski.net.Enums;
using Luski.net.Interfaces;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading.Tasks;
namespace Luski.net.JsonTypes.BaseTypes;
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class SocketUserBase : IncomingHTTP, IUser
{
[JsonPropertyName("id")]
[JsonInclude]
public long Id { get; internal set; } = default!;
[JsonPropertyName("username")]
[JsonInclude]
public string Username { get; internal set; } = default!;
// [JsonPropertyName("tag")]
//[JsonInclude]
//public short Tag { get; internal set; } = default!;
[JsonPropertyName("status")]
[JsonInclude]
public UserStatus Status { get; internal set; } = default!;
[JsonPropertyName("picture_type")]
[JsonInclude]
public PictureType PictureType { get; internal set; } = default!;
[JsonPropertyName("flags")]
[JsonInclude]
public UserFlag Flags { get; internal set; } = default!;
public async Task<byte[]> GetAvatar()
{
if (Server.Cache != null)
{
bool isc = System.IO.File.Exists($"{Server.Cache}/avatars/{Id}");
if (!isc) await Server.GetFromServer($"socketuserprofile/Avatar/{Id}", $"{Server.Cache}/avatars/{Id}");
}
return System.IO.File.ReadAllBytes($"{Server.Cache}/avatars/{Id}");
}
public Task<string> GetUserKey()
{
if (Server._user is null) throw new Exception("you are not loged in");
if (Id == Server._user.Id && Encryption.MyPublicKey is not null) return Task.FromResult(Encryption.MyPublicKey);
string data = Server.GetFromServer($"Keys/GetUserKey/{Id}").Content.ReadAsStringAsync().Result;
return Task.FromResult(data);
}
internal static async Task<TUser> GetUser<TUser>(long UserId, JsonTypeInfo<TUser> Json) where TUser : SocketUserBase, new()
{
TUser user;
if (Server.poeople is null) Server.poeople = new();
if (Server.poeople.Count > 0 && Server.poeople.Any(s => s.Id == UserId))
{
TUser temp = Server.poeople.Where(s => s is TUser && s.Id == UserId).Cast<TUser>().FirstOrDefault()!;
if (temp is SocketRemoteUser && (temp as SocketRemoteUser)!.Channel == null)
{
foreach (SocketDMChannel chan in Server.chans.Where(s => s is SocketDMChannel).Cast<SocketDMChannel>())
{
if (chan.Type == ChannelType.DM && chan.Id != 0 && chan.MemberIdList is not null)
{
if (chan.MemberIdList.Any(s => s == UserId)) (temp as SocketRemoteUser)!.Channel = chan;
}
}
}
return temp!;
}
while (true)
{
if (Server.CanRequest)
{
user = await Server.GetFromServer("socketuser",
Json,
new System.Collections.Generic.KeyValuePair<string, string?>("id", UserId.ToString()));
break;
}
}
if (user is null) throw new Exception("Server did not return a user");
if (Server.poeople.Count > 0 && Server.poeople.Any(s => s.Id == UserId))
{
foreach (IUser? p in Server.poeople.Where(s => s.Id == UserId))
{
Server.poeople.Remove(p);
}
}
if (Server._user is not null && UserId != 0 && UserId != Server._user.Id)
{
foreach (SocketDMChannel chan in Server.chans.Where(s => s is SocketDMChannel).Cast<SocketDMChannel>())
{
if (chan.Id != 0 && chan.MemberIdList is not null)
{
if (chan.MemberIdList.Any(s => s == UserId)) (user as SocketRemoteUser)!.Channel = chan;
}
}
}
Server.poeople.Add(user);
return user;
}
}
[JsonSerializable(typeof(SocketUserBase))]
[JsonSourceGenerationOptions(
GenerationMode = JsonSourceGenerationMode.Default,
PropertyNamingPolicy = JsonKnownNamingPolicy.Unspecified,
WriteIndented = false,
DefaultIgnoreCondition = JsonIgnoreCondition.Never)]
internal partial class SocketUserBaseContext : JsonSerializerContext
{
}

View File

@ -5,18 +5,12 @@ namespace Luski.net.JsonTypes.HTTP;
internal class FriendRequest : HTTPRequest
{
[JsonPropertyName("code")]
[JsonInclude]
public string code { get; set; } = default!;
[JsonPropertyName("id")]
[JsonInclude]
public long Id { get; set; } = default!;
[JsonPropertyName("subtype")]
[JsonInclude]
public int SubType { get; set; } = default!;
[JsonPropertyName("username")]
[JsonInclude]
public string Username { get; set; } = default!;
[JsonPropertyName("tag")]
[JsonInclude]
public short Tag { get; set; } = default!;
}
[JsonSerializable(typeof(FriendRequest))]

View File

@ -0,0 +1,21 @@
using System.Text.Json.Serialization;
using Luski.net.JsonTypes.BaseTypes;
namespace Luski.net.JsonTypes;
public class OfflineData : IncomingHTTP
{
[JsonPropertyName("data")]
[JsonInclude]
public string[]? Data { get; internal set; } = default!;
}
[JsonSerializable(typeof(OfflineData))]
[JsonSourceGenerationOptions(
GenerationMode = JsonSourceGenerationMode.Default,
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
WriteIndented = false)]
internal partial class OfflineDataContext : JsonSerializerContext
{
}

View File

@ -1,178 +0,0 @@
using Luski.net.Interfaces;
using Luski.net.JsonTypes.BaseTypes;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
namespace Luski.net.JsonTypes;
public class SocketAppUser : SocketUserBase
{
[JsonPropertyName("email")]
[JsonInclude]
public string Email { get; internal set; } = default!;
[JsonIgnore]
public IReadOnlyList<SocketChannel> Channels
{
get
{
if (_Channels is null || ChannelIdList is not null)
{
if (ChannelIdList.Length != 0)
{
_Channels = new List<SocketChannel>();
foreach (long channel in ChannelIdList)
{
SocketChannel s = SocketChannel.GetChannel(channel, SocketChannelContext.Default.SocketChannel).Result;
Server.chans.Remove(s);
switch (s.Type)
{
case Enums.ChannelType.GROUP:
_Channels.Add(SocketChannel.GetChannel(channel, SocketGroupChannelContext.Default.SocketGroupChannel).Result);
break;
case Enums.ChannelType.DM:
_Channels.Add(SocketChannel.GetChannel(channel, SocketDMChannelContext.Default.SocketDMChannel).Result);
break;
}
}
}
else _Channels = new List<SocketChannel>();
}
return _Channels.AsReadOnly();
}
}
[JsonIgnore]
public IReadOnlyList<SocketRemoteUser> FriendRequests
{
get
{
if (_FriendRequests is null || FriendRequestsRaw is not null)
{
_FriendRequests = new();
if (ChannelIdList.Length != 0 && FriendRequestsRaw is not null)
{
foreach (FR person in FriendRequestsRaw)
{
//_Friends.Add(SocketRemoteUser.GetUser(person));
long id = person.user_id == Id ? person.from : person.user_id;
SocketRemoteUser frq = GetUser(id, SocketRemoteUserContext.Default.SocketRemoteUser).Result;
_FriendRequests.Add(frq);
}
}
else _FriendRequests = new();
}
return _FriendRequests.AsReadOnly();
}
}
[JsonIgnore]
public IReadOnlyList<SocketRemoteUser> Friends
{
get
{
if (_Friends is null || FriendIdList is not null)
{
if (ChannelIdList.Length != 0)
{
_Friends = new List<SocketRemoteUser>();
foreach (long person in FriendIdList)
{
_Friends.Add(GetUser(person, SocketRemoteUserContext.Default.SocketRemoteUser).Result);
}
}
else _Friends = new List<SocketRemoteUser>();
}
return _Friends.AsReadOnly();
}
}
[JsonPropertyName("selected_channel")]
[JsonInclude]
public long SelectedChannel { get; internal set; } = default!;
[JsonPropertyName("channels")]
[JsonInclude]
public long[] ChannelIdList { get; internal set; } = default!;
[JsonPropertyName("friends")]
[JsonInclude]
public long[] FriendIdList { get; internal set; } = default!;
[JsonPropertyName("friend_requests")]
[JsonInclude]
public FR[] FriendRequestsRaw { get; internal set; } = default!;
[JsonIgnore]
private List<SocketChannel> _Channels = default!;
[JsonIgnore]
private List<SocketRemoteUser> _Friends = default!;
[JsonIgnore]
private List<SocketRemoteUser> _FriendRequests = default!;
public class FR
{
public long from { get; set; } = default!;
public long user_id { get; set; } = default!;
}
internal void AddFriend(SocketRemoteUser User)
{
if (Server.poeople.Any(s => s.Id == User.Id))
{
IEnumerable<IUser> b = Server.poeople.Where(s => s.Id == User.Id);
foreach (IUser item in b)
{
Server.poeople.Remove(item);
}
Server.poeople.Add(User);
}
else
{
Server.poeople.Add(User);
}
_Friends.Add(User);
}
internal void RemoveFriendRequest(SocketRemoteUser User)
{
if (Server.poeople.Any(s => s.Id == User.Id))
{
IEnumerable<IUser> b = Server.poeople.Where(s => s.Id == User.Id);
foreach (IUser item in b)
{
Server.poeople.Remove(item);
}
}
Server.poeople.Add(User);
foreach (SocketRemoteUser user in _FriendRequests)
{
if (User.Id == user.Id)
{
_FriendRequests.Remove(User);
}
}
}
internal void AddFriendRequest(SocketRemoteUser User)
{
if (Server.poeople.Any(s => s.Id == User.Id))
{
IEnumerable<IUser> b = Server.poeople.Where(s => s.Id == User.Id);
foreach (IUser item in b)
{
Server.poeople.Remove(item);
}
Server.poeople.Add(User);
}
else
{
Server.poeople.Add(User);
}
_FriendRequests.Add(User);
}
}
[JsonSerializable(typeof(SocketAppUser))]
[JsonSourceGenerationOptions(
GenerationMode = JsonSourceGenerationMode.Default,
PropertyNamingPolicy = JsonKnownNamingPolicy.Unspecified,
WriteIndented = false,
DefaultIgnoreCondition = JsonIgnoreCondition.Never)]
internal partial class SocketAppUserContext : JsonSerializerContext
{
}

View File

@ -1,33 +0,0 @@
using Luski.net.JsonTypes.BaseTypes;
using System.Linq;
using System.Text.Json.Serialization;
namespace Luski.net.JsonTypes;
public class SocketDMChannel : SocketTextChannel
{
public SocketRemoteUser User
{
get
{
if (_user is null)
{
var list = MemberIdList.ToList();
list.Remove(Server._user!.Id);
_user = SocketUserBase.GetUser(list.FirstOrDefault(), SocketRemoteUserContext.Default.SocketRemoteUser).Result;
}
return _user;
}
}
public SocketRemoteUser _user = null!;
}
[JsonSerializable(typeof(SocketDMChannel))]
[JsonSourceGenerationOptions(
GenerationMode = JsonSourceGenerationMode.Default,
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
WriteIndented = false)]
internal partial class SocketDMChannelContext : JsonSerializerContext
{
}

View File

@ -13,21 +13,17 @@
<RepositoryUrl>https://github.com/JacobTech-com/Luski.net</RepositoryUrl>
<IncludeSymbols>True</IncludeSymbols>
<FileVersion>1.0.0</FileVersion>
<Version>1.1.4-alpha</Version>
<Version>1.1.3-alpha23</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="JacobTechEncryption" Version="1.0.1" />
<PackageReference Include="websocketsharp.core" Version="1.0.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Sockets\" />
<Folder Include="Sound\" />
</ItemGroup>
<Target Name="CustomActionsAfterPublish" AfterTargets="Pack">
<Message Text="Actions AfterPublish: $(PackageId).$(PackageVersion).nupkg" Importance="high" />
<Exec Command="nuget push -Source https://nuget.jacobtech.com/v3/index.json bin\Release\$(PackageId).$(PackageVersion).nupkg" />
<Exec Command="nuget push -Source https://nuget.jacobtech.com/v3/index.json bin/Release/$(PackageId).$(PackageVersion).nupkg" />
</Target>
</Project>

174
Luski.net/Server.Account.cs Normal file
View File

@ -0,0 +1,174 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Authentication;
using System.Text;
using System.Text.Json;
using System.Threading;
using JacobTechEncryption;
using JacobTechEncryption.Enums;
using Luski.net.Enums;
using Luski.net.JsonTypes;
using Luski.net.JsonTypes.WSS;
using Luski.net.Structures.Main;
using Luski.net.Structures.Public;
using WebSocketSharp;
using File = System.IO.File;
namespace Luski.net;
public partial class Server<TUser>
{
public void Login(string Email, string Password, CancellationToken CancellationToken)
{
Both(Email, Password, CancellationToken);
}
public void CreateAccount(string Email, string Password, string Username, string PFP, CancellationToken CancellationToken)
{
Both(Email, Password, CancellationToken, Username, PFP);
}
private void Both(string Email, string Password, CancellationToken CancellationToken, string? Username = null, string? pfp = null)
{
if (!ClientEncryption.Generating)
{
ClientEncryption.GenerateKeys();
}
while (!ClientEncryption.Generated) { }
login = true;
Login json;
List<KeyValuePair<string, string?>> heads = new()
{
new("key", ClientEncryption.MyPublicKey),
new("username", Convert.ToBase64String(Encryption.RSA.Encrypt(Email, ClientEncryption.MyPublicKey, EncoderType.UTF8))),
new("password", ClientEncryption.RemotePasswordEncrypt(Encoding.UTF8.GetBytes(Password)))
};
if (File.Exists("LastPassVer.txt") && int.TryParse(File.ReadAllText("LastPassVer.txt"), out int lpv) && lpv < ClientEncryption.PasswordVersion && lpv >= 0)
{
heads.Add(new("old_password", ClientEncryption.RemotePasswordEncrypt(Encoding.UTF8.GetBytes(Password), lpv)));
heads.Add(new("old_version", lpv.ToString()));
}
if (pfp is not null)
{
heads.Add(new("username", Username));
json = SendServer(
"CreateAccount",
pfp,
LoginContext.Default.Login,
CancellationToken,
heads.ToArray()).Result;
}
else
{
json = GetFromServer(
"Login",
LoginContext.Default.Login,
CancellationToken,
heads.ToArray()).Result;
}
if (json.Error is not null) throw new Exception($"Luski appears to be down at the current moment: {json.ErrorMessage}");
if (ClientEncryption.ofkey is null || ClientEncryption.outofkey is null) throw new Exception("Something went wrong generating the offline keys");
login = false;
if (json is not null && json.Error is null)
{
ServerOut = new WebSocket($"wss://{Domain}/WSS/{ApiVersion}");
ServerOut.SslConfiguration.EnabledSslProtocols = SslProtocols.Tls13 | SslProtocols.Tls12;
ServerOut.OnMessage += DataFromServer;
ServerOut.WaitTime = new TimeSpan(0, 0, 5);
ServerOut.OnError += ServerOut_OnError;
ServerOut.Connect();
SendServer(new WSSLogin() { Token = json.Token! }, WSSLoginContext.Default.WSSLogin);
while (Token is null && Error is null)
{
}
if (Error is not null)
{
throw new Exception(Error);
}
if (Token is null) throw new Exception("Server did not send a token");
CanRequest = true;
long id = long.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(
Token.Split('.')[0]
)));
TUser t = new();
User = t switch
{
MainSocketAppUser => (GetUser(id, MainSocketAppUserContext.Default.MainSocketAppUser,
CancellationToken.None)
.Result as TUser)!,
_ => (GetUser(id, PublicSocketAppUserContext.Default.PublicSocketAppUser, CancellationToken.None)
.Result as TUser)!
};
if (User is null || User.Error is not null)
{
string error = "User was null";
if (User is not null && User.Error is not null) error = $"{User.Error}: {User.ErrorMessage}";
throw new Exception($"Something went wrong getting your user infermation\n{error}");
}
Console.WriteLine("User got");
Console.WriteLine("Insert");
//User.Email = Email;
_ = UpdateStatus(UserStatus.Online, CancellationToken);
Console.WriteLine("stat");
try
{
ClientEncryption.pw = Email.ToLower() + Password;
_ = ClientEncryption.File.GetOfflineKey();
}
catch
{
try
{
ClientEncryption.pw = Email + Password;
var temp222 = ClientEncryption.File.LuskiDataFile.GetDefualtDataFile();
ClientEncryption.pw = Email.ToLower() + Password;
if (temp222 is not null) temp222.Save("key.lsk", ClientEncryption.pw);
}
catch
{
Token = null;
Error = null;
ServerOut.Close();
throw new Exception("The key file you have is getting the wrong pasword. Type your Email in the same way you creaated your account to fix this error.");
}
}
Console.WriteLine("req offline");
OfflineData offlinedata = GetFromServer("Keys/GetOfflineData", OfflineDataContext.Default.OfflineData, CancellationToken).Result;
if (offlinedata.Data is not null && offlinedata.Data.Any()) Console.WriteLine(offlinedata.Data);
if (offlinedata is not null && offlinedata.Error is null && offlinedata.Data is not null && offlinedata.Data.Length > 0)
{
foreach (string keyex in offlinedata.Data)
{
Console.WriteLine(keyex);
KeyExchange? okd = JsonSerializer.Deserialize<KeyExchange>(keyex);
Console.WriteLine(okd);
if (okd is not null && !string.IsNullOrEmpty(okd.key))
{
Console.WriteLine(okd.channel);
Console.WriteLine(okd.key);
ClientEncryption.File.Channels.AddKey(okd.channel, Encoding.UTF8.GetString(Encryption.RSA.Decrypt(Convert.FromBase64String(okd.key), ClientEncryption.File.GetOfflineKey())));
}
}
}
Console.WriteLine("lpv");
System.IO.File.WriteAllText("LastPassVer.txt", ClientEncryption.PasswordVersion.ToString());
ClientEncryption.File.SetOfflineKey(ClientEncryption.ofkey);
using HttpClient setkey = new();
setkey.DefaultRequestHeaders.Add("token", Token);
_ = setkey.PostAsync($"https://{Domain}/{ApiVersion}/Keys/SetOfflineKey", new StringContent(ClientEncryption.outofkey)).Result;
//_ = User.Channels;
foreach (var ch in chans)
{
_ = ch.Members;
}
ClientEncryption.outofkey = null;
ClientEncryption.ofkey = null;
}
else throw new Exception(json?.ErrorMessage);
}
}

View File

@ -1,17 +0,0 @@
using System;
using System.IO;
namespace Luski.net;
public sealed partial class Server : IDisposable
{
~Server()
{
try { if (Directory.Exists(Cache)) Directory.Delete(Cache, true); } catch { }
}
public void Dispose()
{
try { if (Directory.Exists(Cache)) Directory.Delete(Cache, true); } catch { }
}
}

View File

@ -1,129 +0,0 @@
using Luski.net.Enums;
using Luski.net.JsonTypes;
using Luski.net.JsonTypes.BaseTypes;
using Luski.net.JsonTypes.WSS;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using WebSocketSharp;
using File = System.IO.File;
namespace Luski.net;
public sealed partial class Server
{
internal Server(string Email, string Password, Branch branch = Branch.Master, string? Username = null, string? pfp = null)
{
if (!Encryption.Generating)
{
Encryption.GenerateKeys();
}
while (!Encryption.Generated) { }
InternalDomain = $"api.{branch}.luski.JacobTech.com";
Branch = branch;
login = true;
Login json;
List<KeyValuePair<string, string?>> heads = new()
{
new("key", Encryption.MyPublicKey),
new("email", Convert.ToBase64String(Encryption.Encrypt(Email))),
new("password", Encryption.RemotePasswordEncrypt(Encryption.Encoder.GetBytes(Password)))
};
if (File.Exists("LastPassVer.txt") && int.TryParse(File.ReadAllText("LastPassVer.txt"), out int lpv) && lpv < Encryption.PasswordVersion && lpv >= 0)
{
heads.Add(new("old_password", Encryption.RemotePasswordEncrypt(Encryption.Encoder.GetBytes(Password), lpv)));
heads.Add(new("old_version", lpv.ToString()));
}
if (pfp is not null)
{
heads.Add(new("username", Username));
json = SendServer(
"CreateAccount",
pfp,
LoginContext.Default.Login,
heads.ToArray()).Result;
}
else
{
json = GetFromServer(
"Login",
LoginContext.Default.Login,
heads.ToArray()).Result;
}
if (json.Error is not null) throw new Exception($"Luski appears to be down at the current moment: {json.ErrorMessage}");
if (Encryption.ofkey is null || Encryption.outofkey is null) throw new Exception("Something went wrong generating the offline keys");
login = false;
if (json is not null && json.Error is null)
{
ServerOut = new WebSocket($"wss://{InternalDomain}/WSS/{API_Ver}");
ServerOut.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls13;
ServerOut.OnMessage += DataFromServer;
ServerOut.WaitTime = new TimeSpan(0, 0, 5);
ServerOut.OnError += ServerOut_OnError;
ServerOut.Connect();
string Infermation = $"{{\"token\": \"{json.Token}\"}}";
SendServer(new WSSLogin() { Token = json.Token! }, WSSLoginContext.Default.WSSLogin);
while (Token is null && Error is null)
{
}
if (Error is not null)
{
throw new Exception(Error);
}
if (Token is null) throw new Exception("Server did not send a token");
CanRequest = true;
_user = SocketUserBase.GetUser(long.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(Token.Split('.')[0]))), SocketAppUserContext.Default.SocketAppUser).Result;
if (_user is null || _user.Error is not null) throw new Exception("Something went wrong getting your user infermation");
_ = _user.Channels;
foreach (var ch in chans)
{
_ = ch.Members;
}
_user.Email = Email;
_ = UpdateStatus(UserStatus.Online);
try
{
Encryption.pw = Email.ToLower() + Password;
_ = Encryption.File.GetOfflineKey();
}
catch
{
try
{
Encryption.pw = Email + Password;
var temp222 = Encryption.File.LuskiDataFile.GetDefualtDataFile();
Encryption.pw = Email.ToLower() + Password;
if (temp222 is not null) temp222.Save(GetKeyFilePath, Encryption.pw);
}
catch
{
Token = null;
Error = null;
ServerOut.Close();
throw new Exception("The key file you have is getting the wrong pasword. Type your Email in the same way you creaated your account to fix this error.");
}
}
OfflineKeyData offlinedata = GetFromServer("Keys/GetOfflineData", OfflineKeyDataContext.Default.OfflineKeyData).Result;
if (st