const uniID = require('uni-id-common'); const db = uniCloud.database(); // 密钥不要硬编码在源码里:请在 uniCloud 控制台为本云函数配置环境变量 // (或使用 uni-config-center 统一管理),否则源码一旦外泄等于存储桶失守。 const QINIU_DOMAIN = process.env.QINIU_DOMAIN || "qnycdn.mymoyu.top"; const QINIU_BUCKET = process.env.QINIU_BUCKET || "dc-qiniu-alipay-env-00jxt5y29hrd-85e"; const QINIU_SECRET = process.env.QINIU_BUCKET_SECRET || ""; const extStorageManager = uniCloud.getExtStorageManager({ provider: "qiniu", domain: QINIU_DOMAIN, bucketName: QINIU_BUCKET, bucketSecret: QINIU_SECRET }); module.exports = { _before: function() { }, async getUploadFileOptions(data = {}) { const { errCode } = await uniID.createInstance({ context: this.getClientInfo() }).checkToken(this.getUniIdToken()); if (errCode) throw new Error('请先登录后再上传文件'); let { cloudPath } = data; console.log(data); let uploadFileOptionsRes = extStorageManager.getUploadFileOptions({ cloudPath: `${cloudPath}`, allowUpdate: false, }); return uploadFileOptionsRes; }, async getTempFileURL(data = {}) { let { src } = data; // 列表页的缩略图对未登录用户也要可见,所以这里不做登录校验, // 但必须限定只为本站存储协议的地址签发,避免被当成任意 URL 的签名代理。 if (typeof src !== 'string' || !/^(qiniu|cloud):\/\//.test(src)) { throw new Error('不支持的文件地址'); } let res = extStorageManager.getTempFileURL({ fileList: [src], // 文件地址列表 }); return res; }, // // 下载文件 // async downloadFile(data = {}) { // let { // fileID, // domain, // } = data; // const extStorageManager = uniCloud.getExtStorageManager({ // provider, // 扩展存储供应商 // domain, // 自定义域名 // }); // let res = extStorageManager.downloadFile({ // fileID // }); // return res; // }, // // 删除文件 async deleteFile(data = {}) { const payload = await uniID.createInstance({ context: this.getClientInfo() }).checkToken(this.getUniIdToken()); if (payload.errCode) throw new Error('请先登录'); const fileList = Array.isArray(data.fileList) ? data.fileList.filter(Boolean) : []; if (!fileList.length) throw new Error('缺少文件地址'); if ((payload.role || []).includes('admin')) { return extStorageManager.deleteFile({ fileList }); } const articleId = data.article_id || data.articleId; if (!articleId) throw new Error('普通用户删除文件必须提供文章 id'); const articleRes = await db.collection('uni-cms-articles').doc(articleId).field({ user_id: true, cmsLst: true, thumbnail: true }).get(); const article = articleRes.data && articleRes.data[0]; if (!article || article.user_id !== payload.uid) throw new Error('无权删除该文章文件'); const refs = JSON.stringify(article); if (fileList.some(file => !refs.includes(file))) throw new Error('文件不是该文章引用资源'); return extStorageManager.deleteFile({ fileList }); } }