UNPKG

cckj-util

Version:

A common util lib for cj

724 lines (675 loc) 36.4 kB
/** * cj 前端公用库 * 19-05-11 * Author@草鞋没号 [https://github.com/caoxiemeihao] */ ; (function (window) { /** https://cdn.bootcss.com/node-uuid/1.4.8/uuid.min.js */ ; !function (n) { "use strict"; function e() { var e = n.crypto || n.msCrypto; if (!f && e && e.getRandomValues) try { var r = new Uint8Array(16); s = f = function () { return e.getRandomValues(r), r }, f() } catch (n) { } if (!f) { var o = new Array(16); i = f = function () { for (var n, e = 0; e < 16; e++)0 === (3 & e) && (n = 4294967296 * Math.random()), o[e] = n >>> ((3 & e) << 3) & 255; return o }, "undefined" != typeof console && console.warn && console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()") } } function r() { if ("function" == typeof require) try { var n = require("crypto").randomBytes; c = f = n && function () { return n(16) }, f() } catch (n) { } } function o(n, e, r) { var o = e && r || 0, t = 0; for (e = e || [], n.toLowerCase().replace(/[0-9a-f]{2}/g, function (n) { t < 16 && (e[o + t++] = y[n]) }); t < 16;)e[o + t++] = 0; return e } function t(n, e) { var r = e || 0, o = v; return o[n[r++]] + o[n[r++]] + o[n[r++]] + o[n[r++]] + "-" + o[n[r++]] + o[n[r++]] + "-" + o[n[r++]] + o[n[r++]] + "-" + o[n[r++]] + o[n[r++]] + "-" + o[n[r++]] + o[n[r++]] + o[n[r++]] + o[n[r++]] + o[n[r++]] + o[n[r++]] } function u(n, e, r) { var o = e && r || 0, u = e || []; n = n || {}; var a = null != n.clockseq ? n.clockseq : g, f = null != n.msecs ? n.msecs : (new Date).getTime(), i = null != n.nsecs ? n.nsecs : C + 1, c = f - h + (i - C) / 1e4; if (c < 0 && null == n.clockseq && (a = a + 1 & 16383), (c < 0 || f > h) && null == n.nsecs && (i = 0), i >= 1e4) throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); h = f, C = i, g = a, f += 122192928e5; var s = (1e4 * (268435455 & f) + i) % 4294967296; u[o++] = s >>> 24 & 255, u[o++] = s >>> 16 & 255, u[o++] = s >>> 8 & 255, u[o++] = 255 & s; var l = f / 4294967296 * 1e4 & 268435455; u[o++] = l >>> 8 & 255, u[o++] = 255 & l, u[o++] = l >>> 24 & 15 | 16, u[o++] = l >>> 16 & 255, u[o++] = a >>> 8 | 128, u[o++] = 255 & a; for (var d = n.node || w, v = 0; v < 6; v++)u[o + v] = d[v]; return e ? e : t(u) } function a(n, e, r) { var o = e && r || 0; "string" == typeof n && (e = "binary" === n ? new d(16) : null, n = null), n = n || {}; var u = n.random || (n.rng || f)(); if (u[6] = 15 & u[6] | 64, u[8] = 63 & u[8] | 128, e) for (var a = 0; a < 16; a++)e[o + a] = u[a]; return e || t(u) } var f, i, c, s, l; n ? e() : r(); for (var d = "function" == typeof Buffer ? Buffer : Array, v = [], y = {}, m = 0; m < 256; m++)v[m] = (m + 256).toString(16).substr(1), y[v[m]] = m; var p = f(), w = [1 | p[0], p[1], p[2], p[3], p[4], p[5]], g = 16383 & (p[6] << 8 | p[7]), h = 0, C = 0, R = a; R.v1 = u, R.v4 = a, R.parse = o, R.unparse = t, R.BufferClass = d, R._rng = f, R._mathRNG = i, R._nodeRNG = c, R._whatwgRNG = s, "undefined" != typeof module && module.exports ? module.exports = R : "function" == typeof define && define.amd ? define(function () { return R }) : (l = n.utils_uuid, R.noConflict = function () { return n.utils_uuid = l, R }, n.utils_uuid = R) }("undefined" != typeof window ? window : null); /** https://github.com/blueimp/JavaScript-MD5 */ ; !function (n) { "use strict"; function t(n, t) { var r = (65535 & n) + (65535 & t); return (n >> 16) + (t >> 16) + (r >> 16) << 16 | 65535 & r } function r(n, t) { return n << t | n >>> 32 - t } function e(n, e, o, u, c, f) { return t(r(t(t(e, n), t(u, f)), c), o) } function o(n, t, r, o, u, c, f) { return e(t & r | ~t & o, n, t, u, c, f) } function u(n, t, r, o, u, c, f) { return e(t & o | r & ~o, n, t, u, c, f) } function c(n, t, r, o, u, c, f) { return e(t ^ r ^ o, n, t, u, c, f) } function f(n, t, r, o, u, c, f) { return e(r ^ (t | ~o), n, t, u, c, f) } function i(n, r) { n[r >> 5] |= 128 << r % 32, n[14 + (r + 64 >>> 9 << 4)] = r; var e, i, a, d, h, l = 1732584193, g = -271733879, v = -1732584194, m = 271733878; for (e = 0; e < n.length; e += 16)i = l, a = g, d = v, h = m, g = f(g = f(g = f(g = f(g = c(g = c(g = c(g = c(g = u(g = u(g = u(g = u(g = o(g = o(g = o(g = o(g, v = o(v, m = o(m, l = o(l, g, v, m, n[e], 7, -680876936), g, v, n[e + 1], 12, -389564586), l, g, n[e + 2], 17, 606105819), m, l, n[e + 3], 22, -1044525330), v = o(v, m = o(m, l = o(l, g, v, m, n[e + 4], 7, -176418897), g, v, n[e + 5], 12, 1200080426), l, g, n[e + 6], 17, -1473231341), m, l, n[e + 7], 22, -45705983), v = o(v, m = o(m, l = o(l, g, v, m, n[e + 8], 7, 1770035416), g, v, n[e + 9], 12, -1958414417), l, g, n[e + 10], 17, -42063), m, l, n[e + 11], 22, -1990404162), v = o(v, m = o(m, l = o(l, g, v, m, n[e + 12], 7, 1804603682), g, v, n[e + 13], 12, -40341101), l, g, n[e + 14], 17, -1502002290), m, l, n[e + 15], 22, 1236535329), v = u(v, m = u(m, l = u(l, g, v, m, n[e + 1], 5, -165796510), g, v, n[e + 6], 9, -1069501632), l, g, n[e + 11], 14, 643717713), m, l, n[e], 20, -373897302), v = u(v, m = u(m, l = u(l, g, v, m, n[e + 5], 5, -701558691), g, v, n[e + 10], 9, 38016083), l, g, n[e + 15], 14, -660478335), m, l, n[e + 4], 20, -405537848), v = u(v, m = u(m, l = u(l, g, v, m, n[e + 9], 5, 568446438), g, v, n[e + 14], 9, -1019803690), l, g, n[e + 3], 14, -187363961), m, l, n[e + 8], 20, 1163531501), v = u(v, m = u(m, l = u(l, g, v, m, n[e + 13], 5, -1444681467), g, v, n[e + 2], 9, -51403784), l, g, n[e + 7], 14, 1735328473), m, l, n[e + 12], 20, -1926607734), v = c(v, m = c(m, l = c(l, g, v, m, n[e + 5], 4, -378558), g, v, n[e + 8], 11, -2022574463), l, g, n[e + 11], 16, 1839030562), m, l, n[e + 14], 23, -35309556), v = c(v, m = c(m, l = c(l, g, v, m, n[e + 1], 4, -1530992060), g, v, n[e + 4], 11, 1272893353), l, g, n[e + 7], 16, -155497632), m, l, n[e + 10], 23, -1094730640), v = c(v, m = c(m, l = c(l, g, v, m, n[e + 13], 4, 681279174), g, v, n[e], 11, -358537222), l, g, n[e + 3], 16, -722521979), m, l, n[e + 6], 23, 76029189), v = c(v, m = c(m, l = c(l, g, v, m, n[e + 9], 4, -640364487), g, v, n[e + 12], 11, -421815835), l, g, n[e + 15], 16, 530742520), m, l, n[e + 2], 23, -995338651), v = f(v, m = f(m, l = f(l, g, v, m, n[e], 6, -198630844), g, v, n[e + 7], 10, 1126891415), l, g, n[e + 14], 15, -1416354905), m, l, n[e + 5], 21, -57434055), v = f(v, m = f(m, l = f(l, g, v, m, n[e + 12], 6, 1700485571), g, v, n[e + 3], 10, -1894986606), l, g, n[e + 10], 15, -1051523), m, l, n[e + 1], 21, -2054922799), v = f(v, m = f(m, l = f(l, g, v, m, n[e + 8], 6, 1873313359), g, v, n[e + 15], 10, -30611744), l, g, n[e + 6], 15, -1560198380), m, l, n[e + 13], 21, 1309151649), v = f(v, m = f(m, l = f(l, g, v, m, n[e + 4], 6, -145523070), g, v, n[e + 11], 10, -1120210379), l, g, n[e + 2], 15, 718787259), m, l, n[e + 9], 21, -343485551), l = t(l, i), g = t(g, a), v = t(v, d), m = t(m, h); return [l, g, v, m] } function a(n) { var t, r = "", e = 32 * n.length; for (t = 0; t < e; t += 8)r += String.fromCharCode(n[t >> 5] >>> t % 32 & 255); return r } function d(n) { var t, r = []; for (r[(n.length >> 2) - 1] = void 0, t = 0; t < r.length; t += 1)r[t] = 0; var e = 8 * n.length; for (t = 0; t < e; t += 8)r[t >> 5] |= (255 & n.charCodeAt(t / 8)) << t % 32; return r } function h(n) { return a(i(d(n), 8 * n.length)) } function l(n, t) { var r, e, o = d(n), u = [], c = []; for (u[15] = c[15] = void 0, o.length > 16 && (o = i(o, 8 * n.length)), r = 0; r < 16; r += 1)u[r] = 909522486 ^ o[r], c[r] = 1549556828 ^ o[r]; return e = i(u.concat(d(t)), 512 + 8 * t.length), a(i(c.concat(e), 640)) } function g(n) { var t, r, e = ""; for (r = 0; r < n.length; r += 1)t = n.charCodeAt(r), e += "0123456789abcdef".charAt(t >>> 4 & 15) + "0123456789abcdef".charAt(15 & t); return e } function v(n) { return unescape(encodeURIComponent(n)) } function m(n) { return h(v(n)) } function p(n) { return g(m(n)) } function s(n, t) { return l(v(n), v(t)) } function C(n, t) { return g(s(n, t)) } function A(n, t, r) { return t ? r ? s(t, n) : C(t, n) : r ? m(n) : p(n) } "function" == typeof define && define.amd ? define(function () { return A }) : "object" == typeof module && module.exports ? module.exports = A : n.utils_md5 = A }(this); //# sourceMappingURL=md5.min.js.map /** https://github.com/dankogai/js-base64 */ ; (function (global, factory) { typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory(global) : typeof define === "function" && define.amd ? define(factory) : factory(global) })(typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : this, function (global) { "use strict"; var _Base64 = global.utils_Base64; var version = "2.5.0"; var buffer; if (typeof module !== "undefined" && module.exports) { try { buffer = eval("require('buffer').Buffer") } catch (err) { buffer = undefined } } var b64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var b64tab = function (bin) { var t = {}; for (var i = 0, l = bin.length; i < l; i++)t[bin.charAt(i)] = i; return t }(b64chars); var fromCharCode = String.fromCharCode; var cb_utob = function (c) { if (c.length < 2) { var cc = c.charCodeAt(0); return cc < 128 ? c : cc < 2048 ? fromCharCode(192 | cc >>> 6) + fromCharCode(128 | cc & 63) : fromCharCode(224 | cc >>> 12 & 15) + fromCharCode(128 | cc >>> 6 & 63) + fromCharCode(128 | cc & 63) } else { var cc = 65536 + (c.charCodeAt(0) - 55296) * 1024 + (c.charCodeAt(1) - 56320); return fromCharCode(240 | cc >>> 18 & 7) + fromCharCode(128 | cc >>> 12 & 63) + fromCharCode(128 | cc >>> 6 & 63) + fromCharCode(128 | cc & 63) } }; var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g; var utob = function (u) { return u.replace(re_utob, cb_utob) }; var cb_encode = function (ccc) { var padlen = [0, 2, 1][ccc.length % 3], ord = ccc.charCodeAt(0) << 16 | (ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8 | (ccc.length > 2 ? ccc.charCodeAt(2) : 0), chars = [b64chars.charAt(ord >>> 18), b64chars.charAt(ord >>> 12 & 63), padlen >= 2 ? "=" : b64chars.charAt(ord >>> 6 & 63), padlen >= 1 ? "=" : b64chars.charAt(ord & 63)]; return chars.join("") }; var btoa = global.btoa ? function (b) { return global.btoa(b) } : function (b) { return b.replace(/[\s\S]{1,3}/g, cb_encode) }; var _encode = buffer ? buffer.from && Uint8Array && buffer.from !== Uint8Array.from ? function (u) { return (u.constructor === buffer.constructor ? u : buffer.from(u)).toString("base64") } : function (u) { return (u.constructor === buffer.constructor ? u : new buffer(u)).toString("base64") } : function (u) { return btoa(utob(u)) }; var encode = function (u, urisafe) { return !urisafe ? _encode(String(u)) : _encode(String(u)).replace(/[+\/]/g, function (m0) { return m0 == "+" ? "-" : "_" }).replace(/=/g, "") }; var encodeURI = function (u) { return encode(u, true) }; var re_btou = new RegExp(["[À-ß][€-¿]", "[à-ï][€-¿]{2}", "[ð-÷][€-¿]{3}"].join("|"), "g"); var cb_btou = function (cccc) { switch (cccc.length) { case 4: var cp = (7 & cccc.charCodeAt(0)) << 18 | (63 & cccc.charCodeAt(1)) << 12 | (63 & cccc.charCodeAt(2)) << 6 | 63 & cccc.charCodeAt(3), offset = cp - 65536; return fromCharCode((offset >>> 10) + 55296) + fromCharCode((offset & 1023) + 56320); case 3: return fromCharCode((15 & cccc.charCodeAt(0)) << 12 | (63 & cccc.charCodeAt(1)) << 6 | 63 & cccc.charCodeAt(2)); default: return fromCharCode((31 & cccc.charCodeAt(0)) << 6 | 63 & cccc.charCodeAt(1)) } }; var btou = function (b) { return b.replace(re_btou, cb_btou) }; var cb_decode = function (cccc) { var len = cccc.length, padlen = len % 4, n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0) | (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0) | (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0) | (len > 3 ? b64tab[cccc.charAt(3)] : 0), chars = [fromCharCode(n >>> 16), fromCharCode(n >>> 8 & 255), fromCharCode(n & 255)]; chars.length -= [0, 0, 2, 1][padlen]; return chars.join("") }; var _atob = global.atob ? function (a) { return global.atob(a) } : function (a) { return a.replace(/\S{1,4}/g, cb_decode) }; var atob = function (a) { return _atob(String(a).replace(/[^A-Za-z0-9\+\/]/g, "")) }; var _decode = buffer ? buffer.from && Uint8Array && buffer.from !== Uint8Array.from ? function (a) { return (a.constructor === buffer.constructor ? a : buffer.from(a, "base64")).toString() } : function (a) { return (a.constructor === buffer.constructor ? a : new buffer(a, "base64")).toString() } : function (a) { return btou(_atob(a)) }; var decode = function (a) { return _decode(String(a).replace(/[-_]/g, function (m0) { return m0 == "-" ? "+" : "/" }).replace(/[^A-Za-z0-9\+\/]/g, "")) }; var noConflict = function () { var Base64 = global.utils_Base64; global.utils_Base64 = _Base64; return Base64 }; global.utils_Base64 = { VERSION: version, atob: atob, btoa: btoa, fromBase64: decode, toBase64: encode, utob: utob, encode: encode, encodeURI: encodeURI, btou: btou, decode: decode, noConflict: noConflict, __buffer__: buffer }; if (typeof Object.defineProperty === "function") { var noEnum = function (v) { return { value: v, enumerable: false, writable: true, configurable: true } }; global.utils_Base64.extendString = function () { Object.defineProperty(String.prototype, "fromBase64", noEnum(function () { return decode(this) })); Object.defineProperty(String.prototype, "toBase64", noEnum(function (urisafe) { return encode(this, urisafe) })); Object.defineProperty(String.prototype, "toBase64URI", noEnum(function () { return encode(this, true) })) } } if (global["Meteor"]) { Base64 = global.utils_Base64 } if (typeof module !== "undefined" && module.exports) { module.exports.Base64 = global.utils_Base64 } else if (typeof define === "function" && define.amd) { define([], function () { return global.utils_Base64 }) } return { Base64: global.utils_Base64 } }); var cjUtils = { md5: utils_md5, Base64: utils_Base64, uuid: utils_uuid, }; cjUtils.ajax = ({ url, success, data, failed, type = 'POST', hearders = {} }) => { var xhr = new XMLHttpRequest() var _url = url xhr.onload = () => { if (xhr.status === 200 || xhr.status === 304) { success(cjUtils.JSONparse(xhr.responseText) || {}) } else { failed(xhr) } } if (type.toUpperCase() === 'GET') { let params = []; for (let k in data) { params.push(`${k}=${data[k]}`) } _url = `${_url}?${params.join('&')}&v=${Date.now()}` } xhr.open(type, _url) for (let k in hearders) { xhr.setRequestHeader(k, hearders[k]) } xhr.setRequestHeader("Content-type", "application/json") // console.log(JSON.stringify(Object.assign({}, data))) xhr.send(JSON.stringify(Object.assign({}, data))) }; /** * 安全的 JSON.parse 😀 [解析失败返回null] * @param jsonStr JSON字符串 */ cjUtils.JSONparse = function (jsonStr) { let ret = null try { ret = JSON.parse(jsonStr) } catch (e) { console.warn('JSON.parse() error\n------------------\n', jsonStr + '\n------------------\n', e) } finally { return ret } }; /** https前缀 */ cjUtils.httpsPrefix = function (url) { let _url = url try { _url = (url.startsWith('http') ? url : 'https://' + url).replace(/$http(s?)/, 'https'); } catch (e) { console.warn(e) } return _url }; /** * 阿里云图片大小处理[oss服务器自带] * @param {String} url 图片链接 * @param {JSON} options 处理参数 [w]、[h] * 文档链接 [https://help.aliyun.com/document_detail/44688.html] * 示例结果 https://cc-west-usa.oss-us-west-1.aliyuncs.com/15330528/2076770670210.jpg?x-oss-process=image/resize,m_fill,w_200,h_200 * @return [柯里化(urry)] */ cjUtils.imageSizeProcess = function (options = {}) { let param = `?x-oss-process=image/resize` , paramLen = 0 for (let k in options) { param += `,${k}_${options[k]}` paramLen++ } return url => cjUtils.httpsPrefix(url) + ( paramLen > 1 ? param + ',m_fill' // 固定宽高,将延伸出指定w与h的矩形框外的最小图片进行居中裁剪 : param + ',m_lfit' // 等比缩放,限制在指定w与h的矩形内的最大图片 ) } /** * 读取本地图片,文件 * [默认读取图片] * 返回 Promise,支持回调 */ cjUtils.readLocalFile = function ({ accept = 'image/*', success, failed }) { return new Promise((resolve, rejcet) => { let oInput = document.createElement('input') oInput.type = 'file' oInput.accept = accept oInput.multiple = 'multiple' oInput.onchange = ev => { if (accept.includes('image')) { cjUtils.readIMG2base64({ imgFiles: ev.target.files }).then(res => { resolve(res) success && success(res) }) } else { resolve(ev.target.files) success && success(ev.target.files) } } oInput.click() }) } /** * 图片读取,转换base64 * 返回 Promise,支持回调 * @return { * FileList: Files -> input 原生读取的 FileList,原样返回 * FileArr: [] -> 读取结果 * } */ cjUtils.readIMG2base64 = function ({ imgFiles, success, failed }) { return new Promise((resolve, reject) => { let idx = 0 , res = { FileList: imgFiles, // input 原生读取的 FileList FileArr: [] // 读取结果 } , reader = new FileReader() , readFile = file => { reader.onerror = err => console.warn(`--------文件读取出错\n`, err, `\n--------`) // reader.onprogress = ev => console.log(`${~~(ev.loaded / ev.total * 100)} % `) reader.onload = ev => { res.FileArr.push({ base64: ev.target.result, // 图片base64编码 file, // 图片本身 index: idx, lastModified: file.lastModified, name: file.name, size: file.size, type: file.type }) idx++ if (imgFiles[idx]) { readFile(imgFiles[idx]) } else { resolve(res) success && success(res) } } reader.readAsDataURL(file) } imgFiles.length ? readFile(imgFiles[idx]) // 单个 : readFile(imgFiles) // 多图 }) }; /** upload image to 阿里云 OSS server */ cjUtils.uploadFileToOSS = function ({ file, signatureURL, success, failed, callback }) { return new Promise(async (resolve, reject) => { if (!(file instanceof File)) { console.error('非文件') reject(`Not a valid file.`) failed && failed(`Not a valid file.`) return } let authorizedSignature , expired = 30 * 1000 // AliOSS 过期时间,实测 30秒 [原计划计划10分钟] , sessionField = 'oss-authorized-signature' , startUpload = ({ accessid, host, policy, signature, code }) => { if (code !== '200') { console.error(`OSS Token 请求失败`) reject(`OSS Token 请求失败`) failed && failed(`OSS Token 请求失败`) return } let formData = new FormData() let fileName = `${cjUtils.uuid.v4() + file.name.substr(file.name.lastIndexOf('.'))}` if (callback instanceof Function) { fileName = callback('filename', fileName); } formData.append('key', fileName) // 唯一文件名 formData.append('policy', policy) // policy formData.append('OSSAccessKeyId', accessid) // accessKeyId formData.append('success_action_status', '200') // 成功后返回的操作码 formData.append('Signature', signature) // 鉴权签名 formData.append('file', file) /** * 图片上传至阿里云 OSS * fetch 参考链接 [https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch] * http.post(host, formData, { headers: { 'Content-Type': 'multipart/form-data' } }) // 可用 * @return [注意,没有返回值,code==200就是成功] */ window.fetch(host, { method: 'POST', body: formData }) .then(_ => { resolve(`${host}/${fileName}`) success && success(`${host}/${fileName}`) }) } try { authorizedSignature = JSON.parse(window.sessionStorage.getItem(sessionField)) || {} } catch (e) { authorizedSignature = {} } if ( (!authorizedSignature.signature) // 没有签名 || (Date.now() - authorizedSignature.timestamp > expired) // 签名过期 ) { cjUtils.ajax({ url: signatureURL, success(authorizedSignature) { authorizedSignature.timestamp = Date.now() window.sessionStorage.setItem(sessionField, JSON.stringify(authorizedSignature)) startUpload(authorizedSignature) } }) } else { startUpload(authorizedSignature) } }) }; //下载视频 cjUtils.downloadVideo = function ({ videoId = '', sourceUrl = '', videoName = 'cjVideos' }) { if (videoId) { cjUtils.ajax({ url: 'https://tools.cjdropshipping.com/tool/downLoad/getVideoPlayInfos', data: { videoId }, failed: () => { }, type: 'GET', hearders: { token: "" }, success: list => { list = list.filter(item => !item.playURL.includes('.m3u8') && !item.watermarkId) let playUrl if (list && list.length > 0) { playUrl = list[0].playURL } if (!playUrl) {//获取原视频链接 cjUtils.ajax({ url: 'https://tools.cjdropshipping.com/tool/downLoad/getVideoInfo', data: { videoId }, failed: () => { }, type: 'GET', hearders: { token: "" }, success: ({ fileURL }) => { downloadVideoFn(fileURL, videoName) } }) } else { downloadVideoFn(playUrl, videoName) } } }) } else if (sourceUrl) { downloadVideoFn(sourceUrl, videoName) } } function downloadVideoFn(playUrl, videoName) { const url = `https://tools.cjdropshipping.com/tool/downLoad/file?urlStr=${playUrl}&fileName=${videoName}${playUrl.slice(playUrl.lastIndexOf('.'))}` let aElement = document.createElement('a') document.body.appendChild(aElement) aElement.style.display = 'none' aElement.href = url aElement.download = '' aElement.click(); document.body.removeChild(aElement) } //播放视屏前获取视频流信息 cjUtils.getVideoInfo = function ({ eleId, videoId = '', configuration = {}, sourceUrl = "", callback = () => { }, hasWater = true }) { const { width = '240px', height = '136px', autoplay = false, isLive = false, rePlay = false, playsinline = true, preload = true, cover = ' ' } = configuration let params = { eleId, configuration: { width, height, autoplay, isLive, rePlay, playsinline, preload, cover }, callback } if (sourceUrl) { cjUtils.AccessVideo(Object.assign({ sourceUrl }, params)) } else if (videoId) { cjUtils.ajax({ url: 'https://tools.cjdropshipping.com/tool/downLoad/getVideoPlayInfos', data: { videoId }, failed: () => { }, type: 'GET', hearders: { token: "" }, success: list => { list = list.filter(item => !item.playURL.includes('.m3u8')) let playUrl = '' //无水印视频 , waterPlayUrl = '' //有水印视频 list.forEach(item => { if (item.watermarkId) { waterPlayUrl = item.playURL } else { playUrl = item.playURL } }) // console.log('无水印 =>', playUrl, '有水印 =>', waterPlayUrl, '是否需要水印 =>', hasWater ) if (hasWater) { //需要有水印视频 cjUtils.AccessVideo(Object.assign({ sourceUrl: waterPlayUrl }, params)) } else { //不需要水印 if (!playUrl) { //老视频没有转码过后的无水印视频,需要获取原视频地址 cjUtils.ajax({ url: 'https://tools.cjdropshipping.com/tool/downLoad/getVideoInfo', data: { videoId }, failed: () => { }, type: 'GET', hearders: { token: "" }, success: ({ fileURL }) => { // console.log('原视频地址 =>', fileURL) cjUtils.AccessVideo(Object.assign({ sourceUrl: fileURL }, params)) } }) } else { cjUtils.AccessVideo(Object.assign({ sourceUrl: playUrl }, params)) } } } }) } } //播放视频 cjUtils.AccessVideo = function ({ eleId, videoId = "", playAuth = '', getPlayAuthUrl = '', sourceUrl = '', configuration = {}, token = "", callback }) { let player , _obj = Object.assign({ language: "en-us", id: eleId, "controlBarVisibility": "hover", "definition ": 'FD,LD,SD,HD', "skinLayout": [ { "name": "bigPlayButton", "align": "blabs", "x": 30, "y": 80 }, { "name": "H5Loading", "align": "cc" }, { "name": "errorDisplay", "align": "tlabs", "x": 0, "y": 0 }, { "name": "infoDisplay" }, { "name": "tooltip", "align": "blabs", "x": 0, "y": 56 }, { "name": "thumbnail" }, { "name": "controlBar", "align": "blabs", "x": 0, "y": 0, "children": [ { "name": "progress", "align": "blabs", "x": 0, "y": 44 }, { "name": "playButton", "align": "tl", "x": 15, "y": 12 }, { "name": "timeDisplay", "align": "tl", "x": 10, "y": 7 }, { "name": "fullScreenButton", "align": "tr", "x": 10, "y": 12 }, { "name": "setting", "align": "tr", "x": 15, "y": 12 }, { "name": "volume", "align": "tr", "x": 5, "y": 10 } ] } ], }, configuration) if (playAuth) { player = new Aliplayer(Object.assign({ hvid: videoId, playauth: playAut }, _obj), function (player) { }) callback(player) } else if (sourceUrl) { player = new Aliplayer(Object.assign({ source: sourceUrl }, _obj), function (player) { }) callback(player) } else if (getPlayAuthUrl) { cjUtils.ajax({ url: getPlayAuthUrl, data: { videoId }, failed: function () { }, type: 'GET', hearders: { token }, success: res => { player = new Aliplayer(Object.assign({ vid: videoId, playauth: res.playAuth }, _obj), function (player) { }) callback(player) } }) } }; //上传视频 cjUtils.createUploader = function ({ url, type, addFileSuccessFn, onUploadProgress, success, error, onUploadEnd }) { let createUrl = url , uploader = new AliyunUpload.Vod({ timeout: 60000, partSize: 1048576, parallel: 5, retryCount: 3, retryDuration: 2, region: 'cn-shanghai', userId: '1654317246160868', // 添加文件成功 addFileSuccess: function (uploadInfo) { // console.log('addFileSuccess') addFileSuccessFn({ uploadInfo }) }, // 开始上传 onUploadstarted: function (uploadInfo) { // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法 // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值,调用点播的不同接口获取uploadauth和uploadAddress // 如果 uploadInfo.videoId 有值,调用刷新视频上传凭证接口,否则调用创建视频上传凭证接口 // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html) // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html) if (!uploadInfo.videoId) { // var createUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateUploadVideo?Title=testvod1&FileName=aa.mp4&BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&VideoId=5bfcc7864fc14b96972842172207c9e6' let sendData = { type, fileName: uploadInfo.file.name, title: '123' } cjUtils.ajax({ url: createUrl, success: res => { // console.log(res) var uploadAuth = res.result.UploadAuth var uploadAddress = res.result.UploadAddress var videoId = res.result.VideoId uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId) }, data: sendData, failed: function () { }, type: 'GET' }) } else { let sendData = { type: 2, videoId: uploadInfo.videoId }; // 如果videoId有值,根据videoId刷新上传凭证 cjUtils.ajax({ url: createUrl, success: res => { // console.log(res) var uploadAuth = res.result.UploadAuth var uploadAddress = res.result.UploadAddress var videoId = uploadInfo.videoId uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId) }, data: sendData, failed: function () { }, type: 'GET' }); } }, // 文件上传成功 onUploadSucceed: function (uploadInfo) { success({ uploadInfo }) }, // 文件上传失败 onUploadFailed: function (uploadInfo, code, message) { error({ uploadInfo, code, message }) // $('#status').text('文件上传失败!') }, // 取消文件上传 onUploadCanceled: function (uploadInfo, code, message) { // console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message) $('#status').text('文件上传已暂停!') }, // 文件上传进度,单位:字节, 可以在这个函数中拿到上传进度并显示在页面上 onUploadProgress: function (uploadInfo, totalSize, progress) { onUploadProgress({ uploadInfo, totalSize, progress }) }, // 上传凭证超时 onUploadTokenExpired: function (uploadInfo) { // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时 // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth // let refreshUrl = 'https://vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId //http://vod.cn-shanghai.aliyuncs.com/?Action=RefreshUploadVideo&VideoId=93ab850b4f6f44eab54b6e91d24d81d4&Format=JSON&<公共参数>、 let sendData = { type: 2, videoId: uploadInfo.videoId } cjUtils.ajax({ url: createUrl, success: res => { // console.log(res) var uploadAuth = res.result.UploadAuth var uploadAddress = res.result.UploadAddress var videoId = res.result.VideoId uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId) }, data: sendData, failed: function () { }, type: 'GET' }) }, // 全部文件上传结束 onUploadEnd: function (uploadInfo) { onUploadEnd({ uploadInfo }) // $('#status').text('文件上传完毕!') } }) return uploader } /** * 获取文件流导出文件 responseType:'blob' * @param {Object} data 文件流对象输入 * @param {String} name 文件类型 */ cjUtils.exportFile = function (data, name) { if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(data, name) } else { const blob = new Blob([data]) const elink = document.createElement('a') elink.download = name elink.style.display = 'none' // eslint-disable-next-line compat/compat elink.href = URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() // eslint-disable-next-line compat/compat URL.revokeObjectURL(elink.href) document.body.removeChild(elink) } } /** * 获取聊天链接 * @param {String} cookie 当前域名下所含的cookie * @param {String} env 需要返回的聊天链接环境 * @param {String} domain 聊天所在项目的域名 */ cjUtils.getChatUrl = function (options = {}) { const { cookie = document.cookie, env = 'dev', domain = document.domain } = options let cjLoginName = '', cjLoginToken = '', temchattoken = '', temchatname = '' if (cookie) { const cookieList = cookie.split('; ') cookieList.forEach(_cookie => { const variate = _cookie.split('=') switch (variate[0]) { case 'cjLoginToken': cjLoginToken = variate[1] break case 'cjLoginName': cjLoginName = variate[1] break case 'asj_temchatname': temchatname = variate[1] break case 'asj_temchattoken': temchattoken = variate[1] break } }) } const envList = { dev: 'http://chat.test.com/index.html', test: 'http://chat.test.com/index.html', prod: 'https://chat.cjdropshipping.com/index.html' } const chatIp = envList[env] let chatUrl if (cjLoginToken) { //当cjLoginToken存在时,cj已登录 chatUrl = `${chatIp}?user=${cjLoginName}&token=${cjLoginToken}&logincj=1&brand=CJDropShipping&domain=${domain}#/chat/client` } else if (cjLoginName) { //cjLoginToken不存在,但是cjLoginName存在,说明临时客户注册时填写了邮箱已被注册的邮箱,直接在聊天验证了cj账号,记录了cj登录名 chatUrl = `${chatIp}?user=${cjLoginName}&token=123&logincj=1&brand=CJDropShipping&domain=${domain}#/chat/client` } else if (temchattoken && temchatname) { //临时账号token和登录名存在的情况下 chatUrl = `${chatIp}?user=${temchatname}&token=${temchattoken}&temcachefrompage=1&brand=CJDropShipping&domain=${domain}#/chat/client` } else { chatUrl = `${chatIp}?inpage=2&domain=${domain}&brand=CJDropShipping#/chat/openChat` } return chatUrl } /** * 剪切板读取写入 * const clipboard = new Clipboard();//创建实例 clipboard.get().then(text => ).catch(reason => )//获取剪切板 内容 clipboard.set(value).then(res => ).catch(reason => )//设置剪切板 内容 clipboard.action(res => res).catch(message => layer(message))//获取剪切板 内容 并执行回调函数 如果无效 则 走catch msg为错误信息`; */ class Clipboard { constructor() { this.browserNeedUpdate = navigator.clipboard === undefined;//不存在此api 浏览器 须升级 this.errMsg = '浏览器不兼容 请升级'; this.desc = `使用说明 const clipboard = new Clipboard();//创建实例 clipboard.get().then(text => ).catch(reason => )//获取剪切板 内容 clipboard.set(value).then(res => ).catch(reason => )//设置剪切板 内容 clipboard.action(res => res).catch(message => layer(message))//获取剪切板 内容 并执行回调函数 如果无效 则 走catch msg为错误信息`; } get() { if (this.browserNeedUpdate) return Promise.reject(this.errorModel()) return new Promise((resolve, reject) => { navigator.clipboard.readText() .then(text => { const res = this.successModel('ok', text) resolve(res) // console.log('readText --->> ', text); }) .catch(err => { // console.log('readText failed', err); reject(this.errorModel(err.message, err)) }); }) } set(val = '') { if (this.browserNeedUpdate) return Promise.reject(this.errorModel()) return new Promise((resolve, reject) => { navigator.clipboard.writeText(val) .then(() => { // console.log('writeText success'); const res = this.successModel() resolve(res) }) .catch(err => { // console.log('writeText failed', err); reject(this.errorModel('writeText failed', err)) }); }) } successModel(message, result = null) { message = message || 'ok'; return { code: 0, message, result } } errorModel(message, result = null) { message = message || this.errMsg; return { code: -1, message, result } } help() { console.log(this.desc) } action(cb) { if (typeof cb !== 'function') return Promise.reject('传入参数必须为 回调函数'); return new Promise((_, reject) => { this.get().then(({ result }) => cb(result)).catch((reason) => reject(reason.message || 'failed')) }) } } cjUtils.Clipboard = Clipboard; window.cjUtils = cjUtils; }(window));