doTask.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. // pages/doTask/doTask.js
  2. import VODUpload from '../../utils/aliyun-upload-sdk-1.0.1.min'
  3. const app = getApp()
  4. const util = require("../../utils/util")
  5. const urlDef = require("../../utils/urls")
  6. const recordManager = wx.getRecorderManager() //录音对象
  7. const audioContext = wx.createInnerAudioContext() //音频播放对象
  8. var uploader = null //阿里云视频上传对象
  9. const urls = urlDef.urls;
  10. Page({
  11. /**
  12. * 页面的初始数据
  13. */
  14. data: {
  15. uploadIng: false,
  16. homeworkId: null,
  17. talkFlag: false,
  18. closeName: '开始录音',
  19. videoList: [],
  20. videoFlag: 0,
  21. imgList: [],
  22. audioList: [],
  23. audioPause: false,
  24. content: '',
  25. delItems: [],
  26. contents: null,
  27. },
  28. renderTime: function (date) {
  29. var dateee = new Date(date).toJSON();
  30. return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
  31. },
  32. getRecord: function () {
  33. const that = this
  34. if (that.data.audioList.length >= 6) {
  35. wx.showToast({
  36. title: '最多上传6段录音',
  37. icon: 'none'
  38. })
  39. return
  40. }
  41. if (that.data.talkFlag) {
  42. recordManager.stop()
  43. recordManager.onStop((res) => { //监听录音停止的事件
  44. console.log("监听录音停止事件", res)
  45. if (res.duration < 1000) {
  46. wx.showToast({
  47. title: '录音时间太短',
  48. icon: 'none'
  49. })
  50. return;
  51. } else {
  52. console.log(res)
  53. var tempFilePath = res.tempFilePath; // 文件临时路径
  54. console.log("文件临时路径", tempFilePath)
  55. wx.uploadFile({
  56. filePath: tempFilePath,
  57. name: 'name',
  58. url: urls.file_upload,
  59. header: util.getHeaders(),
  60. success(res) {
  61. wx.showToast({
  62. title: '上传成功',
  63. })
  64. const rs = JSON.parse(JSON.parse(JSON.stringify(res.data)))
  65. const list = [{
  66. url: rs.data[0].url
  67. }]
  68. that.setData({
  69. audioList: that.data.audioList.concat(list)
  70. })
  71. },
  72. fail(res) {
  73. wx.showToast({
  74. title: '上传失败',
  75. icon: 'none'
  76. })
  77. },
  78. complete(res) {
  79. wx.hideLoading({
  80. success: (res) => {},
  81. })
  82. }
  83. })
  84. }
  85. });
  86. that.setData({
  87. talkFlag: false,
  88. closeName: '开始录音'
  89. })
  90. } else {
  91. wx.getSetting({
  92. success(res) {
  93. if (!res.authSetting['scope.record']) {
  94. wx.authorize({
  95. scope: 'scope.record',
  96. success() {
  97. // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
  98. const options = {}
  99. recordManager.start(options)
  100. },
  101. fail() {
  102. wx.openSetting({
  103. withSubscriptions: true,
  104. })
  105. }
  106. })
  107. } else {
  108. that.setData({
  109. talkFlag: true,
  110. closeName: '正在录音,再次点击结束录音'
  111. })
  112. const options = {}
  113. recordManager.start(options)
  114. }
  115. }
  116. })
  117. }
  118. },
  119. showAudio: function (e) {
  120. const index = e.currentTarget.dataset.index
  121. if (this.data.curAudioIndex != index) {
  122. this.setData({
  123. curAudioIndex: index,
  124. })
  125. audioContext.src = this.data.audioList[index].url
  126. audioContext.play()
  127. audioContext.onEnded((res) => {
  128. this.setData({
  129. curAudioIndex: '-1',
  130. })
  131. })
  132. } else {
  133. if (this.data.audioPause) {
  134. audioContext.play()
  135. this.setData({
  136. audioPause: false
  137. })
  138. } else {
  139. audioContext.pause()
  140. this.setData({
  141. audioPause: true
  142. })
  143. }
  144. }
  145. },
  146. delAudio: function (e) {
  147. const index = e.currentTarget.dataset.index
  148. // this.data.audioList.splice(index, 1);
  149. // this.setData({
  150. // audioList: this.data.audioList
  151. // })
  152. let records = this.data.audioList;
  153. let record = records[index];
  154. record.delete = 1
  155. this.setData({
  156. audioList: records
  157. })
  158. },
  159. uploadTap: function () {
  160. const that = this
  161. if (that.data.imgList.length >= 6) {
  162. wx.showToast({
  163. title: '最多上传6张图片',
  164. icon: 'none'
  165. })
  166. return
  167. }
  168. wx.chooseImage({
  169. count: 6,
  170. sourceType: ['album', 'camera'],
  171. success(res) {
  172. wx.showLoading({
  173. title: '上传中...',
  174. })
  175. for (var i in res.tempFilePaths) {
  176. wx.uploadFile({
  177. filePath: res.tempFilePaths[i],
  178. name: 'name',
  179. url: urls.file_upload,
  180. header: util.getHeaders(),
  181. success(res) {
  182. wx.showToast({
  183. title: '上传成功',
  184. })
  185. const rs = JSON.parse(JSON.parse(JSON.stringify(res.data)))
  186. const list = [{
  187. url: rs.data[0].url
  188. }]
  189. that.setData({
  190. imgList: that.data.imgList.concat(list)
  191. })
  192. },
  193. fail(res) {
  194. wx.showToast({
  195. title: '上传失败',
  196. icon: none
  197. })
  198. },
  199. complete(res) {
  200. wx.hideLoading({
  201. success: (res) => {},
  202. })
  203. }
  204. })
  205. }
  206. }
  207. })
  208. },
  209. showImg: function (e) {
  210. const index = e.currentTarget.dataset.index
  211. let images = this.data.imgList;
  212. let imgs = []
  213. images.map(i => {
  214. imgs.push(i.url)
  215. })
  216. wx.previewImage({
  217. current: images[index].url,
  218. urls: imgs,
  219. })
  220. },
  221. delImg: function (e) {
  222. const index = e.currentTarget.dataset.index
  223. // this.data.imgList.splice(index, 1);
  224. let images = this.data.imgList;
  225. let image = images[index]
  226. image.delete = 1
  227. this.setData({
  228. imgList: images
  229. })
  230. },
  231. upLoadVideo: function () {
  232. const that = this
  233. if (that.data.videoList.length >= 6) {
  234. wx.showToast({
  235. title: '最多上传6部视频',
  236. icon: 'none'
  237. })
  238. return
  239. }
  240. wx.chooseVideo({
  241. camera: ['album'],
  242. success(res) {
  243. var file = {
  244. url: res.tempFilePath,
  245. coverUrl: res.thumbTempFilePath
  246. };
  247. var userData = '{"Vod":{}}';
  248. const urls = urlDef.urls;
  249. let createUrl = urls.video_create_upload + '?title=' + res.tempFilePath + '&fileName=' + res.tempFilePath;
  250. console.log('createUploadVideo ... ');
  251. util.apiPost(createUrl).then((rs) => {
  252. let d = JSON.parse(rs.data);
  253. // console.log('createUploadVideo ' + JSON.stringify(d));
  254. that.setData({
  255. uploadAuth: d.UploadAuth,
  256. uploadAddress: d.UploadAddress,
  257. videoId: d.VideoId,
  258. })
  259. wx.showLoading({
  260. title: '上传中...',
  261. })
  262. // that.setData({
  263. // uploadIng: true
  264. // })
  265. uploader.addFile(file, null, null, null, userData)
  266. uploader.startUpload();
  267. // uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId);
  268. }, e => {
  269. console.log('createUploadVideo error ' + JSON.stringify(e));
  270. });
  271. }
  272. })
  273. },
  274. showVideo: function (e) {
  275. const index = e.currentTarget.dataset.index
  276. const curVideo = this.data.videoList[index].playUrl
  277. this.setData({
  278. curVideo
  279. })
  280. this.videoContext.requestFullScreen({ // 设置全屏时视频的方向,不指定则根据宽高比自动判断。
  281. direction: 90 // 屏幕逆时针90度
  282. });
  283. },
  284. // 监听视频是否为全屏,否则直接关闭
  285. bindfullscreenchange: function () {
  286. if (this.data.videoFlag == 0) {
  287. this.setData({
  288. videoFlag: 1
  289. })
  290. } else {
  291. this.setData({
  292. videoFlag: 0,
  293. curVideo: ""
  294. })
  295. }
  296. },
  297. delVideo: function (e) {
  298. const index = e.currentTarget.dataset.index
  299. // this.data.videoList.splice(index, 1);
  300. // this.setData({
  301. // videoList: this.data.videoList
  302. // })
  303. let videos = this.data.videoList;
  304. let video = videos[index]
  305. video.delete = 1
  306. this.setData({
  307. videoList: videos
  308. })
  309. },
  310. /**
  311. * 生命周期函数--监听页面加载
  312. */
  313. onLoad: function (options) {
  314. let urls = urlDef.urls;
  315. let stu = wx.getStorageSync('student')
  316. let homeworkId = options.homeworkId;
  317. let studentId = stu.studentId;
  318. this.setData({
  319. homeworkId: homeworkId
  320. })
  321. let params = {
  322. 'q.homeworkId': homeworkId,
  323. 'q.studentId': studentId
  324. }
  325. util.apiPost(urls.homework_receive, params).then(rs => {});
  326. util.apiPost(urls.my_homework, params).then(rs => {
  327. if (rs.length > 0) {
  328. let entity = rs[0]
  329. let contents;
  330. try {
  331. contents = entity
  332. contents.receiveDate = this.renderTime(contents.receiveDate)
  333. this.setData({
  334. contents
  335. })
  336. } catch (e) {
  337. contents = {};
  338. console.error(e);
  339. }
  340. this.setData({
  341. content: contents.content
  342. })
  343. let images = contents.images == null ? [] : contents.images;
  344. images.forEach(r => {
  345. r.url = urls.oss_file + 'image/' + r.url
  346. });
  347. let records = contents.records == null ? [] : contents.records;
  348. records.forEach(r => {
  349. r.url = urls.oss_file + 'file/' + r.url
  350. });
  351. let videos = contents.videos == null ? [] : contents.videos;
  352. this.setData({
  353. imgList: images,
  354. audioList: records,
  355. videoList: videos
  356. });
  357. videos.forEach(r => {
  358. util.apiPost(urls.video_loadInfo + r.url).then(rs => {
  359. r.imgUrl = rs.img
  360. r.playUrl = rs.url
  361. this.reloadVideos(r)
  362. });
  363. });
  364. }
  365. });
  366. this.videoContext = wx.createVideoContext('play-video'); // 创建 video 上下文 VideoContext 对象。
  367. const that = this
  368. const createUpLoad = new VODUpload({
  369. //阿里账号ID,必须有值
  370. userId: "WaWQOn6gXod13WLEp8cr4ljUdvcbXJ",
  371. //网络原因失败时,重新上传次数,默认为3
  372. retryCount: 3,
  373. //网络原因失败时,重新上传间隔时间,默认为2秒
  374. retryDuration: 2,
  375. //开始上传
  376. 'onUploadstarted': function (uploadInfo) {
  377. console.log("开始上传")
  378. // console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
  379. //上传方式1,需要根据uploadInfo.videoId是否有值,调用点播的不同接口获取uploadauth和uploadAddress,如果videoId有值,调用刷新视频上传凭证接口,否则调用创建视频上传凭证接口
  380. if (uploadInfo.videoId) {
  381. //如果uploadInfo.videoId存在,调用刷新视频上传凭证接口
  382. } else {
  383. //如果uploadInfo.videoId不存在,调用获取视频上传地址和凭证接口
  384. }
  385. //从点播服务获取的uploadAuth、uploadAddress和videoId,设置SDK
  386. // console.log(that.data)
  387. uploader.setUploadAuthAndAddress(uploadInfo, that.data.uploadAuth, that.data.uploadAddress, that.data.videoId);
  388. },
  389. //文件上传成功
  390. 'onUploadSucceed': function (uploadInfo) {
  391. console.log("上传成功:" + JSON.stringify(uploadInfo))
  392. let vid = uploadInfo.videoId
  393. let stu = wx.getStorageSync('student')
  394. var video = {
  395. name: vid,
  396. videoId: vid,
  397. orgId: stu.orgId,
  398. size: uploadInfo.fileSize,
  399. title: '',
  400. content: ''
  401. };
  402. // 保存一个 video
  403. let urls = urlDef.urls
  404. util.apiPost(urls.video_save, video, 'application/json').then((rs) => {
  405. var json = {
  406. url: uploadInfo.videoId,
  407. playUrl: uploadInfo.url,
  408. imgUrl: uploadInfo.coverUrl
  409. }
  410. console.log('视频上传成功' + JSON.stringify(json))
  411. var list = [json]
  412. that.setData({
  413. videoList: that.data.videoList.concat(list)
  414. })
  415. wx.showToast({
  416. title: '上传成功',
  417. })
  418. that.setData({
  419. uploadIng: false
  420. })
  421. })
  422. // console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
  423. },
  424. //文件上传失败
  425. 'onUploadFailed': function (uploadInfo, code, message) {
  426. // console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
  427. wx.showToast({
  428. title: '上传失败',
  429. })
  430. },
  431. //文件上传进度,单位:字节
  432. 'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
  433. // console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(loadedPercent * 100) + "%");
  434. },
  435. //上传凭证超时
  436. 'onUploadTokenExpired': function (uploadInfo) {
  437. wx.showToast({
  438. title: '上传超时',
  439. })
  440. console.log("onUploadTokenExpired");
  441. //实现时,根据uploadInfo.videoId调用刷新视频上传凭证接口重新获取UploadAuth
  442. //从点播服务刷新的uploadAuth,设置到SDK里
  443. uploader.resumeUploadWithAuth(uploadAuth);
  444. },
  445. //全部文件上传结束
  446. 'onUploadEnd': function (uploadInfo) {
  447. console.log("onUploadEnd: uploaded all the files");
  448. }
  449. });
  450. uploader = createUpLoad
  451. },
  452. removeUpload: function () {
  453. uploader.stopUpload()
  454. uploader.cleanList();
  455. wx.showToast({
  456. title: '取消上传',
  457. icon: 'none'
  458. })
  459. this.setData({
  460. uploadIng: false
  461. })
  462. },
  463. /**
  464. * 生命周期函数--监听页面初次渲染完成
  465. */
  466. onReady: function () {
  467. },
  468. /**
  469. * 生命周期函数--监听页面显示
  470. */
  471. onShow: function () {
  472. },
  473. /**
  474. * 生命周期函数--监听页面隐藏
  475. */
  476. onHide: function () {
  477. },
  478. /**
  479. * 生命周期函数--监听页面卸载
  480. */
  481. onUnload: function () {
  482. audioContext.stop()
  483. },
  484. /**
  485. * 页面相关事件处理函数--监听用户下拉动作
  486. */
  487. onPullDownRefresh: function () {
  488. },
  489. /**
  490. * 页面上拉触底事件的处理函数
  491. */
  492. onReachBottom: function () {
  493. },
  494. /**
  495. * 用户点击右上角分享
  496. */
  497. onShareAppMessage: function () {
  498. },
  499. doConfirmComplete: function () {
  500. console.log('homeworkId ' + this.data.homeworkId)
  501. let contents = {};
  502. let dlist = [];
  503. let images = [];
  504. if (this.data.imgList.length > 0) {
  505. this.data.imgList.forEach(r => {
  506. console.log(r.url)
  507. let fid = r.url.substring(r.url.lastIndexOf('/') + 1)
  508. if (r.delete == 1) {
  509. dlist.push({
  510. id: fid,
  511. type: 'image'
  512. })
  513. } else {
  514. images.push({
  515. url: fid
  516. })
  517. }
  518. });
  519. }
  520. let records = [];
  521. if (this.data.audioList.length > 0) {
  522. this.data.audioList.forEach(r => {
  523. console.log(r.url,2)
  524. let fid = r.url.substring(r.url.lastIndexOf('/') + 1)
  525. if (r.delete == 1) {
  526. dlist.push({
  527. id: fid,
  528. type: 'record'
  529. })
  530. } else {
  531. records.push({
  532. url: fid
  533. })
  534. }
  535. });
  536. }
  537. let videos = [];
  538. if (this.data.videoList.length > 0) {
  539. this.data.videoList.forEach(r => {
  540. if (r.delete == 1) {
  541. dlist.push({
  542. id: r.url,
  543. type: 'video'
  544. })
  545. } else {
  546. videos.push({
  547. url: r.url
  548. })
  549. }
  550. });
  551. }
  552. this.setData({
  553. delItems: dlist
  554. })
  555. contents.images = images;
  556. contents.videos = videos;
  557. contents.records = records;
  558. contents.content = this.data.content;
  559. let stu = wx.getStorageSync('student')
  560. let data = {
  561. 'q.content': JSON.stringify(contents),
  562. 'q.status': 1,
  563. 'q.studentId': stu.studentId,
  564. 'q.homeworkId': this.data.homeworkId
  565. }
  566. util.apiPost(urls.complete_homework, data).then(rs => {
  567. const msgParams = {
  568. 'homeworkId': this.data.homeworkId,
  569. 'studentId': stu.studentId
  570. };
  571. util.apiPost(urls.homework_complete_send_message, msgParams).then((rs) => {
  572. console.log('发送通知 ' + JSON.stringify(rs));
  573. });
  574. wx.showToast({
  575. title: '已完成作业'
  576. })
  577. setTimeout(() => {
  578. wx.navigateBack({
  579. delta: 2, // 返回上一级页面。
  580. success: function () {
  581. console.log('成功!')
  582. }
  583. })
  584. }, 1000)
  585. // 删除文件
  586. if (this.data.delItems.length > 0) {
  587. // 视频的删除跟文件的删除不一样
  588. let delFiles = [];
  589. let delVideos = [];
  590. this.data.delItems.forEach(r => {
  591. if (r.type === 'video') {
  592. delVideos.push(r.id);
  593. } else {
  594. delFiles.push(r.id);
  595. }
  596. });
  597. if (delFiles.length > 0) {
  598. const params = {
  599. 'keys': delFiles
  600. };
  601. util.apiPost(urls.file_delete, params).then((rs) => {
  602. console.log('删除文件 ... ' + JSON.stringify(params));
  603. });
  604. }
  605. if (delVideos.length > 0) {
  606. const params = {
  607. 'ids[]': delVideos
  608. }
  609. util.apiPost(urls.video_delete, params).then((rs) => {
  610. console.log('删除视频 ... ' + JSON.stringify(params));
  611. });
  612. }
  613. }
  614. })
  615. },
  616. reloadVideos: function (v) {
  617. let videos = this.data.videoList
  618. videos.map(o => {
  619. if (o.url == v.url) {
  620. o = v;
  621. }
  622. })
  623. this.setData({
  624. videoList: videos
  625. })
  626. },
  627. doInput: function (e) {
  628. this.setData({
  629. content: e.detail.value
  630. })
  631. }
  632. })