Skip to content
This repository has been archived by the owner on Jun 19, 2023. It is now read-only.

Commit

Permalink
Cache AcIds in settings.
Browse files Browse the repository at this point in the history
  • Loading branch information
Berrysoft committed Aug 13, 2020
1 parent 14f7d8d commit f1bbb18
Show file tree
Hide file tree
Showing 12 changed files with 117 additions and 107 deletions.
17 changes: 17 additions & 0 deletions TsinghuaNet.CLI/NetCLISettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System.Text.Json.Serialization;
using TsinghuaNet.Models;

namespace TsinghuaNet.CLI
{
class NetCLISettings : NetSettingsBase
{
[JsonIgnore]
public override bool AutoLogin { get; set; }
[JsonIgnore]
public override bool EnableFluxLimit { get; set; }
[JsonIgnore]
public override ByteSize FluxLimit { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
}
1 change: 1 addition & 0 deletions TsinghuaNet.CLI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ private static async Task<int> RunVerb(object opts)
try
{
await ((VerbBase)opts).RunAsync();
VerbHelper.SaveSettings();
return 0;
}
catch (Exception ex)
Expand Down
52 changes: 18 additions & 34 deletions TsinghuaNet.CLI/VerbHelper.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TsinghuaNet.Models;
Expand All @@ -14,23 +13,25 @@ public async static Task<IConnect> GetHelperAsync(this NetVerbBase opts)
{
if (opts.Host == OptionNetState.Auto)
opts.Host = (OptionNetState)await Status.SuggestAsync();
var cred = Credential;
var settings = Settings;
var cred = new NetCredential { Username = settings.Username, Password = settings.Password };
cred.State = (NetState)opts.Host;
cred.UseProxy = opts.UseProxy;
return cred.GetHelper();
return cred.GetHelper(settings);
}

public static IUsereg GetUseregHelper(this WebVerbBase opts)
{
var cred = Credential;
var settings = Settings;
var cred = new NetCredential { Username = settings.Username, Password = settings.Password };
cred.UseProxy = opts.UseProxy;
return cred.GetUseregHelper();
}

private static string ReadPassword()
{
StringBuilder builder = new StringBuilder();
do
while (true)
{
var c = Console.ReadKey(true);
if (c.Key == ConsoleKey.Enter)
Expand All @@ -45,47 +46,30 @@ private static string ReadPassword()
break;
}
}
while (true);
Console.WriteLine();
return builder.ToString();
}

public static NetCredential ReadCredential()
public static NetCLISettings ReadCredential()
{
Console.Write("请输入用户名:");
var u = Console.ReadLine();
Console.Write("请输入密码:");
var p = ReadPassword();
return new NetCredential() { Username = u, Password = p };
return new NetCLISettings() { Username = u, Password = p };
}

public static NetCredential Credential
private static NetCLISettings settingsCache;

public static NetCLISettings Settings
{
get
{
var settings = SettingsHelper.Helper.ReadDictionary();
if (settings != null)
{
return new NetCredential
{
Username = settings["username"],
Password = Encoding.UTF8.GetString(Convert.FromBase64String(settings["password"]))
};
}
else
{
return ReadCredential();
}
}
set
{
var settings = new Dictionary<string, string>()
{
["username"] = value.Username ?? string.Empty,
["password"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(value.Password ?? string.Empty))
};
SettingsHelper.Helper.WriteDictionary(settings);
}
get => settingsCache ??= (SettingsHelper.Helper.ReadSettings<NetCLISettings>() ?? ReadCredential());
set => SettingsHelper.Helper.WriteSettings(value);
}

public static void SaveSettings()
{
Settings = settingsCache;
}
}

Expand Down
2 changes: 1 addition & 1 deletion TsinghuaNet.CLI/Verbs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ public override async Task RunAsync()
[Verb("savecred", HelpText = "保存用户名和密码")]
class SaveCredentialVerb : VerbBase
{
public override Task RunAsync() => Task.Run(() => VerbHelper.Credential = VerbHelper.ReadCredential());
public override Task RunAsync() => Task.Run(() => VerbHelper.Settings = VerbHelper.ReadCredential());
}

[Verb("deletecred", HelpText = "删除已保存的用户名和密码")]
Expand Down
15 changes: 5 additions & 10 deletions TsinghuaNet.Eto/TsinghuaNet.Eto/Models/NetEtoSettings.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
using System;
using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;
using TsinghuaNet.Models;

namespace TsinghuaNet.Eto.Models
{
public class NetEtoSettings : INetSettings
public class NetEtoSettings : NetSettingsBase
{
#pragma warning disable 0067
public event PropertyChangedEventHandler PropertyChanged;
#pragma warning restore 0067

public bool AutoLogin { get; set; }
public bool EnableFluxLimit { get; set; }
public override bool AutoLogin { get; set; }
public override bool EnableFluxLimit { get; set; }
[JsonConverter(typeof(JsonConverterByteSize))]
public ByteSize FluxLimit { get; set; }
public override ByteSize FluxLimit { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool UseTimer { get; set; }
Expand All @@ -33,7 +28,7 @@ internal static class SettingsHelper
public static readonly SettingsFileHelper Helper = new SettingsFileHelper(ProjectName, SettingsFilename);
}

internal class JsonConverterByteSize : JsonConverter<ByteSize>
public class JsonConverterByteSize : JsonConverter<ByteSize>
{
public override ByteSize Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Expand Down
29 changes: 20 additions & 9 deletions TsinghuaNet.XF/TsinghuaNet.XF/Models/NetXFSettings.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
using System.ComponentModel;
using System.Linq;
using TsinghuaNet.Models;
using Xamarin.Essentials;

namespace TsinghuaNet.XF.Models
{
public class NetXFSettings : INetSettings
public class NetXFSettings : NetSettingsBase
{
#pragma warning disable 0067
public event PropertyChangedEventHandler PropertyChanged;
#pragma warning restore 0067

public bool AutoLogin { get; set; }
public bool EnableFluxLimit { get; set; }
public ByteSize FluxLimit { get; set; }
public override bool AutoLogin { get; set; }
public override bool EnableFluxLimit { get; set; }
public override ByteSize FluxLimit { get; set; }
public bool BackgroundAutoLogin { get; set; }
public bool BackgroundLiveTile { get; set; }
public bool UseProxy { get; set; }
Expand All @@ -23,6 +19,7 @@ public class NetXFSettings : INetSettings
private const string EnableFluxLimitKey = "EnableFluxLimit";
private const string FluxLimitKey = "FluxLimit";
private const string UseProxyKey = "UseProxy";
private const string AcIdsKey = "AcIds";

public void LoadSettings()
{
Expand All @@ -32,6 +29,13 @@ public void LoadSettings()
EnableFluxLimit = Preferences.Get(EnableFluxLimitKey, false);
FluxLimit = ByteSize.FromGigaBytes(Preferences.Get(FluxLimitKey, 20.0));
UseProxy = Preferences.Get(UseProxyKey, false);
AcIds = Preferences.Get(AcIdsKey, string.Join(
#if NETSTANDARD2_0
";"
#else
';'
#endif
, PredefinedAcIds)).Split(';').Select(s => int.Parse(s)).ToList();
}

public void SaveSettings()
Expand All @@ -42,6 +46,13 @@ public void SaveSettings()
Preferences.Set(EnableFluxLimitKey, EnableFluxLimit);
Preferences.Set(FluxLimitKey, FluxLimit.GigaBytes);
Preferences.Set(UseProxyKey, UseProxy);
Preferences.Set(AcIdsKey, string.Join(
#if NETSTANDARD2_0
";"
#else
';'
#endif
, AcIds));
}
}
}
24 changes: 17 additions & 7 deletions TsinghuaNet/AuthHelper.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Text.RegularExpressions;
Expand All @@ -13,34 +14,43 @@ internal abstract class AuthHelper : NetHelperBase, IConnect
private const string LogUri = "https://auth{0}.tsinghua.edu.cn/cgi-bin/srun_portal";
private const string FluxUri = "https://auth{0}.tsinghua.edu.cn/rad_user_info.php";
private const string ChallengeUri = "https://auth{0}.tsinghua.edu.cn/cgi-bin/get_challenge?username={1}&double_stack=1&ip&callback=callback";
private static readonly int[] AcIds = new int[] { 1, 25, 33, 35, 37, 159 };
private static readonly int[] PredefinedAcIds = new int[] { 1, 25, 33, 35, 37, 159 };
private readonly int version;
private readonly NetSettingsBase settings;

public AuthHelper(string username, string password, HttpClient client, int version)
public AuthHelper(string username, string password, HttpClient client, int version, NetSettingsBase settings = null)
: base(username, password, client)
{
this.version = version;
this.settings = settings;
}

private async Task<LogResponse> LogAsync(Func<int, Task<Dictionary<string, string>>> f)
{
LogResponse response = default;
string uri = string.Format(LogUri, version);
foreach (int ac_id in AcIds)
foreach (int ac_id in settings != null ? settings.AcIds.AsEnumerable() : PredefinedAcIds)
{
response = LogResponse.ParseFromAuth(await PostReturnBytesAsync(uri, await f(ac_id)));
if (response.Succeed)
break;
}
if (response.Succeed)
{
return response;
}
else
{
int ac_id = await GetAcId();
if (ac_id > 0)
{
if (settings != null) settings.AcIds.Add(ac_id);
return LogResponse.ParseFromAuth(await PostReturnBytesAsync(uri, await f(ac_id)));
}
else
{
return response;
}
}
}

Expand Down Expand Up @@ -114,15 +124,15 @@ private async Task<Dictionary<string, string>> GetLogoutDataAsync(int ac_id)

internal class Auth4Helper : AuthHelper
{
public Auth4Helper(string username, string password, HttpClient client)
: base(username, password, client, 4)
public Auth4Helper(string username, string password, HttpClient client, NetSettingsBase settings = null)
: base(username, password, client, 4, settings)
{ }
}

internal class Auth6Helper : AuthHelper
{
public Auth6Helper(string username, string password, HttpClient client)
: base(username, password, client, 6)
public Auth6Helper(string username, string password, HttpClient client, NetSettingsBase settings = null)
: base(username, password, client, 6, settings)
{ }
}
}
13 changes: 0 additions & 13 deletions TsinghuaNet/Models/INetSettings.cs

This file was deleted.

6 changes: 3 additions & 3 deletions TsinghuaNet/Models/NetCredential.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ public class NetCredential : INotifyPropertyChanged
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private HttpClient GetClient() => UseProxy ? Client : NoProxyClient;

public IConnect GetHelper()
public IConnect GetHelper(NetSettingsBase settings = null)
{
return State switch
{
NetState.Net => new NetHelper(Username, Password, GetClient()),
NetState.Auth4 => new Auth4Helper(Username, Password, GetClient()),
NetState.Auth6 => new Auth6Helper(Username, Password, GetClient()),
NetState.Auth4 => new Auth4Helper(Username, Password, GetClient(), settings),
NetState.Auth6 => new Auth6Helper(Username, Password, GetClient(), settings),
_ => null,
};
}
Expand Down
22 changes: 22 additions & 0 deletions TsinghuaNet/Models/NetSettingsBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System.Collections.Generic;
using System.ComponentModel;

namespace TsinghuaNet.Models
{
public abstract class NetSettingsBase : INotifyPropertyChanged
{
protected static readonly List<int> PredefinedAcIds = new List<int> { 1, 25, 33, 35, 37, 159 };

#pragma warning disable 0067
public event PropertyChangedEventHandler PropertyChanged;
#pragma warning restore 0067

public abstract bool AutoLogin { get; set; }

public abstract bool EnableFluxLimit { get; set; }

public abstract ByteSize FluxLimit { get; set; }

public List<int> AcIds { get; set; } = new List<int>(PredefinedAcIds);
}
}
Loading

0 comments on commit f1bbb18

Please sign in to comment.