down.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. // subpackagestow/down/down.js
  2. import { models, db, _ } from '../../utils/cloudbase.js'
  3. Page({
  4. /**
  5. * 页面的初始数据
  6. */
  7. data: {
  8. fuzhi: '',
  9. itemlist: {},
  10. itemtempFileURL: '',
  11. countdown: '00:05:00', // 倒计时文本
  12. countdownTime: 300, // 倒计时秒数(5分钟)
  13. timer: null // 定时器句柄
  14. },
  15. onLoad(options) {
  16. // 获取传递过来的数据
  17. const itemStr = decodeURIComponent(options.item);
  18. const item = JSON.parse(itemStr);
  19. // 设置到页面数据中
  20. this.setData({
  21. itemlist: item
  22. }, () => {
  23. wx.cloud.getTempFileURL({
  24. fileList: [
  25. {
  26. fileID: this.data.itemlist.url[0]
  27. }
  28. ],
  29. maxAge: 300 // 5分钟,单位秒
  30. })
  31. .then(res => {
  32. console.log(res.fileList, 'fileList');
  33. this.setData({
  34. itemtempFileURL: res.fileList[0].tempFileURL
  35. })
  36. this.startCountdown(); // 启动倒计时
  37. })
  38. .catch(err => {
  39. console.error(err);
  40. });
  41. });
  42. const fileIDs = [
  43. 'cloud://cloud1-6g98iw7i28b01747.636c-cloud1-6g98iw7i28b01747-1367995226/images/icon/fuzhi.png',
  44. ];
  45. // 并发下载多个 fileID
  46. Promise.all(
  47. fileIDs.map(fileID => wx.cloud.downloadFile({ fileID }))
  48. ).then(results => {
  49. // 每个 result 对应一个下载结果
  50. const tempFilePaths = results.map(r => r.tempFilePath);
  51. console.log('全部下载成功:', tempFilePaths);
  52. this.setData({
  53. fuzhi: tempFilePaths[0],
  54. });
  55. }).catch(err => {
  56. console.error('有文件下载失败:', err);
  57. });
  58. },
  59. // 五分钟倒计时
  60. startCountdown() {
  61. const interval = setInterval(() => {
  62. let time = this.data.countdownTime;
  63. if (time <= 0) {
  64. clearInterval(interval);
  65. this.setData({
  66. countdown: '00:00:00',
  67. timer: null
  68. });
  69. return;
  70. }
  71. time--;
  72. const min = String(Math.floor(time / 60)).padStart(2, '0');
  73. const sec = String(time % 60).padStart(2, '0');
  74. const formatted = `00:${min}:${sec}`;
  75. this.setData({
  76. countdown: formatted,
  77. countdownTime: time,
  78. timer: interval
  79. });
  80. }, 1000);
  81. },
  82. // 分享到微信
  83. onShareAppMessage() {
  84. return {
  85. title: this.data.itemlist.name || '文件分享',
  86. path: `/subpackagestow/down/down?item=${encodeURIComponent(JSON.stringify(this.data.itemlist))}`,
  87. imageUrl: this.data.itemlist.cover, // 可选:自定义分享图
  88. }
  89. },
  90. handleShareTap() {
  91. wx.showToast({
  92. title: '请点击右上角“···”分享',
  93. icon: 'none',
  94. duration: 3000
  95. });
  96. this.getaddlishi()
  97. },
  98. // 保存链接地址
  99. handleCopyLink() {
  100. const link = this.data.itemtempFileURL;
  101. if (!link) {
  102. wx.showToast({
  103. title: '暂无可复制链接',
  104. icon: 'none'
  105. });
  106. return;
  107. }
  108. const that = this; // 保存页面上下文
  109. wx.setClipboardData({
  110. data: link,
  111. success() {
  112. that.getaddlishi()
  113. wx.showToast({
  114. title: '链接已复制',
  115. icon: 'success'
  116. });
  117. },
  118. fail() {
  119. wx.showToast({
  120. title: '复制失败',
  121. icon: 'none'
  122. });
  123. }
  124. });
  125. },
  126. // 下载
  127. handleDownloadFile() {
  128. const url = this.data.itemtempFileURL;
  129. if (!url) {
  130. wx.showToast({
  131. title: '文件链接不存在',
  132. icon: 'none'
  133. });
  134. return;
  135. }
  136. wx.showLoading({
  137. title: '下载中...',
  138. mask: true
  139. });
  140. wx.downloadFile({
  141. url: url,
  142. success: (res) => {
  143. wx.hideLoading();
  144. if (res.statusCode === 200) {
  145. const tempFilePath = res.tempFilePath;
  146. const fileExt = url.split('.').pop().toLowerCase();
  147. const that = this; // 保存页面上下文
  148. if (['pdf', 'ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx'].includes(fileExt)) {
  149. // 打开文档
  150. wx.openDocument({
  151. filePath: tempFilePath,
  152. showMenu: true,
  153. success() {
  154. console.log('打开文档成功');
  155. that.getaddlishi()
  156. },
  157. fail(err) {
  158. wx.showToast({
  159. title: '打开文档失败',
  160. icon: 'none'
  161. });
  162. console.error('文档打开失败', err);
  163. }
  164. });
  165. } else if (['mp4', 'mov', 'avi'].includes(fileExt)) {
  166. // 视频:先检查权限再保存
  167. wx.getSetting({
  168. success: (res) => {
  169. if (!res.authSetting['scope.writePhotosAlbum']) {
  170. wx.authorize({
  171. scope: 'scope.writePhotosAlbum',
  172. success: () => {
  173. this.saveVideo(tempFilePath);
  174. },
  175. fail: () => {
  176. wx.showModal({
  177. title: '提示',
  178. content: '保存视频需要开启“保存到相册”权限,请前往设置开启。',
  179. showCancel: true,
  180. success(result) {
  181. if (result.confirm) {
  182. wx.openSetting();
  183. }
  184. }
  185. });
  186. }
  187. });
  188. } else {
  189. this.saveVideo(tempFilePath);
  190. }
  191. }
  192. });
  193. } else if (['mp3', 'wav', 'aac'].includes(fileExt)) {
  194. // 音频保存到本地缓存
  195. wx.saveFile({
  196. tempFilePath,
  197. success(result) {
  198. wx.showToast({
  199. title: '音频已保存',
  200. icon: 'success'
  201. });
  202. that.getaddlishi()
  203. console.log('音频保存路径:', result.savedFilePath);
  204. },
  205. fail(err) {
  206. wx.showToast({
  207. title: '保存失败',
  208. icon: 'none'
  209. });
  210. console.error('音频保存失败:', err);
  211. }
  212. });
  213. } else {
  214. wx.showToast({
  215. title: '暂不支持的文件类型',
  216. icon: 'none'
  217. });
  218. }
  219. } else {
  220. wx.showToast({
  221. title: '下载失败',
  222. icon: 'none'
  223. });
  224. }
  225. },
  226. fail: (err) => {
  227. wx.hideLoading();
  228. wx.showToast({
  229. title: '下载失败',
  230. icon: 'none'
  231. });
  232. console.error('下载出错:', err);
  233. }
  234. });
  235. },
  236. saveVideo(filePath) {
  237. const that = this; // 保存页面上下文
  238. wx.saveVideoToPhotosAlbum({
  239. filePath,
  240. success() {
  241. wx.showToast({
  242. title: '视频已保存',
  243. icon: 'success'
  244. });
  245. that.getaddlishi()
  246. },
  247. fail(err) {
  248. wx.showToast({
  249. title: '保存失败',
  250. icon: 'none'
  251. });
  252. console.error('视频保存失败:', err);
  253. }
  254. });
  255. },
  256. // 新增下载历史
  257. async getaddlishi() {
  258. const userInfo = wx.getStorageSync('userInfo');
  259. const userId = userInfo && userInfo._id ? userInfo._id : '';
  260. const schoolId = userInfo && userInfo.school_id ? userInfo.school_id : '';
  261. const fileId = this.data.itemlist._id;
  262. // 先查是否存在
  263. const { data } = await models.microcode.list({
  264. filter: {
  265. where: {
  266. school_id: schoolId,
  267. user_id: userId,
  268. file_id: fileId
  269. }
  270. },
  271. envType: "prod",
  272. });
  273. console.log(data,'datadatadata');
  274. const datalist = data.records || []
  275. if (datalist.length > 0) {
  276. // 已存在 → 更新 visits + 1
  277. const existItem = datalist[0];
  278. const recordId = String(existItem._id);
  279. console.log(existItem, 'existItem');
  280. await models.microcode.update({
  281. data: {
  282. download: existItem.download + 1 , // 访问量
  283. },
  284. filter: {
  285. where: {
  286. $and: [
  287. {
  288. _id: {
  289. $eq: recordId, // 推荐传入_id数据标识进行操作
  290. },
  291. },
  292. ]
  293. }
  294. },
  295. // envType: pre 体验环境, prod 正式环境
  296. envType: "prod",
  297. });
  298. console.log("更新成功:visits + 1");
  299. } else {
  300. // 不存在 → 创建新记录
  301. const { data: newData } = await models.microcode.create({
  302. data: {
  303. visits: 1,
  304. download: 1,
  305. school_id: schoolId,
  306. user_id: userId,
  307. file_id: fileId,
  308. },
  309. envType: "prod",
  310. });
  311. console.log("创建成功", newData);
  312. }
  313. },
  314. // 清除定时器
  315. onUnload() {
  316. if (this.data.timer) {
  317. clearInterval(this.data.timer);
  318. this.setData({ timer: null });
  319. }
  320. }
  321. })