Skip to content

Commit

Permalink
Merge pull request #89 from DreamEnderKing/dev
Browse files Browse the repository at this point in the history
build: 🧪 Log system in installer updated.
  • Loading branch information
ONLOX authored Jan 28, 2024
2 parents 85f1d2f + a4b9810 commit 24e95ba
Show file tree
Hide file tree
Showing 6 changed files with 303 additions and 78 deletions.
2 changes: 2 additions & 0 deletions installer/MauiProgram.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ namespace installer
public static class MauiProgram
{
public static Model.Downloader Downloader = new Model.Downloader();
public static bool ErrorTrigger_WhileDebug = true;
public static bool RefreshLogs_WhileDebug = false;
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
Expand Down
97 changes: 91 additions & 6 deletions installer/Model/Downloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Compression;
using System.Formats.Tar;

namespace installer.Model
{
Expand All @@ -29,9 +32,9 @@ public class UserInfo
public Tencent_Cos Cloud; // THUAI7 Cos桶

public HttpClient Client = new HttpClient();
public EEsast Web = new EEsast(); // EEsast服务器
protected Logger Log = LoggerProvider.FromConsole();// 日志管理器

public EEsast Web; // EEsast服务器
public Logger Log; // 日志管理器
public Logger LogError;
public enum UpdateStatus
{
success, unarchieving, downloading, hash_computing, error
Expand All @@ -50,7 +53,7 @@ public enum LaunchLanguage { cpp, python };
public LaunchLanguage Language { get; set; } = LaunchLanguage.cpp;
public enum UsingOS { Win, Linux, OSX };
public UsingOS usingOS { get; set; }
public ConcurrentStack<Exception> Exceptions = new ConcurrentStack<Exception>();
public ExceptionStack Exceptions;
public class Updater
{
public string Message = string.Empty;
Expand All @@ -68,9 +71,88 @@ public class Updater
public Downloader()
{
Data = new Local_Data();
Log = LoggerProvider.FromFile(Path.Combine(Data.LogPath, "Main.log"));
LogError = LoggerProvider.FromFile(Path.Combine(Data.LogPath, "Main.error.log"));
if ((Log.LastRecordTime != DateTime.MinValue && DateTime.Now.Month != Log.LastRecordTime.Month)
|| (LogError.LastRecordTime != DateTime.MinValue && DateTime.Now.Month != LogError.LastRecordTime.Month))
{
string tardir = Path.Combine(Data.InstallPath, "LogArchieved");
if (!Directory.Exists(tardir))
Directory.CreateDirectory(tardir);
string tarPath = Path.Combine(tardir, $"Backup-{Log.LastRecordTime.Year}-{Log.LastRecordTime.Month}.tar");
if (File.Exists(tarPath))
File.Delete(tarPath);
if (File.Exists(tarPath + ".gz"))
File.Delete(tarPath + ".gz");
Data.Log.Dispose();
Data.LogError.Dispose();
Data.Exceptions.logger.Dispose();
Log.Dispose();
LogError.Dispose();
TarFile.CreateFromDirectory(Data.LogPath, tarPath, false);
using (FileStream tar = File.Open(tarPath, FileMode.Open))
using (FileStream gz = File.Create(tarPath + ".gz"))
using (var compressor = new GZipStream(gz, CompressionMode.Compress))
{
tar.CopyTo(compressor);
}
File.Delete(tarPath);
foreach (var log in Directory.EnumerateFiles(Data.LogPath))
{
File.Delete(log);
}
Data.Log = LoggerProvider.FromFile(Path.Combine(Data.LogPath, "LocalData.log"));
Data.LogError = LoggerProvider.FromFile(Path.Combine(Data.LogPath, "LocalData.error.log"));
Data.Exceptions = new ExceptionStack(Data.LogError);
Log = LoggerProvider.FromFile(Path.Combine(Data.LogPath, "Main.log"));
LogError = LoggerProvider.FromFile(Path.Combine(Data.LogPath, "Main.error.log"));
}
Exceptions = new ExceptionStack(LogError, this);
Route = Data.InstallPath;
Cloud = new Tencent_Cos("1319625962", "ap-beijing", "bucket1");
Cloud = new Tencent_Cos("1319625962", "ap-beijing", "bucket1",
LoggerProvider.FromFile(Path.Combine(Data.LogPath, "TencentCos.log")),
LoggerProvider.FromFile(Path.Combine(Data.LogPath, "TencentCos.error.log")));
Web = new EEsast(LoggerProvider.FromFile(Path.Combine(Data.LogPath, "EESAST.log")),
LoggerProvider.FromFile(Path.Combine(Data.LogPath, "EESAST.error.log")));
Web.Token_Changed += SaveToken;

// Debug模式下将Exceptions直接抛出触发断点
if (Debugger.IsAttached && MauiProgram.ErrorTrigger_WhileDebug)
{
Exceptions.OnFailed += (obj, _) =>
{
var e = Exceptions.Pop();
if (e is not null)
throw e;
};
}
Data.Exceptions.OnFailed += (obj, _) =>
{
var e = Data.Exceptions.Pop();
if (e is null) return;
if (obj is not null)
e.Data["Source"] = obj.ToString();
LogError.LogError($"从Downloader.Data处提取的错误。");
Exceptions.Push(e);
};
Cloud.Exceptions.OnFailed += (obj, _) =>
{
var e = Cloud.Exceptions.Pop();
if (e is null) return;
if (obj is not null)
e.Data["Source"] = obj.ToString();
LogError.LogError($"从Downloader.Cloud处提取的错误。");
Exceptions.Push(e);
};
Web.Exceptions.OnFailed += (obj, _) =>
{
var e = Web.Exceptions.Pop();
if (e is null) return;
if (obj is not null)
e.Data["Source"] = obj.ToString();
LogError.LogError($"从Downloader.Web处提取的错误。");
Exceptions.Push(e);
};
string? temp;
if (Data.Config.TryGetValue("Remembered", out temp))
{
Expand Down Expand Up @@ -138,7 +220,10 @@ public void Install()
/// <param name="newPath">新的THUAI7根目录</param>
public void ResetInstallPath(string newPath)
{
Data.ResetInstallPath(newPath);
newPath = newPath.EndsWith(Path.DirectorySeparatorChar) ? newPath[0..-1] : newPath;
var installPath = Data.InstallPath.EndsWith(Path.DirectorySeparatorChar) ? Data.InstallPath[0..-1] : Data.InstallPath;
if (newPath != Data.InstallPath)
Data.ResetInstallPath(newPath);
}

/// <summary>
Expand Down
46 changes: 24 additions & 22 deletions installer/Model/EEsast.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -23,7 +24,8 @@ public enum LangUsed { cpp, py };
private string token = string.Empty;
public string Token
{
get => token; protected set
get => token;
protected set
{
if (token != value)
Token_Changed?.Invoke(this, new EventArgs());
Expand All @@ -36,15 +38,21 @@ public string Token
public string ID { get; protected set; } = string.Empty;
public string Email { get; protected set; } = string.Empty;

public ConcurrentStack<Exception> Exceptions = new ConcurrentStack<Exception>();
protected Logger Log = LoggerProvider.FromConsole();

public Logger Log;
public Logger LogError;
public ExceptionStack Exceptions;
public enum WebStatus
{
disconnected, offline, logined
}
public WebStatus Status = WebStatus.disconnected;
public Tencent_Cos EEsast_Cos { get; protected set; } = new Tencent_Cos("1255334966", "ap-beijing", "eesast");
public EEsast(Logger? _log = null, Logger? _logError = null)
{
Log = _log ?? LoggerProvider.FromConsole();
LogError = _logError ?? Log;
Exceptions = new ExceptionStack(LogError, this);
}
public async Task LoginToEEsast(HttpClient client, string useremail = "", string userpassword = "")
{
try
Expand All @@ -62,6 +70,7 @@ public async Task LoginToEEsast(HttpClient client, string useremail = "", string
ID = info.Keys.Contains("_id") ? info["_id"] : string.Empty;

Check warning on line 70 in installer/Model/EEsast.cs

View workflow job for this annotation

GitHub Actions / dotnet-build-install

Dereference of a possibly null reference.
Email = info.Keys.Contains("email") ? info["email"] : string.Empty;
Token = info.Keys.Contains("token") ? info["token"] : string.Empty;
Log.LogInfo($"{Username} logined successfully.");
Status = WebStatus.logined;
break;
default:
Expand Down Expand Up @@ -96,8 +105,7 @@ public async Task<int> UploadFiles(HttpClient client, string userfile, string ty
{
if (Status != WebStatus.logined)
{
Log.LogError("用户未登录");
Exceptions.Append(new UnauthorizedAccessException("User hasn't logined."));
Exceptions.Push(new UnauthorizedAccessException("用户未登录。"));
return -1;
}
try
Expand All @@ -106,8 +114,7 @@ public async Task<int> UploadFiles(HttpClient client, string userfile, string ty
client.DefaultRequestHeaders.Authorization = new("Bearer", Token);
if (!File.Exists(userfile))
{
Log.LogError("选手文件(AI.cpp or AI.py)不存在");
Exceptions.Append(new IOException("Cannot find user's code."));
Exceptions.Push(new IOException("选手文件(AI.cpp or AI.py)不存在。"));
return -2;
}
using FileStream fs = new FileStream(userfile, FileMode.Open, FileAccess.Read);
Expand All @@ -128,29 +135,25 @@ public async Task<int> UploadFiles(HttpClient client, string userfile, string ty

string cosPath = $"/THUAI7/{GetTeamId()}/{type}/{plr}"; //对象在存储桶中的位置标识符,即称对象键
EEsast_Cos.UploadFileAsync(userfile, cosPath).Wait();

Log.LogInfo($"{userfile}上传成功。");
break;
case System.Net.HttpStatusCode.Unauthorized:
Log.LogError("未登录或登录过期,无法上传文件");
Exceptions.Push(new UnauthorizedAccessException("User token is out of expire time."));
Exceptions.Push(new UnauthorizedAccessException("未登录或登录过期,无法向EEsast上传文件。"));
return -4;
default:
Log.LogError("未知的错误");
Exceptions.Push(new Exception("Unknown reason."));
Exceptions.Push(new Exception("向eesast服务器上传时发生了未知的错误。"));
return -5;
}
}
}
catch (IOException)
{
Log.LogError("文件读取错误,请检查文件是否被其它应用占用");
Exceptions.Push(new IOException());
Exceptions.Push(new IOException($"{userfile}读取错误,请检查文件是否被其它应用占用。"));
return -6;
}
catch
{
Log.LogError("请求错误,无网络连接。");
Exceptions.Push(new Exception("Cannot connect to the web server."));
Exceptions.Push(new Exception("请求错误,无法连接到eesast服务器。"));
return -7;
}
return 0;
Expand All @@ -160,7 +163,7 @@ async public Task UserDetails(HttpClient client) // 用来测试访问网站
{
if (Status != WebStatus.logined) // 读取token失败
{
Exceptions.Append(new UnauthorizedAccessException("用户未登录"));
Exceptions.Push(new UnauthorizedAccessException("用户未登录"));
return;
}
try
Expand All @@ -172,14 +175,13 @@ async public Task UserDetails(HttpClient client) // 用来测试访问网站
switch (response.StatusCode)
{
case System.Net.HttpStatusCode.OK:
Console.WriteLine("Require OK");
Console.WriteLine(await response.Content.ReadAsStringAsync());
Log.LogInfo("Success!\n" + await response.Content.ReadAsStringAsync());
break;
default:
int code = ((int)response.StatusCode);
if (code == 401)
{
Console.WriteLine("您未登录或登录过期,请先登录");
Exceptions.Push(new UnauthorizedAccessException("您未登录或登录过期,请先登录"));
}
return;
}
Expand Down
Loading

0 comments on commit 24e95ba

Please sign in to comment.