video.js 32 KB

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