down.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/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. console.log(url);
  130. if (!url) {
  131. wx.showToast({
  132. title: '文件链接不存在',
  133. icon: 'none'
  134. });
  135. return;
  136. }
  137. wx.showLoading({
  138. title: '下载中...',
  139. mask: true
  140. });
  141. wx.downloadFile({
  142. url: url,
  143. success: (res) => {
  144. wx.hideLoading();
  145. console.log('进来了++++++++');
  146. if (res.statusCode === 200) {
  147. const tempFilePath = res.tempFilePath;
  148. const fileExt = url.split('.').pop().toLowerCase();
  149. const that = this; // 保存页面上下文
  150. if (['pdf', 'ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx'].includes(fileExt)) {
  151. // 打开文档
  152. wx.openDocument({
  153. filePath: tempFilePath,
  154. showMenu: true,
  155. success() {
  156. console.log('打开文档成功');
  157. that.getaddlishi()
  158. },
  159. fail(err) {
  160. wx.showToast({
  161. title: '打开文档失败',
  162. icon: 'none'
  163. });
  164. console.error('文档打开失败', err);
  165. }
  166. });
  167. } else if (['mp4', 'mov', 'avi'].includes(fileExt)) {
  168. // 视频:先检查权限再保存
  169. wx.getSetting({
  170. success: (res) => {
  171. if (!res.authSetting['scope.writePhotosAlbum']) {
  172. wx.authorize({
  173. scope: 'scope.writePhotosAlbum',
  174. success: () => {
  175. this.saveVideo(tempFilePath);
  176. },
  177. fail: () => {
  178. wx.showModal({
  179. title: '提示',
  180. content: '保存视频需要开启“保存到相册”权限,请前往设置开启。',
  181. showCancel: true,
  182. success(result) {
  183. if (result.confirm) {
  184. wx.openSetting();
  185. }
  186. }
  187. });
  188. }
  189. });
  190. } else {
  191. this.saveVideo(tempFilePath);
  192. }
  193. }
  194. });
  195. } else if (['mp3', 'wav', 'aac'].includes(fileExt)) {
  196. // 音频保存到本地缓存
  197. wx.saveFile({
  198. tempFilePath,
  199. success(result) {
  200. wx.showToast({
  201. title: '音频已保存',
  202. icon: 'success'
  203. });
  204. that.getaddlishi()
  205. console.log('音频保存路径:', result.savedFilePath);
  206. },
  207. fail(err) {
  208. wx.showToast({
  209. title: '保存失败',
  210. icon: 'none'
  211. });
  212. console.error('音频保存失败:', err);
  213. }
  214. });
  215. } else {
  216. wx.showToast({
  217. title: '暂不支持的文件类型',
  218. icon: 'none'
  219. });
  220. }
  221. } else {
  222. wx.showToast({
  223. title: '下载失败',
  224. icon: 'none'
  225. });
  226. }
  227. },
  228. fail: (err) => {
  229. wx.hideLoading();
  230. wx.showToast({
  231. title: '下载失败',
  232. icon: 'none'
  233. });
  234. console.error('下载出错:', err);
  235. }
  236. });
  237. },
  238. saveVideo(filePath) {
  239. const that = this; // 保存页面上下文
  240. wx.saveVideoToPhotosAlbum({
  241. filePath,
  242. success() {
  243. wx.showToast({
  244. title: '视频已保存',
  245. icon: 'success'
  246. });
  247. that.getaddlishi()
  248. },
  249. fail(err) {
  250. wx.showToast({
  251. title: '保存失败',
  252. icon: 'none'
  253. });
  254. console.error('视频保存失败:', err);
  255. }
  256. });
  257. },
  258. // 新增下载历史
  259. async getaddlishi() {
  260. const userInfo = wx.getStorageSync('userInfo');
  261. const userId = userInfo && userInfo._id ? userInfo._id : '';
  262. const schoolId = userInfo && userInfo.school_id ? userInfo.school_id : '';
  263. const fileId = this.data.itemlist._id;
  264. const res = await models.download_history.create({
  265. data: {
  266. user_id: userId, // 用户id
  267. delete: 0, // 逻辑删除
  268. file_manage_id: fileId, // 课件id
  269. },
  270. // envType: pre 体验环境, prod 正式环境
  271. envType: "prod",
  272. });
  273. // 返回创建的数据 id
  274. console.log(res, '++++++++++++++++++++++++++++++');
  275. // { count: 1}
  276. // 先查是否存在
  277. const { data } = await models.microcode.list({
  278. filter: {
  279. where: {
  280. school_id: schoolId,
  281. // user_id: userId,
  282. file_id: fileId
  283. }
  284. },
  285. envType: "prod",
  286. });
  287. console.log(data,'datadatadata');
  288. const datalist = data.records || []
  289. if (datalist.length > 0) {
  290. // 已存在 → 更新 visits + 1
  291. const existItem = datalist[0];
  292. const recordId = String(existItem._id);
  293. console.log(existItem, 'existItem');
  294. await models.microcode.update({
  295. data: {
  296. download: existItem.download + 1 , // 访问量
  297. },
  298. filter: {
  299. where: {
  300. $and: [
  301. {
  302. _id: {
  303. $eq: recordId, // 推荐传入_id数据标识进行操作
  304. },
  305. },
  306. ]
  307. }
  308. },
  309. // envType: pre 体验环境, prod 正式环境
  310. envType: "prod",
  311. });
  312. console.log("更新成功:visits + 1");
  313. } else {
  314. // 不存在 → 创建新记录
  315. const { data: newData } = await models.microcode.create({
  316. data: {
  317. visits: 1,
  318. download: 1,
  319. school_id: schoolId,
  320. // user_id: userId,
  321. file_id: fileId,
  322. },
  323. envType: "prod",
  324. });
  325. console.log("创建成功", newData);
  326. }
  327. },
  328. // 清除定时器
  329. onUnload() {
  330. if (this.data.timer) {
  331. clearInterval(this.data.timer);
  332. this.setData({ timer: null });
  333. }
  334. }
  335. })