Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
AlphaBs committed Jun 2, 2021
2 parents bed09f7 + 461e41b commit d158438
Show file tree
Hide file tree
Showing 106 changed files with 3,584 additions and 3,477 deletions.
6 changes: 0 additions & 6 deletions CmlLib.sln
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CmlLibWinFormSample", "CmlL
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CmlLib", "CmlLib\CmlLib.csproj", "{AF1C09F9-C4BD-420A-85B9-9EB454F55FCD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XboxLoginTest", "XboxLoginTest\XboxLoginTest.csproj", "{734E181F-9954-4F9C-93A0-A646FF96AEC1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -29,10 +27,6 @@ Global
{AF1C09F9-C4BD-420A-85B9-9EB454F55FCD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AF1C09F9-C4BD-420A-85B9-9EB454F55FCD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AF1C09F9-C4BD-420A-85B9-9EB454F55FCD}.Release|Any CPU.Build.0 = Release|Any CPU
{734E181F-9954-4F9C-93A0-A646FF96AEC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{734E181F-9954-4F9C-93A0-A646FF96AEC1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{734E181F-9954-4F9C-93A0-A646FF96AEC1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{734E181F-9954-4F9C-93A0-A646FF96AEC1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
3 changes: 3 additions & 0 deletions CmlLib.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=1b89beda_002D4214_002D4128_002Db463_002D5c556bb68962/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Static, Instance" AccessRightKinds="Public" Description="public method"&gt;&lt;ElementKinds&gt;&lt;Kind Name="METHOD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=31c49da0_002D9fe2_002D42ee_002Db6f8_002D81a44971aaf8/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Static, Instance" AccessRightKinds="Private" Description="private method"&gt;&lt;ElementKinds&gt;&lt;Kind Name="METHOD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String></wpf:ResourceDictionary>
54 changes: 33 additions & 21 deletions CmlLib/CmlLib.csproj
Original file line number Diff line number Diff line change
@@ -1,27 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net462;net5.0</TargetFrameworks>
<Version>3.1.1</Version>
<Description>Minecraft Launcher Library for .NET Core and .NET Framework
<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net462;net5.0</TargetFrameworks>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
<Version>3.2.0</Version>
<Description>Minecraft Launcher Library for .NET Core and .NET Framework
Support All versions, forge, optifine
see github to learn how to use</Description>
<Copyright>Copyright (c) 2020 AlphaBs</Copyright>
<PackageProjectUrl>https://github.com/AlphaBs/CmlLib.Core</PackageProjectUrl>
<RepositoryUrl>https://github.com/AlphaBs/CmlLib.Core</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageTags>Minecraft Launcher forge optifine .NET Core Crossplatform C#</PackageTags>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Authors>AlphaBs</Authors>
<PackageReleaseNotes />
<PackageId>CmlLib.Core</PackageId>
</PropertyGroup>
see github to learn how to use
</Description>
<Copyright>Copyright (c) 2020 AlphaBs</Copyright>
<PackageProjectUrl>https://github.com/AlphaBs/CmlLib.Core</PackageProjectUrl>
<RepositoryUrl>https://github.com/AlphaBs/CmlLib.Core</RepositoryUrl>
<iconUrl>icon.png</iconUrl>
<RepositoryType>git</RepositoryType>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageTags>Minecraft Launcher forge optifine mojang Crossplatform C#</PackageTags>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Authors>AlphaBs</Authors>
<PackageReleaseNotes/>
<PackageId>CmlLib.Core</PackageId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="LZMA-SDK" Version="19.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="SharpZipLib" Version="1.2.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Fody" Version="6.5.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="LZMA-SDK" Version="19.0.0"/>
<PackageReference Include="MethodTimer.Fody" Version="3.2.0">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3"/>
<PackageReference Include="SharpZipLib" Version="1.2.0"/>
<None Include="../icon.png" Pack="true" Visible="false" PackagePath=""/>
</ItemGroup>

</Project>
104 changes: 56 additions & 48 deletions CmlLib/Core/Auth/MLogin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
using System.Net;
using System.Text;

// use new library:
// https://github.com/CmlLib/MojangAPI

namespace CmlLib.Core.Auth
{
public enum MLoginResult { Success, BadRequest, WrongAccount, NeedLogin, UnknownError, NoProfile }
Expand All @@ -28,21 +31,23 @@ private string CreateNewClientToken()
return Guid.NewGuid().ToString().Replace("-", "");
}

private MSession CreateNewSession()
private MSession createNewSession()
{
var session = new MSession();
if (SaveSession)
{
session.ClientToken = CreateNewClientToken();
WriteSessionCache(session);
writeSessionCache(session);
}
return session;
}

private void WriteSessionCache(MSession session)
private void writeSessionCache(MSession session)
{
if (!SaveSession) return;
Directory.CreateDirectory(Path.GetDirectoryName(SessionCacheFilePath));
var directoryPath = Path.GetDirectoryName(SessionCacheFilePath);
if (!string.IsNullOrEmpty(directoryPath))
Directory.CreateDirectory(directoryPath);

var json = JsonConvert.SerializeObject(session);
File.WriteAllText(SessionCacheFilePath, json, Encoding.UTF8);
Expand All @@ -52,13 +57,13 @@ public MSession ReadSessionCache()
{
if (File.Exists(SessionCacheFilePath))
{
var filedata = File.ReadAllText(SessionCacheFilePath, Encoding.UTF8);
var fileData = File.ReadAllText(SessionCacheFilePath, Encoding.UTF8);
try
{
var session = JsonConvert.DeserializeObject<MSession>(filedata, new JsonSerializerSettings()
var session = JsonConvert.DeserializeObject<MSession>(fileData, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
}) ?? new MSession();

if (SaveSession && string.IsNullOrEmpty(session.ClientToken))
session.ClientToken = CreateNewClientToken();
Expand All @@ -67,31 +72,31 @@ public MSession ReadSessionCache()
}
catch (JsonReaderException) // invalid json
{
return CreateNewSession();
return createNewSession();
}
}
else
{
return CreateNewSession();
return createNewSession();
}
}

private HttpWebResponse mojangRequest(string endpoint, string postdata)
{
var http = WebRequest.CreateHttp(MojangServer.Auth + endpoint);
HttpWebRequest http = WebRequest.CreateHttp(MojangServer.Auth + endpoint);
http.ContentType = "application/json";
http.Method = "POST";
using (var req = new StreamWriter(http.GetRequestStream()))
using (StreamWriter req = new StreamWriter(http.GetRequestStream()))
{
req.Write(postdata);
req.Flush();
}

var res = http.GetResponseNoException();
HttpWebResponse res = http.GetResponseNoException();
return res;
}

private MLoginResponse parseSession(string json, string clientToken)
private MLoginResponse parseSession(string json, string? clientToken)
{
var job = JObject.Parse(json); //json parse

Expand All @@ -100,15 +105,15 @@ private MLoginResponse parseSession(string json, string clientToken)
return new MLoginResponse(MLoginResult.NoProfile, null, null, json);
else
{
var session = new MSession()
var session = new MSession
{
AccessToken = job["accessToken"]?.ToString(),
UUID = profile["id"]?.ToString(),
Username = profile["name"]?.ToString(),
ClientToken = clientToken
};

WriteSessionCache(session);
writeSessionCache(session);
return new MLoginResponse(MLoginResult.Success, session, null, null);
}
}
Expand All @@ -117,10 +122,10 @@ private MLoginResponse errorHandle(string json)
{
try
{
var job = JObject.Parse(json);
JObject job = JObject.Parse(json);

var error = job["error"]?.ToString(); // error type
var errormsg = job["message"]?.ToString() ?? ""; // detail error message
string error = job["error"]?.ToString() ?? ""; // error type
string errorMessage = job["message"]?.ToString() ?? ""; // detail error message
MLoginResult result;

switch (error)
Expand All @@ -139,7 +144,7 @@ private MLoginResponse errorHandle(string json)
break;
}

return new MLoginResponse(result, null, errormsg, json);
return new MLoginResponse(result, null, errorMessage, json);
}
catch (Exception ex)
{
Expand All @@ -149,13 +154,13 @@ private MLoginResponse errorHandle(string json)

public MLoginResponse Authenticate(string id, string pw)
{
var clientToken = ReadSessionCache().ClientToken;
string? clientToken = ReadSessionCache().ClientToken;
return Authenticate(id, pw, clientToken);
}

public MLoginResponse Authenticate(string id, string pw, string clientToken)
public MLoginResponse Authenticate(string id, string pw, string? clientToken)
{
var req = new JObject
JObject req = new JObject
{
{ "username", id },
{ "password", pw },
Expand All @@ -168,11 +173,11 @@ public MLoginResponse Authenticate(string id, string pw, string clientToken)
}
};

var resHeader = mojangRequest("authenticate", req.ToString());
HttpWebResponse resHeader = mojangRequest("authenticate", req.ToString());

using (var res = new StreamReader(resHeader.GetResponseStream()))
using (StreamReader res = new StreamReader(resHeader.GetResponseStream()!))
{
var rawResponse = res.ReadToEnd();
string rawResponse = res.ReadToEnd();
if (resHeader.StatusCode == HttpStatusCode.OK) // ResultCode == 200
return parseSession(rawResponse, clientToken);
else // fail to login
Expand All @@ -182,15 +187,15 @@ public MLoginResponse Authenticate(string id, string pw, string clientToken)

public MLoginResponse TryAutoLogin()
{
var session = ReadSessionCache();
MSession session = ReadSessionCache();
return TryAutoLogin(session);
}

public MLoginResponse TryAutoLogin(MSession session)
{
try
{
var result = Validate(session);
MLoginResponse result = Validate(session);
if (result.Result != MLoginResult.Success)
result = Refresh(session);
return result;
Expand All @@ -206,6 +211,9 @@ public MLoginResponse TryAutoLoginFromMojangLauncher()
var mojangAccounts = MojangLauncher.MojangLauncherAccounts.FromDefaultPath();
var activeAccount = mojangAccounts.GetActiveAccount();

if (activeAccount == null)
return new MLoginResponse(MLoginResult.NeedLogin, null, null, null);

return TryAutoLogin(activeAccount.ToSession());
}

Expand All @@ -214,33 +222,36 @@ public MLoginResponse TryAutoLoginFromMojangLauncher(string accountFilePath)
var mojangAccounts = MojangLauncher.MojangLauncherAccounts.FromFile(accountFilePath);
var activeAccount = mojangAccounts.GetActiveAccount();

if (activeAccount == null)
return new MLoginResponse(MLoginResult.NeedLogin, null, null, null);

return TryAutoLogin(activeAccount.ToSession());
}

public MLoginResponse Refresh()
{
var session = ReadSessionCache();
MSession session = ReadSessionCache();
return Refresh(session);
}

public MLoginResponse Refresh(MSession session)
{
var req = new JObject
JObject req = new JObject
{
{ "accessToken", session.AccessToken },
{ "clientToken", session.ClientToken },
{ "selectedProfile", new JObject()
{ "selectedProfile", new JObject
{
{ "id", session.UUID },
{ "name", session.Username }
}
}
};

var resHeader = mojangRequest("refresh", req.ToString());
using (var res = new StreamReader(resHeader.GetResponseStream()))
HttpWebResponse resHeader = mojangRequest("refresh", req.ToString());
using (StreamReader res = new StreamReader(resHeader.GetResponseStream()!))
{
var rawResponse = res.ReadToEnd();
string rawResponse = res.ReadToEnd();

if ((int)resHeader.StatusCode / 100 == 2)
return parseSession(rawResponse, session.ClientToken);
Expand All @@ -251,7 +262,7 @@ public MLoginResponse Refresh(MSession session)

public MLoginResponse Validate()
{
var session = ReadSessionCache();
MSession session = ReadSessionCache();
return Validate(session);
}

Expand All @@ -263,14 +274,11 @@ public MLoginResponse Validate(MSession session)
{ "clientToken", session.ClientToken }
};

var resHeader = mojangRequest("validate", req.ToString());
using (var res = new StreamReader(resHeader.GetResponseStream()))
{
if (resHeader.StatusCode == HttpStatusCode.NoContent) // StatusCode == 204
return new MLoginResponse(MLoginResult.Success, session, null, null);
else
return new MLoginResponse(MLoginResult.NeedLogin, null, null, null);
}
HttpWebResponse resHeader = mojangRequest("validate", req.ToString());
if (resHeader.StatusCode == HttpStatusCode.NoContent) // StatusCode == 204
return new MLoginResponse(MLoginResult.Success, session, null, null);
else
return new MLoginResponse(MLoginResult.NeedLogin, null, null, null);
}

public void DeleteTokenFile()
Expand All @@ -281,31 +289,31 @@ public void DeleteTokenFile()

public bool Invalidate()
{
var session = ReadSessionCache();
MSession session = ReadSessionCache();
return Invalidate(session);
}

public bool Invalidate(MSession session)
{
var job = new JObject
JObject job = new JObject
{
{ "accessToken", session.AccessToken },
{ "clientToken", session.ClientToken }
};

var res = mojangRequest("invalidate", job.ToString());
HttpWebResponse res = mojangRequest("invalidate", job.ToString());
return res.StatusCode == HttpStatusCode.NoContent; // 204
}

public bool Signout(string id, string pw)
{
var job = new JObject
JObject job = new JObject
{
{ "username", id },
{ "password", pw }
};

var res = mojangRequest("signout", job.ToString());
HttpWebResponse res = mojangRequest("signout", job.ToString());
return res.StatusCode == HttpStatusCode.NoContent; // 204
}
}
Expand All @@ -320,7 +328,7 @@ public static HttpWebResponse GetResponseNoException(this HttpWebRequest req)
}
catch (WebException we)
{
var resp = we.Response as HttpWebResponse;
HttpWebResponse? resp = we.Response as HttpWebResponse;
if (resp == null)
throw;
return resp;
Expand Down
Loading

0 comments on commit d158438

Please sign in to comment.