doTask.js 16 KB

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