-
-
Save Last-Order/82dba13f3696062697f415f0249a149c to your computer and use it in GitHub Desktop.
test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var hexcase = 0 | |
, b64pad = "="; | |
function b64_hmac_sha1(k, d) { | |
return rstr2b64(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))) | |
} | |
function rstr_sha1(s) { | |
return binb2rstr(binb_sha1(rstr2binb(s), 8 * s.length)) | |
} | |
function rstr_hmac_sha1(key, data) { | |
var bkey = rstr2binb(key); | |
16 < bkey.length && (bkey = binb_sha1(bkey, 8 * key.length)); | |
for (var ipad = Array(16), opad = Array(16), i = 0; i < 16; i++) | |
ipad[i] = 909522486 ^ bkey[i], | |
opad[i] = 1549556828 ^ bkey[i]; | |
var hash = binb_sha1(ipad.concat(rstr2binb(data)), 512 + 8 * data.length); | |
return binb2rstr(binb_sha1(opad.concat(hash), 672)) | |
} | |
function rstr2hex(input) { | |
for (var x, hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef", output = "", i = 0; i < input.length; i++) | |
x = input.charCodeAt(i), | |
output += hex_tab.charAt(x >>> 4 & 15) + hex_tab.charAt(15 & x); | |
return output | |
} | |
function rstr2b64(input) { | |
for (var output = "", len = input.length, i = 0; i < len; i += 3) | |
for (var triplet = input.charCodeAt(i) << 16 | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0), j = 0; j < 4; j++) | |
8 * i + 6 * j > 8 * input.length ? output += b64pad : output += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(triplet >>> 6 * (3 - j) & 63); | |
return output | |
} | |
function rstr2any(input, encoding) { | |
var i, q, x, quotient, divisor = encoding.length, remainders = Array(), dividend = Array(Math.ceil(input.length / 2)); | |
for (i = 0; i < dividend.length; i++) | |
dividend[i] = input.charCodeAt(2 * i) << 8 | input.charCodeAt(2 * i + 1); | |
for (; 0 < dividend.length; ) { | |
for (quotient = Array(), | |
i = x = 0; i < dividend.length; i++) | |
x = (x << 16) + dividend[i], | |
x -= (q = Math.floor(x / divisor)) * divisor, | |
(0 < quotient.length || 0 < q) && (quotient[quotient.length] = q); | |
remainders[remainders.length] = x, | |
dividend = quotient | |
} | |
var output = ""; | |
for (i = remainders.length - 1; 0 <= i; i--) | |
output += encoding.charAt(remainders[i]); | |
var full_length = Math.ceil(8 * input.length / (Math.log(encoding.length) / Math.log(2))); | |
for (i = output.length; i < full_length; i++) | |
output = encoding[0] + output; | |
return output | |
} | |
function str2rstr_utf8(input) { | |
for (var x, y, output = "", i = -1; ++i < input.length; ) | |
x = input.charCodeAt(i), | |
y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0, | |
55296 <= x && x <= 56319 && 56320 <= y && y <= 57343 && (x = 65536 + ((1023 & x) << 10) + (1023 & y), | |
i++), | |
x <= 127 ? output += String.fromCharCode(x) : x <= 2047 ? output += String.fromCharCode(192 | x >>> 6 & 31, 128 | 63 & x) : x <= 65535 ? output += String.fromCharCode(224 | x >>> 12 & 15, 128 | x >>> 6 & 63, 128 | 63 & x) : x <= 2097151 && (output += String.fromCharCode(240 | x >>> 18 & 7, 128 | x >>> 12 & 63, 128 | x >>> 6 & 63, 128 | 63 & x)); | |
return output | |
} | |
function str2rstr_utf16le(input) { | |
for (var output = "", i = 0; i < input.length; i++) | |
output += String.fromCharCode(255 & input.charCodeAt(i), input.charCodeAt(i) >>> 8 & 255); | |
return output | |
} | |
function str2rstr_utf16be(input) { | |
for (var output = "", i = 0; i < input.length; i++) | |
output += String.fromCharCode(input.charCodeAt(i) >>> 8 & 255, 255 & input.charCodeAt(i)); | |
return output | |
} | |
function rstr2binb(input) { | |
for (var output = Array(input.length >> 2), i = 0; i < output.length; i++) | |
output[i] = 0; | |
for (i = 0; i < 8 * input.length; i += 8) | |
output[i >> 5] |= (255 & input.charCodeAt(i / 8)) << 24 - i % 32; | |
return output | |
} | |
function binb2rstr(input) { | |
for (var output = "", i = 0; i < 32 * input.length; i += 8) | |
output += String.fromCharCode(input[i >> 5] >>> 24 - i % 32 & 255); | |
return output | |
} | |
function binb_sha1(x, len) { | |
x[len >> 5] |= 128 << 24 - len % 32, | |
x[15 + (len + 64 >> 9 << 4)] = len; | |
for (var w = Array(80), a = 1732584193, b = -271733879, c = -1732584194, d = 271733878, e = -1009589776, i = 0; i < x.length; i += 16) { | |
for (var olda = a, oldb = b, oldc = c, oldd = d, olde = e, j = 0; j < 80; j++) { | |
w[j] = j < 16 ? x[i + j] : bit_rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1); | |
var t = safe_add(safe_add(bit_rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))); | |
e = d, | |
d = c, | |
c = bit_rol(b, 30), | |
b = a, | |
a = t | |
} | |
a = safe_add(a, olda), | |
b = safe_add(b, oldb), | |
c = safe_add(c, oldc), | |
d = safe_add(d, oldd), | |
e = safe_add(e, olde) | |
} | |
return Array(a, b, c, d, e) | |
} | |
function sha1_ft(t, b, c, d) { | |
return t < 20 ? b & c | ~b & d : t < 40 ? b ^ c ^ d : t < 60 ? b & c | b & d | c & d : b ^ c ^ d | |
} | |
function sha1_kt(t) { | |
return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514 | |
} | |
function safe_add(x, y) { | |
var lsw = (65535 & x) + (65535 & y); | |
return (x >> 16) + (y >> 16) + (lsw >> 16) << 16 | 65535 & lsw | |
} | |
function bit_rol(num, cnt) { | |
return num << cnt | num >>> 32 - cnt | |
} | |
!function(f) { | |
if ("object" == typeof exports && "undefined" != typeof module) | |
module.exports = f(); | |
else if ("function" == typeof define && define.amd) | |
define([], f); | |
else { | |
("undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : this).baidubce = f() | |
} | |
}(function() { | |
return function e(t, n, r) { | |
function s(o, u) { | |
if (!n[o]) { | |
if (!t[o]) { | |
var a = "function" == typeof require && require; | |
if (!u && a) | |
return a(o, !0); | |
if (i) | |
return i(o, !0); | |
var f = new Error("Cannot find module '" + o + "'"); | |
throw f.code = "MODULE_NOT_FOUND", | |
f | |
} | |
var l = n[o] = { | |
exports: {} | |
}; | |
t[o][0].call(l.exports, function(e) { | |
var n = t[o][1][e]; | |
return s(n || e) | |
}, l, l.exports, e, t, n, r) | |
} | |
return n[o].exports | |
} | |
for (var i = "function" == typeof require && require, o = 0; o < r.length; o++) | |
s(r[o]); | |
return s | |
}({ | |
1: [function(require, module, exports) { | |
var Q = require(44) | |
, BosClient = require(17) | |
, Auth = require(15) | |
, Uploader = require(31) | |
, utils = require(32); | |
module.exports = { | |
bos: { | |
Uploader: Uploader | |
}, | |
utils: utils, | |
sdk: { | |
Q: Q, | |
BosClient: BosClient, | |
Auth: Auth | |
} | |
} | |
} | |
, { | |
15: 15, | |
17: 17, | |
31: 31, | |
32: 32, | |
44: 44 | |
}], | |
2: [function(require, module, exports) { | |
"use strict"; | |
var mapAsync = require(9) | |
, doParallelLimit = require(3); | |
module.exports = doParallelLimit(mapAsync) | |
} | |
, { | |
3: 3, | |
9: 9 | |
}], | |
3: [function(require, module, exports) { | |
"use strict"; | |
var eachOfLimit = require(4); | |
module.exports = function(fn) { | |
return function(obj, limit, iterator, cb) { | |
return fn(eachOfLimit(limit), obj, iterator, cb) | |
} | |
} | |
} | |
, { | |
4: 4 | |
}], | |
4: [function(require, module, exports) { | |
var once = require(11) | |
, noop = require(10) | |
, onlyOnce = require(12) | |
, keyIterator = require(7); | |
module.exports = function(limit) { | |
return function(obj, iterator, cb) { | |
cb = once(cb || noop); | |
var nextKey = keyIterator(obj = obj || []); | |
if (limit <= 0) | |
return cb(null); | |
var done = !1 | |
, running = 0 | |
, errored = !1; | |
!function replenish() { | |
if (done && running <= 0) | |
return cb(null); | |
for (; running < limit && !errored; ) { | |
var key = nextKey(); | |
if (null === key) | |
return done = !0, | |
void (running <= 0 && cb(null)); | |
running += 1, | |
iterator(obj[key], key, onlyOnce(function(err) { | |
running -= 1, | |
err ? (cb(err), | |
errored = !0) : replenish() | |
})) | |
} | |
}() | |
} | |
} | |
} | |
, { | |
10: 10, | |
11: 11, | |
12: 12, | |
7: 7 | |
}], | |
5: [function(require, module, exports) { | |
"use strict"; | |
module.exports = Array.isArray || function(obj) { | |
return "[object Array]" === Object.prototype.toString.call(obj) | |
} | |
} | |
, {}], | |
6: [function(require, module, exports) { | |
"use strict"; | |
var isArray = require(5); | |
module.exports = function(arr) { | |
return isArray(arr) || "number" == typeof arr.length && 0 <= arr.length && arr.length % 1 == 0 | |
} | |
} | |
, { | |
5: 5 | |
}], | |
7: [function(require, module, exports) { | |
"use strict"; | |
var _keys = require(8) | |
, isArrayLike = require(6); | |
module.exports = function(coll) { | |
var len, keys, i = -1; | |
return isArrayLike(coll) ? (len = coll.length, | |
function() { | |
return ++i < len ? i : null | |
} | |
) : (keys = _keys(coll), | |
len = keys.length, | |
function() { | |
return ++i < len ? keys[i] : null | |
} | |
) | |
} | |
} | |
, { | |
6: 6, | |
8: 8 | |
}], | |
8: [function(require, module, exports) { | |
"use strict"; | |
module.exports = Object.keys || function(obj) { | |
var _keys = []; | |
for (var k in obj) | |
obj.hasOwnProperty(k) && _keys.push(k); | |
return _keys | |
} | |
} | |
, {}], | |
9: [function(require, module, exports) { | |
"use strict"; | |
var once = require(11) | |
, noop = require(10) | |
, isArrayLike = require(6); | |
module.exports = function(eachfn, arr, iterator, cb) { | |
cb = once(cb || noop); | |
var results = isArrayLike(arr = arr || []) ? [] : {}; | |
eachfn(arr, function(value, index, cb) { | |
iterator(value, function(err, v) { | |
results[index] = v, | |
cb(err) | |
}) | |
}, function(err) { | |
cb(err, results) | |
}) | |
} | |
} | |
, { | |
10: 10, | |
11: 11, | |
6: 6 | |
}], | |
10: [function(require, module, exports) { | |
"use strict"; | |
module.exports = function() {} | |
} | |
, {}], | |
11: [function(require, module, exports) { | |
"use strict"; | |
module.exports = function(fn) { | |
return function() { | |
null !== fn && (fn.apply(this, arguments), | |
fn = null) | |
} | |
} | |
} | |
, {}], | |
12: [function(require, module, exports) { | |
"use strict"; | |
module.exports = function(fn) { | |
return function() { | |
if (null === fn) | |
throw new Error("Callback was already called."); | |
fn.apply(this, arguments), | |
fn = null | |
} | |
} | |
} | |
, {}], | |
13: [function(require, module, exports) { | |
var objectToString = Object.prototype.toString; | |
module.exports = function(value) { | |
return "number" == typeof value || function(value) { | |
return !!value && "object" == typeof value | |
}(value) && "[object Number]" == objectToString.call(value) | |
} | |
} | |
, {}], | |
14: [function(require, module, exports) { | |
module.exports = function(value) { | |
var type = typeof value; | |
return !!value && ("object" == type || "function" == type) | |
} | |
} | |
, {}], | |
15: [function(require, module, exports) { | |
var helper = require(42) | |
, util = require(47) | |
, u = require(46) | |
, H = require(19) | |
, strings = require(22); | |
function Auth(ak, sk) { | |
this.ak = ak, | |
this.sk = sk | |
} | |
Auth.prototype.generateAuthorization = function(method, resource, params, headers, timestamp, expirationInSeconds, headersToSign) { | |
var now = timestamp ? new Date(1e3 * timestamp) : new Date | |
, rawSessionKey = util.format("bce-auth-v1/%s/%s/%d", this.ak, helper.toUTCString(now), expirationInSeconds || 1800) | |
, sessionKey = this.hash(rawSessionKey, this.sk) | |
, canonicalUri = this.uriCanonicalization(resource) | |
, canonicalQueryString = this.queryStringCanonicalization(params || {}) | |
, rv = this.headersCanonicalization(headers || {}, headersToSign) | |
, canonicalHeaders = rv[0] | |
, signedHeaders = rv[1] | |
, rawSignature = util.format("%s\n%s\n%s\n%s", method, canonicalUri, canonicalQueryString, canonicalHeaders) | |
, signature = this.hash(rawSignature, sessionKey); | |
return signedHeaders.length ? util.format("%s/%s/%s", rawSessionKey, signedHeaders.join(";"), signature) : util.format("%s//%s", rawSessionKey, signature) | |
} | |
, | |
Auth.prototype.uriCanonicalization = function(uri) { | |
return uri | |
} | |
, | |
Auth.prototype.queryStringCanonicalization = function(params) { | |
var canonicalQueryString = []; | |
return u.each(u.keys(params), function(key) { | |
if (key.toLowerCase() !== H.AUTHORIZATION.toLowerCase()) { | |
var value = null == params[key] ? "" : params[key]; | |
canonicalQueryString.push(key + "=" + strings.normalize(value)) | |
} | |
}), | |
canonicalQueryString.sort(), | |
canonicalQueryString.join("&") | |
} | |
, | |
Auth.prototype.headersCanonicalization = function(headers, headersToSign) { | |
headersToSign && headersToSign.length || (headersToSign = [H.HOST, H.CONTENT_MD5, H.CONTENT_LENGTH, H.CONTENT_TYPE]); | |
var headersMap = {}; | |
u.each(headersToSign, function(item) { | |
headersMap[item.toLowerCase()] = !0 | |
}); | |
var canonicalHeaders = []; | |
u.each(u.keys(headers), function(key) { | |
var value = headers[key]; | |
null != (value = u.isString(value) ? strings.trim(value) : value) && "" !== value && (key = key.toLowerCase(), | |
(/^x\-bce\-/.test(key) || !0 === headersMap[key]) && canonicalHeaders.push(util.format("%s:%s", strings.normalize(key), strings.normalize(value)))) | |
}), | |
canonicalHeaders.sort(); | |
var signedHeaders = []; | |
return u.each(canonicalHeaders, function(item) { | |
signedHeaders.push(item.split(":")[0]) | |
}), | |
[canonicalHeaders.join("\n"), signedHeaders] | |
} | |
, | |
Auth.prototype.hash = function(data, key) { | |
var sha256Hmac = require(40).createHmac("sha256", key); | |
return sha256Hmac.update(data), | |
sha256Hmac.digest("hex") | |
} | |
, | |
module.exports = Auth | |
} | |
, { | |
19: 19, | |
22: 22, | |
40: 40, | |
42: 42, | |
46: 46, | |
47: 47 | |
}], | |
16: [function(require, module, exports) { | |
var EventEmitter = require(41).EventEmitter | |
, util = require(47) | |
, Q = require(44) | |
, u = require(46) | |
, config = require(18) | |
, Auth = require(15); | |
function BceBaseClient(clientConfig, serviceId, regionSupported) { | |
EventEmitter.call(this), | |
this.config = u.extend({}, config.DEFAULT_CONFIG, clientConfig), | |
this.serviceId = serviceId, | |
this.regionSupported = !!regionSupported, | |
this.config.endpoint = this._computeEndpoint(), | |
this._httpAgent = null | |
} | |
util.inherits(BceBaseClient, EventEmitter), | |
BceBaseClient.prototype._computeEndpoint = function() { | |
return this.config.endpoint ? this.config.endpoint : this.regionSupported ? util.format("%s://%s.%s.%s", this.config.protocol, this.serviceId, this.config.region, config.DEFAULT_SERVICE_DOMAIN) : util.format("%s://%s.%s", this.config.protocol, this.serviceId, config.DEFAULT_SERVICE_DOMAIN) | |
} | |
, | |
BceBaseClient.prototype.createSignature = function(credentials, httpMethod, path, params, headers) { | |
return Q.fcall(function() { | |
return new Auth(credentials.ak,credentials.sk).generateAuthorization(httpMethod, path, params, headers) | |
}) | |
} | |
, | |
module.exports = BceBaseClient | |
} | |
, { | |
15: 15, | |
18: 18, | |
41: 41, | |
44: 44, | |
46: 46, | |
47: 47 | |
}], | |
17: [function(require, module, exports) { | |
var path = require(43) | |
, util = require(47) | |
, u = require(46) | |
, Buffer = require(33) | |
, H = require(19) | |
, strings = require(22) | |
, HttpClient = require(20) | |
, BceBaseClient = require(16) | |
, MimeType = require(21); | |
function BosClient(config) { | |
BceBaseClient.call(this, config, "bos", !0), | |
this._httpAgent = null | |
} | |
util.inherits(BosClient, BceBaseClient), | |
BosClient.prototype.deleteObject = function(bucketName, key, options) { | |
return options = options || {}, | |
this.sendRequest("DELETE", { | |
bucketName: bucketName, | |
key: key, | |
config: options.config | |
}) | |
} | |
, | |
BosClient.prototype.putObject = function(bucketName, key, data, options) { | |
if (!key) | |
throw new TypeError("key should not be empty."); | |
return options = this._checkOptions(options || {}), | |
this.sendRequest("PUT", { | |
bucketName: bucketName, | |
key: key, | |
body: data, | |
headers: options.headers, | |
config: options.config | |
}) | |
} | |
, | |
BosClient.prototype.putObjectFromBlob = function(bucketName, key, blob, options) { | |
var headers = {}; | |
return headers[H.CONTENT_LENGTH] = blob.size, | |
options = u.extend(headers, options), | |
this.putObject(bucketName, key, blob, options) | |
} | |
, | |
BosClient.prototype.getObjectMetadata = function(bucketName, key, options) { | |
return options = options || {}, | |
this.sendRequest("HEAD", { | |
bucketName: bucketName, | |
key: key, | |
config: options.config | |
}) | |
} | |
, | |
BosClient.prototype.initiateMultipartUpload = function(bucketName, key, options) { | |
options = options || {}; | |
var headers = {}; | |
return headers[H.CONTENT_TYPE] = options[H.CONTENT_TYPE] || MimeType.guess(path.extname(key)), | |
this.sendRequest("POST", { | |
bucketName: bucketName, | |
key: key, | |
params: { | |
uploads: "" | |
}, | |
headers: headers, | |
config: options.config | |
}) | |
} | |
, | |
BosClient.prototype.abortMultipartUpload = function(bucketName, key, uploadId, options) { | |
return options = options || {}, | |
this.sendRequest("DELETE", { | |
bucketName: bucketName, | |
key: key, | |
params: { | |
uploadId: uploadId | |
}, | |
config: options.config | |
}) | |
} | |
, | |
BosClient.prototype.completeMultipartUpload = function(bucketName, key, uploadId, partList, options) { | |
var headers = {}; | |
return headers[H.CONTENT_TYPE] = "application/json; charset=UTF-8", | |
options = this._checkOptions(u.extend(headers, options)), | |
this.sendRequest("POST", { | |
bucketName: bucketName, | |
key: key, | |
body: JSON.stringify({ | |
parts: partList | |
}), | |
headers: options.headers, | |
params: { | |
uploadId: uploadId | |
}, | |
config: options.config | |
}) | |
} | |
, | |
BosClient.prototype.uploadPartFromBlob = function(bucketName, key, uploadId, partNumber, partSize, blob, options) { | |
if (blob.size !== partSize) | |
throw new TypeError(util.format("Invalid partSize %d and data length %d", partSize, blob.size)); | |
var headers = {}; | |
return headers[H.CONTENT_LENGTH] = partSize, | |
headers[H.CONTENT_TYPE] = "application/octet-stream", | |
options = this._checkOptions(u.extend(headers, options)), | |
this.sendRequest("PUT", { | |
bucketName: bucketName, | |
key: key, | |
body: blob, | |
headers: options.headers, | |
params: { | |
partNumber: partNumber, | |
uploadId: uploadId | |
}, | |
config: options.config | |
}) | |
} | |
, | |
BosClient.prototype.listParts = function(bucketName, key, uploadId, options) { | |
if (!uploadId) | |
throw new TypeError("uploadId should not empty"); | |
return (options = this._checkOptions(options || {}, ["maxParts", "partNumberMarker", "uploadId"])).params.uploadId = uploadId, | |
this.sendRequest("GET", { | |
bucketName: bucketName, | |
key: key, | |
params: options.params, | |
config: options.config | |
}) | |
} | |
, | |
BosClient.prototype.listMultipartUploads = function(bucketName, options) { | |
return (options = this._checkOptions(options || {}, ["delimiter", "maxUploads", "keyMarker", "prefix", "uploads"])).params.uploads = "", | |
this.sendRequest("GET", { | |
bucketName: bucketName, | |
params: options.params, | |
config: options.config | |
}) | |
} | |
, | |
BosClient.prototype.appendObject = function(bucketName, key, data, offset, options) { | |
if (!key) | |
throw new TypeError("key should not be empty."); | |
options = this._checkOptions(options || {}); | |
var params = { | |
append: "" | |
}; | |
return u.isNumber(offset) && (params.offset = offset), | |
this.sendRequest("POST", { | |
bucketName: bucketName, | |
key: key, | |
body: data, | |
headers: options.headers, | |
params: params, | |
config: options.config | |
}) | |
} | |
, | |
BosClient.prototype.appendObjectFromBlob = function(bucketName, key, blob, offset, options) { | |
var headers = {}; | |
return headers[H.CONTENT_LENGTH] = blob.size, | |
options = u.extend(headers, options), | |
this.appendObject(bucketName, key, blob, offset, options) | |
} | |
, | |
BosClient.prototype.sendRequest = function(httpMethod, varArgs) { | |
var args = u.extend({ | |
bucketName: null, | |
key: null, | |
body: null, | |
headers: {}, | |
params: {}, | |
config: {}, | |
outputStream: null | |
}, varArgs) | |
, config = u.extend({}, this.config, args.config) | |
, resource = ["/v1", strings.normalize(args.bucketName || ""), strings.normalize(args.key || "", !1)].join("/"); | |
return config.sessionToken && (args.headers[H.SESSION_TOKEN] = config.sessionToken), | |
this.sendHTTPRequest(httpMethod, resource, args, config) | |
} | |
, | |
BosClient.prototype.sendHTTPRequest = function(httpMethod, resource, args, config) { | |
var client = this | |
, agent = this._httpAgent = new HttpClient(config) | |
, httpContext = { | |
httpMethod: httpMethod, | |
resource: resource, | |
args: args, | |
config: config | |
}; | |
u.each(["progress", "error", "abort"], function(eventName) { | |
agent.on(eventName, function(evt) { | |
client.emit(eventName, evt, httpContext) | |
}) | |
}); | |
var promise = this._httpAgent.sendRequest(httpMethod, resource, args.body, args.headers, args.params, u.bind(this.createSignature, this), args.outputStream); | |
return promise.abort = function() { | |
agent._req && agent._req.xhr && agent._req.xhr.abort() | |
} | |
, | |
promise | |
} | |
, | |
BosClient.prototype._checkOptions = function(options, allowedParams) { | |
var rv = {}; | |
return rv.config = options.config || {}, | |
rv.headers = this._prepareObjectHeaders(options), | |
rv.params = u.pick(options, allowedParams || []), | |
rv | |
} | |
, | |
BosClient.prototype._prepareObjectHeaders = function(options) { | |
var allowedHeaders = {}; | |
u.each([H.CONTENT_LENGTH, H.CONTENT_ENCODING, H.CONTENT_MD5, H.X_BCE_CONTENT_SHA256, H.CONTENT_TYPE, H.CONTENT_DISPOSITION, H.ETAG, H.SESSION_TOKEN, H.CACHE_CONTROL, H.EXPIRES, H.X_BCE_OBJECT_ACL, H.X_BCE_OBJECT_GRANT_READ], function(header) { | |
allowedHeaders[header] = !0 | |
}); | |
var metaSize = 0 | |
, headers = u.pick(options, function(value, key) { | |
return !!allowedHeaders[key] || (/^x\-bce\-meta\-/.test(key) ? (metaSize += Buffer.byteLength(key) + Buffer.byteLength("" + value), | |
!0) : void 0) | |
}); | |
if (2048 < metaSize) | |
throw new TypeError("Metadata size should not be greater than 2048."); | |
if (headers.hasOwnProperty(H.CONTENT_LENGTH)) { | |
var contentLength = headers[H.CONTENT_LENGTH]; | |
if (contentLength < 0) | |
throw new TypeError("content_length should not be negative."); | |
if (5368709120 < contentLength) | |
throw new TypeError("Object length should be less than 5368709120. Use multi-part upload instead.") | |
} | |
if (headers.hasOwnProperty("ETag")) { | |
var etag = headers.ETag; | |
/^"/.test(etag) || (headers.ETag = util.format('"%s"', etag)) | |
} | |
return headers.hasOwnProperty(H.CONTENT_TYPE) || (headers[H.CONTENT_TYPE] = "application/octet-stream"), | |
headers | |
} | |
, | |
module.exports = BosClient | |
} | |
, { | |
16: 16, | |
19: 19, | |
20: 20, | |
21: 21, | |
22: 22, | |
33: 33, | |
43: 43, | |
46: 46, | |
47: 47 | |
}], | |
18: [function(require, module, exports) { | |
exports.DEFAULT_SERVICE_DOMAIN = "baidubce.com", | |
exports.DEFAULT_CONFIG = { | |
protocol: "http", | |
region: "bj" | |
} | |
} | |
, {}], | |
19: [function(require, module, exports) { | |
exports.CONTENT_TYPE = "Content-Type", | |
exports.CONTENT_LENGTH = "Content-Length", | |
exports.CONTENT_MD5 = "Content-MD5", | |
exports.CONTENT_ENCODING = "Content-Encoding", | |
exports.CONTENT_DISPOSITION = "Content-Disposition", | |
exports.ETAG = "ETag", | |
exports.CONNECTION = "Connection", | |
exports.HOST = "Host", | |
exports.USER_AGENT = "User-Agent", | |
exports.CACHE_CONTROL = "Cache-Control", | |
exports.EXPIRES = "Expires", | |
exports.AUTHORIZATION = "Authorization", | |
exports.X_BCE_DATE = "x-bce-date", | |
exports.X_BCE_ACL = "x-bce-acl", | |
exports.X_BCE_REQUEST_ID = "x-bce-request-id", | |
exports.X_BCE_CONTENT_SHA256 = "x-bce-content-sha256", | |
exports.X_BCE_OBJECT_ACL = "x-bce-object-acl", | |
exports.X_BCE_OBJECT_GRANT_READ = "x-bce-object-grant-read", | |
exports.X_HTTP_HEADERS = "http_headers", | |
exports.X_BODY = "body", | |
exports.X_STATUS_CODE = "status_code", | |
exports.X_MESSAGE = "message", | |
exports.X_CODE = "code", | |
exports.X_REQUEST_ID = "request_id", | |
exports.SESSION_TOKEN = "x-bce-security-token", | |
exports.X_VOD_MEDIA_TITLE = "x-vod-media-title", | |
exports.X_VOD_MEDIA_DESCRIPTION = "x-vod-media-description", | |
exports.ACCEPT_ENCODING = "accept-encoding", | |
exports.ACCEPT = "accept" | |
} | |
, {}], | |
20: [function(require, module, exports) { | |
var EventEmitter = require(41).EventEmitter | |
, Buffer = require(33) | |
, Q = require(44) | |
, helper = require(42) | |
, u = require(46) | |
, util = require(47) | |
, H = require(19); | |
function HttpClient(config) { | |
EventEmitter.call(this), | |
this.config = config, | |
this._req = null | |
} | |
util.inherits(HttpClient, EventEmitter), | |
HttpClient.prototype.sendRequest = function(httpMethod, path, body, headers, params, signFunction, outputStream) { | |
var requestUrl = this._getRequestUrl(path, params) | |
, defaultHeaders = {}; | |
defaultHeaders[H.X_BCE_DATE] = helper.toUTCString(new Date), | |
defaultHeaders[H.CONTENT_TYPE] = "application/json; charset=UTF-8", | |
defaultHeaders[H.HOST] = /^\w+:\/\/([^\/]+)/.exec(this.config.endpoint)[1]; | |
var requestHeaders = u.extend(defaultHeaders, headers); | |
if (!requestHeaders.hasOwnProperty(H.CONTENT_LENGTH)) { | |
var contentLength = this._guessContentLength(body); | |
0 === contentLength && /GET|HEAD/i.test(httpMethod) || (requestHeaders[H.CONTENT_LENGTH] = contentLength) | |
} | |
var self = this | |
, createSignature = signFunction || u.noop; | |
try { | |
return Q.resolve(createSignature(this.config.credentials, httpMethod, path, params, requestHeaders)).then(function(authorization, xbceDate) { | |
return authorization && (requestHeaders[H.AUTHORIZATION] = authorization), | |
xbceDate && (requestHeaders[H.X_BCE_DATE] = xbceDate), | |
self._doRequest(httpMethod, requestUrl, u.omit(requestHeaders, H.CONTENT_LENGTH, H.HOST), body, outputStream) | |
}) | |
} catch (ex) { | |
return Q.reject(ex) | |
} | |
} | |
, | |
HttpClient.prototype._doRequest = function(httpMethod, requestUrl, requestHeaders, body, outputStream) { | |
var deferred = Q.defer() | |
, self = this | |
, xhr = new XMLHttpRequest; | |
for (var header in xhr.open(httpMethod, requestUrl, !0), | |
requestHeaders) | |
if (requestHeaders.hasOwnProperty(header)) { | |
var value = requestHeaders[header]; | |
xhr.setRequestHeader(header, value) | |
} | |
return xhr.onerror = function(error) { | |
deferred.reject(error) | |
} | |
, | |
xhr.onabort = function() { | |
deferred.reject(new Error("xhr aborted")) | |
} | |
, | |
xhr.onreadystatechange = function() { | |
if (4 === xhr.readyState) { | |
var status = xhr.status; | |
1223 === status && (status = 204); | |
var contentType = xhr.getResponseHeader("Content-Type") | |
, responseBody = /application\/json/.test(contentType) ? JSON.parse(xhr.responseText) : xhr.responseText; | |
if (responseBody || (responseBody = { | |
location: requestUrl | |
}), | |
200 <= status && status < 300 || 304 === status) { | |
var headers = self._fixHeaders(xhr.getAllResponseHeaders()); | |
deferred.resolve({ | |
http_headers: headers, | |
body: responseBody | |
}) | |
} else | |
deferred.reject({ | |
status_code: status, | |
message: responseBody.message || "<message>", | |
code: responseBody.code || "<code>", | |
request_id: responseBody.requestId || "<request_id>" | |
}) | |
} | |
} | |
, | |
xhr.upload && u.each(["progress", "error", "abort"], function(eventName) { | |
xhr.upload.addEventListener(eventName, function(evt) { | |
"function" == typeof self.emit && self.emit(eventName, evt) | |
}, !1) | |
}), | |
xhr.send(body), | |
self._req = { | |
xhr: xhr | |
}, | |
deferred.promise | |
} | |
, | |
HttpClient.prototype._guessContentLength = function(data) { | |
if (null == data || "" === data) | |
return 0; | |
if (u.isString(data)) | |
return Buffer.byteLength(data); | |
if ("undefined" != typeof Blob && data instanceof Blob) | |
return data.size; | |
if ("undefined" != typeof ArrayBuffer && data instanceof ArrayBuffer) | |
return data.byteLength; | |
throw new Error("No Content-Length is specified.") | |
} | |
, | |
HttpClient.prototype._fixHeaders = function(headers) { | |
var fixedHeaders = {}; | |
return headers && u.each(headers.split(/\r?\n/), function(line) { | |
var idx = line.indexOf(":"); | |
if (-1 !== idx) { | |
var key = line.substring(0, idx).toLowerCase() | |
, value = line.substring(idx + 1).replace(/^\s+|\s+$/, ""); | |
"etag" === key && (value = value.replace(/"/g, "")), | |
fixedHeaders[key] = value | |
} | |
}), | |
fixedHeaders | |
} | |
, | |
HttpClient.prototype.buildQueryString = function(params) { | |
return require(45).stringify(params).replace(/[()'!~.*\-_]/g, function(char) { | |
return "%" + char.charCodeAt().toString(16) | |
}) | |
} | |
, | |
HttpClient.prototype._getRequestUrl = function(path, params) { | |
var uri = path | |
, qs = this.buildQueryString(params); | |
return qs && (uri += "?" + qs), | |
this.config.endpoint + uri | |
} | |
, | |
module.exports = HttpClient | |
} | |
, { | |
19: 19, | |
33: 33, | |
41: 41, | |
42: 42, | |
44: 44, | |
45: 45, | |
46: 46, | |
47: 47 | |
}], | |
21: [function(require, module, exports) { | |
var mimeTypes = {}; | |
exports.guess = function(ext) { | |
return ext && ext.length ? ("." === ext[0] && (ext = ext.substr(1)), | |
mimeTypes[ext.toLowerCase()] || "application/octet-stream") : "application/octet-stream" | |
} | |
} | |
, {}], | |
22: [function(require, module, exports) { | |
var kEscapedMap = { | |
"!": "%21", | |
"'": "%27", | |
"(": "%28", | |
")": "%29", | |
"*": "%2A" | |
}; | |
exports.normalize = function(string, encodingSlash) { | |
var result = encodeURIComponent(string); | |
return result = result.replace(/[!'\(\)\*]/g, function($1) { | |
return kEscapedMap[$1] | |
}), | |
!1 === encodingSlash && (result = result.replace(/%2F/gi, "/")), | |
result | |
} | |
, | |
exports.trim = function(string) { | |
return (string || "").replace(/^\s+|\s+$/g, "") | |
} | |
} | |
, {}], | |
23: [function(require, module, exports) { | |
module.exports = { | |
runtimes: "html5", | |
bos_endpoint: "http://bj.bcebos.com", | |
bos_ak: null, | |
bos_sk: null, | |
bos_credentials: null, | |
bos_appendable: !1, | |
bos_relay_server: "https://relay.efe.tech", | |
multi_selection: !1, | |
max_retries: 0, | |
retry_interval: 1e3, | |
auto_start: !1, | |
max_file_size: "100mb", | |
bos_multipart_min_size: "10mb", | |
bos_multipart_parallel: 1, | |
bos_task_parallel: 3, | |
auth_stripped_headers: ["User-Agent", "Connection"], | |
chunk_size: "4mb", | |
bos_multipart_auto_continue: !1, | |
bos_multipart_local_key_generator: "default", | |
dir_selection: !1, | |
get_new_uptoken: !0, | |
uptoken_via_jsonp: !0, | |
uptoken_timeout: 5e3, | |
uptoken_jsonp_timeout: 5e3, | |
tracker_id: null | |
} | |
} | |
, {}], | |
24: [function(require, module, exports) { | |
module.exports = { | |
kPostInit: "PostInit", | |
kKey: "Key", | |
kListParts: "ListParts", | |
kObjectMetas: "ObjectMetas", | |
kFileFiltered: "FileFiltered", | |
kFilesAdded: "FilesAdded", | |
kFilesFilter: "FilesFilter", | |
kNetworkSpeed: "NetworkSpeed", | |
kBeforeUpload: "BeforeUpload", | |
kUploadProgress: "UploadProgress", | |
kFileUploaded: "FileUploaded", | |
kUploadPartProgress: "UploadPartProgress", | |
kChunkUploaded: "ChunkUploaded", | |
kUploadResume: "UploadResume", | |
kUploadResumeError: "UploadResumeError", | |
kUploadComplete: "UploadComplete", | |
kError: "Error", | |
kAborted: "Aborted" | |
} | |
} | |
, {}], | |
25: [function(require, module, exports) { | |
var Q = require(44) | |
, async = require(35) | |
, u = require(46) | |
, utils = require(32) | |
, events = require(24) | |
, Task = require(30); | |
function MultipartTask() { | |
Task.apply(this, arguments), | |
this.xhrPools = [] | |
} | |
utils.inherits(MultipartTask, Task), | |
MultipartTask.prototype.start = function() { | |
if (this.aborted) | |
return Q.resolve(); | |
var self = this | |
, dispatcher = this.eventDispatcher | |
, file = this.options.file | |
, bucket = this.options.bucket | |
, object = this.options.object | |
, metas = this.options.metas | |
, chunkSize = this.options.chunk_size | |
, multipartParallel = this.options.bos_multipart_parallel | |
, options = { | |
"Content-Type": utils.guessContentType(file) | |
} | |
, uploadId = null; | |
return this._initiateMultipartUpload(file, chunkSize, bucket, object, options).then(function(response) { | |
uploadId = response.body.uploadId; | |
var parts = response.body.parts || [] | |
, deferred = Q.defer() | |
, tasks = utils.getTasks(file, uploadId, chunkSize, bucket, object); | |
utils.filterTasks(tasks, parts); | |
var loaded = parts.length | |
, state = { | |
lengthComputable: !0, | |
loaded: loaded, | |
total: tasks.length | |
}; | |
if (file._previousLoaded = loaded * chunkSize, | |
loaded) { | |
var progress = file._previousLoaded / file.size; | |
dispatcher.dispatchEvent(events.kUploadProgress, [file, progress, null]) | |
} | |
return async.mapLimit(tasks, multipartParallel, self._uploadPart(state), function(err, results) { | |
err ? deferred.reject(err) : deferred.resolve(results) | |
}), | |
deferred.promise | |
}).then(function(responses) { | |
var partList = []; | |
return u.each(responses, function(response, index) { | |
partList.push({ | |
partNumber: index + 1, | |
eTag: response.http_headers.etag | |
}) | |
}), | |
self._generateLocalKey({ | |
blob: file, | |
chunkSize: chunkSize, | |
bucket: bucket, | |
object: object | |
}).then(function(key) { | |
utils.removeUploadId(key) | |
}), | |
self.client.completeMultipartUpload(bucket, object, uploadId, partList, metas) | |
}).then(function(response) { | |
dispatcher.dispatchEvent(events.kUploadProgress, [file, 1]), | |
response.body.bucket = bucket, | |
response.body.object = object, | |
dispatcher.dispatchEvent(events.kFileUploaded, [file, response]) | |
}).catch(function(error) { | |
var eventType = self.aborted ? events.kAborted : events.kError; | |
dispatcher.dispatchEvent(eventType, [error, file]) | |
}) | |
} | |
, | |
MultipartTask.prototype._initiateMultipartUpload = function(file, chunkSize, bucket, object, options) { | |
var uploadId, localSaveKey, self = this, dispatcher = this.eventDispatcher; | |
function initNewMultipartUpload() { | |
return self.client.initiateMultipartUpload(bucket, object, options).then(function(response) { | |
return localSaveKey && utils.setUploadId(localSaveKey, response.body.uploadId), | |
response.body.parts = [], | |
response | |
}) | |
} | |
var keyOptions = { | |
blob: file, | |
chunkSize: chunkSize, | |
bucket: bucket, | |
object: object | |
}; | |
return (this.options.bos_multipart_auto_continue ? this._generateLocalKey(keyOptions) : Q.resolve(null)).then(function(key) { | |
return (localSaveKey = key) && (uploadId = utils.getUploadId(localSaveKey)) ? self._listParts(file, bucket, object, uploadId) : initNewMultipartUpload() | |
}).then(function(response) { | |
if (uploadId && localSaveKey) { | |
var parts = response.body.parts; | |
dispatcher.dispatchEvent(events.kUploadResume, [file, parts, null]), | |
response.body.uploadId = uploadId | |
} | |
return response | |
}).catch(function(error) { | |
if (uploadId && localSaveKey) | |
return dispatcher.dispatchEvent(events.kUploadResumeError, [file, error, null]), | |
utils.removeUploadId(localSaveKey), | |
initNewMultipartUpload(); | |
throw error | |
}) | |
} | |
, | |
MultipartTask.prototype._generateLocalKey = function(options) { | |
var generator = this.options.bos_multipart_local_key_generator; | |
return utils.generateLocalKey(options, generator) | |
} | |
, | |
MultipartTask.prototype._listParts = function(file, bucket, object, uploadId) { | |
var self = this | |
, localParts = this.eventDispatcher.dispatchEvent(events.kListParts, [file, uploadId]); | |
return Q.resolve(localParts).then(function(parts) { | |
return u.isArray(parts) && parts.length ? { | |
http_headers: {}, | |
body: { | |
parts: parts | |
} | |
} : self._listAllParts(bucket, object, uploadId) | |
}) | |
} | |
, | |
MultipartTask.prototype._listAllParts = function(bucket, object, uploadId) { | |
var self = this | |
, deferred = Q.defer() | |
, parts = [] | |
, payload = null | |
, maxParts = 1e3 | |
, partNumberMarker = 0; | |
return function listParts() { | |
var options = { | |
maxParts: maxParts, | |
partNumberMarker: partNumberMarker | |
}; | |
self.client.listParts(bucket, object, uploadId, options).then(function(response) { | |
null == payload && (payload = response), | |
parts.push.apply(parts, response.body.parts), | |
partNumberMarker = response.body.nextPartNumberMarker, | |
!1 === response.body.isTruncated ? (payload.body.parts = parts, | |
deferred.resolve(payload)) : listParts() | |
}).catch(function(error) { | |
deferred.reject(error) | |
}) | |
}(), | |
deferred.promise | |
} | |
, | |
MultipartTask.prototype._uploadPart = function(state) { | |
var self = this | |
, dispatcher = this.eventDispatcher; | |
return function(item, callback) { | |
(function uploadPartInner(item, opt_maxRetries) { | |
if (item.etag) | |
return self.networkInfo.loadedBytes += item.partSize, | |
Q.resolve({ | |
http_headers: { | |
etag: item.etag | |
}, | |
body: {} | |
}); | |
var maxRetries = null == opt_maxRetries ? self.options.max_retries : opt_maxRetries | |
, retryInterval = self.options.retry_interval | |
, blob = item.file.slice(item.start, item.stop + 1); | |
blob._parentUUID = item.file.uuid, | |
blob._previousLoaded = 0; | |
var uploadPartXhr = self.client.uploadPartFromBlob(item.bucket, item.object, item.uploadId, item.partNumber, item.partSize, blob) | |
, xhrPoolIndex = self.xhrPools.push(uploadPartXhr); | |
return uploadPartXhr.then(function(response) { | |
++state.loaded; | |
var result = { | |
uploadId: item.uploadId, | |
partNumber: item.partNumber, | |
partSize: item.partSize, | |
bucket: item.bucket, | |
object: item.object, | |
offset: item.start, | |
total: blob.size, | |
response: response | |
}; | |
return dispatcher.dispatchEvent(events.kChunkUploaded, [item.file, result]), | |
self.xhrPools[xhrPoolIndex - 1] = null, | |
response | |
}).catch(function(error) { | |
if (0 < maxRetries && !self.aborted) | |
return utils.delay(retryInterval).then(function() { | |
return uploadPartInner(item, maxRetries - 1) | |
}); | |
throw error | |
}) | |
} | |
)(item).then(function(response) { | |
callback(null, response) | |
}, function(error) { | |
callback(error) | |
}) | |
} | |
} | |
, | |
MultipartTask.prototype.abort = function() { | |
this.aborted = !0, | |
this.xhrRequesting = null; | |
for (var i = 0; i < this.xhrPools.length; i++) { | |
var xhr = this.xhrPools[i]; | |
xhr && "function" == typeof xhr.abort && xhr.abort() | |
} | |
} | |
, | |
module.exports = MultipartTask | |
} | |
, { | |
24: 24, | |
30: 30, | |
32: 32, | |
35: 35, | |
44: 44, | |
46: 46 | |
}], | |
26: [function(require, module, exports) { | |
var utils = require(32); | |
function NetworkInfo() { | |
this.loadedBytes = 0, | |
this.totalBytes = 0, | |
this._startTime = utils.now(), | |
this.reset() | |
} | |
NetworkInfo.prototype.dump = function() { | |
return [this.loadedBytes, utils.now() - this._startTime, this.totalBytes - this.loadedBytes] | |
} | |
, | |
NetworkInfo.prototype.reset = function() { | |
this.loadedBytes = 0, | |
this._startTime = utils.now() | |
} | |
, | |
module.exports = NetworkInfo | |
} | |
, { | |
32: 32 | |
}], | |
27: [function(require, module, exports) { | |
var Q = require(44) | |
, u = require(46) | |
, utils = require(32) | |
, events = require(24) | |
, Task = require(30); | |
function PutObjectTask() { | |
Task.apply(this, arguments) | |
} | |
utils.inherits(PutObjectTask, Task), | |
PutObjectTask.prototype.start = function(opt_maxRetries) { | |
if (this.aborted) | |
return Q.resolve(); | |
var self = this | |
, dispatcher = this.eventDispatcher | |
, file = this.options.file | |
, bucket = this.options.bucket | |
, object = this.options.object | |
, metas = this.options.metas | |
, maxRetries = null == opt_maxRetries ? this.options.max_retries : opt_maxRetries | |
, retryInterval = this.options.retry_interval | |
, contentType = utils.guessContentType(file) | |
, options = u.extend({ | |
"Content-Type": contentType | |
}, metas); | |
return this.xhrRequesting = this.client.putObjectFromBlob(bucket, object, file, options), | |
this.xhrRequesting.then(function(response) { | |
dispatcher.dispatchEvent(events.kUploadProgress, [file, 1]), | |
response.body.bucket = bucket, | |
response.body.key = object, | |
dispatcher.dispatchEvent(events.kFileUploaded, [file, response]) | |
}).catch(function(error) { | |
var eventType = self.aborted ? events.kAborted : events.kError; | |
return dispatcher.dispatchEvent(eventType, [error, file]), | |
error.status_code && error.code && error.request_id ? Q.resolve() : 0 < maxRetries && !self.aborted ? utils.delay(retryInterval).then(function() { | |
return self.start(maxRetries - 1) | |
}) : Q.resolve() | |
}) | |
} | |
, | |
module.exports = PutObjectTask | |
} | |
, { | |
24: 24, | |
30: 30, | |
32: 32, | |
44: 44, | |
46: 46 | |
}], | |
28: [function(require, module, exports) { | |
function Queue(collection) { | |
this.collection = collection | |
} | |
Queue.prototype.isEmpty = function() { | |
return this.collection.length <= 0 | |
} | |
, | |
Queue.prototype.size = function() { | |
return this.collection.length | |
} | |
, | |
Queue.prototype.dequeue = function() { | |
return this.collection.shift() | |
} | |
, | |
module.exports = Queue | |
} | |
, {}], | |
29: [function(require, module, exports) { | |
var Q = require(44) | |
, utils = require(32); | |
function StsTokenManager(options) { | |
this.options = options, | |
this._cache = {} | |
} | |
StsTokenManager.prototype.get = function(bucket) { | |
var self = this; | |
return null != self._cache[bucket] ? self._cache[bucket] : Q.resolve(this._getImpl.apply(this, arguments)).then(function(payload) { | |
return self._cache[bucket] = payload | |
}) | |
} | |
, | |
StsTokenManager.prototype._getImpl = function(bucket) { | |
var options = this.options | |
, uptoken_url = options.uptoken_url | |
, timeout = options.uptoken_timeout || options.uptoken_jsonp_timeout | |
, viaJsonp = options.uptoken_via_jsonp | |
, deferred = Q.defer(); | |
return $.ajax({ | |
url: uptoken_url, | |
jsonp: !!viaJsonp && "callback", | |
dataType: viaJsonp ? "jsonp" : "json", | |
timeout: timeout, | |
data: { | |
sts: JSON.stringify(utils.getDefaultACL(bucket)) | |
}, | |
success: function(payload) { | |
deferred.resolve(payload) | |
}, | |
error: function() { | |
deferred.reject(new Error("Get sts token timeout (" + timeout + "ms).")) | |
} | |
}), | |
deferred.promise | |
} | |
, | |
module.exports = StsTokenManager | |
} | |
, { | |
32: 32, | |
44: 44 | |
}], | |
30: [function(require, module, exports) { | |
function Task(client, eventDispatcher, options) { | |
this.xhrRequesting = null, | |
this.aborted = !1, | |
this.networkInfo = null, | |
this.client = client, | |
this.eventDispatcher = eventDispatcher, | |
this.options = options | |
} | |
function abstractMethod() { | |
throw new Error("unimplemented method.") | |
} | |
Task.prototype.start = abstractMethod, | |
Task.prototype.pause = abstractMethod, | |
Task.prototype.resume = abstractMethod, | |
Task.prototype.setNetworkInfo = function(networkInfo) { | |
this.networkInfo = networkInfo | |
} | |
, | |
Task.prototype.abort = function() { | |
this.xhrRequesting && "function" == typeof this.xhrRequesting.abort && (this.aborted = !0, | |
this.xhrRequesting.abort(), | |
this.xhrRequesting = null) | |
} | |
, | |
module.exports = Task | |
} | |
, {}], | |
31: [function(require, module, exports) { | |
var Q = require(44) | |
, u = require(46) | |
, utils = require(32) | |
, events = require(24) | |
, kDefaultOptions = require(23) | |
, PutObjectTask = require(27) | |
, MultipartTask = require(25) | |
, StsTokenManager = require(29) | |
, NetworkInfo = require(26) | |
, Auth = require(15) | |
, BosClient = require(17); | |
function Uploader(options) { | |
u.isString(options) && (options = u.extend({ | |
browse_button: options, | |
auto_start: !0 | |
}, $(options).data())); | |
this.options = u.extend({}, kDefaultOptions, {}, options), | |
this.options.max_file_size = utils.parseSize(this.options.max_file_size), | |
this.options.bos_multipart_min_size = utils.parseSize(this.options.bos_multipart_min_size), | |
this.options.chunk_size = utils.parseSize(this.options.chunk_size), | |
!this.options.bos_credentials && this.options.bos_ak && this.options.bos_sk && (this.options.bos_credentials = { | |
ak: this.options.bos_ak, | |
sk: this.options.bos_sk | |
}), | |
this.client = new BosClient({ | |
endpoint: utils.normalizeEndpoint(this.options.bos_endpoint), | |
credentials: this.options.bos_credentials, | |
sessionToken: this.options.uptoken | |
}), | |
this._files = [], | |
this._uploadingFiles = {}, | |
this._abort = !1, | |
this._working = !1, | |
this._xhr2Supported = utils.isXhr2Supported(), | |
this._networkInfo = new NetworkInfo, | |
this._init() | |
} | |
Uploader.prototype._getCustomizedSignature = function(uptokenUrl) { | |
var options = this.options | |
, timeout = options.uptoken_timeout || options.uptoken_jsonp_timeout | |
, viaJsonp = options.uptoken_via_jsonp; | |
return function(_, httpMethod, path, params, headers) { | |
/\bed=([\w\.]+)\b/.test(location.search) && (headers.Host = RegExp.$1), | |
u.isArray(options.auth_stripped_headers) && (headers = u.omit(headers, options.auth_stripped_headers)); | |
var deferred = Q.defer(); | |
return $.ajax({ | |
url: uptokenUrl, | |
jsonp: !!viaJsonp && "callback", | |
dataType: viaJsonp ? "jsonp" : "json", | |
timeout: timeout, | |
data: { | |
httpMethod: httpMethod, | |
path: path, | |
queries: JSON.stringify(params || {}), | |
headers: JSON.stringify(headers || {}) | |
}, | |
error: function() { | |
deferred.reject(new Error("Get authorization timeout (" + timeout + "ms).")) | |
}, | |
success: function(payload) { | |
200 === payload.statusCode && payload.signature ? deferred.resolve(payload.signature, payload.xbceDate) : deferred.reject(new Error("createSignature failed, statusCode = " + payload.statusCode)) | |
} | |
}), | |
deferred.promise | |
} | |
} | |
, | |
Uploader.prototype._invoke = function(methodName, args, throwErrors) { | |
var init = this.options.init || this.options.Init; | |
if (init) { | |
var method = init[methodName]; | |
if ("function" == typeof method) | |
try { | |
var up = null; | |
return args = null == args ? [up] : [up].concat(args), | |
method.apply(null, args) | |
} catch (ex) { | |
if (!0 === throwErrors) | |
return Q.reject(ex) | |
} | |
} | |
} | |
, | |
Uploader.prototype._init = function() { | |
var options = this.options | |
, accept = options.accept | |
, btnElement = $(options.browse_button); | |
if ("INPUT" !== btnElement.prop("nodeName")) { | |
var elementContainer = btnElement | |
, inputElementContainer = (elementContainer.outerWidth(), | |
elementContainer.outerHeight(), | |
$('<div class="bce-bos-uploader-input-container"><input type="file" /></div>')); | |
inputElementContainer.css({ | |
visibility: "hidden", | |
position: "absolute", | |
top: 0, | |
left: 0, | |
width: 0, | |
height: 0, | |
overflow: "hidden", | |
"z-index": 0 | |
}), | |
inputElementContainer.find("input").css({ | |
visibility: "hidden", | |
position: "absolute", | |
top: 0, | |
left: 0, | |
width: "100%", | |
height: "100%", | |
"font-size": "999px", | |
opacity: 0 | |
}), | |
elementContainer.css({ | |
position: "relative", | |
"z-index": 1 | |
}), | |
elementContainer.after(inputElementContainer), | |
elementContainer.parent().css("position", "relative"), | |
options.browse_button = inputElementContainer.find("input"), | |
this._xhr2Supported && elementContainer.click(function() { | |
options.browse_button.click() | |
}) | |
} | |
var self = this; | |
if (!this._xhr2Supported && "undefined" != typeof mOxie && u.isFunction(mOxie.FileInput)) { | |
var fileInput = new mOxie.FileInput({ | |
runtime_order: "flash,html4", | |
browse_button: $(options.browse_button).get(0), | |
swf_url: options.flash_swf_url, | |
accept: utils.expandAcceptToArray(accept), | |
multiple: options.multi_selection, | |
directory: options.dir_selection, | |
file: "file" | |
}); | |
fileInput.onchange = u.bind(this._onFilesAdded, this), | |
fileInput.onready = function() { | |
self._initEvents(), | |
self._invoke(events.kPostInit) | |
} | |
, | |
fileInput.init() | |
} | |
(options.bos_credentials ? Q.resolve() : self.refreshStsToken()).then(function() { | |
options.bos_credentials ? self.client.createSignature = function(_, httpMethod, path, params, headers) { | |
var credentials = _ || this.config.credentials; | |
return Q.fcall(function() { | |
return new Auth(credentials.ak,credentials.sk).generateAuthorization(httpMethod, path, params, headers) | |
}) | |
} | |
: options.uptoken_url && !0 === options.get_new_uptoken && (self.client.createSignature = self._getCustomizedSignature(options.uptoken_url)), | |
self._xhr2Supported && (self._initEvents(), | |
self._invoke(events.kPostInit)) | |
}).catch(function(error) { | |
self._invoke(events.kError, [error]) | |
}) | |
} | |
, | |
Uploader.prototype._initEvents = function() { | |
var options = this.options; | |
if (this._xhr2Supported) { | |
var btn = $(options.browse_button); | |
null == btn.attr("multiple") && btn.attr("multiple", !!options.multi_selection), | |
btn.on("change", u.bind(this._onFilesAdded, this)); | |
var accept = options.accept; | |
if (null != accept) { | |
var exts = utils.expandAccept(accept); | |
/Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor) && (exts = utils.extToMimeType(exts)), | |
btn.attr("accept", exts) | |
} | |
options.dir_selection && (btn.attr("directory", !0), | |
btn.attr("mozdirectory", !0), | |
btn.attr("webkitdirectory", !0)) | |
} | |
this.client.on("progress", u.bind(this._onUploadProgress, this)), | |
this.client.on("error", u.bind(this._onError, this)), | |
this._xhr2Supported || (this.client.sendHTTPRequest = u.bind(utils.fixXhr(this.options, !0), this.client)) | |
} | |
, | |
Uploader.prototype._filterFiles = function(candidates) { | |
var self = this | |
, maxFileSize = this.options.max_file_size | |
, files = u.filter(candidates, function(file) { | |
return 1 || !(0 < maxFileSize && file.size > maxFileSize) || (self._invoke(events.kFileFiltered, [file]), | |
!1) | |
}); | |
return this._invoke(events.kFilesFilter, [files]) || files | |
} | |
, | |
Uploader.prototype._onFilesAdded = function(e) { | |
var files = e.target.files; | |
files || (files = [{ | |
name: e.target.value.split(/[\/\\]/).pop(), | |
size: 0 | |
}]); | |
files = this._filterFiles(files), | |
u.isArray(files) && files.length && this.addFiles(files), | |
this.options.auto_start && this.start() | |
} | |
, | |
Uploader.prototype._onError = function(e) {} | |
, | |
Uploader.prototype._onUploadProgress = function(e, httpContext) { | |
var args = httpContext.args | |
, file = args.body; | |
if (utils.isBlob(file)) { | |
var progress = e.lengthComputable ? e.loaded / e.total : 0 | |
, delta = e.loaded - file._previousLoaded; | |
this._networkInfo.loadedBytes += delta, | |
this._invoke(events.kNetworkSpeed, this._networkInfo.dump()), | |
file._previousLoaded = e.loaded; | |
var eventType = events.kUploadProgress; | |
if (args.params.partNumber && args.params.uploadId) { | |
eventType = events.kUploadPartProgress, | |
this._invoke(eventType, [file, progress, e]); | |
var uuid = file._parentUUID | |
, originalFile = this._uploadingFiles[uuid] | |
, originalFileProgress = 0; | |
originalFile && (originalFile._previousLoaded += delta, | |
originalFileProgress = Math.min(originalFile._previousLoaded / originalFile.size, 1), | |
this._invoke(events.kUploadProgress, [originalFile, originalFileProgress, null])) | |
} else | |
this._invoke(eventType, [file, progress, e]) | |
} | |
} | |
, | |
Uploader.prototype.addFiles = function(files) { | |
function buildAbortHandler(item, self) { | |
return function() { | |
item._aborted = !0, | |
self._invoke(events.kAborted, [null, item]) | |
} | |
} | |
for (var totalBytes = 0, i = 0; i < files.length; i++) { | |
var item = files[i]; | |
item.abort = buildAbortHandler(item, this), | |
item.uuid = utils.uuid(), | |
totalBytes += item.size | |
} | |
this._networkInfo.totalBytes += totalBytes, | |
this._files.push.apply(this._files, files), | |
this._invoke(events.kFilesAdded, [files]) | |
} | |
, | |
Uploader.prototype.addFile = function(file) { | |
this.addFiles([file]) | |
} | |
, | |
Uploader.prototype.remove = function(item) { | |
"string" == typeof item && (item = this._uploadingFiles[item] || u.find(this._files, function(file) { | |
return file.uuid === item | |
})), | |
item && "function" == typeof item.abort && item.abort() | |
} | |
, | |
Uploader.prototype.start = function() { | |
var self = this; | |
if (!this._working && this._files.length) { | |
this._working = !0, | |
this._abort = !1, | |
this._networkInfo.reset(); | |
var taskParallel = this.options.bos_task_parallel; | |
utils.eachLimit(this._files, taskParallel, function(file, callback) { | |
file._previousLoaded = 0, | |
self._uploadNext(file).then(function() { | |
delete self._uploadingFiles[file.uuid], | |
callback(null, file) | |
}).catch(function() { | |
delete self._uploadingFiles[file.uuid], | |
callback(null, file) | |
}) | |
}, function(error) { | |
self._working = !1, | |
self._files.length = 0, | |
self._networkInfo.totalBytes = 0, | |
self._invoke(events.kUploadComplete) | |
}) | |
} | |
} | |
, | |
Uploader.prototype.stop = function() { | |
this._abort = !0, | |
this._working = !1 | |
} | |
, | |
Uploader.prototype.setOptions = function(options) { | |
var supportedOptions = u.pick(options, "bos_credentials", "bos_ak", "bos_sk", "uptoken", "bos_bucket", "bos_endpoint"); | |
this.options = u.extend(this.options, supportedOptions); | |
var config = this.client && this.client.config; | |
if (config) { | |
var credentials = null; | |
options.bos_credentials ? credentials = options.bos_credentials : options.bos_ak && options.bos_sk && (credentials = { | |
ak: options.bos_ak, | |
sk: options.bos_sk | |
}), | |
credentials && (this.options.bos_credentials = credentials, | |
config.credentials = credentials), | |
options.uptoken && (config.sessionToken = options.uptoken), | |
options.bos_endpoint && (config.endpoint = utils.normalizeEndpoint(options.bos_endpoint)) | |
} | |
} | |
, | |
Uploader.prototype.refreshStsToken = function() { | |
var self = this | |
, options = self.options; | |
return options.bos_bucket && options.uptoken_url && !1 === options.get_new_uptoken ? new StsTokenManager(options).get(options.bos_bucket).then(function(payload) { | |
return self.setOptions({ | |
bos_ak: payload.AccessKeyId, | |
bos_sk: payload.SecretAccessKey, | |
uptoken: payload.SessionToken | |
}) | |
}) : Q.resolve() | |
} | |
, | |
Uploader.prototype._uploadNext = function(file) { | |
if (this._abort) | |
return this._working = !1, | |
Q.resolve(); | |
if (!0 === file._aborted) | |
return Q.resolve(); | |
var returnValue = this._invoke(events.kBeforeUpload, [file], !0); | |
if (!1 === returnValue) | |
return Q.resolve(); | |
var self = this; | |
return Q.resolve(returnValue).then(function() { | |
return self._uploadNextImpl(file) | |
}).catch(function(error) { | |
self._invoke(events.kError, [error, file]) | |
}) | |
} | |
, | |
Uploader.prototype._uploadNextImpl = function(file) { | |
var self = this | |
, options = this.options | |
, object = file.name | |
, defaultTaskOptions = u.pick(options, "flash_swf_url", "max_retries", "chunk_size", "retry_interval", "bos_multipart_parallel", "bos_multipart_auto_continue", "bos_multipart_local_key_generator"); | |
return Q.all([this._invoke(events.kKey, [file], !0), this._invoke(events.kObjectMetas, [file])]).then(function(array) { | |
var bucket = options.bos_bucket | |
, result = array[0] | |
, objectMetas = array[1] | |
, multipart = "auto"; | |
u.isString(result) ? object = result : u.isObject(result) && (bucket = result.bucket || bucket, | |
object = result.key || object, | |
multipart = result.multipart || multipart); | |
var client = self.client | |
, eventDispatcher = self | |
, taskOptions = u.extend(defaultTaskOptions, { | |
file: file, | |
bucket: bucket, | |
object: object, | |
metas: objectMetas | |
}) | |
, TaskConstructor = PutObjectTask; | |
"auto" === multipart && self._xhr2Supported && file.size > options.bos_multipart_min_size && (TaskConstructor = MultipartTask); | |
var task = new TaskConstructor(client,eventDispatcher,taskOptions); | |
return (self._uploadingFiles[file.uuid] = file).abort = function() { | |
return file._aborted = !0, | |
task.abort() | |
} | |
, | |
task.setNetworkInfo(self._networkInfo), | |
task.start() | |
}) | |
} | |
, | |
Uploader.prototype.dispatchEvent = function(eventName, eventArguments, throwErrors) { | |
if (eventName === events.kAborted && eventArguments && eventArguments[1]) { | |
var file = eventArguments[1]; | |
if (0 < file.size) { | |
var loadedSize = file._previousLoaded || 0; | |
this._networkInfo.totalBytes -= file.size - loadedSize, | |
this._invoke(events.kNetworkSpeed, this._networkInfo.dump()) | |
} | |
} | |
return this._invoke(eventName, eventArguments, throwErrors) | |
} | |
, | |
module.exports = Uploader | |
} | |
, { | |
15: 15, | |
17: 17, | |
23: 23, | |
24: 24, | |
25: 25, | |
26: 26, | |
27: 27, | |
29: 29, | |
32: 32, | |
44: 44, | |
46: 46 | |
}], | |
32: [function(require, module, exports) { | |
var qsModule = require(45) | |
, Q = require(44) | |
, u = require(46) | |
, helper = require(42) | |
, Queue = require(28) | |
, MimeType = require(21); | |
function parseHost(url) { | |
var match = /^\w+:\/\/([^\/]+)/.exec(url); | |
return match && match[1] | |
} | |
exports.getTasks = function(file, uploadId, chunkSize, bucket, object) { | |
for (var leftSize = file.size, offset = 0, partNumber = 1, tasks = []; 0 < leftSize; ) { | |
var partSize = Math.min(leftSize, chunkSize); | |
tasks.push({ | |
file: file, | |
uploadId: uploadId, | |
bucket: bucket, | |
object: object, | |
partNumber: partNumber, | |
partSize: partSize, | |
start: offset, | |
stop: offset + partSize - 1 | |
}), | |
leftSize -= partSize, | |
offset += partSize, | |
partNumber += 1 | |
} | |
return tasks | |
} | |
, | |
exports.getAppendableTasks = function(fileSize, offset, chunkSize) { | |
for (var leftSize = fileSize - offset, tasks = []; leftSize; ) { | |
var partSize = Math.min(leftSize, chunkSize); | |
tasks.push({ | |
partSize: partSize, | |
start: offset, | |
stop: offset + partSize - 1 | |
}), | |
leftSize -= partSize, | |
offset += partSize | |
} | |
return tasks | |
} | |
, | |
exports.parseSize = function(size) { | |
if ("number" == typeof size) | |
return size; | |
var match = /^([\d\.]+)([mkg]?b?)$/i.exec(size); | |
if (!match) | |
return 0; | |
var $1 = match[1] | |
, $2 = match[2]; | |
return /^k/i.test($2) ? 1024 * $1 : /^m/i.test($2) ? 1024 * $1 * 1024 : /^g/i.test($2) ? 1024 * $1 * 1024 * 1024 : +$1 | |
} | |
, | |
exports.isXhr2Supported = function() { | |
return "XMLHttpRequest"in window && "withCredentials"in new XMLHttpRequest | |
} | |
, | |
exports.isAppendable = function(headers) { | |
return "Appendable" === headers["x-bce-object-type"] | |
} | |
, | |
exports.delay = function(ms) { | |
var deferred = Q.defer(); | |
return setTimeout(function() { | |
deferred.resolve() | |
}, ms), | |
deferred.promise | |
} | |
, | |
exports.normalizeEndpoint = function(endpoint) { | |
return endpoint.replace(/(\/+)$/, "") | |
} | |
, | |
exports.getDefaultACL = function(bucket) { | |
return { | |
accessControlList: [{ | |
service: "bce:bos", | |
region: "*", | |
effect: "Allow", | |
resource: [bucket + "/*"], | |
permission: ["READ", "WRITE"] | |
}] | |
} | |
} | |
, | |
exports.uuid = function() { | |
var random = (Math.random() * Math.pow(2, 32)).toString(36); | |
return "u-" + (new Date).getTime() + "-" + random | |
} | |
, | |
exports.generateLocalKey = function(option, generator) { | |
return "default" === generator ? Q.resolve([option.blob.name, option.blob.size, option.chunkSize, option.bucket, option.object].join("&")) : Q.resolve(null) | |
} | |
, | |
exports.getDefaultPolicy = function(bucket) { | |
if (null == bucket) | |
return null; | |
var now = (new Date).getTime() | |
, expiration = new Date(now + 864e5); | |
return { | |
expiration: helper.toUTCString(expiration), | |
conditions: [{ | |
bucket: bucket | |
}] | |
} | |
} | |
, | |
exports.getUploadId = function(key) { | |
return localStorage.getItem(key) | |
} | |
, | |
exports.setUploadId = function(key, uploadId) { | |
localStorage.setItem(key, uploadId) | |
} | |
, | |
exports.removeUploadId = function(key) { | |
localStorage.removeItem(key) | |
} | |
, | |
exports.filterTasks = function(tasks, parts) { | |
u.each(tasks, function(task) { | |
var etag = function(partNumber, existParts) { | |
var matchParts = u.filter(existParts || [], function(part) { | |
return +part.partNumber === partNumber | |
}); | |
return matchParts.length ? matchParts[0].eTag : null | |
}(task.partNumber, parts); | |
etag && (task.etag = etag) | |
}) | |
} | |
, | |
exports.expandAccept = function(accept) { | |
var exts = []; | |
return u.isArray(accept) ? u.each(accept, function(item) { | |
item.extensions && exts.push.apply(exts, item.extensions.split(",")) | |
}) : u.isString(accept) && (exts = accept.split(",")), | |
(exts = u.map(exts, function(ext) { | |
return /^\./.test(ext) ? ext : "." + ext | |
})).join(",") | |
} | |
, | |
exports.extToMimeType = function(exts) { | |
return u.map(exts.split(","), function(ext) { | |
return -1 !== ext.indexOf("/") ? ext : MimeType.guess(ext) | |
}).join(",") | |
} | |
, | |
exports.expandAcceptToArray = function(accept) { | |
return !accept || u.isArray(accept) ? accept : u.isString(accept) ? [{ | |
title: "All files", | |
extensions: accept | |
}] : [] | |
} | |
, | |
exports.transformUrl = function(url) { | |
return url.replace(/(https?:)\/\/([^\/]+)\/([^\/]+)\/([^\/]+)/, function(_, protocol, host, $3, $4) { | |
return /^v\d$/.test($3) ? protocol + "//" + $4 + "." + host + "/" + $3 : protocol + "//" + $3 + "." + host + "/" + $4 | |
}) | |
} | |
, | |
exports.isBlob = function(body) { | |
var blobCtor = null; | |
if ("undefined" != typeof Blob) | |
blobCtor = Blob; | |
else { | |
if ("undefined" == typeof mOxie || !u.isFunction(mOxie.Blob)) | |
return !1; | |
blobCtor = mOxie.Blob | |
} | |
return body instanceof blobCtor | |
} | |
, | |
exports.now = function() { | |
return (new Date).getTime() | |
} | |
, | |
exports.toDHMS = function(seconds) { | |
var days = 0 | |
, hours = 0 | |
, minutes = 0; | |
return 60 <= seconds && (seconds -= 60 * (minutes = ~~(seconds / 60))), | |
60 <= minutes && (minutes -= 60 * (hours = ~~(minutes / 60))), | |
24 <= hours && (hours -= 24 * (days = ~~(hours / 24))), | |
{ | |
DD: days, | |
HH: hours, | |
MM: minutes, | |
SS: seconds | |
} | |
} | |
, | |
exports.fixXhr = function(options, isBos) { | |
return function(httpMethod, resource, args, config) { | |
var client = this | |
, endpointHost = parseHost(config.endpoint); | |
args.headers["x-bce-date"] = helper.toUTCString(new Date), | |
args.headers.host = endpointHost, | |
args.params[".stamp"] = (new Date).getTime(); | |
var xhrUri, originalHttpMethod = httpMethod; | |
"PUT" === httpMethod && (httpMethod = "POST"); | |
var xhrMethod = httpMethod | |
, xhrBody = args.body; | |
if ("HEAD" === httpMethod) { | |
var relayServer = exports.normalizeEndpoint(options.bos_relay_server); | |
xhrUri = relayServer + "/" + endpointHost + resource, | |
args.params.httpMethod = httpMethod, | |
xhrMethod = "POST" | |
} else | |
!0 === isBos ? (xhrUri = exports.transformUrl(config.endpoint + resource), | |
resource = xhrUri.replace(/^\w+:\/\/[^\/]+\//, "/"), | |
args.headers.host = parseHost(xhrUri)) : xhrUri = config.endpoint + resource; | |
"POST" !== xhrMethod || xhrBody || (xhrBody = '{"FORCE_POST": true}'); | |
var deferred = Q.defer() | |
, xhr = new mOxie.XMLHttpRequest; | |
return xhr.onload = function() { | |
var response = null; | |
try { | |
(response = JSON.parse(xhr.response || "{}")).location = xhrUri | |
} catch (ex) { | |
response = { | |
location: xhrUri | |
} | |
} | |
200 <= xhr.status && xhr.status < 300 ? "HEAD" === httpMethod ? deferred.resolve(response) : deferred.resolve({ | |
http_headers: {}, | |
body: response | |
}) : deferred.reject({ | |
status_code: xhr.status, | |
message: response.message || "", | |
code: response.code || "", | |
request_id: response.requestId || "" | |
}) | |
} | |
, | |
xhr.onerror = function(error) { | |
deferred.reject(error) | |
} | |
, | |
xhr.upload && (xhr.upload.onprogress = function(e) { | |
if ("PUT" === originalHttpMethod) { | |
e.lengthComputable = !0; | |
var httpContext = { | |
httpMethod: originalHttpMethod, | |
resource: resource, | |
args: args, | |
config: config, | |
xhr: xhr | |
}; | |
client.emit("progress", e, httpContext) | |
} | |
} | |
), | |
client.createSignature(client.config.credentials, httpMethod, resource, args.params, args.headers).then(function(authorization, xbceDate) { | |
authorization && (args.headers.authorization = authorization), | |
xbceDate && (args.headers["x-bce-date"] = xbceDate); | |
var qs = qsModule.stringify(args.params); | |
for (var key in qs && (xhrUri += "?" + qs), | |
xhr.open(xhrMethod, xhrUri, !0), | |
args.headers) | |
if (args.headers.hasOwnProperty(key) && !/(host|content\-length)/i.test(key)) { | |
var value = args.headers[key]; | |
xhr.setRequestHeader(key, value) | |
} | |
xhr.send(xhrBody, { | |
runtime_order: "flash", | |
swf_url: options.flash_swf_url | |
}) | |
}).catch(function(error) { | |
deferred.reject(error) | |
}), | |
deferred.promise | |
} | |
} | |
, | |
exports.eachLimit = function(tasks, taskParallel, executer, done) { | |
var runningCount = 0 | |
, aborted = !1 | |
, fin = !1 | |
, queue = new Queue(tasks); | |
function infiniteLoop() { | |
var task = queue.dequeue(); | |
task && (runningCount++, | |
executer(task, function(error) { | |
runningCount--, | |
error ? (fin = aborted = !0, | |
done(error)) : queue.isEmpty() || aborted ? runningCount <= 0 && (fin || (fin = !0, | |
done())) : setTimeout(infiniteLoop, 0) | |
})) | |
} | |
taskParallel = Math.min(taskParallel, queue.size()); | |
for (var i = 0; i < taskParallel; i++) | |
infiniteLoop() | |
} | |
, | |
exports.inherits = function(ChildCtor, ParentCtor) { | |
return require(47).inherits(ChildCtor, ParentCtor) | |
} | |
, | |
exports.guessContentType = function(file, opt_ignoreCharset) { | |
var contentType = file.type; | |
if (!contentType) { | |
var ext = file.name.split(/\./g).pop(); | |
contentType = MimeType.guess(ext) | |
} | |
return opt_ignoreCharset || /charset=/.test(contentType) || (contentType += "; charset=UTF-8"), | |
contentType | |
} | |
} | |
, { | |
21: 21, | |
28: 28, | |
42: 42, | |
44: 44, | |
45: 45, | |
46: 46, | |
47: 47 | |
}], | |
33: [function(require, module, exports) { | |
function Buffer() {} | |
Buffer.byteLength = function(data) { | |
var m = encodeURIComponent(data).match(/%[89ABab]/g); | |
return data.length + (m ? m.length : 0) | |
} | |
, | |
module.exports = Buffer | |
} | |
, {}], | |
34: [function(require, module, exports) { | |
!function(root) { | |
var setTimeoutFunc = setTimeout; | |
function noop() {} | |
function Promise(fn) { | |
if ("object" != typeof this) | |
throw new TypeError("Promises must be constructed via new"); | |
if ("function" != typeof fn) | |
throw new TypeError("not a function"); | |
this._state = 0, | |
this._handled = !1, | |
this._value = void 0, | |
this._deferreds = [], | |
doResolve(fn, this) | |
} | |
function handle(self, deferred) { | |
for (; 3 === self._state; ) | |
self = self._value; | |
0 !== self._state ? (self._handled = !0, | |
Promise._immediateFn(function() { | |
var cb = 1 === self._state ? deferred.onFulfilled : deferred.onRejected; | |
if (null !== cb) { | |
var ret; | |
try { | |
ret = cb(self._value) | |
} catch (e) { | |
return void reject(deferred.promise, e) | |
} | |
resolve(deferred.promise, ret) | |
} else | |
(1 === self._state ? resolve : reject)(deferred.promise, self._value) | |
})) : self._deferreds.push(deferred) | |
} | |
function resolve(self, newValue) { | |
try { | |
if (newValue === self) | |
throw new TypeError("A promise cannot be resolved with itself."); | |
if (newValue && ("object" == typeof newValue || "function" == typeof newValue)) { | |
var then = newValue.then; | |
if (newValue instanceof Promise) | |
return self._state = 3, | |
self._value = newValue, | |
void finale(self); | |
if ("function" == typeof then) | |
return void doResolve((fn = then, | |
thisArg = newValue, | |
function() { | |
fn.apply(thisArg, arguments) | |
} | |
), self) | |
} | |
self._state = 1, | |
self._value = newValue, | |
finale(self) | |
} catch (e) { | |
reject(self, e) | |
} | |
var fn, thisArg | |
} | |
function reject(self, newValue) { | |
self._state = 2, | |
self._value = newValue, | |
finale(self) | |
} | |
function finale(self) { | |
2 === self._state && 0 === self._deferreds.length && Promise._immediateFn(function() { | |
self._handled || Promise._unhandledRejectionFn(self._value) | |
}); | |
for (var i = 0, len = self._deferreds.length; i < len; i++) | |
handle(self, self._deferreds[i]); | |
self._deferreds = null | |
} | |
function Handler(onFulfilled, onRejected, promise) { | |
this.onFulfilled = "function" == typeof onFulfilled ? onFulfilled : null, | |
this.onRejected = "function" == typeof onRejected ? onRejected : null, | |
this.promise = promise | |
} | |
function doResolve(fn, self) { | |
var done = !1; | |
try { | |
fn(function(value) { | |
done || (done = !0, | |
resolve(self, value)) | |
}, function(reason) { | |
done || (done = !0, | |
reject(self, reason)) | |
}) | |
} catch (ex) { | |
if (done) | |
return; | |
done = !0, | |
reject(self, ex) | |
} | |
} | |
Promise.prototype.catch = function(onRejected) { | |
return this.then(null, onRejected) | |
} | |
, | |
Promise.prototype.then = function(onFulfilled, onRejected) { | |
var prom = new this.constructor(noop); | |
return handle(this, new Handler(onFulfilled,onRejected,prom)), | |
prom | |
} | |
, | |
Promise.all = function(arr) { | |
var args = Array.prototype.slice.call(arr); | |
return new Promise(function(resolve, reject) { | |
if (0 === args.length) | |
return resolve([]); | |
var remaining = args.length; | |
function res(i, val) { | |
try { | |
if (val && ("object" == typeof val || "function" == typeof val)) { | |
var then = val.then; | |
if ("function" == typeof then) | |
return void then.call(val, function(val) { | |
res(i, val) | |
}, reject) | |
} | |
args[i] = val, | |
0 == --remaining && resolve(args) | |
} catch (ex) { | |
reject(ex) | |
} | |
} | |
for (var i = 0; i < args.length; i++) | |
res(i, args[i]) | |
} | |
) | |
} | |
, | |
Promise.resolve = function(value) { | |
return value && "object" == typeof value && value.constructor === Promise ? value : new Promise(function(resolve) { | |
resolve(value) | |
} | |
) | |
} | |
, | |
Promise.reject = function(value) { | |
return new Promise(function(resolve, reject) { | |
reject(value) | |
} | |
) | |
} | |
, | |
Promise.race = function(values) { | |
return new Promise(function(resolve, reject) { | |
for (var i = 0, len = values.length; i < len; i++) | |
values[i].then(resolve, reject) | |
} | |
) | |
} | |
, | |
Promise._immediateFn = "function" == typeof setImmediate && function(fn) { | |
setImmediate(fn) | |
} | |
|| function(fn) { | |
setTimeoutFunc(fn, 0) | |
} | |
, | |
Promise._unhandledRejectionFn = function(err) { | |
"undefined" != typeof console && console && console.warn("Possible Unhandled Promise Rejection:", err) | |
} | |
, | |
Promise._setImmediateFn = function(fn) { | |
Promise._immediateFn = fn | |
} | |
, | |
Promise._setUnhandledRejectionFn = function(fn) { | |
Promise._unhandledRejectionFn = fn | |
} | |
, | |
void 0 !== module && module.exports ? module.exports = Promise : root.Promise || (root.Promise = Promise) | |
}(this) | |
} | |
, {}], | |
35: [function(require, module, exports) { | |
exports.mapLimit = require(2) | |
} | |
, { | |
2: 2 | |
}], | |
36: [function(require, module, exports) { | |
var create = Object.create || function() { | |
function F() {} | |
return function(obj) { | |
var subtype; | |
return F.prototype = obj, | |
subtype = new F, | |
F.prototype = null, | |
subtype | |
} | |
}() | |
, C = {} | |
, C_algo = C.algo = {} | |
, C_lib = C.lib = {} | |
, Base = C_lib.Base = { | |
extend: function(overrides) { | |
var subtype = create(this); | |
return overrides && subtype.mixIn(overrides), | |
subtype.hasOwnProperty("init") && this.init !== subtype.init || (subtype.init = function() { | |
subtype.$super.init.apply(this, arguments) | |
} | |
), | |
(subtype.init.prototype = subtype).$super = this, | |
subtype | |
}, | |
create: function() { | |
var instance = this.extend(); | |
return instance.init.apply(instance, arguments), | |
instance | |
}, | |
init: function() {}, | |
mixIn: function(properties) { | |
for (var propertyName in properties) | |
properties.hasOwnProperty(propertyName) && (this[propertyName] = properties[propertyName]); | |
properties.hasOwnProperty("toString") && (this.toString = properties.toString) | |
}, | |
clone: function() { | |
return this.init.prototype.extend(this) | |
} | |
} | |
, WordArray = C_lib.WordArray = Base.extend({ | |
init: function(words, sigBytes) { | |
words = this.words = words || [], | |
this.sigBytes = null != sigBytes ? sigBytes : 4 * words.length | |
}, | |
toString: function(encoder) { | |
return (encoder || Hex).stringify(this) | |
}, | |
concat: function(wordArray) { | |
var i, thisWords = this.words, thatWords = wordArray.words, thisSigBytes = this.sigBytes, thatSigBytes = wordArray.sigBytes; | |
if (this.clamp(), | |
thisSigBytes % 4) | |
for (i = 0; i < thatSigBytes; i++) { | |
var thatByte = thatWords[i >>> 2] >>> 24 - i % 4 * 8 & 255; | |
thisWords[thisSigBytes + i >>> 2] |= thatByte << 24 - (thisSigBytes + i) % 4 * 8 | |
} | |
else | |
for (i = 0; i < thatSigBytes; i += 4) | |
thisWords[thisSigBytes + i >>> 2] = thatWords[i >>> 2]; | |
return this.sigBytes += thatSigBytes, | |
this | |
}, | |
clamp: function() { | |
var words = this.words | |
, sigBytes = this.sigBytes; | |
words[sigBytes >>> 2] &= 4294967295 << 32 - sigBytes % 4 * 8, | |
words.length = Math.ceil(sigBytes / 4) | |
}, | |
clone: function() { | |
var clone = Base.clone.call(this); | |
return clone.words = this.words.slice(0), | |
clone | |
}, | |
random: function(nBytes) { | |
for (var rcache, words = [], r = function(m_w) { | |
var m_z = 987654321 | |
, mask = 4294967295; | |
return function() { | |
var result = ((m_z = 36969 * (65535 & m_z) + (m_z >> 16) & mask) << 16) + (m_w = 18e3 * (65535 & m_w) + (m_w >> 16) & mask) & mask; | |
return result /= 4294967296, | |
(result += .5) * (.5 < Math.random() ? 1 : -1) | |
} | |
}, i = 0; i < nBytes; i += 4) { | |
var _r = r(4294967296 * (rcache || Math.random())); | |
rcache = 987654071 * _r(), | |
words.push(4294967296 * _r() | 0) | |
} | |
return new WordArray.init(words,nBytes) | |
} | |
}) | |
, C_enc = C.enc = {} | |
, Hex = C_enc.Hex = { | |
stringify: function(wordArray) { | |
for (var words = wordArray.words, sigBytes = wordArray.sigBytes, hexChars = [], i = 0; i < sigBytes; i++) { | |
var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255; | |
hexChars.push((bite >>> 4).toString(16)), | |
hexChars.push((15 & bite).toString(16)) | |
} | |
return hexChars.join("") | |
}, | |
parse: function(hexStr) { | |
for (var hexStrLength = hexStr.length, words = [], i = 0; i < hexStrLength; i += 2) | |
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << 24 - i % 8 * 4; | |
return new WordArray.init(words,hexStrLength / 2) | |
} | |
} | |
, Latin1 = C_enc.Latin1 = { | |
stringify: function(wordArray) { | |
for (var words = wordArray.words, sigBytes = wordArray.sigBytes, latin1Chars = [], i = 0; i < sigBytes; i++) { | |
var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255; | |
latin1Chars.push(String.fromCharCode(bite)) | |
} | |
return latin1Chars.join("") | |
}, | |
parse: function(latin1Str) { | |
for (var latin1StrLength = latin1Str.length, words = [], i = 0; i < latin1StrLength; i++) | |
words[i >>> 2] |= (255 & latin1Str.charCodeAt(i)) << 24 - i % 4 * 8; | |
return new WordArray.init(words,latin1StrLength) | |
} | |
} | |
, Utf8 = C_enc.Utf8 = { | |
stringify: function(wordArray) { | |
try { | |
return decodeURIComponent(escape(Latin1.stringify(wordArray))) | |
} catch (e) { | |
throw new Error("Malformed UTF-8 data") | |
} | |
}, | |
parse: function(utf8Str) { | |
return Latin1.parse(unescape(encodeURIComponent(utf8Str))) | |
} | |
} | |
, BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ | |
reset: function() { | |
this._data = new WordArray.init, | |
this._nDataBytes = 0 | |
}, | |
_append: function(data) { | |
"string" == typeof data && (data = Utf8.parse(data)), | |
this._data.concat(data), | |
this._nDataBytes += data.sigBytes | |
}, | |
_process: function(doFlush) { | |
var data = this._data | |
, dataWords = data.words | |
, dataSigBytes = data.sigBytes | |
, blockSize = this.blockSize | |
, nBlocksReady = dataSigBytes / (4 * blockSize) | |
, nWordsReady = (nBlocksReady = doFlush ? Math.ceil(nBlocksReady) : Math.max((0 | nBlocksReady) - this._minBufferSize, 0)) * blockSize | |
, nBytesReady = Math.min(4 * nWordsReady, dataSigBytes); | |
if (nWordsReady) { | |
for (var offset = 0; offset < nWordsReady; offset += blockSize) | |
this._doProcessBlock(dataWords, offset); | |
var processedWords = dataWords.splice(0, nWordsReady); | |
data.sigBytes -= nBytesReady | |
} | |
return new WordArray.init(processedWords,nBytesReady) | |
}, | |
clone: function() { | |
var clone = Base.clone.call(this); | |
return clone._data = this._data.clone(), | |
clone | |
}, | |
_minBufferSize: 0 | |
}); | |
C_lib.Hasher = BufferedBlockAlgorithm.extend({ | |
cfg: Base.extend(), | |
init: function(cfg) { | |
this.cfg = this.cfg.extend(cfg), | |
this.reset() | |
}, | |
reset: function() { | |
BufferedBlockAlgorithm.reset.call(this), | |
this._doReset() | |
}, | |
update: function(messageUpdate) { | |
return this._append(messageUpdate), | |
this._process(), | |
this | |
}, | |
finalize: function(messageUpdate) { | |
return messageUpdate && this._append(messageUpdate), | |
this._doFinalize() | |
}, | |
blockSize: 16, | |
_createHelper: function(hasher) { | |
return function(message, cfg) { | |
return new hasher.init(cfg).finalize(message) | |
} | |
}, | |
_createHmacHelper: function(hasher) { | |
return function(message, key) { | |
return new C_algo.HMAC.init(hasher,key).finalize(message) | |
} | |
} | |
}), | |
module.exports = C | |
} | |
, {}], | |
37: [function(require, module, exports) { | |
require(39), | |
require(38); | |
var CryptoJS = require(36); | |
module.exports = CryptoJS.HmacSHA256 | |
} | |
, { | |
36: 36, | |
38: 38, | |
39: 39 | |
}], | |
38: [function(require, module, exports) { | |
var C = require(36) | |
, Base = C.lib.Base | |
, Utf8 = C.enc.Utf8; | |
C.algo.HMAC = Base.extend({ | |
init: function(hasher, key) { | |
hasher = this._hasher = new hasher.init, | |
"string" == typeof key && (key = Utf8.parse(key)); | |
var hasherBlockSize = hasher.blockSize | |
, hasherBlockSizeBytes = 4 * hasherBlockSize; | |
key.sigBytes > hasherBlockSizeBytes && (key = hasher.finalize(key)), | |
key.clamp(); | |
for (var oKey = this._oKey = key.clone(), iKey = this._iKey = key.clone(), oKeyWords = oKey.words, iKeyWords = iKey.words, i = 0; i < hasherBlockSize; i++) | |
oKeyWords[i] ^= 1549556828, | |
iKeyWords[i] ^= 909522486; | |
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes, | |
this.reset() | |
}, | |
reset: function() { | |
var hasher = this._hasher; | |
hasher.reset(), | |
hasher.update(this._iKey) | |
}, | |
update: function(messageUpdate) { | |
return this._hasher.update(messageUpdate), | |
this | |
}, | |
finalize: function(messageUpdate) { | |
var hasher = this._hasher | |
, innerHash = hasher.finalize(messageUpdate); | |
return hasher.reset(), | |
hasher.finalize(this._oKey.clone().concat(innerHash)) | |
} | |
}) | |
} | |
, { | |
36: 36 | |
}], | |
39: [function(require, module, exports) { | |
var CryptoJS = require(36) | |
, C = CryptoJS | |
, C_lib = C.lib | |
, WordArray = C_lib.WordArray | |
, Hasher = C_lib.Hasher | |
, C_algo = C.algo | |
, H = [] | |
, K = []; | |
!function() { | |
function isPrime(n) { | |
for (var sqrtN = Math.sqrt(n), factor = 2; factor <= sqrtN; factor++) | |
if (!(n % factor)) | |
return !1; | |
return !0 | |
} | |
function getFractionalBits(n) { | |
return 4294967296 * (n - (0 | n)) | 0 | |
} | |
for (var n = 2, nPrime = 0; nPrime < 64; ) | |
isPrime(n) && (nPrime < 8 && (H[nPrime] = getFractionalBits(Math.pow(n, .5))), | |
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)), | |
nPrime++), | |
n++ | |
}(); | |
var W = [] | |
, SHA256 = C_algo.SHA256 = Hasher.extend({ | |
_doReset: function() { | |
this._hash = new WordArray.init(H.slice(0)) | |
}, | |
_doProcessBlock: function(M, offset) { | |
for (var H = this._hash.words, a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7], i = 0; i < 64; i++) { | |
if (i < 16) | |
W[i] = 0 | M[offset + i]; | |
else { | |
var gamma0x = W[i - 15] | |
, gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3 | |
, gamma1x = W[i - 2] | |
, gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10; | |
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] | |
} | |
var maj = a & b ^ a & c ^ b & c | |
, sigma0 = (a << 30 | a >>> 2) ^ (a << 19 | a >>> 13) ^ (a << 10 | a >>> 22) | |
, t1 = h + ((e << 26 | e >>> 6) ^ (e << 21 | e >>> 11) ^ (e << 7 | e >>> 25)) + (e & f ^ ~e & g) + K[i] + W[i]; | |
h = g, | |
g = f, | |
f = e, | |
e = d + t1 | 0, | |
d = c, | |
c = b, | |
b = a, | |
a = t1 + (sigma0 + maj) | 0 | |
} | |
H[0] = H[0] + a | 0, | |
H[1] = H[1] + b | 0, | |
H[2] = H[2] + c | 0, | |
H[3] = H[3] + d | 0, | |
H[4] = H[4] + e | 0, | |
H[5] = H[5] + f | 0, | |
H[6] = H[6] + g | 0, | |
H[7] = H[7] + h | 0 | |
}, | |
_doFinalize: function() { | |
var data = this._data | |
, dataWords = data.words | |
, nBitsTotal = 8 * this._nDataBytes | |
, nBitsLeft = 8 * data.sigBytes; | |
return dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32, | |
dataWords[14 + (nBitsLeft + 64 >>> 9 << 4)] = Math.floor(nBitsTotal / 4294967296), | |
dataWords[15 + (nBitsLeft + 64 >>> 9 << 4)] = nBitsTotal, | |
data.sigBytes = 4 * dataWords.length, | |
this._process(), | |
this._hash | |
}, | |
clone: function() { | |
var clone = Hasher.clone.call(this); | |
return clone._hash = this._hash.clone(), | |
clone | |
} | |
}); | |
C.SHA256 = Hasher._createHelper(SHA256), | |
C.HmacSHA256 = Hasher._createHmacHelper(SHA256), | |
module.exports = CryptoJS.SHA256 | |
} | |
, { | |
36: 36 | |
}], | |
40: [function(require, module, exports) { | |
var HmacSHA256 = require(37) | |
, Hex = require(36).enc.Hex; | |
exports.createHmac = function(type, key) { | |
if ("sha256" === type) { | |
var result = null; | |
return { | |
update: function(data) { | |
result = HmacSHA256(data, key).toString(Hex) | |
}, | |
digest: function() { | |
return result | |
} | |
} | |
} | |
} | |
} | |
, { | |
36: 36, | |
37: 37 | |
}], | |
41: [function(require, module, exports) { | |
function EventEmitter() { | |
this.__events = {} | |
} | |
EventEmitter.prototype.emit = function(eventName, var_args) { | |
var handlers = this.__events[eventName]; | |
if (!handlers) | |
return !1; | |
for (var args = [].slice.call(arguments, 1), i = 0; i < handlers.length; i++) { | |
var handler = handlers[i]; | |
try { | |
handler.apply(this, args) | |
} catch (ex) {} | |
} | |
return !0 | |
} | |
, | |
EventEmitter.prototype.on = function(eventName, listener) { | |
this.__events[eventName] ? this.__events[eventName].push(listener) : this.__events[eventName] = [listener] | |
} | |
, | |
exports.EventEmitter = EventEmitter | |
} | |
, {}], | |
42: [function(require, module, exports) { | |
function pad(number) { | |
return number < 10 ? "0" + number : number | |
} | |
exports.toISOString = function(date) { | |
return date.toISOString ? date.toISOString() : date.getUTCFullYear() + "-" + pad(date.getUTCMonth() + 1) + "-" + pad(date.getUTCDate()) + "T" + pad(date.getUTCHours()) + ":" + pad(date.getUTCMinutes()) + ":" + pad(date.getUTCSeconds()) + "." + (date.getUTCMilliseconds() / 1e3).toFixed(3).slice(2, 5) + "Z" | |
} | |
, | |
exports.toUTCString = function(date) { | |
return exports.toISOString(date).replace(/\.\d+Z$/, "Z") | |
} | |
} | |
, {}], | |
43: [function(require, module, exports) { | |
var u = require(46) | |
, splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; | |
var substr = "b" === "ab".substr(-1) ? function(str, start, len) { | |
return str.substr(start, len) | |
} | |
: function(str, start, len) { | |
return start < 0 && (start = str.length + start), | |
str.substr(start, len) | |
} | |
; | |
exports.extname = function(path) { | |
return (filename = path, | |
splitPathRe.exec(filename).slice(1))[3]; | |
var filename | |
} | |
, | |
exports.join = function() { | |
var paths = Array.prototype.slice.call(arguments, 0); | |
return exports.normalize(u.filter(paths, function(p, index) { | |
if ("string" != typeof p) | |
throw new TypeError("Arguments to path.join must be strings"); | |
return p | |
}).join("/")) | |
} | |
, | |
exports.normalize = function(path) { | |
var isAbsolute = "/" === path.charAt(0) | |
, trailingSlash = "/" === substr(path, -1); | |
return (path = function(parts, allowAboveRoot) { | |
for (var up = 0, i = parts.length - 1; 0 <= i; i--) { | |
var last = parts[i]; | |
"." === last ? parts.splice(i, 1) : ".." === last ? (parts.splice(i, 1), | |
up++) : up && (parts.splice(i, 1), | |
up--) | |
} | |
if (allowAboveRoot) | |
for (; up--; up) | |
parts.unshift(".."); | |
return parts | |
}(u.filter(path.split("/"), function(p) { | |
return !!p | |
}), !isAbsolute).join("/")) || isAbsolute || (path = "."), | |
path && trailingSlash && (path += "/"), | |
(isAbsolute ? "/" : "") + path | |
} | |
} | |
, { | |
46: 46 | |
}], | |
44: [function(require, module, exports) { | |
var Promise = require(34); | |
exports.resolve = function() { | |
return Promise.resolve.apply(Promise, arguments) | |
} | |
, | |
exports.reject = function() { | |
return Promise.reject.apply(Promise, arguments) | |
} | |
, | |
exports.all = function() { | |
return Promise.all.apply(Promise, arguments) | |
} | |
, | |
exports.fcall = function(fn) { | |
try { | |
return Promise.resolve(fn()) | |
} catch (ex) { | |
return Promise.reject(ex) | |
} | |
} | |
, | |
exports.defer = function() { | |
var deferred = {}; | |
return deferred.promise = new Promise(function(resolve, reject) { | |
deferred.resolve = function() { | |
resolve.apply(null, arguments) | |
} | |
, | |
deferred.reject = function() { | |
reject.apply(null, arguments) | |
} | |
} | |
), | |
deferred | |
} | |
} | |
, { | |
34: 34 | |
}], | |
45: [function(require, module, exports) { | |
var u = require(46); | |
function stringifyPrimitive(v) { | |
return "string" == typeof v ? v : "number" == typeof v && isFinite(v) ? "" + v : "boolean" == typeof v ? v ? "true" : "false" : "" | |
} | |
exports.stringify = function(obj, sep, eq, options) { | |
sep = sep || "&", | |
eq = eq || "="; | |
var encode = encodeURIComponent; | |
if (options && "function" == typeof options.encodeURIComponent && (encode = options.encodeURIComponent), | |
null !== obj && "object" == typeof obj) { | |
for (var keys = u.keys(obj), len = keys.length, flast = len - 1, fields = "", i = 0; i < len; ++i) { | |
var k = keys[i] | |
, v = obj[k] | |
, ks = encode(stringifyPrimitive(k)) + eq; | |
if (u.isArray(v)) { | |
for (var vlen = v.length, vlast = vlen - 1, j = 0; j < vlen; ++j) | |
fields += ks + encode(stringifyPrimitive(v[j])), | |
j < vlast && (fields += sep); | |
vlen && i < flast && (fields += sep) | |
} else | |
fields += ks + encode(stringifyPrimitive(v)), | |
i < flast && (fields += sep) | |
} | |
return fields | |
} | |
return "" | |
} | |
} | |
, { | |
46: 46 | |
}], | |
46: [function(require, module, exports) { | |
var isArray = require(5) | |
, noop = require(10) | |
, isNumber = require(13) | |
, isObject = require(14) | |
, objectToString = Object.prototype.toString; | |
function isFunction(value) { | |
return "function" == typeof value | |
} | |
function indexOf(array, value) { | |
for (var i = 0; i < array.length; i++) | |
if (array[i] === value) | |
return i; | |
return -1 | |
} | |
var hasOwnProperty = Object.prototype.hasOwnProperty | |
, hasDontEnumBug = !{ | |
toString: null | |
}.propertyIsEnumerable("toString") | |
, dontEnums = ["toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor"]; | |
function keys(obj) { | |
var prop, i, result = []; | |
for (prop in obj) | |
hasOwnProperty.call(obj, prop) && result.push(prop); | |
if (hasDontEnumBug) | |
for (i = 0; i < dontEnums.length; i++) | |
hasOwnProperty.call(obj, dontEnums[i]) && result.push(dontEnums[i]); | |
return result | |
} | |
exports.bind = function(fn, context) { | |
return function() { | |
return fn.apply(context, [].slice.call(arguments)) | |
} | |
} | |
, | |
exports.each = function(array, callback, context) { | |
for (var i = 0; i < array.length; i++) | |
callback.call(context, array[i], i, array) | |
} | |
, | |
exports.extend = function(source, var_args) { | |
for (var i = 1; i < arguments.length; i++) { | |
var item = arguments[i]; | |
if (item && isObject(item)) | |
for (var oKeys = keys(item), j = 0; j < oKeys.length; j++) { | |
var key = oKeys[j] | |
, value = item[key]; | |
source[key] = value | |
} | |
} | |
return source | |
} | |
, | |
exports.filter = function(array, callback, context) { | |
for (var res = [], i = 0; i < array.length; i++) { | |
var value = array[i]; | |
callback.call(context, value, i, array) && res.push(value) | |
} | |
return res | |
} | |
, | |
exports.find = function(array, callback, context) { | |
for (var i = 0; i < array.length; i++) { | |
var value = array[i]; | |
if (callback.call(context, value, i, array)) | |
return value | |
} | |
} | |
, | |
exports.isArray = isArray, | |
exports.isFunction = isFunction, | |
exports.isNumber = isNumber, | |
exports.isObject = isObject, | |
exports.isString = function(value) { | |
return "string" == typeof value || "[object String]" === objectToString.call(value) | |
} | |
, | |
exports.map = function(array, callback, context) { | |
for (var result = [], i = 0; i < array.length; i++) | |
result[i] = callback.call(context, array[i], i, array); | |
return result | |
} | |
, | |
exports.omit = function(object, var_args) { | |
for (var args = isArray(var_args) ? var_args : [].slice.call(arguments, 1), result = {}, oKeys = keys(object), i = 0; i < oKeys.length; i++) { | |
var key = oKeys[i]; | |
-1 === indexOf(args, key) && (result[key] = object[key]) | |
} | |
return result | |
} | |
, | |
exports.pick = function(object, var_args, context) { | |
var i, key, value, result = {}; | |
if (isFunction(var_args)) { | |
var callback = var_args | |
, oKeys = keys(object); | |
for (i = 0; i < oKeys.length; i++) | |
value = object[key = oKeys[i]], | |
callback.call(context, value, key, object) && (result[key] = value) | |
} else { | |
var args = isArray(var_args) ? var_args : [].slice.call(arguments, 1); | |
for (i = 0; i < args.length; i++) | |
key = args[i], | |
object.hasOwnProperty(key) && (result[key] = object[key]) | |
} | |
return result | |
} | |
, | |
exports.keys = keys, | |
exports.noop = noop | |
} | |
, { | |
10: 10, | |
13: 13, | |
14: 14, | |
5: 5 | |
}], | |
47: [function(require, module, exports) { | |
var u = require(46); | |
exports.inherits = function(subClass, superClass) { | |
var subClassProto = subClass.prototype | |
, F = new Function; | |
F.prototype = superClass.prototype, | |
subClass.prototype = new F, | |
subClass.prototype.constructor = subClass, | |
u.extend(subClass.prototype, subClassProto) | |
} | |
, | |
exports.format = function(f) { | |
var argLen = arguments.length; | |
if (1 === argLen) | |
return f; | |
for (var str = "", a = 1, lastPos = 0, i = 0; i < f.length; ) { | |
if (37 === f.charCodeAt(i) && i + 1 < f.length) | |
switch (f.charCodeAt(i + 1)) { | |
case 100: | |
if (argLen <= a) | |
break; | |
lastPos < i && (str += f.slice(lastPos, i)), | |
str += Number(arguments[a++]), | |
lastPos = i += 2; | |
continue; | |
case 115: | |
if (argLen <= a) | |
break; | |
lastPos < i && (str += f.slice(lastPos, i)), | |
str += String(arguments[a++]), | |
lastPos = i += 2; | |
continue; | |
case 37: | |
lastPos < i && (str += f.slice(lastPos, i)), | |
str += "%", | |
lastPos = i += 2; | |
continue | |
} | |
++i | |
} | |
return 0 === lastPos ? str = f : lastPos < f.length && (str += f.slice(lastPos)), | |
str | |
} | |
} | |
, { | |
46: 46 | |
}] | |
}, {}, [1])(1) | |
}), | |
function(a) { | |
if ("object" == typeof exports && "undefined" != typeof module) | |
module.exports = a(); | |
else if ("function" == typeof define && define.amd) | |
define([], a); | |
else { | |
("undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : this).Raven = a() | |
} | |
}(function() { | |
return function a(b, c, d) { | |
function e(g, h) { | |
if (!c[g]) { | |
if (!b[g]) { | |
var i = "function" == typeof require && require; | |
if (!h && i) | |
return i(g, !0); | |
if (f) | |
return f(g, !0); | |
var j = new Error("Cannot find module '" + g + "'"); | |
throw j.code = "MODULE_NOT_FOUND", | |
j | |
} | |
var k = c[g] = { | |
exports: {} | |
}; | |
b[g][0].call(k.exports, function(a) { | |
var c = b[g][1][a]; | |
return e(c || a) | |
}, k, k.exports, a, b, c, d) | |
} | |
return c[g].exports | |
} | |
for (var f = "function" == typeof require && require, g = 0; g < d.length; g++) | |
e(d[g]); | |
return e | |
}({ | |
1: [function(a, b, c) { | |
function d(a) { | |
this.name = "RavenConfigError", | |
this.message = a | |
} | |
(d.prototype = new Error).constructor = d, | |
b.exports = d | |
} | |
, {}], | |
2: [function(a, b, c) { | |
b.exports = { | |
wrapMethod: function(a, b, c) { | |
var d = a[b] | |
, e = a; | |
if (b in a) { | |
var f = "warn" === b ? "warning" : b; | |
a[b] = function() { | |
var a = [].slice.call(arguments) | |
, g = "" + a.join(" ") | |
, h = { | |
level: f, | |
logger: "console", | |
extra: { | |
arguments: a | |
} | |
}; | |
"assert" === b ? !1 === a[0] && (g = "Assertion failed: " + (a.slice(1).join(" ") || "console.assert"), | |
h.extra.arguments = a.slice(1), | |
c && c(g, h)) : c && c(g, h), | |
d && Function.prototype.apply.call(d, e, a) | |
} | |
} | |
} | |
} | |
} | |
, {}], | |
3: [function(a, b, c) { | |
(function(c) { | |
function d() { | |
return +new Date | |
} | |
function e(a, b) { | |
return h(b) ? function(c) { | |
return b(c, a) | |
} | |
: b | |
} | |
function f() { | |
for (var a in this.a = !("object" != typeof JSON || !JSON.stringify), | |
this.b = !g(J), | |
this.c = !g(K), | |
this.d = null, | |
this.e = null, | |
this.f = null, | |
this.g = null, | |
this.h = null, | |
this.i = null, | |
this.j = {}, | |
this.k = { | |
logger: "javascript", | |
ignoreErrors: [], | |
ignoreUrls: [], | |
whitelistUrls: [], | |
includePaths: [], | |
collectWindowErrors: !0, | |
maxMessageLength: 0, | |
maxUrlLength: 250, | |
stackTraceLimit: 50, | |
autoBreadcrumbs: !0, | |
instrument: !0, | |
sampleRate: 1 | |
}, | |
this.l = 0, | |
this.m = !1, | |
this.n = Error.stackTraceLimit, | |
this.o = I.console || {}, | |
this.p = {}, | |
this.q = [], | |
this.r = d(), | |
this.s = [], | |
this.t = [], | |
this.u = null, | |
this.v = I.location, | |
this.w = this.v && this.v.href, | |
this.x(), | |
this.o) | |
this.p[a] = this.o[a] | |
} | |
function g(a) { | |
return void 0 === a | |
} | |
function h(a) { | |
return "function" == typeof a | |
} | |
function i(a) { | |
return "[object String]" === L.toString.call(a) | |
} | |
function j(a) { | |
for (var b in a) | |
return !1; | |
return !0 | |
} | |
function k(a, b) { | |
var c, d; | |
if (g(a.length)) | |
for (c in a) | |
o(a, c) && b.call(null, c, a[c]); | |
else if (d = a.length) | |
for (c = 0; c < d; c++) | |
b.call(null, c, a[c]) | |
} | |
function l(a, b) { | |
return b && k(b, function(b, c) { | |
a[b] = c | |
}), | |
a | |
} | |
function m(a) { | |
return !!Object.isFrozen && Object.isFrozen(a) | |
} | |
function n(a, b) { | |
return !b || a.length <= b ? a : a.substr(0, b) + "…" | |
} | |
function o(a, b) { | |
return L.hasOwnProperty.call(a, b) | |
} | |
function p(a) { | |
for (var b, c = [], d = 0, e = a.length; d < e; d++) | |
i(b = a[d]) ? c.push(b.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1")) : b && b.source && c.push(b.source); | |
return new RegExp(c.join("|"),"i") | |
} | |
function r(a) { | |
var b = a.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); | |
if (!b) | |
return {}; | |
var c = b[6] || "" | |
, d = b[8] || ""; | |
return { | |
protocol: b[2], | |
host: b[4], | |
path: b[5], | |
relative: b[5] + c + d | |
} | |
} | |
function u(a) { | |
var b, c, d, e, f, g = []; | |
if (!a || !a.tagName) | |
return ""; | |
if (g.push(a.tagName.toLowerCase()), | |
a.id && g.push("#" + a.id), | |
(b = a.className) && i(b)) | |
for (c = b.split(/\s+/), | |
f = 0; f < c.length; f++) | |
g.push("." + c[f]); | |
var h = ["type", "name", "title", "alt"]; | |
for (f = 0; f < h.length; f++) | |
d = h[f], | |
(e = a.getAttribute(d)) && g.push("[" + d + '="' + e + '"]'); | |
return g.join("") | |
} | |
function v(a, b) { | |
return !!(!!a ^ !!b) | |
} | |
function x(a, b) { | |
if (v(a, b)) | |
return !1; | |
var c = a.frames | |
, d = b.frames; | |
if (c.length !== d.length) | |
return !1; | |
for (var e, f, g = 0; g < c.length; g++) | |
if (e = c[g], | |
f = d[g], | |
e.filename !== f.filename || e.lineno !== f.lineno || e.colno !== f.colno || e.function !== f.function) | |
return !1; | |
return !0 | |
} | |
function y(a, b, c, d) { | |
var e = a[b]; | |
a[b] = c(e), | |
d && d.push([a, b, e]) | |
} | |
var z = a(6) | |
, A = a(7) | |
, B = a(1) | |
, C = a(5) | |
, D = C.isError | |
, E = C.isObject | |
, F = a(2).wrapMethod | |
, G = "source protocol user pass host port path".split(" ") | |
, H = /^(?:(\w+):)?\/\/(?:(\w+)(:\w+)?@)?([\w\.-]+)(?::(\d+))?(\/.*)/ | |
, I = "undefined" != typeof window ? window : void 0 !== c ? c : "undefined" != typeof self ? self : {} | |
, J = I.document | |
, K = I.navigator; | |
f.prototype = { | |
VERSION: "3.18.1", | |
debug: !1, | |
TraceKit: z, | |
config: function(a, b) { | |
var c = this; | |
if (c.g) | |
return this.y("error", "Error: Raven has already been configured"), | |
c; | |
if (!a) | |
return c; | |
var d = c.k; | |
b && k(b, function(a, b) { | |
"tags" === a || "extra" === a || "user" === a ? c.j[a] = b : d[a] = b | |
}), | |
c.setDSN(a), | |
d.ignoreErrors.push(/^Script error\.?$/), | |
d.ignoreErrors.push(/^Javascript error: Script error\.? on line 0$/), | |
d.ignoreErrors = p(d.ignoreErrors), | |
d.ignoreUrls = !!d.ignoreUrls.length && p(d.ignoreUrls), | |
d.whitelistUrls = !!d.whitelistUrls.length && p(d.whitelistUrls), | |
d.includePaths = p(d.includePaths), | |
d.maxBreadcrumbs = Math.max(0, Math.min(d.maxBreadcrumbs || 100, 100)); | |
var e = { | |
xhr: !0, | |
console: !0, | |
dom: !0, | |
location: !0 | |
} | |
, f = d.autoBreadcrumbs; | |
"[object Object]" === {}.toString.call(f) ? f = l(e, f) : !1 !== f && (f = e), | |
d.autoBreadcrumbs = f; | |
var g = { | |
tryCatch: !0 | |
} | |
, h = d.instrument; | |
return "[object Object]" === {}.toString.call(h) ? h = l(g, h) : !1 !== h && (h = g), | |
d.instrument = h, | |
z.collectWindowErrors = !!d.collectWindowErrors, | |
c | |
}, | |
install: function() { | |
var a = this; | |
return a.isSetup() && !a.m && (z.report.subscribe(function() { | |
a.z.apply(a, arguments) | |
}), | |
a.k.instrument && a.k.instrument.tryCatch && a.A(), | |
a.k.autoBreadcrumbs && a.B(), | |
a.C(), | |
a.m = !0), | |
Error.stackTraceLimit = a.k.stackTraceLimit, | |
this | |
}, | |
setDSN: function(a) { | |
var b = this | |
, c = b.D(a) | |
, d = c.path.lastIndexOf("/") | |
, e = c.path.substr(1, d); | |
b.E = a, | |
b.h = c.user, | |
b.F = c.pass && c.pass.substr(1), | |
b.i = c.path.substr(d + 1), | |
b.g = b.G(c), | |
b.H = b.g + "/" + e + "api/" + b.i + "/store/", | |
this.x() | |
}, | |
context: function(a, b, c) { | |
return h(a) && (c = b || [], | |
b = a, | |
a = void 0), | |
this.wrap(a, b).apply(this, c) | |
}, | |
wrap: function(a, b, c) { | |
function d() { | |
var d = [] | |
, f = arguments.length | |
, g = !a || a && !1 !== a.deep; | |
for (c && h(c) && c.apply(this, arguments); f--; ) | |
d[f] = g ? e.wrap(a, arguments[f]) : arguments[f]; | |
try { | |
return b.apply(this, d) | |
} catch (i) { | |
throw e.I(), | |
e.captureException(i, a), | |
i | |
} | |
} | |
var e = this; | |
if (g(b) && !h(a)) | |
return a; | |
if (h(a) && (b = a, | |
a = void 0), | |
!h(b)) | |
return b; | |
try { | |
if (b.J) | |
return b; | |
if (b.K) | |
return b.K | |
} catch (f) { | |
return b | |
} | |
for (var i in b) | |
o(b, i) && (d[i] = b[i]); | |
return d.prototype = b.prototype, | |
(b.K = d).J = !0, | |
d.L = b, | |
d | |
}, | |
uninstall: function() { | |
return z.report.uninstall(), | |
this.M(), | |
Error.stackTraceLimit = this.n, | |
this.m = !1, | |
this | |
}, | |
captureException: function(a, b) { | |
if (!D(a)) | |
return this.captureMessage(a, l({ | |
trimHeadFrames: 1, | |
stacktrace: !0 | |
}, b)); | |
this.d = a; | |
try { | |
var c = z.computeStackTrace(a); | |
this.N(c, b) | |
} catch (d) { | |
if (a !== d) | |
throw d | |
} | |
return this | |
}, | |
captureMessage: function(a, b) { | |
if (!this.k.ignoreErrors.test || !this.k.ignoreErrors.test(a)) { | |
var c = l({ | |
message: a + "" | |
}, b = b || {}); | |
if (this.k.stacktrace || b && b.stacktrace) { | |
var d; | |
try { | |
throw new Error(a) | |
} catch (e) { | |
d = e | |
} | |
d.name = null, | |
b = l({ | |
fingerprint: a, | |
trimHeadFrames: (b.trimHeadFrames || 0) + 1 | |
}, b); | |
var f = z.computeStackTrace(d) | |
, g = this.O(f, b); | |
c.stacktrace = { | |
frames: g.reverse() | |
} | |
} | |
return this.P(c), | |
this | |
} | |
}, | |
captureBreadcrumb: function(a) { | |
var b = l({ | |
timestamp: d() / 1e3 | |
}, a); | |
if (h(this.k.breadcrumbCallback)) { | |
var c = this.k.breadcrumbCallback(b); | |
if (E(c) && !j(c)) | |
b = c; | |
else if (!1 === c) | |
return this | |
} | |
return this.t.push(b), | |
this.t.length > this.k.maxBreadcrumbs && this.t.shift(), | |
this | |
}, | |
addPlugin: function(a) { | |
var b = [].slice.call(arguments, 1); | |
return this.q.push([a, b]), | |
this.m && this.C(), | |
this | |
}, | |
setUserContext: function(a) { | |
return this.j.user = a, | |
this | |
}, | |
setExtraContext: function(a) { | |
return this.Q("extra", a), | |
this | |
}, | |
setTagsContext: function(a) { | |
return this.Q("tags", a), | |
this | |
}, | |
clearContext: function() { | |
return this.j = {}, | |
this | |
}, | |
getContext: function() { | |
return JSON.parse(A(this.j)) | |
}, | |
setEnvironment: function(a) { | |
return this.k.environment = a, | |
this | |
}, | |
setRelease: function(a) { | |
return this.k.release = a, | |
this | |
}, | |
setDataCallback: function(a) { | |
var b = this.k.dataCallback; | |
return this.k.dataCallback = e(b, a), | |
this | |
}, | |
setBreadcrumbCallback: function(a) { | |
var b = this.k.breadcrumbCallback; | |
return this.k.breadcrumbCallback = e(b, a), | |
this | |
}, | |
setShouldSendCallback: function(a) { | |
var b = this.k.shouldSendCallback; | |
return this.k.shouldSendCallback = e(b, a), | |
this | |
}, | |
setTransport: function(a) { | |
return this.k.transport = a, | |
this | |
}, | |
lastException: function() { | |
return this.d | |
}, | |
lastEventId: function() { | |
return this.f | |
}, | |
isSetup: function() { | |
return !(!this.a || !this.g && (this.ravenNotConfiguredError || (this.ravenNotConfiguredError = !0, | |
this.y("error", "Error: Raven has not been configured.")), | |
1)) | |
}, | |
afterLoad: function() { | |
var a = I.RavenConfig; | |
a && this.config(a.dsn, a.config).install() | |
}, | |
showReportDialog: function(a) { | |
if (J) { | |
var b = (a = a || {}).eventId || this.lastEventId(); | |
if (!b) | |
throw new B("Missing eventId"); | |
var c = a.dsn || this.E; | |
if (!c) | |
throw new B("Missing DSN"); | |
var d = encodeURIComponent | |
, e = ""; | |
e += "?eventId=" + d(b), | |
e += "&dsn=" + d(c); | |
var f = a.user || this.j.user; | |
f && (f.name && (e += "&name=" + d(f.name)), | |
f.email && (e += "&email=" + d(f.email))); | |
var g = this.G(this.D(c)) | |
, h = J.createElement("script"); | |
h.async = !0, | |
h.src = g + "/api/embed/error-page/" + e, | |
(J.head || J.body).appendChild(h) | |
} | |
}, | |
I: function() { | |
var a = this; | |
this.l += 1, | |
setTimeout(function() { | |
a.l -= 1 | |
}) | |
}, | |
R: function(a, b) { | |
var c, d; | |
if (this.b) { | |
for (d in b = b || {}, | |
a = "raven" + a.substr(0, 1).toUpperCase() + a.substr(1), | |
J.createEvent ? (c = J.createEvent("HTMLEvents")).initEvent(a, !0, !0) : (c = J.createEventObject()).eventType = a, | |
b) | |
o(b, d) && (c[d] = b[d]); | |
if (J.createEvent) | |
J.dispatchEvent(c); | |
else | |
try { | |
J.fireEvent("on" + c.eventType.toLowerCase(), c) | |
} catch (e) {} | |
} | |
}, | |
S: function(a) { | |
var b = this; | |
return function(c) { | |
if (b.T = null, | |
b.u !== c) { | |
var d; | |
b.u = c; | |
try { | |
d = function(a) { | |
for (var b, e = [], f = 0, g = 0, i = " > ".length; a && f++ < 5 && !("html" === (b = u(a)) || 1 < f && 80 <= g + e.length * i + b.length); ) | |
e.push(b), | |
g += b.length, | |
a = a.parentNode; | |
return e.reverse().join(" > ") | |
}(c.target) | |
} catch (e) { | |
d = "<unknown>" | |
} | |
b.captureBreadcrumb({ | |
category: "ui." + a, | |
message: d | |
}) | |
} | |
} | |
}, | |
U: function() { | |
var a = this; | |
return function(c) { | |
var d; | |
try { | |
d = c.target | |
} catch (e) { | |
return | |
} | |
var f = d && d.tagName; | |
if (f && ("INPUT" === f || "TEXTAREA" === f || d.isContentEditable)) { | |
var g = a.T; | |
g || a.S("input")(c), | |
clearTimeout(g), | |
a.T = setTimeout(function() { | |
a.T = null | |
}, 1e3) | |
} | |
} | |
}, | |
V: function(a, b) { | |
var c = r(this.v.href) | |
, d = r(b) | |
, e = r(a); | |
this.w = b, | |
c.protocol === d.protocol && c.host === d.host && (b = d.relative), | |
c.protocol === e.protocol && c.host === e.host && (a = e.relative), | |
this.captureBreadcrumb({ | |
category: "navigation", | |
data: { | |
to: b, | |
from: a | |
} | |
}) | |
}, | |
A: function() { | |
function a(a) { | |
return function(b, d) { | |
for (var e = new Array(arguments.length), f = 0; f < e.length; ++f) | |
e[f] = arguments[f]; | |
var g = e[0]; | |
return h(g) && (e[0] = c.wrap(g)), | |
a.apply ? a.apply(this, e) : a(e[0], e[1]) | |
} | |
} | |
function b(a) { | |
var b = I[a] && I[a].prototype; | |
b && b.hasOwnProperty && b.hasOwnProperty("addEventListener") && (y(b, "addEventListener", function(b) { | |
return function(d, f, g, h) { | |
try { | |
f && f.handleEvent && (f.handleEvent = c.wrap(f.handleEvent)) | |
} catch (i) {} | |
var j, k, l; | |
return e && e.dom && ("EventTarget" === a || "Node" === a) && (k = c.S("click"), | |
l = c.U(), | |
j = function(a) { | |
if (a) { | |
var b; | |
try { | |
b = a.type | |
} catch (c) { | |
return | |
} | |
return "click" === b ? k(a) : "keypress" === b ? l(a) : void 0 | |
} | |
} | |
), | |
b.call(this, d, c.wrap(f, void 0, j), g, h) | |
} | |
}, d), | |
y(b, "removeEventListener", function(a) { | |
return function(b, c, d, e) { | |
try { | |
c = c && (c.K ? c.K : c) | |
} catch (f) {} | |
return a.call(this, b, c, d, e) | |
} | |
}, d)) | |
} | |
var c = this | |
, d = c.s | |
, e = this.k.autoBreadcrumbs; | |
y(I, "setTimeout", a, d), | |
y(I, "setInterval", a, d), | |
I.requestAnimationFrame && y(I, "requestAnimationFrame", function(a) { | |
return function(b) { | |
return a(c.wrap(b)) | |
} | |
}, d); | |
for (var f = ["EventTarget", "Window", "Node", "ApplicationCache", "AudioTrackList", "ChannelMergerNode", "CryptoOperation", "EventSource", "FileReader", "HTMLUnknownElement", "IDBDatabase", "IDBRequest", "IDBTransaction", "KeyOperation", "MediaController", "MessagePort", "ModalWindow", "Notification", "SVGElementInstance", "Screen", "TextTrack", "TextTrackCue", "TextTrackList", "WebSocket", "WebSocketWorker", "Worker", "XMLHttpRequest", "XMLHttpRequestEventTarget", "XMLHttpRequestUpload"], g = 0; g < f.length; g++) | |
b(f[g]) | |
}, | |
B: function() { | |
function a(a, c) { | |
a in c && h(c[a]) && y(c, a, function(a) { | |
return b.wrap(a) | |
}) | |
} | |
var b = this | |
, c = this.k.autoBreadcrumbs | |
, d = b.s; | |
if (c.xhr && "XMLHttpRequest"in I) { | |
var e = XMLHttpRequest.prototype; | |
y(e, "open", function(a) { | |
return function(c, d) { | |
return i(d) && -1 === d.indexOf(b.h) && (this.W = { | |
method: c, | |
url: d, | |
status_code: null | |
}), | |
a.apply(this, arguments) | |
} | |
}, d), | |
y(e, "send", function(c) { | |
return function(d) { | |
function e() { | |
if (f.W && 4 === f.readyState) { | |
try { | |
f.W.status_code = f.status | |
} catch (a) {} | |
b.captureBreadcrumb({ | |
type: "http", | |
category: "xhr", | |
data: f.W | |
}) | |
} | |
} | |
for (var f = this, g = ["onload", "onerror", "onprogress"], i = 0; i < g.length; i++) | |
a(g[i], f); | |
return "onreadystatechange"in f && h(f.onreadystatechange) ? y(f, "onreadystatechange", function(a) { | |
return b.wrap(a, void 0, e) | |
}) : f.onreadystatechange = e, | |
c.apply(this, arguments) | |
} | |
}, d) | |
} | |
c.xhr && "fetch"in I && y(I, "fetch", function(a) { | |
return function(c, d) { | |
for (var e = new Array(arguments.length), f = 0; f < e.length; ++f) | |
e[f] = arguments[f]; | |
var g, h = e[0], i = "GET"; | |
"string" == typeof h ? g = h : (g = h.url, | |
h.method && (i = h.method)), | |
e[1] && e[1].method && (i = e[1].method); | |
var j = { | |
method: i, | |
url: g, | |
status_code: null | |
}; | |
return b.captureBreadcrumb({ | |
type: "http", | |
category: "fetch", | |
data: j | |
}), | |
a.apply(this, e).then(function(a) { | |
return j.status_code = a.status, | |
a | |
}) | |
} | |
}, d), | |
c.dom && this.b && (J.addEventListener ? (J.addEventListener("click", b.S("click"), !1), | |
J.addEventListener("keypress", b.U(), !1)) : (J.attachEvent("onclick", b.S("click")), | |
J.attachEvent("onkeypress", b.U()))); | |
var f = I.chrome | |
, j = !(f && f.app && f.app.runtime) && I.history && history.pushState; | |
if (c.location && j) { | |
var l = I.onpopstate; | |
I.onpopstate = function() { | |
var a = b.v.href; | |
if (b.V(b.w, a), | |
l) | |
return l.apply(this, arguments) | |
} | |
, | |
y(history, "pushState", function(a) { | |
return function() { | |
var c = 2 < arguments.length ? arguments[2] : void 0; | |
return c && b.V(b.w, c + ""), | |
a.apply(this, arguments) | |
} | |
}, d) | |
} | |
if (c.console && "console"in I && console.log) { | |
var m = function(a, c) { | |
b.captureBreadcrumb({ | |
message: a, | |
level: c.level, | |
category: "console" | |
}) | |
}; | |
k(["debug", "info", "warn", "error", "log"], function(a, b) { | |
F(console, b, m) | |
}) | |
} | |
}, | |
M: function() { | |
for (var a; this.s.length; ) { | |
var b = (a = this.s.shift())[0] | |
, c = a[1] | |
, d = a[2]; | |
b[c] = d | |
} | |
}, | |
C: function() { | |
var a = this; | |
k(this.q, function(b, c) { | |
var d = c[0] | |
, e = c[1]; | |
d.apply(a, [a].concat(e)) | |
}) | |
}, | |
D: function(a) { | |
var b = H.exec(a) | |
, c = {} | |
, d = 7; | |
try { | |
for (; d--; ) | |
c[G[d]] = b[d] || "" | |
} catch (e) { | |
throw new B("Invalid DSN: " + a) | |
} | |
if (c.pass && !this.k.allowSecretKey) | |
throw new B("Do not specify your secret key in the DSN. See: http://bit.ly/raven-secret-key"); | |
return c | |
}, | |
G: function(a) { | |
var b = "//" + a.host + (a.port ? ":" + a.port : ""); | |
return a.protocol && (b = a.protocol + ":" + b), | |
b | |
}, | |
z: function() { | |
this.l || this.N.apply(this, arguments) | |
}, | |
N: function(a, b) { | |
var c = this.O(a, b); | |
this.R("handle", { | |
stackInfo: a, | |
options: b | |
}), | |
this.X(a.name, a.message, a.url, a.lineno, c, b) | |
}, | |
O: function(a, b) { | |
var c = this | |
, d = []; | |
if (a.stack && a.stack.length && (k(a.stack, function(b, e) { | |
var f = c.Y(e, a.url); | |
f && d.push(f) | |
}), | |
b && b.trimHeadFrames)) | |
for (var e = 0; e < b.trimHeadFrames && e < d.length; e++) | |
d[e].in_app = !1; | |
return d = d.slice(0, this.k.stackTraceLimit) | |
}, | |
Y: function(a, b) { | |
var c = { | |
filename: a.url, | |
lineno: a.line, | |
colno: a.column, | |
function: a.func || "?" | |
}; | |
return a.url || (c.filename = b), | |
c.in_app = !(this.k.includePaths.test && !this.k.includePaths.test(c.filename) || /(Raven|TraceKit)\./.test(c.function) || /raven\.(min\.)?js$/.test(c.filename)), | |
c | |
}, | |
X: function(a, b, c, d, e, f) { | |
var h, g = (a || "") + ": " + (b || ""); | |
if ((!this.k.ignoreErrors.test || !this.k.ignoreErrors.test(g)) && (e && e.length ? (c = e[0].filename || c, | |
e.reverse(), | |
h = { | |
frames: e | |
}) : c && (h = { | |
frames: [{ | |
filename: c, | |
lineno: d, | |
in_app: !0 | |
}] | |
}), | |
(!this.k.ignoreUrls.test || !this.k.ignoreUrls.test(c)) && (!this.k.whitelistUrls.test || this.k.whitelistUrls.test(c)))) { | |
var i = l({ | |
exception: { | |
values: [{ | |
type: a, | |
value: b, | |
stacktrace: h | |
}] | |
}, | |
culprit: c | |
}, f); | |
this.P(i) | |
} | |
}, | |
Z: function(a) { | |
var b = this.k.maxMessageLength; | |
if (a.message && (a.message = n(a.message, b)), | |
a.exception) { | |
var c = a.exception.values[0]; | |
c.value = n(c.value, b) | |
} | |
var d = a.request; | |
return d && (d.url && (d.url = n(d.url, this.k.maxUrlLength)), | |
d.Referer && (d.Referer = n(d.Referer, this.k.maxUrlLength))), | |
a.breadcrumbs && a.breadcrumbs.values && this.$(a.breadcrumbs), | |
a | |
}, | |
$: function(a) { | |
for (var b, c, d, e = ["to", "from", "url"], f = 0; f < a.values.length; ++f) | |
if ((c = a.values[f]).hasOwnProperty("data") && E(c.data) && !m(c.data)) { | |
d = l({}, c.data); | |
for (var g = 0; g < e.length; ++g) | |
b = e[g], | |
d.hasOwnProperty(b) && d[b] && (d[b] = n(d[b], this.k.maxUrlLength)); | |
a.values[f].data = d | |
} | |
}, | |
_: function() { | |
if (this.c || this.b) { | |
var a = {}; | |
return this.c && K.userAgent && (a.headers = { | |
"User-Agent": navigator.userAgent | |
}), | |
this.b && (J.location && J.location.href && (a.url = J.location.href), | |
J.referrer && (a.headers || (a.headers = {}), | |
a.headers.Referer = J.referrer)), | |
a | |
} | |
}, | |
x: function() { | |
this.aa = 0, | |
this.ba = null | |
}, | |
ca: function() { | |
return this.aa && d() - this.ba < this.aa | |
}, | |
da: function(a) { | |
var b = this.e; | |
return !(!b || a.message !== b.message || a.culprit !== b.culprit) && (a.stacktrace || b.stacktrace ? x(a.stacktrace, b.stacktrace) : !a.exception && !b.exception || function(a, b) { | |
return !v(a, b) && (a = a.values[0], | |
b = b.values[0], | |
a.type === b.type && a.value === b.value && x(a.stacktrace, b.stacktrace)) | |
}(a.exception, b.exception)) | |
}, | |
ea: function(a) { | |
if (!this.ca()) { | |
var b = a.status; | |
if (400 === b || 401 === b || 429 === b) { | |
var c; | |
try { | |
c = a.getResponseHeader("Retry-After"), | |
c = 1e3 * parseInt(c, 10) | |
} catch (e) {} | |
this.aa = c || (2 * this.aa || 1e3), | |
this.ba = d() | |
} | |
} | |
}, | |
P: function(a) { | |
var b = this.k | |
, c = { | |
project: this.i, | |
logger: b.logger, | |
platform: "javascript" | |
} | |
, e = this._(); | |
if (e && (c.request = e), | |
a.trimHeadFrames && delete a.trimHeadFrames, | |
(a = l(c, a)).tags = l(l({}, this.j.tags), a.tags), | |
a.extra = l(l({}, this.j.extra), a.extra), | |
a.extra["session:duration"] = d() - this.r, | |
this.t && 0 < this.t.length && (a.breadcrumbs = { | |
values: [].slice.call(this.t, 0) | |
}), | |
j(a.tags) && delete a.tags, | |
this.j.user && (a.user = this.j.user), | |
b.environment && (a.environment = b.environment), | |
b.release && (a.release = b.release), | |
b.serverName && (a.server_name = b.serverName), | |
h(b.dataCallback) && (a = b.dataCallback(a) || a), | |
a && !j(a) && (!h(b.shouldSendCallback) || b.shouldSendCallback(a))) | |
return this.ca() ? void this.y("warn", "Raven dropped error due to backoff: ", a) : void ("number" == typeof b.sampleRate ? Math.random() < b.sampleRate && this.fa(a) : this.fa(a)) | |
}, | |
ga: function() { | |
return function() { | |
var a = I.crypto || I.msCrypto; | |
if (!g(a) && a.getRandomValues) { | |
var b = new Uint16Array(8); | |
a.getRandomValues(b), | |
b[3] = 4095 & b[3] | 16384, | |
b[4] = 16383 & b[4] | 32768; | |
var c = function(a) { | |
for (var b = a.toString(16); b.length < 4; ) | |
b = "0" + b; | |
return b | |
}; | |
return c(b[0]) + c(b[1]) + c(b[2]) + c(b[3]) + c(b[4]) + c(b[5]) + c(b[6]) + c(b[7]) | |
} | |
return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function(a) { | |
var b = 16 * Math.random() | 0; | |
return ("x" === a ? b : 3 & b | 8).toString(16) | |
}) | |
}() | |
}, | |
fa: function(a, b) { | |
var c = this | |
, d = this.k; | |
if (this.isSetup()) { | |
if (a = this.Z(a), | |
!this.k.allowDuplicates && this.da(a)) | |
return void this.y("warn", "Raven dropped repeat event: ", a); | |
this.f = a.event_id || (a.event_id = this.ga()), | |
this.e = a, | |
this.y("debug", "Raven about to send:", a); | |
var e = { | |
sentry_version: "7", | |
sentry_client: "raven-js/" + this.VERSION, | |
sentry_key: this.h | |
}; | |
this.F && (e.sentry_secret = this.F); | |
var f = a.exception && a.exception.values[0]; | |
this.captureBreadcrumb({ | |
category: "sentry", | |
message: f ? (f.type ? f.type + ": " : "") + f.value : a.message, | |
event_id: a.event_id, | |
level: a.level || "error" | |
}); | |
var g = this.H; | |
(d.transport || this.ha).call(this, { | |
url: g, | |
auth: e, | |
data: a, | |
options: d, | |
onSuccess: function() { | |
c.x(), | |
c.R("success", { | |
data: a, | |
src: g | |
}), | |
b && b() | |
}, | |
onError: function(d) { | |
c.y("error", "Raven transport failed to send: ", d), | |
d.request && c.ea(d.request), | |
c.R("failure", { | |
data: a, | |
src: g | |
}), | |
d = d || new Error("Raven send failed (no additional details provided)"), | |
b && b(d) | |
} | |
}) | |
} | |
}, | |
ha: function(a) { | |
var b = I.XMLHttpRequest && new I.XMLHttpRequest; | |
if (b && ("withCredentials"in b || "undefined" != typeof XDomainRequest)) { | |
var d = a.url; | |
"withCredentials"in b ? b.onreadystatechange = function() { | |
if (4 === b.readyState) | |
if (200 === b.status) | |
a.onSuccess && a.onSuccess(); | |
else if (a.onError) { | |
var c = new Error("Sentry error code: " + b.status); | |
c.request = b, | |
a.onError(c) | |
} | |
} | |
: (b = new XDomainRequest, | |
d = d.replace(/^https?:/, ""), | |
a.onSuccess && (b.onload = a.onSuccess), | |
a.onError && (b.onerror = function() { | |
var c = new Error("Sentry error code: XDomainRequest"); | |
c.request = b, | |
a.onError(c) | |
} | |
)), | |
b.open("POST", d + "?" + function(a) { | |
var b = []; | |
return k(a, function(a, c) { | |
b.push(encodeURIComponent(a) + "=" + encodeURIComponent(c)) | |
}), | |
b.join("&") | |
}(a.auth)), | |
b.send(A(a.data)) | |
} | |
}, | |
y: function(a) { | |
this.p[a] && this.debug && Function.prototype.apply.call(this.p[a], this.o, [].slice.call(arguments, 1)) | |
}, | |
Q: function(a, b) { | |
g(b) ? delete this.j[a] : this.j[a] = l(this.j[a] || {}, b) | |
} | |
}; | |
var L = Object.prototype; | |
f.prototype.setUser = f.prototype.setUserContext, | |
f.prototype.setReleaseContext = f.prototype.setRelease, | |
b.exports = f | |
} | |
).call(this, "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}) | |
} | |
, { | |
1: 1, | |
2: 2, | |
5: 5, | |
6: 6, | |
7: 7 | |
}], | |
4: [function(a, b, c) { | |
(function(c) { | |
var d = a(3) | |
, e = "undefined" != typeof window ? window : void 0 !== c ? c : "undefined" != typeof self ? self : {} | |
, f = e.Raven | |
, g = new d; | |
g.noConflict = function() { | |
return e.Raven = f, | |
g | |
} | |
, | |
g.afterLoad(), | |
b.exports = g | |
} | |
).call(this, "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}) | |
} | |
, { | |
3: 3 | |
}], | |
5: [function(a, b, c) { | |
b.exports = { | |
isObject: function(a) { | |
return "object" == typeof a && null !== a | |
}, | |
isError: function(a) { | |
switch ({}.toString.call(a)) { | |
case "[object Error]": | |
case "[object Exception]": | |
case "[object DOMException]": | |
return !0; | |
default: | |
return a instanceof Error | |
} | |
}, | |
wrappedCallback: function(a) { | |
return function(b, c) { | |
var d = a(b) || b; | |
return c && c(d) || d | |
} | |
} | |
} | |
} | |
, {}], | |
6: [function(a, b, c) { | |
(function(c) { | |
function d() { | |
return "undefined" == typeof document || null == document.location ? "" : document.location.href | |
} | |
var e = a(5) | |
, f = { | |
collectWindowErrors: !0, | |
debug: !1 | |
} | |
, g = "undefined" != typeof window ? window : void 0 !== c ? c : "undefined" != typeof self ? self : {} | |
, h = [].slice | |
, i = "?" | |
, j = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/; | |
f.report = function() { | |
function k(a, b) { | |
var c = null; | |
if (!b || f.collectWindowErrors) { | |
for (var d in s) | |
if (s.hasOwnProperty(d)) | |
try { | |
s[d].apply(null, [a].concat(h.call(arguments, 2))) | |
} catch (e) { | |
c = e | |
} | |
if (c) | |
throw c | |
} | |
} | |
function l(a, b, c, g, h) { | |
if (v) | |
f.computeStackTrace.augmentStackTraceWithInitialElement(v, b, c, a), | |
o(); | |
else if (h && e.isError(h)) | |
k(f.computeStackTrace(h), !0); | |
else { | |
var m, n = { | |
url: b, | |
line: c, | |
column: g | |
}, p = void 0, r = a; | |
if ("[object String]" === {}.toString.call(a)) | |
(m = a.match(j)) && (p = m[1], | |
r = m[2]); | |
n.func = i, | |
k({ | |
name: p, | |
message: r, | |
url: d(), | |
stack: [n] | |
}, !0) | |
} | |
return !!q && q.apply(this, arguments) | |
} | |
function o() { | |
var a = v | |
, b = t; | |
k.apply(u = v = t = null, [a, !1].concat(b)) | |
} | |
function p(a, b) { | |
var c = h.call(arguments, 1); | |
if (v) { | |
if (u === a) | |
return; | |
o() | |
} | |
var d = f.computeStackTrace(a); | |
if (v = d, | |
u = a, | |
t = c, | |
setTimeout(function() { | |
u === a && o() | |
}, d.incomplete ? 2e3 : 0), | |
!1 !== b) | |
throw a | |
} | |
var q, r, s = [], t = null, u = null, v = null; | |
return p.subscribe = function(a) { | |
r || (q = g.onerror, | |
g.onerror = l, | |
r = !0), | |
s.push(a) | |
} | |
, | |
p.unsubscribe = function(a) { | |
for (var b = s.length - 1; 0 <= b; --b) | |
s[b] === a && s.splice(b, 1) | |
} | |
, | |
p.uninstall = function() { | |
r && (g.onerror = q, | |
r = !1, | |
q = void 0), | |
s = [] | |
} | |
, | |
p | |
}(), | |
f.computeStackTrace = function() { | |
function a(a) { | |
if (void 0 !== a.stack && a.stack) { | |
for (var b, c, e, f = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i, g = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i, h = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i, j = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i, k = /\((\S*)(?::(\d+))(?::(\d+))\)/, l = a.stack.split("\n"), m = [], n = (/^(.*) is undefined$/.exec(a.message), | |
0), o = l.length; n < o; ++n) { | |
if (c = f.exec(l[n])) { | |
var p = c[2] && 0 === c[2].indexOf("native"); | |
c[2] && 0 === c[2].indexOf("eval") && (b = k.exec(c[2])) && (c[2] = b[1], | |
c[3] = b[2], | |
c[4] = b[3]), | |
e = { | |
url: p ? null : c[2], | |
func: c[1] || i, | |
args: p ? [c[2]] : [], | |
line: c[3] ? +c[3] : null, | |
column: c[4] ? +c[4] : null | |
} | |
} else if (c = h.exec(l[n])) | |
e = { | |
url: c[2], | |
func: c[1] || i, | |
args: [], | |
line: +c[3], | |
column: c[4] ? +c[4] : null | |
}; | |
else { | |
if (!(c = g.exec(l[n]))) | |
continue; | |
c[3] && -1 < c[3].indexOf(" > eval") && (b = j.exec(c[3])) ? (c[3] = b[1], | |
c[4] = b[2], | |
c[5] = null) : 0 !== n || c[5] || void 0 === a.columnNumber || (m[0].column = a.columnNumber + 1), | |
e = { | |
url: c[3], | |
func: c[1] || i, | |
args: c[2] ? c[2].split(",") : [], | |
line: c[4] ? +c[4] : null, | |
column: c[5] ? +c[5] : null | |
} | |
} | |
!e.func && e.line && (e.func = i), | |
m.push(e) | |
} | |
return m.length ? { | |
name: a.name, | |
message: a.message, | |
url: d(), | |
stack: m | |
} : null | |
} | |
} | |
function b(a, b, c, d) { | |
var e = { | |
url: b, | |
line: c | |
}; | |
if (e.url && e.line) { | |
if (a.incomplete = !1, | |
e.func || (e.func = i), | |
0 < a.stack.length && a.stack[0].url === e.url) { | |
if (a.stack[0].line === e.line) | |
return !1; | |
if (!a.stack[0].line && a.stack[0].func === e.func) | |
return a.stack[0].line = e.line, | |
!1 | |
} | |
return a.stack.unshift(e), | |
a.partial = !0 | |
} | |
return !(a.incomplete = !0) | |
} | |
function c(a, g) { | |
for (var h, j, k = /function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i, l = [], m = {}, n = !1, o = c.caller; o && !n; o = o.caller) | |
if (o !== e && o !== f.report) { | |
if (j = { | |
url: null, | |
func: i, | |
line: null, | |
column: null | |
}, | |
o.name ? j.func = o.name : (h = k.exec(o.toString())) && (j.func = h[1]), | |
void 0 === j.func) | |
try { | |
j.func = h.input.substring(0, h.input.indexOf("{")) | |
} catch (p) {} | |
m["" + o] ? n = !0 : m["" + o] = !0, | |
l.push(j) | |
} | |
g && l.splice(0, g); | |
var q = { | |
name: a.name, | |
message: a.message, | |
url: d(), | |
stack: l | |
}; | |
return b(q, a.sourceURL || a.fileName, a.line || a.lineNumber, a.message || a.description), | |
q | |
} | |
function e(b, e) { | |
var g = null; | |
e = null == e ? 0 : +e; | |
try { | |
if (g = a(b)) | |
return g | |
} catch (h) { | |
if (f.debug) | |
throw h | |
} | |
try { | |
if (g = c(b, e + 1)) | |
return g | |
} catch (h) { | |
if (f.debug) | |
throw h | |
} | |
return { | |
name: b.name, | |
message: b.message, | |
url: d() | |
} | |
} | |
return e.augmentStackTraceWithInitialElement = b, | |
e.computeStackTraceFromStackProp = a, | |
e | |
}(), | |
b.exports = f | |
} | |
).call(this, "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}) | |
} | |
, { | |
5: 5 | |
}], | |
7: [function(a, b, c) { | |
function d(a, b) { | |
for (var c = 0; c < a.length; ++c) | |
if (a[c] === b) | |
return c; | |
return -1 | |
} | |
function g(a, b) { | |
var c = [] | |
, e = []; | |
return null == b && (b = function(a, b) { | |
return c[0] === b ? "[Circular ~]" : "[Circular ~." + e.slice(0, d(c, b)).join(".") + "]" | |
} | |
), | |
function(g, h) { | |
if (0 < c.length) { | |
var i = d(c, this); | |
~i ? c.splice(i + 1) : c.push(this), | |
~i ? e.splice(i, 1 / 0, g) : e.push(g), | |
~d(c, h) && (h = b.call(this, g, h)) | |
} else | |
c.push(h); | |
return null == a ? h instanceof Error ? function(a) { | |
var b = { | |
stack: a.stack, | |
message: a.message, | |
name: a.name | |
}; | |
for (var c in a) | |
Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); | |
return b | |
}(h) : h : a.call(this, g, h) | |
} | |
} | |
(b.exports = function(a, b, c, d) { | |
return JSON.stringify(a, g(b, d), c) | |
} | |
).getSerialize = g | |
} | |
, {}] | |
}, {}, [4])(4) | |
}), | |
function(factory) { | |
"function" == typeof define && define.amd ? define(["jquery"], factory) : "object" == typeof exports ? factory(require("jquery")) : factory(jQuery) | |
}(function($) { | |
$.ajaxPrefilter(function(options, originalOptions, jqXHR) { | |
jqXHR.retry = function(opts) { | |
return opts.timeout && (this.timeout = opts.timeout), | |
opts.statusCodes && (this.statusCodes = opts.statusCodes), | |
this.pipe(null, function(jqXHR, opts) { | |
var times = opts.times | |
, timeout = jqXHR.timeout; | |
return function(input, status, msg) { | |
var ajaxOptions = this | |
, output = new $.Deferred | |
, retryAfter = jqXHR.getResponseHeader("Retry-After"); | |
function nextRequest() { | |
$.ajax(ajaxOptions).retry({ | |
times: times - 1, | |
timeout: opts.timeout, | |
statusCodes: opts.statusCodes | |
}).pipe(output.resolve, output.reject) | |
} | |
return 1 < times && (!jqXHR.statusCodes || -1 < $.inArray(input.status, jqXHR.statusCodes)) ? (retryAfter && (timeout = isNaN(retryAfter) ? new Date(retryAfter).getTime() - $.now() : 1e3 * parseInt(retryAfter, 10), | |
(isNaN(timeout) || timeout < 0) && (timeout = jqXHR.timeout)), | |
void 0 !== timeout ? setTimeout(nextRequest, timeout) : nextRequest()) : output.rejectWith(this, arguments), | |
output | |
} | |
}(this, opts)) | |
} | |
}) | |
}), | |
function(root, factory) { | |
var origin, modules = {}, _require = function(deps, callback) { | |
var args, len, i; | |
if ("string" == typeof deps) | |
return getModule(deps); | |
for (args = [], | |
len = deps.length, | |
i = 0; i < len; i++) | |
args.push(getModule(deps[i])); | |
return callback.apply(null, args) | |
}, _define = function(id, deps, factory) { | |
2 === arguments.length && (factory = deps, | |
deps = null), | |
_require(deps || [], function() { | |
setModule(id, factory, arguments) | |
}) | |
}, setModule = function(id, factory, args) { | |
var returned, module = { | |
exports: factory | |
}; | |
"function" == typeof factory && (args.length || (args = [_require, module.exports, module]), | |
void 0 !== (returned = factory.apply(null, args)) && (module.exports = returned)), | |
modules[id] = module.exports | |
}, getModule = function(id) { | |
var module = modules[id] || root[id]; | |
if (!module) | |
throw new Error("`" + id + "` is undefined"); | |
return module | |
}, makeExport = function(dollar) { | |
return root.__dollar = dollar, | |
function(obj) { | |
var key, host, parts, part, last, ucFirst; | |
for (key in ucFirst = function(str) { | |
return str && str.charAt(0).toUpperCase() + str.substr(1) | |
} | |
, | |
modules) | |
if (host = obj, | |
modules.hasOwnProperty(key)) { | |
for (last = ucFirst((parts = key.split("/")).pop()); part = ucFirst(parts.shift()); ) | |
host[part] = host[part] || {}, | |
host = host[part]; | |
host[last] = modules[key] | |
} | |
return obj | |
}((window = root, | |
require = _require, | |
(define = _define)("dollar-third", [], function() { | |
var req = window.require | |
, $ = window.__dollar || window.jQuery || window.Zepto || req("jquery") || req("zepto"); | |
if (!$) | |
throw new Error("jQuery or Zepto not found!"); | |
return $ | |
}), | |
define("dollar", ["dollar-third"], function(_) { | |
return _ | |
}), | |
define("promise-third", ["dollar"], function($) { | |
return { | |
Deferred: $.Deferred, | |
when: $.when, | |
isPromise: function(anything) { | |
return anything && "function" == typeof anything.then | |
} | |
} | |
}), | |
define("promise", ["promise-third"], function(_) { | |
return _ | |
}), | |
define("base", ["dollar", "promise"], function($, promise) { | |
var counter, fn, ua, ret, webkit, chrome, ie, firefox, safari, opera, noop = function() {}, call = Function.call; | |
function bindFn(fn, context) { | |
return function() { | |
return fn.apply(context, arguments) | |
} | |
} | |
return { | |
version: "0.1.8-alpha", | |
$: $, | |
Deferred: promise.Deferred, | |
isPromise: promise.isPromise, | |
when: promise.when, | |
browser: (ua = navigator.userAgent, | |
ret = {}, | |
webkit = ua.match(/WebKit\/([\d.]+)/), | |
chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/), | |
ie = ua.match(/MSIE\s([\d\.]+)/) || ua.match(/(?:trident)(?:.*rv:([\w.]+))?/i), | |
firefox = ua.match(/Firefox\/([\d.]+)/), | |
safari = ua.match(/Safari\/([\d.]+)/), | |
opera = ua.match(/OPR\/([\d.]+)/), | |
webkit && (ret.webkit = parseFloat(webkit[1])), | |
chrome && (ret.chrome = parseFloat(chrome[1])), | |
ie && (ret.ie = parseFloat(ie[1])), | |
firefox && (ret.firefox = parseFloat(firefox[1])), | |
safari && (ret.safari = parseFloat(safari[1])), | |
opera && (ret.opera = parseFloat(opera[1])), | |
ret), | |
os: function(ua) { | |
var ret = {} | |
, android = ua.match(/(?:Android);?[\s\/]+([\d.]+)?/) | |
, ios = ua.match(/(?:iPad|iPod|iPhone).*OS\s([\d_]+)/); | |
return android && (ret.android = parseFloat(android[1])), | |
ios && (ret.ios = parseFloat(ios[1].replace(/_/g, "."))), | |
ret | |
}(navigator.userAgent), | |
inherits: function(Super, protos, staticProtos) { | |
var child, proto, f; | |
return "function" == typeof protos ? (child = protos, | |
protos = null) : child = protos && protos.hasOwnProperty("constructor") ? protos.constructor : function() { | |
return Super.apply(this, arguments) | |
} | |
, | |
$.extend(!0, child, Super, staticProtos || {}), | |
child.__super__ = Super.prototype, | |
child.prototype = (proto = Super.prototype, | |
Object.create ? Object.create(proto) : ((f = function() {} | |
).prototype = proto, | |
new f)), | |
protos && $.extend(!0, child.prototype, protos), | |
child | |
}, | |
noop: noop, | |
bindFn: bindFn, | |
log: window.console ? bindFn(console.log, console) : noop, | |
nextTick: function(cb) { | |
setTimeout(cb, 1) | |
}, | |
slice: (fn = [].slice, | |
function() { | |
return call.apply(fn, arguments) | |
} | |
), | |
guid: (counter = 0, | |
function(prefix) { | |
for (var guid = (+new Date).toString(32), i = 0; i < 5; i++) | |
guid += Math.floor(65535 * Math.random()).toString(32); | |
return (prefix || "wu_") + guid + (counter++).toString(32) | |
} | |
), | |
formatSize: function(size, pointLength, units) { | |
var unit; | |
for (units = units || ["B", "K", "M", "G", "TB"]; (unit = units.shift()) && 1024 < size; ) | |
size /= 1024; | |
return ("B" === unit ? size : size.toFixed(pointLength || 2)) + unit | |
} | |
} | |
}), | |
define("mediator", ["base"], function(Base) { | |
var protos, $ = Base.$, slice = [].slice, separator = /\s+/; | |
function findHandlers(arr, name, callback, context) { | |
return $.grep(arr, function(handler) { | |
return handler && (!name || handler.e === name) && (!callback || handler.cb === callback || handler.cb._cb === callback) && (!context || handler.ctx === context) | |
}) | |
} | |
function eachEvent(events, callback, iterator) { | |
$.each((events || "").split(separator), function(_, key) { | |
iterator(key, callback) | |
}) | |
} | |
function triggerHanders(events, args) { | |
for (var handler, stoped = !1, i = -1, len = events.length; ++i < len; ) | |
if (!1 === (handler = events[i]).cb.apply(handler.ctx2, args)) { | |
stoped = !0; | |
break | |
} | |
return !stoped | |
} | |
return protos = { | |
on: function(name, callback, context) { | |
var set, me = this; | |
return callback && (set = this._events || (this._events = []), | |
eachEvent(name, callback, function(name, callback) { | |
var handler = { | |
e: name | |
}; | |
handler.cb = callback, | |
handler.ctx = context, | |
handler.ctx2 = context || me, | |
handler.id = set.length, | |
set.push(handler) | |
})), | |
this | |
}, | |
once: function(name, callback, context) { | |
var me = this; | |
return callback && eachEvent(name, callback, function(name, callback) { | |
var once = function() { | |
return me.off(name, once), | |
callback.apply(context || me, arguments) | |
}; | |
once._cb = callback, | |
me.on(name, once, context) | |
}), | |
me | |
}, | |
off: function(name, cb, ctx) { | |
var events = this._events; | |
return events && (name || cb || ctx ? eachEvent(name, cb, function(name, cb) { | |
$.each(findHandlers(events, name, cb, ctx), function() { | |
delete events[this.id] | |
}) | |
}) : this._events = []), | |
this | |
}, | |
trigger: function(type) { | |
var args, events, allEvents; | |
return this._events && type ? (args = slice.call(arguments, 1), | |
events = findHandlers(this._events, type), | |
allEvents = findHandlers(this._events, "all"), | |
triggerHanders(events, args) && triggerHanders(allEvents, arguments)) : this | |
} | |
}, | |
$.extend({ | |
installTo: function(obj) { | |
return $.extend(obj, protos) | |
} | |
}, protos) | |
}), | |
define("uploader", ["base", "mediator"], function(Base, Mediator) { | |
var $ = Base.$; | |
function Uploader(opts) { | |
this.options = $.extend(!0, {}, Uploader.options, opts), | |
this._init(this.options) | |
} | |
return Uploader.options = {}, | |
Mediator.installTo(Uploader.prototype), | |
$.each({ | |
upload: "start-upload", | |
stop: "stop-upload", | |
getFile: "get-file", | |
getFiles: "get-files", | |
addFile: "add-file", | |
addFiles: "add-file", | |
sort: "sort-files", | |
removeFile: "remove-file", | |
cancelFile: "cancel-file", | |
skipFile: "skip-file", | |
retry: "retry", | |
isInProgress: "is-in-progress", | |
makeThumb: "make-thumb", | |
md5File: "md5-file", | |
getDimension: "get-dimension", | |
addButton: "add-btn", | |
predictRuntimeType: "predict-runtime-type", | |
refresh: "refresh", | |
disable: "disable", | |
enable: "enable", | |
reset: "reset" | |
}, function(fn, command) { | |
Uploader.prototype[fn] = function() { | |
return this.request(command, arguments) | |
} | |
}), | |
$.extend(Uploader.prototype, { | |
state: "pending", | |
_init: function(opts) { | |
var me = this; | |
me.request("init", opts, function() { | |
me.state = "ready", | |
me.trigger("ready") | |
}) | |
}, | |
option: function(key, val) { | |
var opts = this.options; | |
if (!(1 < arguments.length)) | |
return key ? opts[key] : opts; | |
$.isPlainObject(val) && $.isPlainObject(opts[key]) ? $.extend(opts[key], val) : opts[key] = val | |
}, | |
getStats: function() { | |
var stats = this.request("get-stats"); | |
return stats ? { | |
successNum: stats.numOfSuccess, | |
progressNum: stats.numOfProgress, | |
cancelNum: stats.numOfCancel, | |
invalidNum: stats.numOfInvalid, | |
uploadFailNum: stats.numOfUploadFailed, | |
queueNum: stats.numOfQueue, | |
interruptNum: stats.numofInterrupt | |
} : {} | |
}, | |
trigger: function(type) { | |
var args = [].slice.call(arguments, 1) | |
, opts = this.options | |
, name = "on" + type.substring(0, 1).toUpperCase() + type.substring(1); | |
return !(!1 === Mediator.trigger.apply(this, arguments) || $.isFunction(opts[name]) && !1 === opts[name].apply(this, args) || $.isFunction(this[name]) && !1 === this[name].apply(this, args) || !1 === Mediator.trigger.apply(Mediator, [this, type].concat(args))) | |
}, | |
destroy: function() { | |
this.request("destroy", arguments), | |
this.off() | |
}, | |
request: Base.noop | |
}), | |
Base.create = Uploader.create = function(opts) { | |
return new Uploader(opts) | |
} | |
, | |
Base.Uploader = Uploader | |
}), | |
define("runtime/runtime", ["base", "mediator"], function(Base, Mediator) { | |
var $ = Base.$ | |
, factories = {} | |
, getFirstKey = function(obj) { | |
for (var key in obj) | |
if (obj.hasOwnProperty(key)) | |
return key; | |
return null | |
}; | |
function Runtime(options) { | |
this.options = $.extend({ | |
container: document.body | |
}, options), | |
this.uid = Base.guid("rt_") | |
} | |
return $.extend(Runtime.prototype, { | |
getContainer: function() { | |
var parent, container, opts = this.options; | |
return this._container ? this._container : (parent = $(opts.container || document.body), | |
(container = $(document.createElement("div"))).attr("id", "rt_" + this.uid), | |
container.css({ | |
position: "absolute", | |
top: "0px", | |
left: "0px", | |
width: "1px", | |
height: "1px", | |
overflow: "hidden" | |
}), | |
parent.append(container), | |
parent.addClass("webuploader-container"), | |
this._container = container, | |
this._parent = parent, | |
container) | |
}, | |
init: Base.noop, | |
exec: Base.noop, | |
destroy: function() { | |
this._container && this._container.remove(), | |
this._parent && this._parent.removeClass("webuploader-container"), | |
this.off() | |
} | |
}), | |
Runtime.orders = "html5,flash", | |
Runtime.addRuntime = function(type, factory) { | |
factories[type] = factory | |
} | |
, | |
Runtime.hasRuntime = function(type) { | |
return !!(type ? factories[type] : getFirstKey(factories)) | |
} | |
, | |
Runtime.create = function(opts, orders) { | |
var type; | |
if (orders = orders || Runtime.orders, | |
$.each(orders.split(/\s*,\s*/g), function() { | |
if (factories[this]) | |
return type = this, | |
!1 | |
}), | |
!(type = type || getFirstKey(factories))) | |
throw new Error("Runtime Error"); | |
return new factories[type](opts) | |
} | |
, | |
Mediator.installTo(Runtime.prototype), | |
Runtime | |
}), | |
define("runtime/client", ["base", "mediator", "runtime/runtime"], function(Base, Mediator, Runtime) { | |
var cache, obj; | |
function RuntimeClient(component, standalone) { | |
var runtime, destroy, deferred = Base.Deferred(); | |
this.uid = Base.guid("client_"), | |
this.runtimeReady = function(cb) { | |
return deferred.done(cb) | |
} | |
, | |
this.connectRuntime = function(opts, cb) { | |
if (runtime) | |
throw new Error("already connected!"); | |
return deferred.done(cb), | |
"string" == typeof opts && cache.get(opts) && (runtime = cache.get(opts)), | |
(runtime = runtime || cache.get(null, standalone)) ? (Base.$.extend(runtime.options, opts), | |
runtime.__promise.then(deferred.resolve), | |
runtime.__client++) : ((runtime = Runtime.create(opts, opts.runtimeOrder)).__promise = deferred.promise(), | |
runtime.once("ready", deferred.resolve), | |
runtime.init(), | |
cache.add(runtime), | |
runtime.__client = 1), | |
standalone && (runtime.__standalone = standalone), | |
runtime | |
} | |
, | |
this.getRuntime = function() { | |
return runtime | |
} | |
, | |
this.disconnectRuntime = function() { | |
runtime && (runtime.__client--, | |
runtime.__client <= 0 && (cache.remove(runtime), | |
delete runtime.__promise, | |
runtime.destroy()), | |
runtime = null) | |
} | |
, | |
this.exec = function() { | |
if (runtime) { | |
var args = Base.slice(arguments); | |
return component && args.unshift(component), | |
runtime.exec.apply(this, args) | |
} | |
} | |
, | |
this.getRuid = function() { | |
return runtime && runtime.uid | |
} | |
, | |
this.destroy = (destroy = this.destroy, | |
function() { | |
destroy && destroy.apply(this, arguments), | |
this.trigger("destroy"), | |
this.off(), | |
this.exec("destroy"), | |
this.disconnectRuntime() | |
} | |
) | |
} | |
return obj = {}, | |
cache = { | |
add: function(runtime) { | |
obj[runtime.uid] = runtime | |
}, | |
get: function(ruid, standalone) { | |
var i; | |
if (ruid) | |
return obj[ruid]; | |
for (i in obj) | |
if (!standalone || !obj[i].__standalone) | |
return obj[i]; | |
return null | |
}, | |
remove: function(runtime) { | |
delete obj[runtime.uid] | |
} | |
}, | |
Mediator.installTo(RuntimeClient.prototype), | |
RuntimeClient | |
}), | |
define("lib/dnd", ["base", "mediator", "runtime/client"], function(Base, Mediator, RuntimeClent) { | |
var $ = Base.$; | |
function DragAndDrop(opts) { | |
(opts = this.options = $.extend({}, DragAndDrop.options, opts)).container = $(opts.container), | |
opts.container.length && RuntimeClent.call(this, "DragAndDrop") | |
} | |
return DragAndDrop.options = { | |
accept: null, | |
disableGlobalDnd: !1 | |
}, | |
Base.inherits(RuntimeClent, { | |
constructor: DragAndDrop, | |
init: function() { | |
var me = this; | |
me.connectRuntime(me.options, function() { | |
me.exec("init"), | |
me.trigger("ready") | |
}) | |
} | |
}), | |
Mediator.installTo(DragAndDrop.prototype), | |
DragAndDrop | |
}), | |
define("widgets/widget", ["base", "uploader"], function(Base, Uploader) { | |
var $ = Base.$ | |
, _init = Uploader.prototype._init | |
, _destroy = Uploader.prototype.destroy | |
, IGNORE = {} | |
, widgetClass = []; | |
function Widget(uploader) { | |
this.owner = uploader, | |
this.options = uploader.options | |
} | |
return $.extend(Widget.prototype, { | |
init: Base.noop, | |
invoke: function(apiName, args) { | |
var map = this.responseMap; | |
return map && apiName in map && map[apiName]in this && $.isFunction(this[map[apiName]]) ? this[map[apiName]].apply(this, args) : IGNORE | |
}, | |
request: function() { | |
return this.owner.request.apply(this.owner, arguments) | |
} | |
}), | |
$.extend(Uploader.prototype, { | |
_init: function() { | |
var me = this | |
, widgets = me._widgets = [] | |
, deactives = me.options.disableWidgets || ""; | |
return $.each(widgetClass, function(_, klass) { | |
(!deactives || !~deactives.indexOf(klass._name)) && widgets.push(new klass(me)) | |
}), | |
_init.apply(me, arguments) | |
}, | |
request: function(apiName, args, callback) { | |
var rlt, promise, key, i = 0, widgets = this._widgets, len = widgets && widgets.length, rlts = [], dfds = []; | |
for (args = function(obj) { | |
if (!obj) | |
return !1; | |
var length = obj.length | |
, type = $.type(obj); | |
return !(1 !== obj.nodeType || !length) || "array" === type || "function" !== type && "string" !== type && (0 === length || "number" == typeof length && 0 < length && length - 1 in obj) | |
}(args) ? args : [args]; i < len; i++) | |
(rlt = widgets[i].invoke(apiName, args)) !== IGNORE && (Base.isPromise(rlt) ? dfds.push(rlt) : rlts.push(rlt)); | |
return callback || dfds.length ? (promise = Base.when.apply(Base, dfds))[key = promise.pipe ? "pipe" : "then"](function() { | |
var deferred = Base.Deferred() | |
, args = arguments; | |
return 1 === args.length && (args = args[0]), | |
setTimeout(function() { | |
deferred.resolve(args) | |
}, 1), | |
deferred.promise() | |
})[callback ? key : "done"](callback || Base.noop) : rlts[0] | |
}, | |
destroy: function() { | |
_destroy.apply(this, arguments), | |
this._widgets = null | |
} | |
}), | |
Uploader.register = Widget.register = function(responseMap, widgetProto) { | |
var klass, map = { | |
init: "init", | |
destroy: "destroy", | |
name: "anonymous" | |
}; | |
return 1 === arguments.length ? (widgetProto = responseMap, | |
$.each(widgetProto, function(key) { | |
"_" !== key[0] && "name" !== key ? map[key.replace(/[A-Z]/g, "-$&").toLowerCase()] = key : "name" === key && (map.name = widgetProto.name) | |
})) : map = $.extend(map, responseMap), | |
widgetProto.responseMap = map, | |
(klass = Base.inherits(Widget, widgetProto))._name = map.name, | |
widgetClass.push(klass), | |
klass | |
} | |
, | |
Uploader.unRegister = Widget.unRegister = function(name) { | |
if (name && "anonymous" !== name) | |
for (var i = widgetClass.length; i--; ) | |
widgetClass[i]._name === name && widgetClass.splice(i, 1) | |
} | |
, | |
Widget | |
}), | |
define("widgets/filednd", ["base", "uploader", "lib/dnd", "widgets/widget"], function(Base, Uploader, Dnd) { | |
var $ = Base.$; | |
return Uploader.options.dnd = "", | |
Uploader.register({ | |
name: "dnd", | |
init: function(opts) { | |
if (opts.dnd && "html5" === this.request("predict-runtime-type")) { | |
var dnd, me = this, deferred = Base.Deferred(), options = $.extend({}, { | |
disableGlobalDnd: opts.disableGlobalDnd, | |
container: opts.dnd, | |
accept: opts.accept | |
}); | |
return this.dnd = dnd = new Dnd(options), | |
dnd.once("ready", deferred.resolve), | |
dnd.on("drop", function(files) { | |
me.request("add-file", [files]) | |
}), | |
dnd.on("accept", function(items) { | |
return me.owner.trigger("dndAccept", items) | |
}), | |
dnd.init(), | |
deferred.promise() | |
} | |
}, | |
destroy: function() { | |
this.dnd && this.dnd.destroy() | |
} | |
}) | |
}), | |
define("lib/filepaste", ["base", "mediator", "runtime/client"], function(Base, Mediator, RuntimeClent) { | |
var $ = Base.$; | |
function FilePaste(opts) { | |
(opts = this.options = $.extend({}, opts)).container = $(opts.container || document.body), | |
RuntimeClent.call(this, "FilePaste") | |
} | |
return Base.inherits(RuntimeClent, { | |
constructor: FilePaste, | |
init: function() { | |
var me = this; | |
me.connectRuntime(me.options, function() { | |
me.exec("init"), | |
me.trigger("ready") | |
}) | |
} | |
}), | |
Mediator.installTo(FilePaste.prototype), | |
FilePaste | |
}), | |
define("widgets/filepaste", ["base", "uploader", "lib/filepaste", "widgets/widget"], function(Base, Uploader, FilePaste) { | |
var $ = Base.$; | |
return Uploader.register({ | |
name: "paste", | |
init: function(opts) { | |
if (opts.paste && "html5" === this.request("predict-runtime-type")) { | |
var paste, me = this, deferred = Base.Deferred(), options = $.extend({}, { | |
container: opts.paste, | |
accept: opts.accept | |
}); | |
return this.paste = paste = new FilePaste(options), | |
paste.once("ready", deferred.resolve), | |
paste.on("paste", function(files) { | |
me.owner.request("add-file", [files]) | |
}), | |
paste.init(), | |
deferred.promise() | |
} | |
}, | |
destroy: function() { | |
this.paste && this.paste.destroy() | |
} | |
}) | |
}), | |
define("lib/blob", ["base", "runtime/client"], function(Base, RuntimeClient) { | |
function Blob(ruid, source) { | |
this.source = source, | |
this.ruid = ruid, | |
this.size = source.size || 0, | |
!source.type && this.ext && ~"jpg,jpeg,png,gif,bmp".indexOf(this.ext) ? this.type = "image/" + ("jpg" === this.ext ? "jpeg" : this.ext) : this.type = source.type || "application/octet-stream", | |
RuntimeClient.call(this, "Blob"), | |
this.uid = source.uid || this.uid, | |
ruid && this.connectRuntime(ruid) | |
} | |
return Base.inherits(RuntimeClient, { | |
constructor: Blob, | |
slice: function(start, end) { | |
return this.exec("slice", start, end) | |
}, | |
getSource: function() { | |
return this.source | |
} | |
}), | |
Blob | |
}), | |
define("lib/file", ["base", "lib/blob"], function(Base, Blob) { | |
var uid = 1 | |
, rExt = /\.([^.]+)$/; | |
return Base.inherits(Blob, function(ruid, file) { | |
var ext; | |
this.name = file.name || "untitled" + uid++, | |
!(ext = rExt.exec(file.name) ? RegExp.$1.toLowerCase() : "") && file.type && (ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec(file.type) ? RegExp.$1.toLowerCase() : "", | |
this.name += "." + ext), | |
this.ext = ext, | |
this.lastModifiedDate = file.lastModifiedDate || (new Date).toLocaleString(), | |
Blob.apply(this, arguments) | |
}) | |
}), | |
define("lib/filepicker", ["base", "runtime/client", "lib/file"], function(Base, RuntimeClient, File) { | |
var $ = Base.$; | |
function FilePicker(opts) { | |
if ((opts = this.options = $.extend({}, FilePicker.options, opts)).container = $(opts.id), | |
!opts.container.length) | |
throw new Error("按钮指定错误"); | |
opts.innerHTML = opts.innerHTML || opts.label || opts.container.html() || "", | |
opts.button = $(opts.button || document.createElement("div")), | |
opts.button.html(opts.innerHTML), | |
opts.container.html(opts.button), | |
RuntimeClient.call(this, "FilePicker", !0) | |
} | |
return FilePicker.options = { | |
button: null, | |
container: null, | |
label: null, | |
innerHTML: null, | |
multiple: !0, | |
accept: null, | |
name: "file", | |
style: "webuploader-pick" | |
}, | |
Base.inherits(RuntimeClient, { | |
constructor: FilePicker, | |
init: function() { | |
var me = this | |
, opts = me.options | |
, button = opts.button | |
, style = opts.style; | |
style && button.addClass("webuploader-pick"), | |
me.on("all", function(type) { | |
var files; | |
switch (type) { | |
case "mouseenter": | |
style && button.addClass("webuploader-pick-hover"); | |
break; | |
case "mouseleave": | |
style && button.removeClass("webuploader-pick-hover"); | |
break; | |
case "change": | |
files = me.exec("getFiles"), | |
me.trigger("select", $.map(files, function(file) { | |
return (file = new File(me.getRuid(),file))._refer = opts.container, | |
file | |
}), opts.container) | |
} | |
}), | |
me.connectRuntime(opts, function() { | |
me.refresh(), | |
me.exec("init", opts), | |
me.trigger("ready") | |
}), | |
this._resizeHandler = Base.bindFn(this.refresh, this), | |
$(window).on("resize", this._resizeHandler) | |
}, | |
refresh: function() { | |
var shimContainer = this.getRuntime().getContainer() | |
, button = this.options.button | |
, width = button.outerWidth ? button.outerWidth() : button.width() | |
, height = button.outerHeight ? button.outerHeight() : button.height() | |
, pos = button.offset(); | |
width && height && shimContainer.css({ | |
bottom: "auto", | |
right: "auto", | |
width: width + "px", | |
height: height + "px" | |
}).offset(pos) | |
}, | |
enable: function() { | |
this.options.button.removeClass("webuploader-pick-disable"), | |
this.refresh() | |
}, | |
disable: function() { | |
var btn = this.options.button; | |
this.getRuntime().getContainer().css({ | |
top: "-99999px" | |
}), | |
btn.addClass("webuploader-pick-disable") | |
}, | |
destroy: function() { | |
var btn = this.options.button; | |
$(window).off("resize", this._resizeHandler), | |
btn.removeClass("webuploader-pick-disable webuploader-pick-hover webuploader-pick") | |
} | |
}), | |
FilePicker | |
}), | |
define("widgets/filepicker", ["base", "uploader", "lib/filepicker", "widgets/widget"], function(Base, Uploader, FilePicker) { | |
var $ = Base.$; | |
return $.extend(Uploader.options, { | |
pick: null, | |
accept: null | |
}), | |
Uploader.register({ | |
name: "picker", | |
init: function(opts) { | |
return this.pickers = [], | |
opts.pick && this.addBtn(opts.pick) | |
}, | |
refresh: function() { | |
$.each(this.pickers, function() { | |
this.refresh() | |
}) | |
}, | |
addBtn: function(pick) { | |
var me = this | |
, opts = me.options | |
, accept = opts.accept | |
, promises = []; | |
if (pick) | |
return $.isPlainObject(pick) || (pick = { | |
id: pick | |
}), | |
$(pick.id).each(function() { | |
var options, picker, deferred; | |
deferred = Base.Deferred(), | |
options = $.extend({}, pick, { | |
accept: $.isPlainObject(accept) ? [accept] : accept, | |
swf: opts.swf, | |
runtimeOrder: opts.runtimeOrder, | |
id: this | |
}), | |
(picker = new FilePicker(options)).once("ready", deferred.resolve), | |
picker.on("select", function(files) { | |
me.owner.request("add-file", [files]) | |
}), | |
picker.on("dialogopen", function() { | |
me.owner.trigger("dialogOpen", picker.button) | |
}), | |
picker.init(), | |
me.pickers.push(picker), | |
promises.push(deferred.promise()) | |
}), | |
Base.when.apply(Base, promises) | |
}, | |
disable: function() { | |
$.each(this.pickers, function() { | |
this.disable() | |
}) | |
}, | |
enable: function() { | |
$.each(this.pickers, function() { | |
this.enable() | |
}) | |
}, | |
destroy: function() { | |
$.each(this.pickers, function() { | |
this.destroy() | |
}), | |
this.pickers = null | |
} | |
}) | |
}), | |
define("lib/image", ["base", "runtime/client", "lib/blob"], function(Base, RuntimeClient, Blob) { | |
var $ = Base.$; | |
function Image(opts) { | |
this.options = $.extend({}, Image.options, opts), | |
RuntimeClient.call(this, "Image"), | |
this.on("load", function() { | |
this._info = this.exec("info"), | |
this._meta = this.exec("meta") | |
}) | |
} | |
return Image.options = { | |
quality: 90, | |
crop: !1, | |
preserveHeaders: !1, | |
allowMagnify: !1 | |
}, | |
Base.inherits(RuntimeClient, { | |
constructor: Image, | |
info: function(val) { | |
return val ? (this._info = val, | |
this) : this._info | |
}, | |
meta: function(val) { | |
return val ? (this._meta = val, | |
this) : this._meta | |
}, | |
loadFromBlob: function(blob) { | |
var me = this | |
, ruid = blob.getRuid(); | |
this.connectRuntime(ruid, function() { | |
me.exec("init", me.options), | |
me.exec("loadFromBlob", blob) | |
}) | |
}, | |
resize: function() { | |
var args = Base.slice(arguments); | |
return this.exec.apply(this, ["resize"].concat(args)) | |
}, | |
crop: function() { | |
var args = Base.slice(arguments); | |
return this.exec.apply(this, ["crop"].concat(args)) | |
}, | |
getAsDataUrl: function(type) { | |
return this.exec("getAsDataUrl", type) | |
}, | |
getAsBlob: function(type) { | |
var blob = this.exec("getAsBlob", type); | |
return new Blob(this.getRuid(),blob) | |
} | |
}), | |
Image | |
}), | |
define("widgets/image", ["base", "uploader", "lib/image", "widgets/widget"], function(Base, Uploader, Image) { | |
var throttle, occupied, waiting, tick, $ = Base.$; | |
return occupied = 0, | |
waiting = [], | |
tick = function() { | |
for (var item; waiting.length && occupied < 5242880; ) | |
item = waiting.shift(), | |
occupied += item[0], | |
item[1]() | |
} | |
, | |
throttle = function(emiter, size, cb) { | |
waiting.push([size, cb]), | |
emiter.once("destroy", function() { | |
occupied -= size, | |
setTimeout(tick, 1) | |
}), | |
setTimeout(tick, 1) | |
} | |
, | |
$.extend(Uploader.options, { | |
thumb: { | |
width: 110, | |
height: 110, | |
quality: 70, | |
allowMagnify: !0, | |
crop: !0, | |
preserveHeaders: !1, | |
type: "image/jpeg" | |
}, | |
compress: { | |
width: 1600, | |
height: 1600, | |
quality: 90, | |
allowMagnify: !1, | |
crop: !1, | |
preserveHeaders: !0 | |
} | |
}), | |
Uploader.register({ | |
name: "image", | |
makeThumb: function(file, cb, width, height) { | |
var opts, image; | |
(file = this.request("get-file", file)).type.match(/^image/) ? (opts = $.extend({}, this.options.thumb), | |
$.isPlainObject(width) && (opts = $.extend(opts, width), | |
width = null), | |
width = width || opts.width, | |
height = height || opts.height, | |
(image = new Image(opts)).once("load", function() { | |
file._info = file._info || image.info(), | |
file._meta = file._meta || image.meta(), | |
width <= 1 && 0 < width && (width = file._info.width * width), | |
height <= 1 && 0 < height && (height = file._info.height * height), | |
image.resize(width, height) | |
}), | |
image.once("complete", function() { | |
cb(!1, image.getAsDataUrl(opts.type)), | |
image.destroy() | |
}), | |
image.once("error", function(reason) { | |
cb(reason || !0), | |
image.destroy() | |
}), | |
throttle(image, file.source.size, function() { | |
file._info && image.info(file._info), | |
file._meta && image.meta(file._meta), | |
image.loadFromBlob(file.source) | |
})) : cb(!0) | |
}, | |
beforeSendFile: function(file) { | |
var image, deferred, opts = this.options.compress || this.options.resize, compressSize = opts && opts.compressSize || 0, noCompressIfLarger = opts && opts.noCompressIfLarger || !1; | |
if (file = this.request("get-file", file), | |
opts && ~"image/jpeg,image/jpg".indexOf(file.type) && !(file.size < compressSize) && !file._compressed) | |
return opts = $.extend({}, opts), | |
deferred = Base.Deferred(), | |
image = new Image(opts), | |
deferred.always(function() { | |
image.destroy(), | |
image = null | |
}), | |
image.once("error", deferred.reject), | |
image.once("load", function() { | |
var width = opts.width | |
, height = opts.height; | |
file._info = file._info || image.info(), | |
file._meta = file._meta || image.meta(), | |
width <= 1 && 0 < width && (width = file._info.width * width), | |
height <= 1 && 0 < height && (height = file._info.height * height), | |
image.resize(width, height) | |
}), | |
image.once("complete", function() { | |
var blob, size; | |
try { | |
blob = image.getAsBlob(opts.type), | |
size = file.size, | |
(!noCompressIfLarger || blob.size < size) && (file.source = blob, | |
file.size = blob.size, | |
file.trigger("resize", blob.size, size)), | |
file._compressed = !0, | |
deferred.resolve() | |
} catch (e) { | |
deferred.resolve() | |
} | |
}), | |
file._info && image.info(file._info), | |
file._meta && image.meta(file._meta), | |
image.loadFromBlob(file.source), | |
deferred.promise() | |
} | |
}) | |
}), | |
define("file", ["base", "mediator"], function(Base, Mediator) { | |
var $ = Base.$ | |
, idPrefix = "WU_FILE_" | |
, idSuffix = 0 | |
, rExt = /\.([^.]+)$/ | |
, statusMap = {}; | |
function WUFile(source) { | |
this.name = source.name || "Untitled", | |
this.size = source.size || 0, | |
this.type = source.type || "application/octet-stream", | |
this.lastModifiedDate = source.lastModifiedDate || 1 * new Date, | |
this.id = idPrefix + idSuffix++, | |
this.ext = rExt.exec(this.name) ? RegExp.$1 : "", | |
this.statusText = "", | |
statusMap[this.id] = WUFile.Status.INITED, | |
this.source = source, | |
this.loaded = 0, | |
this.on("error", function(msg) { | |
this.setStatus(WUFile.Status.ERROR, msg) | |
}) | |
} | |
return $.extend(WUFile.prototype, { | |
setStatus: function(status, text) { | |
var prevStatus = statusMap[this.id]; | |
void 0 !== text && (this.statusText = text), | |
status !== prevStatus && (statusMap[this.id] = status, | |
this.trigger("statuschange", status, prevStatus)) | |
}, | |
getStatus: function() { | |
return statusMap[this.id] | |
}, | |
getSource: function() { | |
return this.source | |
}, | |
destroy: function() { | |
this.off(), | |
delete statusMap[this.id] | |
} | |
}), | |
Mediator.installTo(WUFile.prototype), | |
WUFile.Status = { | |
INITED: "inited", | |
QUEUED: "queued", | |
PROGRESS: "progress", | |
ERROR: "error", | |
COMPLETE: "complete", | |
CANCELLED: "cancelled", | |
INTERRUPT: "interrupt", | |
INVALID: "invalid" | |
}, | |
WUFile | |
}), | |
define("queue", ["base", "mediator", "file"], function(Base, Mediator, WUFile) { | |
var $ = Base.$ | |
, STATUS = WUFile.Status; | |
function Queue() { | |
this.stats = { | |
numOfQueue: 0, | |
numOfSuccess: 0, | |
numOfCancel: 0, | |
numOfProgress: 0, | |
numOfUploadFailed: 0, | |
numOfInvalid: 0, | |
numofDeleted: 0, | |
numofInterrupt: 0 | |
}, | |
this._queue = [], | |
this._map = {} | |
} | |
return $.extend(Queue.prototype, { | |
append: function(file) { | |
return this._queue.push(file), | |
this._fileAdded(file), | |
this | |
}, | |
prepend: function(file) { | |
return this._queue.unshift(file), | |
this._fileAdded(file), | |
this | |
}, | |
getFile: function(fileId) { | |
return "string" != typeof fileId ? fileId : this._map[fileId] | |
}, | |
fetch: function(status) { | |
var i, file, len = this._queue.length; | |
for (status = status || STATUS.QUEUED, | |
i = 0; i < len; i++) | |
if (status === (file = this._queue[i]).getStatus()) | |
return file; | |
return null | |
}, | |
sort: function(fn) { | |
"function" == typeof fn && this._queue.sort(fn) | |
}, | |
getFiles: function() { | |
for (var file, sts = [].slice.call(arguments, 0), ret = [], i = 0, len = this._queue.length; i < len; i++) | |
file = this._queue[i], | |
sts.length && !~$.inArray(file.getStatus(), sts) || ret.push(file); | |
return ret | |
}, | |
removeFile: function(file) { | |
this._map[file.id] && (delete this._map[file.id], | |
this._delFile(file), | |
file.destroy(), | |
this.stats.numofDeleted++) | |
}, | |
_fileAdded: function(file) { | |
var me = this; | |
this._map[file.id] || (this._map[file.id] = file).on("statuschange", function(cur, pre) { | |
me._onFileStatusChange(cur, pre) | |
}) | |
}, | |
_delFile: function(file) { | |
for (var i = this._queue.length - 1; 0 <= i; i--) | |
if (this._queue[i] == file) { | |
this._queue.splice(i, 1); | |
break | |
} | |
}, | |
_onFileStatusChange: function(curStatus, preStatus) { | |
var stats = this.stats; | |
switch (preStatus) { | |
case STATUS.PROGRESS: | |
stats.numOfProgress--; | |
break; | |
case STATUS.QUEUED: | |
stats.numOfQueue--; | |
break; | |
case STATUS.ERROR: | |
stats.numOfUploadFailed--; | |
break; | |
case STATUS.INVALID: | |
stats.numOfInvalid--; | |
break; | |
case STATUS.INTERRUPT: | |
stats.numofInterrupt-- | |
} | |
switch (curStatus) { | |
case STATUS.QUEUED: | |
stats.numOfQueue++; | |
break; | |
case STATUS.PROGRESS: | |
stats.numOfProgress++; | |
break; | |
case STATUS.ERROR: | |
stats.numOfUploadFailed++; | |
break; | |
case STATUS.COMPLETE: | |
stats.numOfSuccess++; | |
break; | |
case STATUS.CANCELLED: | |
stats.numOfCancel++; | |
break; | |
case STATUS.INVALID: | |
stats.numOfInvalid++; | |
break; | |
case STATUS.INTERRUPT: | |
stats.numofInterrupt++ | |
} | |
} | |
}), | |
Mediator.installTo(Queue.prototype), | |
Queue | |
}), | |
define("widgets/queue", ["base", "uploader", "queue", "file", "lib/file", "runtime/client", "widgets/widget"], function(Base, Uploader, Queue, WUFile, File, RuntimeClient) { | |
var $ = Base.$ | |
, rExt = /\.\w+$/ | |
, Status = WUFile.Status; | |
return Uploader.register({ | |
name: "queue", | |
init: function(opts) { | |
var deferred, len, i, item, arr, accept, runtime, me = this; | |
if ($.isPlainObject(opts.accept) && (opts.accept = [opts.accept]), | |
opts.accept) { | |
for (arr = [], | |
i = 0, | |
len = opts.accept.length; i < len; i++) | |
(item = opts.accept[i].extensions) && arr.push(item); | |
arr.length && (accept = "\\." + arr.join(",").replace(/,/g, "$|\\.").replace(/\*/g, ".*") + "$"), | |
me.accept = new RegExp(accept,"i") | |
} | |
if (me.queue = new Queue, | |
me.stats = me.queue.stats, | |
"html5" === this.request("predict-runtime-type")) | |
return deferred = Base.Deferred(), | |
this.placeholder = runtime = new RuntimeClient("Placeholder"), | |
runtime.connectRuntime({ | |
runtimeOrder: "html5" | |
}, function() { | |
me._ruid = runtime.getRuid(), | |
deferred.resolve() | |
}), | |
deferred.promise() | |
}, | |
_wrapFile: function(file) { | |
if (!(file instanceof WUFile)) { | |
if (!(file instanceof File)) { | |
if (!this._ruid) | |
throw new Error("Can't add external files."); | |
file = new File(this._ruid,file) | |
} | |
file = new WUFile(file) | |
} | |
return file | |
}, | |
acceptFile: function(file) { | |
return !(!file || !file.size || this.accept && rExt.exec(file.name) && !this.accept.test(file.name)) | |
}, | |
_addFile: function(file) { | |
var me = this; | |
if (file = me._wrapFile(file), | |
me.owner.trigger("beforeFileQueued", file)) { | |
if (me.acceptFile(file)) | |
return me.queue.append(file), | |
me.owner.trigger("fileQueued", file), | |
file; | |
me.owner.trigger("error", "Q_TYPE_DENIED", file) | |
} | |
}, | |
getFile: function(fileId) { | |
return this.queue.getFile(fileId) | |
}, | |
addFile: function(files) { | |
var me = this; | |
files.length || (files = [files]), | |
(files = $.map(files, function(file) { | |
return me._addFile(file) | |
})).length && (me.owner.trigger("filesQueued", files), | |
me.options.auto && setTimeout(function() { | |
me.request("start-upload") | |
}, 20)) | |
}, | |
getStats: function() { | |
return this.stats | |
}, | |
removeFile: function(file, remove) { | |
file = file.id ? file : this.queue.getFile(file), | |
this.request("cancel-file", file), | |
remove && this.queue.removeFile(file) | |
}, | |
getFiles: function() { | |
return this.queue.getFiles.apply(this.queue, arguments) | |
}, | |
fetchFile: function() { | |
return this.queue.fetch.apply(this.queue, arguments) | |
}, | |
retry: function(file, noForceStart) { | |
var files, i, len; | |
if (file) | |
return (file = file.id ? file : this.queue.getFile(file)).setStatus(Status.QUEUED), | |
void (noForceStart || this.request("start-upload")); | |
for (i = 0, | |
len = (files = this.queue.getFiles(Status.ERROR)).length; i < len; i++) | |
(file = files[i]).setStatus(Status.QUEUED); | |
this.request("start-upload") | |
}, | |
sortFiles: function() { | |
return this.queue.sort.apply(this.queue, arguments) | |
}, | |
reset: function() { | |
this.owner.trigger("reset"), | |
this.queue = new Queue, | |
this.stats = this.queue.stats | |
}, | |
destroy: function() { | |
this.reset(), | |
this.placeholder && this.placeholder.destroy() | |
} | |
}) | |
}), | |
define("widgets/runtime", ["uploader", "runtime/runtime", "widgets/widget"], function(Uploader, Runtime) { | |
return Uploader.support = function() { | |
return Runtime.hasRuntime.apply(Runtime, arguments) | |
} | |
, | |
Uploader.register({ | |
name: "runtime", | |
init: function() { | |
if (!this.predictRuntimeType()) | |
throw Error("Runtime Error") | |
}, | |
predictRuntimeType: function() { | |
var i, len, orders = this.options.runtimeOrder || Runtime.orders, type = this.type; | |
if (!type) | |
for (i = 0, | |
len = (orders = orders.split(/\s*,\s*/g)).length; i < len; i++) | |
if (Runtime.hasRuntime(orders[i])) { | |
this.type = type = orders[i]; | |
break | |
} | |
return type | |
} | |
}) | |
}), | |
define("lib/transport", ["base", "runtime/client", "mediator"], function(Base, RuntimeClient, Mediator) { | |
var $ = Base.$; | |
function Transport(opts) { | |
var me = this; | |
opts = me.options = $.extend(!0, {}, Transport.options, opts || {}), | |
RuntimeClient.call(this, "Transport"), | |
this._blob = null, | |
this._formData = opts.formData || {}, | |
this._headers = opts.headers || {}, | |
this.on("progress", this._timeout), | |
this.on("load error", function() { | |
me.trigger("progress", 1), | |
clearTimeout(me._timer) | |
}) | |
} | |
return Transport.options = { | |
server: "", | |
method: "POST", | |
withCredentials: !1, | |
fileVal: "file", | |
timeout: 12e4, | |
formData: {}, | |
headers: {}, | |
sendAsBinary: !1 | |
}, | |
$.extend(Transport.prototype, { | |
appendBlob: function(key, blob, filename) { | |
var me = this | |
, opts = me.options; | |
me.getRuid() && me.disconnectRuntime(), | |
me.connectRuntime(blob.ruid, function() { | |
me.exec("init") | |
}), | |
me._blob = blob, | |
opts.fileVal = key || opts.fileVal, | |
opts.filename = filename || opts.filename | |
}, | |
append: function(key, value) { | |
"object" == typeof key ? $.extend(this._formData, key) : this._formData[key] = value | |
}, | |
setRequestHeader: function(key, value) { | |
"object" == typeof key ? $.extend(this._headers, key) : this._headers[key] = value | |
}, | |
send: function(method) { | |
this.exec("send", method), | |
this._timeout() | |
}, | |
abort: function() { | |
return clearTimeout(this._timer), | |
this.exec("abort") | |
}, | |
destroy: function() { | |
this.trigger("destroy"), | |
this.off(), | |
this.exec("destroy"), | |
this.disconnectRuntime() | |
}, | |
getResponseHeaders: function() { | |
return this.exec("getResponseHeaders") | |
}, | |
getResponse: function() { | |
return this.exec("getResponse") | |
}, | |
getResponseAsJson: function() { | |
return this.exec("getResponseAsJson") | |
}, | |
getStatus: function() { | |
return this.exec("getStatus") | |
}, | |
_timeout: function() { | |
var me = this | |
, duration = me.options.timeout; | |
duration && (clearTimeout(me._timer), | |
me._timer = setTimeout(function() { | |
me.abort(), | |
me.trigger("error", "timeout") | |
}, duration)) | |
} | |
}), | |
Mediator.installTo(Transport.prototype), | |
Transport | |
}), | |
define("widgets/upload", ["base", "uploader", "file", "lib/transport", "widgets/widget"], function(Base, Uploader, WUFile, Transport) { | |
var $ = Base.$ | |
, isPromise = Base.isPromise | |
, Status = WUFile.Status; | |
$.extend(Uploader.options, { | |
prepareNextFile: !1, | |
chunked: !1, | |
chunkSize: 5242880, | |
chunkRetry: 2, | |
chunkRetryDelay: 1e3, | |
threads: 3, | |
formData: {} | |
}), | |
Uploader.register({ | |
name: "upload", | |
init: function() { | |
var owner = this.owner | |
, me = this; | |
this.runing = !1, | |
this.progress = !1, | |
owner.on("startUpload", function() { | |
me.progress = !0 | |
}).on("uploadFinished", function() { | |
me.progress = !1 | |
}), | |
this.pool = [], | |
this.stack = [], | |
this.pending = [], | |
this.remaning = 0, | |
this.__tick = Base.bindFn(this._tick, this), | |
owner.on("uploadComplete", function(file) { | |
file.blocks && $.each(file.blocks, function(_, v) { | |
v.transport && (v.transport.abort(), | |
v.transport.destroy()), | |
delete v.transport | |
}), | |
delete file.blocks, | |
delete file.remaning | |
}) | |
}, | |
reset: function() { | |
this.request("stop-upload", !0), | |
this.runing = !1, | |
this.pool = [], | |
this.stack = [], | |
this.pending = [], | |
this.remaning = 0, | |
this._trigged = !1, | |
this._promise = null | |
}, | |
startUpload: function(file) { | |
var me = this; | |
if ($.each(me.request("get-files", Status.INVALID), function() { | |
me.request("remove-file", this) | |
}), | |
file ? (file = file.id ? file : me.request("get-file", file)).getStatus() === Status.INTERRUPT ? (file.setStatus(Status.QUEUED), | |
$.each(me.pool, function(_, v) { | |
v.file === file && (v.transport && v.transport.send(), | |
file.setStatus(Status.PROGRESS)) | |
})) : file.getStatus() !== Status.PROGRESS && file.setStatus(Status.QUEUED) : $.each(me.request("get-files", [Status.INITED]), function() { | |
this.setStatus(Status.QUEUED) | |
}), | |
me.runing) | |
return me.owner.trigger("startUpload", file), | |
Base.nextTick(me.__tick); | |
me.runing = !0; | |
var files = []; | |
file || $.each(me.pool, function(_, v) { | |
var file = v.file; | |
file.getStatus() === Status.INTERRUPT && (me._trigged = !1, | |
files.push(file), | |
v.transport && v.transport.send()) | |
}), | |
$.each(files, function() { | |
this.setStatus(Status.PROGRESS) | |
}), | |
file || $.each(me.request("get-files", Status.INTERRUPT), function() { | |
this.setStatus(Status.PROGRESS) | |
}), | |
me._trigged = !1, | |
Base.nextTick(me.__tick), | |
me.owner.trigger("startUpload") | |
}, | |
stopUpload: function(file, interrupt) { | |
var me = this; | |
if (!0 === file && (interrupt = file, | |
file = null), | |
!1 !== me.runing) { | |
if (file) { | |
if ((file = file.id ? file : me.request("get-file", file)).getStatus() !== Status.PROGRESS && file.getStatus() !== Status.QUEUED) | |
return; | |
return file.setStatus(Status.INTERRUPT), | |
$.each(me.pool, function(_, v) { | |
v.file === file && (v.transport && v.transport.abort(), | |
interrupt && (me._putback(v), | |
me._popBlock(v))) | |
}), | |
me.owner.trigger("stopUpload", file), | |
Base.nextTick(me.__tick) | |
} | |
me.runing = !1, | |
this._promise && this._promise.file && this._promise.file.setStatus(Status.INTERRUPT), | |
interrupt && $.each(me.pool, function(_, v) { | |
v.transport && v.transport.abort(), | |
v.file.setStatus(Status.INTERRUPT) | |
}), | |
me.owner.trigger("stopUpload") | |
} | |
}, | |
cancelFile: function(file) { | |
(file = file.id ? file : this.request("get-file", file)).blocks && $.each(file.blocks, function(_, v) { | |
var _tr = v.transport; | |
_tr && (_tr.abort(), | |
_tr.destroy(), | |
delete v.transport) | |
}), | |
file.setStatus(Status.CANCELLED), | |
this.owner.trigger("fileDequeued", file) | |
}, | |
isInProgress: function() { | |
return !!this.progress | |
}, | |
_getStats: function() { | |
return this.request("get-stats") | |
}, | |
skipFile: function(file, status) { | |
(file = file.id ? file : this.request("get-file", file)).setStatus(status || Status.COMPLETE), | |
file.skipped = !0, | |
file.blocks && $.each(file.blocks, function(_, v) { | |
var _tr = v.transport; | |
_tr && (_tr.abort(), | |
_tr.destroy(), | |
delete v.transport) | |
}), | |
this.owner.trigger("uploadSkip", file) | |
}, | |
_tick: function() { | |
var fn, val, me = this, opts = me.options; | |
if (me._promise) | |
return me._promise.always(me.__tick); | |
me.pool.length < opts.threads && (val = me._nextBlock()) ? (me._trigged = !1, | |
fn = function(val) { | |
me._promise = null, | |
val && val.file && me._startSend(val), | |
Base.nextTick(me.__tick) | |
} | |
, | |
me._promise = isPromise(val) ? val.always(fn) : fn(val)) : me.remaning || me._getStats().numOfQueue || me._getStats().numofInterrupt || (me.runing = !1, | |
me._trigged || Base.nextTick(function() { | |
me.owner.trigger("uploadFinished") | |
}), | |
me._trigged = !0) | |
}, | |
_putback: function(block) { | |
block.cuted.unshift(block), | |
~this.stack.indexOf(block.cuted) || this.stack.unshift(block.cuted) | |
}, | |
_getStack: function() { | |
for (var act, i = 0; act = this.stack[i++]; ) { | |
if (act.has() && act.file.getStatus() === Status.PROGRESS) | |
return act; | |
(!act.has() || act.file.getStatus() !== Status.PROGRESS && act.file.getStatus() !== Status.INTERRUPT) && this.stack.splice(--i, 1) | |
} | |
return null | |
}, | |
_nextBlock: function() { | |
var act, next, done, preparing, me = this, opts = me.options; | |
return (act = this._getStack()) ? (opts.prepareNextFile && !me.pending.length && me._prepareNextFile(), | |
act.shift()) : me.runing ? (!me.pending.length && me._getStats().numOfQueue && me._prepareNextFile(), | |
next = me.pending.shift(), | |
done = function(file) { | |
return file ? (act = function(file, chunkSize) { | |
var len, api, pending = [], total = file.source.size, chunks = chunkSize ? Math.ceil(total / chunkSize) : 1, start = 0, index = 0; | |
for (api = { | |
file: file, | |
has: function() { | |
return !!pending.length | |
}, | |
shift: function() { | |
return pending.shift() | |
}, | |
unshift: function(block) { | |
pending.unshift(block) | |
} | |
}; index < chunks; ) | |
len = Math.min(chunkSize, total - start), | |
pending.push({ | |
file: file, | |
start: start, | |
end: chunkSize ? start + len : total, | |
total: total, | |
chunks: chunks, | |
chunk: index++, | |
cuted: api | |
}), | |
start += len; | |
return 2 < pending.length && (pending.unshift(pending.pop()), | |
pending.unshift(pending.pop())), | |
file.blocks = pending.concat(), | |
file.remaning = pending.length, | |
api | |
}(file, opts.chunked ? opts.chunkSize : 0), | |
me.stack.push(act), | |
act.shift()) : null | |
} | |
, | |
isPromise(next) ? (preparing = next.file, | |
(next = next[next.pipe ? "pipe" : "then"](done)).file = preparing, | |
next) : done(next)) : void 0 | |
}, | |
_prepareNextFile: function() { | |
var promise, me = this, file = me.request("fetch-file"), pending = me.pending; | |
file && (promise = me.request("before-send-file", file, function() { | |
return file.getStatus() === Status.PROGRESS || file.getStatus() === Status.INTERRUPT ? file : me._finishFile(file) | |
}), | |
me.owner.trigger("uploadStart", file), | |
file.setStatus(Status.PROGRESS), | |
promise.file = file, | |
promise.done(function() { | |
var idx = $.inArray(promise, pending); | |
~idx && pending.splice(idx, 1, file) | |
}), | |
promise.fail(function(reason) { | |
file.setStatus(Status.ERROR, reason), | |
me.owner.trigger("uploadError", file, reason), | |
me.owner.trigger("uploadComplete", file) | |
}), | |
pending.push(promise)) | |
}, | |
_popBlock: function(block) { | |
var idx = $.inArray(block, this.pool); | |
this.pool.splice(idx, 1), | |
block.file.remaning--, | |
this.remaning-- | |
}, | |
_startSend: function(block) { | |
var me = this | |
, file = block.file; | |
file.getStatus() === Status.PROGRESS ? (me.pool.push(block), | |
me.remaning++, | |
block.blob = 1 === block.chunks ? file.source : file.source.slice(block.start, block.end), | |
me.request("before-send", block, function() { | |
file.getStatus() === Status.PROGRESS ? me._doSend(block) : (me._popBlock(block), | |
Base.nextTick(me.__tick)) | |
}).fail(function() { | |
1 === file.remaning ? me._finishFile(file).always(function() { | |
block.percentage = 1, | |
me._popBlock(block), | |
me.owner.trigger("uploadComplete", file), | |
Base.nextTick(me.__tick) | |
}) : (block.percentage = 1, | |
me.updateFileProgress(file), | |
me._popBlock(block), | |
Base.nextTick(me.__tick)) | |
})) : file.getStatus() === Status.INTERRUPT && me._putback(block) | |
}, | |
_doSend: function(block) { | |
var requestAccept, ret, me = this, owner = me.owner, opts = $.extend({}, me.options, block.options), file = block.file, tr = new Transport(opts), data = $.extend({}, opts.formData), headers = $.extend({}, opts.headers); | |
(block.transport = tr).on("destroy", function() { | |
delete block.transport, | |
me._popBlock(block), | |
Base.nextTick(me.__tick) | |
}), | |
tr.on("progress", function(percentage) { | |
block.percentage = percentage, | |
me.updateFileProgress(file) | |
}), | |
requestAccept = function(reject) { | |
var fn; | |
return (ret = tr.getResponseAsJson() || {})._raw = tr.getResponse(), | |
ret._headers = tr.getResponseHeaders(), | |
block.response = ret, | |
fn = function(value) { | |
reject = value | |
} | |
, | |
owner.trigger("uploadAccept", block, ret, fn) || (reject = reject || "server"), | |
reject | |
} | |
, | |
tr.on("error", function(type, flag) { | |
block.retried = block.retried || 0, | |
1 < block.chunks && ~"http,abort,server".indexOf(type.replace(/-.*/, "")) && block.retried < opts.chunkRetry ? (block.retried++, | |
me.retryTimer = setTimeout(function() { | |
tr.send() | |
}, opts.chunkRetryDelay || 1e3)) : (flag || "server" !== type || (type = requestAccept(type)), | |
file.setStatus(Status.ERROR, type), | |
owner.trigger("uploadError", file, type), | |
owner.trigger("uploadComplete", file)) | |
}), | |
tr.on("load", function() { | |
var reason; | |
(reason = requestAccept()) ? tr.trigger("error", reason, !0) : 1 === file.remaning ? me._finishFile(file, ret) : tr.destroy() | |
}), | |
data = $.extend(data, { | |
id: file.id, | |
name: file.name, | |
type: file.type, | |
lastModifiedDate: file.lastModifiedDate, | |
size: file.size | |
}), | |
1 < block.chunks && $.extend(data, { | |
chunks: block.chunks, | |
chunk: block.chunk | |
}), | |
owner.trigger("uploadBeforeSend", block, data, headers), | |
tr.appendBlob(opts.fileVal, block.blob, file.name), | |
tr.append(data), | |
tr.setRequestHeader(headers), | |
tr.send() | |
}, | |
_finishFile: function(file, ret, hds) { | |
var owner = this.owner; | |
return owner.request("after-send-file", arguments, function() { | |
file.setStatus(Status.COMPLETE), | |
owner.trigger("uploadSuccess", file, ret, hds) | |
}).fail(function(reason) { | |
file.getStatus() === Status.PROGRESS && file.setStatus(Status.ERROR, reason), | |
owner.trigger("uploadError", file, reason) | |
}).always(function() { | |
owner.trigger("uploadComplete", file) | |
}) | |
}, | |
updateFileProgress: function(file) { | |
var totalPercent, uploaded = 0; | |
file.blocks && ($.each(file.blocks, function(_, v) { | |
uploaded += (v.percentage || 0) * (v.end - v.start) | |
}), | |
totalPercent = uploaded / file.size, | |
this.owner.trigger("uploadProgress", file, totalPercent || 0)) | |
}, | |
destroy: function() { | |
clearTimeout(this.retryTimer) | |
} | |
}) | |
}), | |
define("widgets/validator", ["base", "uploader", "file", "widgets/widget"], function(Base, Uploader, WUFile) { | |
var api, $ = Base.$, validators = {}; | |
return api = { | |
addValidator: function(type, cb) { | |
validators[type] = cb | |
}, | |
removeValidator: function(type) { | |
delete validators[type] | |
} | |
}, | |
Uploader.register({ | |
name: "validator", | |
init: function() { | |
var me = this; | |
Base.nextTick(function() { | |
$.each(validators, function() { | |
this.call(me.owner) | |
}) | |
}) | |
} | |
}), | |
api.addValidator("fileNumLimit", function() { | |
var opts = this.options | |
, count = 0 | |
, max = parseInt(opts.fileNumLimit, 10) | |
, flag = !0; | |
max && (this.on("beforeFileQueued", function(file) { | |
return !(!this.trigger("beforeFileQueuedCheckfileNumLimit", file, count) || (max <= count && flag && (flag = !1, | |
this.trigger("error", "Q_EXCEED_NUM_LIMIT", max, file), | |
setTimeout(function() { | |
flag = !0 | |
}, 1)), | |
max <= count)) | |
}), | |
this.on("fileQueued", function() { | |
count++ | |
}), | |
this.on("fileDequeued", function() { | |
count-- | |
}), | |
this.on("reset", function() { | |
count = 0 | |
})) | |
}), | |
api.addValidator("fileSizeLimit", function() { | |
var opts = this.options | |
, count = 0 | |
, max = parseInt(opts.fileSizeLimit, 10) | |
, flag = !0; | |
max && (this.on("beforeFileQueued", function(file) { | |
var invalid = (count + file.size > max) && 0; | |
return invalid && flag && (flag = !1, | |
this.trigger("error", "Q_EXCEED_SIZE_LIMIT", max, file), | |
setTimeout(function() { | |
flag = !0 | |
}, 1)), | |
!invalid | |
}), | |
this.on("fileQueued", function(file) { | |
count += file.size | |
}), | |
this.on("fileDequeued", function(file) { | |
count -= file.size | |
}), | |
this.on("reset", function() { | |
count = 0 | |
})) | |
}), | |
api.addValidator("fileSingleSizeLimit", function() { | |
var max = this.options.fileSingleSizeLimit; | |
max && this.on("beforeFileQueued", function(file) { | |
if (file.size > max && 0) | |
return file.setStatus(WUFile.Status.INVALID, "exceed_size"), | |
this.trigger("error", "F_EXCEED_SIZE", max, file), | |
!1 | |
}) | |
}), | |
api.addValidator("duplicate", function() { | |
var opts = this.options | |
, mapping = {}; | |
opts.duplicate || (this.on("beforeFileQueued", function(file) { | |
var hash = file.__hash || (file.__hash = function(str) { | |
for (var hash = 0, i = 0, len = str.length; i < len; i++) | |
hash = str.charCodeAt(i) + (hash << 6) + (hash << 16) - hash; | |
return hash | |
}(file.name + file.size + file.lastModifiedDate)); | |
if (mapping[hash]) | |
return this.trigger("error", "F_DUPLICATE", file), | |
!1 | |
}), | |
this.on("fileQueued", function(file) { | |
var hash = file.__hash; | |
hash && (mapping[hash] = !0) | |
}), | |
this.on("fileDequeued", function(file) { | |
var hash = file.__hash; | |
hash && delete mapping[hash] | |
}), | |
this.on("reset", function() { | |
mapping = {} | |
})) | |
}), | |
api | |
}), | |
define("runtime/compbase", [], function() { | |
return function(owner, runtime) { | |
this.owner = owner, | |
this.options = owner.options, | |
this.getRuntime = function() { | |
return runtime | |
} | |
, | |
this.getRuid = function() { | |
return runtime.uid | |
} | |
, | |
this.trigger = function() { | |
return owner.trigger.apply(owner, arguments) | |
} | |
} | |
}), | |
define("runtime/html5/runtime", ["base", "runtime/runtime", "runtime/compbase"], function(Base, Runtime, CompBase) { | |
var components = {}; | |
function Html5Runtime() { | |
var pool = {} | |
, me = this | |
, destroy = this.destroy; | |
Runtime.apply(me, arguments), | |
me.type = "html5", | |
me.exec = function(comp, fn) { | |
var instance, uid = this.uid, args = Base.slice(arguments, 2); | |
if (components[comp] && (instance = pool[uid] = pool[uid] || new components[comp](this,me))[fn]) | |
return instance[fn].apply(instance, args) | |
} | |
, | |
me.destroy = function() { | |
return destroy && destroy.apply(this, arguments) | |
} | |
} | |
return Base.inherits(Runtime, { | |
constructor: Html5Runtime, | |
init: function() { | |
var me = this; | |
setTimeout(function() { | |
me.trigger("ready") | |
}, 1) | |
} | |
}), | |
Html5Runtime.register = function(name, component) { | |
return components[name] = Base.inherits(CompBase, component) | |
} | |
, | |
window.Blob && window.FileReader && window.DataView && Runtime.addRuntime("html5", Html5Runtime), | |
Html5Runtime | |
}), | |
define("runtime/html5/blob", ["runtime/html5/runtime", "lib/blob"], function(Html5Runtime, Blob) { | |
return Html5Runtime.register("Blob", { | |
slice: function(start, end) { | |
var blob = this.owner.source; | |
return blob = (blob.slice || blob.webkitSlice || blob.mozSlice).call(blob, start, end), | |
new Blob(this.getRuid(),blob) | |
} | |
}) | |
}), | |
define("runtime/html5/dnd", ["base", "runtime/html5/runtime", "lib/file"], function(Base, Html5Runtime, File) { | |
var $ = Base.$ | |
, prefix = "webuploader-dnd-"; | |
return Html5Runtime.register("DragAndDrop", { | |
init: function() { | |
var elem = this.elem = this.options.container; | |
this.dragEnterHandler = Base.bindFn(this._dragEnterHandler, this), | |
this.dragOverHandler = Base.bindFn(this._dragOverHandler, this), | |
this.dragLeaveHandler = Base.bindFn(this._dragLeaveHandler, this), | |
this.dropHandler = Base.bindFn(this._dropHandler, this), | |
this.dndOver = !1, | |
elem.on("dragenter", this.dragEnterHandler), | |
elem.on("dragover", this.dragOverHandler), | |
elem.on("dragleave", this.dragLeaveHandler), | |
elem.on("drop", this.dropHandler), | |
this.options.disableGlobalDnd && ($(document).on("dragover", this.dragOverHandler), | |
$(document).on("drop", this.dropHandler)) | |
}, | |
_dragEnterHandler: function(e) { | |
var items, me = this, denied = me._denied || !1; | |
return e = e.originalEvent || e, | |
me.dndOver || (me.dndOver = !0, | |
(items = e.dataTransfer.items) && items.length && (me._denied = denied = !me.trigger("accept", items)), | |
me.elem.addClass(prefix + "over"), | |
me.elem[denied ? "addClass" : "removeClass"](prefix + "denied")), | |
e.dataTransfer.dropEffect = denied ? "none" : "copy", | |
!1 | |
}, | |
_dragOverHandler: function(e) { | |
var parentElem = this.elem.parent().get(0); | |
return parentElem && !$.contains(parentElem, e.currentTarget) || (clearTimeout(this._leaveTimer), | |
this._dragEnterHandler.call(this, e)), | |
!1 | |
}, | |
_dragLeaveHandler: function() { | |
var handler, me = this; | |
return handler = function() { | |
me.dndOver = !1, | |
me.elem.removeClass(prefix + "over " + prefix + "denied") | |
} | |
, | |
clearTimeout(me._leaveTimer), | |
me._leaveTimer = setTimeout(handler, 100), | |
!1 | |
}, | |
_dropHandler: function(e) { | |
var dataTransfer, data, me = this, ruid = me.getRuid(), parentElem = me.elem.parent().get(0); | |
if (parentElem && !$.contains(parentElem, e.currentTarget)) | |
return !1; | |
dataTransfer = (e = e.originalEvent || e).dataTransfer; | |
try { | |
data = dataTransfer.getData("text/html") | |
} catch (err) {} | |
return me.dndOver = !1, | |
me.elem.removeClass(prefix + "over"), | |
dataTransfer && !data ? (me._getTansferFiles(dataTransfer, function(results) { | |
me.trigger("drop", $.map(results, function(file) { | |
return new File(ruid,file) | |
})) | |
}), | |
!1) : void 0 | |
}, | |
_getTansferFiles: function(dataTransfer, callback) { | |
var items, files, file, item, i, len, canAccessFolder, results = [], promises = []; | |
for (items = dataTransfer.items, | |
files = dataTransfer.files, | |
canAccessFolder = !(!items || !items[0].webkitGetAsEntry), | |
i = 0, | |
len = files.length; i < len; i++) | |
file = files[i], | |
item = items && items[i], | |
canAccessFolder && item.webkitGetAsEntry().isDirectory ? promises.push(this._traverseDirectoryTree(item.webkitGetAsEntry(), results)) : results.push(file); | |
Base.when.apply(Base, promises).done(function() { | |
results.length && callback(results) | |
}) | |
}, | |
_traverseDirectoryTree: function(entry, results) { | |
var deferred = Base.Deferred() | |
, me = this; | |
return entry.isFile ? entry.file(function(file) { | |
results.push(file), | |
deferred.resolve() | |
}) : entry.isDirectory && entry.createReader().readEntries(function(entries) { | |
var i, len = entries.length, promises = [], arr = []; | |
for (i = 0; i < len; i++) | |
promises.push(me._traverseDirectoryTree(entries[i], arr)); | |
Base.when.apply(Base, promises).then(function() { | |
results.push.apply(results, arr), | |
deferred.resolve() | |
}, deferred.reject) | |
}), | |
deferred.promise() | |
}, | |
destroy: function() { | |
var elem = this.elem; | |
elem && (elem.off("dragenter", this.dragEnterHandler), | |
elem.off("dragover", this.dragOverHandler), | |
elem.off("dragleave", this.dragLeaveHandler), | |
elem.off("drop", this.dropHandler), | |
this.options.disableGlobalDnd && ($(document).off("dragover", this.dragOverHandler), | |
$(document).off("drop", this.dropHandler))) | |
} | |
}) | |
}), | |
define("runtime/html5/filepaste", ["base", "runtime/html5/runtime", "lib/file"], function(Base, Html5Runtime, File) { | |
return Html5Runtime.register("FilePaste", { | |
init: function() { | |
var arr, i, len, item, opts = this.options, elem = this.elem = opts.container, accept = ".*"; | |
if (opts.accept) { | |
for (arr = [], | |
i = 0, | |
len = opts.accept.length; i < len; i++) | |
(item = opts.accept[i].mimeTypes) && arr.push(item); | |
arr.length && (accept = (accept = arr.join(",")).replace(/,/g, "|").replace(/\*/g, ".*")) | |
} | |
this.accept = accept = new RegExp(accept,"i"), | |
this.hander = Base.bindFn(this._pasteHander, this), | |
elem.on("paste", this.hander) | |
}, | |
_pasteHander: function(e) { | |
var items, item, blob, i, len, allowed = [], ruid = this.getRuid(); | |
for (i = 0, | |
len = (items = (e = e.originalEvent || e).clipboardData.items).length; i < len; i++) | |
"file" === (item = items[i]).kind && (blob = item.getAsFile()) && allowed.push(new File(ruid,blob)); | |
allowed.length && (e.preventDefault(), | |
e.stopPropagation(), | |
this.trigger("paste", allowed)) | |
}, | |
destroy: function() { | |
this.elem.off("paste", this.hander) | |
} | |
}) | |
}), | |
define("runtime/html5/filepicker", ["base", "runtime/html5/runtime"], function(Base, Html5Runtime) { | |
var $ = Base.$; | |
return Html5Runtime.register("FilePicker", { | |
init: function() { | |
var arr, i, len, mouseHandler, changeHandler, container = this.getRuntime().getContainer(), me = this, owner = me.owner, opts = me.options, label = this.label = $(document.createElement("label")), input = this.input = $(document.createElement("input")); | |
if (input.attr("type", "file"), | |
input.attr("name", opts.name), | |
input.addClass("webuploader-element-invisible"), | |
label.on("click", function(e) { | |
input.trigger("click"), | |
e.stopPropagation(), | |
owner.trigger("dialogopen") | |
}), | |
label.css({ | |
opacity: 0, | |
width: "100%", | |
height: "100%", | |
display: "block", | |
cursor: "pointer", | |
background: "#ffffff" | |
}), | |
opts.multiple && input.attr("multiple", "multiple"), | |
opts.accept && 0 < opts.accept.length) { | |
for (arr = [], | |
i = 0, | |
len = opts.accept.length; i < len; i++) | |
arr.push(opts.accept[i].mimeTypes); | |
input.attr("accept", arr.join(",")) | |
} | |
container.append(input), | |
container.append(label), | |
mouseHandler = function(e) { | |
owner.trigger(e.type) | |
} | |
, | |
changeHandler = function(e) { | |
var clone; | |
if (0 === e.target.files.length) | |
return !1; | |
me.files = e.target.files, | |
(clone = this.cloneNode(!0)).value = null, | |
this.parentNode.replaceChild(clone, this), | |
input.off(), | |
input = $(clone).on("change", changeHandler).on("mouseenter mouseleave", mouseHandler), | |
owner.trigger("change") | |
} | |
, | |
input.on("change", changeHandler), | |
label.on("mouseenter mouseleave", mouseHandler) | |
}, | |
getFiles: function() { | |
return this.files | |
}, | |
destroy: function() { | |
this.input.off(), | |
this.label.off() | |
} | |
}) | |
}), | |
define("runtime/html5/util", ["base"], function(Base) { | |
var urlAPI = window.createObjectURL && window || window.URL && URL.revokeObjectURL && URL || window.webkitURL | |
, createObjectURL = Base.noop | |
, revokeObjectURL = createObjectURL; | |
return urlAPI && (createObjectURL = function() { | |
return urlAPI.createObjectURL.apply(urlAPI, arguments) | |
} | |
, | |
revokeObjectURL = function() { | |
return urlAPI.revokeObjectURL.apply(urlAPI, arguments) | |
} | |
), | |
{ | |
createObjectURL: createObjectURL, | |
revokeObjectURL: revokeObjectURL, | |
dataURL2Blob: function(dataURI) { | |
var byteStr, intArray, ab, i, mimetype, parts; | |
for (byteStr = ~(parts = dataURI.split(","))[0].indexOf("base64") ? atob(parts[1]) : decodeURIComponent(parts[1]), | |
ab = new ArrayBuffer(byteStr.length), | |
intArray = new Uint8Array(ab), | |
i = 0; i < byteStr.length; i++) | |
intArray[i] = byteStr.charCodeAt(i); | |
return mimetype = parts[0].split(":")[1].split(";")[0], | |
this.arrayBufferToBlob(ab, mimetype) | |
}, | |
dataURL2ArrayBuffer: function(dataURI) { | |
var byteStr, intArray, i, parts; | |
for (byteStr = ~(parts = dataURI.split(","))[0].indexOf("base64") ? atob(parts[1]) : decodeURIComponent(parts[1]), | |
intArray = new Uint8Array(byteStr.length), | |
i = 0; i < byteStr.length; i++) | |
intArray[i] = byteStr.charCodeAt(i); | |
return intArray.buffer | |
}, | |
arrayBufferToBlob: function(buffer, type) { | |
var bb, builder = window.BlobBuilder || window.WebKitBlobBuilder; | |
return builder ? ((bb = new builder).append(buffer), | |
bb.getBlob(type)) : new Blob([buffer],type ? { | |
type: type | |
} : {}) | |
}, | |
canvasToDataUrl: function(canvas, type, quality) { | |
return canvas.toDataURL(type, quality / 100) | |
}, | |
parseMeta: function(blob, callback) { | |
callback(!1, {}) | |
}, | |
updateImageHead: function(data) { | |
return data | |
} | |
} | |
}), | |
define("runtime/html5/imagemeta", ["runtime/html5/util"], function(Util) { | |
var api; | |
return api = { | |
parsers: { | |
65505: [] | |
}, | |
maxMetaDataSize: 262144, | |
parse: function(blob, cb) { | |
var me = this | |
, fr = new FileReader; | |
fr.onload = function() { | |
cb(!1, me._parse(this.result)), | |
fr = fr.onload = fr.onerror = null | |
} | |
, | |
fr.onerror = function(e) { | |
cb(e.message), | |
fr = fr.onload = fr.onerror = null | |
} | |
, | |
blob = blob.slice(0, me.maxMetaDataSize), | |
fr.readAsArrayBuffer(blob.getSource()) | |
}, | |
_parse: function(buffer, noParse) { | |
if (!(buffer.byteLength < 6)) { | |
var markerBytes, markerLength, parsers, i, dataview = new DataView(buffer), offset = 2, maxOffset = dataview.byteLength - 4, headLength = offset, ret = {}; | |
if (65496 === dataview.getUint16(0)) { | |
for (; offset < maxOffset && (65504 <= (markerBytes = dataview.getUint16(offset)) && markerBytes <= 65519 || 65534 === markerBytes) && !(offset + (markerLength = dataview.getUint16(offset + 2) + 2) > dataview.byteLength); ) { | |
if (parsers = api.parsers[markerBytes], | |
!noParse && parsers) | |
for (i = 0; i < parsers.length; i += 1) | |
parsers[i].call(api, dataview, offset, markerLength, ret); | |
headLength = offset += markerLength | |
} | |
6 < headLength && (buffer.slice ? ret.imageHead = buffer.slice(2, headLength) : ret.imageHead = new Uint8Array(buffer).subarray(2, headLength)) | |
} | |
return ret | |
} | |
}, | |
updateImageHead: function(buffer, head) { | |
var buf1, buf2, bodyoffset, data = this._parse(buffer, !0); | |
return bodyoffset = 2, | |
data.imageHead && (bodyoffset = 2 + data.imageHead.byteLength), | |
buf2 = buffer.slice ? buffer.slice(bodyoffset) : new Uint8Array(buffer).subarray(bodyoffset), | |
(buf1 = new Uint8Array(head.byteLength + 2 + buf2.byteLength))[0] = 255, | |
buf1[1] = 216, | |
buf1.set(new Uint8Array(head), 2), | |
buf1.set(new Uint8Array(buf2), head.byteLength + 2), | |
buf1.buffer | |
} | |
}, | |
Util.parseMeta = function() { | |
return api.parse.apply(api, arguments) | |
} | |
, | |
Util.updateImageHead = function() { | |
return api.updateImageHead.apply(api, arguments) | |
} | |
, | |
api | |
}), | |
define("runtime/html5/imagemeta/exif", ["base", "runtime/html5/imagemeta"], function(Base, ImageMeta) { | |
var EXIF = { | |
ExifMap: function() { | |
return this | |
} | |
}; | |
return EXIF.ExifMap.prototype.map = { | |
Orientation: 274 | |
}, | |
EXIF.ExifMap.prototype.get = function(id) { | |
return this[id] || this[this.map[id]] | |
} | |
, | |
EXIF.exifTagTypes = { | |
1: { | |
getValue: function(dataView, dataOffset) { | |
return dataView.getUint8(dataOffset) | |
}, | |
size: 1 | |
}, | |
2: { | |
getValue: function(dataView, dataOffset) { | |
return String.fromCharCode(dataView.getUint8(dataOffset)) | |
}, | |
size: 1, | |
ascii: !0 | |
}, | |
3: { | |
getValue: function(dataView, dataOffset, littleEndian) { | |
return dataView.getUint16(dataOffset, littleEndian) | |
}, | |
size: 2 | |
}, | |
4: { | |
getValue: function(dataView, dataOffset, littleEndian) { | |
return dataView.getUint32(dataOffset, littleEndian) | |
}, | |
size: 4 | |
}, | |
5: { | |
getValue: function(dataView, dataOffset, littleEndian) { | |
return dataView.getUint32(dataOffset, littleEndian) / dataView.getUint32(dataOffset + 4, littleEndian) | |
}, | |
size: 8 | |
}, | |
9: { | |
getValue: function(dataView, dataOffset, littleEndian) { | |
return dataView.getInt32(dataOffset, littleEndian) | |
}, | |
size: 4 | |
}, | |
10: { | |
getValue: function(dataView, dataOffset, littleEndian) { | |
return dataView.getInt32(dataOffset, littleEndian) / dataView.getInt32(dataOffset + 4, littleEndian) | |
}, | |
size: 8 | |
} | |
}, | |
EXIF.exifTagTypes[7] = EXIF.exifTagTypes[1], | |
EXIF.getExifValue = function(dataView, tiffOffset, offset, type, length, littleEndian) { | |
var tagSize, dataOffset, values, i, str, c, tagType = EXIF.exifTagTypes[type]; | |
if (tagType) { | |
if (!((dataOffset = 4 < (tagSize = tagType.size * length) ? tiffOffset + dataView.getUint32(offset + 8, littleEndian) : offset + 8) + tagSize > dataView.byteLength)) { | |
if (1 === length) | |
return tagType.getValue(dataView, dataOffset, littleEndian); | |
for (values = [], | |
i = 0; i < length; i += 1) | |
values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian); | |
if (tagType.ascii) { | |
for (str = "", | |
i = 0; i < values.length && "\0" !== (c = values[i]); i += 1) | |
str += c; | |
return str | |
} | |
return values | |
} | |
Base.log("Invalid Exif data: Invalid data offset.") | |
} else | |
Base.log("Invalid Exif data: Invalid tag type.") | |
} | |
, | |
EXIF.parseExifTag = function(dataView, tiffOffset, offset, littleEndian, data) { | |
var tag = dataView.getUint16(offset, littleEndian); | |
data.exif[tag] = EXIF.getExifValue(dataView, tiffOffset, offset, dataView.getUint16(offset + 2, littleEndian), dataView.getUint32(offset + 4, littleEndian), littleEndian) | |
} | |
, | |
EXIF.parseExifTags = function(dataView, tiffOffset, dirOffset, littleEndian, data) { | |
var tagsNumber, dirEndOffset, i; | |
if (dirOffset + 6 > dataView.byteLength) | |
Base.log("Invalid Exif data: Invalid directory offset."); | |
else { | |
if (!((dirEndOffset = dirOffset + 2 + 12 * (tagsNumber = dataView.getUint16(dirOffset, littleEndian))) + 4 > dataView.byteLength)) { | |
for (i = 0; i < tagsNumber; i += 1) | |
this.parseExifTag(dataView, tiffOffset, dirOffset + 2 + 12 * i, littleEndian, data); | |
return dataView.getUint32(dirEndOffset, littleEndian) | |
} | |
Base.log("Invalid Exif data: Invalid directory size.") | |
} | |
} | |
, | |
EXIF.parseExifData = function(dataView, offset, length, data) { | |
var littleEndian, dirOffset, tiffOffset = offset + 10; | |
if (1165519206 === dataView.getUint32(offset + 4)) | |
if (tiffOffset + 8 > dataView.byteLength) | |
Base.log("Invalid Exif data: Invalid segment size."); | |
else if (0 === dataView.getUint16(offset + 8)) { | |
switch (dataView.getUint16(tiffOffset)) { | |
case 18761: | |
littleEndian = !0; | |
break; | |
case 19789: | |
littleEndian = !1; | |
break; | |
default: | |
return void Base.log("Invalid Exif data: Invalid byte alignment marker.") | |
} | |
42 === dataView.getUint16(tiffOffset + 2, littleEndian) ? (dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian), | |
data.exif = new EXIF.ExifMap, | |
dirOffset = EXIF.parseExifTags(dataView, tiffOffset, tiffOffset + dirOffset, littleEndian, data)) : Base.log("Invalid Exif data: Missing TIFF marker.") | |
} else | |
Base.log("Invalid Exif data: Missing byte alignment offset.") | |
} | |
, | |
ImageMeta.parsers[65505].push(EXIF.parseExifData), | |
EXIF | |
}), | |
define("runtime/html5/image", ["base", "runtime/html5/runtime", "runtime/html5/util"], function(Base, Html5Runtime, Util) { | |
return Html5Runtime.register("Image", { | |
modified: !1, | |
init: function() { | |
var me = this | |
, img = new Image; | |
img.onload = function() { | |
me._info = { | |
type: me.type, | |
width: this.width, | |
height: this.height | |
}, | |
me._metas || "image/jpeg" !== me.type ? me.owner.trigger("load") : Util.parseMeta(me._blob, function(error, ret) { | |
me._metas = ret, | |
me.owner.trigger("load") | |
}) | |
} | |
, | |
img.onerror = function() { | |
me.owner.trigger("error") | |
} | |
, | |
me._img = img | |
}, | |
loadFromBlob: function(blob) { | |
var img = this._img; | |
this._blob = blob, | |
this.type = blob.type, | |
img.src = Util.createObjectURL(blob.getSource()), | |
this.owner.once("load", function() { | |
Util.revokeObjectURL(img.src) | |
}) | |
}, | |
resize: function(width, height) { | |
var canvas = this._canvas || (this._canvas = document.createElement("canvas")); | |
this._resize(this._img, canvas, width, height), | |
this._blob = null, | |
this.modified = !0, | |
this.owner.trigger("complete", "resize") | |
}, | |
crop: function(x, y, w, h, s) { | |
var cvs = this._canvas || (this._canvas = document.createElement("canvas")) | |
, opts = this.options | |
, img = this._img | |
, iw = img.naturalWidth | |
, ih = img.naturalHeight | |
, orientation = this.getOrientation(); | |
s = s || 1, | |
cvs.width = w, | |
cvs.height = h, | |
opts.preserveHeaders || this._rotate2Orientaion(cvs, orientation), | |
this._renderImageToCanvas(cvs, img, -x, -y, iw * s, ih * s), | |
this._blob = null, | |
this.modified = !0, | |
this.owner.trigger("complete", "crop") | |
}, | |
getAsBlob: function(type) { | |
var canvas, blob = this._blob, opts = this.options; | |
if (type = type || this.type, | |
this.modified || this.type !== type) { | |
if (canvas = this._canvas, | |
"image/jpeg" === type) { | |
if (blob = Util.canvasToDataUrl(canvas, type, opts.quality), | |
opts.preserveHeaders && this._metas && this._metas.imageHead) | |
return blob = Util.dataURL2ArrayBuffer(blob), | |
blob = Util.updateImageHead(blob, this._metas.imageHead), | |
blob = Util.arrayBufferToBlob(blob, type) | |
} else | |
blob = Util.canvasToDataUrl(canvas, type); | |
blob = Util.dataURL2Blob(blob) | |
} | |
return blob | |
}, | |
getAsDataUrl: function(type) { | |
var opts = this.options; | |
return "image/jpeg" === (type = type || this.type) ? Util.canvasToDataUrl(this._canvas, type, opts.quality) : this._canvas.toDataURL(type) | |
}, | |
getOrientation: function() { | |
return this._metas && this._metas.exif && this._metas.exif.get("Orientation") || 1 | |
}, | |
info: function(val) { | |
return val ? (this._info = val, | |
this) : this._info | |
}, | |
meta: function(val) { | |
return val ? (this._metas = val, | |
this) : this._metas | |
}, | |
destroy: function() { | |
var canvas = this._canvas; | |
this._img.onload = null, | |
canvas && (canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height), | |
canvas.width = canvas.height = 0, | |
this._canvas = null), | |
this._img.src = "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D", | |
this._img = this._blob = null | |
}, | |
_resize: function(img, cvs, width, height) { | |
var scale, w, h, x, y, opts = this.options, naturalWidth = img.width, naturalHeight = img.height, orientation = this.getOrientation(); | |
~[5, 6, 7, 8].indexOf(orientation) && (width ^= height, | |
width ^= height ^= width), | |
scale = Math[opts.crop ? "max" : "min"](width / naturalWidth, height / naturalHeight), | |
opts.allowMagnify || (scale = Math.min(1, scale)), | |
w = naturalWidth * scale, | |
h = naturalHeight * scale, | |
opts.crop ? (cvs.width = width, | |
cvs.height = height) : (cvs.width = w, | |
cvs.height = h), | |
x = (cvs.width - w) / 2, | |
y = (cvs.height - h) / 2, | |
opts.preserveHeaders || this._rotate2Orientaion(cvs, orientation), | |
this._renderImageToCanvas(cvs, img, x, y, w, h) | |
}, | |
_rotate2Orientaion: function(canvas, orientation) { | |
var width = canvas.width | |
, height = canvas.height | |
, ctx = canvas.getContext("2d"); | |
switch (orientation) { | |
case 5: | |
case 6: | |
case 7: | |
case 8: | |
canvas.width = height, | |
canvas.height = width | |
} | |
switch (orientation) { | |
case 2: | |
ctx.translate(width, 0), | |
ctx.scale(-1, 1); | |
break; | |
case 3: | |
ctx.translate(width, height), | |
ctx.rotate(Math.PI); | |
break; | |
case 4: | |
ctx.translate(0, height), | |
ctx.scale(1, -1); | |
break; | |
case 5: | |
ctx.rotate(.5 * Math.PI), | |
ctx.scale(1, -1); | |
break; | |
case 6: | |
ctx.rotate(.5 * Math.PI), | |
ctx.translate(0, -height); | |
break; | |
case 7: | |
ctx.rotate(.5 * Math.PI), | |
ctx.translate(width, -height), | |
ctx.scale(-1, 1); | |
break; | |
case 8: | |
ctx.rotate(-.5 * Math.PI), | |
ctx.translate(-width, 0) | |
} | |
}, | |
_renderImageToCanvas: function() { | |
if (!Base.os.ios) | |
return function(canvas) { | |
var args = Base.slice(arguments, 1) | |
, ctx = canvas.getContext("2d"); | |
ctx.drawImage.apply(ctx, args) | |
} | |
; | |
function detectVerticalSquash(img, iw, ih) { | |
var data, ratio, canvas = document.createElement("canvas"), ctx = canvas.getContext("2d"), sy = 0, ey = ih, py = ih; | |
for (canvas.width = 1, | |
canvas.height = ih, | |
ctx.drawImage(img, 0, 0), | |
data = ctx.getImageData(0, 0, 1, ih).data; sy < py; ) | |
0 === data[4 * (py - 1) + 3] ? ey = py : sy = py, | |
py = ey + sy >> 1; | |
return 0 == (ratio = py / ih) ? 1 : ratio | |
} | |
return 7 <= Base.os.ios ? function(canvas, img, x, y, w, h) { | |
var iw = img.naturalWidth | |
, ih = img.naturalHeight | |
, vertSquashRatio = detectVerticalSquash(img, 0, ih); | |
return canvas.getContext("2d").drawImage(img, 0, 0, iw * vertSquashRatio, ih * vertSquashRatio, x, y, w, h) | |
} | |
: function(canvas, img, x, y, width, height) { | |
var tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx, iw = img.naturalWidth, ih = img.naturalHeight, ctx = canvas.getContext("2d"), subsampled = function(img) { | |
var canvas, ctx, iw = img.naturalWidth; | |
return 1048576 < iw * img.naturalHeight && ((canvas = document.createElement("canvas")).width = canvas.height = 1, | |
(ctx = canvas.getContext("2d")).drawImage(img, 1 - iw, 0), | |
0 === ctx.getImageData(0, 0, 1, 1).data[3]) | |
}(img), doSquash = "image/jpeg" === this.type, d = 1024, sy = 0, dy = 0; | |
for (subsampled && (iw /= 2, | |
ih /= 2), | |
ctx.save(), | |
(tmpCanvas = document.createElement("canvas")).width = tmpCanvas.height = d, | |
tmpCtx = tmpCanvas.getContext("2d"), | |
vertSquashRatio = doSquash ? detectVerticalSquash(img, 0, ih) : 1, | |
dw = Math.ceil(d * width / iw), | |
dh = Math.ceil(d * height / ih / vertSquashRatio); sy < ih; ) { | |
for (dx = sx = 0; sx < iw; ) | |
tmpCtx.clearRect(0, 0, d, d), | |
tmpCtx.drawImage(img, -sx, -sy), | |
ctx.drawImage(tmpCanvas, 0, 0, d, d, x + dx, y + dy, dw, dh), | |
sx += d, | |
dx += dw; | |
sy += d, | |
dy += dh | |
} | |
ctx.restore(), | |
tmpCanvas = tmpCtx = null | |
} | |
}() | |
}) | |
}), | |
define("runtime/html5/transport", ["base", "runtime/html5/runtime"], function(Base, Html5Runtime) { | |
var noop = Base.noop | |
, $ = Base.$; | |
return Html5Runtime.register("Transport", { | |
init: function() { | |
this._status = 0, | |
this._response = null | |
}, | |
send: function() { | |
var formData, binary, fr, owner = this.owner, opts = this.options, xhr = this._initAjax(), blob = owner._blob, server = opts.server; | |
opts.sendAsBinary ? (server += !1 !== opts.attachInfoToQuery ? (/\?/.test(server) ? "&" : "?") + $.param(owner._formData) : "", | |
binary = blob.getSource()) : (formData = new FormData, | |
$.each(owner._formData, function(k, v) { | |
formData.append(k, v) | |
}), | |
formData.append(opts.fileVal, blob.getSource(), opts.filename || owner._formData.name || "")), | |
opts.withCredentials && "withCredentials"in xhr ? (xhr.open(opts.method, server, !0), | |
xhr.withCredentials = !0) : xhr.open(opts.method, server), | |
this._setRequestHeader(xhr, opts.headers), | |
binary ? (xhr.overrideMimeType && xhr.overrideMimeType("application/octet-stream"), | |
Base.os.android ? ((fr = new FileReader).onload = function() { | |
xhr.send(this.result), | |
fr = fr.onload = null | |
} | |
, | |
fr.readAsArrayBuffer(binary)) : xhr.send(binary)) : xhr.send(formData) | |
}, | |
getResponse: function() { | |
return this._response | |
}, | |
getResponseAsJson: function() { | |
return this._parseJson(this._response) | |
}, | |
getResponseHeaders: function() { | |
return this._headers | |
}, | |
getStatus: function() { | |
return this._status | |
}, | |
abort: function() { | |
var xhr = this._xhr; | |
xhr && (xhr.upload.onprogress = noop, | |
xhr.onreadystatechange = noop, | |
xhr.abort(), | |
this._xhr = xhr = null) | |
}, | |
destroy: function() { | |
this.abort() | |
}, | |
_parseHeader: function(raw) { | |
var ret = {}; | |
return raw && raw.replace(/^([^\:]+):(.*)$/gm, function(_, key, value) { | |
ret[key.trim()] = value.trim() | |
}), | |
ret | |
}, | |
_initAjax: function() { | |
var me = this | |
, xhr = new XMLHttpRequest; | |
return !this.options.withCredentials || "withCredentials"in xhr || "undefined" == typeof XDomainRequest || (xhr = new XDomainRequest), | |
xhr.upload.onprogress = function(e) { | |
var percentage = 0; | |
return e.lengthComputable && (percentage = e.loaded / e.total), | |
me.trigger("progress", percentage) | |
} | |
, | |
xhr.onreadystatechange = function() { | |
if (4 === xhr.readyState) | |
return xhr.upload.onprogress = noop, | |
xhr.onreadystatechange = noop, | |
me._xhr = null, | |
me._status = xhr.status, | |
200 <= xhr.status && xhr.status < 300 ? (me._response = xhr.responseText, | |
me._headers = me._parseHeader(xhr.getAllResponseHeaders()), | |
me.trigger("load")) : 500 <= xhr.status && xhr.status < 600 ? (me._response = xhr.responseText, | |
me._headers = me._parseHeader(xhr.getAllResponseHeaders()), | |
me.trigger("error", "server-" + xhr.status)) : me.trigger("error", me._status ? "http-" + xhr.status : "abort") | |
} | |
, | |
me._xhr = xhr | |
}, | |
_setRequestHeader: function(xhr, headers) { | |
$.each(headers, function(key, val) { | |
xhr.setRequestHeader(key, val) | |
}) | |
}, | |
_parseJson: function(str) { | |
var json; | |
try { | |
json = JSON.parse(str) | |
} catch (ex) { | |
json = {} | |
} | |
return json | |
} | |
}) | |
}), | |
define("preset/html5only", ["base", "widgets/filednd", "widgets/filepaste", "widgets/filepicker", "widgets/image", "widgets/queue", "widgets/runtime", "widgets/upload", "widgets/validator", "runtime/html5/blob", "runtime/html5/dnd", "runtime/html5/filepaste", "runtime/html5/filepicker", "runtime/html5/imagemeta/exif", "runtime/html5/image", "runtime/html5/transport"], function(Base) { | |
return Base | |
}), | |
define("webuploader", ["preset/html5only"], function(preset) { | |
return preset | |
}), | |
require("webuploader"))); | |
var window, define, require | |
}; | |
"object" == typeof module && "object" == typeof module.exports ? module.exports = makeExport() : "function" == typeof define && define.amd ? define(["jquery"], makeExport) : (origin = root.WebUploader, | |
root.WebUploader = makeExport(), | |
root.WebUploader.noConflict = function() { | |
root.WebUploader = origin | |
} | |
) | |
}(window); | |
var ybuploader = WebUploader; | |
ybuploader.get_upcdns = function(callback, limitNum) { | |
limitNum = limitNum || 1; | |
var upcdns = [] | |
, complete = !1 | |
, timer = setTimeout(function() { | |
upcdns.sort(function(a, b) { | |
return a.cost - b.cost | |
}), | |
callback(upcdns.concat()), | |
complete = !0 | |
}, 800); | |
$.each([{ | |
os: "kodo", | |
query: "os=kodo&bucket=bvcupcdnkodobm", | |
url: "//up-na0.qbox.me/crossdomain.xml" | |
}, { | |
os: "upos", | |
query: "os=upos&upcdn=ws", | |
url: "//upos-hz-upcdnws.acgvideo.com/OK" | |
}, { | |
os: "upos", | |
query: "os=upos&upcdn=tx", | |
url: "//upos-hz-upcdntx.acgvideo.com/OK" | |
}, { | |
os: "bos", | |
query: "os=bos&bucket=bvcupcdnbosxg", | |
url: "//hk-2.bcebos.com/m/opmon" | |
}], function(_, line) { | |
!function(url, timeout, callback) { | |
var img = document.createElement("img"); | |
img.src = url + "?_=" + Date.now(); | |
var called = !1 | |
, start = Date.now(); | |
function onload() { | |
called || (callback(null, Date.now() - start), | |
called = !0) | |
} | |
img.onload = onload, | |
img.onerror = onload, | |
setTimeout(function() { | |
called || (img.src = "") | |
}, timeout) | |
}(line.url, 800, function(_, cost) { | |
line.cost = cost, | |
upcdns.push(line), | |
upcdns.length !== limitNum || complete || (callback(upcdns), | |
clearInterval(timer), | |
complete = !0) | |
}) | |
}) | |
} | |
, | |
ybuploader.Ybuploader = function(os, options, profile, preupload, upcdn_query) { | |
if (upcdn_query = upcdn_query || "", | |
WebUploader.Uploader.support() || alert("暂不支持您的浏览器,推荐使用Chrome浏览器!如有疑问请加QQ:385749807"), | |
window.weblog = function(name, data) { | |
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection || {}; | |
data.rtt = connection.rtt, | |
data.effectiveType = connection.effectiveType, | |
data.downlink = connection.downlink, | |
data.weblog = name, | |
data.sysos = WebUploader.os, | |
data.browser = WebUploader.browser, | |
data.js_now = Date.now(), | |
data.js_uploadstart = data.js_uploadstart, | |
"string" != typeof data.statusText && (data.statusText = "NOT_STRING"), | |
"string" != typeof data.reason && (data.reason = "NOT_STRING"), | |
WebUploader.log(data), | |
$.ajax({ | |
url: "//member.bilibili.com/preupload?r=weblog", | |
type: "post", | |
data: data | |
}) | |
} | |
, | |
"undefined" != typeof Raven && 1 != options.disable_sentry && (Raven.config("//[email protected]/3").install(), | |
WebUploader.log("sentry_install")), | |
-1 == ["cos", "kodo", "bos", "upos", "oss"].indexOf(os)) { | |
os = "upos"; | |
var ret = JSON.parse($.ajax({ | |
timeout: 200, | |
url: "http://member.bilibili.com/preupload?r=get_os", | |
type: "GET", | |
async: !1 | |
}).responseText); | |
"bos" != ret.os && "cos" != ret.os && "kodo" != ret.os && "upos" != ret.os && "oss" != ret.os || (os = ret.os) | |
} | |
if ("kodo" === (window.os = os)) | |
profile = "ugcupos/fetch", | |
WebUploader.Uploader.register({ | |
name: "_", | |
"before-send-file": function(file) { | |
var deferred = WebUploader.Deferred(); | |
return $.ajax({ | |
url: preUploadUrl, | |
data: { | |
name: file.name, | |
size: file.size, | |
r: os, | |
ssl: 0, | |
profile: profile | |
}, | |
dataType: "json", | |
success: function(ret) { | |
file.js_uploadstart = Date.now(), | |
file.bili_filename = ret.bili_filename, | |
file.key = ret.key, | |
file.cdn = ret.cdn, | |
file.endpoint = ret.endpoint, | |
file.token = ret.uptoken, | |
file.biz_id = ret.biz_id, | |
file.fetch_url = ret.fetch_url, | |
file.fetch_headers = ret.fetch_headers, | |
_this.trigger("BeforeUpload", WUploader, file), | |
deferred.resolve(file) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "PREUPLOAD_FAIL", | |
deferred.reject(file) | |
}), | |
deferred.promise() | |
}, | |
"before-send": function(block) { | |
block.options = { | |
method: "POST", | |
server: block.file.endpoint + "/mkblk/" + (block.end - block.start), | |
sendAsBinary: !0, | |
headers: { | |
Authorization: "UpToken " + block.file.token, | |
"Content-Type": "application/octet-stream" | |
} | |
} | |
}, | |
"after-send-file": function(file) { | |
var parts = []; | |
$.each(file.blocks, function(_, block) { | |
parts[block.chunk] = block.response.ctx | |
}); | |
var deferred = WebUploader.Deferred(); | |
return $.ajax({ | |
type: "POST", | |
url: file.endpoint + "/mkfile/" + file.size + "/key/" + btoa(unescape(encodeURIComponent(file.key))).replace(/\//g, "_").replace(/\+/g, "-"), | |
data: parts.join(","), | |
headers: { | |
Authorization: "UpToken " + file.token | |
} | |
}).success(function() { | |
$.ajax({ | |
url: file.fetch_url, | |
headers: file.fetch_headers, | |
type: "POST", | |
contentType: "application/json; charset=utf-8", | |
dataType: "json", | |
success: function(ret) { | |
deferred.resolve(file) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "FETCH_FAIL", | |
deferred.reject(file) | |
}) | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "COMPLETE_FAIL", | |
deferred.reject(file) | |
}), | |
deferred.promise() | |
} | |
}); | |
else if ("upos" === os) | |
profile = profile || "ugcupos/yb", | |
WebUploader.Uploader.register({ | |
name: "_", | |
"before-send-file": function(file) { | |
var deferred = WebUploader.Deferred(); | |
return $.ajax({ | |
url: preUploadUrl, | |
xhrFields: { | |
withCredentials: !0 | |
}, | |
data: { | |
name: file.name, | |
size: file.size, | |
r: os, | |
profile: profile, | |
ssl: 0 | |
}, | |
dataType: "json", | |
success: function(ret) { | |
file.auth = ret.auth, | |
file.js_uploadstart = Date.now(), | |
file.bili_filename = ret.upos_uri.split(/(\\|\/)/g).pop().split(".")[0], | |
file.upos_uri = ret.upos_uri, | |
file.biz_id = ret.biz_id, | |
file.endpoint = ret.endpoint, | |
$.ajax({ | |
type: "POST", | |
url: file.upos_uri.replace(/^upos:\/\//, file.endpoint + "/") + "?uploads&output=json", | |
headers: { | |
"X-Upos-Auth": file.auth | |
}, | |
dataType: "json", | |
success: function(ret) { | |
file.uploadId = ret.upload_id, | |
_this.trigger("BeforeUpload", WUploader, file), | |
deferred.resolve(file) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "UPLOADS_FAIL", | |
deferred.reject(file) | |
}) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "PREUPLOAD_FAIL", | |
deferred.reject(file) | |
}), | |
deferred.promise() | |
}, | |
"before-send": function(block) { | |
console.log(block), | |
block.options = { | |
method: "PUT", | |
server: block.file.upos_uri.replace(/^upos:\/\//, block.file.endpoint + "/") + "?" + $.param({ | |
partNumber: block.chunk + 1, | |
uploadId: block.file.uploadId, | |
chunk: block.chunk, | |
chunks: block.chunks, | |
size: block.blob.size, | |
start: block.start, | |
end: block.end, | |
total: block.total | |
}), | |
headers: { | |
"X-Upos-Auth": block.file.auth | |
} | |
} | |
}, | |
"after-send-file": function(file) { | |
var deferred = WebUploader.Deferred() | |
, parts = []; | |
return $.each(file.blocks, function(k, v) { | |
parts.push({ | |
partNumber: v.chunk + 1, | |
eTag: "etag" | |
}) | |
}), | |
$.ajax({ | |
url: file.upos_uri.replace(/^upos:\/\//, file.endpoint + "/") + "?" + $.param({ | |
output: "json", | |
name: file.name, | |
profile: profile, | |
uploadId: file.uploadId, | |
biz_id: file.biz_id | |
}), | |
type: "POST", | |
headers: { | |
"X-Upos-Auth": file.auth | |
}, | |
data: JSON.stringify({ | |
parts: parts | |
}), | |
contentType: "application/json; charset=utf-8", | |
dataType: "json", | |
success: function(ret) { | |
deferred.resolve(file) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "COMPLETE_FAIL", | |
deferred.reject(file) | |
}), | |
deferred.promise() | |
} | |
}); | |
else if ("bos" === os) | |
profile = profile || "ugcupos/fetch", | |
WebUploader.Uploader.register({ | |
"before-send-file": function(file) { | |
var deferred = WebUploader.Deferred(); | |
return $.ajax({ | |
url: preUploadUrl, | |
type: "GET", | |
data: { | |
name: file.name, | |
size: file.size, | |
r: os, | |
profile: profile, | |
ssl: 0 | |
}, | |
dataType: "json", | |
success: function(ret) { | |
file.cdn = ret.cdn, | |
file.AK = ret.AccessKeyId, | |
file.SK = ret.SecretAccessKey, | |
file.SESSION_TOKEN = ret.SessionToken, | |
file.key = ret.key, | |
file.bucket = ret.bucket, | |
file.endpoint = ret.endpoint, | |
file.biz_id = ret.biz_id, | |
file.bili_filename = ret.bili_filename, | |
file.fetch_url = ret.fetch_url, | |
file.fetch_headers = ret.fetch_headers; | |
var resource = "/" + file.bucket + "/" + file.key | |
, xbceDate = (new Date).toISOString().replace(/\.\d+Z$/, "Z") | |
, timestamp = (new Date).getTime() / 1e3 | |
, headers_ = { | |
"x-bce-date": xbceDate, | |
"x-bce-security-token": file.SESSION_TOKEN, | |
host: file.endpoint | |
}; | |
$.ajax({ | |
url: "//" + file.endpoint + resource + "?uploads", | |
type: "POST", | |
headers: { | |
authorization: new baidubce.sdk.Auth(file.AK,file.SK).generateAuthorization("POST", resource, { | |
uploads: "" | |
}, headers_, timestamp, 0, Object.keys(headers_)), | |
"x-bce-date": xbceDate, | |
"x-bce-security-token": file.SESSION_TOKEN | |
}, | |
success: function(ret) { | |
file.uploadId = ret.uploadId, | |
_this.trigger("BeforeUpload", WUploader, file), | |
deferred.resolve(file) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "UPLOADS_FAIL", | |
deferred.reject(file) | |
}) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "PREUPLOAD_FAIL", | |
deferred.reject(file) | |
}), | |
deferred.promise() | |
}, | |
"before-send": function(block) { | |
var file = block.file | |
, resource = "/" + file.bucket + "/" + file.key | |
, params = { | |
partNumber: block.chunk + 1, | |
uploadId: file.uploadId | |
} | |
, xbceDate = (new Date).toISOString().replace(/\.\d+Z$/, "Z") | |
, timestamp = (new Date).getTime() / 1e3 | |
, headers_ = { | |
"x-bce-date": xbceDate, | |
"x-bce-security-token": file.SESSION_TOKEN, | |
host: file.endpoint | |
}; | |
block.options = { | |
method: "PUT", | |
server: "//" + file.endpoint + resource + "?partNumber=" + params.partNumber + "&uploadId=" + params.uploadId, | |
headers: { | |
authorization: new baidubce.sdk.Auth(file.AK,file.SK).generateAuthorization("PUT", resource, params, headers_, timestamp, 0, Object.keys(headers_)), | |
"x-bce-date": xbceDate, | |
"x-bce-security-token": file.SESSION_TOKEN | |
} | |
} | |
}, | |
"after-send-file": function(file) { | |
var blocks = file.blocks | |
, parts = []; | |
$.each(blocks, function(k, v) { | |
var etag = v.response._headers.ETag || v.response._headers.etag; | |
parts[v.chunk] = { | |
partNumber: v.chunk + 1, | |
eTag: etag.replace(/^"|"$/g, "") | |
} | |
}); | |
var resource = "/" + file.bucket + "/" + file.key | |
, params = { | |
uploadId: file.uploadId | |
} | |
, xbceDate = (new Date).toISOString().replace(/\.\d+Z$/, "Z") | |
, timestamp = (new Date).getTime() / 1e3 | |
, headers_ = { | |
"x-bce-date": xbceDate, | |
"x-bce-security-token": file.SESSION_TOKEN, | |
host: file.endpoint | |
} | |
, deferred = WebUploader.Deferred(); | |
return $.ajax({ | |
url: "//" + file.endpoint + resource + "?uploadId=" + params.uploadId, | |
type: "POST", | |
headers: { | |
authorization: new baidubce.sdk.Auth(file.AK,file.SK).generateAuthorization("POST", resource, params, headers_, timestamp, 0, Object.keys(headers_)), | |
"x-bce-date": xbceDate, | |
"x-bce-security-token": file.SESSION_TOKEN | |
}, | |
dataType: "json", | |
data: JSON.stringify({ | |
parts: parts | |
}), | |
contentType: "application/json; charset=utf-8", | |
success: function(ret) { | |
$.ajax({ | |
url: file.fetch_url, | |
headers: file.fetch_headers, | |
type: "POST", | |
contentType: "application/json; charset=utf-8", | |
dataType: "json", | |
success: function(ret) { | |
deferred.resolve(file) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "FETCH_FAIL", | |
deferred.reject(file) | |
}) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "COMPLETE_FAIL", | |
deferred.reject(file) | |
}), | |
deferred.promise() | |
} | |
}); | |
else if ("cos" === os) | |
profile = profile || "ugcupos/fetch", | |
WebUploader.Uploader.register({ | |
"before-send-file": function(file) { | |
var deferred = WebUploader.Deferred(); | |
return $.ajax({ | |
url: preUploadUrl, | |
type: "GET", | |
data: { | |
name: file.name, | |
size: file.size, | |
r: os, | |
ssl: 0, | |
profile: profile | |
}, | |
dataType: "json", | |
success: function(ret) { | |
file.cdn = ret.cdn, | |
file.post_auth = ret.post_auth, | |
file.put_auth = ret.put_auth, | |
file.url = ret.url, | |
file.fetch_url = ret.fetch_url, | |
file.fetch_headers = ret.fetch_headers, | |
file.biz_id = ret.biz_id, | |
file.bili_filename = ret.bili_filename, | |
$.ajax({ | |
type: "POST", | |
url: file.url + "?uploads", | |
headers: { | |
Authorization: file.post_auth | |
}, | |
success: function(ret) { | |
file.uploadId = $(ret).find("UploadId")[0].textContent, | |
_this.trigger("BeforeUpload", WUploader, file), | |
deferred.resolve(file) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "UPLOADS_FAIL", | |
deferred.reject(file) | |
}) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "PREUPLOAD_FAIL", | |
deferred.reject(file) | |
}), | |
deferred.promise() | |
}, | |
"before-send": function(block) { | |
var file = block.file; | |
block.options = { | |
server: file.url + "?" + $.param({ | |
partNumber: block.chunk + 1, | |
uploadId: file.uploadId, | |
name: file.name | |
}), | |
headers: { | |
Authorization: file.put_auth | |
} | |
} | |
}, | |
"after-send-file": function(file) { | |
var parts = []; | |
$.each(file.blocks, function(_, block) { | |
parts[block.chunk] = block | |
}); | |
var xml = "<CompleteMultipartUpload>"; | |
$.each(parts, function(chunk, block) { | |
var etag = block.response._headers.etag || block.response._headers.ETag; | |
xml += "<Part><PartNumber>" + (chunk + 1) + "</PartNumber><ETag>" + etag.replace(/^"|"$/g, "") + "</ETag></Part>" | |
}), | |
xml += "</CompleteMultipartUpload>"; | |
var deferred = WebUploader.Deferred(); | |
return $.ajax({ | |
contentType: "application/xml", | |
data: xml, | |
type: "POST", | |
url: file.url + "?uploadId=" + file.uploadId, | |
headers: { | |
Authorization: file.post_auth | |
}, | |
success: function(r) { | |
$.ajax({ | |
contentType: "application/json; charset=utf-8", | |
dataType: "json", | |
headers: file.fetch_headers, | |
type: "POST", | |
url: file.fetch_url, | |
success: function(ret) { | |
deferred.resolve(file) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "FETCH_FAIL", | |
deferred.reject(file) | |
}) | |
}, | |
error: function(err) { | |
file.statusText = "COMPLETE_FAIL", | |
deferred.reject(file) | |
} | |
}), | |
deferred.promise() | |
} | |
}); | |
else if ("oss" === os) { | |
function buildAuth(date, method, params, contentMD5, contentType, bucket, key, aki, aks, token) { | |
var canonicalizedResource; | |
return canonicalizedResource = bucket || key ? "/" + bucket + "/" + key : "/", | |
params && (canonicalizedResource += params), | |
"OSS " + aki + ":" + b64_hmac_sha1(aks, method + "\n" + contentMD5 + "\n" + contentType + "\n" + date + "\n" + ("x-oss-date:" + date + "\nx-oss-security-token:" + token) + "\n" + canonicalizedResource) | |
} | |
profile = profile || "ugcupos/fetch", | |
WebUploader.Uploader.register({ | |
"before-send-file": function(file) { | |
var deferred = WebUploader.Deferred(); | |
return $.ajax({ | |
url: preUploadUrl, | |
data: { | |
name: file.name, | |
size: file.size, | |
r: os, | |
ssl: 0, | |
profile: profile | |
}, | |
dataType: "json", | |
success: function(ret) { | |
file.js_uploadstart = Date.now(), | |
file.token = ret.Credentials.SecurityToken, | |
file.aki = ret.Credentials.AccessKeyId, | |
file.aks = ret.Credentials.AccessKeySecret, | |
file.bili_filename = ret.bili_filename, | |
file.bucket = ret.bucket, | |
file.key = ret.key, | |
file.cdn = ret.cdn, | |
file.endpoint = ret.endpoint, | |
file.biz_id = ret.biz_id, | |
file.url = ret.url, | |
file.fetch_url = ret.fetch_url, | |
file.fetch_headers = ret.fetch_headers; | |
var date = (new Date).toUTCString(); | |
$.ajax({ | |
type: "POST", | |
url: file.url + "?uploads", | |
headers: { | |
"x-oss-date": date, | |
"x-oss-security-token": file.token, | |
Authorization: buildAuth(date, "POST", "?uploads", "", "", file.bucket, file.key, file.aki, file.aks, file.token) | |
}, | |
success: function(ret) { | |
file.uploadId = $(ret).find("UploadId")[0].textContent, | |
_this.trigger("BeforeUpload", WUploader, file), | |
deferred.resolve(file) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "UPLOADS_FAIL", | |
deferred.reject(file) | |
}) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "PREUPLOAD_FAIL", | |
deferred.reject(file) | |
}), | |
deferred.promise() | |
}, | |
"before-send": function(block) { | |
var file = block.file | |
, date = (new Date).toUTCString() | |
, params = "?" + $.param({ | |
partNumber: block.chunk + 1, | |
uploadId: file.uploadId | |
}); | |
block.options = { | |
server: file.url + params, | |
headers: { | |
"x-oss-date": date, | |
"x-oss-security-token": file.token, | |
Authorization: buildAuth(date, "PUT", params, "", "", file.bucket, file.key, file.aki, file.aks, file.token) | |
} | |
} | |
}, | |
"after-send-file": function(file) { | |
var deferred = WebUploader.Deferred() | |
, etags = new Array; | |
$.each(file.blocks, function(_, block) { | |
var etag = block.response._headers.etag || block.response._headers.ETag; | |
etags[block.chunk] = etag.replace(/^"|"$/g, "") | |
}); | |
for (var xml = "<CompleteMultipartUpload>", i = 0; i < etags.length; i++) | |
xml += "<Part><PartNumber>" + (i + 1) + "</PartNumber><ETag>" + etags[i] + "</ETag></Part>"; | |
xml += "</CompleteMultipartUpload>"; | |
var date = (new Date).toUTCString() | |
, params = "?uploadId=" + file.uploadId; | |
return $.ajax({ | |
contentType: "application/xml", | |
data: xml, | |
type: "POST", | |
url: file.url + params, | |
headers: { | |
"x-oss-date": date, | |
"x-oss-security-token": file.token, | |
Authorization: buildAuth(date, "POST", params, "", "application/xml", file.bucket, file.key, file.aki, file.aks, file.token) | |
} | |
}).success(function() { | |
$.ajax({ | |
url: file.fetch_url, | |
headers: file.fetch_headers, | |
type: "POST", | |
contentType: "application/json; charset=utf-8", | |
dataType: "json", | |
success: function(ret) { | |
deferred.resolve(file) | |
} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "FETCH_FAIL", | |
deferred.reject(file) | |
}) | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "COMPLETE_FAIL", | |
deferred.reject(file) | |
}), | |
deferred.promise() | |
} | |
}) | |
} | |
var _this = this | |
, preUploadUrl = preupload || "/preupload?" + upcdn_query; | |
WebUploader.log(options); | |
var chunkSize = 4194304 | |
, threads = 2; | |
Date.now() - (window.localStorage.getItem("yb_lock") || 0) < 3e4 && (threads = 1, | |
weblog("yb_lock", {})), | |
window.location.search.match(/upcdn=office/) && (threads = 8, | |
chunkSize = 20971520); | |
var WUploader = new WebUploader.create({ | |
attachInfoToQuery: !1, | |
auto: !0, | |
chunked: !0, | |
method: "PUT", | |
prepareNextFile: !0, | |
runtimeOrder: "html5", | |
sendAsBinary: !0, | |
dnd: options.dnd, | |
pick: options.pick, | |
fileNumLimit: options.fileNumLimit, | |
fileSizeLimit: options.fileSizeLimit, | |
fileSingleSizeLimit: options.fileSingleSizeLimit || 4294967296, | |
accept: options.accept, | |
duplicate: options.duplicate, | |
timeout: 9e5, | |
chunkRetryDelay: options.chunkrRetryDelay || 3e3, | |
chunkRetry: options.chunkRetry || 200, | |
chunkSize: chunkSize, | |
threads: threads | |
}); | |
WebUploader.log(WUploader.options), | |
WUploader.total = { | |
bytesPerSec: 0 | |
}, | |
WUploader.onBeforeFileQueued = function(file) { | |
if (-1 == ["webp", "raw", "gif", "bmp", "jpeg", "png", "jpg", "eml", "msg", "flac", "wav", "wma", "mp3", "txt", "mp4", "m4a", "m4v", "flv", "avi", "wmv", "mov", "webm", "mpeg4", "ts", "mpg", "rm", "rmvb", "mkv"].indexOf(file.ext.toLowerCase()) || 42949672960 < file.size) | |
return !1 | |
} | |
, | |
WUploader.onFileQueued = function(file) { | |
_this.trigger("FileFiltered", WUploader, file), | |
file.on("statuschange", function(status) { | |
var prev_status = file.status; | |
"error" == file.status && "progress" == status || (file.status = status), | |
-1 != ["cancelled", "invalid", "interrupt", "error"].indexOf(status) && weblog("statuschange", { | |
statusText: file.statusText, | |
bili_filename: file.bili_filename, | |
js_uploadstart: file.js_uploadstart, | |
size: file.size, | |
bytesPerSec: file.bytesPerSec, | |
percent: file.percent, | |
name: file.name, | |
type: file.type, | |
lastModifiedDate: file.lastModifiedDate, | |
id: file.id, | |
prev_status: prev_status, | |
status: status | |
}) | |
}) | |
} | |
, | |
WUploader.onUploadError = function(file, reason) { | |
weblog("upload_error", { | |
os: os, | |
cdn: file.cdn, | |
reason: reason, | |
bili_filename: file.bili_filename, | |
status: file.status, | |
statusText: file.statusText | |
}), | |
_this.trigger("Error", {}, { | |
message: reason, | |
showText: "异常退出" | |
}) | |
} | |
, | |
WUploader.onError = function(type) { | |
var showText = type; | |
"F_DUPLICATE" == type ? showText = "请勿添加重复文件" : "http-" == type ? showText = "网络错误" : "abort" == type ? showText = "异常退出,请稍后再试" : "PREUPLOAD_FAIL" == type ? showText = "获取上传地址失败" : "F_EXCEED_SIZE" == type ? showText = "体积过大" : "Q_TYPE_DENIED" == type ? showText = "类型不支持,支持列表:txt,mp4,flv,avi,wmv,mov,webm,mpeg4,ts,mpg,rm,rmvb,mkv" : "PULL_ERROR" == type && (showText = "通知失败"), | |
_this.trigger("Error", {}, { | |
message: type, | |
showText: showText | |
}), | |
weblog("on_error", { | |
message: type, | |
showText: showText | |
}) | |
} | |
, | |
WUploader.onStartUpload = function(file) { | |
WebUploader.log("startUpload") | |
} | |
, | |
WUploader.onUploadStart = function(file) { | |
WebUploader.log("uploadStart") | |
} | |
, | |
WUploader.onUploadAccept = function(file, ret) { | |
WebUploader.log("uploadAccept") | |
} | |
, | |
WUploader.onUploadSuccess = function(file, response) { | |
WebUploader.log("uploadSuccess"), | |
_this.trigger("FileUploaded", WUploader, file, {}) | |
} | |
, | |
WUploader.onUploadBeforeSend = function(object, data, headers) { | |
WebUploader.log("uploadBeforeSend") | |
} | |
, | |
WUploader.onUploadProgress = function(file, percentage) { | |
window.localStorage.setItem("yb_lock", Date.now()); | |
var time = Date.now() | |
, bytesPerSec = (percentage - (file.prev_percentage || 0)) * file.size / (time - (file.prev_time || Date.now())) * 1e3; | |
file.percent = Math.round(100 * percentage), | |
file.bytesPerSec = bytesPerSec, | |
_this.trigger("UploadProgress", { | |
total: { | |
bytesPerSec: bytesPerSec | |
} | |
}, file), | |
(2e3 < time - file.prev_time || !file.prev_time) && (file.prev_percentage = percentage, | |
file.prev_time = time) | |
} | |
, | |
this.removeFile = function(file) { | |
return WebUploader.log("removeFile"), | |
WUploader.removeFile(WUploader.getFile(file.id)) | |
} | |
, | |
WebUploader.log(WUploader.predictRuntimeType()), | |
this.addFiles = WUploader.addFiles, | |
this.getFile = function(fileid) { | |
return WUploader.getFile(fileid) | |
} | |
, | |
this.destroy = function() { | |
return WebUploader.Uploader.unRegister("_"), | |
WebUploader.log("WUploader.destroy()"), | |
WUploader.destroy() | |
} | |
, | |
this.init = function() {} | |
, | |
this.retry = function() { | |
return WUploader.retry() | |
} | |
, | |
this.start = function() { | |
return WUploader.stop(!0), | |
WUploader.upload() | |
} | |
, | |
this.upload = function() { | |
return WUploader.upload() | |
} | |
, | |
this.formatSize = WebUploader.formatSize, | |
this.stop = function() { | |
return WUploader.stop(!0) | |
} | |
, | |
Object.defineProperty(this, "files", { | |
get: function() { | |
return WUploader.getFiles() | |
} | |
}), | |
WebUploader.Mediator.installTo(this), | |
this.bind = this.on, | |
this.addUrl = function(pull_url) { | |
$.ajax({ | |
url: "//member.bilibili.com/preupload", | |
type: "get", | |
data: { | |
r: "head", | |
url: pull_url | |
}, | |
async: !1, | |
dataType: "json", | |
success: function(ret) { | |
ret, | |
WebUploader.log(ret) | |
} | |
}); | |
var file = { | |
percent: 100, | |
size: 1, | |
id: WebUploader.guid(), | |
name: pull_url.split(/(\\|\/)/g).pop() | |
}; | |
$.ajax({ | |
url: "//member.bilibili.com/preupload?name=a.flv&r=upos&profile=ugcupos/addurl", | |
async: !1, | |
dataType: "json", | |
success: function(ret) { | |
file.auth = ret.auth, | |
file.upos_uri = ret.upos_uri, | |
file.biz_id = ret.biz_id, | |
file.endpoint = ret.endpoint, | |
file.bili_filename = ret.upos_uri.split(/(\\|\/)/g).pop().split(".")[0] | |
} | |
}), | |
_this.trigger("FileFiltered", {}, file), | |
_this.trigger("BeforeUpload", {}, file), | |
$.ajax({ | |
url: file.upos_uri.replace(/^upos:\/\//, file.endpoint + "/") + "?fetch&yamdi=1&output=json&profile=ugcupos/addurl&biz_id=" + file.biz_id, | |
type: "post", | |
async: !1, | |
headers: { | |
"X-Upos-Fetch-Source": pull_url, | |
"X-Upos-Auth": file.auth | |
}, | |
contentType: "application/json; charset=utf-8", | |
dataType: "json", | |
success: function(ret) {} | |
}).retry({ | |
times: 5 | |
}).fail(function() { | |
file.statusText = "COMPLETE_FAIL" | |
}), | |
_this.trigger("UploadProgress", { | |
total: { | |
bytesPerSec: 0 | |
} | |
}, file), | |
_this.trigger("FileUploaded", {}, file) | |
} | |
} | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment