doTask.js 17 KB

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