1. 下载取消更新视图

2. 下载取消删除文件
3. 下载取消删除数据库记录
dev2.0
陈伟 2025-04-21 16:35:40 +08:00
parent f972f94c42
commit 4d0f69f3ce
6 changed files with 57 additions and 63 deletions

View File

@ -24,7 +24,9 @@ namespace Hopetry.Provider
// 配置AOP // 配置AOP
db.Aop.OnLogExecuting = (sql, pars) => db.Aop.OnLogExecuting = (sql, pars) =>
{ {
Console.WriteLine(sql); // 输出SQL //Console.WriteLine(sql); // 输出SQL
Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer, sql, pars));
}; };
}); });

View File

@ -1,8 +1,6 @@
using System.Configuration; using System.IO;
using System.Windows; using System.Windows;
using System.Windows.Forms.VisualStyles;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Threading;
using HeBianGu.Base.WpfBase; using HeBianGu.Base.WpfBase;
using Hopetry.Models; using Hopetry.Models;
using Hopetry.Provider; using Hopetry.Provider;
@ -10,23 +8,15 @@ using SqlSugar;
namespace Hopetry.Services; namespace Hopetry.Services;
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using Minio;
[SugarTable(TableName = "download_task")] [SugarTable(TableName = "download_task")]
public class MinioDownloadTask : INotifyPropertyChanged public class MinioDownloadTask : NotifyPropertyChangedBase
{ {
public MinioService Minio; public MinioService Minio;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public CancellationTokenSource _cts; public CancellationTokenSource StopDownTs;
/// <summary> /// <summary>
/// ///
@ -78,7 +68,7 @@ public class MinioDownloadTask : INotifyPropertyChanged
set set
{ {
_downloadInfo = value; _downloadInfo = value;
OnPropertyChanged(nameof(DownloadInfo)); RaisePropertyChanged();
} }
} }
@ -91,7 +81,7 @@ public class MinioDownloadTask : INotifyPropertyChanged
set set
{ {
_speed = value; _speed = value;
OnPropertyChanged(nameof(Speed)); RaisePropertyChanged();
} }
} }
@ -112,7 +102,7 @@ public class MinioDownloadTask : INotifyPropertyChanged
set set
{ {
_progress = value; _progress = value;
OnPropertyChanged(nameof(Progress)); RaisePropertyChanged();
} }
} }
@ -140,12 +130,7 @@ public class MinioDownloadTask : INotifyPropertyChanged
PauseCommand = new CustomCommand(OnPause); PauseCommand = new CustomCommand(OnPause);
CancelCommand = new CustomCommand(OnCancel); CancelCommand = new CustomCommand(OnCancel);
} }
public void RefreshProgress()
{
OnPropertyChanged(nameof(Progress));
OnPropertyChanged("Progress");
}
/// <summary> /// <summary>
/// 下载 /// 下载
@ -153,8 +138,7 @@ public class MinioDownloadTask : INotifyPropertyChanged
/// <param name="savePath"></param> /// <param name="savePath"></param>
public async Task StartDownload() public async Task StartDownload()
{ {
_cts = new CancellationTokenSource(); StopDownTs = new CancellationTokenSource();
try try
{ {
var stat = await Minio.GetObjectMetadata(Bucket, ObjectKey); var stat = await Minio.GetObjectMetadata(Bucket, ObjectKey);
@ -180,7 +164,7 @@ public class MinioDownloadTask : INotifyPropertyChanged
var humanFileSize = (TotalSize > 1048576 var humanFileSize = (TotalSize > 1048576
? $"{TotalSize / 1048576}MB" ? $"{TotalSize / 1048576}MB"
: $"{TotalSize / 1024}KB"); : $"{TotalSize / 1024}KB");
await Minio.DownLoadObjectWithCallBack(TaskId,Bucket, ObjectKey, FilePath, FileETag, await Minio.DownLoadObjectWithCallBack(this,Bucket, ObjectKey, FilePath, FileETag,
(downloaded, total, speed) => (downloaded, total, speed) =>
{ {
var progress = (double)downloaded / total * 100; var progress = (double)downloaded / total * 100;
@ -217,18 +201,10 @@ public class MinioDownloadTask : INotifyPropertyChanged
Console.WriteLine($"文件{ObjectKey}下载完成"); Console.WriteLine($"文件{ObjectKey}下载完成");
} }
catch (OperationCanceledException)
{
Status = "已取消";
}
catch (Exception ex)
{
Status = $"错误:{ex.Message}";
}
finally finally
{ {
_pauseEvent.Dispose(); _pauseEvent.Dispose();
OnPropertyChanged(nameof(Status)); RaisePropertyChanged(nameof(Status));
} }
} }
@ -245,20 +221,13 @@ public class MinioDownloadTask : INotifyPropertyChanged
Status = "下载中"; Status = "下载中";
} }
OnPropertyChanged(nameof(Status)); RaisePropertyChanged(nameof(Status));
} }
private void OnCancel() private void OnCancel()
{ {
_cts?.Cancel(); StopDownTs?.Cancel();
Status = "已取消"; Status = "已取消";
OnPropertyChanged(nameof(Status)); RaisePropertyChanged();
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
} }
} }

View File

@ -409,9 +409,11 @@ namespace Hopetry.Services
#endregion #endregion
} }
public async Task DownLoadObjectWithCallBack(int taskId, string bucketName, string objectKey, string filePath, public async Task DownLoadObjectWithCallBack(MinioDownloadTask downTask, string bucketName, string objectKey,
string fileETag, Action<long, long, double> action, long offset = 0, CancellationToken token = default) string filePath,
string fileETag, Action<long, long, double> action, long offset = 0)
{ {
var token = downTask.StopDownTs.Token;
long totalBytes = 0; long totalBytes = 0;
var index = objectKey.LastIndexOf("/", StringComparison.Ordinal); var index = objectKey.LastIndexOf("/", StringComparison.Ordinal);
if (index > 0) if (index > 0)
@ -426,7 +428,7 @@ namespace Hopetry.Services
var args = new StatObjectArgs() var args = new StatObjectArgs()
.WithBucket(string.IsNullOrEmpty(bucketName) ? _bucketName : bucketName) .WithBucket(string.IsNullOrEmpty(bucketName) ? _bucketName : bucketName)
.WithObject(objectKey); .WithObject(objectKey);
var stat = await _minioClient.StatObjectAsync(args); var stat = await _minioClient.StatObjectAsync(args, token);
totalBytes = stat.Size; totalBytes = stat.Size;
var localPath = Path.Combine(filePath, objectKey.Replace('/', Path.DirectorySeparatorChar)); var localPath = Path.Combine(filePath, objectKey.Replace('/', Path.DirectorySeparatorChar));
GetObjectArgs getObjectArgs = new GetObjectArgs() GetObjectArgs getObjectArgs = new GetObjectArgs()
@ -460,11 +462,12 @@ namespace Hopetry.Services
var client = SqlSugarConfig.GetSqlSugarScope(); var client = SqlSugarConfig.GetSqlSugarScope();
var temp = new MinioDownloadTask var temp = new MinioDownloadTask
{ {
TaskId = taskId, TaskId = downTask.TaskId,
Downloaded = bytesRead Downloaded = bytesRead
}; };
client.Updateable(temp).IgnoreNullColumns().ExecuteCommand(); client.Updateable(temp).IgnoreNullColumns().ExecuteCommand();
client.Close(); client.Close();
fileStream.Close();
} }
// 检查取消令牌 // 检查取消令牌

View File

@ -64,7 +64,7 @@
Style="{DynamicResource {x:Static h:TextBlockKeys.Icon}}" Style="{DynamicResource {x:Static h:TextBlockKeys.Icon}}"
Text="&#xe741;" /> Text="&#xe741;" />
<TextBlock Grid.RowSpan="2" <TextBlock Grid.Row="0" Grid.RowSpan="2"
Grid.Column="1" Grid.Column="1"
HorizontalAlignment="Left" HorizontalAlignment="Left"
Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}" Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}"
@ -75,7 +75,7 @@
HorizontalAlignment="Right" HorizontalAlignment="Right"
Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}" Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}"
Text="{Binding DownloadInfo}" /> Text="{Binding DownloadInfo}" />
<!--进度条底-->
<TextBlock Grid.Row="0" <TextBlock Grid.Row="0"
Grid.Column="3" Grid.Column="3"
Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}" Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}"
@ -107,7 +107,10 @@
Command="{Binding RelativeSource={RelativeSource AncestorType=ListBox}, Command="{Binding RelativeSource={RelativeSource AncestorType=ListBox},
Path= DataContext.DownViewModel.StartOrPauseDown }" Path= DataContext.DownViewModel.StartOrPauseDown }"
CommandParameter="{Binding}" /> <!--暂停--> CommandParameter="{Binding}" /> <!--暂停-->
<Button h:Cattach.Icon="&#xe8a0;" h:Cattach.IconSize="13" /> <!--取消--> <Button h:Cattach.Icon="&#xe8a0;" h:Cattach.IconSize="13"
Command="{Binding RelativeSource={RelativeSource AncestorType=ListBox},
Path= DataContext.DownViewModel.CancelDownload }"
CommandParameter="{Binding}" /> <!--取消-->
<Button h:Cattach.Icon="&#xe87a;" h:Cattach.IconSize="15" <Button h:Cattach.Icon="&#xe87a;" h:Cattach.IconSize="15"
Command="{Binding RelativeSource={RelativeSource AncestorType=ListBox}, Command="{Binding RelativeSource={RelativeSource AncestorType=ListBox},
Path= DataContext.DownViewModel.OpenDownItemFolder }" Path= DataContext.DownViewModel.OpenDownItemFolder }"

View File

@ -634,9 +634,8 @@ namespace HeBianGu.App.Disk
var objectKey = temp.FullName.Replace(temp.BucketName + "/", ""); var objectKey = temp.FullName.Replace(temp.BucketName + "/", "");
ViewModelLocator.DownViewModel.AddTask(temp.BucketName, objectKey, temp.Size, downDir); ViewModelLocator.DownViewModel.AddTask(temp.BucketName, objectKey, temp.Size, downDir);
MessageProxy.Snacker.Show($"{temp.Name} 加入下载队列");
} }
MessageProxy.Snacker.Show("已加入下载队列");
if (item is MinIODirectoryModel dir) if (item is MinIODirectoryModel dir)
{ {
Console.WriteLine("建设中..."); Console.WriteLine("建设中...");

View File

@ -1,12 +1,9 @@
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.Windows; using System.Windows;
using System.Windows.Data;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Shapes;
using System.Windows.Threading;
using HeBianGu.Base.WpfBase; using HeBianGu.Base.WpfBase;
using HeBianGu.Service.Mvc; using HeBianGu.Service.Mvc;
using Hopetry.Models; using Hopetry.Models;
@ -23,6 +20,7 @@ public class DownViewModel : MvcViewModelBase
private readonly MinioService _minioService; private readonly MinioService _minioService;
public RelayCommand<MinioDownloadTask> OpenDownItemFolder { get; set; } public RelayCommand<MinioDownloadTask> OpenDownItemFolder { get; set; }
public RelayCommand<MinioDownloadTask> CancelDownload { get; set; }
private readonly ConcurrentQueue<MinioDownloadTask> _taskQueue = new(); private readonly ConcurrentQueue<MinioDownloadTask> _taskQueue = new();
private SemaphoreSlim _semaphore; private SemaphoreSlim _semaphore;
@ -172,6 +170,8 @@ public class DownViewModel : MvcViewModelBase
Console.WriteLine("初始化DownViewModel"); Console.WriteLine("初始化DownViewModel");
using var client = SqlSugarConfig.GetSqlSugarScope(); using var client = SqlSugarConfig.GetSqlSugarScope();
OpenDownItemFolder = new RelayCommand<MinioDownloadTask>(DoOpenDownItemFolder); OpenDownItemFolder = new RelayCommand<MinioDownloadTask>(DoOpenDownItemFolder);
// 取消下载
CancelDownload = new RelayCommand<MinioDownloadTask>(DoCancelDownload);
StartOrPauseDown = new RelayCommand<MinioDownloadTask>(DoStartOrPauseDown); StartOrPauseDown = new RelayCommand<MinioDownloadTask>(DoStartOrPauseDown);
LoadFinishedTasks(); LoadFinishedTasks();
LoadRunningTasks(); LoadRunningTasks();
@ -284,13 +284,19 @@ public class DownViewModel : MvcViewModelBase
FinishedTasks.Add(task); FinishedTasks.Add(task);
RefreshHeader(); RefreshHeader();
}); });
}catch (Exception ex) }
catch (Exception ex)
{ {
Console.WriteLine($"下载失败{ex.Message}"); Console.WriteLine($"下载失败或取消{ex.Message}");
} }
finally finally
{ {
if (task.Status.Equals("删除中"))
{
Console.WriteLine($"删除文件:{task.FileName}");
File.Delete(Path.Combine(task.FilePath, task.FileName));
Console.WriteLine($"{task.FileName}删除成功");
}
} }
} }
@ -318,10 +324,22 @@ public class DownViewModel : MvcViewModelBase
Process.Start("explorer.exe", $"/select,\"{file}\""); Process.Start("explorer.exe", $"/select,\"{file}\"");
} }
public void DoCancelDownItem(MinioDownloadTask item) public void DoCancelDownload(MinioDownloadTask item)
{ {
Console.WriteLine("取消下载"); Console.WriteLine("取消下载");
// todo 实现取消下载 item.Status = "删除中";
// 取消操作
if (item.StopDownTs != null)
{
item.StopDownTs.Cancel();
}
using var client = SqlSugarConfig.GetSqlSugarScope();
client.Deleteable<MinioDownloadTask>().Where(x => x.TaskId == item.TaskId).ExecuteCommand();
RunningTasks.Remove(item);
RefreshHeader();
// 删除下载文件
//File.Delete(Path.Combine(item.FilePath, item.FileName));
MessageProxy.Snacker.Show($"<{item.FileName}>取消下载");
} }
public void DoPauseDownItem(MinioDownloadTask item) public void DoPauseDownItem(MinioDownloadTask item)