11.21提交

This commit is contained in:
zoujiandong
2025-11-21 17:49:39 +08:00
parent 6b37f0899d
commit 91726b87c5
18 changed files with 2483 additions and 119 deletions
+149
View File
@@ -0,0 +1,149 @@
// 下载任务全局状态管理
class DownloadStore {
constructor() {
let tasks = uni.getStorageSync('downloadVideoTasks');
this.tasks = tasks || [] ; // 下载任务列表
this.listeners = []; // 监听器列表
}
// 添加任务
addTask(data) {
const taskIndex = this.tasks.length;
const taskItem = {
id: Date.now() + Math.random(), // 唯一ID
url: '',
status: 'downloading', // downloading, paused, completed, failed
progress: 0,
totalSize:0,
downloadSize:0,
task: null,
filePath: '',
imgpath:'',
author:'',
name:'',
duration:'',
size:'',
createTime: Date.now(),
localPath:''
};
Object.assign(taskItem, data);
this.tasks.push(taskItem);
this.notifyListeners();
this.saveToStorage();
return taskIndex;
}
// 更新任务
updateTask(index, updates) {
if (this.tasks[index]) {
Object.assign(this.tasks[index], updates);
this.notifyListeners();
this.saveToStorage();
}
}
// 删除任务
removeTask(index) {
const taskItem = this.tasks[index];
if (taskItem && taskItem.task && taskItem.status === 'downloading') {
taskItem.task.abort();
}
this.tasks.splice(index, 1);
this.notifyListeners();
this.saveToStorage();
}
// 获取所有任务
getTasks() {
return this.tasks;
}
// 获取任务
getTask(index) {
return this.tasks[index];
}
// 添加监听器
addListener(callback) {
this.listeners.push(callback);
// 返回取消监听的函数
return () => {
const index = this.listeners.indexOf(callback);
if (index > -1) {
this.listeners.splice(index, 1);
}
};
}
// 通知所有监听器
notifyListeners() {
// 创建新数组引用,确保Vue能检测到变化
const tasksCopy = [...this.tasks];
this.listeners.forEach(callback => {
try {
callback(tasksCopy);
} catch (e) {
console.error('DownloadStore listener error:', e);
}
});
}
// 保存到本地存储
saveToStorage() {
// 只保存基本信息,不保存task对象
const tasksToSave = this.tasks.map(item => ({
id: item.id,
url: item.url,
status: item.status,
progress: item.progress,
filePath: item.filePath,
createTime: item.createTime,
imgpath:item.imgpath,
author:item.author,
name:item.name,
duration:item.duration,
size:item.size,
totalSize:item.totalSize,
downloadSize:item.downloadSize,
localPath:item.localPath,
}));
uni.setStorageSync('downloadVideoTasks', tasksToSave);
}
// 从本地存储加载
loadFromStorage() {
const savedTasks = uni.getStorageSync('downloadVideoTasks');
if (savedTasks && Array.isArray(savedTasks)) {
this.tasks = savedTasks.map(item => ({
...item,
task: null // task对象无法序列化,需要重新创建
}));
this.notifyListeners();
}
}
// 恢复下载中的任务
resumeDownloadingTasks(startDownloadCallback) {
this.tasks.forEach((taskItem, index) => {
// 如果任务状态是下载中,但task对象为null,说明需要重新创建下载任务
if (taskItem.status === 'downloading' && !taskItem.task) {
if (typeof startDownloadCallback === 'function') {
startDownloadCallback(index);
}
}
});
}
}
// 创建单例
const downloadStore = new DownloadStore();
// 在应用启动时加载存储的任务
// #ifndef VUE3
if (typeof Vue !== 'undefined') {
Vue.prototype.$downloadStore = downloadStore;
}
// #endif
export default downloadStore;