code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
evaluate(expression, scope) { return new Promise((resolve, reject) => { if (!expression) return reject(new Error('Expression - eval() - expression is required')); let astTokens = esprima.tokenize(expression); let startTime = process.hrtime(); _eval(expression, scope) .then(result => { let time = _getTime(startTime); let expressionResult = { result: result, time: time, mongoMethodName: _getMongoMethodName(astTokens), mongoCollectionName: _getMongoCollectionName(expression, astTokens) }; if (_.isArray(expressionResult.result)) { expressionResult.keyValueResults = keyValueUtils.convert(expressionResult.result); } return resolve(expressionResult); }) .catch(reject); }); }
evaluate a JS expression @param {String} expression @param {Object} [scope] - a customized scope that the expression will be evaluated in @returns Promise
evaluate
javascript
officert/mongotron
src/lib/modules/expression/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/expression/index.js
MIT
getMongoCollectionName(expression) { if (!expression) return null; let errors = this.validate(expression); if (errors && errors.length) return null; let astTokens = esprima.tokenize(expression); return _getMongoCollectionName(expression, astTokens); }
evaluate a JS expression @param {String} expression @param {Object} [scope] - a customized scope that the expression will be evaluated in @returns Promise
getMongoCollectionName
javascript
officert/mongotron
src/lib/modules/expression/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/expression/index.js
MIT
getMongoMethodName(expression) { if (!expression) return null; let errors = this.validate(expression); if (errors && errors.length) return null; let astTokens = esprima.tokenize(expression); return _getMongoMethodName(astTokens); }
evaluate a JS expression @param {String} expression @param {Object} [scope] - a customized scope that the expression will be evaluated in @returns Promise
getMongoMethodName
javascript
officert/mongotron
src/lib/modules/expression/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/expression/index.js
MIT
validate(expression) { let syntax; try { syntax = esprima.parse(expression, { tolerant: true, loc: true }); } catch (e) { return null; } return syntax.errors; }
evaluate a JS expression @param {String} expression @param {Object} [scope] - a customized scope that the expression will be evaluated in @returns Promise
validate
javascript
officert/mongotron
src/lib/modules/expression/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/expression/index.js
MIT
function _getMongoCollectionName(expression, astTokens) { if (!astTokens || astTokens.length < 3) return null; if (astTokens[0].value !== 'db') return null; let bracketNotation = mongoUtils.isBracketNotation(expression); let value = astTokens[2].value; if (bracketNotation) value = _getStringValue(value); return value; }
evaluate a JS expression @param {String} expression @param {Object} [scope] - a customized scope that the expression will be evaluated in @returns Promise
_getMongoCollectionName
javascript
officert/mongotron
src/lib/modules/expression/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/expression/index.js
MIT
function _getMongoMethodName(astTokens) { if (!astTokens || astTokens.length < 4) return null; if (astTokens[0].value !== 'db') return null; let bracketNotation = astTokens[3].value === '['; let value = astTokens[4].value; if (bracketNotation) value = _getStringValue(value); return value; }
evaluate a JS expression @param {String} expression @param {Object} [scope] - a customized scope that the expression will be evaluated in @returns Promise
_getMongoMethodName
javascript
officert/mongotron
src/lib/modules/expression/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/expression/index.js
MIT
function _getTime(startTime) { let endTime = process.hrtime(startTime); return endTime[0], endTime[1] / 1000000; }
evaluate a JS expression @param {String} expression @param {Object} [scope] - a customized scope that the expression will be evaluated in @returns Promise
_getTime
javascript
officert/mongotron
src/lib/modules/expression/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/expression/index.js
MIT
function _eval(expression, scope) { return new Promise((resolve, reject) => { if (!expression) return reject(new Error('evaluator - eval() - must pass an expression')); if (!_.isString(expression)) return reject(new Error('evaluator - eval() - expression must be a string')); var evalScope = { ObjectId: ObjectId, console: _getConsole() }; if (scope && _.isObject(scope)) { _.extend(evalScope, scope); } var options = { displayErrors: false }; // Evalutate the expression with the given scope var script; var result; try { script = new vm.Script(expression, options); } catch (err) { return reject(err); } //NOTE: ast could contain multiple expressions (top level nodes) try { result = script.runInNewContext(evalScope, options); } catch (err) { return reject(err); } if (typeUtils.isPromise(result)) { result.then(promiseResult => { return resolve(promiseResult); }); if (result.catch) result.catch(reject); } else if (typeUtils.isStream(result)) { // result.on('end', ) } else { return resolve(result); } }); }
@private @param {String} expression @param {Object} scope
_eval
javascript
officert/mongotron
src/lib/modules/expression/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/expression/index.js
MIT
function _getConsole() { let customConsole = { log: function() { return arguments; }, debug: function() { return arguments; }, info: function() { return arguments; }, warn: function() { return arguments; }, error: function() { return arguments; } }; return customConsole; }
@private @param {String} expression @param {Object} scope
_getConsole
javascript
officert/mongotron
src/lib/modules/expression/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/expression/index.js
MIT
function _getStringValue(str) { let matches = str.match(/(?:\\?\"|\\?\')(.*?)(?:\\?\"|\\?\')/); return matches && matches.length >= 2 ? matches[1] : null; }
@private @param {String} expression @param {Object} scope
_getStringValue
javascript
officert/mongotron
src/lib/modules/expression/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/expression/index.js
MIT
function parseKeybindingsFileData(data) { return new Promise((resolve, reject) => { if (!data || !_.isArray(data)) return reject(new Error('keybindings - list() - error parsing keybindings file data')); //TODO: should we group these by context name to avoid duplicates?? var commands = []; _.each(data, context => { if (context.commands) { for (let key in context.commands) { commands.push({ keystroke: key, command: context.commands[key], context: context.context }); } } }); return resolve(commands); }); }
@function parseKeybindingsFileData @private @param {Object} data - raw contexts from keybindings file
parseKeybindingsFileData
javascript
officert/mongotron
src/lib/modules/keybindings/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/keybindings/index.js
MIT
changeActive(themeName) { var _this = this; var newActiveTheme; if (!themeName) return Promise.reject(new Error('theme - changeActive() - themeName is required')); return _this.list() .then((themes) => { return new Promise((resolve, reject) => { newActiveTheme = _.findWhere(themes, { name: themeName }); if (!newActiveTheme) return reject(new Error(`theme - changeActive() - ${themeName} is not a valid theme`)); themes = themes.map(theme => { theme.active = false; return theme; }); newActiveTheme.active = true; return resolve(themes); }); }) .then(writeThemesFile) .then(readThemesFile) .then(() => { return new Promise((resolve) => { return resolve(newActiveTheme); }); }); }
Change active theme @param {string} themeName - Name of the theme to change to
changeActive
javascript
officert/mongotron
src/lib/modules/themes/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/themes/index.js
MIT
function readThemesFile() { return fileUtils.readJsonFile(appConfig.themesPath); }
Change active theme @param {string} themeName - Name of the theme to change to
readThemesFile
javascript
officert/mongotron
src/lib/modules/themes/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/themes/index.js
MIT
function writeThemesFile(fileData) { return fileUtils.writeJsonFile(appConfig.themesPath, fileData); }
Change active theme @param {string} themeName - Name of the theme to change to
writeThemesFile
javascript
officert/mongotron
src/lib/modules/themes/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/themes/index.js
MIT
function parseThemesFileData(data) { return new Promise((resolve, reject) => { if (!data || !_.isArray(data)) return reject(new Error('themes - list() - error parsing themes file data')); return resolve(data); }); }
@function parseThemesFileData @private @param {Object} data - raw contexts from themes file
parseThemesFileData
javascript
officert/mongotron
src/lib/modules/themes/index.js
https://github.com/officert/mongotron/blob/master/src/lib/modules/themes/index.js
MIT
get(key) { if (!key) throw new Error('localStorageService - get() - key is required'); let json; try { var val = $window.localStorage.getItem(key); if (val) json = JSON.parse(val); } catch (e) {} if (!json) json = CACHE[key]; return json; }
@desc get a value by key @param {String} key @return {String}
get
javascript
officert/mongotron
src/ui/services/localStorageService.js
https://github.com/officert/mongotron/blob/master/src/ui/services/localStorageService.js
MIT
set(key, value) { if (!key) throw new Error('localStorageService - set() - key is required'); if (!value) throw new Error('localStorageService - set() - value is required'); if (value) { try { var val = JSON.stringify(value); $window.localStorage.setItem(key, val); } catch (e) { CACHE[key] = value; } return null; } else { this.remove(key); } }
@desc set a value by key @param {String} key @param {Object} obj @return null
set
javascript
officert/mongotron
src/ui/services/localStorageService.js
https://github.com/officert/mongotron/blob/master/src/ui/services/localStorageService.js
MIT
remove(key) { if (!key) throw new Error('localStorageService - remove() - key is required'); try { $window.localStorage.removeItem(key); } catch (e) { delete CACHE[key]; } return null; }
@desc remove a value by key @param {String} key @return null
remove
javascript
officert/mongotron
src/ui/services/localStorageService.js
https://github.com/officert/mongotron/blob/master/src/ui/services/localStorageService.js
MIT
exists(key) { if (!key) throw new Error('localStorageService - exists() - key is required'); var exists = null; try { exists = this.get(key) !== null && this.get(key) !== undefined; } catch (e) { exists = CACHE[key] ? true : false; } return exists; }
@desc check if a value exists by key @param {String} key @return {Boolean}
exists
javascript
officert/mongotron
src/ui/services/localStorageService.js
https://github.com/officert/mongotron/blob/master/src/ui/services/localStorageService.js
MIT
compareMongoObjectIds(expected, result) { var expectedString = expected.toString(); var resultString = result.toString(); if (result instanceof mongodb.ObjectId !== true) return false; if (expectedString !== resultString) return false; return true; }
Tests that the resulting objectId is an instance of mongodb.ObjectId and tests that it matches the toString value of the expected ObjectId @param {ObjectId} expected The ObjectId that's expected @param {ObjectId} result The ObjectId that's returned @return {[type]} [description]
compareMongoObjectIds
javascript
officert/mongotron
tests/utils/testUtils.js
https://github.com/officert/mongotron/blob/master/tests/utils/testUtils.js
MIT
function extractVersion(uastring, expr, pos) { var match = uastring.match(expr); return match && match.length >= pos && parseInt(match[pos], 10); }
Extract browser version out of the provided user agent string. @param {!string} uastring userAgent string. @param {!string} expr Regular expression used as match criteria. @param {!number} pos position in the version string to be returned. @return {!number} browser version.
extractVersion
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/desktopCapture-p2p/background/helpers/adapter.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/desktopCapture-p2p/background/helpers/adapter.js
MIT
function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) { if (!window.RTCPeerConnection) { return; } var proto = window.RTCPeerConnection.prototype; var nativeAddEventListener = proto.addEventListener; proto.addEventListener = function(nativeEventName, cb) { if (nativeEventName !== eventNameToWrap) { return nativeAddEventListener.apply(this, arguments); } var wrappedCallback = function(e) { cb(wrapper(e)); }; this._eventMap = this._eventMap || {}; this._eventMap[cb] = wrappedCallback; return nativeAddEventListener.apply(this, [nativeEventName, wrappedCallback ]); }; var nativeRemoveEventListener = proto.removeEventListener; proto.removeEventListener = function(nativeEventName, cb) { if (nativeEventName !== eventNameToWrap || !this._eventMap || !this._eventMap[cb]) { return nativeRemoveEventListener.apply(this, arguments); } var unwrappedCb = this._eventMap[cb]; delete this._eventMap[cb]; return nativeRemoveEventListener.apply(this, [nativeEventName, unwrappedCb ]); }; Object.defineProperty(proto, 'on' + eventNameToWrap, { get: function() { return this['_on' + eventNameToWrap]; }, set: function(cb) { if (this['_on' + eventNameToWrap]) { this.removeEventListener(eventNameToWrap, this['_on' + eventNameToWrap]); delete this['_on' + eventNameToWrap]; } if (cb) { this.addEventListener(eventNameToWrap, this['_on' + eventNameToWrap] = cb); } } }); }
Extract browser version out of the provided user agent string. @param {!string} uastring userAgent string. @param {!string} expr Regular expression used as match criteria. @param {!number} pos position in the version string to be returned. @return {!number} browser version.
wrapPeerConnectionEvent
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/desktopCapture-p2p/background/helpers/adapter.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/desktopCapture-p2p/background/helpers/adapter.js
MIT
function lookup(uri, opts) { if ((typeof uri === 'undefined' ? 'undefined' : _typeof(uri)) === 'object') { opts = uri; uri = undefined; } opts = opts || {}; var parsed = url(uri); var source = parsed.source; var id = parsed.id; var path = parsed.path; var sameNamespace = cache[id] && path in cache[id].nsps; var newConnection = opts.forceNew || opts['force new connection'] || false === opts.multiplex || sameNamespace; var io; if (newConnection) { debug('ignoring socket cache for %s', source); io = Manager(source, opts); } else { if (!cache[id]) { debug('new io instance for %s', source); cache[id] = Manager(source, opts); } io = cache[id]; } if (parsed.query && !opts.query) { opts.query = parsed.query; } else if (opts && 'object' === _typeof(opts.query)) { opts.query = encodeQueryString(opts.query); } return io.socket(parsed.path, opts); }
Looks up an existing `Manager` for multiplexing. If the user summons: `io('http://localhost/a');` `io('http://localhost/b');` We reuse the existing instance based on same scheme/port/host, and we initialize sockets for each namespace. @api public
lookup
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function encodeQueryString(obj) { var str = []; for (var p in obj) { if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); } } return str.join('&'); }
Helper method to parse query objects to string. @param {object} query @returns {string}
encodeQueryString
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function url(uri, loc) { var obj = uri; // default to window.location loc = loc || global.location; if (null == uri) uri = loc.protocol + '//' + loc.host; // relative path support if ('string' === typeof uri) { if ('/' === uri.charAt(0)) { if ('/' === uri.charAt(1)) { uri = loc.protocol + uri; } else { uri = loc.host + uri; } } if (!/^(https?|wss?):\/\//.test(uri)) { debug('protocol-less url %s', uri); if ('undefined' !== typeof loc) { uri = loc.protocol + '//' + uri; } else { uri = 'https://' + uri; } } // parse debug('parse %s', uri); obj = parseuri(uri); } // make sure we treat `localhost:80` and `localhost` equally if (!obj.port) { if (/^(http|ws)$/.test(obj.protocol)) { obj.port = '80'; } else if (/^(http|ws)s$/.test(obj.protocol)) { obj.port = '443'; } } obj.path = obj.path || '/'; var ipv6 = obj.host.indexOf(':') !== -1; var host = ipv6 ? '[' + obj.host + ']' : obj.host; // define unique id obj.id = obj.protocol + '://' + host + ':' + obj.port; // define href obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : ':' + obj.port); return obj; }
URL parser. @param {String} url @param {Object} An object meant to mimic window.location. Defaults to window.location. @api public
url
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function useColors() { // is webkit? http://stackoverflow.com/a/16459606/376773 return ('WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); }
Currently only WebKit-based Web Inspectors, Firefox >= v31, and the Firebug extension (any Firefox version) are known to support "%c" CSS customizations. TODO: add a `localStorage` variable to explicitly enable/disable colors
useColors
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function formatArgs() { var args = arguments; var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return args; var c = 'color: ' + this.color; args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); return args; }
Colorize log arguments if enabled. @api public
formatArgs
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); }
Invokes `console.log()` when available. No-op when `console.log` is not a "function". @api public
log
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} }
Save `namespaces`. @param {String} namespaces @api private
save
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function load() { var r; try { r = exports.storage.debug; } catch(e) {} return r; }
Load `namespaces`. @return {String} returns the previously persisted debug modes @api private
load
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function localstorage(){ try { return window.localStorage; } catch (e) {} }
Localstorage attempts to return the localstorage. This is necessary because safari throws when a user disables cookies/localstorage and you attempt to access it. @return {LocalStorage} @api private
localstorage
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; }
Select a color. @return {Number} @api private
selectColor
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = Array.prototype.slice.call(arguments); args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); if ('function' === typeof exports.formatArgs) { args = exports.formatArgs.apply(self, args); } var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; }
Create a debugger with the given `namespace`. @param {String} namespace @return {Function} @api public
debug
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = Array.prototype.slice.call(arguments); args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); if ('function' === typeof exports.formatArgs) { args = exports.formatArgs.apply(self, args); } var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); }
Create a debugger with the given `namespace`. @param {String} namespace @return {Function} @api public
enabled
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } }
Enables a debug mode by namespaces. This can include modes separated by a colon and wildcards. @param {String} namespaces @api public
enable
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; }
Returns true if the given mode name is enabled, false otherwise. @param {String} name @return {Boolean} @api public
enabled
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; }
Coerce `val`. @param {Mixed} val @return {Mixed} @api private
coerce
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function parse(str) { str = '' + str; if (str.length > 10000) return; var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); if (!match) return; var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; } }
Parse the given `str` and return milliseconds. @param {String} str @return {Number} @api private
parse
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function short(ms) { if (ms >= d) return Math.round(ms / d) + 'd'; if (ms >= h) return Math.round(ms / h) + 'h'; if (ms >= m) return Math.round(ms / m) + 'm'; if (ms >= s) return Math.round(ms / s) + 's'; return ms + 'ms'; }
Short format for `ms`. @param {Number} ms @return {String} @api private
short
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function long(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; }
Long format for `ms`. @param {Number} ms @return {String} @api private
long
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function encodeAsString(obj) { var str = ''; var nsp = false; // first is type str += obj.type; // attachments if we have them if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) { str += obj.attachments; str += '-'; } // if we have a namespace other than `/` // we append it followed by a comma `,` if (obj.nsp && '/' != obj.nsp) { nsp = true; str += obj.nsp; } // immediately followed by the id if (null != obj.id) { if (nsp) { str += ','; nsp = false; } str += obj.id; } // json data if (null != obj.data) { if (nsp) str += ','; str += json.stringify(obj.data); } debug('encoded %j as %s', obj, str); return str; }
Encode packet as string. @param {Object} packet @return {String} encoded @api private
encodeAsString
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function encodeAsBinary(obj, callback) { function writeEncoding(bloblessData) { var deconstruction = binary.deconstructPacket(bloblessData); var pack = encodeAsString(deconstruction.packet); var buffers = deconstruction.buffers; buffers.unshift(pack); // add packet info to beginning of data list callback(buffers); // write all the buffers } binary.removeBlobs(obj, writeEncoding); }
Encode packet as 'buffer sequence' by removing blobs, and deconstructing packet into object with placeholders and a list of buffers. @param {Object} packet @return {Buffer} encoded @api private
encodeAsBinary
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function writeEncoding(bloblessData) { var deconstruction = binary.deconstructPacket(bloblessData); var pack = encodeAsString(deconstruction.packet); var buffers = deconstruction.buffers; buffers.unshift(pack); // add packet info to beginning of data list callback(buffers); // write all the buffers }
Encode packet as 'buffer sequence' by removing blobs, and deconstructing packet into object with placeholders and a list of buffers. @param {Object} packet @return {Buffer} encoded @api private
writeEncoding
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function Decoder() { this.reconstructor = null; }
A socket.io Decoder instance @return {Object} decoder @api public
Decoder
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function decodeString(str) { var p = {}; var i = 0; // look up type p.type = Number(str.charAt(0)); if (null == exports.types[p.type]) return error(); // look up attachments if type binary if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) { var buf = ''; while (str.charAt(++i) != '-') { buf += str.charAt(i); if (i == str.length) break; } if (buf != Number(buf) || str.charAt(i) != '-') { throw new Error('Illegal attachments'); } p.attachments = Number(buf); } // look up namespace (if any) if ('/' == str.charAt(i + 1)) { p.nsp = ''; while (++i) { var c = str.charAt(i); if (',' == c) break; p.nsp += c; if (i == str.length) break; } } else { p.nsp = '/'; } // look up id var next = str.charAt(i + 1); if ('' !== next && Number(next) == next) { p.id = ''; while (++i) { var c = str.charAt(i); if (null == c || Number(c) != c) { --i; break; } p.id += str.charAt(i); if (i == str.length) break; } p.id = Number(p.id); } // look up json data if (str.charAt(++i)) { try { p.data = json.parse(str.substr(i)); } catch(e){ return error(); } } debug('decoded %s as %j', str, p); return p; }
Decode a packet String (JSON data) @param {String} str @return {Object} packet @api private
decodeString
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function BinaryReconstructor(packet) { this.reconPack = packet; this.buffers = []; }
A manager of a binary event's 'buffer sequence'. Should be constructed whenever a packet of type BINARY_EVENT is decoded. @param {Object} packet @return {BinaryReconstructor} initialized reconstructor @api private
BinaryReconstructor
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function error(data){ return { type: exports.ERROR, data: 'parser error' }; }
Cleans up binary packet reconstruction variables. @api private
error
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function _deconstructPacket(data) { if (!data) return data; if (isBuf(data)) { var placeholder = { _placeholder: true, num: buffers.length }; buffers.push(data); return placeholder; } else if (isArray(data)) { var newData = new Array(data.length); for (var i = 0; i < data.length; i++) { newData[i] = _deconstructPacket(data[i]); } return newData; } else if ('object' == typeof data && !(data instanceof Date)) { var newData = {}; for (var key in data) { newData[key] = _deconstructPacket(data[key]); } return newData; } return data; }
Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder. Anything with blobs or files should be fed through removeBlobs before coming here. @param {Object} packet - socket.io event packet @return {Object} with deconstructed packet and list of buffers @api public
_deconstructPacket
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function _reconstructPacket(data) { if (data && data._placeholder) { var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway) return buf; } else if (isArray(data)) { for (var i = 0; i < data.length; i++) { data[i] = _reconstructPacket(data[i]); } return data; } else if (data && 'object' == typeof data) { for (var key in data) { data[key] = _reconstructPacket(data[key]); } return data; } return data; }
Reconstructs a binary packet from its placeholder packet and buffers @param {Object} packet - event packet with placeholders @param {Array} buffers - binary buffers to put in placeholder positions @return {Object} reconstructed packet @api public
_reconstructPacket
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function _removeBlobs(obj, curKey, containingObject) { if (!obj) return obj; // convert any blob if ((global.Blob && obj instanceof Blob) || (global.File && obj instanceof File)) { pendingBlobs++; // async filereader var fileReader = new FileReader(); fileReader.onload = function() { // this.result == arraybuffer if (containingObject) { containingObject[curKey] = this.result; } else { bloblessData = this.result; } // if nothing pending its callback time if(! --pendingBlobs) { callback(bloblessData); } }; fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer } else if (isArray(obj)) { // handle array for (var i = 0; i < obj.length; i++) { _removeBlobs(obj[i], i, obj); } } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object for (var key in obj) { _removeBlobs(obj[key], key, obj); } } }
Asynchronously removes Blobs or Files from data via FileReader's readAsArrayBuffer method. Used before encoding data as msgpack. Calls callback with the blobless data. @param {Object} data @param {Function} callback @api private
_removeBlobs
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function isBuf(obj) { return (global.Buffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer); }
Returns true if obj is a buffer or an arraybuffer. @api private
isBuf
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function Manager(uri, opts) { if (!(this instanceof Manager)) return new Manager(uri, opts); if (uri && 'object' === (typeof uri === 'undefined' ? 'undefined' : _typeof(uri))) { opts = uri; uri = undefined; } opts = opts || {}; opts.path = opts.path || '/socket.io'; this.nsps = {}; this.subs = []; this.opts = opts; this.reconnection(opts.reconnection !== false); this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); this.reconnectionDelay(opts.reconnectionDelay || 1000); this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); this.randomizationFactor(opts.randomizationFactor || 0.5); this.backoff = new Backoff({ min: this.reconnectionDelay(), max: this.reconnectionDelayMax(), jitter: this.randomizationFactor() }); this.timeout(null == opts.timeout ? 20000 : opts.timeout); this.readyState = 'closed'; this.uri = uri; this.connecting = []; this.lastPing = null; this.encoding = false; this.packetBuffer = []; this.encoder = new parser.Encoder(); this.decoder = new parser.Decoder(); this.autoConnect = opts.autoConnect !== false; if (this.autoConnect) this.open(); }
`Manager` constructor. @param {String} engine instance or engine uri/opts @param {Object} options @api public
Manager
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function onConnecting() { if (!~indexOf(self.connecting, socket)) { self.connecting.push(socket); } }
Creates a new socket for the given `nsp`. @return {Socket} @api public
onConnecting
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function Socket (uri, opts) { if (!(this instanceof Socket)) return new Socket(uri, opts); opts = opts || {}; if (uri && 'object' === typeof uri) { opts = uri; uri = null; } if (uri) { uri = parseuri(uri); opts.hostname = uri.host; opts.secure = uri.protocol === 'https' || uri.protocol === 'wss'; opts.port = uri.port; if (uri.query) opts.query = uri.query; } else if (opts.host) { opts.hostname = parseuri(opts.host).host; } this.secure = null != opts.secure ? opts.secure : (global.location && 'https:' === location.protocol); if (opts.hostname && !opts.port) { // if no port is specified manually, use the protocol default opts.port = this.secure ? '443' : '80'; } this.agent = opts.agent || false; this.hostname = opts.hostname || (global.location ? location.hostname : 'localhost'); this.port = opts.port || (global.location && location.port ? location.port : (this.secure ? 443 : 80)); this.query = opts.query || {}; if ('string' === typeof this.query) this.query = parseqs.decode(this.query); this.upgrade = false !== opts.upgrade; this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; this.forceJSONP = !!opts.forceJSONP; this.jsonp = false !== opts.jsonp; this.forceBase64 = !!opts.forceBase64; this.enablesXDR = !!opts.enablesXDR; this.timestampParam = opts.timestampParam || 't'; this.timestampRequests = opts.timestampRequests; this.transports = opts.transports || ['polling', 'websocket']; this.readyState = ''; this.writeBuffer = []; this.prevBufferLen = 0; this.policyPort = opts.policyPort || 843; this.rememberUpgrade = opts.rememberUpgrade || false; this.binaryType = null; this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false; if (true === this.perMessageDeflate) this.perMessageDeflate = {}; if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) { this.perMessageDeflate.threshold = 1024; } // SSL options for Node.js client this.pfx = opts.pfx || null; this.key = opts.key || null; this.passphrase = opts.passphrase || null; this.cert = opts.cert || null; this.ca = opts.ca || null; this.ciphers = opts.ciphers || null; this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized; // other options for Node.js client var freeGlobal = typeof global === 'object' && global; if (freeGlobal.global === freeGlobal) { if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) { this.extraHeaders = opts.extraHeaders; } } // set on handshake this.id = null; this.upgrades = null; this.pingInterval = null; this.pingTimeout = null; // set on heartbeat this.pingIntervalTimer = null; this.pingTimeoutTimer = null; this.open(); }
Socket constructor. @param {String|Object} uri or options @param {Object} options @api public
Socket
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function clone (obj) { var o = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { o[i] = obj[i]; } } return o; }
Creates transport of the given type. @param {String} transport name @return {Transport} @api private
clone
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function onTransportOpen () { if (self.onlyBinaryUpgrades) { var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; failed = failed || upgradeLosesBinary; } if (failed) return; debug('probe transport "%s" opened', name); transport.send([{ type: 'ping', data: 'probe' }]); transport.once('packet', function (msg) { if (failed) return; if ('pong' === msg.type && 'probe' === msg.data) { debug('probe transport "%s" pong', name); self.upgrading = true; self.emit('upgrading', transport); if (!transport) return; Socket.priorWebsocketSuccess = 'websocket' === transport.name; debug('pausing current transport "%s"', self.transport.name); self.transport.pause(function () { if (failed) return; if ('closed' === self.readyState) return; debug('changing transport and sending upgrade packet'); cleanup(); self.setTransport(transport); transport.send([{ type: 'upgrade' }]); self.emit('upgrade', transport); transport = null; self.upgrading = false; self.flush(); }); } else { debug('probe transport "%s" failed', name); var err = new Error('probe error'); err.transport = transport.name; self.emit('upgradeError', err); } }); }
Probes a transport. @param {String} transport name @api private
onTransportOpen
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function freezeTransport () { if (failed) return; // Any callback called by transport should be ignored since now failed = true; cleanup(); transport.close(); transport = null; }
Probes a transport. @param {String} transport name @api private
freezeTransport
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function onerror (err) { var error = new Error('probe error: ' + err); error.transport = transport.name; freezeTransport(); debug('probe transport "%s" failed because of error: %s', name, err); self.emit('upgradeError', error); }
Probes a transport. @param {String} transport name @api private
onerror
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function onTransportClose () { onerror('transport closed'); }
Probes a transport. @param {String} transport name @api private
onTransportClose
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function onclose () { onerror('socket closed'); }
Probes a transport. @param {String} transport name @api private
onclose
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function onupgrade (to) { if (transport && to.name !== transport.name) { debug('"%s" works - aborting "%s"', to.name, transport.name); freezeTransport(); } }
Probes a transport. @param {String} transport name @api private
onupgrade
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function cleanup () { transport.removeListener('open', onTransportOpen); transport.removeListener('error', onerror); transport.removeListener('close', onTransportClose); self.removeListener('close', onclose); self.removeListener('upgrading', onupgrade); }
Probes a transport. @param {String} transport name @api private
cleanup
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function polling (opts) { var xhr; var xd = false; var xs = false; var jsonp = false !== opts.jsonp; if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } xd = opts.hostname !== location.hostname || port !== opts.port; xs = opts.secure !== isSSL; } opts.xdomain = xd; opts.xscheme = xs; xhr = new XMLHttpRequest(opts); if ('open' in xhr && !opts.forceJSONP) { return new XHR(opts); } else { if (!jsonp) throw new Error('JSONP disabled'); return new JSONP(opts); } }
Polling transport polymorphic constructor. Decides on xhr vs jsonp based on feature detection. @api private
polling
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function XHR (opts) { Polling.call(this, opts); if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } this.xd = opts.hostname !== global.location.hostname || port !== opts.port; this.xs = opts.secure !== isSSL; } else { this.extraHeaders = opts.extraHeaders; } }
XHR Polling constructor. @param {Object} opts @api public
XHR
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function Request (opts) { this.method = opts.method || 'GET'; this.uri = opts.uri; this.xd = !!opts.xd; this.xs = !!opts.xs; this.async = false !== opts.async; this.data = undefined !== opts.data ? opts.data : null; this.agent = opts.agent; this.isBinary = opts.isBinary; this.supportsBinary = opts.supportsBinary; this.enablesXDR = opts.enablesXDR; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; // other options for Node.js client this.extraHeaders = opts.extraHeaders; this.create(); }
Request constructor @param {Object} options @api public
Request
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function Polling (opts) { var forceBase64 = (opts && opts.forceBase64); if (!hasXHR2 || forceBase64) { this.supportsBinary = false; } Transport.call(this, opts); }
Polling interface. @param {Object} opts @api private
Polling
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function pause () { debug('paused'); self.readyState = 'paused'; onPause(); }
Pauses polling. @param {Function} callback upon buffers are flushed and transport is paused @api private
pause
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
callback = function (packet, index, total) { // if its the first message we consider the transport open if ('opening' === self.readyState) { self.onOpen(); } // if its a close packet, we close the ongoing requests if ('close' === packet.type) { self.onClose(); return false; } // otherwise bypass onData and handle the message self.onPacket(packet); }
Overloads onData to detect payloads. @api private
callback
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function close () { debug('writing close packet'); self.write([{ type: 'close' }]); }
For polling, send a close packet. @api private
close
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
callbackfn = function () { self.writable = true; self.emit('drain'); }
Writes a packets payload. @param {Array} data packets @param {Function} drain callback @api private
callbackfn
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function Transport (opts) { this.path = opts.path; this.hostname = opts.hostname; this.port = opts.port; this.secure = opts.secure; this.query = opts.query; this.timestampParam = opts.timestampParam; this.timestampRequests = opts.timestampRequests; this.readyState = ''; this.agent = opts.agent || false; this.socket = opts.socket; this.enablesXDR = opts.enablesXDR; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; // other options for Node.js client this.extraHeaders = opts.extraHeaders; }
Transport abstract constructor. @param {Object} options. @api private
Transport
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function encodeBase64Object(packet, callback) { // packet data is an object { base64: true, data: dataAsBase64String } var message = 'b' + exports.packets[packet.type] + packet.data.data; return callback(message); }
Encodes a packet. <packet type id> [ <data> ] Example: 5hello world 3 4 Binary is encoded in an identical principle @api private
encodeBase64Object
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function encodeArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var data = packet.data; var contentArray = new Uint8Array(data); var resultBuffer = new Uint8Array(1 + data.byteLength); resultBuffer[0] = packets[packet.type]; for (var i = 0; i < contentArray.length; i++) { resultBuffer[i+1] = contentArray[i]; } return callback(resultBuffer.buffer); }
Encode packet helpers for binary types
encodeArrayBuffer
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var fr = new FileReader(); fr.onload = function() { packet.data = fr.result; exports.encodePacket(packet, supportsBinary, true, callback); }; return fr.readAsArrayBuffer(packet.data); }
Encode packet helpers for binary types
encodeBlobAsArrayBuffer
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function encodeBlob(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } if (dontSendBlobs) { return encodeBlobAsArrayBuffer(packet, supportsBinary, callback); } var length = new Uint8Array(1); length[0] = packets[packet.type]; var blob = new Blob([length.buffer, packet.data]); return callback(blob); }
Encode packet helpers for binary types
encodeBlob
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function tryDecode(data) { try { data = utf8.decode(data); } catch (e) { return false; } return data; }
Decodes a packet. Changes format to Blob if requested. @return {Object} with `type` and `data` (if any) @api private
tryDecode
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function setLengthHeader(message) { return message.length + ':' + message; }
Encodes multiple messages (payload). <length>:data Example: 11:hello world2:hi If any contents are binary, they will be encoded as base64 strings. Base64 encoded strings are marked with a b before the length specifier @param {Array} packets @api private
setLengthHeader
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function encodeOne(packet, doneCallback) { exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) { doneCallback(null, setLengthHeader(message)); }); }
Encodes multiple messages (payload). <length>:data Example: 11:hello world2:hi If any contents are binary, they will be encoded as base64 strings. Base64 encoded strings are marked with a b before the length specifier @param {Array} packets @api private
encodeOne
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, true, function(data) { return doneCallback(null, data); }); }
Encodes multiple messages (payload) as binary. <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number 255><data> Example: 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers @param {Array} packets @return {ArrayBuffer} encoded payload @api private
encodeOne
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function hasBinary(data) { function _hasBinary(obj) { if (!obj) return false; if ( (global.Buffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer) || (global.Blob && obj instanceof Blob) || (global.File && obj instanceof File) ) { return true; } if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (_hasBinary(obj[i])) { return true; } } } else if (obj && 'object' == typeof obj) { if (obj.toJSON) { obj = obj.toJSON(); } for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) { return true; } } } return false; } return _hasBinary(data); }
Checks for binary data. Right now only Buffer and ArrayBuffer are supported.. @param {Object} anything @api public
hasBinary
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function _hasBinary(obj) { if (!obj) return false; if ( (global.Buffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer) || (global.Blob && obj instanceof Blob) || (global.File && obj instanceof File) ) { return true; } if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (_hasBinary(obj[i])) { return true; } } } else if (obj && 'object' == typeof obj) { if (obj.toJSON) { obj = obj.toJSON(); } for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) { return true; } } } return false; }
Checks for binary data. Right now only Buffer and ArrayBuffer are supported.. @param {Object} anything @api public
_hasBinary
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function mapArrayBufferViews(ary) { for (var i = 0; i < ary.length; i++) { var chunk = ary[i]; if (chunk.buffer instanceof ArrayBuffer) { var buf = chunk.buffer; // if this is a subarray, make a copy so we only // include the subarray region from the underlying buffer if (chunk.byteLength !== buf.byteLength) { var copy = new Uint8Array(chunk.byteLength); copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); buf = copy.buffer; } ary[i] = buf; } } }
Helper function that maps ArrayBufferViews to ArrayBuffers Used by BlobBuilder constructor and old browsers that didn't support it in the Blob constructor.
mapArrayBufferViews
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function BlobBuilderConstructor(ary, options) { options = options || {}; var bb = new BlobBuilder(); mapArrayBufferViews(ary); for (var i = 0; i < ary.length; i++) { bb.append(ary[i]); } return (options.type) ? bb.getBlob(options.type) : bb.getBlob(); }
Helper function that maps ArrayBufferViews to ArrayBuffers Used by BlobBuilder constructor and old browsers that didn't support it in the Blob constructor.
BlobBuilderConstructor
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function BlobConstructor(ary, options) { mapArrayBufferViews(ary); return new Blob(ary, options || {}); }
Helper function that maps ArrayBufferViews to ArrayBuffers Used by BlobBuilder constructor and old browsers that didn't support it in the Blob constructor.
BlobConstructor
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function encode(num) { var encoded = ''; do { encoded = alphabet[num % length] + encoded; num = Math.floor(num / length); } while (num > 0); return encoded; }
Return a string representing the specified number. @param {Number} num The number to convert. @returns {String} The string representation of the number. @api public
encode
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function decode(str) { var decoded = 0; for (i = 0; i < str.length; i++) { decoded = decoded * length + map[str.charAt(i)]; } return decoded; }
Return the integer value specified by the given string. @param {String} str The string to convert. @returns {Number} The integer value represented by the string. @api public
decode
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function yeast() { var now = encode(+new Date()); if (now !== prev) return seed = 0, prev = now; return now +'.'+ encode(seed++); }
Yeast: A tiny growing id generator. @returns {String} A unique id. @api public
yeast
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function JSONPPolling (opts) { Polling.call(this, opts); this.query = this.query || {}; // define global callbacks array if not present // we do this here (lazily) to avoid unneeded global pollution if (!callbacks) { // we need to consider multiple engines in the same page if (!global.___eio) global.___eio = []; callbacks = global.___eio; } // callback identifier this.index = callbacks.length; // add callback to jsonp global var self = this; callbacks.push(function (msg) { self.onData(msg); }); // append to query string this.query.j = this.index; // prevent spurious errors from being emitted when the window is unloaded if (global.document && global.addEventListener) { global.addEventListener('beforeunload', function () { if (self.script) self.script.onerror = empty; }, false); } }
JSONP Polling constructor. @param {Object} opts. @api public
JSONPPolling
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function complete () { initIframe(); fn(); }
Writes with a hidden iframe. @param {String} data to send @param {Function} called upon flush. @api private
complete
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function initIframe () { if (self.iframe) { try { self.form.removeChild(self.iframe); } catch (e) { self.onError('jsonp polling iframe removal error', e); } } try { // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) var html = '<iframe src="javascript:0" name="' + self.iframeId + '">'; iframe = document.createElement(html); } catch (e) { iframe = document.createElement('iframe'); iframe.name = self.iframeId; iframe.src = 'javascript:0'; } iframe.id = self.iframeId; self.form.appendChild(iframe); self.iframe = iframe; }
Writes with a hidden iframe. @param {String} data to send @param {Function} called upon flush. @api private
initIframe
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function WS (opts) { var forceBase64 = (opts && opts.forceBase64); if (forceBase64) { this.supportsBinary = false; } this.perMessageDeflate = opts.perMessageDeflate; Transport.call(this, opts); }
WebSocket transport constructor. @api {Object} connection options @api public
WS
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function done () { self.emit('flush'); // fake drain // defer to next tick to allow Socket to clear writeBuffer setTimeout(function () { self.writable = true; self.emit('drain'); }, 0); }
Writes data to socket. @param {Array} array of packets. @api private
done
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function hasBinary(data) { function _hasBinary(obj) { if (!obj) return false; if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer) || (global.Blob && obj instanceof Blob) || (global.File && obj instanceof File) ) { return true; } if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (_hasBinary(obj[i])) { return true; } } } else if (obj && 'object' == typeof obj) { // see: https://github.com/Automattic/has-binary/pull/4 if (obj.toJSON && 'function' == typeof obj.toJSON) { obj = obj.toJSON(); } for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) { return true; } } } return false; } return _hasBinary(data); }
Checks for binary data. Right now only Buffer and ArrayBuffer are supported.. @param {Object} anything @api public
hasBinary
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function _hasBinary(obj) { if (!obj) return false; if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer) || (global.Blob && obj instanceof Blob) || (global.File && obj instanceof File) ) { return true; } if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (_hasBinary(obj[i])) { return true; } } } else if (obj && 'object' == typeof obj) { // see: https://github.com/Automattic/has-binary/pull/4 if (obj.toJSON && 'function' == typeof obj.toJSON) { obj = obj.toJSON(); } for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) { return true; } } } return false; }
Checks for binary data. Right now only Buffer and ArrayBuffer are supported.. @param {Object} anything @api public
_hasBinary
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function Backoff(opts) { opts = opts || {}; this.ms = opts.min || 100; this.max = opts.max || 10000; this.factor = opts.factor || 2; this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; this.attempts = 0; }
Initialize backoff timer with `opts`. - `min` initial timeout in milliseconds [100] - `max` max timeout [10000] - `jitter` [0] - `factor` [2] @param {Object} opts @api public
Backoff
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/file-sharing/rmc-files-handler.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js
MIT
function makeMetadataSeekable(originalMetadata, duration, cuesInfo) { // extract the header, we can reuse this as-is var header = extractElement("EBML", originalMetadata); var headerSize = encodedSizeOfEbml(header); //console.error("Header size: " + headerSize); //printElementIds(header); // After the header comes the Segment open tag, which in this implementation is always 12 bytes (4 byte id, 8 byte 'unknown length') // After that the segment content starts. All SeekPositions and CueClusterPosition must be relative to segmentContentStartPos var segmentContentStartPos = headerSize + 12; //console.error("segmentContentStartPos: " + segmentContentStartPos); // find the original metadata size, and adjust it for header size and Segment start element so we can keep all positions relative to segmentContentStartPos var originalMetadataSize = originalMetadata[originalMetadata.length - 1].dataEnd - segmentContentStartPos; //console.error("Original Metadata size: " + originalMetadataSize); //printElementIds(originalMetadata); // extract the segment info, remove the potentially existing Duration element, and add our own one. var info = extractElement("Info", originalMetadata); removeElement("Duration", info); info.splice(1, 0, { name: "Duration", type: "f", data: createFloatBuffer(duration, 8) }); var infoSize = encodedSizeOfEbml(info); //console.error("Info size: " + infoSize); //printElementIds(info); // extract the track info, we can re-use this as is var tracks = extractElement("Tracks", originalMetadata); var tracksSize = encodedSizeOfEbml(tracks); //console.error("Tracks size: " + tracksSize); //printElementIds(tracks); var seekHeadSize = 47; // Initial best guess, but could be slightly larger if the Cues element is huge. var seekHead = []; var cuesSize = 5 + cuesInfo.length * 15; // very rough initial approximation, depends a lot on file size and number of CuePoints var cues = []; var lastSizeDifference = -1; // // The size of SeekHead and Cues elements depends on how many bytes the offsets values can be encoded in. // The actual offsets in CueClusterPosition depend on the final size of the SeekHead and Cues elements // We need to iteratively converge to a stable solution. var maxIterations = 10; var _loop_1 = function (i) { // SeekHead starts at 0 var infoStart = seekHeadSize; // Info comes directly after SeekHead var tracksStart = infoStart + infoSize; // Tracks comes directly after Info var cuesStart = tracksStart + tracksSize; // Cues starts directly after var newMetadataSize = cuesStart + cuesSize; // total size of metadata // This is the offset all CueClusterPositions should be adjusted by due to the metadata size changing. var sizeDifference = newMetadataSize - originalMetadataSize; // console.error(`infoStart: ${infoStart}, infoSize: ${infoSize}`); // console.error(`tracksStart: ${tracksStart}, tracksSize: ${tracksSize}`); // console.error(`cuesStart: ${cuesStart}, cuesSize: ${cuesSize}`); // console.error(`originalMetadataSize: ${originalMetadataSize}, newMetadataSize: ${newMetadataSize}, sizeDifference: ${sizeDifference}`); // create the SeekHead element seekHead = []; seekHead.push({ name: "SeekHead", type: "m", isEnd: false }); seekHead.push({ name: "Seek", type: "m", isEnd: false }); seekHead.push({ name: "SeekID", type: "b", data: new exports.Buffer([0x15, 0x49, 0xA9, 0x66]) }); // Info seekHead.push({ name: "SeekPosition", type: "u", data: createUIntBuffer(infoStart) }); seekHead.push({ name: "Seek", type: "m", isEnd: true }); seekHead.push({ name: "Seek", type: "m", isEnd: false }); seekHead.push({ name: "SeekID", type: "b", data: new exports.Buffer([0x16, 0x54, 0xAE, 0x6B]) }); // Tracks seekHead.push({ name: "SeekPosition", type: "u", data: createUIntBuffer(tracksStart) }); seekHead.push({ name: "Seek", type: "m", isEnd: true }); seekHead.push({ name: "Seek", type: "m", isEnd: false }); seekHead.push({ name: "SeekID", type: "b", data: new exports.Buffer([0x1C, 0x53, 0xBB, 0x6B]) }); // Cues seekHead.push({ name: "SeekPosition", type: "u", data: createUIntBuffer(cuesStart) }); seekHead.push({ name: "Seek", type: "m", isEnd: true }); seekHead.push({ name: "SeekHead", type: "m", isEnd: true }); seekHeadSize = encodedSizeOfEbml(seekHead); //console.error("SeekHead size: " + seekHeadSize); //printElementIds(seekHead); // create the Cues element cues = []; cues.push({ name: "Cues", type: "m", isEnd: false }); cuesInfo.forEach(function (_a) { var CueTrack = _a.CueTrack, CueClusterPosition = _a.CueClusterPosition, CueTime = _a.CueTime; cues.push({ name: "CuePoint", type: "m", isEnd: false }); cues.push({ name: "CueTime", type: "u", data: createUIntBuffer(CueTime) }); cues.push({ name: "CueTrackPositions", type: "m", isEnd: false }); cues.push({ name: "CueTrack", type: "u", data: createUIntBuffer(CueTrack) }); //console.error(`CueClusterPosition: ${CueClusterPosition}, Corrected to: ${CueClusterPosition - segmentContentStartPos} , offset by ${sizeDifference} to become ${(CueClusterPosition - segmentContentStartPos) + sizeDifference - segmentContentStartPos}`); // EBMLReader returns CueClusterPosition with absolute byte offsets. The Cues section expects them as offsets from the first level 1 element of the Segment, so we need to adjust it. CueClusterPosition -= segmentContentStartPos; // We also need to adjust to take into account the change in metadata size from when EBMLReader read the original metadata. CueClusterPosition += sizeDifference; cues.push({ name: "CueClusterPosition", type: "u", data: createUIntBuffer(CueClusterPosition) }); cues.push({ name: "CueTrackPositions", type: "m", isEnd: true }); cues.push({ name: "CuePoint", type: "m", isEnd: true }); }); cues.push({ name: "Cues", type: "m", isEnd: true }); cuesSize = encodedSizeOfEbml(cues); //console.error("Cues size: " + cuesSize); //console.error("Cue count: " + cuesInfo.length); //printElementIds(cues); // If the new MetadataSize is not the same as the previous iteration, we need to run once more. if (lastSizeDifference !== sizeDifference) { lastSizeDifference = sizeDifference; if (i === maxIterations - 1) { throw new Error("Failed to converge to a stable metadata size"); } } else { return "break"; } }; for (var i = 0; i < maxIterations; i++) { var state_1 = _loop_1(i); if (state_1 === "break") break; } var finalMetadata = [].concat.apply([], [ header, { name: "Segment", type: "m", isEnd: false, unknownSize: true }, seekHead, info, tracks, cues ]); var result = new EBMLEncoder_1.default().encode(finalMetadata); //printElementIds(finalMetadata); //console.error(`Final metadata buffer size: ${result.byteLength}`); //console.error(`Final metadata buffer size without header and segment: ${result.byteLength-segmentContentStartPos}`); return result; }
convert the metadata from a streaming webm bytestream to a seekable file by inserting Duration, Seekhead and Cues @param originalMetadata - orginal metadata (everything before the clusters start) from media recorder @param duration - Duration (TimecodeScale) @param cues - cue points for clusters
makeMetadataSeekable
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/screen-recording/RecordRTC/EBML.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/screen-recording/RecordRTC/EBML.js
MIT
_loop_1 = function (i) { // SeekHead starts at 0 var infoStart = seekHeadSize; // Info comes directly after SeekHead var tracksStart = infoStart + infoSize; // Tracks comes directly after Info var cuesStart = tracksStart + tracksSize; // Cues starts directly after var newMetadataSize = cuesStart + cuesSize; // total size of metadata // This is the offset all CueClusterPositions should be adjusted by due to the metadata size changing. var sizeDifference = newMetadataSize - originalMetadataSize; // console.error(`infoStart: ${infoStart}, infoSize: ${infoSize}`); // console.error(`tracksStart: ${tracksStart}, tracksSize: ${tracksSize}`); // console.error(`cuesStart: ${cuesStart}, cuesSize: ${cuesSize}`); // console.error(`originalMetadataSize: ${originalMetadataSize}, newMetadataSize: ${newMetadataSize}, sizeDifference: ${sizeDifference}`); // create the SeekHead element seekHead = []; seekHead.push({ name: "SeekHead", type: "m", isEnd: false }); seekHead.push({ name: "Seek", type: "m", isEnd: false }); seekHead.push({ name: "SeekID", type: "b", data: new exports.Buffer([0x15, 0x49, 0xA9, 0x66]) }); // Info seekHead.push({ name: "SeekPosition", type: "u", data: createUIntBuffer(infoStart) }); seekHead.push({ name: "Seek", type: "m", isEnd: true }); seekHead.push({ name: "Seek", type: "m", isEnd: false }); seekHead.push({ name: "SeekID", type: "b", data: new exports.Buffer([0x16, 0x54, 0xAE, 0x6B]) }); // Tracks seekHead.push({ name: "SeekPosition", type: "u", data: createUIntBuffer(tracksStart) }); seekHead.push({ name: "Seek", type: "m", isEnd: true }); seekHead.push({ name: "Seek", type: "m", isEnd: false }); seekHead.push({ name: "SeekID", type: "b", data: new exports.Buffer([0x1C, 0x53, 0xBB, 0x6B]) }); // Cues seekHead.push({ name: "SeekPosition", type: "u", data: createUIntBuffer(cuesStart) }); seekHead.push({ name: "Seek", type: "m", isEnd: true }); seekHead.push({ name: "SeekHead", type: "m", isEnd: true }); seekHeadSize = encodedSizeOfEbml(seekHead); //console.error("SeekHead size: " + seekHeadSize); //printElementIds(seekHead); // create the Cues element cues = []; cues.push({ name: "Cues", type: "m", isEnd: false }); cuesInfo.forEach(function (_a) { var CueTrack = _a.CueTrack, CueClusterPosition = _a.CueClusterPosition, CueTime = _a.CueTime; cues.push({ name: "CuePoint", type: "m", isEnd: false }); cues.push({ name: "CueTime", type: "u", data: createUIntBuffer(CueTime) }); cues.push({ name: "CueTrackPositions", type: "m", isEnd: false }); cues.push({ name: "CueTrack", type: "u", data: createUIntBuffer(CueTrack) }); //console.error(`CueClusterPosition: ${CueClusterPosition}, Corrected to: ${CueClusterPosition - segmentContentStartPos} , offset by ${sizeDifference} to become ${(CueClusterPosition - segmentContentStartPos) + sizeDifference - segmentContentStartPos}`); // EBMLReader returns CueClusterPosition with absolute byte offsets. The Cues section expects them as offsets from the first level 1 element of the Segment, so we need to adjust it. CueClusterPosition -= segmentContentStartPos; // We also need to adjust to take into account the change in metadata size from when EBMLReader read the original metadata. CueClusterPosition += sizeDifference; cues.push({ name: "CueClusterPosition", type: "u", data: createUIntBuffer(CueClusterPosition) }); cues.push({ name: "CueTrackPositions", type: "m", isEnd: true }); cues.push({ name: "CuePoint", type: "m", isEnd: true }); }); cues.push({ name: "Cues", type: "m", isEnd: true }); cuesSize = encodedSizeOfEbml(cues); //console.error("Cues size: " + cuesSize); //console.error("Cue count: " + cuesInfo.length); //printElementIds(cues); // If the new MetadataSize is not the same as the previous iteration, we need to run once more. if (lastSizeDifference !== sizeDifference) { lastSizeDifference = sizeDifference; if (i === maxIterations - 1) { throw new Error("Failed to converge to a stable metadata size"); } } else { return "break"; } }
convert the metadata from a streaming webm bytestream to a seekable file by inserting Duration, Seekhead and Cues @param originalMetadata - orginal metadata (everything before the clusters start) from media recorder @param duration - Duration (TimecodeScale) @param cues - cue points for clusters
_loop_1
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/screen-recording/RecordRTC/EBML.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/screen-recording/RecordRTC/EBML.js
MIT
function removeElement(idName, metadata) { var result = []; var start = -1; for (var i = 0; i < metadata.length; i++) { var element = metadata[i]; if (element.name === idName) { // if it's a Master element, extract the start and end element, and everything in between if (element.type === "m") { if (!element.isEnd) { start = i; } else { // we've reached the end, extract the whole thing if (start == -1) throw new Error("Detected " + idName + " closing element before finding the start"); metadata.splice(start, i - start + 1); return; } } else { // not a Master element, so we've found what we're looking for. metadata.splice(i, 1); return; } } } }
remove all occurances of an EBML element from an array of elements If it's a MasterElement you will also remove the content. (everything between start and end) @param idName - name of the EBML Element to remove. @param metadata - array of EBML elements to search
removeElement
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/screen-recording/RecordRTC/EBML.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/screen-recording/RecordRTC/EBML.js
MIT
function extractElement(idName, metadata) { var result = []; var start = -1; for (var i = 0; i < metadata.length; i++) { var element = metadata[i]; if (element.name === idName) { // if it's a Master element, extract the start and end element, and everything in between if (element.type === "m") { if (!element.isEnd) { start = i; } else { // we've reached the end, extract the whole thing if (start == -1) throw new Error("Detected " + idName + " closing element before finding the start"); result = metadata.slice(start, i + 1); break; } } else { // not a Master element, so we've found what we're looking for. result.push(metadata[i]); break; } } } return result; }
extract the first occurance of an EBML tag from a flattened array of EBML data. If it's a MasterElement you will also get the content. (everything between start and end) @param idName - name of the EBML Element to extract. @param metadata - array of EBML elements to search
extractElement
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/screen-recording/RecordRTC/EBML.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/screen-recording/RecordRTC/EBML.js
MIT
function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff }
The Buffer constructor returns instances of `Uint8Array` that have their prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, so the returned instances will have all the node `Buffer` methods and the `Uint8Array` methods. Square bracket notation works as expected -- it returns a single octet. The `Uint8Array` prototype remains unmodified.
kMaxLength
javascript
muaz-khan/WebRTC-Experiment
Chrome-Extensions/screen-recording/RecordRTC/EBML.js
https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/screen-recording/RecordRTC/EBML.js
MIT