微信公众号管理后台

audio.js 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. (function () {
  2. var insertaudio,
  3. uploadaudio;
  4. // 音频文件key前缀
  5. var keyPrefix = editor.getOpt('keyPrefix') + '/audio';
  6. window.onload = function () {
  7. initTabs();
  8. initButtons();
  9. };
  10. /* 初始化tab标签 */
  11. function initTabs() {
  12. var tabs = $G('tabhead').children;
  13. var audio = editor.selection.getRange().getClosedNode();
  14. var id = tabs[0].getAttribute('data-content-id');
  15. for (var i = 0; i < tabs.length; i++) {
  16. domUtils.on(tabs[i], "click", function (e) {
  17. var j, bodyId, target = e.target || e.srcElement;
  18. id = target.getAttribute('data-content-id');
  19. for (j = 0; j < tabs.length; j++) {
  20. bodyId = tabs[j].getAttribute('data-content-id');
  21. if(tabs[j] == target){
  22. domUtils.addClass(tabs[j], 'focus');
  23. domUtils.addClass($G(bodyId), 'focus');
  24. }else {
  25. domUtils.removeClasses(tabs[j], 'focus');
  26. domUtils.removeClasses($G(bodyId), 'focus');
  27. }
  28. }
  29. });
  30. }
  31. switch (id) {
  32. case 'remote': // 插入音频/远程音频(预留)
  33. insertaudio = insertaudio || new RemoteAudio();
  34. break;
  35. case 'upload': // 上传音频(主要)
  36. uploadaudio = uploadaudio || new UploadAudio('queueList');
  37. break;
  38. }
  39. }
  40. /* 初始化onok事件 */
  41. function initButtons() {
  42. dialog.onok = function () {
  43. var remote = false, list = [], id, tabs = $G('tabhead').children;
  44. for (var i = 0; i < tabs.length; i++) {
  45. if (domUtils.hasClass(tabs[i], 'focus')) {
  46. id = tabs[i].getAttribute('data-content-id');
  47. break;
  48. }
  49. }
  50. switch (id) {
  51. case 'remote':
  52. list = insertaudio.getInsertList();
  53. break;
  54. case 'upload':
  55. list = uploadaudio.getInsertList();
  56. var count = uploadaudio.getQueueCount();
  57. if (count) {
  58. $('.info', '#queueList').html('<span style="color:red;">' + '还有2个未上传文件'.replace(/[\d]/, count) + '</span>');
  59. return false;
  60. }
  61. // 配上标题
  62. var title = $('.uploadAudioTitle').val();
  63. if (!title || $.trim(title) == '') {
  64. alert('请填写标题');
  65. $('.uploadAudioTitle').focus();
  66. return false;
  67. }
  68. if(list) {
  69. for(var i = 0; i < list.length; i++) {
  70. var f = list[i];
  71. f['title'] = title;
  72. list[i] = f;
  73. }
  74. }
  75. break;
  76. }
  77. if(list) {
  78. editor.execCommand('insertaudio', list);
  79. remote && editor.fireEvent("catchRemoteAudio");
  80. }
  81. };
  82. }
  83. /* 上传音频 */
  84. function UploadAudio(target) {
  85. this.$wrap = target.constructor == String ? $('#' + target) : $(target);
  86. this.init();
  87. }
  88. UploadAudio.prototype = {
  89. init: function () {
  90. this.audioList = [];
  91. this.initContainer();
  92. this.initUploader();
  93. },
  94. initContainer: function () {
  95. this.$queue = this.$wrap.find('.filelist');
  96. },
  97. /* 初始化容器 */
  98. initUploader: function () {
  99. var _this = this,
  100. $ = jQuery, // just in case. Make sure it's not an other libaray.
  101. $wrap = _this.$wrap,
  102. // 文件容器
  103. $queue = $wrap.find('.filelist'),
  104. // 状态栏,包括进度和控制按钮
  105. $statusBar = $wrap.find('.statusBar'),
  106. // 文件总体选择信息。
  107. $info = $statusBar.find('.info'),
  108. // 上传按钮
  109. $upload = $wrap.find('.uploadBtn'),
  110. // 上传按钮
  111. $filePickerBtn = $wrap.find('.filePickerBtn'),
  112. // 上传按钮
  113. $filePickerBlock = $wrap.find('.filePickerBlock'),
  114. // 没选择文件之前的内容。
  115. $placeHolder = $wrap.find('.placeholder'),
  116. // 总体进度条
  117. $progress = $statusBar.find('.progress').hide(),
  118. // 添加的文件数量
  119. fileCount = 0,
  120. // 添加的文件总大小
  121. fileSize = 0,
  122. // 优化retina, 在retina下这个值是2
  123. ratio = window.devicePixelRatio || 1,
  124. // 缩略图大小
  125. thumbnailWidth = 550 * ratio,
  126. thumbnailHeight = 113 * ratio,
  127. // 可能有pedding, ready, uploading, confirm, done.
  128. state = '',
  129. // 所有文件的进度信息,key为file id
  130. percentages = {},
  131. supportTransition = (function () {
  132. var s = document.createElement('p').style,
  133. r = 'transition' in s ||
  134. 'WebkitTransition' in s ||
  135. 'MozTransition' in s ||
  136. 'msTransition' in s ||
  137. 'OTransition' in s;
  138. s = null;
  139. return r;
  140. })(),
  141. // WebUploader实例
  142. uploader,
  143. actionUrl = editor.getActionUrl(editor.getOpt('audioActionName')),
  144. acceptExtensions = (editor.getOpt('audioAllowFiles') || []).join('').replace(/\./g, ',').replace(/^[,]/, ''),
  145. audioMaxSize = editor.getOpt('audioMaxSize'),
  146. imageCompressBorder = editor.getOpt('imageCompressBorder');
  147. if (!WebUploader.Uploader.support()) {
  148. $('#filePickerReady').after($('<div>').html(lang.errorNotSupport)).hide();
  149. return;
  150. } else if (!editor.getOpt('audioActionName')) {
  151. $('#filePickerReady').after($('<div>').html(lang.errorLoadConfig)).hide();
  152. return;
  153. }
  154. uploader = _this.uploader = WebUploader.create({
  155. pick: {
  156. id: '#filePickerReady',
  157. label: lang.uploadSelectFile,
  158. multiple: false // 限制为单选
  159. },
  160. accept: {
  161. title: 'Audios',
  162. extensions: acceptExtensions,
  163. mimeTypes: 'audio/mp3,audio/amr,audio/wma,audio/wav'
  164. },
  165. swf: '../../third-party/webuploader/Uploader.swf',
  166. server: actionUrl,
  167. fileVal: editor.getOpt('audioFieldName'),
  168. duplicate: false,
  169. fileNumLimit: 1, // 限制为单个文件
  170. fileSingleSizeLimit: audioMaxSize // 默认 30 M
  171. });
  172. uploader.addButton({
  173. id: '#filePickerBlock'
  174. });
  175. // uploader.addButton({
  176. // id: '#filePickerBtn',
  177. // label: lang.uploadAddFile
  178. // });
  179. setState('pedding');
  180. // 当有文件添加进来时执行,负责view的创建
  181. function addFile(file) {
  182. var $li = $('<li id="' + file.id + '">' +
  183. '<p class="title">' + file.name + '</p>' +
  184. '<p class="progress"><span></span></p>' +
  185. '</li>'),
  186. $btns = $('<div class="file-panel">' +
  187. '<span class="cancel">' + lang.uploadDelete + '</span>' +
  188. '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
  189. '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
  190. $prgress = $li.find('p.progress span'),
  191. $wrap = $li.find('p.imgWrap'),
  192. $info = $('<p class="error"></p>').hide().appendTo($li),
  193. showError = function (code) {
  194. switch (code) {
  195. case 'exceed_size':
  196. text = lang.errorExceedSize;
  197. break;
  198. case 'interrupt':
  199. text = lang.errorInterrupt;
  200. break;
  201. case 'http':
  202. text = lang.errorHttp;
  203. break;
  204. case 'not_allow_type':
  205. text = lang.errorFileType;
  206. break;
  207. default:
  208. text = lang.errorUploadRetry;
  209. break;
  210. }
  211. $info.text(text).show();
  212. };
  213. if (file.getStatus() === 'invalid') {
  214. showError(file.statusText);
  215. } else {
  216. percentages[ file.id ] = [ file.size, 0 ];
  217. file.rotation = 0;
  218. /* 检查文件格式 */
  219. if (!file.ext || acceptExtensions.indexOf(file.ext.toLowerCase()) == -1) {
  220. showError('not_allow_type');
  221. uploader.removeFile(file);
  222. }
  223. }
  224. file.on('statuschange', function (cur, prev) {
  225. if (prev === 'progress') {
  226. $prgress.hide().width(0);
  227. } else if (prev === 'queued') {
  228. $li.off('mouseenter mouseleave');
  229. $btns.remove();
  230. }
  231. // 成功
  232. if (cur === 'error' || cur === 'invalid') {
  233. showError(file.statusText);
  234. percentages[ file.id ][ 1 ] = 1;
  235. } else if (cur === 'interrupt') {
  236. showError('interrupt');
  237. } else if (cur === 'queued') {
  238. percentages[ file.id ][ 1 ] = 0;
  239. } else if (cur === 'progress') {
  240. $info.hide();
  241. $prgress.css('display', 'block');
  242. } else if (cur === 'complete') {
  243. }
  244. $li.removeClass('state-' + prev).addClass('state-' + cur);
  245. });
  246. $li.on('mouseenter', function () {
  247. $btns.stop().animate({height: 30});
  248. });
  249. $li.on('mouseleave', function () {
  250. $btns.stop().animate({height: 0});
  251. });
  252. $btns.on('click', 'span', function () {
  253. var index = $(this).index(),
  254. deg;
  255. switch (index) {
  256. case 0:
  257. uploader.removeFile(file);
  258. return;
  259. case 1:
  260. file.rotation += 90;
  261. break;
  262. case 2:
  263. file.rotation -= 90;
  264. break;
  265. }
  266. if (supportTransition) {
  267. deg = 'rotate(' + file.rotation + 'deg)';
  268. $wrap.css({
  269. '-webkit-transform': deg,
  270. '-mos-transform': deg,
  271. '-o-transform': deg,
  272. 'transform': deg
  273. });
  274. } else {
  275. $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
  276. }
  277. });
  278. $li.insertBefore($filePickerBlock);
  279. // 隐藏继续添加控件,设置为单个文件上传
  280. $filePickerBlock.hide();
  281. }
  282. // 取消上传
  283. function cancelFile(file) {
  284. var $li = $('#' + file.id);
  285. var spans = $progress.children();
  286. spans.eq(0).text('0%');
  287. spans.eq(1).css('width', '0%');
  288. $progress.css('display', 'none');
  289. $('.statusBar').children('.info').css('display', 'inline-block');
  290. $('.error').remove();
  291. var upBtn = $('.uploadBtn');
  292. upBtn.removeClass('state-paused disabled');
  293. upBtn.addClass('state-ready');
  294. upBtn.html(lang.uploadStart);
  295. }
  296. // 负责view的销毁
  297. function removeFile(file) {
  298. var $li = $('#' + file.id);
  299. delete percentages[ file.id ];
  300. updateTotalProgress();
  301. $li.off().find('.file-panel').off().end().remove();
  302. // 显示继续添加控件
  303. $filePickerBlock.show();
  304. }
  305. function updateTotalProgress() {
  306. var loaded = 0,
  307. total = 0,
  308. spans = $progress.children(),
  309. percent;
  310. $.each(percentages, function (k, v) {
  311. total += v[ 0 ];
  312. loaded += v[ 0 ] * v[ 1 ];
  313. });
  314. percent = total ? loaded / total : 0;
  315. spans.eq(0).text(Math.round(percent * 100) + '%');
  316. spans.eq(1).css('width', Math.round(percent * 100) + '%');
  317. updateStatus();
  318. }
  319. function setState(val, files) {
  320. if (val != state) {
  321. var stats = uploader.getStats();
  322. $upload.removeClass('state-' + state);
  323. $upload.addClass('state-' + val);
  324. switch (val) {
  325. /* 未选择文件 */
  326. case 'pedding':
  327. $queue.addClass('element-invisible');
  328. $statusBar.addClass('element-invisible');
  329. $placeHolder.removeClass('element-invisible');
  330. $progress.hide(); $info.hide();
  331. uploader.refresh();
  332. break;
  333. /* 可以开始上传 */
  334. case 'ready':
  335. $placeHolder.addClass('element-invisible');
  336. $queue.removeClass('element-invisible');
  337. $statusBar.removeClass('element-invisible');
  338. $progress.hide(); $info.show();
  339. $upload.text(lang.uploadStart);
  340. uploader.refresh();
  341. break;
  342. /* 上传中 */
  343. case 'uploading':
  344. $progress.show(); $info.hide();
  345. // $upload.text(lang.uploadPause);
  346. $upload.text(lang.uploadCancel);
  347. break;
  348. /* 暂停上传 */
  349. case 'paused':
  350. $progress.show(); $info.hide();
  351. $upload.text(lang.uploadContinue);
  352. break;
  353. /* 取消上传 */
  354. case 'cancel':
  355. $placeHolder.addClass('element-invisible');
  356. $queue.removeClass('element-invisible');
  357. $statusBar.removeClass('element-invisible');
  358. $progress.hide(); $info.show();
  359. $upload.text(lang.uploadStart);
  360. uploader.refresh();
  361. break;
  362. case 'confirm':
  363. $progress.show(); $info.hide();
  364. $upload.text(lang.uploadStart);
  365. stats = uploader.getStats();
  366. if (stats.successNum && !stats.uploadFailNum) {
  367. setState('finish');
  368. return;
  369. }
  370. break;
  371. case 'finish':
  372. $progress.hide(); $info.show();
  373. if (stats.uploadFailNum) {
  374. $upload.text(lang.uploadRetry);
  375. } else {
  376. $upload.text(lang.uploadStart);
  377. }
  378. break;
  379. }
  380. state = val;
  381. updateStatus();
  382. }
  383. if (!_this.getQueueCount()) {
  384. $upload.addClass('disabled')
  385. } else {
  386. $upload.removeClass('disabled')
  387. }
  388. }
  389. function updateStatus() {
  390. var text = '', stats;
  391. if (state === 'ready') {
  392. text = lang.updateStatusReady.replace('_', fileCount).replace('_KB', WebUploader.formatSize(fileSize));
  393. } else if (state === 'confirm') {
  394. stats = uploader.getStats();
  395. if (stats.uploadFailNum) {
  396. text = lang.updateStatusConfirm.replace('_', stats.successNum).replace('_', stats.successNum);
  397. }
  398. } else {
  399. stats = uploader.getStats();
  400. text = lang.updateStatusFinish.replace('_', fileCount).
  401. replace('_KB', WebUploader.formatSize(fileSize)).
  402. replace('_', stats.successNum);
  403. if (stats.uploadFailNum) {
  404. text += lang.updateStatusError.replace('_', stats.uploadFailNum);
  405. }
  406. }
  407. $info.html(text);
  408. }
  409. uploader.on('fileQueued', function (file) {
  410. fileCount++;
  411. fileSize += file.size;
  412. if (fileCount === 1) {
  413. $placeHolder.addClass('element-invisible');
  414. $statusBar.show();
  415. }
  416. addFile(file);
  417. });
  418. uploader.on('fileDequeued', function (file) {
  419. fileCount--;
  420. fileSize -= file.size;
  421. removeFile(file);
  422. updateTotalProgress();
  423. });
  424. uploader.on('filesQueued', function (file) {
  425. if (!uploader.isInProgress() && (state == 'pedding' || state == 'finish' || state == 'confirm' || state == 'ready')) {
  426. setState('ready');
  427. }
  428. updateTotalProgress();
  429. });
  430. uploader.on('all', function (type, files) {
  431. switch (type) {
  432. case 'uploadFinished':
  433. setState('confirm', files);
  434. break;
  435. case 'startUpload':
  436. /* 添加额外的GET参数 */
  437. var params = utils.serializeParam(editor.queryCommandValue('serverparam')) || '';
  438. //url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?':'&') + 'encode=utf-8&' + params);
  439. uploader.option('server', editor.getOpt('imageUrl'));
  440. setState('uploading', files);
  441. break;
  442. case 'stopUpload':
  443. setState('paused', files);
  444. break;
  445. }
  446. });
  447. uploader.on('uploadBeforeSend', function (file, data, header) {
  448. //这里可以通过data对象添加POST参数
  449. header['X_Requested_With'] = 'XMLHttpRequest';
  450. // 上传token
  451. var token = getUploadToken4UE();
  452. if (token == null) {
  453. alert('获取上传token异常,请稍后再试~');
  454. return false;
  455. }
  456. data['token'] = token;
  457. // 文件key
  458. data['key'] = keyPrefix + '/' + uuid();
  459. });
  460. uploader.on('uploadProgress', function (file, percentage) {
  461. var $li = $('#' + file.id),
  462. $percent = $li.find('.progress span');
  463. $percent.css('width', percentage * 100 + '%');
  464. percentages[ file.id ][ 1 ] = percentage;
  465. updateTotalProgress();
  466. });
  467. uploader.on('uploadSuccess', function (file, ret) {
  468. var $file = $('#' + file.id);
  469. try {
  470. var responseText = (ret._raw || ret),
  471. json = utils.str2json(responseText);
  472. if (json.state == 'SUCCESS') {
  473. //_this.audioList.push(json);
  474. _this.audioList[$file.index()] = json; //按选择好的文件列表顺序存储
  475. $file.append('<span class="success"></span>');
  476. } else {
  477. $file.find('.error').text(json.state).show();
  478. }
  479. } catch (e) {
  480. $file.find('.error').text(lang.errorServerUpload).show();
  481. }
  482. });
  483. uploader.on('uploadError', function (file, code) {
  484. });
  485. uploader.on('error', function (code, file) {
  486. if (code == 'Q_TYPE_DENIED' || code == 'F_EXCEED_SIZE') {
  487. addFile(file);
  488. }
  489. });
  490. uploader.on('uploadComplete', function (file, ret) {
  491. });
  492. $upload.on('click', function () {
  493. if ($(this).hasClass('disabled')) {
  494. return false;
  495. }
  496. if (state === 'ready') {
  497. uploader.upload();
  498. } else if (state === 'paused') {
  499. uploader.upload();
  500. } else if (state === 'cancel') {
  501. uploader.upload();
  502. } else if (state === 'uploading') {
  503. // uploader.stop();
  504. // 调整为取消上传
  505. var file = uploader.getFiles()[0];
  506. uploader.stop(file);
  507. // removeFile(file);
  508. cancelFile(file);
  509. // setState('cancel');
  510. }
  511. });
  512. $upload.addClass('state-' + state);
  513. updateTotalProgress();
  514. },
  515. getQueueCount: function () {
  516. var file, i, status, readyFile = 0, files = this.uploader.getFiles();
  517. for (i = 0; file = files[i++]; ) {
  518. status = file.getStatus();
  519. if (status == 'queued' || status == 'uploading' || status == 'progress') readyFile++;
  520. }
  521. return readyFile;
  522. },
  523. destroy: function () {
  524. this.$wrap.remove();
  525. },
  526. getInsertList: function () {
  527. var i, data, list = [],
  528. prefix = editor.getOpt('audioUrlPrefix');
  529. for (i = 0; i < this.audioList.length; i++) {
  530. data = this.audioList[i];
  531. if(data == undefined){
  532. continue;
  533. }
  534. //修改END
  535. list.push({
  536. src: prefix + data.key,
  537. key: + new Date() // 以时间戳作为音频控件父div的id
  538. });
  539. }
  540. return list;
  541. }
  542. };
  543. })();