// subpackagestow/down/down.js import { models, db, _ } from '../../utils/cloudbase.js' Page({ /** * 页面的初始数据 */ data: { fuzhi: '', itemlist: {}, itemtempFileURL: '', countdown: '00:05:00', // 倒计时文本 countdownTime: 300, // 倒计时秒数(5分钟) timer: null, // 定时器句柄 downloadTimestamps: [], // 记录下载时间戳 hasAlarmed: false, // 防止重复报警 }, onLoad(options) { // 获取传递过来的数据 const itemStr = decodeURIComponent(options.item); const item = JSON.parse(itemStr); // 设置到页面数据中 this.setData({ itemlist: item }, () => { wx.cloud.getTempFileURL({ fileList: [ { fileID: this.data.itemlist.url[0] } ], maxAge: 300 // 5分钟,单位秒 }) .then(res => { console.log(res.fileList, 'fileList'); this.setData({ itemtempFileURL: res.fileList[0].tempFileURL }) this.startCountdown(); // 启动倒计时 }) .catch(err => { console.error(err); }); }); const fileIDs = [ 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/fuzhi.png', ]; // 并发下载多个 fileID Promise.all( fileIDs.map(fileID => wx.cloud.downloadFile({ fileID })) ).then(results => { // 每个 result 对应一个下载结果 const tempFilePaths = results.map(r => r.tempFilePath); console.log('全部下载成功:', tempFilePaths); this.setData({ fuzhi: tempFilePaths[0], }); }).catch(err => { console.error('有文件下载失败:', err); }); }, // 五分钟倒计时 startCountdown() { const interval = setInterval(() => { let time = this.data.countdownTime; if (time <= 0) { clearInterval(interval); this.setData({ countdown: '00:00:00', timer: null }); return; } time--; const min = String(Math.floor(time / 60)).padStart(2, '0'); const sec = String(time % 60).padStart(2, '0'); const formatted = `00:${min}:${sec}`; this.setData({ countdown: formatted, countdownTime: time, timer: interval }); }, 1000); }, // 分享到微信 onShareAppMessage() { return { title: this.data.itemlist.name || '文件分享', path: `/subpackagestow/down/down?item=${encodeURIComponent(JSON.stringify(this.data.itemlist))}`, imageUrl: this.data.itemlist.cover, // 可选:自定义分享图 } }, handleShareTap() { wx.showToast({ title: '请点击右上角“···”分享', icon: 'none', duration: 3000 }); this.getaddlishi() }, // 保存链接地址 handleCopyLink() { const link = this.data.itemtempFileURL; if (!link) { wx.showToast({ title: '暂无可复制链接', icon: 'none' }); return; } const that = this; // 保存页面上下文 wx.setClipboardData({ data: link, success() { that.getaddlishi() wx.showToast({ title: '链接已复制', icon: 'success' }); }, fail() { wx.showToast({ title: '复制失败', icon: 'none' }); } }); }, // 下载 handleDownloadFile() { const now = Date.now(); // 当前时间戳 毫秒 let timestamps = this.data.downloadTimestamps || []; // 5分钟 = 5*60*1000 毫秒 const FIVE_MINUTES = 5 * 60 * 1000; // 过滤掉超过5分钟的点击 timestamps = timestamps.filter(ts => now - ts <= FIVE_MINUTES); // 加入当前点击 timestamps.push(now); this.setData({ downloadTimestamps: timestamps }); // 超过10次 && 未报警 → 静默存一次 if (timestamps.length >= 10 && !this.data.hasAlarmed) { this.setData({ hasAlarmed: true }); this.saveAbnormalBehavior(); } const link = this.data.itemtempFileURL; if (!link) { wx.showToast({ title: '下载链接为空', icon: 'none' }); return; } // 复制到剪贴板 wx.setClipboardData({ data: link, success: () => { wx.showModal({ title: '提示', content: '下载链接已复制,请到浏览器粘贴并下载', showCancel: false, // 不显示取消按钮 confirmText: '我知道了', success(res) { if (res.confirm) { console.log('用户点击确定,弹框关闭'); } } }); } }); // const url = this.data.itemtempFileURL; // console.log(url); // if (!url) { // wx.showToast({ // title: '文件链接不存在', // icon: 'none' // }); // return; // } // wx.showLoading({ // title: '下载中...', // mask: true // }); // wx.downloadFile({ // url: url, // success: (res) => { // wx.hideLoading(); // console.log('进来了++++++++'); // if (res.statusCode === 200) { // const tempFilePath = res.tempFilePath; // const fileExt = url.split('.').pop().toLowerCase(); // const that = this; // 保存页面上下文 // if (['pdf', 'ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx'].includes(fileExt)) { // // 打开文档 // wx.openDocument({ // filePath: tempFilePath, // showMenu: true, // success() { // console.log('打开文档成功'); // that.getaddlishi() // }, // fail(err) { // wx.showToast({ // title: '打开文档失败', // icon: 'none' // }); // console.error('文档打开失败', err); // } // }); // } else if (['mp4', 'mov', 'avi'].includes(fileExt)) { // // 视频:先检查权限再保存 // wx.getSetting({ // success: (res) => { // if (!res.authSetting['scope.writePhotosAlbum']) { // wx.authorize({ // scope: 'scope.writePhotosAlbum', // success: () => { // this.saveVideo(tempFilePath); // }, // fail: () => { // wx.showModal({ // title: '提示', // content: '保存视频需要开启“保存到相册”权限,请前往设置开启。', // showCancel: true, // success(result) { // if (result.confirm) { // wx.openSetting(); // } // } // }); // } // }); // } else { // this.saveVideo(tempFilePath); // } // } // }); // } else if (['mp3', 'wav', 'aac'].includes(fileExt)) { // // 音频保存到本地缓存 // wx.saveFile({ // tempFilePath, // success(result) { // wx.showToast({ // title: '音频已保存', // icon: 'success' // }); // that.getaddlishi() // console.log('音频保存路径:', result.savedFilePath); // }, // fail(err) { // wx.showToast({ // title: '保存失败', // icon: 'none' // }); // console.error('音频保存失败:', err); // } // }); // } else { // wx.showToast({ // title: '暂不支持的文件类型', // icon: 'none' // }); // } // } else { // wx.showToast({ // title: '下载失败', // icon: 'none' // }); // } // }, // fail: (err) => { // wx.hideLoading(); // wx.showToast({ // title: '下载失败', // icon: 'none' // }); // console.error('下载出错:', err); // } // }); }, // saveVideo(filePath) { // const that = this; // 保存页面上下文 // wx.saveVideoToPhotosAlbum({ // filePath, // success() { // wx.showToast({ // title: '视频已保存', // icon: 'success' // }); // that.getaddlishi() // }, // fail(err) { // wx.showToast({ // title: '保存失败', // icon: 'none' // }); // console.error('视频保存失败:', err); // } // }); // }, // 新增下载历史 async getaddlishi() { const userInfo = wx.getStorageSync('userInfo'); const userId = userInfo && userInfo._id ? userInfo._id : ''; const schoolId = userInfo && userInfo.school_id ? userInfo.school_id : ''; const fileId = this.data.itemlist._id; const res = await models.download_history.create({ data: { user_id: userId, // 用户id delete: 0, // 逻辑删除 file_manage_id: fileId, // 课件id }, // envType: pre 体验环境, prod 正式环境 envType: "prod", }); // 返回创建的数据 id console.log(res, '++++++++++++++++++++++++++++++'); // { count: 1} // 先查是否存在 const { data } = await models.microcode.list({ filter: { where: { school_id: schoolId, // user_id: userId, file_id: fileId } }, envType: "prod", }); console.log(data,'datadatadata'); const datalist = data.records || [] if (datalist.length > 0) { // 已存在 → 更新 visits + 1 const existItem = datalist[0]; const recordId = String(existItem._id); console.log(existItem, 'existItem'); await models.microcode.update({ data: { download: existItem.download + 1 , // 访问量 }, filter: { where: { $and: [ { _id: { $eq: recordId, // 推荐传入_id数据标识进行操作 }, }, ] } }, // envType: pre 体验环境, prod 正式环境 envType: "prod", }); console.log("更新成功:visits + 1"); } else { // 不存在 → 创建新记录 const { data: newData } = await models.microcode.create({ data: { visits: 1, download: 1, school_id: schoolId, // user_id: userId, file_id: fileId, }, envType: "prod", }); console.log("创建成功", newData); } }, // 清除定时器 onUnload() { if (this.data.timer) { clearInterval(this.data.timer); this.setData({ timer: null }); } }, async saveAbnormalBehavior() { const userInfo = wx.getStorageSync('userInfo'); const userId = userInfo && userInfo._id ? userInfo._id : ''; const schoolId = userInfo && userInfo.school_id ? userInfo.school_id : ''; const fileName = this.data.itemlist.name || ''; try { await models.abnormal_behavior_alarm.create({ data: { school_id: schoolId, reason: '五分钟内点击下载超过10次', type: 0, // 可自行定义数字类型,表示下载异常 file_name: fileName, user_id: userId }, envType: 'prod' }); console.log('异常行为已记录'); } catch (err) { console.error('记录异常行为失败', err); } } })