video.js 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. /**
  2. * Created by JetBrains PhpStorm.
  3. * User: taoqili
  4. * Date: 12-2-20
  5. * Time: 上午11:19
  6. * To change this template use File | Settings | File Templates.
  7. */
  8. (function(){
  9. var video = {},
  10. uploadVideoList = [],
  11. isModifyUploadVideo = false,
  12. uploadFile;
  13. window.onload = function(){
  14. $focus($G("videoUrl"));
  15. initTabs();
  16. initVideo();
  17. initUpload();
  18. };
  19. /* 初始化tab标签 */
  20. function initTabs(){
  21. var tabs = $G('tabHeads').children;
  22. for (var i = 0; i < tabs.length; i++) {
  23. domUtils.on(tabs[i], "click", function (e) {
  24. var j, bodyId, target = e.target || e.srcElement;
  25. for (j = 0; j < tabs.length; j++) {
  26. bodyId = tabs[j].getAttribute('data-content-id');
  27. if(tabs[j] == target){
  28. domUtils.addClass(tabs[j], 'focus');
  29. domUtils.addClass($G(bodyId), 'focus');
  30. }else {
  31. domUtils.removeClasses(tabs[j], 'focus');
  32. domUtils.removeClasses($G(bodyId), 'focus');
  33. }
  34. }
  35. });
  36. }
  37. }
  38. function initVideo(){
  39. createAlignButton( ["videoFloat", "upload_alignment"] );
  40. addUrlChangeListener($G("videoUrl"));
  41. addOkListener();
  42. //编辑视频时初始化相关信息
  43. (function(){
  44. var img = editor.selection.getRange().getClosedNode(),url;
  45. if(img && img.className){
  46. var hasFakedClass = (img.className == "edui-faked-video"),
  47. hasUploadClass = img.className.indexOf("edui-upload-video")!=-1;
  48. if(hasFakedClass || hasUploadClass) {
  49. $G("videoUrl").value = url = img.getAttribute("_url");
  50. $G("videoWidth").value = img.width;
  51. $G("videoHeight").value = img.height;
  52. var align = domUtils.getComputedStyle(img,"float"),
  53. parentAlign = domUtils.getComputedStyle(img.parentNode,"text-align");
  54. updateAlignButton(parentAlign==="center"?"center":align);
  55. }
  56. if(hasUploadClass) {
  57. isModifyUploadVideo = true;
  58. }
  59. }
  60. createPreviewVideo(url);
  61. })();
  62. }
  63. /**
  64. * 监听确认和取消两个按钮事件,用户执行插入或者清空正在播放的视频实例操作
  65. */
  66. function addOkListener(){
  67. dialog.onok = function(){
  68. $G("preview").innerHTML = "";
  69. var currentTab = findFocus("tabHeads","tabSrc");
  70. switch(currentTab){
  71. case "video":
  72. return insertSingle();
  73. break;
  74. case "videoSearch":
  75. return insertSearch("searchList");
  76. break;
  77. case "upload":
  78. return insertUpload();
  79. break;
  80. }
  81. };
  82. dialog.oncancel = function(){
  83. $G("preview").innerHTML = "";
  84. };
  85. }
  86. /**
  87. * 依据传入的align值更新按钮信息
  88. * @param align
  89. */
  90. function updateAlignButton( align ) {
  91. var aligns = $G( "videoFloat" ).children;
  92. for ( var i = 0, ci; ci = aligns[i++]; ) {
  93. if ( ci.getAttribute( "name" ) == align ) {
  94. if ( ci.className !="focus" ) {
  95. ci.className = "focus";
  96. }
  97. } else {
  98. if ( ci.className =="focus" ) {
  99. ci.className = "";
  100. }
  101. }
  102. }
  103. }
  104. /**
  105. * 将单个视频信息插入编辑器中
  106. */
  107. function insertSingle(){
  108. var width = $G("videoWidth"),
  109. height = $G("videoHeight"),
  110. url=$G('videoUrl').value,
  111. align = findFocus("videoFloat","name");
  112. var newurl = convert_url(url);
  113. if (newurl.startsWith("<embed>")) {
  114. var arr = newurl.split(" ");
  115. for (var i=0; i>arr.length; i++) {
  116. if (arr[i].startsWith("src")) {
  117. newurl = arr[i].replace("src=", "");
  118. }
  119. if (arr[i].startsWith("width")) {
  120. if (!width) {
  121. width = arr[i].replace("width=", "");
  122. }
  123. }
  124. if (arr[i].startsWith("height")) {
  125. if (!height) {
  126. height = arr[i].replace("height=", "");
  127. }
  128. }
  129. }
  130. }
  131. if(!newurl) return false;
  132. if ( !checkNum( [width, height] ) ) return false;
  133. editor.execCommand('insertvideo', {
  134. url: newurl,
  135. width: width.value,
  136. height: height.value,
  137. align: align
  138. }, isModifyUploadVideo ? 'upload':null);
  139. }
  140. /**
  141. * 将元素id下的所有代表视频的图片插入编辑器中
  142. * @param id
  143. */
  144. function insertSearch(id){
  145. var imgs = domUtils.getElementsByTagName($G(id),"img"),
  146. videoObjs=[];
  147. for(var i=0,img; img=imgs[i++];){
  148. if(img.getAttribute("selected")){
  149. videoObjs.push({
  150. url:img.getAttribute("ue_video_url"),
  151. width:420,
  152. height:280,
  153. align:"none"
  154. });
  155. }
  156. }
  157. editor.execCommand('insertvideo',videoObjs);
  158. }
  159. /**
  160. * 找到id下具有focus类的节点并返回该节点下的某个属性
  161. * @param id
  162. * @param returnProperty
  163. */
  164. function findFocus( id, returnProperty ) {
  165. var tabs = $G( id ).children,
  166. property;
  167. for ( var i = 0, ci; ci = tabs[i++]; ) {
  168. if ( ci.className=="focus" ) {
  169. property = ci.getAttribute( returnProperty );
  170. break;
  171. }
  172. }
  173. return property;
  174. }
  175. function convert_url(url){
  176. if ( !url ) return '';
  177. //去掉多余参数,否则可能导致插入后无法播放
  178. var arr = url.split('?');
  179. if (arr && arr.length > 1) {
  180. url = arr[0];
  181. }
  182. url = utils.trim(url)
  183. .replace(/v\.youku\.com\/v_show\/id_([\w\-=]+)\.html/i, 'player.youku.com/player.php/sid/$1/v.swf')
  184. .replace(/(www\.)?youtube\.com\/watch\?v=([\w\-]+)/i, "www.youtube.com/v/$2")
  185. .replace(/youtu.be\/(\w+)$/i, "www.youtube.com/v/$1")
  186. .replace(/v\.ku6\.com\/.+\/([\w\.]+)\.html.*$/i, "player.ku6.com/refer/$1/v.swf")
  187. .replace(/www\.56\.com\/u\d+\/v_([\w\-]+)\.html/i, "player.56.com/v_$1.swf")
  188. .replace(/www.56.com\/w\d+\/play_album\-aid\-\d+_vid\-([^.]+)\.html/i, "player.56.com/v_$1.swf")
  189. .replace(/v\.pps\.tv\/play_([\w]+)\.html.*$/i, "player.pps.tv/player/sid/$1/v.swf")
  190. .replace(/www\.letv\.com\/ptv\/vplay\/([\d]+)\.html.*$/i, "i7.imgs.letv.com/player/swfPlayer.swf?id=$1&autoplay=0")
  191. .replace(/www\.tudou\.com\/programs\/view\/([\w\-]+)\/?/i, "www.tudou.com/v/$1")
  192. .replace(/v\.qq\.com\/cover\/[\w]+\/[\w]+\/([\w]+)\.html/i, "static.video.qq.com/TPout.swf?vid=$1")
  193. .replace(/v\.qq\.com\/.+[\?\&]vid=([^&]+).*$/i, "static.video.qq.com/TPout.swf?vid=$1")
  194. .replace(/my\.tv\.sohu\.com\/[\w]+\/[\d]+\/([\d]+)\.shtml.*$/i, "share.vrs.sohu.com/my/v.swf&id=$1");
  195. return url;
  196. }
  197. /**
  198. * 检测传入的所有input框中输入的长宽是否是正数
  199. * @param nodes input框集合,
  200. */
  201. function checkNum( nodes ) {
  202. for ( var i = 0, ci; ci = nodes[i++]; ) {
  203. var value = ci.value;
  204. if ( !isNumber( value ) && value) {
  205. alert( lang.numError );
  206. ci.value = "";
  207. ci.focus();
  208. return false;
  209. }
  210. }
  211. return true;
  212. }
  213. /**
  214. * 数字判断
  215. * @param value
  216. */
  217. function isNumber( value ) {
  218. return /(0|^[1-9]\d*$)/.test( value );
  219. }
  220. /**
  221. * 创建图片浮动选择按钮
  222. * @param ids
  223. */
  224. function createAlignButton( ids ) {
  225. for ( var i = 0, ci; ci = ids[i++]; ) {
  226. var floatContainer = $G( ci ),
  227. nameMaps = {"none":lang['default'], "left":lang.floatLeft, "right":lang.floatRight, "center":lang.block};
  228. for ( var j in nameMaps ) {
  229. var div = document.createElement( "div" );
  230. div.setAttribute( "name", j );
  231. if ( j == "none" ) div.className="focus";
  232. div.style.cssText = "background:url(images/" + j + "_focus.jpg);";
  233. div.setAttribute( "title", nameMaps[j] );
  234. floatContainer.appendChild( div );
  235. }
  236. switchSelect( ci );
  237. }
  238. }
  239. /**
  240. * 选择切换
  241. * @param selectParentId
  242. */
  243. function switchSelect( selectParentId ) {
  244. var selects = $G( selectParentId ).children;
  245. for ( var i = 0, ci; ci = selects[i++]; ) {
  246. domUtils.on( ci, "click", function () {
  247. for ( var j = 0, cj; cj = selects[j++]; ) {
  248. cj.className = "";
  249. cj.removeAttribute && cj.removeAttribute( "class" );
  250. }
  251. this.className = "focus";
  252. } )
  253. }
  254. }
  255. /**
  256. * 监听url改变事件
  257. * @param url
  258. */
  259. function addUrlChangeListener(url){
  260. if (browser.ie) {
  261. url.onpropertychange = function () {
  262. createPreviewVideo( this.value );
  263. }
  264. } else {
  265. url.addEventListener( "input", function () {
  266. createPreviewVideo( this.value );
  267. }, false );
  268. }
  269. }
  270. /**
  271. * 根据url生成视频预览
  272. * @param url
  273. */
  274. function createPreviewVideo(url){
  275. if ( !url ) return;
  276. if (url.startsWith("http") && url.indexOf(".mp4") > 0) {
  277. $G("preview").innerHTML = '<div class="previewMsg"><span>'+lang.urlError+'</span></div>'+
  278. '<video class="previewVideo"' +
  279. ' src="' + url + '"' +
  280. ' width="' + 420 + '"' +
  281. ' height="' + 280 + '"' +
  282. ' play="true" loop="false" data-setup="{}" controls="controls" preload="auto">' +
  283. '</video>';
  284. }
  285. if (url.startsWith("<embed>")) {
  286. $G("preview").innerHTML = '<div class="previewMsg"><span>'+lang.urlError+'</span></div>'+url;
  287. }
  288. }
  289. /* 插入上传视频 */
  290. function insertUpload(){
  291. var videoObjs=[],
  292. prefix = editor.getOpt('videoUrlPrefix'),
  293. width = $G('upload_width').value || 420,
  294. height = $G('upload_height').value || 280,
  295. align = findFocus("upload_alignment","name") || 'none',
  296. videoSrcField = editor.getOpt("imageUploadService")(this, editor).videoSrcField || 'url',
  297. videoSrc = '',
  298. videoSrcFieldKeys = videoSrcField.split('.');
  299. for(var key in uploadVideoList) {
  300. var file = uploadVideoList[key];
  301. if(videoSrcFieldKeys.length > 1) {
  302. function setVideoSrc(obj, keys, index) {
  303. obj = obj[keys[index]];
  304. if (index < keys.length - 1) {
  305. setVideoSrc(obj, keys, index += 1)
  306. } else {
  307. videoSrc = obj;
  308. }
  309. }
  310. setVideoSrc(file, videoSrcFieldKeys, 0);
  311. } else {
  312. videoSrc = file[videoSrcField];
  313. }
  314. videoObjs.push({
  315. url: prefix + videoSrc,
  316. width:width,
  317. height:height,
  318. align:align
  319. });
  320. }
  321. var count = uploadFile.getQueueCount();
  322. if (count) {
  323. $('.info', '#queueList').html('<span style="color:red;">' + '还有2个未上传文件'.replace(/[\d]/, count) + '</span>');
  324. return false;
  325. } else {
  326. editor.execCommand('insertvideo', videoObjs, 'upload');
  327. }
  328. }
  329. /*初始化上传标签*/
  330. function initUpload(){
  331. uploadFile = new UploadVideo('queueList');
  332. }
  333. /* 上传视频 */
  334. function UploadVideo(target) {
  335. this.$wrap = target.constructor == String ? $('#' + target) : $(target);
  336. this.init();
  337. }
  338. UploadVideo.prototype = {
  339. init: function () {
  340. this.fileList = [];
  341. this.initContainer();
  342. this.initUploader();
  343. },
  344. initContainer: function () {
  345. this.$queue = this.$wrap.find('.filelist');
  346. },
  347. /* 初始化容器 */
  348. initUploader: function () {
  349. var _this = this,
  350. $ = jQuery, // just in case. Make sure it's not an other libaray.
  351. $wrap = _this.$wrap,
  352. // 图片容器
  353. $queue = $wrap.find('.filelist'),
  354. // 状态栏,包括进度和控制按钮
  355. $statusBar = $wrap.find('.statusBar'),
  356. // 文件总体选择信息。
  357. $info = $statusBar.find('.info'),
  358. // 上传按钮
  359. $upload = $wrap.find('.uploadBtn'),
  360. // 上传按钮
  361. $filePickerBtn = $wrap.find('.filePickerBtn'),
  362. // 上传按钮
  363. $filePickerBlock = $wrap.find('.filePickerBlock'),
  364. // 没选择文件之前的内容。
  365. $placeHolder = $wrap.find('.placeholder'),
  366. // 总体进度条
  367. $progress = $statusBar.find('.progress').hide(),
  368. // 添加的文件数量
  369. fileCount = 0,
  370. // 添加的文件总大小
  371. fileSize = 0,
  372. // 优化retina, 在retina下这个值是2
  373. ratio = window.devicePixelRatio || 1,
  374. // 缩略图大小
  375. thumbnailWidth = 113 * ratio,
  376. thumbnailHeight = 113 * ratio,
  377. // 可能有pedding, ready, uploading, confirm, done.
  378. state = '',
  379. // 所有文件的进度信息,key为file id
  380. percentages = {},
  381. supportTransition = (function () {
  382. var s = document.createElement('p').style,
  383. r = 'transition' in s ||
  384. 'WebkitTransition' in s ||
  385. 'MozTransition' in s ||
  386. 'msTransition' in s ||
  387. 'OTransition' in s;
  388. s = null;
  389. return r;
  390. })(),
  391. // WebUploader实例
  392. uploader,
  393. actionUrl = editor.getActionUrl(editor.getOpt('videoActionName')),
  394. fileMaxSize = editor.getOpt('videoMaxSize'),
  395. acceptExtensions = (editor.getOpt('videoAllowFiles') || [".mp4", ".webm", ".flv", ".ogg", ".f4v"]).join('').replace(/\./g, ',').replace(/^[,]/, '');;
  396. if (!WebUploader.Uploader.support()) {
  397. $('#filePickerReady').after($('<div>').html(lang.errorNotSupport)).hide();
  398. return;
  399. } else if (!editor.getOpt('videoActionName')) {
  400. $('#filePickerReady').after($('<div>').html(lang.errorLoadConfig)).hide();
  401. return;
  402. }
  403. uploader = _this.uploader = WebUploader.create({
  404. pick: {
  405. id: '#filePickerReady',
  406. label: lang.uploadSelectFile
  407. },
  408. swf: '../../third-party/webuploader/Uploader.swf',
  409. server: actionUrl,
  410. fileVal: editor.getOpt('videoFieldName'),
  411. duplicate: true,
  412. fileSingleSizeLimit: fileMaxSize,
  413. compress: false
  414. });
  415. uploader.addButton({
  416. id: '#filePickerBlock'
  417. });
  418. uploader.addButton({
  419. id: '#filePickerBtn',
  420. label: lang.uploadAddFile
  421. });
  422. setState('pedding');
  423. // 当有文件添加进来时执行,负责view的创建
  424. function addFile(file) {
  425. var $li = $('<li id="' + file.id + '">' +
  426. '<p class="title">' + file.name + '</p>' +
  427. '<p class="imgWrap"></p>' +
  428. '<p class="progress"><span></span></p>' +
  429. '</li>'),
  430. $btns = $('<div class="file-panel">' +
  431. '<span class="cancel">' + lang.uploadDelete + '</span>' +
  432. '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
  433. '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
  434. $prgress = $li.find('p.progress span'),
  435. $wrap = $li.find('p.imgWrap'),
  436. $info = $('<p class="error"></p>').hide().appendTo($li),
  437. showError = function (code) {
  438. switch (code) {
  439. case 'exceed_size':
  440. text = lang.errorExceedSize;
  441. break;
  442. case 'interrupt':
  443. text = lang.errorInterrupt;
  444. break;
  445. case 'http':
  446. text = lang.errorHttp;
  447. break;
  448. case 'not_allow_type':
  449. text = lang.errorFileType;
  450. break;
  451. default:
  452. text = lang.errorUploadRetry;
  453. break;
  454. }
  455. $info.text(text).show();
  456. };
  457. if (file.getStatus() === 'invalid') {
  458. showError(file.statusText);
  459. } else {
  460. $wrap.text(lang.uploadPreview);
  461. if ('|png|jpg|jpeg|bmp|gif|'.indexOf('|'+file.ext.toLowerCase()+'|') == -1) {
  462. $wrap.empty().addClass('notimage').append('<i class="file-preview file-type-' + file.ext.toLowerCase() + '"></i>' +
  463. '<span class="file-title">' + file.name + '</span>');
  464. } else {
  465. if (browser.ie && browser.version <= 7) {
  466. $wrap.text(lang.uploadNoPreview);
  467. } else {
  468. uploader.makeThumb(file, function (error, src) {
  469. if (error || !src || (/^data:/.test(src) && browser.ie && browser.version <= 7)) {
  470. $wrap.text(lang.uploadNoPreview);
  471. } else {
  472. var $img = $('<img src="' + src + '">');
  473. $wrap.empty().append($img);
  474. $img.on('error', function () {
  475. $wrap.text(lang.uploadNoPreview);
  476. });
  477. }
  478. }, thumbnailWidth, thumbnailHeight);
  479. }
  480. }
  481. percentages[ file.id ] = [ file.size, 0 ];
  482. file.rotation = 0;
  483. /* 检查文件格式 */
  484. if (!file.ext || acceptExtensions.indexOf(file.ext.toLowerCase()) == -1) {
  485. showError('not_allow_type');
  486. uploader.removeFile(file);
  487. }
  488. }
  489. file.on('statuschange', function (cur, prev) {
  490. if (prev === 'progress') {
  491. $prgress.hide().width(0);
  492. } else if (prev === 'queued') {
  493. $li.off('mouseenter mouseleave');
  494. $btns.remove();
  495. }
  496. // 成功
  497. if (cur === 'error' || cur === 'invalid') {
  498. showError(file.statusText);
  499. percentages[ file.id ][ 1 ] = 1;
  500. } else if (cur === 'interrupt') {
  501. showError('interrupt');
  502. } else if (cur === 'queued') {
  503. percentages[ file.id ][ 1 ] = 0;
  504. } else if (cur === 'progress') {
  505. $info.hide();
  506. $prgress.css('display', 'block');
  507. } else if (cur === 'complete') {
  508. }
  509. $li.removeClass('state-' + prev).addClass('state-' + cur);
  510. });
  511. $li.on('mouseenter', function () {
  512. $btns.stop().animate({height: 30});
  513. });
  514. $li.on('mouseleave', function () {
  515. $btns.stop().animate({height: 0});
  516. });
  517. $btns.on('click', 'span', function () {
  518. var index = $(this).index(),
  519. deg;
  520. switch (index) {
  521. case 0:
  522. uploader.removeFile(file);
  523. return;
  524. case 1:
  525. file.rotation += 90;
  526. break;
  527. case 2:
  528. file.rotation -= 90;
  529. break;
  530. }
  531. if (supportTransition) {
  532. deg = 'rotate(' + file.rotation + 'deg)';
  533. $wrap.css({
  534. '-webkit-transform': deg,
  535. '-mos-transform': deg,
  536. '-o-transform': deg,
  537. 'transform': deg
  538. });
  539. } else {
  540. $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
  541. }
  542. });
  543. $li.insertBefore($filePickerBlock);
  544. }
  545. // 负责view的销毁
  546. function removeFile(file) {
  547. var $li = $('#' + file.id);
  548. delete percentages[ file.id ];
  549. updateTotalProgress();
  550. $li.off().find('.file-panel').off().end().remove();
  551. }
  552. function updateTotalProgress() {
  553. var loaded = 0,
  554. total = 0,
  555. spans = $progress.children(),
  556. percent;
  557. $.each(percentages, function (k, v) {
  558. total += v[ 0 ];
  559. loaded += v[ 0 ] * v[ 1 ];
  560. });
  561. percent = total ? loaded / total : 0;
  562. spans.eq(0).text(Math.round(percent * 100) + '%');
  563. spans.eq(1).css('width', Math.round(percent * 100) + '%');
  564. updateStatus();
  565. }
  566. function setState(val, files) {
  567. if (val != state) {
  568. var stats = uploader.getStats();
  569. $upload.removeClass('state-' + state);
  570. $upload.addClass('state-' + val);
  571. switch (val) {
  572. /* 未选择文件 */
  573. case 'pedding':
  574. $queue.addClass('element-invisible');
  575. $statusBar.addClass('element-invisible');
  576. $placeHolder.removeClass('element-invisible');
  577. $progress.hide(); $info.hide();
  578. uploader.refresh();
  579. break;
  580. /* 可以开始上传 */
  581. case 'ready':
  582. $placeHolder.addClass('element-invisible');
  583. $queue.removeClass('element-invisible');
  584. $statusBar.removeClass('element-invisible');
  585. $progress.hide(); $info.show();
  586. $upload.text(lang.uploadStart);
  587. uploader.refresh();
  588. break;
  589. /* 上传中 */
  590. case 'uploading':
  591. $progress.show(); $info.hide();
  592. $upload.text(lang.uploadPause);
  593. break;
  594. /* 暂停上传 */
  595. case 'paused':
  596. $progress.show(); $info.hide();
  597. $upload.text(lang.uploadContinue);
  598. break;
  599. case 'confirm':
  600. $progress.show(); $info.hide();
  601. $upload.text(lang.uploadStart);
  602. stats = uploader.getStats();
  603. if (stats.successNum && !stats.uploadFailNum) {
  604. setState('finish');
  605. return;
  606. }
  607. break;
  608. case 'finish':
  609. $progress.hide(); $info.show();
  610. if (stats.uploadFailNum) {
  611. $upload.text(lang.uploadRetry);
  612. } else {
  613. $upload.text(lang.uploadStart);
  614. }
  615. break;
  616. }
  617. state = val;
  618. updateStatus();
  619. }
  620. if (!_this.getQueueCount()) {
  621. $upload.addClass('disabled')
  622. } else {
  623. $upload.removeClass('disabled')
  624. }
  625. }
  626. function updateStatus() {
  627. var text = '', stats;
  628. if (state === 'ready') {
  629. text = lang.updateStatusReady.replace('_', fileCount).replace('_KB', WebUploader.formatSize(fileSize));
  630. } else if (state === 'confirm') {
  631. stats = uploader.getStats();
  632. if (stats.uploadFailNum) {
  633. text = lang.updateStatusConfirm.replace('_', stats.successNum).replace('_', stats.successNum);
  634. }
  635. } else {
  636. stats = uploader.getStats();
  637. text = lang.updateStatusFinish.replace('_', fileCount).
  638. replace('_KB', WebUploader.formatSize(fileSize)).
  639. replace('_', stats.successNum);
  640. if (stats.uploadFailNum) {
  641. text += lang.updateStatusError.replace('_', stats.uploadFailNum);
  642. }
  643. }
  644. $info.html(text);
  645. }
  646. uploader.on('fileQueued', function (file) {
  647. /* 选择文件后设置上传相关的url和自定义参数 */
  648. editor.getOpt("videoUploadService")(_this, editor).setUploadData(file);
  649. fileCount++;
  650. fileSize += file.size;
  651. if (fileCount === 1) {
  652. $placeHolder.addClass('element-invisible');
  653. $statusBar.show();
  654. }
  655. addFile(file);
  656. });
  657. uploader.on('fileDequeued', function (file) {
  658. fileCount--;
  659. fileSize -= file.size;
  660. removeFile(file);
  661. updateTotalProgress();
  662. });
  663. uploader.on('filesQueued', function (file) {
  664. if (!uploader.isInProgress() && (state == 'pedding' || state == 'finish' || state == 'confirm' || state == 'ready')) {
  665. setState('ready');
  666. }
  667. updateTotalProgress();
  668. });
  669. uploader.on('all', function (type, files) {
  670. switch (type) {
  671. case 'uploadFinished':
  672. setState('confirm', files);
  673. break;
  674. case 'startUpload':
  675. /* 设置Uploader配置项 */
  676. editor.getOpt("videoUploadService")(_this, editor).setUploaderOptions(uploader);
  677. setState('uploading', files);
  678. break;
  679. case 'stopUpload':
  680. setState('paused', files);
  681. break;
  682. }
  683. });
  684. uploader.on('uploadBeforeSend', function (object, data, headers) {
  685. //这里可以通过data对象添加POST参数
  686. editor.getOpt("videoUploadService")(_this, editor).setFormData(object, data, headers);
  687. });
  688. uploader.on('uploadProgress', function (file, percentage) {
  689. var $li = $('#' + file.id),
  690. $percent = $li.find('.progress span');
  691. $percent.css('width', percentage * 100 + '%');
  692. percentages[ file.id ][ 1 ] = percentage;
  693. updateTotalProgress();
  694. });
  695. uploader.on('uploadSuccess', function (file, res) {
  696. var $file = $('#' + file.id);
  697. try {
  698. if (editor.getOpt("videoUploadService")(_this, editor).getResponseSuccess(res)) {
  699. uploadVideoList.push({
  700. 'url': res.url,
  701. 'type': res.mimetype,
  702. 'original':res.original || ''
  703. });
  704. $file.append('<span class="success"></span>');
  705. } else {
  706. $file.find('.error').text(res.message).show();
  707. }
  708. } catch (e) {
  709. $file.find('.error').text(lang.errorServerUpload).show();
  710. }
  711. });
  712. uploader.on('uploadError', function (file, code) {
  713. });
  714. uploader.on('error', function (code, file) {
  715. if (code == 'Q_TYPE_DENIED' || code == 'F_EXCEED_SIZE') {
  716. addFile(file);
  717. }
  718. });
  719. uploader.on('uploadComplete', function (file, ret) {
  720. });
  721. $upload.on('click', function () {
  722. if ($(this).hasClass('disabled')) {
  723. return false;
  724. }
  725. if (state === 'ready') {
  726. window.setTimeout(function() {
  727. uploader.upload();
  728. }, 500);
  729. } else if (state === 'paused') {
  730. window.setTimeout(function() {
  731. uploader.upload();
  732. }, 500);
  733. } else if (state === 'uploading') {
  734. uploader.stop();
  735. }
  736. });
  737. $upload.addClass('state-' + state);
  738. updateTotalProgress();
  739. },
  740. getQueueCount: function () {
  741. var file, i, status, readyFile = 0, files = this.uploader.getFiles();
  742. for (i = 0; file = files[i++]; ) {
  743. status = file.getStatus();
  744. if (status == 'queued' || status == 'uploading' || status == 'progress') readyFile++;
  745. }
  746. return readyFile;
  747. },
  748. refresh: function(){
  749. this.uploader.refresh();
  750. }
  751. };
  752. })();