apply Network.ts

This commit is contained in:
Timi
2025-12-17 16:56:33 +08:00
parent 369cfe2bf2
commit 62186abdb8
13 changed files with 584 additions and 696 deletions

View File

@ -6,6 +6,9 @@ import Time from "../../../utils/Time";
import Toolkit from "../../../utils/Toolkit";
import { Location, MediaItemType } from "../../../types/UI";
import { MediaAttachExt } from "../../../types/Attachment";
import { MomentApi } from "../../../api/MomentApi";
import { JournalApi } from "../../../api/JournalApi";
import { Network } from "../../../utils/Network";
type Item = {
id: number;
@ -123,34 +126,29 @@ Page({
}
});
},
fetch() {
wx.request({
url: `${config.url}/journal/moment/list`,
method: "POST",
header: {
Key: wx.getStorageSync("key")
},
success: async (resp: any) => {
const list = resp.data.data;
if (!list || list.length === 0) {
return;
}
this.setData({
list: list.map((item: any) => {
const ext = JSON.parse(item.ext) as MediaAttachExt;
const thumbURL = `${config.url}/attachment/read/${item.mongoId}`;
const sourceURL = `${config.url}/attachment/read/${ext.sourceMongoId}`;
return {
id: item.id,
type: ext.isImage ? MediaItemType.IMAGE : MediaItemType.VIDEO,
thumbURL,
sourceURL,
checked: false
} as Item;
})
});
async fetch() {
try {
const list = await MomentApi.getList();
if (!list || list.length === 0) {
return;
}
});
this.setData({
list: list.map((item: any) => {
const ext = JSON.parse(item.ext) as MediaAttachExt;
const thumbURL = `${config.url}/attachment/read/${item.mongoId}`;
const sourceURL = `${config.url}/attachment/read/${ext.sourceMongoId}`;
return {
id: item.id,
type: ext.isImage ? MediaItemType.IMAGE : MediaItemType.VIDEO,
thumbURL,
sourceURL,
checked: false
} as Item;
})
});
} catch (error) {
console.error("加载 moment 列表失败:", error);
}
},
updateHasChecked() {
this.setData({ hasChecked: this.data.list.some(item => item.checked) });
@ -226,155 +224,65 @@ Page({
} as MD5Result);
}));
// 查重
const filterMD5Result: string[] = await new Promise((resolve, reject) => {
wx.request({
url: `${config.url}/journal/moment/filter`,
method: "POST",
header: {
Key: wx.getStorageSync("key")
},
data: md5Results.map(item => item.md5),
success: async (resp: any) => {
resolve(resp.data.data);
},
fail: reject
});
});
const filterMD5Result: string[] = await MomentApi.filterByMD5(
md5Results.map(item => item.md5)
);
// 过滤文件
const filterPath = md5Results.filter(item => filterMD5Result.indexOf(item.md5) !== -1)
.map(item => item.path);
files = files.filter(file => filterPath.indexOf(file.tempFilePath) !== -1);
if (files.length === 0) {
wx.hideLoading();
that.setData({ isUploading: false });
return;
}
wx.showLoading({
title: "正在上传..",
mask: true
})
// 计算上传大小
const sizePromises = files.map(file => {
return new Promise<number>((sizeResolve, sizeReject) => {
wx.getFileSystemManager().getFileInfo({
filePath: file.tempFilePath,
success: (res) => sizeResolve(res.size),
fail: (err) => sizeReject(err)
});
});
});
Promise.all(sizePromises).then(fileSizes => {
const totalSize = fileSizes.reduce((acc, size) => acc + size, 0);
const uploadTasks: WechatMiniprogram.UploadTask[] = [];
let uploadedSize = 0;
let lastUploadedSize = 0;
// 使用 Network.uploadFiles 上传文件
try {
const tempFileIds = await Network.uploadFiles({
mediaList: files.map(file => ({
path: file.tempFilePath,
size: file.size
})),
onProgress: (progress) => {
that.setData({
uploaded: IOSize.formatWithoutUnit(progress.uploaded, 2, Unit.MB),
uploadTotal: IOSize.format(progress.total, 2, Unit.MB),
uploadSpeed: `${IOSize.format(progress.speed)} / s`,
uploadProgress: progress.percent
});
},
showLoading: true
});
// 上传完成转附件
const list = await MomentApi.create(tempFileIds);
wx.showToast({ title: "上传成功", icon: "success" });
const added = list.map((item: any) => {
const ext = JSON.parse(item.ext) as MediaAttachExt;
const thumbURL = `${config.url}/attachment/read/${item.mongoId}`;
const sourceURL = `${config.url}/attachment/read/${ext.sourceMongoId}`;
return {
id: item.id,
type: ext.isImage ? MediaItemType.IMAGE : MediaItemType.VIDEO,
thumbURL,
sourceURL,
checked: false
} as Item;
});
// 前插列表
that.data.list.unshift(...added);
that.setData({
uploadTotal: IOSize.format(totalSize, 2, Unit.MB)
list: that.data.list,
isUploading: false,
uploaded: "0",
uploadTotal: "0 MB",
uploadProgress: 0
});
// 计算上传速度
const speedUpdateInterval = setInterval(() => {
const chunkSize = uploadedSize - lastUploadedSize;
that.setData({
uploadSpeed: `${IOSize.format(chunkSize)} / s`
});
lastUploadedSize = uploadedSize;
}, 1000);
// 上传文件
const uploadPromises = files.map(file => {
return new Promise<string>((uploadResolve, uploadReject) => {
const task = wx.uploadFile({
url: `${config.url}/temp/file/upload`,
filePath: file.tempFilePath,
name: "file",
success: (resp) => {
const result = JSON.parse(resp.data);
if (result && result.code === 20000) {
// 更新进度
const progress = totalSize > 0 ? uploadedSize / totalSize : 1;
that.setData({
uploadProgress: Math.round(progress * 10000) / 100
});
uploadResolve(result.data[0].id);
} else {
uploadReject(new Error(`文件上传失败: ${result?.message || "未知错误"}`));
}
},
fail: (err) => uploadReject(new Error(`文件上传失败: ${err.errMsg}`))
});
// 监听上传进度事件
let prevProgress = 0;
task.onProgressUpdate((res) => {
const fileUploaded = (res.totalBytesExpectedToSend * res.progress) / 100;
const delta = fileUploaded - prevProgress;
uploadedSize += delta;
// 保存当前进度
prevProgress = fileUploaded;
// 更新进度条
that.setData({
uploaded: IOSize.formatWithoutUnit(uploadedSize, 2, Unit.MB),
uploadProgress: Math.round((uploadedSize / totalSize) * 10000) / 100
});
});
uploadTasks.push(task);
});
});
Promise.all(uploadPromises).then((tempFileIds) => {
wx.showLoading({
title: "正在保存..",
mask: true
})
// 清除定时器
clearInterval(speedUpdateInterval);
uploadTasks.forEach(task => task.offProgressUpdate());
that.setData({
uploadProgress: 100,
uploadSpeed: "0 MB / s"
});
// 上传完成转附件
wx.request({
url: `${config.url}/journal/moment/create`,
method: "POST",
header: {
Key: wx.getStorageSync("key")
},
data: tempFileIds,
success: async (resp: any) => {
wx.showToast({ title: "上传成功", icon: "success" });
const list = resp.data.data;
const added = list.map((item: any) => {
const ext = JSON.parse(item.ext) as MediaAttachExt;
const thumbURL = `${config.url}/attachment/read/${item.mongoId}`;
const sourceURL = `${config.url}/attachment/read/${ext.sourceMongoId}`;
return {
id: item.id,
type: ext.isImage ? MediaItemType.IMAGE : MediaItemType.VIDEO,
thumbURL,
sourceURL,
checked: false
} as Item;
});
// 前插列表
that.data.list.unshift(...added);
that.setData({
list: that.data.list,
isUploading: false,
uploaded: "0",
uploadTotal: "0 MB",
uploadProgress: 0
});
that.updateHasChecked();
wx.hideLoading();
},
fail: handleFail
});
}).catch((e: Error) => {
// 取消所有上传任务
uploadTasks.forEach(task => task.abort());
that.updateHasChecked();
handleFail(e);
});
}).catch(handleFail);
that.updateHasChecked();
} catch (error) {
handleFail(error);
}
}
})
},
@ -450,27 +358,14 @@ Page({
})
const openId = await new Promise<string>((resolve, reject) => {
wx.login({
success: (res) => {
success: async (res) => {
if (res.code) {
wx.request({
url: `${config.url}/journal/openid`,
method: "POST",
header: {
Key: wx.getStorageSync("key")
},
data: {
code: res.code
},
success: (resp) => {
const data = resp.data as any;
if (data.code === 20000) {
resolve(data.data);
} else {
reject(new Error("获取 openId 失败"));
}
},
fail: () => reject(new Error("获取 openId 请求失败"))
});
try {
const openId = await JournalApi.getOpenId(res.code);
resolve(openId);
} catch (error) {
reject(new Error("获取 openId 失败"));
}
} else {
reject(new Error("获取登录凭证失败"));
}
@ -491,36 +386,23 @@ Page({
if (this.data.selectedJournalId) {
archiveData.id = this.data.selectedJournalId;
}
wx.request({
url: `${config.url}/journal/moment/archive`,
method: "POST",
header: {
Key: wx.getStorageSync("key")
},
data: archiveData,
success: async (resp: any) => {
if (resp.data && resp.data.code === 20000) {
Events.emit("JOURNAL_REFRESH");
wx.showToast({ title: "归档成功", icon: "success" });
this.setData({
idea: "",
list: [],
hasChecked: false,
isArchiving: false,
selectedJournalId: undefined,
isVisibleArchivePopup: false
});
await Toolkit.sleep(1000);
this.fetch();
} else {
wx.showToast({ title: "归档失败", icon: "error" });
this.setData({
isArchiving: false
});
}
},
fail: handleFail
});
try {
await MomentApi.archive(archiveData);
Events.emit("JOURNAL_REFRESH");
wx.showToast({ title: "归档成功", icon: "success" });
this.setData({
idea: "",
list: [],
hasChecked: false,
isArchiving: false,
selectedJournalId: undefined,
isVisibleArchivePopup: false
});
await Toolkit.sleep(1000);
this.fetch();
} catch (error) {
handleFail();
}
},
allChecked() {
this.data.list.forEach(item => item.checked = true);
@ -556,27 +438,21 @@ Page({
confirmText: "删除已选",
confirmColor: "#E64340",
cancelText: "取消",
success: res => {
success: async (res) => {
if (res.confirm) {
const selected = this.data.list.filter(item => item.checked);
wx.request({
url: `${config.url}/journal/moment/delete`,
method: "POST",
header: {
Key: wx.getStorageSync("key")
},
data: selected.map(item => item.id),
success: async (resp: any) => {
if (resp.data && resp.data.code === 20000) {
wx.showToast({ title: "删除成功", icon: "success" });
const list = this.data.list.filter(item => !item.checked);
this.setData({
list
});
this.updateHasChecked();
}
},
});
try {
await MomentApi.delete(selected.map(item => item.id));
wx.showToast({ title: "删除成功", icon: "success" });
const list = this.data.list.filter(item => !item.checked);
this.setData({
list
});
this.updateHasChecked();
} catch (error) {
console.error("删除 moment 失败:", error);
wx.showToast({ title: "删除失败", icon: "error" });
}
}
}
})