1
0
mirror of https://e.coding.net/circlecloud/CTZLauncher.git synced 2024-11-22 02:08:49 +00:00

添加外部登陆接口...

This commit is contained in:
j502647092 2015-07-31 22:27:55 +08:00
parent 40549f65af
commit 6c220236ab
10 changed files with 387 additions and 291 deletions

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using CityCraft;
namespace CTZLauncher.CTZAuth
{
class CTZAuth : ICTZAuth
{
HttpHelper http = new HttpHelper();
string address;
string port;
public bool isRegister(string username)
{
return getResult(address + ":" + port + "/isregister?username=" + username);
}
public bool Register(string username, string password)
{
return false;
}
public bool isLogin(string username)
{
return getResult(address + ":" + port + "/islogin?username=" + username);
}
public bool Login(string username, string password)
{
return false;
}
public bool getResult(string url)
{
string result = http.Send(HttpMethod.GET, url);
if (result == "true")
return true;
return false;
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CTZLauncher.CTZAuth
{
interface ICTZAuth
{
public abstract bool isRegister(string username);
public abstract bool Register(string username, string password);
public abstract bool isLogin(string username);
public abstract bool Login(string username, string password);
}
}

View File

@ -65,6 +65,8 @@
<DependentUpon>App.xaml</DependentUpon> <DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
<Compile Include="CTZAuth\CTZAuth.cs" />
<Compile Include="CTZAuth\ICTZAuth.cs" />
<Compile Include="HttpHelper.cs" /> <Compile Include="HttpHelper.cs" />
<Compile Include="MainWindow.xaml.cs"> <Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon> <DependentUpon>MainWindow.xaml</DependentUpon>

View File

@ -12,6 +12,7 @@ using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading; using System.Threading;
using System.Windows.Threading;
namespace CityCraft namespace CityCraft
{ {
@ -60,12 +61,33 @@ namespace CityCraft
/// <param name="geturl">请求地址</param> /// <param name="geturl">请求地址</param>
/// <param name="cookieser">Cookies存储器</param> /// <param name="cookieser">Cookies存储器</param>
/// <returns>请求返回的Stream</returns> /// <returns>请求返回的Stream</returns>
public void Send(HttpMethod method, string url) public string Send(HttpMethod method, string url, bool Async = false)
{ {
readyState = HttpReadyState.; readyState = HttpReadyState.;
ParseURL(url); ParseURL(url);
args.Method = method; args.Method = method;
new Thread(new ThreadStart(ReciveData)).Start(); new Thread(new ThreadStart(ReciveData)).Start();
if (!Async)
{
while (readyState != HttpReadyState.) { this.DoEvent(); }
return responseBody;
}
return string.Empty;
}
/// <summary>
/// 模仿C#的Application.Doevent函数。可以适当添加try catch 模块
/// </summary>
public void DoEvent()
{
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrame), frame);
Dispatcher.PushFrame(frame);
}
public object ExitFrame(object f)
{
((DispatcherFrame)f).Continue = false;
return null;
} }
public void ReciveData() public void ReciveData()

View File

@ -66,7 +66,7 @@
</Grid> </Grid>
<Grid Margin="30,20,30,30" Height="100" VerticalAlignment="Bottom"> <Grid Margin="30,20,30,30" Height="100" VerticalAlignment="Bottom">
<Button Margin="12,24,167,35" Template="{StaticResource CornerButton}" Width="111" HorizontalAlignment="Center" Content="登录" Click="Login_Click" Background="Green" /> <Button Margin="12,24,167,35" Template="{StaticResource CornerButton}" Width="111" HorizontalAlignment="Center" Content="登录" Click="Login_Click" Background="Green" />
<Button Margin="167,24,12,35" Template="{StaticResource CornerButton}" Width="111" HorizontalAlignment="Center" Content="注册" Background="Green" /> <Button Name="register" Margin="167,24,12,35" Template="{StaticResource CornerButton}" Width="111" HorizontalAlignment="Center" Content="注册" Background="Green" Click="register_Click" />
</Grid> </Grid>
</Grid> </Grid>
</Grid> </Grid>

View File

@ -160,7 +160,6 @@ namespace CTZLauncher
private void maxmem_TextChanged(object sender, TextChangedEventArgs e) private void maxmem_TextChanged(object sender, TextChangedEventArgs e)
{ {
//屏蔽中文输入和非法字符粘贴输入 //屏蔽中文输入和非法字符粘贴输入
TextBox textBox = sender as TextBox; TextBox textBox = sender as TextBox;
TextChange[] change = new TextChange[e.Changes.Count]; TextChange[] change = new TextChange[e.Changes.Count];
@ -177,5 +176,15 @@ namespace CTZLauncher
} }
} }
} }
private void register_Click(object sender, RoutedEventArgs e)
{
if (username.Text.Length == 0 || password.Text.Length == 0)
{
MessageBox.Show("请输入账号密码!");
return;
}
}
} }
} }

View File

@ -20,12 +20,12 @@
/// <summary> /// <summary>
/// UUID不解释 /// UUID不解释
/// </summary> /// </summary>
public Guid UUID { get; set; } public Guid? UUID { get; set; }
/// <summary> /// <summary>
/// Session不解释 /// Session不解释
/// </summary> /// </summary>
public Guid AccessToken { get; set; } public Guid? AccessToken { get; set; }
/// <summary> /// <summary>
/// 各种属性比如Twitch的Session /// 各种属性比如Twitch的Session

View File

@ -1,70 +1,70 @@
namespace KMCCC.Authentication namespace KMCCC.Authentication
{ {
#region #region
using System; using System;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
#endregion #endregion
/// <summary> /// <summary>
/// 离线验证器 /// 离线验证器
/// </summary> /// </summary>
public class OfflineAuthenticator : IAuthenticator public class OfflineAuthenticator : IAuthenticator
{ {
/// <summary> /// <summary>
/// 玩家的名字 /// 玩家的名字
/// </summary> /// </summary>
public readonly string DisplayName; public readonly string DisplayName;
/// <summary> /// <summary>
/// 构造离线验证器 /// 构造离线验证器
/// </summary> /// </summary>
/// <param name="displayName">玩家的名字</param> /// <param name="displayName">玩家的名字</param>
public OfflineAuthenticator(string displayName) public OfflineAuthenticator(string displayName)
{ {
DisplayName = displayName; DisplayName = displayName;
} }
/// <summary> /// <summary>
/// 标注离线验证器 /// 标注离线验证器
/// </summary> /// </summary>
public string Type public string Type
{ {
get { return "KMCCC.Offline"; } get { return "KMCCC.Offline"; }
} }
public AuthenticationInfo Do() public AuthenticationInfo Do()
{ {
if (String.IsNullOrWhiteSpace(DisplayName)) if (String.IsNullOrWhiteSpace(DisplayName))
{ {
return new AuthenticationInfo return new AuthenticationInfo
{ {
Error = "DisplayName不符合规范" Error = "DisplayName不符合规范"
}; };
} }
if (DisplayName.Count(char.IsWhiteSpace) > 0) if (DisplayName.Count(char.IsWhiteSpace) > 0)
{ {
return new AuthenticationInfo return new AuthenticationInfo
{ {
Error = "DisplayName不符合规范" Error = "DisplayName不符合规范"
}; };
} }
return new AuthenticationInfo return new AuthenticationInfo
{ {
AccessToken = Guid.NewGuid(), AccessToken = null,
DisplayName = DisplayName, DisplayName = DisplayName,
UUID = Guid.NewGuid(), UUID = null,
Properties = "{}", Properties = "{}",
UserType = "Mojang" UserType = "Mojang"
}; };
} }
public Task<AuthenticationInfo> DoAsync(CancellationToken token) public Task<AuthenticationInfo> DoAsync(CancellationToken token)
{ {
return Task.Factory.StartNew((Func<AuthenticationInfo>)Do, token); return Task.Factory.StartNew((Func<AuthenticationInfo>)Do, token);
} }
} }
} }

View File

@ -1,217 +1,217 @@
namespace KMCCC.Launcher namespace KMCCC.Launcher
{ {
#region #region
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Tools; using Tools;
#endregion #endregion
partial class LauncherCore partial class LauncherCore
{ {
internal object Locker = new object(); internal object Locker = new object();
private LaunchResult GenerateArguments(LaunchOptions options, ref MinecraftLaunchArguments args) private LaunchResult GenerateArguments(LaunchOptions options, ref MinecraftLaunchArguments args)
{ {
try try
{ {
var authentication = options.Authenticator.Do(); var authentication = options.Authenticator.Do();
if (!string.IsNullOrWhiteSpace(authentication.Error)) if (!string.IsNullOrWhiteSpace(authentication.Error))
return new LaunchResult return new LaunchResult
{ {
Success = false, Success = false,
ErrorType = ErrorType.AuthenticationFailed, ErrorType = ErrorType.AuthenticationFailed,
ErrorMessage = "验证错误: " + authentication.Error ErrorMessage = "验证错误: " + authentication.Error
}; };
args.CGCEnabled = true; args.CGCEnabled = true;
args.MainClass = options.Version.MainClass; args.MainClass = options.Version.MainClass;
args.MaxMemory = options.MaxMemory; args.MaxMemory = options.MaxMemory;
args.MinMemory = options.MinMemory; args.MinMemory = options.MinMemory;
args.NativePath = GameRootPath + options.Version.Id + @"\\" + options.Version.Id + @"-natives"; args.NativePath = GameRootPath + options.Version.Id + @"\\" + options.Version.Id + @"-natives";
foreach (var native in options.Version.Natives) foreach (var native in options.Version.Natives)
{ {
var exp = ZipTools.UnzipFile(this.GetNativePath(native), args.NativePath, native.Options); var exp = ZipTools.UnzipFile(this.GetNativePath(native), args.NativePath, native.Options);
if (exp == null) if (exp == null)
{ {
continue; continue;
} }
return new LaunchResult return new LaunchResult
{ {
Success = false, Success = false,
ErrorType = ErrorType.UncompressingFailed, ErrorType = ErrorType.UncompressingFailed,
ErrorMessage = string.Format("解压错误: {0}:{1}:{2}", native.NS, native.Name, native.Version), ErrorMessage = string.Format("解压错误: {0}:{1}:{2}", native.NS, native.Name, native.Version),
Exception = exp Exception = exp
}; };
} }
args.Server = options.Server; args.Server = options.Server;
args.Size = options.Size; args.Size = options.Size;
args.Libraries = options.Version.Libraries.Select(this.GetLibPath).ToList(); args.Libraries = options.Version.Libraries.Select(this.GetLibPath).ToList();
args.Libraries.Add(this.GetVersionJarPath(options.Version.JarId)); args.Libraries.Add(this.GetVersionJarPath(options.Version.JarId));
args.MinecraftArguments = options.Version.MinecraftArguments; args.MinecraftArguments = options.Version.MinecraftArguments;
args.Tokens.Add("auth_access_token", authentication.AccessToken.GoString()); args.Tokens.Add("auth_access_token", authentication.AccessToken.GoString());
args.Tokens.Add("auth_session", authentication.AccessToken.GoString()); args.Tokens.Add("auth_session", authentication.AccessToken.GoString());
args.Tokens.Add("auth_player_name", authentication.DisplayName); args.Tokens.Add("auth_player_name", authentication.DisplayName);
args.Tokens.Add("version_name", options.Version.Id); args.Tokens.Add("version_name", options.Version.Id);
args.Tokens.Add("game_directory", "."); args.Tokens.Add("game_directory", ".");
args.Tokens.Add("game_assets", "assets"); args.Tokens.Add("game_assets", "assets");
args.Tokens.Add("assets_root", "assets"); args.Tokens.Add("assets_root", "assets");
args.Tokens.Add("assets_index_name", options.Version.Assets); args.Tokens.Add("assets_index_name", options.Version.Assets);
args.Tokens.Add("auth_uuid", authentication.UUID.GoString()); args.Tokens.Add("auth_uuid", authentication.UUID.GoString());
args.Tokens.Add("user_properties", authentication.Properties); args.Tokens.Add("user_properties", authentication.Properties);
args.Tokens.Add("user_type", authentication.UserType); args.Tokens.Add("user_type", authentication.UserType);
args.AdvencedArguments = new List<string> { "-Dfml.ignoreInvalidMinecraftCertificates=true -Dfml.ignorePatchDiscrepancies=true" }; args.AdvencedArguments = new List<string> { "-Dfml.ignoreInvalidMinecraftCertificates=true -Dfml.ignorePatchDiscrepancies=true" };
args.Authentication = authentication; args.Authentication = authentication;
args.Version = options.Version; args.Version = options.Version;
if (options.Mode != null) if (options.Mode != null)
{ {
options.Mode.Operate(this, args); options.Mode.Operate(this, args);
} }
return null; return null;
} }
catch (Exception exp) catch (Exception exp)
{ {
Console.WriteLine(exp.Message); Console.WriteLine(exp.Message);
Console.WriteLine(exp.Source); Console.WriteLine(exp.Source);
Console.WriteLine(exp.StackTrace); Console.WriteLine(exp.StackTrace);
return new LaunchResult { Success = false, ErrorType = ErrorType.Unknown, ErrorMessage = "在生成参数时发生了意外的错误", Exception = exp }; return new LaunchResult { Success = false, ErrorType = ErrorType.Unknown, ErrorMessage = "在生成参数时发生了意外的错误", Exception = exp };
} }
} }
internal LaunchResult LaunchInternal(LaunchOptions options, params Action<MinecraftLaunchArguments>[] argumentsOperators) internal LaunchResult LaunchInternal(LaunchOptions options, params Action<MinecraftLaunchArguments>[] argumentsOperators)
{ {
lock (Locker) lock (Locker)
{ {
if (!File.Exists(JavaPath)) if (!File.Exists(JavaPath))
{ {
return new LaunchResult { Success = false, ErrorType = ErrorType.NoJAVA, ErrorMessage = "指定的JAVA位置不存在" }; return new LaunchResult { Success = false, ErrorType = ErrorType.NoJAVA, ErrorMessage = "指定的JAVA位置不存在" };
} }
CurrentCode = Random.Next(); CurrentCode = Random.Next();
var args = new MinecraftLaunchArguments(); var args = new MinecraftLaunchArguments();
var result = GenerateArguments(options, ref args); var result = GenerateArguments(options, ref args);
if (result != null) if (result != null)
{ {
return result; return result;
} }
if (argumentsOperators == null) return LaunchGame(args); if (argumentsOperators == null) return LaunchGame(args);
foreach (var opt in argumentsOperators) foreach (var opt in argumentsOperators)
{ {
try try
{ {
if (opt != null) if (opt != null)
{ {
opt(args); opt(args);
} }
} }
catch (Exception exp) catch (Exception exp)
{ {
return new LaunchResult { Success = false, ErrorType = ErrorType.OperatorException, ErrorMessage = "指定的操作器引发了异常", Exception = exp }; return new LaunchResult { Success = false, ErrorType = ErrorType.OperatorException, ErrorMessage = "指定的操作器引发了异常", Exception = exp };
} }
} }
return LaunchGame(args); return LaunchGame(args);
} }
} }
private LaunchResult LaunchGame(MinecraftLaunchArguments args) private LaunchResult LaunchGame(MinecraftLaunchArguments args)
{ {
Console.WriteLine(args.ToArguments()); Console.WriteLine(args.ToArguments());
try try
{ {
var handle = new LaunchHandle(args.Authentication) var handle = new LaunchHandle(args.Authentication)
{ {
Code = CurrentCode, Code = CurrentCode,
Core = this, Core = this,
Arguments = args, Arguments = args,
Process = Process.Start(new ProcessStartInfo(JavaPath) Process = Process.Start(new ProcessStartInfo(JavaPath)
{ {
Arguments = args.ToArguments(), Arguments = args.ToArguments(),
UseShellExecute = false, UseShellExecute = false,
WorkingDirectory = GameRootPath, WorkingDirectory = GameRootPath,
RedirectStandardError = true, RedirectStandardError = true,
RedirectStandardOutput = true RedirectStandardOutput = true
}) })
}; };
handle.Work(); handle.Work();
Task.Factory.StartNew(handle.Process.WaitForExit).ContinueWith(t => Exit(handle, handle.Process.ExitCode)); Task.Factory.StartNew(handle.Process.WaitForExit).ContinueWith(t => Exit(handle, handle.Process.ExitCode));
return new LaunchResult { Success = true, Handle = handle }; return new LaunchResult { Success = true, Handle = handle };
} }
catch (Exception exp) catch (Exception exp)
{ {
return new LaunchResult { Success = false, ErrorType = ErrorType.Unknown, ErrorMessage = "启动时出现了异常", Exception = exp }; return new LaunchResult { Success = false, ErrorType = ErrorType.Unknown, ErrorMessage = "启动时出现了异常", Exception = exp };
} }
} }
#region #region
public void CopyVersionDirectory(string directoryName, string versionId) public void CopyVersionDirectory(string directoryName, string versionId)
{ {
CopyDirectory(string.Format(@"{0}\versions\{2}\{1}", GameRootPath, directoryName, versionId), CopyDirectory(string.Format(@"{0}\versions\{2}\{1}", GameRootPath, directoryName, versionId),
string.Format(@"{0}\{1}", GameRootPath, directoryName)); string.Format(@"{0}\{1}", GameRootPath, directoryName));
} }
public void CopyDirectory(string source, string target) public void CopyDirectory(string source, string target)
{ {
var code = CurrentCode; var code = CurrentCode;
if (!Directory.Exists(source)) return; if (!Directory.Exists(source)) return;
if (Directory.Exists(target)) if (Directory.Exists(target))
{ {
Directory.Delete(target, true); Directory.Delete(target, true);
} }
UsefulTools.Dircopy(source, target); UsefulTools.Dircopy(source, target);
Action<LaunchHandle, int> handler = null; Action<LaunchHandle, int> handler = null;
handler = (handle, c) => handler = (handle, c) =>
{ {
if (handle.Code == code) if (handle.Code == code)
{ {
Directory.Delete(source, true); Directory.Delete(source, true);
UsefulTools.Dircopy(target, source); UsefulTools.Dircopy(target, source);
Directory.Delete(target, true); Directory.Delete(target, true);
} }
GameExit -= handler; GameExit -= handler;
}; };
GameExit += handler; GameExit += handler;
} }
public void CopyVersionDirectories(string ver) public void CopyVersionDirectories(string ver)
{ {
var root = string.Format(@"{0}\versions\{1}\moddir", GameRootPath, ver); var root = string.Format(@"{0}\versions\{1}\moddir", GameRootPath, ver);
if (!Directory.Exists(root)) if (!Directory.Exists(root))
{ {
return; return;
} }
foreach (var dir in new DirectoryInfo(root).EnumerateDirectories()) foreach (var dir in new DirectoryInfo(root).EnumerateDirectories())
{ {
CopyDirectory(dir.FullName, string.Format(@"{0}\{1}", GameRootPath, dir.Name)); CopyDirectory(dir.FullName, string.Format(@"{0}\{1}", GameRootPath, dir.Name));
} }
} }
#endregion #endregion
#region #region
internal void Log(LaunchHandle handle, string line) internal void Log(LaunchHandle handle, string line)
{ {
if (GameLog != null) if (GameLog != null)
{ {
GameLog(handle, line); GameLog(handle, line);
} }
} }
internal void Exit(LaunchHandle handle, int code) internal void Exit(LaunchHandle handle, int code)
{ {
if (GameExit != null) if (GameExit != null)
{ {
GameExit(handle, code); GameExit(handle, code);
} }
} }
#endregion #endregion
} }
} }

View File

@ -19,8 +19,10 @@
return dic.Aggregate(source, (current, pair) => current.Replace("${" + pair.Key + "}", pair.Value)); return dic.Aggregate(source, (current, pair) => current.Replace("${" + pair.Key + "}", pair.Value));
} }
public static string GoString(this Guid guid) public static string GoString(this Guid? guid)
{ {
if (guid == null)
return "{}";
return guid.ToString().Replace("-", ""); return guid.ToString().Replace("-", "");
} }