Skip to content

Commit

Permalink
Merge pull request #105 from DreamEnderKing/dev
Browse files Browse the repository at this point in the history
依赖关系注入优化。
  • Loading branch information
ONLOX authored Mar 2, 2024
2 parents b256d8c + ed688e6 commit caca192
Show file tree
Hide file tree
Showing 16 changed files with 199 additions and 88 deletions.
44 changes: 41 additions & 3 deletions installer/MauiProgram.cs
Original file line number Diff line number Diff line change
@@ -1,31 +1,69 @@
using Microsoft.Extensions.Logging;
using System.Reflection;
using CommunityToolkit.Maui;
using CommunityToolkit.Maui.Core;
using CommunityToolkit.Maui.Storage;
using installer.ViewModel;
using System.Runtime.CompilerServices;
using installer.Model;

namespace installer
{
public static class MauiProgram
{
public static Model.Downloader Downloader = new Model.Downloader();
// public static Model.Logger logger = Model.LoggerProvider.FromFile(@"E:\bin\log\123.log");
public static bool ErrorTrigger_WhileDebug = true;
public static bool RefreshLogs_WhileDebug = false;
public static string SecretID = "***";
public static string SecretKey = "***";
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseMauiCommunityToolkitCore()
.UseMauiCommunityToolkit()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});

// 此处填写Secret ID和Secret Key
Downloader.Cloud.UpdateSecret("***", "***");
var c = builder.Services.AddSingleton<Downloader>().First();

builder.Services.AddSingleton(FolderPicker.Default);


AddViewModelService(builder);
AddPageService(builder);
#if DEBUG
builder.Logging.AddDebug();
#endif

return builder.Build();
}

public static void AddViewModelService(MauiAppBuilder builder)
{
var a = typeof(MauiProgram).Assembly;
foreach (var t in a.GetTypes())
{
if ((t.FullName ?? string.Empty).StartsWith($"{a.GetName().Name}.ViewModel") && !t.IsAbstract)
{
builder.Services.AddSingleton(t);
}
}
}
public static void AddPageService(MauiAppBuilder builder)
{
var a = typeof(MauiProgram).Assembly;
foreach (var t in a.GetTypes())
{
if ((t.FullName ?? string.Empty).StartsWith($"{a.GetName().Name}.Page") && !t.IsAbstract)
{
builder.Services.AddSingleton(t);
}
}
}
}
}
1 change: 1 addition & 0 deletions installer/Model/Downloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ public Downloader()
Password = temp;
}
}
Cloud.UpdateSecret(MauiProgram.SecretID, MauiProgram.SecretKey);
}

public void LoggerBinding()
Expand Down
92 changes: 51 additions & 41 deletions installer/Model/Local_Data.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ public Dictionary<string, string> Config
{
get; protected set;
} = new Dictionary<string, string>();
public Dictionary<string, string> MD5Data
public ConcurrentDictionary<string, string> MD5Data
{
get; protected set;
} = new Dictionary<string, string>(); // 路径为尽可能相对路径
} = new ConcurrentDictionary<string, string>(); // 路径为尽可能相对路径
public ConcurrentBag<(DataRowState state, string name)> MD5Update
{
get; set;
Expand Down Expand Up @@ -249,7 +249,7 @@ public void ReadMD5Data()
}
else
{
newMD5Data = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
newMD5Data = JsonSerializer.Deserialize<Dictionary<string, string>>(json) ?? new Dictionary<string, string>();
}
r.Close(); r.Dispose();
}
Expand All @@ -270,19 +270,16 @@ public void ReadMD5Data()
foreach (var item in newMD5Data)
{
var key = item.Key.Replace('/', Path.DirectorySeparatorChar);
if (MD5Data.ContainsKey(key))
MD5Data.AddOrUpdate(key, (k) =>
{
if (MD5Data[key] != item.Value)
{
MD5Data[key] = item.Value;
MD5Update.Add((DataRowState.Modified, key));
}
}
else
{
MD5Data.Add(key, item.Value);
MD5Update.Add((DataRowState.Added, key));
}
return item.Value;
}, (k, v) =>
{
if (v != item.Value)
MD5Update.Add((DataRowState.Modified, key));
return item.Value;
});
}
}

Expand Down Expand Up @@ -314,41 +311,54 @@ public void ScanDir()
continue;
var file = _file.StartsWith('.') ?
Path.Combine(InstallPath, _file) : _file;
if (!File.Exists(file))
if (!File.Exists(file) && MD5Data.TryRemove(_file, out _))
{
MD5Data.Remove(_file);
MD5Update.Add((DataRowState.Deleted, _file));
}
}
ScanDir(InstallPath);
SaveMD5Data();
}

public void ScanDir(string dir)
{
var d = new DirectoryInfo(dir);
foreach (var file in d.GetFiles())
// 层序遍历文件树
Stack<string> stack = new Stack<string>();
List<string> files = new List<string>();
stack.Push(InstallPath);
while (stack.Count > 0)
{
var relFile = Helper.ConvertAbsToRel(InstallPath, file.FullName);
// 用户自己的文件不会被计入更新hash数据中
if (IsUserFile(relFile))
continue;
var hash = Helper.GetFileMd5Hash(file.FullName);
if (MD5Data.Keys.Contains(relFile))
string cur = stack.Pop();
files.AddRange(from f in Directory.GetFiles(cur)
where !IsUserFile(f)
select f);
foreach (var d in Directory.GetDirectories(cur))
stack.Push(d);
}
if (files.Count == 0)
{
MD5Data.Clear();
SaveMD5Data();
return;
}
// 并行计算hash值
var partitioner = Partitioner.Create(0, files.Count);
Parallel.ForEach(partitioner, (range, loopState) =>
{
for (int i = range.Item1; i < range.Item2; i++)
{
if (MD5Data[relFile] != hash)
if (loopState.IsStopped)
break;
var file = files[i];
var relFile = Helper.ConvertAbsToRel(InstallPath, file);
var hash = Helper.GetFileMd5Hash(file);
MD5Data.AddOrUpdate(relFile, (k) =>
{
MD5Data[relFile] = hash;
MD5Update.Add((DataRowState.Modified, relFile));
}
}
else
{
MD5Data.Add(relFile, hash);
MD5Update.Add((DataRowState.Added, relFile));
MD5Update.Add((DataRowState.Added, relFile));
return hash;
}, (k, v) =>
{
if (v != hash)
MD5Update.Add((DataRowState.Modified, relFile));
return hash;
});
}
}
foreach (var d1 in d.GetDirectories()) { ScanDir(d1.FullName); }
});
SaveMD5Data();
}
}
}
27 changes: 17 additions & 10 deletions installer/Model/Tencent_Cos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Formats.Tar;
using COSXML.Common;
using COSXML.Transfer;
using System;

// 禁用对没有调用异步API的异步函数的警告
#pragma warning disable CS1998
Expand Down Expand Up @@ -38,6 +39,8 @@ public Tencent_Cos(string appid, string region, string bucketName, Logger? _log
.SetRegion(Region) // 设置一个默认的存储桶地域
.SetDebugLog(true) // 显示日志
.Build(); // 创建 CosXmlConfig 对象
QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider("***", "***", 1000);
cosXml = new CosXmlServer(config, cosCredentialProvider);
}

public void UpdateSecret(string secretId, string secretKey, long durationSecond = 1000)
Expand Down Expand Up @@ -93,30 +96,34 @@ public async Task<int> DownloadQueueAsync(string basePath, IEnumerable<string> q
{
int thID = Log.StartNew();
Log.LogInfo(thID, "Batch download task started.");
int count = queue.Count();
var array = queue.ToArray();
int count = array.Count();
int finished = 0;
foreach (var item in queue)
var partitionar = Partitioner.Create(0, count);
Parallel.ForEach(partitionar, (range, loopState) =>
{
string local = Path.Combine(basePath, item);
int subID = -1;
ThreadPool.QueueUserWorkItem(_ =>
for (int i = range.Item1; i < range.Item2; i++)
{
if (!loopState.IsStopped)
break;
string local = Path.Combine(basePath, array[i]);
int subID = -1;
try
{
subID = DownloadFileAsync(local, item).Result;
subID = DownloadFileAsync(local, array[i]).Result;
}
catch (Exception ex)
{
downloadFailed.Enqueue(item);
downloadFailed.Enqueue(array[i]);
Exceptions.Push(ex);
}
finally
{
Interlocked.Increment(ref finished);
Log.LogInfo(thID, $"Child process: {subID} finished.");
}
});
}
while (finished < count) ;
}
});
Log.LogInfo(thID, "Batch download task finished.");
return thID;
}
Expand Down
3 changes: 0 additions & 3 deletions installer/Page/InstallPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@
xmlns:viewModels="clr-namespace:installer.ViewModel"
x:Class="installer.Page.InstallPage"
Title="Installer">
<ContentPage.BindingContext>
<viewModels:InstallViewModel/>
</ContentPage.BindingContext>

<VerticalStackLayout
HorizontalOptions="Center"
Expand Down
6 changes: 5 additions & 1 deletion installer/Page/InstallPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
using CommunityToolkit.Maui.Storage;
using installer.ViewModel;

namespace installer.Page;

public partial class InstallPage : ContentPage
{
public InstallPage()
public InstallPage(InstallViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
}
}
3 changes: 0 additions & 3 deletions installer/Page/LaunchPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@
xmlns:viewModels="clr-namespace:installer.ViewModel"
x:Class="installer.Page.LaunchPage"
Title="Launcher">
<ContentPage.BindingContext>
<viewModels:LaunchViewModel/>
</ContentPage.BindingContext>

<VerticalStackLayout>
<Label
Expand Down
5 changes: 4 additions & 1 deletion installer/Page/LaunchPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
using installer.ViewModel;

namespace installer.Page;

public partial class LaunchPage : ContentPage
{
public LaunchPage()
public LaunchPage(LaunchViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
}
}
3 changes: 0 additions & 3 deletions installer/Page/LoginPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@
xmlns:viewModels="clr-namespace:installer.ViewModel"
x:Class="installer.Page.LoginPage"
Title="Login">
<ContentPage.BindingContext>
<viewModels:LoginViewModel/>
</ContentPage.BindingContext>

<VerticalStackLayout
HorizontalOptions="Center"
Expand Down
5 changes: 4 additions & 1 deletion installer/Page/LoginPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
using installer.ViewModel;

namespace installer.Page;

public partial class LoginPage : ContentPage
{
public LoginPage()
public LoginPage(LoginViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
}
}
4 changes: 3 additions & 1 deletion installer/Platforms/Android/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true"></application>
<application android:allowBackup="true" android:icon="@mipmap/appicon" android:supportsRtl="true"></application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-sdk />
</manifest>
2 changes: 2 additions & 0 deletions installer/Platforms/MacCatalyst/Entitlements.plist
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
<!-- When App Sandbox is enabled, this value is required to open outgoing network connections. -->
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
</dict>
</plist>

Loading

0 comments on commit caca192

Please sign in to comment.