video.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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: convert_url(url),
  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. uploadDir = 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. for (var key in uploadVideoList) {
  297. var file = uploadVideoList[key];
  298. videoObjs.push({
  299. url: uploadDir + file.url,
  300. width: width,
  301. height: height,
  302. align: align
  303. });
  304. }
  305. var count = uploadFile.getQueueCount();
  306. if (count) {
  307. $('.info', '#queueList').html('<span style="color:red;">' + '还有2个未上传文件'.replace(/[\d]/, count) + '</span>');
  308. return false;
  309. } else {
  310. editor.execCommand('insertvideo', videoObjs, 'upload');
  311. }
  312. }
  313. /*初始化上传标签*/
  314. function initUpload() {
  315. uploadFile = new UploadFile('queueList');
  316. }
  317. /* 上传附件 */
  318. function UploadFile(target) {
  319. this.$wrap = target.constructor == String ? $('#' + target) : $(target);
  320. this.init();
  321. }
  322. UploadFile.prototype = {
  323. init: function () {
  324. this.fileList = [];
  325. this.initContainer();
  326. this.initUploader();
  327. },
  328. initContainer: function () {
  329. this.$queue = this.$wrap.find('.filelist');
  330. },
  331. /* 初始化容器 */
  332. initUploader: function () {
  333. var _this = this,
  334. $ = jQuery, // just in case. Make sure it's not an other libaray.
  335. $wrap = _this.$wrap,
  336. // 图片容器
  337. $queue = $wrap.find('.filelist'),
  338. // 状态栏,包括进度和控制按钮
  339. $statusBar = $wrap.find('.statusBar'),
  340. // 文件总体选择信息。
  341. $info = $statusBar.find('.info'),
  342. // 上传按钮
  343. $upload = $wrap.find('.uploadBtn'),
  344. // 上传按钮
  345. $filePickerBtn = $wrap.find('.filePickerBtn'),
  346. // 上传按钮
  347. $filePickerBlock = $wrap.find('.filePickerBlock'),
  348. // 没选择文件之前的内容。
  349. $placeHolder = $wrap.find('.placeholder'),
  350. // 总体进度条
  351. $progress = $statusBar.find('.progress').hide(),
  352. // 添加的文件数量
  353. fileCount = 0,
  354. // 添加的文件总大小
  355. fileSize = 0,
  356. // 优化retina, 在retina下这个值是2
  357. ratio = window.devicePixelRatio || 1,
  358. // 缩略图大小
  359. thumbnailWidth = 113 * ratio,
  360. thumbnailHeight = 113 * ratio,
  361. // 可能有pedding, ready, uploading, confirm, done.
  362. state = '',
  363. // 所有文件的进度信息,key为file id
  364. percentages = {},
  365. supportTransition = (function () {
  366. var s = document.createElement('p').style,
  367. r = 'transition' in s ||
  368. 'WebkitTransition' in s ||
  369. 'MozTransition' in s ||
  370. 'msTransition' in s ||
  371. 'OTransition' in s;
  372. s = null;
  373. return r;
  374. })(),
  375. // WebUploader实例
  376. uploader,
  377. filesArray = [],
  378. actionUrl = editor.getActionUrl(editor.getOpt('videoActionName')),
  379. fileMaxSize = editor.getOpt('videoMaxSize'),
  380. acceptExtensions = (editor.getOpt('videoAllowFiles') || [".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"]).join('').replace(/\./g, ',').replace(/^[,]/, '');;
  381. if (!WebUploader.Uploader.support()) {
  382. $('#filePickerReady').after($('<div>').html(lang.errorNotSupport)).hide();
  383. return;
  384. } else if (!editor.getOpt('videoActionName')) {
  385. $('#filePickerReady').after($('<div>').html(lang.errorLoadConfig)).hide();
  386. return;
  387. }
  388. uploader = _this.uploader = WebUploader.create({
  389. pick: {
  390. id: '#filePickerReady',
  391. label: lang.uploadSelectFile
  392. },
  393. swf: '../../third-party/webuploader/Uploader.swf',
  394. server: actionUrl,
  395. fileVal: editor.getOpt('videoFieldName'),
  396. duplicate: true,
  397. fileSingleSizeLimit: fileMaxSize,
  398. compress: false
  399. });
  400. uploader.addButton({
  401. id: '#filePickerBlock'
  402. });
  403. uploader.addButton({
  404. id: '#filePickerBtn',
  405. label: lang.uploadAddFile
  406. });
  407. setState('pedding');
  408. // 当有文件添加进来时执行,负责view的创建
  409. function addFile(file) {
  410. var $li = $('<li id="' + file.id + '">' +
  411. '<p class="title">' + file.name + '</p>' +
  412. '<p class="imgWrap"></p>' +
  413. '<p class="progress"><span></span></p>' +
  414. '</li>'),
  415. $btns = $('<div class="file-panel">' +
  416. '<span class="cancel">' + lang.uploadDelete + '</span>' +
  417. '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
  418. '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
  419. $prgress = $li.find('p.progress span'),
  420. $wrap = $li.find('p.imgWrap'),
  421. $info = $('<p class="error"></p>').hide().appendTo($li),
  422. showError = function (code) {
  423. switch (code) {
  424. case 'exceed_size':
  425. text = lang.errorExceedSize;
  426. break;
  427. case 'interrupt':
  428. text = lang.errorInterrupt;
  429. break;
  430. case 'http':
  431. text = lang.errorHttp;
  432. break;
  433. case 'not_allow_type':
  434. text = lang.errorFileType;
  435. break;
  436. default:
  437. text = lang.errorUploadRetry;
  438. break;
  439. }
  440. $info.text(text).show();
  441. };
  442. if (file.getStatus() === 'invalid') {
  443. showError(file.statusText);
  444. } else {
  445. $wrap.text(lang.uploadPreview);
  446. if ('|png|jpg|jpeg|bmp|gif|'.indexOf('|' + file.ext.toLowerCase() + '|') == -1) {
  447. $wrap.empty().addClass('notimage').append('<i class="file-preview file-type-' + file.ext.toLowerCase() + '"></i>' +
  448. '<span class="file-title">' + file.name + '</span>');
  449. } else {
  450. if (browser.ie && browser.version <= 7) {
  451. $wrap.text(lang.uploadNoPreview);
  452. } else {
  453. uploader.makeThumb(file, function (error, src) {
  454. if (error || !src || (/^data:/.test(src) && browser.ie && browser.version <= 7)) {
  455. $wrap.text(lang.uploadNoPreview);
  456. } else {
  457. var $img = $('<img src="' + src + '">');
  458. $wrap.empty().append($img);
  459. $img.on('error', function () {
  460. $wrap.text(lang.uploadNoPreview);
  461. });
  462. }
  463. }, thumbnailWidth, thumbnailHeight);
  464. }
  465. }
  466. percentages[file.id] = [file.size, 0];
  467. file.rotation = 0;
  468. /* 检查文件格式 */
  469. if (!file.ext || acceptExtensions.indexOf(file.ext.toLowerCase()) == -1) {
  470. showError('not_allow_type');
  471. uploader.removeFile(file);
  472. }
  473. }
  474. file.on('statuschange', function (cur, prev) {
  475. if (prev === 'progress') {
  476. $prgress.hide().width(0);
  477. } else if (prev === 'queued') {
  478. $li.off('mouseenter mouseleave');
  479. $btns.remove();
  480. }
  481. // 成功
  482. if (cur === 'error' || cur === 'invalid') {
  483. showError(file.statusText);
  484. percentages[file.id][1] = 1;
  485. } else if (cur === 'interrupt') {
  486. showError('interrupt');
  487. } else if (cur === 'queued') {
  488. percentages[file.id][1] = 0;
  489. } else if (cur === 'progress') {
  490. $info.hide();
  491. $prgress.css('display', 'block');
  492. } else if (cur === 'complete') {
  493. }
  494. $li.removeClass('state-' + prev).addClass('state-' + cur);
  495. });
  496. $li.on('mouseenter', function () {
  497. $btns.stop().animate({ height: 30 });
  498. });
  499. $li.on('mouseleave', function () {
  500. $btns.stop().animate({ height: 0 });
  501. });
  502. $btns.on('click', 'span', function () {
  503. var index = $(this).index(),
  504. deg;
  505. switch (index) {
  506. case 0:
  507. uploader.removeFile(file);
  508. return;
  509. case 1:
  510. file.rotation += 90;
  511. break;
  512. case 2:
  513. file.rotation -= 90;
  514. break;
  515. }
  516. if (supportTransition) {
  517. deg = 'rotate(' + file.rotation + 'deg)';
  518. $wrap.css({
  519. '-webkit-transform': deg,
  520. '-mos-transform': deg,
  521. '-o-transform': deg,
  522. 'transform': deg
  523. });
  524. } else {
  525. $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
  526. }
  527. });
  528. $li.insertBefore($filePickerBlock);
  529. }
  530. // 负责view的销毁
  531. function removeFile(file) {
  532. var $li = $('#' + file.id);
  533. delete percentages[file.id];
  534. updateTotalProgress();
  535. $li.off().find('.file-panel').off().end().remove();
  536. }
  537. function updateTotalProgress() {
  538. var loaded = 0,
  539. total = 0,
  540. spans = $progress.children(),
  541. percent;
  542. $.each(percentages, function (k, v) {
  543. total += v[0];
  544. loaded += v[0] * v[1];
  545. });
  546. percent = total ? loaded / total : 0;
  547. spans.eq(0).text(Math.round(percent * 100) + '%');
  548. spans.eq(1).css('width', Math.round(percent * 100) + '%');
  549. updateStatus();
  550. }
  551. function setState(val, files) {
  552. if (val != state) {
  553. var stats = uploader.getStats();
  554. $upload.removeClass('state-' + state);
  555. $upload.addClass('state-' + val);
  556. switch (val) {
  557. /* 未选择文件 */
  558. case 'pedding':
  559. $queue.addClass('element-invisible');
  560. $statusBar.addClass('element-invisible');
  561. $placeHolder.removeClass('element-invisible');
  562. $progress.hide(); $info.hide();
  563. uploader.refresh();
  564. break;
  565. /* 可以开始上传 */
  566. case 'ready':
  567. $placeHolder.addClass('element-invisible');
  568. $queue.removeClass('element-invisible');
  569. $statusBar.removeClass('element-invisible');
  570. $progress.hide(); $info.show();
  571. $upload.text(lang.uploadStart);
  572. uploader.refresh();
  573. break;
  574. /* 上传中 */
  575. case 'uploading':
  576. $progress.show(); $info.hide();
  577. $upload.text(lang.uploadPause);
  578. break;
  579. /* 暂停上传 */
  580. case 'paused':
  581. $progress.show(); $info.hide();
  582. $upload.text(lang.uploadContinue);
  583. break;
  584. case 'confirm':
  585. $progress.show(); $info.hide();
  586. $upload.text(lang.uploadStart);
  587. stats = uploader.getStats();
  588. if (stats.successNum && !stats.uploadFailNum) {
  589. setState('finish');
  590. return;
  591. }
  592. break;
  593. case 'finish':
  594. $progress.hide(); $info.show();
  595. if (stats.uploadFailNum) {
  596. $upload.text(lang.uploadRetry);
  597. } else {
  598. $upload.text(lang.uploadStart);
  599. }
  600. break;
  601. }
  602. state = val;
  603. updateStatus();
  604. }
  605. if (!_this.getQueueCount()) {
  606. $upload.addClass('disabled')
  607. } else {
  608. $upload.removeClass('disabled')
  609. }
  610. }
  611. function updateStatus() {
  612. var text = '', stats;
  613. if (state === 'ready') {
  614. text = lang.updateStatusReady.replace('_', fileCount).replace('_KB', WebUploader.formatSize(fileSize));
  615. } else if (state === 'confirm') {
  616. stats = uploader.getStats();
  617. if (stats.uploadFailNum) {
  618. text = lang.updateStatusConfirm.replace('_', stats.successNum).replace('_', stats.successNum);
  619. }
  620. } else {
  621. stats = uploader.getStats();
  622. text = lang.updateStatusFinish.replace('_', fileCount).
  623. replace('_KB', WebUploader.formatSize(fileSize)).
  624. replace('_', stats.successNum);
  625. if (stats.uploadFailNum) {
  626. text += lang.updateStatusError.replace('_', stats.uploadFailNum);
  627. }
  628. }
  629. $info.html(text);
  630. }
  631. uploader.on('fileQueued', function (file) {
  632. fileCount++;
  633. fileSize += file.size;
  634. if (fileCount === 1) {
  635. $placeHolder.addClass('element-invisible');
  636. $statusBar.show();
  637. }
  638. addFile(file);
  639. filesArray.push(file);
  640. });
  641. uploader.on('fileDequeued', function (file) {
  642. fileCount--;
  643. fileSize -= file.size;
  644. removeFile(file);
  645. updateTotalProgress();
  646. var k = filesArray.findIndex(function (v) {
  647. return v.id == file.id
  648. });
  649. filesArray.splice(k, 1);
  650. });
  651. uploader.on('filesQueued', function (file) {
  652. if (!uploader.isInProgress() && (state == 'pedding' || state == 'finish' || state == 'confirm' || state == 'ready')) {
  653. setState('ready');
  654. }
  655. updateTotalProgress();
  656. });
  657. uploader.on('all', function (type, files) {
  658. switch (type) {
  659. case 'uploadFinished':
  660. setState('confirm', files);
  661. break;
  662. case 'startUpload':
  663. /* 添加额外的GET参数 */
  664. var params = utils.serializeParam(editor.queryCommandValue('serverparam')) || '',
  665. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?' : '&') + 'encode=utf-8&' + params);
  666. uploader.option('server', url);
  667. setState('uploading', files);
  668. break;
  669. case 'stopUpload':
  670. setState('paused', files);
  671. break;
  672. }
  673. });
  674. uploader.on('uploadBeforeSend', function (file, data, header) {
  675. //这里可以通过data对象添加POST参数
  676. if (actionUrl.toLowerCase().indexOf('jsp') != -1) {
  677. header['X_Requested_With'] = 'XMLHttpRequest';
  678. }
  679. });
  680. uploader.on('uploadProgress', function (file, percentage) {
  681. var $li = $('#' + file.id),
  682. $percent = $li.find('.progress span');
  683. $percent.css('width', percentage * 100 + '%');
  684. percentages[file.id][1] = percentage;
  685. updateTotalProgress();
  686. });
  687. uploader.on('uploadSuccess', function (file, ret) {
  688. var $file = $('#' + file.id);
  689. try {
  690. var responseText = (ret._raw || ret),
  691. json = utils.str2json(responseText);
  692. if (json.state == 'SUCCESS') {
  693. var json = {
  694. 'url': json.url,
  695. 'type': json.type,
  696. 'original': json.original
  697. }
  698. // uploadVideoList.push();
  699. uploadVideoList[$file.index()] = json
  700. $file.append('<span class="success"></span>');
  701. } else {
  702. $file.find('.error').text(json.state).show();
  703. }
  704. } catch (e) {
  705. $file.find('.error').text(lang.errorServerUpload).show();
  706. }
  707. });
  708. uploader.on('uploadError', function (file, code) {
  709. });
  710. uploader.on('error', function (code, file) {
  711. if (code == 'Q_TYPE_DENIED' || code == 'F_EXCEED_SIZE') {
  712. addFile(file);
  713. }
  714. });
  715. uploader.on('uploadComplete', function (file, ret) {
  716. });
  717. $upload.on('click', function () {
  718. if ($(this).hasClass('disabled')) {
  719. return false;
  720. }
  721. // if (state === 'ready') {
  722. // uploader.upload();
  723. // } else if (state === 'paused') {
  724. // uploader.upload();
  725. // } else if (state === 'uploading') {
  726. // uploader.stop();
  727. // }
  728. let uploadAction = editor.getOpt("uploadService")(_this, editor).Upload();
  729. let Fast = editor.getOpt("uploadService")(_this, editor).Fast();
  730. //替换上传方法
  731. var filesObj = filesArray;
  732. for (var i = 0; i < filesObj.length; i++) {
  733. (function (j) {
  734. var file = filesObj[j];
  735. var id = filesObj[j].id;
  736. var name = filesObj[j].name;
  737. uploadAction.api.send(file.source.source, function (data) {
  738. var json = {
  739. url: Fast.api.cdnurl(data.url, true),
  740. state: "SUCCESS",
  741. title: name
  742. };
  743. // editor.fireEvent("video.file.success", id, pic, file);
  744. var $file = $('#' + id);
  745. // uploadVideoList.push(pic);
  746. uploadVideoList[$file.index()] = json
  747. $file.append('<span class="success"></span>');
  748. uploader.skipFile(file);
  749. var $li = $('#' + file.id),
  750. $percent = $li.find('.progress span');
  751. $percent.css('width', 1 * 100 + '%');
  752. percentages[file.id][1] = 1;
  753. updateTotalProgress();
  754. setState('confirm');
  755. });
  756. })(i);
  757. }
  758. });
  759. $upload.addClass('state-' + state);
  760. updateTotalProgress();
  761. },
  762. getQueueCount: function () {
  763. var file, i, status, readyFile = 0, files = this.uploader.getFiles();
  764. for (i = 0; file = files[i++];) {
  765. status = file.getStatus();
  766. if (status == 'queued' || status == 'uploading' || status == 'progress') readyFile++;
  767. }
  768. return readyFile;
  769. },
  770. refresh: function () {
  771. this.uploader.refresh();
  772. }
  773. };
  774. })();