language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class LogService { /** * Log message * * @param {*} args * @memberof LogService */ log(...args) {} /** * Log debug message * * @param {*} args * @memberof LogService */ debug(...args) {} /** * Log error message * * @param {*} args * @memberof LogService */ error(...args) {} }
JavaScript
class Schema extends SchemaCommon { constructor(properties) { super(properties); } }
JavaScript
class PlaceholderRegistry { constructor() { this._placeHolderNameCounts = {}; this._signatureToName = {}; } /** * @param {?} tag * @param {?} attrs * @param {?} isVoid * @return {?} */ getStartTagPlaceholderName(tag, attrs, isVoid) { const /** @type {?} */ signature = this._hashTag(tag, attrs, isVoid); if (this._signatureToName[signature]) { return this._signatureToName[signature]; } const /** @type {?} */ upperTag = tag.toUpperCase(); const /** @type {?} */ baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || `TAG_${upperTag}`; const /** @type {?} */ name = this._generateUniqueName(isVoid ? baseName : `START_${baseName}`); this._signatureToName[signature] = name; return name; } /** * @param {?} tag * @return {?} */ getCloseTagPlaceholderName(tag) { const /** @type {?} */ signature = this._hashClosingTag(tag); if (this._signatureToName[signature]) { return this._signatureToName[signature]; } const /** @type {?} */ upperTag = tag.toUpperCase(); const /** @type {?} */ baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || `TAG_${upperTag}`; const /** @type {?} */ name = this._generateUniqueName(`CLOSE_${baseName}`); this._signatureToName[signature] = name; return name; } /** * @param {?} name * @param {?} content * @return {?} */ getPlaceholderName(name, content) { const /** @type {?} */ upperName = name.toUpperCase(); const /** @type {?} */ signature = `PH: ${upperName}=${content}`; if (this._signatureToName[signature]) { return this._signatureToName[signature]; } const /** @type {?} */ uniqueName = this._generateUniqueName(upperName); this._signatureToName[signature] = uniqueName; return uniqueName; } /** * @param {?} name * @return {?} */ getUniquePlaceholder(name) { return this._generateUniqueName(name.toUpperCase()); } /** * @param {?} tag * @param {?} attrs * @param {?} isVoid * @return {?} */ _hashTag(tag, attrs, isVoid) { const /** @type {?} */ start = `<${tag}`; const /** @type {?} */ strAttrs = Object.keys(attrs).sort().map((name) => ` ${name}=${attrs[name]}`).join(''); const /** @type {?} */ end = isVoid ? '/>' : `></${tag}>`; return start + strAttrs + end; } /** * @param {?} tag * @return {?} */ _hashClosingTag(tag) { return this._hashTag(`/${tag}`, {}, false); } /** * @param {?} base * @return {?} */ _generateUniqueName(base) { const /** @type {?} */ seen = this._placeHolderNameCounts.hasOwnProperty(base); if (!seen) { this._placeHolderNameCounts[base] = 1; return base; } const /** @type {?} */ id = this._placeHolderNameCounts[base]; this._placeHolderNameCounts[base] = id + 1; return `${base}_${id}`; } }
JavaScript
class ModifyTrafficMirrorSessionRequest { /** * Constructs a new <code>ModifyTrafficMirrorSessionRequest</code>. * @alias module:model/ModifyTrafficMirrorSessionRequest * @param trafficMirrorSessionId {String} */ constructor(trafficMirrorSessionId) { ModifyTrafficMirrorSessionRequest.initialize(this, trafficMirrorSessionId); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj, trafficMirrorSessionId) { obj['TrafficMirrorSessionId'] = trafficMirrorSessionId; } /** * Constructs a <code>ModifyTrafficMirrorSessionRequest</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/ModifyTrafficMirrorSessionRequest} obj Optional instance to populate. * @return {module:model/ModifyTrafficMirrorSessionRequest} The populated <code>ModifyTrafficMirrorSessionRequest</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new ModifyTrafficMirrorSessionRequest(); if (data.hasOwnProperty('Description')) { obj['Description'] = ApiClient.convertToType(data['Description'], 'String'); } if (data.hasOwnProperty('DryRun')) { obj['DryRun'] = ApiClient.convertToType(data['DryRun'], 'Boolean'); } if (data.hasOwnProperty('PacketLength')) { obj['PacketLength'] = ApiClient.convertToType(data['PacketLength'], 'Number'); } if (data.hasOwnProperty('RemoveFields')) { obj['RemoveFields'] = ApiClient.convertToType(data['RemoveFields'], [TrafficMirrorSessionField]); } if (data.hasOwnProperty('SessionNumber')) { obj['SessionNumber'] = ApiClient.convertToType(data['SessionNumber'], 'Number'); } if (data.hasOwnProperty('TrafficMirrorFilterId')) { obj['TrafficMirrorFilterId'] = ApiClient.convertToType(data['TrafficMirrorFilterId'], 'String'); } if (data.hasOwnProperty('TrafficMirrorSessionId')) { obj['TrafficMirrorSessionId'] = ApiClient.convertToType(data['TrafficMirrorSessionId'], 'String'); } if (data.hasOwnProperty('TrafficMirrorTargetId')) { obj['TrafficMirrorTargetId'] = ApiClient.convertToType(data['TrafficMirrorTargetId'], 'String'); } if (data.hasOwnProperty('VirtualNetworkId')) { obj['VirtualNetworkId'] = ApiClient.convertToType(data['VirtualNetworkId'], 'Number'); } } return obj; } }
JavaScript
class EpochUpdater { constructor(client) { this.client = client; this.db = DB.epochUpdatesDB; } start() { const currentEpoch = blockchainSetting.getCurrentEpoch(); logger.log({ level: 'info', message: `Epoch updater detected that we are in epoch ${currentEpoch}!` }); this.db.get(currentEpoch - 1, (err) => { if (err) { logger.log({ level: 'info', message: `No epoch updates have been performed for epoch ${currentEpoch - 1}.` }); this.update(currentEpoch - 1); } }); const nextEpochDate = blockchainSetting.getTimeFor(currentEpoch + 1, 100); const diff = nextEpochDate - new Date(); logger.log({ level: 'info', message: `Waiting ${diff} ms for the next epoch til ${nextEpochDate}.` }); setTimeout(this.start, diff); } update(epoch) { const guildIDs = Object.keys(GuildManager.guilds); for (let i = 0; i < guildIDs.length; i++) { const guildID = guildIDs[i]; const guild = GuildManager.guilds[guildID]; api.getEpochHistoryInformation(guild.stakepoolID, epoch, (resp, err) => { if (err) { logger.log({ level: 'error', message: `Could not fetch epoch statistics for epoch ${epoch} and stake pool with ID '${guild.stakepoolID}'.`, error: err, }); } else if (resp) { if (guild.updateChannels) { const channelIDs = Object.keys(guild.updateChannels); for (let c = 0; c < channelIDs.length; c++) { const channelID = channelIDs[c]; this.client.channels.fetch(channelID).then(channel => { const locales = guild.updateChannels[channelID]; for (let l = 0; l < locales.length; l++) { channel.send(MessageManager.locale(locales[l]).getEpochInformationMessage(resp)); } }).catch(error => { logger.log({ level: 'error', message: `Could not find channel ${channelID} for guild ${guildID}.`, error: error, channelID: channelID, guildID: guildID, }); }); } } } }); } this.db.put(epoch, true); } }
JavaScript
class keystoneView { constructor(serializedState) { this.element = document.createElement('div'); this.element.classList.add('keystone'); } getTitle() { return "Keystone View"; } serialize() {} destroy() { this.element.remove(); } getElement() { return this.element; } }
JavaScript
class UpdateCloudFrontWafIpRules extends Service { constructor() { super(); this.dependency(['aws']); } async init() { await super.init(); } async execute() { const aws = await this.service('aws'); const ipSetAllowListId = this.settings.get(settingKeys.cloudFrontAllowListId); const ipSetConfig = await this._getIpConfig(); if (_.isEmpty(ipSetAllowListId)) { this.log.info('No WAF WebACL configured'); return; } const wafApi = new aws.sdk.WAF(); const updates = await this._getUpdates(wafApi, ipSetAllowListId, ipSetConfig); if (_.isEmpty(updates)) { this.log.info('No updates to WAF configuration'); return; } const changeTokenResponse = await wafApi.getChangeToken({}).promise(); const wafParams = { ChangeToken: changeTokenResponse.ChangeToken, IPSetId: ipSetAllowListId, Updates: updates, }; this.log.info(`Attempting to update WAF AllowList for CloudFront with ${updates.length} changes`); await wafApi.updateIPSet(wafParams).promise(); } async _getIpConfig() { const aws = await this.service('aws'); const ssm = new aws.sdk.SSM({ apiVersion: '2014-11-06' }); const paramStoreIpConfigSecretName = this.settings.get(settingKeys.cloudFrontAllowListSecretName); let doesKeyExist = false; /** * Parameter value should have the following structure: * [ * { * "Type": "IPV4", * "Value": "192.168.0.1/28" * }, * { * "Type": "IPV4", * "Value": "10.0.0.1/28" * }, * ] */ let parameterValue = '[{"Type": "IPV4", "Value": "127.0.0.1/32"}]'; try { const parameterResponse = await ssm .getParameter({ Name: paramStoreIpConfigSecretName, WithDecryption: true }) .promise(); parameterValue = _.get(parameterResponse, 'Parameter.Value'); doesKeyExist = true; } catch (err) { if (err.code !== 'ParameterNotFound') { // Swallow "ParameterNotFound" and let all other errors bubble up throw err; } } if (doesKeyExist) { this.log.info( `CloudFront WAF Allow List IP Configuration already exists in parameter store at ${paramStoreIpConfigSecretName}. Did not reset it.`, ); return JSON.parse(parameterValue); } await ssm .putParameter({ Name: paramStoreIpConfigSecretName, Type: 'SecureString', Value: parameterValue, Description: `CloudFront WAF Allow List IP Configuration`, Overwrite: true, }) .promise(); this.log.info( `Created empty CloudFront WAF Allow List IP Configuration and saved it to parameter store at "${paramStoreIpConfigSecretName}"`, ); return JSON.parse(parameterValue); // const aws = await this.service('aws'); // const secretsManagerApi = new aws.sdk.SecretsManager(); // const ipSetSecret = await secretsManagerApi.getSecretValue({ SecretId: ipSetSecretArn }).promise(); // let ipSetConfig; // try { // ipSetConfig = JSON.parse(ipSetSecret.SecretString); // if (!_.isArray(ipSetConfig)) { // throw new Error('IP Set should be JSON array'); // } // } catch (e) { // this.log.info(`Error ${e.message}`); // throw new Error('Incorrect WAF IP Set configuration in Secrets Manager'); // } // if (_.isEmpty(ipSetConfig)) { // this.log.warn(`No WAF IPSet has been configured, you may not be able to access the UI`); // } // return ipSetConfig; } async _getUpdates(wafApi, ipSetAllowListId, ipSetConfig) { const existingIPConfigResponse = await wafApi.getIPSet({ IPSetId: ipSetAllowListId }).promise(); const existingIPConfig = _.get(existingIPConfigResponse, 'IPSet.IPSetDescriptors'); // Find the new IPs to add const ipsToAdd = _.differenceWith(ipSetConfig, existingIPConfig, _.isEqual); // Find the existing IPs to delete const ipsToDelete = _.differenceWith(existingIPConfig, ipSetConfig, _.isEqual); const ipsInsert = ipsToAdd.map(ipSet => { return { Action: 'INSERT', IPSetDescriptor: ipSet, }; }); const ipsDelete = ipsToDelete.map(ipSet => { return { Action: 'DELETE', IPSetDescriptor: ipSet, }; }); const updates = ipsInsert.concat(ipsDelete); return updates; } }
JavaScript
class SearchController { constructor ($rootScope, $location, $log, notesGraph, openNotes) { this.$rootScope = $rootScope; this.$location = $location; this.$log = $log; this.notesGraph = notesGraph; this.openNotes = openNotes; this.activate(); } activate () { this.searchTerms = ''; this.isLoading = false; this.results = []; this.$rootScope.$watch(() => this.searchTerms, text => { if (!text) { this.isLoading = false; this.results = []; return; } this.$log.info('Searching for "' + text + '"'); this.isLoading = true; // Todo: case insensitive var regex = new RegExp(text, 'gi'); var contains = x => !!x && x.match(regex); this._search(note => contains(this.notesGraph.body(note)) || contains(this.notesGraph.title(note)) ); }); } _search (predicate) { if (this.runningSearch) { clearTimeout(this.runningSearch); this.results.length = 0; console.info('clear', this.results); } var graph = this.notesGraph; var queue = graph.roots(); console.warn('serach', queue); var digest = _ => this.$rootScope.$$phase || this.$rootScope.$apply(); var process = _ => { var item = queue.shift(); if (item === undefined) return; queue = queue.concat(graph.children(item)); if (predicate(item) && this.results.indexOf(item) == -1) { this.results.push(item); digest(); console.info('change', this.results); } if (queue.length) this.runningSearch = setTimeout(process, 0); }; process(); // on end: this.isLoading = false; } open (note) { // console.log(note); this.openNotes.open(note); } }
JavaScript
class TypeWriter { constructor(txtElement, words, wait = 1000) { this.txtElement = txtElement; this.words = words; this.txt = ''; this.wordIndex = 0; this.wait = parseInt(wait, 10); this.type(); this.isDeleting = false; } type() { const current = this.wordIndex % this.words.length; const fullTxt = this.words[current]; if(this.isDeleting) { this.txt = fullTxt.substring(0, this.txt.length - 1); } else { this.txt = fullTxt.substring(0, this.txt.length + 1); } this.txtElement.innerHTML = `<span class="txt">${this.txt}</span>`; let typeSpeed = 200; if(this.isDeleting) { typeSpeed /= 2; } if(!this.isDeleting && this.txt === fullTxt) { typeSpeed = this.wait; this.isDeleting = true; } else if(this.isDeleting && this.txt === '') { this.isDeleting = false; this.wordIndex++; typeSpeed = 600; } setTimeout(() => this.type(), typeSpeed); } }
JavaScript
class Form extends Component { /** * @type {Object} * @property {Array<HTMLOptionElement>} children - Elements to show inside the form * @property {String} action - The form action attribute * @property {Function} onSubmit - Triggers when the user submits a valid form * @property {Function} [onCancel] - Triggers when the user clicks the cancel button * @property {String} [method='GET'] - The method to use when submitting the form */ static propTypes = { children: PropTypes.array.isRequired, action: PropTypes.string.isRequired, onSubmit: PropTypes.func.isRequired, onCancel: PropTypes.func, method: PropTypes.string, }; /** * @ignore */ static defaultProps = { children: [], method: 'GET', }; /** * @ignore */ constructor(props) { super(props); /** * @ignore */ this.instances = {}; } /** * @ignore */ componentWillMount() { /** * @ignore */ this.children = this.props.children.map(el => React.cloneElement(el, { key: el.props.id || Math.random().toString(36).slice(-8), ref: this.addChildInstance.bind(this, el), })); } /** * @ignore */ addChildInstance(el, instance) { if (el.props.id && typeof el.type !== 'string') { this.instances[el.props.id] = instance; } } /** * @ignore */ onSubmit(e) { e.preventDefault(); const invalidFields = Object.keys(this.instances).filter((key) => { const component = this.instances[key]; component.validate(); return !component.isValid; }); const { onSubmit } = this.props; if (onSubmit && !invalidFields.length) { onSubmit(e); } } onCancel() { const { onCancel } = this.props; if (onCancel) { onCancel(); } } /** * @ignore */ render() { const { action, method } = this.props; return ( <form action={action} method={method} onSubmit={e => this.onSubmit(e)} noValidate> {this.children} <div className='buttonGroup'> <button className='button button--secondary' type='button' onClick={() => this.onCancel()}>Cancel</button> <button className='button' type='submit'>Save</button> </div> </form> ); } }
JavaScript
class FsCache { constructor(projectId, workspaceId, cacheType, requestor) { this.projectId = projectId; this.workspaceId = workspaceId; this.cacheType = cacheType; this.keyBase = `workspace:${this.workspaceId}:${this.cacheType}:`; this.client = redis(); this.requestor = requestor; this.existsVal = undefined; this.isCurrentVal = undefined; this.workspaceName = setupVal(this, 'workspace_name', { keyPrefix: this.keyBase, }); this.manifest = setupVal(this, 'manifest', { json: true, keyPrefix: this.keyBase, }); this.entry = setupVal(this, 'entry', { json: true, keyPrefix: this.keyBase, }); this.timestamp = setupVal(this, 'timestamp', { parse: result => new Date(result), keyPrefix: this.keyBase, }); this.fsData = setupVal(this, 'data', { json: true, keyPrefix: this.keyBase, }); if (config.get('disableFsCache')) { this.isCurrentVal = false; } } isCurrent() { // TODO isCurrent should be cleaned up if (this.isCurrentVal === undefined) { return this.exists().then((exists) => { if (exists) { const url = `/projects/${this.projectId}/workspaces/${this.workspaceId}`; return Promise.all([ this.requestor.request(url), this.timestamp(), ]).then(([workspace, fsTimestamp]) => { const workspaceUpdateDateTime = new Date(workspace.update_date_time); this.isCurrentVal = fsTimestamp > workspaceUpdateDateTime; return this.isCurrentVal; }); } return false; }); } return Promise.resolve(this.isCurrentVal); } exists() { // TODO exists should be cleaned up. if (this.existsVal === undefined || this.existsVal === false) { return this.client.exists(`${this.keyBase}timestamp`).then((exists) => { this.existsVal = exists === 1; return this.existsVal; }); } return Promise.resolve(this.existsVal); } cacheFs(workspaceName, manifest, data, entry = null) { // TODO: Pipeline this redis work this.client.set(`${this.keyBase}workspace_name`, workspaceName, 'EX', expireation); this.client.set(`${this.keyBase}data`, JSON.stringify(data), 'EX', expireation); this.client.set(`${this.keyBase}manifest`, JSON.stringify(manifest), 'EX', expireation); if (entry !== null) { this.client.set(`${this.keyBase}entry`, JSON.stringify(entry), 'EX', expireation); } this.client.set(`${this.keyBase}timestamp`, new Date().toISOString(), 'EX', expireation); } renew() { this.client.expire(`${this.keyBase}workspace_name`, expireation); this.client.expire(`${this.keyBase}data`, expireation); this.client.expire(`${this.keyBase}manifest`, expireation); this.client.expire(`${this.keyBase}entry`, expireation); this.client.expire(`${this.keyBase}timestamp`, expireation); } }
JavaScript
class Galil extends EventEmitter { constructor() { super(...arguments); this._connected = false; this._commands = new Socket(); this._messages = new Socket(); this._interrupts = new Socket(); this._messages .on('connect', () => this._messages.send('CF I', 5000)) .on('data', data => this.emit('message', data)); Array.from(this.sockets.values()).forEach(socket => { socket.on('close', () => this.emit('close', socket)); }); } get commands() { return this._commands; } get messages() { return this._messages; } get interrupts() { return this._interrupts; } get sockets() { return new Map([ [ "commands", this._commands ], [ "messages", this._messages ], ]); } /** * Connect to the galil device. * All sockets will be connected, after which, a "connect" event will be fired. * * @function Galil#connect * @param {Number} port the port to connect to * @param {String} host the host to connect to * @emits connect when successful connection has been established. * @emits error when an error in connection occurs. * @returns {Promise} * @example * > galil * .once('connect', () => console.log('All sockets connected.')) * .once('error', err => console.warn(err)) * .connect(23, '192.168.1.4') * .then(() => console.log('What now?')) * * All sockets connected! * What now? */ connect() { return Bluebird.map(this.sockets.entries(), entry => { const [ name, socket ] = entry; return socket.connectAsync(...arguments); }) .then(() => this.emit('connect')) .catch(err => this.emit('error', err)) } /** * Disconnects from the controller * Stops all attempts at reconnecting. * * @function Galil#disconnect * @emits disconnect when disconnect is successful */ disconnect() { return Bluebird.map(this.sockets.entries(), entry => { return new Bluebird((resolve, reject) => { const [ name, socket ] = entry; socket.stopReconnecting(); socket.once('close', resolve) socket.end(); socket.destroy(); }); }).then(() => this.emit('disconnect')); } /** * Sends a command to the controller. * @function Galil#sendCommand * @param {String} command the command to send * @param {Number} [timeout=5000] the time to wait before throwing an error * @return {[String]} array of strings */ async sendCommand(command, timeout=5000) { return await this.commands.send(command, timeout); } }
JavaScript
class Constants extends Plugins.interfaces.Processor { constructor() { super(); } /** * @inheritDoc */ set configuration(configuration) { if (configuration.mdc && !_.isObject(configuration.mdc)) { throw new Error('Constants have been misconfigured: "mdc" needs to be an object'); } if (configuration.mdc && !_.isArray(configuration.mdc)) { throw new Error('Constants have been misconfigured: "params" needs to be an array'); } this.mdc = configuration.mdc; this.params = configuration.params; } /** * @inheritDoc */ process(events, done) { for(let event of events) { if (this.mdc) { for (let entry in this.mdc) { event.mdc.set(entry, this.mdc[entry]); } } if (this.params) { for (let param of this.params) { event.param(param); } } } done(events); } }
JavaScript
class PrefixMapUriResolver { constructor(definitions) { this.definitions = definitions; } resolveUri(uri) { return Object.keys(this.definitions).reduce((r, key) => { if (key.endsWith("/") && r.startsWith(key)) { const newPrefix = this.definitions[key]; return newPrefix + r.substr(key.length); } else if (r === key) { return this.definitions[key]; } return r; }, uri); } }
JavaScript
class RelativeUriResolver { constructor(parentUri) { this.parentUri = parentUri; } resolveUri(uri) { return UrlUtils_1.resolveReferenceUri(this.parentUri, uri); } }
JavaScript
class ContainerNode extends IsmlNode { constructor(lineNumber, globalPos) { super(); this.head = '(Container node)'; this.lineNumber = lineNumber; this.globalPos = globalPos; } isContainer() { return true; } addChild(clause) { clause.depth = this.depth; clause.parent = this; clause.childNo = this.children.length; this.newestChildNode = clause; this.children.push(clause); } print() { for (let i = 0; i < this.children.length; i++) { this.children[i].print(); } } }
JavaScript
class Number extends _Text_mjs__WEBPACK_IMPORTED_MODULE_3__["default"] { static getStaticConfig() {return { /** * Valid values for triggerPosition * @member {String[]} triggerPositions=['right', 'sides'] * @protected * @static */ triggerPositions: ['right', 'sides'] }} static getConfig() {return { /** * @member {String} className='Neo.form.field.Number' * @protected */ className: 'Neo.form.field.Number', /** * @member {String} ntype='numberfield' * @protected */ ntype: 'numberfield', /** * @member {Array} cls=['neo-numberfield', 'neo-textfield'] */ cls: ['neo-numberfield', 'neo-textfield'], /** * @member {Number[]|null} excluded=null */ excludedValues: null, /** * false only allows changing the field using the spin buttons * @member {Boolean} inputEditable_=true */ inputEditable_: true, /** * Value for the inputType_ textfield config * @member {String} inputType='number' */ inputType: 'number', /** * @member {Number} maxValue_=100 */ maxValue_: 100, /** * @member {Number} minValue_=0 */ minValue_: 0, /** * @member {Number} stepSize_=1 */ stepSize_: 1, /** * Valid values: 'right', 'sides' * @member {String} triggerPosition='right' */ triggerPosition_: 'right', /** * @member {Boolean} useSpinButtons_=true */ useSpinButtons_: true }} /** * Triggered after the inputEditable config got changed * @param {Number} value * @param {Number} oldValue * @protected */ afterSetInputEditable(value, oldValue) { let me = this, vdom = me.vdom, inputEl = me.getInputEl(), style = inputEl.style || {}; if (value) { delete style.pointerEvents; } else { style.pointerEvents = 'none'; } me.vdom = vdom; } /** * Triggered after the maxValue config got changed * @param {Number} value * @param {Number} oldValue * @protected */ afterSetMaxValue(value, oldValue) { this.changeInputElKey('max', value); } /** * Triggered after the minValue config got changed * @param {Number} value * @param {Number} oldValue * @protected */ afterSetMinValue(value, oldValue) { this.changeInputElKey('min', value); } /** * Triggered after the stepSize config got changed * @param {Number} value * @param {Number} oldValue * @protected */ afterSetStepSize(value, oldValue) { let me = this, val = me.value, modulo; me.changeInputElKey('step', value); if (val !== null) { modulo = (val - me.minValue) % value; if (modulo !== 0) { // find the closest valid value if (modulo / value > 0.5) { if (val + value - modulo < me.maxValue) {me.value = val + value - modulo;} else if (val - modulo > me.minValue) {me.value = val - modulo;} } else { if (val - modulo > me.minValue) {me.value = val - modulo;} else if (val + value - modulo < me.maxValue) {me.value = val + value - modulo;} } } } } /** * Triggered after the triggerPosition config got changed * @param {String} value * @param {String} oldValue * @protected */ afterSetTriggerPosition(value, oldValue) { if (oldValue) { this.updateTriggers(); } } /** * Triggered after the useSpinButtons config got changed * @param {Boolean} value * @param {Boolean} oldValue * @protected */ afterSetUseSpinButtons(value, oldValue) { if (typeof oldValue === 'boolean') { this.updateTriggers(); } } /** * Triggered before the triggerPosition config gets changed * @param {String} value * @param {String} oldValue * @protected */ beforeSetTriggerPosition(value, oldValue) { return this.beforeSetEnumValue(value, oldValue, 'triggerPosition'); } /** * */ onConstructed() { this.updateTriggers(); super.onConstructed(); } /** * @param {Object} data * @override */ onInputValueChange(data) { let me = this, value = data.value, oldValue = me.value; if (!value && !me.required) { super.onInputValueChange(data); } else { value = parseInt(value); // todo: support for other number types if (!Neo.isNumber(value)) { me._value = oldValue; } else { value = value - value % me.stepSize; value = Math.max(me.minValue, value); value = Math.min(me.maxValue, value); data.value = value; super.onInputValueChange(data); } } } /** * @protected */ onSpinButtonDownClick() { let me = this, oldValue = me.value || (me.maxValue + me.stepSize), value = Math.max(me.minValue, oldValue - me.stepSize); if (me.excludedValues) { while(me.excludedValues.includes(value)) { value = Math.max(me.minValue, value - me.stepSize); } } if (oldValue !== value) { me.value = value; } } /** * @protected */ onSpinButtonUpClick() { let me = this, oldValue = me.value || (me.minValue - me.stepSize), value = Math.min(me.maxValue, oldValue + me.stepSize); if (me.excludedValues) { while(me.excludedValues.includes(value)) { value = Math.min(me.maxValue, value + me.stepSize); } } if (oldValue !== value) { me.value = value; } } /** * */ updateTriggers() { let me = this, triggers = me.triggers || []; if (me.useSpinButtons) { if (me.triggerPosition === 'right') { if (!me.hasTrigger('spinupdown')) { triggers.push(_trigger_SpinUpDown_mjs__WEBPACK_IMPORTED_MODULE_2__["default"]); } me.removeTrigger('spindown', true, triggers); me.removeTrigger('spinup', true, triggers); } else { if (!me.hasTrigger('spindown')) { triggers.push(_trigger_SpinDown_mjs__WEBPACK_IMPORTED_MODULE_0__["default"]); } if (!me.hasTrigger('spinup')) { triggers.push(_trigger_SpinUp_mjs__WEBPACK_IMPORTED_MODULE_1__["default"]); } me.removeTrigger('spinupdown', true, triggers); } } else { me.removeTrigger('spindown', true, triggers); me.removeTrigger('spinup', true, triggers); me.removeTrigger('spinupdown', true, triggers); } me.triggers = triggers; } }
JavaScript
class SpinDown extends _Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { static getConfig() {return { /** * @member {String} className='Neo.form.field.trigger.SpinUp' * @protected */ className: 'Neo.form.field.trigger.SpinDown', /** * @member {String} ntype='trigger-spindown' * @protected */ ntype: 'trigger-spindown', /** * @member {String} align_='start' */ align: 'start', /** * @member {String|null} iconCls='fa fa-chevron-left' */ iconCls: 'fa fa-chevron-left', /** * Internal flag used by field.getTrigger() * @member {String} type='spindown' * @protected */ type: 'spindown' }} /** * @param {Object} data */ onTriggerClick(data) { this.field.onSpinButtonDownClick(); } }
JavaScript
class SpinUp extends _Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { static getConfig() {return { /** * @member {String} className='Neo.form.field.trigger.SpinUp' * @protected */ className: 'Neo.form.field.trigger.SpinUp', /** * @member {String} ntype='trigger-spinup' * @protected */ ntype: 'trigger-spinup', /** * @member {String|null} iconCls='fa fa-chevron-right' */ iconCls: 'fa fa-chevron-right', /** * Internal flag used by field.getTrigger() * @member {String} type='spinup' * @protected */ type: 'spinup' }} /** * @param {Object} data */ onTriggerClick(data) { this.field.onSpinButtonUpClick(); } }
JavaScript
class SpinUpDown extends _Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { static getConfig() {return { /** * @member {String} className='Neo.form.field.trigger.SpinUpDown' * @protected */ className: 'Neo.form.field.trigger.SpinUpDown', /** * @member {String} ntype='trigger-spinupdown' * @protected */ ntype: 'trigger-spinupdown', /** * @member {String[]} cls=['neo-field-trigger', 'neo-spin-buttons'] */ cls: ['neo-field-trigger', 'neo-spin-buttons'], /** * @member {String} spinButtonDownIconCls='fa fa-chevron-down' */ spinButtonDownIconCls: 'fa fa-chevron-down', /** * @member {String} spinButtonUpIconCls='fa fa-chevron-up' */ spinButtonUpIconCls: 'fa fa-chevron-up', /** * Internal flag used by field.getTrigger() * @member {String} type='spinupdown' * @protected */ type: 'spinupdown' }} /** * */ onConstructed() { let me = this, vdom = me.vdom; vdom.cn = [ {cls: ['neo-spin-button', 'neo-up', me.spinButtonUpIconCls]}, {cls: ['neo-spin-button', 'neo-down', me.spinButtonDownIconCls]} ]; me.vdom = vdom; super.onConstructed(); } /** * @param {Object} data */ onTriggerClick(data) { let me = this, target = data.path[0], cls = target.cls.join(' '); if (cls.includes('neo-down')) { me.field.onSpinButtonDownClick(); } else if (cls.includes('neo-up')) { me.field.onSpinButtonUpClick(); } } }
JavaScript
class VigenereCipheringMachine { constructor(isDirect = true) { this.type = isDirect this.abc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] } encrypt(str, key) { console.log(str,key) if(typeof(str)!=='string'||typeof(key)!=='string') throw new Error('Incorrect arguments!'||arguments.length===0) let strArr = str.split(' ') let keyArr = [] let keyWord = key.toLowerCase().split('') let result = '' for (let i = 0; i < strArr.length; i++) { let word = strArr[i] let strKey = '' for (let j = 0; j < word.length; j++) { let letter = word[j] if ((/[a-z]/gi).test(letter)) { let keyLetter = keyWord.shift() strKey += keyLetter keyWord.push(keyLetter) } else { strKey += letter } } keyArr.push(strKey) } let keyStr = keyArr.join(' ') for (let i = 0; i < str.length; i++) { let letterStr = str[i].toLowerCase() let letterKey = keyStr[i].toLowerCase() if ((/[a-z]/gi).test(letterStr)) { let letterCode = this.abc.findIndex(el => el === letterStr) + this.abc.findIndex(el => el === letterKey) let index = letterCode >= 26 ? letterCode - 26 : letterCode result += this.abc[index] } else { result += letterStr } } return this.type?(result.toUpperCase()):(result.toUpperCase().split('').reverse().join('')) } decrypt(str, key) { console.log(str,key) if(typeof(str)!=='string'||typeof(key)!=='string'||arguments.length===0) throw new Error('Incorrect arguments!') let strArr = str.split(' ') let keyArr = [] let keyWord = key.toLowerCase().split('') let result = '' for (let i = 0; i < strArr.length; i++) { let word = strArr[i] let strKey = '' for (let j = 0; j < word.length; j++) { let letter = word[j].toLowerCase() if ((/[a-z]/gi).test(letter)) { let keyLetter = keyWord.shift() strKey += keyLetter keyWord.push(keyLetter) } else { strKey += letter } } keyArr.push(strKey) } let keyStr = keyArr.join(' ') for (let i = 0; i < str.length; i++) { let letterStr = str[i].toLowerCase() let letterKey = keyStr[i].toLowerCase() if ((/[a-z]/gi).test(letterStr)) { let letterCode = this.abc.findIndex(el => el === letterStr) - this.abc.findIndex(el => el === letterKey) let index = letterCode < 0 ? (26 - Math.abs(letterCode)) : letterCode result += this.abc[index] } else { result += letterStr } } return this.type?(result.toUpperCase()):(result.toUpperCase().split('').reverse().join('')) } }
JavaScript
class TablePage extends React.Component { state = { data: [], dataSource: [], endData:false, pagination: { total: 0, current: 0 }, loading: null, modalOpen: false, modalData: {}, repositiories: [], formUser: null, formRep: null, }; showModal = (record) => { this.setState({ ...this.state, modalOpen: true, }); }; handleOk = (e, some) => { console.log(e); this.setState({ ...this.state, modalOpen: false, }); }; handleCancel = (e) => { console.log(e); this.setState({ ...this.state, modalOpen: false, }); }; constructor(props) { super(props); this.columns = this.props.columns; } changeRecord (text, record, index) { this.setState({ ...this.state, modalData: record, }, () => { this.showModal(record); }); } componentDidMount() { this.columns.push( { title: 'Open', dataIndex: 'rec', sorter: false, render: (text, record, index) => <div><a onClick={this.changeRecord.bind(this, text, record, index)}>Change {text}</a></div>, width: '20%', } ); } handlerUserName(e) { const value = e.target.value; this.setState({ ...this.state, formUser: value }); api.get('getRepos', { params: { user: value }, responseType: 'json' }).then((res) => { this.setState({ ...this.state, repositiories: res.data, }); }).catch((err) => { console.log(err) }); } handleChangeRep(value) { this.setState({ ...this.state, formRep: value }, () => { this.doRequest(); }); } doRequest (params) { this.setState({ loading: true, }); if (this.state.formUser && this.state.formRep) { const pagination = this.state.pagination; api.get('getIssues', { params: { user: this.state.formUser, rep: this.state.formRep, current: 0, limit: 50, ...params, }, responseType: 'json' }).then((res) => { const new_data = this.state.dataSource ? this.state.dataSource.concat(res.data.items) : res.data.items; if (res.data.items.length > 0 || res.data.items.length > 10) { pagination.total = new_data.length + 10 } else { pagination.total = new_data.length } this.setState({ loading: false, data: res.data, dataSource: new_data, endData: res.data.items.length === 0, pagination, }); }).catch((err) => { console.log(err) }); } } handleTableChange = (pagination, filters, sorter, page) => { const pager = this.state.pagination; pager.current = pagination.current; this.setState({ ...this.state, pagination: pager, }); if (Math.ceil(pagination.total / pagination.pageSize) === pagination.current && !this.state.endData) { this.doRequest({ results: pagination.pageSize, page: pagination.current, sortField: sorter.field, sortOrder: sorter.order, current: pagination.total, limit: pagination.total + 50, ...filters, }); } } render() { const columns = this.columns; const {dataSource, pagination, loading} = this.state; const {err, noData} = this.props.table; noData ? console.log(err) : null; return ( <PanelBox title="Table Page"> <div className="header-search" style={{ display: 'flex', justifyContent: 'space-between', paddingBottom: 25}}> <Input type="text" //value={state.number} //onChange={this.handleNumberChange} placeholder="Username here" style={{ width: '30%', marginRight: '3%'}} onBlur={this.handlerUserName.bind(this)} /> <Select //value={state.currency} //size={size} onChange={this.handleChangeRep.bind(this)} showSearch placeholder="Repository here" optionFilterProp="children" filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} style={{ width: '30%', marginRight: '3%'}} //onChange={this.handleCurrencyChange} > { this.state.repositiories.length !== 0 ? this.state.repositiories.map( (item, i) => { return ( <Option value={item.name} key = {i}>{item.name}</Option> ) }) : null } </Select> <Button style={{ width: '17%' }} type="primary" onClick={this.doRequest.bind(this, this.state.url)}>Search</Button> </div> { !loading ? <Table columns={columns} rowKey={record => record.registered} dataSource={dataSource} pagination={pagination} loading={loading} onChange={this.handleTableChange} /> : null } { loading ? <Spin tip="Loading..." /> : null } { noData ? <div style={{textAlign: 'center', maxWidth: 480, margin: '25 auto 0'}}> <Icon style={{ fontSize: 28, marginBottom: 15}} type="exclamation-circle" /> <h4>Что то пошло не так, попробуйте перезагрузить страницу или повторить попытку позднее</h4> </div> : null } <Modal title="Change redord" visible={this.state.modalOpen} //onOk={this.handleOk} onCancel={this.handleCancel} footer={[]} width = {720} > {/*non form-redux*/} {this.state.modalOpen ? <RenderModal modalInner={this.props.modalInner} modalData={this.state.modalData} func={{ onCancel: this.handleCancel.bind(this), onOk: this.handleOk.bind(this), }} /> : null} </Modal> </PanelBox> ); } }
JavaScript
class FileManager { /** * On instantiation we want to authenticate to AWS and specify our user and root folder * * @param string userId - User identifier */ constructor(userId) { AWS.config.update({ region: appConfig.aws.region, credentials: appConfig.aws.credentials }) this.userId = userId this.root = 'user_files/' + this.userId + '/' } /** * Generate a policy for the logged in user and use it to retrieve custom temporary * credentials from AWS STS * * @returns {Promise} */ getCredentials() { const self = this return new Promise((resolve, reject) => { const sts = new AWS.STS() sts.getFederationToken( { Name: self.userId, Policy: JSON.stringify({ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowListingContentsOfUserFolder", "Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": [`arn:aws:s3:::${appConfig.aws.bucket}`], "Condition": { "StringLike": { "s3:prefix": [`${self.root}*`], "s3:delimiter": ['/'] } } }, { "Sid": "AllowActionsWithinUserFolder", "Effect": "Allow", "Action": ["s3:GetObject", "s3:DeleteObject", "s3:PutObject"], "Resource": [`arn:aws:s3:::${appConfig.aws.bucket}/*`] } ] }) }, (err, credentials) => { if (err) reject(err) const config = { credentials: { accessKeyId: credentials.Credentials.AccessKeyId, secretAccessKey: credentials.Credentials.SecretAccessKey, sessionToken: credentials.Credentials.SessionToken }, region: appConfig.aws.region, listParams: { Bucket: appConfig.aws.bucket, Prefix: this.root, Delimiter: '/' }, uploadParams: { Bucket: appConfig.aws.bucket, Key: this.root, ServerSideEncryption: 'AES256' }, deleteParams: { Bucket: appConfig.aws.bucket, Key: '' } } resolve(config) } ) }) } }
JavaScript
class webxr { /** * Setup regular use session. * * @param canvas Canvas The element to use * @param callback function Callback to call for every frame * @param options {} Settings to use to setup the AR session * @param setup function Allows to execute setup functions for session * @returns {Promise} */ startSession(canvas, callback, options, setup = () => {}) { frameCallback = callback; return navigator.xr.requestSession('immersive-ar', options) .then((result) => { this._initSession(canvas, result); setup(this, result, gl); }) } /** * Setup specific session for marker handling. * * @param canvas Canvas The element to use * @param callback function Callback to call for every frame * @param options {} Settings to use to setup the AR session * @returns {Promise} */ startMarkerSession(canvas, callback, options) { markerFrameCallback = callback; return navigator.xr.requestSession('immersive-ar', options) .then((result) => { this._initSession(canvas, result); return this.session.getTrackedImageScores(); }) .then(scores => { // Simplified handling for a single marker image if (scores.length > 0) { // When marker image provided by user or server, inform user that marker can't be tracked console.log('Marker score: ', scores[0]); } }); } /** * Set the default viewport of the WebGL context. */ setViewPort() { gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); } /** * Set the viewport according to provided view. * * @param view XRView The view to make the settings for * @returns {XRViewport} */ setViewportForView(view) { const viewport = this.session.renderState.baseLayer.getViewport(view); if (viewport) { gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); // For an application working in viewport space, get the camera intrinsics // based on the viewport dimensions: getCameraIntrinsics(view.projectionMatrix, viewport); } else { this.setViewPort() } return viewport; } initCameraCapture(gl) { initCameraCaptureScene(gl); } /** * Current best effort to get the camera image from the WebXR session. * * The implementation has recently changed in Chromium. Will adapt when available for Chrome (beta). * * @param frame XRFrame The current frame to get the image for * @param view XRView The view to use * @returns {WebGLTexture} */ getCameraTexture(frame, view) { // NOTE: if we do not draw anything on pose update for more than 5 frames, Chrome's WebXR sends warnings // See OnFrameEnd() in https://chromium.googlesource.com/chromium/src/third_party/+/master/blink/renderer/modules/xr/xr_webgl_layer.cc // We want to capture the camera image, however, it is not directly available here, // but only as a GPU texture. We draw something textured with the camera image at every frame, // so that the texture is kept in GPU memory. We can then capture it below. const cameraTexture = this.glBinding.getCameraImage(frame, view); drawCameraCaptureScene(gl, cameraTexture); checkGLError(gl, "getCameraTexture() end"); return cameraTexture; } // NOTE: since Chrome update in June 2021, the getCameraImage(frame, view) method is not available anymore // Instead we can call getCameraImage(XRCamera) // See https://source.chromium.org/chromium/chromium/src/+/master:third_party/webxr_test_pages/webxr-samples/proposals/camera-access-barebones.html;bpv=0 /** * Get camera image as a texture from the WebXR session. * We want to capture the camera image, however, it is not directly available here, * but only as a GPU texture. We draw something textured with the camera image at every frame, * so that the texture is kept in GPU memory. We can then capture it below. * * @param camera XRCamera The camera of the XR session * @returns {WebGLTexture} */ getCameraTexture2(view) { // For an application working in camera texture space, get the camera // intrinsics based on the camera texture width/height which may be // different from the XR framebuffer width/height. // // Note that the camera texture has origin at bottom left, and the // returned intrinsics are based on that convention. If a library // has a different coordinate convention, the coordinates would // need to be adjusted, for example mirroring the Y coordinate if // the origin needs to be at the top left. const cameraViewport = { width: view.camera.width, height: view.camera.height, x: 0, y: 0 }; getCameraIntrinsics(view.projectionMatrix, cameraViewport); const cameraTexture = this.glBinding.getCameraImage(view.camera); // NOTE: if we do not draw anything on pose update for more than 5 frames, Chrome's WebXR sends warnings // See OnFrameEnd() in https://chromium.googlesource.com/chromium/src/third_party/+/master/blink/renderer/modules/xr/xr_webgl_layer.cc drawCameraCaptureScene(gl, cameraTexture); checkGLError(gl, "getCameraTexture2() end"); return cameraTexture; } /** * Convert WebGL texture to actual image to use for localisation. * * The implementation for camera access has recently changed in Chromium. Will adapt when available for Chrome (beta). * * @param texture WebGLTexture The texture to convert * @param width Number Width of the texture * @param height Number Height of the texture * @returns {string} base64 encoded image */ getCameraImageFromTexture(texture, width, height) { return createImageFromTexture(gl, texture, width, height); } /** * End provided session. * * @param session XRSession The session to end */ onEndSession(session) { session.end(); } /** * Set callbacks that should be called for certain situations. * * @param ended function The function to call when session ends * @param noPose function The function to call when no pose was reported for experiment mode */ setCallbacks(ended, noPose) { endedCallback = ended; noExperimentResultCallback = noPose; } /** * Handler for session ended event. Used to clean up allocated memory and handler. */ onSessionEnded() { this.session = null; gl = null; if (endedCallback) { endedCallback(); } } /** * Create anchor for origin point of WebXR coordinate system to fix the 3D engine to it. * * @param frame XRFrame The current frame to base the anchor on * @param rootUpdater function Callback into the 3D engine to adopt changes when anchor is moved */ createRootAnchor(frame, rootUpdater) { frame.createAnchor(new XRRigidTransform(), floorSpaceReference) .then((anchor) => { anchor.context = {rootUpdater: rootUpdater}; return anchor; }) .catch((error) => { console.error("Anchor failed to create: ", error); }); } /** * Check if anchor has moved and trigger 3D engine to adapt to this change. * * Handles a single anchor right now. Needs to be extended when more anchors are used. * * @param frame XRFrame The current frame to get the image for */ handleAnchors(frame) { frame.trackedAnchors.forEach(anchor => { const anchorPose = frame.getPose(anchor.anchorSpace, floorSpaceReference); if (anchorPose) { anchor.context.rootUpdater(anchorPose.transform.matrix); } }); } /** * @private * Initializes a new session. * * @param canvas Canvas The canvas element to use * @param result XRSession The session created by caller */ _initSession(canvas, result) { this.session = result; onFrameUpdate = this._onFrameUpdate; gl = canvas.getContext('webgl2', { xrCompatible: true }); this.session.addEventListener('end', this.onSessionEnded); this.session.updateRenderState({ baseLayer: new XRWebGLLayer(this.session, gl) }); Promise.all( [this.session.requestReferenceSpace('local-floor'), this.session.requestReferenceSpace('local')]) .then((values => { floorSpaceReference = values[0]; localSpaceReference = values[1]; this.session.requestAnimationFrame(this._onFrameUpdate); })); } /** * @private * Animation loop for WebXR. * * @param time DOMHighResTimeStamp indicates the time at which the frame was scheduled for rendering * @param frame XRFrame The frame to handle */ _onFrameUpdate(time, frame) { const session = frame.session; session.requestAnimationFrame(onFrameUpdate); gl.bindFramebuffer(gl.FRAMEBUFFER, session.renderState.baseLayer.framebuffer); const floorPose = frame.getViewerPose(floorSpaceReference); if (floorPose) { if (frameCallback) { frameCallback(time, frame, floorPose, floorSpaceReference); } if (markerFrameCallback) { const results = frame.getImageTrackingResults(); if (results.length > 0) { const localPose = frame.getPose(results[0].imageSpace, floorSpaceReference); markerFrameCallback(time, frame, floorPose, localPose, results[0]); } } } } }
JavaScript
class ConnectivityManager extends RcModule { /** * @constructor * @param {Object} params - params object * @param {Alert} params.alert - alert module instance * @param {Client} params.client - client module instance * @param {Environment} params.environment - environment module instance * @param {Number} params.timeToRetry - time to Retry * @param {Number} params.heartBeatInterval - heart beat interval * @param {Function} params.checkConnectionFunc - function to check network */ constructor({ auth, oAuth, alert, callingSettings, audioSettings, webphone, connectivityMonitor, availabilityMonitor, ...options }) { super({ ...options, actionTypes, }); this._auth = auth; this._oAuth = oAuth; this._callingSettings = callingSettings; this._audioSettings = audioSettings; this._webphone = webphone; this._availabilityMonitor = availabilityMonitor; this._alert = alert; this._connectivityMonitor = connectivityMonitor; this._reducer = getConnectivityMangerReducer(this.actionTypes); this._oldConnectivityType = ''; } async _onStateChange() { if (this._shouldInit()) { this.store.dispatch({ type: this.actionTypes.initSuccess, }); } else if ( this.ready && this.connectivityType !== this._oldConnectivityType ) { this._oldConnectivityType = this.connectivityType; this.showConnectivityAlert(); } } initialize() { this.store.subscribe(() => this._onStateChange()); } _shouldInit() { return ( (!this._callingSettings || this._callingSettings.ready) && (!this._audioSettings || this._audioSettings.ready) && (!this._webphone || this._webphone.ready) && (!this._availabilityMonitor || this._availabilityMonitor.ready) && this.pending ); } @proxify checkWebphoneAndConnect() { if ( !this._callingSettings || !this._callingSettings.ready || !this._callingSettings.isWebphoneMode ) { return; } if (this._audioSettings && this._audioSettings.ready) { this._audioSettings.showAlert(); this._audioSettings.getUserMedia(); } if (this._webphone && this._webphone.ready) { this._webphone.connect({ force: true, skipConnectDelay: true }); } } @proxify checkStatus() { if (!this._availabilityMonitor) { return; } this._availabilityMonitor.healthCheck(); } _showAlert(message) { if (message) { this._alert.danger({ message, allowDuplicates: false, }); } } _hideAlerts() { const alertIds = this._alert.messages .filter((m) => { for (const type in connectivityTypes) { if (m.message === connectivityTypes[type]) return true; } return false; }) .map((m) => m.id); if (alertIds.length) { this._alert.dismiss(alertIds); } } @proxify showConnectivityAlert() { if ( !this.connectivityType || this.connectivityType === connectivityTypes.webphoneUnavailable ) { this._hideAlerts(); } else { this._showAlert(this.connectivityType); } } get status() { return this.state.status; } get ready() { return this.state.status === moduleStatuses.ready; } get pending() { return this.state.status === moduleStatuses.pending; } get webphoneAvailable() { return ( this._webphone && this._callingSettings && this._audioSettings && this._audioSettings.ready && this._callingSettings.ready && this._auth.ready && this._auth.loggedIn && this._callingSettings.isWebphoneMode && this._audioSettings.userMedia && this._webphone.connected ); } get isWebphoneInitializing() { return ( this._callingSettings.isWebphoneMode && (!this._webphone.ready || this._webphone.disconnected || this._webphone.connecting || this._webphone.connectFailed) ); } get webphoneConnecting() { return ( this._webphone && this._webphone.ready && (this._webphone.connecting || this._webphone.reconnecting) ); } get webphoneUnavailable() { return ( this._webphone && this._callingSettings && this._audioSettings && this._audioSettings.ready && this._auth.ready && this._auth.loggedIn && this._callingSettings.isWebphoneMode && (!this._audioSettings.userMedia || (this._webphone.reconnecting || this._webphone.connectError || this._webphone.inactive)) ); } get proxyRetryCount() { return this._oAuth && this._oAuth.proxyRetryCount > 0; } get isVoIPOnlyModeActivated() { return ( !!this._availabilityMonitor && this._availabilityMonitor.isVoIPOnlyMode ); } get isLimitedModeActivated() { return ( !!this._availabilityMonitor && this._availabilityMonitor.isLimitedMode ); } get hasLimitedStatusError() { return ( !!this._availabilityMonitor && this._availabilityMonitor.hasLimitedStatusError ); } @selector connectivityType = [ () => this._connectivityMonitor.networkLoss, () => this._connectivityMonitor.connectivity, () => this.proxyRetryCount, () => this.isVoIPOnlyModeActivated, () => this.isLimitedModeActivated, () => this.webphoneAvailable, () => this.webphoneUnavailable, ( networkLoss, connectivity, proxyRetryCount, isVoIPOnlyModeActivated, isLimitedModeActivated, webphoneAvailable, webphoneUnavailable, ) => { if (networkLoss) return connectivityTypes.networkLoss; if (proxyRetryCount) return connectivityTypes.offline; if (!connectivity) return connectivityTypes.offline; if (isVoIPOnlyModeActivated) { if (webphoneAvailable) return connectivityTypes.voipOnly; return connectivityTypes.serverUnavailable; } if (webphoneUnavailable) return connectivityTypes.webphoneUnavailable; if (isLimitedModeActivated) return connectivityTypes.survival; return null; }, ]; @selector mode = [ () => this.connectivityType, (connectivityType) => { if ( connectivityType === connectivityTypes.networkLoss || connectivityType === connectivityTypes.serverUnavailable ) return connectivityTypes.offline; return connectivityType; }, ]; get isWebphoneUnavailableMode() { return this.mode === connectivityTypes.webphoneUnavailable; } get isOfflineMode() { return this.mode === connectivityTypes.offline; } get isVoipOnlyMode() { return this.mode === connectivityTypes.voipOnly; } }
JavaScript
class PortfolioController { static getName() { return 'PortfolioCtrl'; } static getDependencies() { return ['$rootScope', PortfolioController]; } constructor($rootScope) { this.$rootScope = $rootScope; this.init(); } init() { this.$rootScope.appData.smallScreenHeader = 'Portfolio'; this.$rootScope.appData.isLight = false; // this.$timeout(() => { // let items = $('form'); // this.velocity(items, 'transition.slideUpIn', {duration: 500, delay: 50}); // }, 0); } }
JavaScript
class CoCreateYjsCodemirror { constructor() { this.elements = []; this.codemirrors = []; this.bindings = []; this.organization_Id = config.organization_Id || 'randomOrganizationID' } _createCodeMirror(editorContainer){ const editor = CodeMirror(editorContainer, { mode: 'htmlmixed', styleActiveLine: true, scrollbarStyle: 'overlay', autoCloseTags: true, lineNumbers: true, lineWrapping: true, extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }}, foldGutter: true, gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], }); editor.setOption('element',editorContainer); this.codemirrors.push(editor); return editor; } _createBinding(type_element, editor, provider , realtime = true){ console.log(provider) let binding = new CodeMirrorBinding(type_element, editor, provider.awareness ,realtime) this.bindings.push(binding); return binding; } _initYSocket(element, editor, isInit) { const { collection, name, document_id } = crud.getAttr(element) const is_realtime = crud.isRealtimeAttr(element) if (collection && name && document_id) { const id = crdt.generateID(config.organization_Id, collection, document_id, name); crdt.createDoc(id, element); let provider = crdt.getProvider(id) let doc_type = crdt.getType(id) let binding = this._createBinding(doc_type, editor, provider, is_realtime) /*if (realtime) { let binding = this._createBinding(doc_type, editor, provider) // this.adapterDB(id, binding.awareness.doc); // CoCreate.crud.readDocument({ // collection: collection, // document_id: document_id, // metadata: { // type: 'crdt' // } // }) // new UserCursor(provider); } else { if (isInit) { const old_string = doc_type.toString() editor.setValue(old_string); if(!old_string) //cmDoc.setValue(textType.toString()) } }*/ } } init(container) { this.initElement(container); this.initSocketEvent(); } initElement(container){ const self = this; const mainContainer = container || document; let elements = mainContainer.querySelectorAll('.codemirror') if (elements.length == 0 && mainContainer.classList && mainContainer.classList.contains('codemirror')) { elements = [mainContainer]; } elements.forEach(function(element, index){ let template = element.closest('.template'); if (template) { return; } if (CoCreateObserver.getInitialized(element)) { return; } try{ let editor = self._createCodeMirror(element); self._initYSocket(element, editor, true) self.initEvent(element, editor) CoCreateObserver.setInitialized(element) self.elements.push(element) }catch(error) { return false } });//end forEach } initSocketEvent() { const self = this; // CoCreateSocket.listen('readDocument', function(data) { // if (!data.metadata || data.metadata.type != "crdt") { // return; // } // self.elements.forEach((mirror) => { // const collection = mirror.getAttribute('data-collection') // const id = mirror.getAttribute('data-document_id') // const name = mirror.getAttribute('name') // if (mirror.crudSetted === true) { // return; // } // if (data['collection'] == collection && data['document_id'] == id && (name in data.data)) { // // _this.sendChangeData(input, data['data'][name], 0, data['data'][name].length, false); // CoCreate.crdt.replaceText({ // collection: collection, // document_id: id, // name: name, // value: data['data'][name], // }) // mirror.crudSetted = true; // } // }); // }); } initEvent(element, editor) { var charWidth = editor.defaultCharWidth(), basePadding = 4; var _this = this; //comment by jean mendoza 05-11-2020, codemirror no tab in editor // editor.on("renderLine", function(cm, line, elt) { // var off = CodeMirror.countColumn(line.text, null, cm.getOption("tabSize")) * charWidth; // elt.style.textIndent = "-" + off + "px"; // elt.style.paddingLeft = (basePadding + off) + "px"; // }); editor.refresh(); editor.on('change',function(codemirror, yjs_event){ var value = codemirror.getValue(); var element = codemirror.getOption('element'); var id = element.getAttribute('id') || ''; _this.requestDocumentID(element) if (!id) return; var targets = document.querySelectorAll('[data-get_value="' + id + '"]'); var is_fold = element.dataset['is_fold'] || false; if(!is_fold){ var fold_lines = element.dataset['fold'] || ''; fold_lines = fold_lines.split(',').filter(value=>parseInt(value) -1 >= 0).map(value => value - 1); fold_lines.forEach((line) => { editor.foldCode(CodeMirror.Pos(line, 0)); element.dataset['is_fold']=true; }); } targets.forEach((target) => { if(target.nodeName == 'IFRAME'){ //tmp_target = target; let document_iframe = target.contentDocument; /* document_iframe.open(); document_iframe.write(value); document_iframe.close(); */ target.srcdoc = value; }else{ if (typeof(target.innerHTML) != "undefined") { target.innerHTML = value; }else if (typeof(target.value) != "undefined") { target.value = value; } else if (typeof(target.textContent) != "undefined") { target.textContent = value; } } }); }) element.addEventListener('set-document_id', function(event){ console.log('created document_id'); _this._initYSocket(element, editor); _this.saveDataIntoDB(element, editor.getValue()); }) element.addEventListener('clicked-submitBtn', function() { console.log('clicked save button') _this.saveDataIntoDB(element, editor.getValue()); }) } requestDocumentID(element) { const document_id = element.getAttribute('data-document_id'); const realtime = crud.isRealtimeAttr(element); if (!document_id && realtime) { CoCreateForm.request({element}) element.setAttribute('data-document_id', 'pending'); } } saveDataIntoDB(element, value) { const { collection, document_id, name } = crud.getAttr(element) crud.updateDocument({ collection, document_id, data: { [name]: value }, }) } parseTypeName(name) { const data = JSON.parse(atob(name)); return data; } }//end Class CoCreateYjsCodemirror
JavaScript
class RedemptionInfo extends BaseFormatter { /** * Constructor for redemption info formatter. * * @param {object} params * @param {object} params.redemptionInfo * * @augments BaseFormatter * * @constructor */ constructor(params) { super(); const oThis = this; oThis.redemptionInfo = params.redemptionInfo; } /** * Validate the input objects. * * @returns {result} * @private */ _validate() { const oThis = this; const redemptionInfoKeyConfig = { id: { isNullAllowed: false }, url: { isNullAllowed: false }, uts: { isNullAllowed: false } }; return oThis.validateParameters(oThis.redemptionInfo, redemptionInfoKeyConfig); } /** * Format the input object. * * @returns {result} * @private */ _format() { const oThis = this; return responseHelper.successWithData(oThis.redemptionInfo); } }
JavaScript
class UiMessageHandler extends MessageHandler { // _model; constructor(model, cluster) { super(cluster); this._model = model; } /** * Deliver messages due for delivery and remove dropped ones. * * @param model the model with the current time */ update(model) { this._model = model; this.cluster = this._model.cluster; // Update cluster in case there was a change // Remove messages that were sent or are to be received by dead servers this._removeMessagesToRemovedServers(); this._removeMessagesFromRemovedServers(); // Remove messages that need to be dropped this._removeDroppedMessages(model); // Deliver messages due for delivery this._deliverMsgsDueForDelivery(model); } _removeMessagesToRemovedServers() { this._inFlightMessages = this._inFlightMessages .filter(msg => this.cluster.nodes.some(n => n.id === msg.targetNodeId)); } _removeMessagesFromRemovedServers() { this._inFlightMessages = this._inFlightMessages .filter(msg => this.cluster.nodes.some(n => n.id === msg.sourceNodeId)); } _removeDroppedMessages(model) { this._inFlightMessages = this._inFlightMessages .filter(msg => msg.recvTime < util.Inf && !(msg.dropTime && msg.dropTime <= model.time)); } _deliverMsgsDueForDelivery(model) { this._inFlightMessages .filter(msg => msg.recvTime <= model.time) .forEach(msg => this.deliver(msg)); } send(message) { if (playback.isPaused() && message.constructor === SyncRequest) { //Hack to ignore sync messages if simulation is paused //TODO should fix when implementing master policy console.log("ignoring sync message as simulation is stopped"); return; } const sendTime = this._model.time; const recvTime = this._calculateRecvTime(); const dropTime = this._calculateDropTime(recvTime, sendTime); Object.assign(message, { sendTime: sendTime, recvTime: recvTime, dropTime: dropTime, from: message.sourceNodeId, to: message.targetNodeId, direction: UiMessageHandler._calculateDirection(message), type: message.constructor.name, term: message.paxosInstanceNumber }); this._inFlightMessages.push(message); if (message.sourceNodeId === message.targetNodeId) { // deliver messages to myself immediately this.deliver(message); } } _calculateRecvTime() { return this._model.time + MIN_RPC_LATENCY + Math.random() * (MAX_RPC_LATENCY - MIN_RPC_LATENCY); } _calculateDropTime(recvTime, sendTime) { if (Math.random() < this._model.channelNoise) { return (recvTime - sendTime) * util.randomBetween(1 / 3, 3 / 4) + sendTime; } } static _calculateDirection(message) { switch (message.constructor) { case Prepare: case Accept: case SyncRequest: return REQUEST; case Promise : case Accepted: case CatchUp: return REPLY; default: console.log(`Don't know how to handle message ${typeof message}`) } } dropMessage(message) { this._inFlightMessages = this.inFlightMessages.filter(m => m !== message); } get inFlightMessages() { return this._inFlightMessages; } }
JavaScript
class Save extends Component { render() { const {dispatch, balance, web3, account} = this.props; const withdraw = (protocol) => { dispatch(selectPage("Withdraw", protocol)); } const deposit = (protocol) => { dispatch(selectPage("Deposit", protocol)); } const topup = () => { topupWallet(dispatch, account); } const actionButton = (clickAction, text, disabled=false) => { return (<Button disabled={disabled} size="sm" onClick={clickAction}> {text} </Button>); } return ( <FadeIn> <Container> <Row> <Col className="text-center"> <BackButton dispatch={dispatch} pageName="Account" /> {(balance.toString() === "0") ? <p>You have no ETH in your wallet. Why not <Button size="sm" onClick={topup}>Topup</Button> ?</p> : <></>} <Table> <thead> <tr> <th>Pool</th> <th>APY</th> <th>Balance</th> <th colSpan="2">Actions</th> </tr> </thead> <tbody> <tr> <td>Compound</td> {/* <td>{parseFloat(compoundAPY).toFixed(2)}%</td> */} {/* <td><strong>{parseFloat(ethCompoundUnderlyingBalance).toFixed(2)} ETH</strong></td> */} <td>{actionButton(() => deposit("compound"), "Deposit", (balance.toString() === "0"))}</td> {/* <td>{actionButton(() => withdraw("compound"), "Withdraw", (compoundUnderlyingBalance.toString() === "0"))}</td> */} </tr> <tr> <td>AAVE</td> {/* <td>{parseFloat(aaveAPY).toFixed(2)}%</td> */} {/* <td><strong>{parseFloat(ethAaveUnderlyingBalance).toFixed(2)} ETH</strong></td> */} <td>{actionButton(() => deposit("aave"), "Deposit", (balance.toString() === "0"))}</td> {/* <td>{actionButton(() => withdraw("aave"), "Withdraw", (aaveUnderlyingBalance.toString() === "0"))}</td> */} </tr> </tbody> </Table> </Col> </Row> </Container> </FadeIn> ) } }
JavaScript
class MessageSummary { /** * Create a MessageSummary. * @member {uuid} id * @member {string} [server] * @member {array} [from] * @member {array} [to] * @member {array} [cc] * @member {array} [bcc] * @member {date} [received] * @member {string} [subject] * @member {string} [summary] * @member {number} [attachments] */ constructor(data) { data = data || {}; this.id = data.id; this.server = data.server; this.from = (data.from || []).map((i) => (new MessageAddress(i))); this.to = (data.to || []).map((i) => (new MessageAddress(i))); this.cc = (data.cc || []).map((i) => (new MessageAddress(i))); this.bcc = (data.bcc || []).map((i) => (new MessageAddress(i))); this.received = moment(data.received).toDate(); this.subject = data.subject; this.summary = data.summary; this.attachments = data.attachments || 0; } }
JavaScript
class RegistryWaitingResult { /** * Create entity * @param {RegistryWaiting} waiting * @param {RegistryDaemon} daemon */ constructor(waiting, daemon) { this._connectionName = waiting.name; this._daemonName = daemon.userEmail + '?' + daemon.name; this._internalAddresses = waiting.internalAddresses.slice(); this._targets = Array.from(waiting.clients).slice(); } /** * Service name is 'entities.registryWaitingResult' * @type {string} */ static get provides() { return 'entities.registryWaitingResult'; } /** * Dependencies as constructor arguments * @type {string[]} */ static get requires() { return []; } /** * Info getter * @type {object} */ get info() { return { connectionName: this._connectionName, daemonName: this._daemonName, internalAddresses: this._internalAddresses, }; } /** * targets getter * @type {string[]} */ get targets() { return this._targets; } }
JavaScript
class NoOnlyTests extends Lint.RuleWalker { visitCallExpression(node) { const expression = node.expression.kind === ts.SyntaxKind.PropertyAccessExpression ? node.expression : null; if ( expression && objNames.indexOf(expression.expression.getText()) !== -1 && expression.name.text === 'only' ) { this.addFailure( this.createFailure( node.getStart(), node.getWidth(), `${node.expression.getText()} is not permitted!`, ), ); } super.visitCallExpression(node); } }
JavaScript
class ExplodeEncounter extends Encounter { constructor() { super({ description: __("You stand in front of the cave-in blocking you from progressing beyond the quarry.\n\n"), type: ENCOUNTER_NAME, }); } /** * Get the title to display for the character's current state. * * @param {Character} character - The character currently in this encounter. * * @return {string} */ getTitle(character) { const remaining = REQUIRED_CRUDE_EXPLOSIVES - character.inventory.quantity(ITEM_CRUDE_EXPLOSIVE); return character.inventory.has(ITEM_CRUDE_EXPLOSIVE, REQUIRED_CRUDE_EXPLOSIVES) ? __("You judge you finally have enough explosives to blast it open.") : __("You still need to collect %d more explosives to open this.", remaining); } /** * Get the action buttons for this encounter. * * @param {Character} character - The character encountering. * * @return {array} */ getActions(character) { let actions = new Actions(); if (character.inventory.has(ITEM_CRUDE_EXPLOSIVE, REQUIRED_CRUDE_EXPLOSIVES)) { actions.addButton(__("Blow it open"), "encounter", { params: { type: ENCOUNTER_NAME, action: ACTION_EXPLODE } } ); actions.addButton(__("Not yet"), "encounter", { params: { type: ENCOUNTER_NAME, action: ACTION_CANCEL } } ); } else { actions.addButton(__("Okay"), "encounter", { params: { type: ENCOUNTER_NAME, action: ACTION_CANCEL } } ); } return actions; } /** * Perform one of this encounter's actions. * * @param {string} action - The action to perform. * @param {Character} character - The character performing the action. * @param {object} message - The message that preceeded this, for updating. */ async doAction(action, character, message) { let title = ''; if (ACTION_EXPLODE === action) { title = this.doExplode(character); } else if (ACTION_CANCEL === action) { title = this.doCancel(character); } else { throw new Error(`Uncrecognized action for ${this.type}: '${action}'`); } character.state = CHARACTER_STATE.IDLE; await this.updateLast({ attachments: Attachments.one({ title }), doLook: true }); } /** * Explode your way into the mines. * * @param {Character} character - The character exploding their way into the mines. * * @return {string} */ doExplode(character) { character.track('Explode Quarry Entrance'); character.inventory.remove(ITEM_CRUDE_EXPLOSIVE, REQUIRED_CRUDE_EXPLOSIVES); character.setFlag(FLAGS.QUARRY_BLOWN_UP); return __("You pile up all your gathered explosives, back up to a safe distance, and toss a flame. The explosives go off instantly, sending rocks flying everywhere. When the dust settles, you can see a clear entrance into the mines."); } /** * Nevermind. * * @param {Character} character - The character cancelling. * * @return {string} */ doCancel(character) { return __("You decide to come back later when you're ready to progress."); } }
JavaScript
class BBOX { constructor(...args) { // const points = [...args]; console.log(args); } }
JavaScript
class ResetPassword extends Component{ constructor(props) { super(props); this.onChangepassword = this.onChangepassword.bind(this); this.onChangeconfirmpassword = this.onChangeconfirmpassword.bind(this); this.onSubmit = this.onSubmit.bind(this); this.state = { password: '', confirmpassword:'', customer:[] } } componentDidMount(){ axios.post('https://carrombackend.herokuapp.com/admin/') .then(response => { this.setState({ customer: response.data}) let result=response.data this.setState({customer: result.map(e => { return{ token : e.resetPasswordToken, } }) }) console.log(this.state.customer[0].token) }) .catch((error) => { console.log(error); }) } onChangepassword(e) { this.setState({ password: e.target.value }) } onChangeconfirmpassword(e) { this.setState({ confirmpassword: e.target.value }) } onSubmit(e) { e.preventDefault(); const customer = { password:this.state.password, } if(this.state.password === this.state.confirmpassword){ axios.post('https://carrombackend.herokuapp.com/admin/reset/' + this.state.customer[0], customer) .then(res => alert("password saved ")); } else { alert("password doesnot match") } } render(){ return ( <main> <section className="bg-soft d-flex align-items-center my-5 mt-lg-6 mb-lg-5"> <Container> <Row className="justify-content-center"> <p className="text-center"> <Card.Link as={Link} to={Routes.Presentation.path} className="text-gray-700"> <FontAwesomeIcon icon={faAngleLeft} className="me-2" /> Back to sign in </Card.Link> </p> <Col xs={12} className="d-flex align-items-center justify-content-center"> <div className="bg-white shadow-soft border rounded border-light p-4 p-lg-5 w-100 fmxw-500"> <h3 className="mb-4">Reset password</h3> <Form onSubmit={this.onSubmit}> <Form.Group id="password" className="mb-4"> <Form.Label>Your Password</Form.Label> <InputGroup> <InputGroup.Text> <FontAwesomeIcon icon={faUnlockAlt} /> </InputGroup.Text> <Form.Control required type="password" placeholder="Password" onChange={this.onChangepassword} /> </InputGroup> </Form.Group> <Form.Group id="confirmPassword" className="mb-4"> <Form.Label>Confirm Password</Form.Label> <InputGroup> <InputGroup.Text> <FontAwesomeIcon icon={faUnlockAlt} /> </InputGroup.Text> <Form.Control required type="password" placeholder="Confirm Password" onChange={this.onChangeconfirmpassword} /> </InputGroup> </Form.Group> <Button variant="primary" type="submit" className="w-100"> Reset password </Button> </Form> </div> </Col> </Row> </Container> </section> </main> ); } }
JavaScript
class ProgressBar { /** * Create a progress bar * @param {...Progress} options - The {@link Progress} options for the progress bar */ constructor(options = {}) { this.percentage = 0 this.height = options.height || 30 this.width = options.width || 300 this.fontSize = options.fontSize || null this.fontColor = options.fontColor || null this.draggable = options.draggable || false this.hidePercent = options.hidePercent || false this.removeWhenDone = options.removeWhenDone !== false this.opacity = options.opacity || 1 this.gradient = options.gradient || ['#00adb981', '#00eeffec'] this.overflow = options.overflow || false this.finishedMessage = options.finishedMessage || null this.HTMLreference = _progressBarHTML() this.HTMLprogress = this.HTMLreference.getElementsByClassName( 'progress' )[0] this.HTMLouterPercentage = this.HTMLreference.getElementsByClassName( 'outerPercentage' )[0] if (options.image) { this.image = { source: options.image.source, leftShift: options.image.leftShift || 0, upShift: options.image.upShift || 0, } } this.style() // contains dom references to the progress bar and progress itself _activeProgressBars.push(this) } /** * Style the progress bar according to this progress bar's attributes */ style() { this.setHeight(this.height) this.setWidth(this.width) if (this.fontSize) this.setFontSize(this.fontSize) if (this.fontColor) this.setFontColor(this.fontColor) this.setOpacity(this.opacity) this.setProgressGradient(this.gradient) if (this.image) this.setBackgroundImage(this.image) if (this.draggable) this.makeDraggable() } /** * Advances the progress bar by amount%. * Should be invoked whenever progress has been made while loading an element * @param {number} amount - The percentage to add to the progress bar */ addProgress(amount) { if (typeof amount !== 'number') { throw new Error('Amount to add to progress bar is invalid') } this.percentage += amount let percent = Math.round(this.percentage * 100) / 100 if (percent >= 100 && !this.overflow) percent = 100 this.HTMLprogress.style.width = Math.min(100, percent) + '%' this.HTMLouterPercentage.style.width = 100 - Math.min(100, percent) + '%' this._updateInnerText() if (percent === 100 && this.removeWhenDone) { this.finishAnimation() } } /** * Sets the progress bar to amount % * @param {number} amount - The percentage to set the progress bar to */ setProgress(amount) { if (typeof amount !== 'number') { throw new Error('Amount to set progress bar to is invalid') } else if (amount < 0 || (amount > 100 && !this.overflow)) { throw new Error('Amount to set progress bar to is out of range') } this.percentage = amount this.HTMLprogress.style.width = Math.min(100, this.percentage) + '%' this.HTMLouterPercentage.style.width = 100 - Math.min(100, percent) + '%' this._updateInnerText() if (percent === 100 && this.removeWhenDone) { this.finishAnimation() } } /** * Helper function that updates the percentage that is shown or hidden */ _updateInnerText() { let percent = Math.round(this.percentage * 100) / 100 if (percent >= 100 && !this.overflow) percent = 100 if (percent === 100 && this.finishedMessage) { this.HTMLprogress.innerText = this.finishedMessage this.HTMLouterPercentage.innerText = '' } else if (!this.hidePercent) { if (this.percentage > 50) { this.HTMLprogress.innerText = percent + '%' this.HTMLouterPercentage.innerText = '' } else { this.HTMLouterPercentage.innerText = percent + '%' } } else { this.HTMLouterPercentage.innerText = '' this.HTMLprogress.innerText = '' } } /** * Fill the bar to 100%, fades it out, and removes it from the DOM and active progress bars */ async finishAnimation() { // complete the bar if (!this.hidePercent) { this.HTMLprogress.innerText = this.finishedMessage || '100%' } this.HTMLprogress.style.width = '100%' this.HTMLouterPercentage.style.width = '0%' // Some css to make the loading bar appear to fade out after a while this.HTMLreference.classList.add('fadeOut') // remove the loading bar from the HTML DOM setTimeout(() => this.cancelBar(), 2000) } /** * Immediately remove the progress bar */ cancelBar() { delete _activeProgressBars.splice( _activeProgressBars.indexOf(this), 1 ) this.HTMLreference.remove() } /** * Set the height of the progress bar * @param {(number|string)} height */ setHeight(height) { if (typeof height === 'number') { this.height = height this.HTMLreference.style.height = height + 'px' } else if (typeof height === 'string') { this.height = height this.HTMLreference.style.height = height } else { throw new Error('Invalid height supplied to progress bar') } } /** * Set the opacity of the progress bar * @param {number} opacity */ setOpacity(opacity) { if (typeof opacity === 'number') { this.opacity = opacity this.HTMLreference.style.opacity = opacity } else { throw new Error('Invalid opacity supplied to progress bar') } } /** * Set the width of the progress bar * @param {(number|string)} width */ setWidth(width) { if (typeof width === 'number') { this.width = width this.HTMLreference.style.width = width + 'px' } else if (typeof width === 'string') { this.width = width this.HTMLreference.style.width = width } else { throw new Error('Invalid width supplied to progress bar') } } /** * Set the font size of the percentage text * @param {(number|string)} fontSize */ setFontSize(fontSize) { if (typeof fontSize === 'string') { this.fontSize = fontSize this.HTMLprogress.style.fontSize = fontSize this.HTMLouterPercentage.style.fontSize = fontSize } else if (typeof fontSize === 'number') { this.fontSize = fontSize + 'px' this.HTMLprogress.style.fontSize = fontSize + 'px' this.HTMLouterPercentage.style.fontSize = fontSize + 'px' } else { throw new Error('Invalid fontSize supplied to progress bar') } } /** * Set the color of the percentage text * @param {string} fontColor */ setFontColor(fontColor) { if (typeof fontColor === 'string') { this.fontColor = fontColor this.HTMLprogress.style.color = fontColor this.HTMLouterPercentage.style.color = fontColor } else { throw new Error('Invalid fontColor supplied to progress bar') } } /** * Change the gradient of the progress bar * A solid color progress bar is possible if the colors provided are the same. * @param {string[]} colors - Array of two or more strings that represent colors */ setProgressGradient(colors) { this.gradient = colors // retrieve the progress bar's information from the stored array this.HTMLprogress.style.background = 'linear-gradient(to right, ' + colors.join(', ') + ' )' this.HTMLprogress.style.boxShadow = '0px 2px 2px -5px ' + colors[0] + ', 0px 2px 5px ' + colors[colors.length - 1] } /** * Set the background image of the progress bar * @param {Image} image - Image to use as the background for the progress bar */ setBackgroundImage(image) { if (image) { this.image.source = image.source || this.image.source this.image.leftShift = image.leftShift || this.image.leftShift this.image.upShift = image.upShift || this.image.upShift } if (this.image.source) { this.HTMLreference.style.backgroundImage = 'url(' + this.image.source + ')' this.HTMLreference.style.backgroundPosition = '-' + this.image.leftShift + 'px -' + this.image.upShift + 'px' } } /** * Hide progress percentage */ hidePercent() { this.hidePercent = true this._updateInnerText() } /** * Display progress percentage */ unhidePercent() { this.hidePercent = false this._updateInnerText() } /** * Toggle hide/display progress percentage */ toggleHidePercent() { this.hidePercent = !this.hidePercent this._updateInnerText() } /** * Set the bar to stay when loading is complete */ keepWhenDone() { this.removeWhenDone = false } /** * Set the bar to disappear when loading is complete. If complete, remove the progress bar. */ unkeepWhenDone() { this.removeWhenDone = true // check if the progress bar is finished let percent = Math.round(this.percentage * 100) / 100 if (percent >= 100 && this.removeWhenDone) { this.finishAnimation() } } /** * Makes the progress bar draggable. * IMPORTANT NOTE: A draggable ProgressBar cannot have a margin style. */ makeDraggable() { // update draggable property in the object this.draggable = true // Set the style of the loading bar so that it can be moved around on the page this.HTMLreference.classList.add('draggable') this.HTMLreference.style.margin = "" // Add a listener for mouse clicks this.HTMLreference.addEventListener( 'mousedown', _mouseDownDragHandler ) } /** * Get all active loading bars * @returns {ProgressBar[]} An array containing all active progress bars */ getAllActiveProgressBars() { return _activeProgressBars } }
JavaScript
class ClickerProgressBar extends ProgressBar { /** * Create a clicker progress bar * In this progress bar, the clicks will be shown instead of percentage, so hidePercent is disabled. * @param {...ClickerProgress} options - {@link ClickerProgress} options to give to the clicker progress bar */ constructor(options = {}) { super(options) this.clicks = 0 this.clickRate = 0 this.hidePercent = false this.removeWhenDone = options.removeWhenDone || false this.HTMLreference.classList.add('clicker-bar') this.HTMLreference.onclick = () => { this.incrementClicks(1) } // default purchases in the clicker game const defaultPurchases = [ { name: 'Machine', cost: 10, rate: 1 }, { name: 'Factory', cost: 25, rate: 3 }, { name: 'Planet', cost: 500, rate: 50 }, ] // purchases defined through arguments passed in let purchases = options.clickPurchases || defaultPurchases this.clickPurchases = purchases.map((i) => this.newClickerPurchase(i.name, i.cost, i.rate) ) this._updateInnerText() // interval to add clicks based on click rate this.interval = setInterval(() => { this.incrementClicks(this.clickRate) }, 1000) } /** * Increment the number of clicks by the specified amount * @param {number} amount - Amount of clicks to increase the clicks by */ incrementClicks(amount) { this.clicks += amount this._updateInnerText() } /** * Increases the auto click generation rate in exchange for a cost in clicks. * Used to buy a click purchase item. * @param {number} cost - Cost of an item in clicks * @param {number} rate - Rate of click production of an item in clicks/second */ buy(cost, rate) { if (this.clicks >= cost) { this.clicks -= cost this.clickRate += rate this._updateInnerText() } } /** * Enables buttons of items that can be purchased, and disables buttons that cannot be purchased. */ checkPurchases() { this.clickPurchases.forEach((item) => { if (this.clicks >= item.cost) { item.HTMLreference.disabled = false } else { item.HTMLreference.disabled = true } }) } /** * Ends the game and removes the progress bar */ finishGame() { clearInterval(this.interval) this.unkeepWhenDone() } /** * Creates a new item that can be purchased with clicks * @param {string} name - Name of the item * @param {number} cost - Cost of the item in clicks * @param {number} rate - Rate of click production of the item in clicks/second * @returns An object containing the button's HTML reference, the rate, and cost of the item. */ newClickerPurchase(name, cost, rate) { if ( typeof name !== 'string' || typeof cost !== 'number' || typeof rate !== 'number' ) { throw new Error('New purchase item for clicker bar invalid') } const clickerButton = document.createElement('button') clickerButton.appendChild( document.createTextNode( name + '. ' + 'Cost: ' + cost + ' clicks. ' + rate + ' click/s' ) ) clickerButton.className = 'clickerbutton' clickerButton.onclick = () => { this.buy(cost, rate) } this.HTMLreference.appendChild(clickerButton) return { HTMLreference: clickerButton, rate: rate, cost: cost } } /** * Helper function that updates the number of clicks and clicks per second */ _updateInnerText() { let active, deactive if (this.percentage > 50) { active = this.HTMLprogress deactive = this.HTMLouterPercentage } else { deactive = this.HTMLprogress active = this.HTMLouterPercentage } active.innerText = 'Clicks: ' + String(this.clicks) + ' (+' + String(this.clickRate) + 'c/s)' deactive.innerText = '' this.checkPurchases() } }
JavaScript
class AttachmentSummaryDto { /** * Constructs a new <code>AttachmentSummaryDto</code>. * @alias module:model/AttachmentSummaryDto */ constructor() { AttachmentSummaryDto.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>AttachmentSummaryDto</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/AttachmentSummaryDto} obj Optional instance to populate. * @return {module:model/AttachmentSummaryDto} The populated <code>AttachmentSummaryDto</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new AttachmentSummaryDto(); if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'String'); } if (data.hasOwnProperty('fileName')) { obj['fileName'] = ApiClient.convertToType(data['fileName'], 'String'); } if (data.hasOwnProperty('mimeType')) { obj['mimeType'] = ApiClient.convertToType(data['mimeType'], 'String'); } if (data.hasOwnProperty('size')) { obj['size'] = ApiClient.convertToType(data['size'], 'Number'); } } return obj; } }
JavaScript
class FileSync extends Worker { constructor(services) { super(services); this.defaultPatterns = []; this.resourcePatterns = []; } /** * The initial handler that will be called by the Harbor TaskManager. */ init() { this.cwd = path.relative(process.cwd(), this.environment.THEME_SRC); this.dist = path.relative(process.cwd(), this.environment.THEME_DIST); // Get the optional defined resource paths to sync. this.defineResourcePatterns(); /** * Resolve all defined path and apply the globbing pattern to sync all files * within that directory. */ this.patterns = this.resolvePatterns(this.defaultPatterns.concat(this.resourcePatterns)); // Push the destination path this.patterns.push(this.dist); this.Console.log('Syncing files...'); // Sync the actual files. copyfiles( this.patterns, { verbose: false, up: 1, }, () => { super.resolve(); } ); } /** * Check if the defined resource path can be resolved form the cwd variable. * Also make sure if the actual path already has the working path defined. */ defineResourcePatterns() { const { patterns } = this.config; if (Array.isArray(patterns)) { this.resourcePatterns = patterns; } } /** * Make sure that each entry is resolved correctly and that a globbing pattern * is also defined for directory defined paths. * * @param {Array} entries Array with all existing paths to sync. */ resolvePatterns(entries) { let resolvedPatterns = [...new Set(entries)]; // Exclude any empty entries. resolvedPatterns = resolvedPatterns.filter((entry) => entry); // Make sure the path is relative to the cwd path. resolvedPatterns = resolvedPatterns.map((entry) => String(entry).startsWith(this.cwd) ? entry : path.join(this.cwd, entry) ); // Append a glob pattern is the current pattern is an actual directory. resolvedPatterns = resolvedPatterns.map((entry) => { if (fs.existsSync(entry) && fs.statSync(entry).isDirectory()) { return `${entry}/**`; } return entry; }); return resolvedPatterns; } }
JavaScript
class RepositoryCollaboratorPermission { /** * Constructs a new <code>RepositoryCollaboratorPermission</code>. * Repository Collaborator Permission * @alias module:model/RepositoryCollaboratorPermission * @param permission {String} * @param user {module:model/SimpleUser} */ constructor(permission, user) { RepositoryCollaboratorPermission.initialize(this, permission, user); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj, permission, user) { obj['permission'] = permission; obj['user'] = user; } /** * Constructs a <code>RepositoryCollaboratorPermission</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/RepositoryCollaboratorPermission} obj Optional instance to populate. * @return {module:model/RepositoryCollaboratorPermission} The populated <code>RepositoryCollaboratorPermission</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new RepositoryCollaboratorPermission(); if (data.hasOwnProperty('permission')) { obj['permission'] = ApiClient.convertToType(data['permission'], 'String'); } if (data.hasOwnProperty('user')) { obj['user'] = ApiClient.convertToType(data['user'], SimpleUser); } } return obj; } }
JavaScript
class FolderBase extends React.Component { static propTypes = { isRootScreen: React.PropTypes.bool, shortcut: React.PropTypes.object.isRequired, style: React.PropTypes.object, executeShortcut: React.PropTypes.func, showText: React.PropTypes.bool, iconSize: React.PropTypes.string, }; static mapPropsToStyleNames = (styleNames, props) => { const { showIcon, showText, iconSize, isRootScreen } = props; styleNames.push(`${iconSize}-icon`); if (!showText) { styleNames.push('text-hidden'); } if (!showIcon) { styleNames.push('icon-hidden'); } if (isRootScreen) { styleNames.push('main-navigation'); } return styleNames; }; constructor(props, context) { super(props, context); this.itemPressed = this.itemPressed.bind(this); this.layoutChanged = this.layoutChanged.bind(this); this.renderPage = this.renderPage.bind(this); this.renderRow = this.renderRow.bind(this); this.renderItem = this.renderItem.bind(this); this.state = { dimensions: { width: null, height: null, }, }; this.scaler = new Scaler(); // Android: lineHeight must be an integer, so we're rounding possible float value to integer. // https://github.com/facebook/react-native/issues/7877 this.scaler.addPropTransformer('lineHeight', oldValue => Math.round(oldValue)); } /** * Get screen layout settings from props. * By default provides layout settings from this.props but it accepts custom props. * @param props (optional) Used for nextProps * @returns {*} */ getLayoutSettings(props = this.props) { return props; } /** * @param width Page width * @param height Page height */ updateDimensions(width, height, callback) { this.setState({ dimensions: { width, height, }, }, callback); } /** * Save new page width and height so it can be reused * Refresh dimension related state after updating page dimensions. * @param width Layout width * @param height Layout height */ layoutChanged({ nativeEvent: { layout: { width, height } } }) { this.scaler.resolveRatioByWidth({ width, height }, defaultResolution); this.updateDimensions(width, height); } /** * Scale value to fit referent resolution. * @param value {int} * @returns {floor} */ scale(value) { return this.scaler.scale(value); } /** * Open a shortcut screen. * @param shortcut */ itemPressed(shortcut) { this.props.executeShortcut(shortcut.id); } /** * Default grouping, it behaves like only one page is to be rendered. * @param children * @returns {*} */ groupChildrenIntoPages(children) { // By default group all rows into one page return [children]; } resolveRowProps() { return {}; } resolvePageProps() { return {}; } resolveScrollViewProps() { return { style: this.props.style.scrollView, }; } // eslint-disable-next-line no-unused-vars renderItem(shortcut, index) {} /** * Iterate trough row items. * @param page * @returns {Array} */ renderItems(row) { return row.map(this.renderItem); } /** * Render row and its items * @param row - array of items * @returns {Array} */ renderRow(row, index) { return ( <View key={`row_${index}`} {...this.resolveRowProps()}> {this.renderItems(row)} </View> ); } /** * Iterate trough page rows. * @param page * @returns {Array} */ renderRows(page = []) { return page.map(this.renderRow); } /** * Render page and it rows. * @param page - array of rows. * @param index * @returns {XML} */ renderPage(page, index = 1) { return ( <View key={`page_${index}`} {...this.resolvePageProps()}> {this.renderRows(page)} </View> ); } /** * Iterate trough pages. * @param pages - is array of page. * @returns {Array} */ renderPages(pages = []) { return pages.map(this.renderPage); } renderScrollView() { const { shortcut } = this.props; return ( <ScrollView {...this.resolveScrollViewProps()}> {this.renderPages(this.groupChildrenIntoPages(shortcut.children))} </ScrollView> ); } renderContentContainer() { const { dimensions: { width, height } } = this.state; if (width === null || height === null) { return null; } const { backgroundImage } = this.getLayoutSettings(); if (backgroundImage) { return ( <View style={this.props.style.backgroundWrapper}> <Image styleName="fill-parent" source={{ uri: backgroundImage }} /> {this.renderScrollView()} </View> ); } return this.renderScrollView(); } render() { return ( <View onLayout={this.layoutChanged} styleName="flexible"> {this.renderContentContainer()} </View> ); } }
JavaScript
class EntityAccessor { constructor() { } /** * Get an attribute value and cast into an XTK string. By attribute here, we mean that it's an * actual XML attribute in the original XML document taken or returned by the SOAP API. * @method * @param {XML.XtkObject} entity the entity (XML or JSON) * @param {string} name the name of the attribute (without the "@" character) * @returns {string} the value of the attribute, as a string. * * @example * const entity = { hello: "world" }; * expect(EntityAccessor.getAttributeAsString(entity, "hello")).toBe("world"); * expect(EntityAccessor.getAttributeAsString(entity, "notFound")).toBe(""); * * @example * const entity = DomUtil.parse("<root hello='world'></root>") * expect(EntityAccessor.getAttributeAsString(entity, "hello")).toBe("world"); */ static getAttributeAsString(entity, name) { if (entity.documentElement) entity = entity.documentElement; if (entity.nodeType && entity.tagName) return DomUtil.getAttributeAsString(entity, name); else if (entity instanceof BadgerFishObject) return XtkCaster.asString(entity[`@${name}`]); else return XtkCaster.asString(entity[name]); } /** * Get an attribute value and cast into an XTK long number (32 bits, never null). By attribute here, we mean that it's an * actual XML attribute in the original XML document taken or returned by the SOAP API. * @method * @param {XML.XtkObject} entity the entity (XML or JSON) * @param {string} name the name of the attribute (without the "@" character) * @returns {number} the value of the attribute, as a 32 bits integer. * * const entity = { hello: 42 }; * expect(EntityAccessor.getAttributeAsLong(entity, "hello")).toBe(42); * expect(EntityAccessor.getAttributeAsLong(entity, "notFound")).toBe(0); * * @example * const entity = DomUtil.parse("<root hello='42'></root>") * expect(EntityAccessor.getAttributeAsLong(entity, "hello")).toBe(42); */ static getAttributeAsLong(entity, name) { if (entity.documentElement) entity = entity.documentElement; if (entity.nodeType && entity.tagName) return DomUtil.getAttributeAsLong(entity, name); else if (entity instanceof BadgerFishObject) return XtkCaster.asLong(entity[`@${name}`]); else return XtkCaster.asLong(entity[name]); } /** * Get an attribute value and cast into an XTK boolean (never null). By attribute here, we mean that it's an * actual XML attribute in the original XML document taken or returned by the SOAP API. * @method * @param {XML.XtkObject} entity the entity (XML or JSON) * @param {string} name the name of the attribute (without the "@" character) * @returns {number} the value of the attribute, as a boolean * * const entity = { hello: true }; * expect(EntityAccessor.getAttributeAsBoolean(entity, "hello")).toBe(true); * expect(EntityAccessor.getAttributeAsBoolean(entity, "notFound")).toBe(false); * * @example * const entity = DomUtil.parse("<root hello='true'></root>") * expect(EntityAccessor.getAttributeAsBoolean(entity, "hello")).toBe(true); */ static getAttributeAsBoolean(entity, name) { if (entity.documentElement) entity = entity.documentElement; if (entity.nodeType && entity.tagName) return DomUtil.getAttributeAsBoolean(entity, name); else if (entity instanceof BadgerFishObject) return XtkCaster.asBoolean(entity[`@${name}`]); else return XtkCaster.asBoolean(entity[name]); } /** * Get the list of child elements with a given tag name * @method * @param {XML.XtkObject} entity the entity (XML or JSON) * @param {string} tagName the tag name of the element * @returns {XML[]|Object[]} a non-null array of child elements * * @example * const entity = { chapter:[ { title:"A" }, { title:"B" } ] }; * // returns an array with 2 elements: { title:"A" } and { title:"B" } * EntityAccessor.getChildElements(entity, "chapter"); * * @example * const entity = DomUtil.parse("<root><chapter title='A'/><chapter title='B'/></root>") * // returns an array with 2 elements: <chapter title='A'/> and <chapter title='B'/> * EntityAccessor.getChildElements(entity, "chapter"); */ static getChildElements(entity, tagName) { if (entity.documentElement) entity = entity.documentElement; if (entity.nodeType && entity.tagName) { const elements = []; var child = DomUtil.getFirstChildElement(entity); while (child) { if (!tagName || tagName == child.tagName) elements.push(child); child = DomUtil.getNextSiblingElement(child); } return elements; } else { var elements = entity[tagName] || []; if (!Util.isArray(elements)) elements = [ elements ]; return elements; } } /** * Get the the first child element with a given tag name (if there's one) * @method * @param {XML.XtkObject} entity the entity (XML or JSON) * @param {string} tagName the tag name of the element * @returns {XML.XtkObject|null} the child element, or null if it's not found * * @example * const entity = { body: { title:"Hello" } }; * // returns an array with 1 elements: { title: "Hello" } * EntityAccessor.getElement(entity, "body"); * * @example * const entity = DomUtil.parse("<root><body title="Hello"/></root>"); * // returns an array with 1 elements: <body title="Hello"/> * EntityAccessor.getElement(entity, "body"); */ static getElement(entity, tagName) { if (entity.documentElement) entity = entity.documentElement; if (entity.nodeType && entity.tagName) { var child = DomUtil.getFirstChildElement(entity); while (child) { if (tagName == child.tagName) return child; child = DomUtil.getNextSiblingElement(child); } return null; } else { const child = entity[tagName]; return child ? child : null; } } }
JavaScript
class Vehicle { constructor(licensePlate, manufacture) { this.licensePlate = licensePlate; this.manufacture = manufacture; this.engineActive = false; } startEngines() { console.log(`Mesin kendaraan ${this.licensePlate} dinyalakan!`); } info() { console.log(`Nomor Kendaraan: ${this.licensePlate}`); console.log(`Manufacture: ${this.manufacture}`); console.log(`Mesin: ${this.engineActive ? "Active": "Inactive"}`); } parking() { console.log(`Kendaraan ${this.licensePlate} parkir!`); } }
JavaScript
class EvidencesAgent { constructor (ctx, db) { this._db = db this._ctx = ctx this._gotNewItem = this._gotNewItem.bind(this) } _gotNewItem () { console.log('got new item and send back to user!') this._ctx.dispatch(actions.add( evidences.generateFakeItem(faker)) ) } start (payload) { this.stop() this.id = setInterval(this._gotNewItem, 5000) } stop () { console.log('stop agent and clear interval', this.id) clearInterval(this.id) } }
JavaScript
class Master extends EventEmitter { /** * Master constructor. * Sets the process title, if it hasn't been modified already... * @param {Obejct} opts User options. */ constructor(opts) { super(); this[options] = typeof opts === 'object' ? opts : {}; if (/node$/.test(process.title)) process.title = 'dist.io master'; // Closes all slaves this.close.all = () => this.close(this.slaves.all); // Closes all slaves in the given group this.close.group = (g, cb) => this.close(this.slaves.inGroup(g), cb); // Shutsdown all slaves this.shutdown.all = () => this.shutdown(this.slaves.all); // Shutsdown all slaves in the given group this.shutdown.group = (g, cb) => this.shutdown(this.slaves.inGroup(g), cb); // Kills all slaves this.kill.all = () => this.kill(this.slaves.all); // Kills all slaves in the given group this.kill.group = (g) => this.kill(this.slaves.inGroup(g)); } /** * If set, every request sent will have this timeout period set on it. * @param {Number} timeout The default timeout period to set in ms. */ set defaultTimeout(timeout) { Slave.defaultTimeout = timeout; } /** * @return {Number} The number of available slaves. */ get slaveCount() { return Slave.getAllSlaves().length; } /** * @return {Number|null} The default timeout period for all slaves. */ get defaultTimeout() { return Slave.defaultTimeout; } /** * Sets the default "catchAll" value on the Slave class, for all slaves. * @param {Boolean|null} value The value to set. */ set shouldCatchAll(value) { Slave.shouldCatchAll = value; } /** * @return {Boolean|null} The default "catchAll" setting for all slaves. */ get shouldCatchAll() { return Slave.shouldCatchAll; } /** * Gets the list of common commands */ get commands() { return COMMANDS; } /** * Used to retrieve slaves. * @returns {Array<Slaves>} An array of slaves */ get slaves() { return { /** * Gets all slaves * @type {Array<Slave>} */ get all() { return Slave.getAllSlaves(); }, /** * Gets all busy slaves * @type {Array<Slave>} */ get busy() { return Slave.getAllBusySlaves(); }, /** * Gets all idle slaves * @type {Array<Slave>} */ get idle() { return Slave.getAllIdleSlaves(); }, /** * @return {SlaveArray} All local slaves. */ get local() { return new SlaveArray(...Slave.getAllSlaves()._.where(s => (s.isRemote === false))); }, /** * @return {SlaveArray} All remote slaves. */ get remote() { return new SlaveArray(...Slave.getAllSlaves()._.where(s => (s.isRemote === true))); }, /** * Gets the idle slaves in the list of slaves. * @param {...String|Number|Slave} slaveList The list of slave to find idle slaves. * @return {Array<Slave>} An array of slaves. */ idleInList: (...slaveList) => { const slaves = flattenSlaveList(true, ...slaveList); return new SlaveArray(...slaves._.where(s => s.isIdle)); }, /** * Gets the least busy slave * @type {Slave} */ get leastBusy() { return Slave.getLeastBusy(...Slave.getAllSlaves()); }, /** * Gets all slaves in the given group. * @param {String} g The group to get the slaves from. * @return {Array<Slave>} An array of slaves. */ inGroup: (g) => Slave.getSlavesInGroup(g), /** * Gets all slaves not in the given group. * @param {String} g The group to omit slaves. * @return {Array<Slave>} An array of slaves. */ notInGroup: (g) => { const slavesInGroupG = Slave.getSlavesInGroup(g); return new SlaveArray(...Slave.getAllSlaves().filter(s => slavesInGroupG.indexOf(s) === -1)); }, /** * Gets the least busy slave in the given group. * @param {String} g The group to find the least busy slave. * @return {Array<Slave>} An array of slaves. */ leastBusyInGroup: (g) => Slave.getLeastBusy(...Slave.getSlavesInGroup(g)), /** * Gets the least busy slave in the list of slaves. * @param {...String|Number|Slave} slaveList The list of slave to find the least busy from. * @return {Array<Slave>} An array of slaves. */ leastBusyInList: (...slaveList) => Slave.getLeastBusy(...flattenSlaveList(true, ...slaveList)), }; } /** * Determines if the given slave belongs to the provided group. * @param {String|Number|Slave} s The slave, slave id, or slave alias to determine group membership. * @param {String} g The group to determine if the slave belongs to. * @return {Boolean} True if the slave belongs to the group, false otherwise. */ slaveBelongsToGroup(s, g) { s = Slave.getSlave(s); if (!s || !g || typeof g !== 'string') return false; return s.group === g; } /** * Creates a new slave. * @param {String} path The file path to the slave's code. * @param {Object} slaveOptions Options to pass to the slave constructor. * @param {...*} rest The rest of the argument to pass to the Slave constructor. * @return {Slave} The newly created slave. */ createSlave(path, slaveOptions, ...rest) { const done = rest._.getAndStripCallback(); const slave = new Slave(path, slaveOptions, ...rest); done.call(slave, slave); /** * Emitted when a new slave is created by the master process. * @event slave created * @argument {Slave} slave The newly created slave instance. */ this.emit('slave created', slave); return slave; } /** * Creates a new remote slave. * @param {String} connectOptions Options for initializing the remote slave. * @param {Object} slaveOptions Options to pass to the slave constructor. * @param {...*} rest The rest of the argument to pass to the Slave constructor. * @return {Slave} The newly created slave. */ createRemoteSlave(connectOptions, slaveOptions, ...rest) { const done = rest._.getAndStripCallback(); const slave = new RemoteSlave(connectOptions, slaveOptions, ...rest); done.call(slave, slave); /** * Emitted when a new *remote* slave is created by the master process. * @event remote slave created * @argument {Slave} slave The newly created slave instance. */ this.emit('remote slave created', slave); this.emit('slave created', slave); return slave; } /** * Creates multiple slaves from a single file path. * @param {Number} count The number of slaves to create. * @param {String} path The file path to the slave's code. * @param {Object} slaveOptions Options to pass to the slave constructor. * @param {...*} rest The rest of the argument to pass to the Slave constructor. * @throws {TypeError} When the value passed to the count param is non-numeric. * @return {Array<Slave>} The newly created slave(s). */ createSlaves(count, path, slaveOptions, ...rest) { if (count === null || count === undefined) count = 0; const done = rest._.getAndStripCallback(); const toCreate = count._.getNumeric(); if (!toCreate._.isNumeric()) { throw new TypeError(`Master#createSlaves expected argument #0 (count) to be numeric, but got ${typeof count}`); } slaveOptions = typeof slaveOptions === 'object' ? slaveOptions : {}; const optionsArray = []; for (let i = 0; i < count; i++) { optionsArray.push(slaveOptions._.clone()); if (typeof slaveOptions.alias === 'string') { if (i !== 0) { optionsArray[i].alias = `${slaveOptions.alias}-${i}`; } else { optionsArray[i].alias = slaveOptions.alias; } } } const slaves = new SlaveArray(); for (let i = 0; i < count; i++) slaves.push(this.createSlave(path, optionsArray[i])); done.call(slaves, slaves); return slaves; } /** * Creates multiple remote slaves from a single location/path. * @param {Number} count The number of slaves to create. * @param {String} connectOptions The connection options that will be sent to the master proxy server. * @param {Object} slaveOptions Options to pass to the slave constructor. * @param {...*} rest The rest of the argument to pass to the Slave constructor. * @throws {TypeError} When the value passed to the count param is non-numeric. * @return {Array<Slave>} The newly created slave(s). */ createRemoteSlaves(count, connectOptions, slaveOptions, ...rest) { if (count === null || count === undefined) count = 0; const done = rest._.getAndStripCallback(); const toCreate = count._.getNumeric(); if (!toCreate._.isNumeric()) { throw new TypeError(`Master#createSlaves expected argument #0 (count) to be numeric, but got ${typeof count}`); } slaveOptions = typeof slaveOptions === 'object' ? slaveOptions : {}; const optionsArray = []; for (let i = 0; i < count; i++) { optionsArray.push(slaveOptions._.clone()); if (typeof slaveOptions.alias === 'string') { if (i !== 0) { optionsArray[i].alias = `${slaveOptions.alias}-${i}`; } else { optionsArray[i].alias = slaveOptions.alias; } } } const slaves = new SlaveArray(); for (let i = 0; i < count; i++) slaves.push(this.createRemoteSlave(connectOptions, optionsArray[i])); done.call(slaves, slaves); return slaves; } /** * Returns the slave with the given id, if it exists. * @param {...*} args The arguments to pass to Slave.getSlaveWithId. * @return {Slave|null} The slave with the given id, if it existed. */ getSlaveWithId(...args) { return Slave.getSlaveWithId(...args); } /** * Returns the slave with the given alias, if it exists. * @param {...*} args The arguments to pass to Slave.getSlaveWithAlias. * @return {Slave|null} The slave with the given alias, if it existed. */ getSlaveWithAlias(...args) { return Slave.getSlaveWithAlias(...args); } /** * Returns the slave with the given path. * @param {...*} args The arguments to pass to Slave.getSlaveWithPath. * @return {SlaveArray<Slave>} The slaves with the given path, if any exist. */ getSlavesWithPath(...args) { return Slave.getSlavesWithPath(...args); } /** * Executes a slave task. * @param {Slave} slave The slave object to execute the task, or the slave id (or alias). * @return {Promise} A promise for completion. */ tellSlave(slave) { slave = Slave.getSlave(slave); return { to: (...args) => new Promise((resolve, reject) => { const done = args._.getAndStripCallback(); if (!(slave instanceof Slave)) { const e = new TypeError('Master#execute expected argument #0 (slave) to be an instanceof Slave'); reject(e); done.call(this, e, null); } slave.exec(...args) .then(resolve) .catch(reject); }), }; } /** * Syntatic sugar for Master#createSlaves, Master#createSlave and various patterns. * @return {Object<Function>} An object containing the Master#createSlave and Master#tellSlave createSlaves. */ get create() { return { slave: (...args) => this.createSlave(...args), slaves: (...args) => this.createSlaves(...args), remote: { slave: (...args) => this.createRemoteSlave(...args), slaves: (...args) => this.createRemoteSlaves(...args), }, pipeline: (...args) => this.createPipeline(...args), scatter: (...args) => this.createScatter(...args), workpool: (...args) => this.createWorkpool(...args), parallel: (...args) => this.createParallel(...args), }; } /** * Syntatic sugar for Master#broadcast and Master#tellSlave * @return {Object<Function>} An object containing the Master#broadcast and Master#tellSlave methods. */ get tell() { return (...slaves) => ({ to: (...args) => { const done = args._.getAndStripCallback(); return this.broadcast(...args).to(...slaves, done); }, }); } /** * Attempts to resolve the slave with the given arugment. * @param {Slave|String|Number} s The value to resolve the slave with. * @return {Slave|null} The slave, if it was resolved. */ slave(s) { return Slave.getSlave(s); } /** * Creates a new parallel directive. * @return {Object} A parallel object, for building out parallel tasks. */ createParallel() { const tasks = []; let addTask = null; let removeTask = null; let forSlave = null; let setTimes = null; let times = 1; const executeTasks = (...args) => { const tasksThisExecution = tasks._.copy(); const done = args._.getAndStripCallback(); return new Promise((resolve, reject) => { const total = tasksThisExecution.length * times; const responses = []; let completed = 0; let broken = false; if (tasksThisExecution.length === 0 || times <= 0) { const res = new ResponseArray(); done.call(this, null, res); resolve(res); return; } const singleResponse = times === 1; const doIteration = (n) => { tasksThisExecution.forEach((t, i) => { if (!responses[n]) responses[n] = new ResponseArray(); if (!(t.slave instanceof Slave)) { const e = new TypeError(`Task #${i} is missing a slave. Did you forget to call ".for"?`); times = 1; done.call(this, e, null); reject(e); return; } t.slave.exec(t.command, t.data, t.meta) .then(res => { responses[n].push(res); if (!broken && ++completed === total) { const result = singleResponse ? responses[0] : responses; times = 1; done.call(this, null, result); resolve(result); } }) .catch(e => { if (!broken) { broken = true; times = 1; done.call(this, e, null); reject(e); } }); }); }; for (let n = 0; n < times; n++) doIteration(n); }); }; setTimes = (n) => { if (typeof n === 'number') times = n; return { execute: executeTasks }; }; forSlave = (slave) => { slave = Slave.getSlave(slave); if (!slave) throw new TypeError('Master#paralle.addTask.for expected argument #0 to be an instanceof Slave.'); tasks[tasks.length - 1].slave = slave; return { addTask, removeTask, execute: executeTasks, times: setTimes, id: tasks[tasks.length - 1].reference }; }; addTask = (command, data, meta) => { validateCommand(command); const id = Symbol(); tasks.push({ command, data, meta, slave: null, reference: id }); return { for: forSlave, removeTask, id }; }; /** * Removes a task from the pipeline. * @param {Symbol|Object<Symbol>} ref The reference to the task to remove. * @return {Boolean} True if the task was removed, false otherwise. */ removeTask = (ref) => { let comparator = null; if (typeof ref === 'symbol') { comparator = ref; } else if (typeof ref === 'object' && typeof ref.id === 'symbol') { comparator = ref.id; } let removed = false; if (comparator) { removed = !tasks._.every((t, i) => { if (t.reference === comparator) { tasks.splice(i, 1); return false; } return true; }); } return { for: forSlave, removeTask, addTask, removed }; }; return { addTask, removeTask, execute: executeTasks, taskCount: () => tasks.length }; } /** * Creates a wookpool from the given slave list. * @param {...Slave|Number|String} A list of slaves to create the workpool from. * @return {Object} A workpool object. */ createWorkpool(...slaves) { return new Workpool(...flattenSlaveList(true, slaves)); } /** * Broadcasts a message to all slaves, or a group. Returns an object for syntatic sugar. * @param {String} command The command to send to the slave. * @param {*} data The data to send with this command. * @param {Object} meta The metadata to send with this broadcast. * @return {Promise} A promise for completion. */ broadcast(command, data, meta) { const bcast = { to: (...slaveList) => new Promise((resolve, reject) => { const done = slaveList._.getAndStripCallback(); if (typeof command === 'string' || typeof command === 'symbol' || (command && command._.isNumeric())) { if (typeof command === 'number') command = command.toString(); const slaves = flattenSlaveList(true, ...slaveList); const totalTasks = slaves.length; const singleResponse = slaves.length === 1; const responses = new ResponseArray(); let broken = false; let completedTasks = 0; /** * When a response is received from one of the slaves. * @param {Response} res The response object from the slave. * @returns {undefined} * @function */ const onResponse = res => { if (!broken) { if (res instanceof Error) { broken = true; done.call(this, res, null); reject(res); return; } responses.push(res); if (++completedTasks === totalTasks) { responses.sort( (a, b) => (a.from < b.from ? -1 : a.from > b.from ? 1 : 0) // eslint-disable-line no-nested-ternary ); if (singleResponse) { done.call(this, null, responses[0]); resolve(responses[0]); } else { done.call(this, null, responses); resolve(responses); } } } }; if (slaves.length === 0) { // No slaves to send the message to, resolve with empty response array. done.call(this, null, responses); resolve(responses); } else { slaves._.every(s => { s.exec(command, data, meta).then(onResponse).catch(onResponse); return true; }); } } else { // Got invalid command. const e = new TypeError( `Master#broadcast expected argument #0 (command) to be a string or number, but got ${typeof command}.` ); reject(e); done.call(this, e, null); } }), }; // Attach broadcast to all function bcast.to.all = () => this.broadcast(command, data, meta).to(...Slave.getAllSlaves()); // Attach broadcast to idle function bcast.to.idle = () => this.broadcast(command, data, meta).to(...Slave.getAllIdleSlaves()); // Attach broadcast to group function bcast.to.group = (g) => this.broadcast(command, data, meta).to(...Slave.getSlavesInGroup(g)); return bcast; } /** * Creates a new executable task pipeline. * @return {Object} A pipeline object. */ createPipeline() { const tasks = []; let task = null; let removeTask = null; /** * Executes the pipeline with the given data. * @param {*} data The initial data to start the pipeline with. * @param {Object} meta The metadata to pass to the pipeline. * @return {Promise} A promise for completion. */ const execute = (data, ...rest) => new Promise((resolve, reject) => { // Copy the task queue to allow for multi-execution const thisRunsTasks = tasks._.copy(); const done = rest._.getAndStripCallback(); let meta; if (typeof rest[0] === 'object') meta = rest[0]; /** * Performs the tasks in the task queue recursively until no tasks remain. * @param {String|Number|Symbol} taskToPerform A task object to perform. * @param {*} dataForTask The data to perform the task with. * @param {Object} metadataForTask The metadata to pass to this task. * @return {undefined} */ const doTask = (taskToPerform, dataForTask, metadataForTask) => { if (!(taskToPerform.slave instanceof Slave)) { const e = new Error(`Task "${taskToPerform.command}" is missing a slave. Did you forget to chain ".for"?`); done.call(this, e, null); reject(e); return; } taskToPerform.slave.exec(taskToPerform.command, dataForTask, metadataForTask) .then(res => { if (res.error) { // Reject pipeline on error. done.call(this, res.error, null); return reject(res.error); } const nextTask = thisRunsTasks.shift(); let finished = false; /** * Cuts off pipeline execution. * @param {*} value The value to end execution with. * @return {undefined} */ const end = (value) => { finished = true; if (value instanceof Error) { res.error = value; } else if (value !== undefined) { res.value = value; } done.call(this, null, res); resolve(res); }; // Execute all the intercepts... taskToPerform.intercepts._.every(intercept => { try { return intercept.call(taskToPerform.slave, res, end); } catch (e) { done.call(this, e, null); reject(e); finished = true; return false; // Break every loop } }); // Perform the next task in the queue... if (nextTask && !finished) { doTask(nextTask, res.value, meta); } else { done.call(this, null, res); resolve(res); } return null; }) .catch(e => { done.call(this, e, null); reject(e); }); }; if (tasks.length === 0) { done.call(this, null, null); resolve(null); return; } // Execute the first task... doTask(thisRunsTasks.shift(), data, meta); }); /** * Allows the user to intercept responses between pipeline sections and modify it. * @param {Function} callback The function to execute on task response. * @return {Object} Various chaining objects to continue defining the pipeline. */ const intercept = (callback) => { if (callback instanceof Function) tasks[tasks.length - 1].intercepts.push(callback); return { addTask: task, removeTask, execute }; }; /** * Adds a slave to the task queue. * @param {Slave|Number|String} s The slave (or slave id, or slave alias) to add. * @return {Object} Various chaining objects to continue defining the pipeline. */ const slave = (s) => { const taskSlave = Slave.getSlave(s); if (!taskSlave) throw new TypeError('Master#pipeline.task.for.slave requires an instanceof Slave.'); tasks[tasks.length - 1].slave = s; return { intercept, addTask: task, removeTask, execute, id: tasks[tasks.length - 1].reference }; }; /** * Adds a new task to the pipeline. * @param {String|Number|Symbol} command The task command to execute. * @return {Object} Various chaining objects to continue defining the pipeline. */ task = (command) => { command = validateCommand(command); const taskReferencer = { id: Symbol(), for: slave, removeTask }; tasks.push({ command, slave: null, intercepts: [], reference: taskReferencer.id }); return taskReferencer; }; /** * Removes a task from the pipeline. * @param {Symbol|Object<Symbol>} ref The reference to the task to remove. * @return {Boolean} True if the task was removed, false otherwise. */ removeTask = (ref) => { let comparator = null; if (typeof ref === 'symbol') { comparator = ref; } else if (typeof ref === 'object' && typeof ref.id === 'symbol') { comparator = ref.id; } let removed = false; if (comparator) { removed = !tasks._.every((t, i) => { if (t.reference === comparator) { tasks.splice(i, 1); return false; } return true; }); } return { for: slave, addTask: task, removeTask, removed }; }; task.execute = execute; task.removeTask = removeTask; return { addTask: task, removeTask, execute, taskCount: () => tasks.length }; } /** * Splits data up among slaves for the given command. * @param {Object} command The command to bind to this scatter. * @param {Object} meta Meta data for this scatter. * @return {Object<Function>} Various functions to finish creating this scatter. */ createScatter(command, meta) { command = validateCommand(command); let dataList = []; const tasks = []; /** * Executes the scatter, and gathers the responses into a response array. * @param {...Slaves} slaves The slaves to execute this scatter with. * @return {ResponseArray} An array of responses. */ const gather = (...slaves) => { meta = typeof meta === 'object' ? meta : {}; let completed = 0; let done = function EMPTY_CALLBACK() {}; const responses = new ResponseArray(); if (slaves[slaves.length - 1] instanceof Function) done = slaves.pop(); slaves = flattenSlaveList(true, ...slaves); return new Promise((resolve, reject) => { if (!slaves || slaves.length === 0) { const e = Error('Cannot gather without at least one slave!'); done.call(this, e, responses); reject(e); } // Build out task list... if (meta.chunk) { const datas = []; while (dataList.length > 0) datas.push(dataList.splice(0, slaves.length)); for (let i = 0; i < datas.length; i++) { tasks.push({ data: datas[i], slave: slaves[i % slaves.length], }); } } else { for (let i = 0; i < dataList.length; i++) { tasks.push({ data: dataList[i], slave: slaves[i % slaves.length], }); } } // We have no tasks to scatter, simply resolve... if (tasks.length === 0) { done.call(this, null, responses); resolve(responses); return; } let hasRejected = false; // Execute task list... tasks.forEach(t => { this.tellSlave(t.slave).to(command, t.data, meta) .then(res => { responses.push(res); if (++completed === tasks.length) { done.call(this, null, responses); resolve(responses); } }) .catch(e => { if (meta.catchAll) { if (!hasRejected) { hasRejected = true; done.call(this, e, null); reject(e); } } else { responses.push(e); if (++completed === tasks.length) { done.call(this, null, responses); resolve(responses); } } }); }); }); }; /** * Adds data to the scatter. * @param {...*} d The data to add. * @return {Object<Function>} An object containing a self reference for chaining, and the gather method. */ const data = (...d) => { dataList = dataList.concat(...d); return { data, gather }; }; return { data }; } /** * Gracefully Closes all the given slaves. * @param {...Slave} slaves A list of the slaves to close. * @return {Promise} A promise for completion. */ close(...slaves) { const done = slaves._.getAndStripCallback(); slaves = flattenSlaveList(false, ...slaves); const statuses = []; const total = slaves.length; let complete = 0; return new Promise(resolve => { const singleResponse = slaves.length === 1; const onClose = (status) => { statuses.push(status); if (++complete === total) { const res = singleResponse ? statuses[0] : statuses; done.call(this, res); resolve(res); } }; slaves.forEach(s => s.close().then(onClose).catch(onClose)); }); } /** * Gracefully Closes all the given slaves, after all messages are received. * @param {...Slave} slaves A list of the slaves to close. * @return {Promise} A promise for completion. */ shutdown(...slaves) { const done = slaves._.getAndStripCallback(); slaves = flattenSlaveList(false, ...slaves); const statuses = []; const total = slaves.length; let complete = 0; return new Promise(resolve => { const singleResponse = slaves.length === 1; const onShutdown = (status) => { statuses.push(status); if (++complete === total) { const res = singleResponse ? statuses[0] : statuses; done.call(this, null, res); resolve(res); } }; slaves.forEach(s => s.shutdown().then(onShutdown).catch(onShutdown)); }); } /** * Kills all the given slaves with SIGKILL * @param {...Slave} slaves A list of the slaves to close. * @return {Master} A self reference for chaining. */ kill(...slaves) { slaves = flattenSlaveList(false, ...slaves); slaves.forEach(s => s.kill('SIGKILL')); return this; } }
JavaScript
class MembershipsSDKAdapter extends MembershipsAdapter { constructor(datasource) { super(datasource); this.members$ = {}; // cache membership observables based on membership id this.listenerCount = 0; } /** * Tells the SDK to start listening to memberships events and tracks the amount of calls. * * Note: Since the SDK listens to ALL memberships events, this function only * calls the SDK's `memberships.listen` function on the first membership to listen. * Repeated calls to `memberships.listen` are not needed afterwards. * * @private */ startListeningToMembershipsUpdates() { if (this.listenerCount === 0) { // Tell the sdk to start listening to membership changes this.datasource.memberships.listen(); } this.listenerCount += 1; } /** * Tells the SDK to stop listening to memberships events. * * Note: Since the SDK listens to ALL memberships events, this function only * calls the SDK's `memberships.stopListening` function once all of the listeners are done. * If `memberships.stopListening` is called early, existing subscribers won't get any updates. * * @private */ stopListeningToMembershipsUpdates() { this.listenerCount -= 1; if (this.listenerCount <= 0) { // Once all listeners are done, stop listening this.datasource.memberships.stopListening(); } } /** * Returns an observable that emits room members list of the given roomID. * * @private * @param {string} roomID ID of the room * @returns {external:Observable.<Array.<Member>>} Observable stream that emits a list of current members in a room */ getRoomMembers(roomID) { this.startListeningToMembershipsUpdates(); const membershipToMember = (membership) => ({ ID: deconstructHydraId(membership.personId).id, orgID: deconstructHydraId(membership.personOrgId).id, muted: null, sharing: null, inMeeting: null, host: null, guest: null, }); const members$ = defer(() => this.datasource.memberships.list({ roomId: roomID, max: MAX_MEMBERSHIPS, })).pipe( map((page) => page.items.map(membershipToMember)), ); const createdEvent$ = fromEvent( this.datasource.memberships, SDK_EVENT.EXTERNAL.EVENT_TYPE.CREATED, ); const deletedEvent$ = fromEvent( this.datasource.memberships, SDK_EVENT.EXTERNAL.EVENT_TYPE.DELETED, ); const event$ = merge(createdEvent$, deletedEvent$) .pipe( filter((event) => event.data.roomId === roomID), mergeMap(() => members$), ); return concat(members$, event$).pipe( publishReplay(1), refCount(), finalize(() => { this.stopListeningToMembershipsUpdates(); }), ); } /** * Returns an observable that emits meeting members list of the given meetingID. * * @private * @param {string} meetingID ID of the meeting * @returns {external:Observable.<Array.<Member>>} Observable stream that emits a list of current members in a meeting */ getMeetingMembers(meetingID) { const meeting = this.datasource.meetings.getMeetingByType('id', meetingID); let members$; if (!meeting) { members$ = throwError(new Error(`Meeting ${meetingID} not found.`)); } else { const members = meeting.members && meeting.members.membersCollection && meeting.members.membersCollection.members; // Behavior subject will keep the last emitted object for new subscribers // https://rxjs.dev/guide/subject#behaviorsubject members$ = new BehaviorSubject(getMembers(members)); // Emit on membership updates meeting.members.on('members:update', (payload) => { if (payload && payload.full) { members$.next(getMembers(payload.full)); } }); } return members$; } /** * Returns an observable that emits a list of Member objects. * Whenever there is an update to the membership, the observable * will emit a new updated Member list, if datasource permits. * * @param {string} destinationID ID of the destination for which to get members * @param {DestinationType} destinationType Type of the membership destination * @returns {external:Observable.<Array.<Member>>} Observable stream that emits member lists */ getMembersFromDestination(destinationID, destinationType) { const membershipID = `${destinationType}-${destinationID}`; let members$ = this.members$[membershipID]; if (!members$) { switch (destinationType) { case DestinationType.ROOM: members$ = this.getRoomMembers(destinationID); break; case DestinationType.MEETING: members$ = this.getMeetingMembers(destinationID); break; default: members$ = throwError(new Error(`getMembersFromDestination for ${destinationType} is not currently supported.`)); } // save for future calls this.members$[membershipID] = members$; } return members$; } }
JavaScript
class Element { constructor(nsName, attrs, options) { var qname = QName.parse(nsName); this.nsName = nsName; this.prefix = qname.prefix; this.name = qname.name; this.nsURI = ""; this.parent = null; this.children = []; this.xmlns = {}; if (this.constructor.elementName) { assert( this.name === this.constructor.elementName, "Invalid element name: " + this.name ); } this._initializeOptions(options); for (var key in attrs) { var match = /^xmlns:?(.*)$/.exec(key); if (match) { if (attrs[key] === namespaces.xsd_rc) { // Handle http://www.w3.org/2000/10/XMLSchema attrs[key] = namespaces.xsd; } if (attrs[key] === namespaces.xsi_rc) { // Handle http://www.w3.org/2000/10/XMLSchema-instance attrs[key] = namespaces.xsi; } this.xmlns[match[1] ? match[1] : EMPTY_PREFIX] = attrs[key]; } else { if (key === "value") { this[this.valueKey] = attrs[key]; } else { this["$" + key] = attrs[key]; } } } if (this.$targetNamespace) { this.targetNamespace = this.$targetNamespace; } } _initializeOptions(options) { if (options) { this.valueKey = options.valueKey || "$value"; this.xmlKey = options.xmlKey || "$xml"; this.ignoredNamespaces = options.ignoredNamespaces || []; this.forceSoapVersion = options.forceSoapVersion; } else { this.valueKey = "$value"; this.xmlKey = "$xml"; this.ignoredNamespaces = []; } } startElement(stack, nsName, attrs, options) { if (!this.constructor.allowedChildren) return; var child; var parent = stack[stack.length - 1]; var qname = this._qnameFor(stack, nsName, attrs, options); var ElementType = typeRegistry.getElementType(qname); if ( this.constructor.allowedChildren.indexOf(qname.name) === -1 && this.constructor.allowedChildren.indexOf("any") === -1 ) { debug("Element %s is not allowed within %j", qname, this.nsName); } if (ElementType) { child = new ElementType(nsName, attrs, options); child.nsURI = qname.nsURI; child.targetNamespace = attrs.targetNamespace || this.getTargetNamespace(); debug("Element created: ", child); child.parent = parent; stack.push(child); } else { this.unexpected(nsName); } } endElement(stack, nsName) { if (this.nsName === nsName) { if (stack.length < 2) return; var parent = stack[stack.length - 2]; if (this !== stack[0]) { helper.extend(stack[0].xmlns, this.xmlns); parent.children.push(this); parent.addChild(this); } stack.pop(); } } _qnameFor(stack, nsName, attrs, options) { // Create a dummy element to help resolve the XML namespace var child = new Element(nsName, attrs, options); var parent = stack[stack.length - 1]; child.parent = parent; var qname = QName.parse(nsName); qname.nsURI = child.getNamespaceURI(qname.prefix); return qname; } addChild(child) { return; } unexpected(name) { throw new Error( g.f("Found unexpected element (%s) inside %s", name, this.nsName) ); } describe(definitions) { return this.$name || this.name; } /** * Look up the namespace by prefix * @param {string} prefix Namespace prefix * @returns {string} Namespace */ getNamespaceURI(prefix) { if (prefix === "xml") return helper.namespaces.xml; var nsURI = null; if (this.xmlns && prefix in this.xmlns) { nsURI = this.xmlns[prefix]; } else { if (this.parent) { return this.parent.getNamespaceURI(prefix); } } return nsURI; } /** * Get the target namespace URI * @returns {string} Target namespace URI */ getTargetNamespace() { if (this.targetNamespace) { return this.targetNamespace; } else if (this.parent) { return this.parent.getTargetNamespace(); } return null; } /** * Get the qualified name * @returns {QName} Qualified name */ getQName() { return new QName(this.targetNamespace, this.$name); } /** * Resolve a schema object by qname * @param schemas * @param elementType * @param nsName * @returns {*} */ resolveSchemaObject(schemas, elementType, nsName) { var qname = QName.parse(nsName); var nsURI; if (qname.prefix === "xml") return null; if (qname.prefix) nsURI = this.getNamespaceURI(qname.prefix); else nsURI = this.getTargetNamespace(); qname.nsURI = nsURI; var name = qname.name; if ( nsURI === helper.namespaces.xsd && (elementType === "simpleType" || elementType === "type") ) { return xsd.getBuiltinType(name); } var schema = schemas[nsURI]; if (!schema) { debug("Schema not found: %s (%s)", qname, elementType); return null; } var found = null; switch (elementType) { case "element": found = schema.elements[name]; break; case "type": found = schema.complexTypes[name] || schema.simpleTypes[name]; break; case "simpleType": found = schema.simpleTypes[name]; break; case "complexType": found = schema.complexTypes[name]; break; case "group": found = schema.groups[name]; break; case "attribute": found = schema.attributes[name]; break; case "attributeGroup": found = schema.attributeGroups[name]; break; } if (!found) { debug("Schema %s not found: %s %s", elementType, nsURI, nsName); return null; } return found; } postProcess(definitions) { debug("Unknown element: %s %s", this.nsURI, this.nsName); } }
JavaScript
class ActivityPostObject { /** * Constructs a new <code>ActivityPostObject</code>. * @alias module:model/ActivityPostObject * @implements module:model/ActivityObjectFragment * @implements module:model/ActivityPostObjectAllOf */ constructor() { ActivityObjectFragment.initialize(this);ActivityPostObjectAllOf.initialize(this); ActivityPostObject.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>ActivityPostObject</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/ActivityPostObject} obj Optional instance to populate. * @return {module:model/ActivityPostObject} The populated <code>ActivityPostObject</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new ActivityPostObject(); ActivityObjectFragment.constructFromObject(data, obj); ActivityPostObjectAllOf.constructFromObject(data, obj); if (data.hasOwnProperty('due_date')) { obj['due_date'] = ApiClient.convertToType(data['due_date'], 'Date'); delete data['due_date']; } if (data.hasOwnProperty('due_time')) { obj['due_time'] = ApiClient.convertToType(data['due_time'], 'String'); delete data['due_time']; } if (data.hasOwnProperty('duration')) { obj['duration'] = ApiClient.convertToType(data['duration'], 'String'); delete data['duration']; } if (data.hasOwnProperty('deal_id')) { obj['deal_id'] = ApiClient.convertToType(data['deal_id'], 'Number'); delete data['deal_id']; } if (data.hasOwnProperty('person_id')) { obj['person_id'] = ApiClient.convertToType(data['person_id'], 'Number'); delete data['person_id']; } if (data.hasOwnProperty('org_id')) { obj['org_id'] = ApiClient.convertToType(data['org_id'], 'Number'); delete data['org_id']; } if (data.hasOwnProperty('note')) { obj['note'] = ApiClient.convertToType(data['note'], 'String'); delete data['note']; } if (data.hasOwnProperty('location')) { obj['location'] = ApiClient.convertToType(data['location'], 'String'); delete data['location']; } if (data.hasOwnProperty('public_description')) { obj['public_description'] = ApiClient.convertToType(data['public_description'], 'String'); delete data['public_description']; } if (data.hasOwnProperty('subject')) { obj['subject'] = ApiClient.convertToType(data['subject'], 'String'); delete data['subject']; } if (data.hasOwnProperty('type')) { obj['type'] = ApiClient.convertToType(data['type'], 'String'); delete data['type']; } if (data.hasOwnProperty('user_id')) { obj['user_id'] = ApiClient.convertToType(data['user_id'], 'Number'); delete data['user_id']; } if (data.hasOwnProperty('participants')) { obj['participants'] = ApiClient.convertToType(data['participants'], [Object]); delete data['participants']; } if (data.hasOwnProperty('busy_flag')) { obj['busy_flag'] = ApiClient.convertToType(data['busy_flag'], 'Boolean'); delete data['busy_flag']; } if (data.hasOwnProperty('attendees')) { obj['attendees'] = ApiClient.convertToType(data['attendees'], [Object]); delete data['attendees']; } if (data.hasOwnProperty('done')) { obj['done'] = ApiClient.convertToType(data['done'], NumberBoolean); delete data['done']; } if (Object.keys(data).length > 0) { Object.assign(obj, data); } } return obj; } }
JavaScript
class VcfNetworkToolPanel extends ThemableMixin(PolymerElement) { static get template() { return html` <style include="lumo-typography"> .panel-container { box-shadow: inset -1px 0 0 0 var(--lumo-shade-10pct); display: flex; flex-direction: column; overflow: auto; width: 240px; flex-shrink: 0; height: 100%; transition: width 0.2s; } .panel-container.add-node-toggle .section-item.active { animation: active 5s linear infinite; } @keyframes active { 0% { box-shadow: inset 0px 0px 0px 1px var(--lumo-shade-10pct); } 50% { box-shadow: inset 0px 0px 20px 2px var(--lumo-shade-20pct); } 100% { box-shadow: inset 0px 0px 0px 1px var(--lumo-shade-10pct); } } :host([hidden]) { display: none !important; } /* Section */ .section:not(.collapsed) { padding-bottom: var(--lumo-space-s); } .section:not(:last-child) { box-shadow: inset 0 -1px 0 0 var(--lumo-shade-10pct); } .section.collapsed .section-items { max-height: 0 !important; } /* Section header */ .section-header { align-items: center; cursor: pointer; display: flex; height: var(--lumo-size-l); padding: 0 var(--lumo-space-m); } .section-header h6 { color: var(--lumo-secondary-text-color); margin: 0 auto 0 0; } .section-header iron-icon { color: var(--lumo-secondary-text-color); transition: all 0.2s; } .section.collapsed .section-header iron-icon { transform: rotate(180deg); } /* Section items */ .section-items { overflow: hidden; transform-origin: top; transition: all 0.2s; } .section-item { align-items: center; cursor: pointer; display: flex; height: var(--lumo-size-l); padding-left: var(--lumo-space-m); transition: all 0.2s; } iron-icon.blue, iron-icon.green, iron-icon.red { margin-right: var(--lumo-space-m); } .section-item vcf-network-color-option { margin: auto var(--lumo-space-m) auto 0; } .section-item span { color: var(--lumo-body-text-color); font-size: var(--lumo-font-size-s); transition: all 0.2s; } .section:first-child .section-item span::first-letter { text-decoration: underline; } .section-item:hover { background-color: var(--lumo-shade-5pct); } .section-item.active { background-color: var(--lumo-primary-color-10pct); } .section-item.active span { color: var(--lumo-primary-text-color); font-weight: 500; } iron-icon.blue { color: var(--lumo-primary-color); } iron-icon.green { color: var(--lumo-success-text-color); } iron-icon.red { color: var(--lumo-error-text-color); } .section-item { display: flex; align-items: center; } .section-item div { flex-grow: 1; display: flex; height: 100%; } .section-item span { display: block; margin: auto 0; } .hidden { display: none; } .edit-hidden .edit-template, .edit-hidden .delete-template, .edit-hidden #new-template-button { display: none; } .section-grow { flex-grow: 1; } .template-item { margin: var(--lumo-space-s) var(--lumo-space-m); } .section-footer { text-align: right; cursor: pointer; } .no-templates { margin: var(--lumo-space-s) var(--lumo-space-m); color: var(--lumo-disabled-text-color); } /** Closed **/ .panel-container.closed { width: 36px; } .closed span, .closed h6, .closed #template-panel { display: none; } .closed .section-header { padding: 0; justify-content: center; } .closed .section-header, .closed .section-item { padding: 0; justify-content: center; } .closed iron-icon.blue, .closed iron-icon.green, .closed iron-icon.red { margin-right: 0; } .closed .section-footer iron-icon { transform: rotate(180deg); } .closed .section-footer { text-align: center; } </style> <div id="tool-panel" class="panel-container"> <div class="section"> <div class="section-header"> <h6>Default</h6> <iron-icon icon="vcf-network:keyboard-arrow-down"></iron-icon> </div> <div class="section-items"> <div id="add-node" class="section-item"> <iron-icon icon="vcf-network:format-shapes" class="blue"></iron-icon> <span>Node</span> </div> <div id="add-input-node" class="section-item"> <iron-icon icon="vcf-network:exit-to-app" class="green"></iron-icon> <span>Input Node</span> </div> <div id="add-output-node" class="section-item"> <iron-icon icon="vcf-network:exit-to-app" class="red"></iron-icon> <span>Output Node</span> </div> </div> </div> <div id="template-panel" class="section edit-hidden"> <div class="section-header"> <h6>Template</h6> <iron-icon icon="vcf-network:keyboard-arrow-down"></iron-icon> </div> <div class="section-items" id="custom"> <template is="dom-if" if="[[!components.length]]" on-dom-change="_initToolbar"> <div class="no-templates">No templates</div> </template> <template is="dom-if" if="[[components.length]]" on-dom-change="_initToolbar"> <template is="dom-repeat" items="[[components]]" on-dom-change="_initToolbar"> <div class="section-item"> <div on-click="_addComponentListener"> <vcf-network-color-option color="[[item.componentColor]]" class="icon"></vcf-network-color-option> <span>[[item.label]]</span> </div> <vaadin-button class="edit-template" theme="tertiary small" title="Edit template" on-click="_updateTemplateListener" > <iron-icon icon="vcf-network:create" slot="prefix"></iron-icon> </vaadin-button> <vaadin-button class="delete-template" theme="tertiary error small" title="Delete template" on-click="_deleteTemplateListener" > <iron-icon icon="vcf-network:delete" slot="prefix"></iron-icon> </vaadin-button> </div> </template> </template> <div id="new-template-button" class="template-item"> <vaadin-button style="flex-grow:1;" title="Add template" on-click="_addTemplateListener"> <iron-icon icon="vcf-network:add" slot="prefix"></iron-icon> New template </vaadin-button> </div> </div> </div> <div class="section section-grow"></div> <div class="section-footer"> <iron-icon icon="vcf-network:keyboard-arrow-left"></iron-icon> </div> </div> `; } static get is() { return 'vcf-network-tool-panel'; } static get properties() { return { addNodeToggle: { type: Boolean, observer: '_addNodeToggleChanged' }, components: { type: Array, value: [] } }; } get _sectionItems() { return this.shadowRoot.querySelectorAll('.section-item'); } connectedCallback() { super.connectedCallback(); this._initToolbar(); this._initEventListeners(); } clear(exclude = null) { this._sectionItems.forEach(item => { if (!exclude || (exclude && exclude !== item)) item.classList.remove('active'); }); } _initEventListeners() { /* section-header */ const sectionHeaders = this.shadowRoot.querySelectorAll('.section-header'); sectionHeaders.forEach(header => { const section = header.parentElement; header.addEventListener('click', () => { if (section.classList.contains('collapsed')) { section.classList.remove('collapsed'); } else { section.classList.add('collapsed'); } }); }); const sectionFooters = this.shadowRoot.querySelectorAll('.section-footer'); sectionFooters.forEach(footer => { const section = footer.parentElement; footer.addEventListener('click', () => { if (section.classList.contains('closed')) { section.classList.remove('closed'); } else { section.classList.add('closed'); } this.main._network.redraw(); }); }); /* buttons */ this.$['add-node'].addEventListener('click', () => this._addNode()); this.$['add-input-node'].addEventListener('click', () => this._addNode('input')); this.$['add-output-node'].addEventListener('click', () => this._addNode('output')); } _initToolbar() { // Set max-height of sections for collapse animation const sections = this.shadowRoot.querySelectorAll('.section-items'); sections.forEach(section => { section.style.maxHeight = 'unset'; section.style.maxHeight = `${section.clientHeight}px`; }); } _addNode(type = true) { let button = 'add-node'; if (type === 'input' || type === 'output') { button = `add-${type}-node`; this.main._nodeType = type; } else { this.main._nodeType = ''; } this._setMode(this.$[button], 'addingNode'); } _addComponentListener(event) { var sectionItem = event.target.matches('.section-item') ? event.target : event.target.parentElement; sectionItem = sectionItem.matches('.section-item') ? sectionItem : sectionItem.parentElement; this.main._componentTemplate = event.model.item; this._setMode(sectionItem, 'addingComponent'); } _setMode(item, mode) { this.clear(item); if (item.classList.contains('active')) { item.classList.remove('active'); this.main[mode] = false; } else { item.classList.add('active'); this.main[mode] = true; } } /** * call new-template-event */ _addTemplateListener() { const evt = new CustomEvent('vcf-network-new-template', { cancelable: true }); const cancelled = !this.main.dispatchEvent(evt); if (!cancelled) { // JCG todo default behaviour for the client side this.confirmAddTemplate({ id: vis.util.randomUUID(), label: 'new template' }); } } /** * Refresh the client model */ confirmAddTemplate(component) { this.components.push(component); this.set('components', this.components.slice()); console.info('template added'); } /** * call delete-template-event */ _deleteTemplateListener(event) { const evt = new CustomEvent('vcf-network-delete-template', { detail: { id: event.model.item.id }, cancelable: true }); const cancelled = !this.main.dispatchEvent(evt); if (!cancelled) { this.confirmDeleteTemplate(event.model.item.id); } } /** * Refresh the client model */ confirmDeleteTemplate(id) { this.set('components', this.components.filter(template => template.id !== id)); } /** * call update-template-event */ _updateTemplateListener(event) { const evt = new CustomEvent('vcf-network-update-template', { detail: { id: event.model.item.id }, cancelable: true }); const cancelled = !this.main.dispatchEvent(evt); if (!cancelled) { this.confirmUpdateTemplate(event.model.item); } } confirmUpdateTemplate(component) { const index = this.components.findIndex(item => item.id === component.id); this.splice('components', index, 1, { ...component }); console.info('template updated component =', component); } hideEditTemplateButton() { this.$['template-panel'].classList.add('edit-hidden'); } showEditTemplateButton() { this.$['template-panel'].classList.remove('edit-hidden'); } hideTemplatePanel() { this.$['template-panel'].classList.add('hidden'); } showTemplatePanel() { this.$['template-panel'].classList.remove('hidden'); } closePanel() { this.$['tool-panel'].classList.add('closed'); } openPanel() { this.$['tool-panel'].classList.remove('closed'); } _addNodeToggleChanged(addNodeToggle) { if (addNodeToggle) this.$['tool-panel'].classList.add('add-node-toggle'); else this.$['tool-panel'].classList.remove('add-node-toggle'); } }
JavaScript
class AnswersCtrl { // 查询答案列表 async find (ctx) { const { per_page = 10 } = ctx.query const page = Math.max(ctx.query.page * 1, 1) - 1 const perPage = Math.max(per_page, 1) const q = new RegExp(ctx.query.q) ctx.body = await Answer.find({ content: q, questionId: ctx.params.questionId }) .limit(perPage) .skip(page * perPage) } // 查询特定答案 async findById (ctx) { const { fields = '' } = ctx.query const selectFields = fields.split(';').filter(e => e).map(e => ' +' + e).join('') const answer = await Answer.findById(ctx.params.id).select(selectFields).populate('answerer') if (!answer) {ctx.throw(404, '答案不存在')} ctx.body = answer } // 新建答案 async create (ctx) { ctx.verifyParams({ content: { type: 'string', required: true } }) const answerer = ctx.state.user._id const { questionId } = ctx.params ctx.body = await new Answer({ ...ctx.request.body, answerer, questionId }).save() } // 修改答案 async update (ctx) { ctx.verifyParams({ content: { type: 'string', required: false } }) await ctx.state.answer.update(ctx.request.body) ctx.body = ctx.state.answer } // 删除答案 async del (ctx) { await Answer.findByIdAndRemove(ctx.params.id) ctx.status = 204 } // 检测答案是否存在 async checkAnswerExist (ctx, next) { const answer = await Answer.findById(ctx.params.id).select('+answerer') if (!answer) {ctx.throw(404, '答案不存在')} // 只有删改查答案的时候才检查此逻辑,赞、踩答案不检查 if (ctx.params.questionId && answer.questionId !== ctx.params.questionId) {ctx.throw(404, '该问题下没有此答案')} ctx.state.answer = answer await next() } // 检测是否拥有答案 async checkAnswerer (ctx, next) { const { answer } = ctx.state if (answer.answerer.toString() !== ctx.state.user._id) {ctx.throw(403, '无权限')} await next() } }
JavaScript
class Lipsum extends Component { constructor(props) { super(props); this.state = { ...this.props, }; } componentWillReceiveProps(nextProps) { this.setState(prevState => ({ ...prevState, ...nextProps, })); } render() { let { length = 0, index, text } = this.state; length = length === 0 ? text.length : length; let str = String(text).substr(index, length); return <Fragment>{str}</Fragment>; } }
JavaScript
class N2TreeNode { /** * Absorb all the properties of the provided JSON object from the model tree. * @param {Object} origNode The node to work from. */ constructor(origNode) { // Merge all of the props from the original JSON tree node to us. Object.assign(this, origNode); this.sourceParentSet = new Set(); this.targetParentSet = new Set(); this.nameWidthPx = 1; // Set by N2Layout this.numLeaves = 0; // Set by N2Layout this.isMinimized = false; this.manuallyExpanded = false; this.childNames = new Set(); // Set by ModelData this.depth = -1; // Set by ModelData this.parent = null; // Set by ModelData this.id = -1; // Set by ModelData this.absPathName = ''; // Set by ModelData this.numDescendants = 0; // Set by ModelData // Solver names may be empty, so set them to "None" instead. if (this.linear_solver == "") this.linear_solver = "None"; if (this.nonlinear_solver == "") this.nonlinear_solver = "None"; this.rootIndex = -1; this.dims = { 'x': 1e-6, 'y': 1e-6, 'width': 1, 'height': 1 }; this.prevDims = { 'x': 1e-6, 'y': 1e-6, 'width': 1e-6, 'height': 1e-6 }; this.solverDims = { 'x': 1e-6, 'y': 1e-6, 'width': 1, 'height': 1 }; this.prevSolverDims = { 'x': 1e-6, 'y': 1e-6, 'width': 1e-6, 'height': 1e-6 }; } /** Run when a node is collapsed. */ minimize() { this.isMinimized = true; } /** Run when a node is restored. */ expand() { this.isMinimized = false; } /** * Create a backup of our position and other info. * @param {boolean} solver Whether to use .dims or .solverDims. * @param {number} leafNum Identify this as the nth leaf of the tree */ preserveDims(solver, leafNum) { let dimProp = solver ? 'dims' : 'solverDims'; let prevDimProp = solver ? 'prevDims' : 'prevSolverDims'; Object.assign(this[prevDimProp], this[dimProp]); if (this.rootIndex < 0) this.rootIndex = leafNum; this.prevRootIndex = this.rootIndex; } /** * Determine if the children array exists and has members. * @param {string} [childrenPropName = 'children'] Usually children, but * sometimes 'subsystem_children' * @return {boolean} True if the children property is an Array and length > 0. */ hasChildren(childrenPropName = 'children') { return (Array.isPopulatedArray(this[childrenPropName])); } /** True if this.type is 'input' or 'unconnected_input'. */ isInput() { return this.type.match(inputRegex); } /** True if this is an input and connected. */ isConnectedInput() { return (this.type == 'input'); } /** True if this an input and unconnected. */ isUnconnectedInput() { return (this.type == 'unconnected_input'); } /** True if this is an input whose source is an auto-ivc'd output */ isAutoIvcInput() { return (this.type == 'autoivc_input'); } /** True if this.type is 'output'. */ isOutput() { return (this.type == 'output'); } /** True if this is the root node in the model */ isRoot() { return (this.type == 'root'); } /** True if this is an output and it's not implicit */ isExplicitOutput() { return (this.isOutput() && !this.implicit); } /** True if this is an output and it is implicit */ isImplicitOutput() { return (this.isOutput() && this.implicit); } /** True if this.type is 'input', 'unconnected_input', or 'output'. */ isInputOrOutput() { return this.type.match(inputOrOutputRegex); } /** True is this.type is 'subsystem' */ isSubsystem() { return (this.type == 'subsystem'); } /** True if it's a subsystem and this.subsystem_type is 'group' */ isGroup() { return (this.isSubsystem() && this.subsystem_type == 'group'); } /** True if it's a subsystem and this.subsystem_type is 'component' */ isComponent() { return (this.isSubsystem() && this.subsystem_type == 'component'); } /** Not connectable if this is a input group or parents are minimized. */ isConnectable() { if (this.isInputOrOutput() && !(this.hasChildren() || this.parent.isMinimized || this.parentComponent.isMinimized)) return true; return this.isMinimized; } /** Return false if the node is minimized or hidden */ isVisible() { return !(this.varIsHidden || this.isMinimized); } /** * Look for the supplied node in the set of child names. * @returns {Boolean} True if a match is found, otherwise false. */ hasNodeInChildren(compareNode) { return this.childNames.has(compareNode.absPathName); } /** Look for the supplied node in the parentage of this one. * @param {N2TreeNode} compareNode The node to look for. * @param {N2TreeNode} [parentLimit = null] Stop searching at this common parent. * @returns {Boolean} True if the node is found, otherwise false. */ hasParent(compareNode, parentLimit = null) { for (let obj = this.parent; obj != null && obj !== parentLimit; obj = obj.parent) { if (obj === compareNode) { return true; } } return false; } /** * Look for the supplied node in the lineage of this one. * @param {N2TreeNode} compareNode The node to look for. * @param {N2TreeNode} [parentLimit = null] Stop searching at this common parent. * @returns {Boolean} True if the node is found, otherwise false. */ hasNode(compareNode, parentLimit = null) { if (this.type == 'root') return true; if (this === compareNode) return true; // Check parents first. if (this.hasParent(compareNode, parentLimit)) return true; return this.hasNodeInChildren(compareNode); } /** * Add ourselves to the supplied array if we contain a cycleArrows property. * @param {Array} arr The array to add to. */ _getNodesInChildrenWithCycleArrows(arr) { if (this.cycleArrows) { arr.push(this); } if (this.hasChildren()) { for (let child of this.children) { child._getNodesInChildrenWithCycleArrows(arr); } } } /** * Populate an array with nodes in our lineage that contain a cycleArrows member. * @returns {Array} The array containing all the found nodes with cycleArrows. */ getNodesWithCycleArrows() { let arr = []; // Check parents first. for (let obj = this.parent; obj != null; obj = obj.parent) { if (obj.cycleArrows) { arr.push(obj); } } // Check all descendants as well. this._getNodesInChildrenWithCycleArrows(arr); return arr; } /** * Find the closest parent shared by two nodes; farthest should be tree root. * @param {N2TreeNode} other Another node to compare parents with. * @returns {N2TreeNode} The first common parent found. */ nearestCommonParent(other) { for (let myParent = this.parent; myParent != null; myParent = myParent.parent) for (let otherParent = other.parent; otherParent != null; otherParent = otherParent.parent) if (myParent === otherParent) return myParent; // Should never get here because root is parent of all debugInfo("No common parent found between two nodes: ", this, other); return null; } /** * If the node has a lot of descendants and it wasn't manually expanded, * minimize it. * @param {Number} depthCount The number of nodes at the next depth down. * @returns {Boolean} True if minimized here, false otherwise. */ minimizeIfLarge(depthCount) { if (!(this.isRoot() || this.manuallyExpanded) && (this.depth >= (this.isComponent() ? Precollapse.cmpDepthStart : Precollapse.grpDepthStart) && this.numDescendants > Precollapse.threshold && this.children.length > Precollapse.children - this.depth && depthCount > Precollapse.depthLimit)) { debugInfo(`Precollapsing node ${this.absPathName}`) this.minimize(); return true; } return false; } /** * Convert an absolute path name to a string that's safe to use as an HTML id. * @param {String} absPathName The name to convert. * @returns {String} The HTML-safe id. */ static absPathToId(absPathName) { return absPathName.replace(/[\.<> :]/g, function (c) { return { ' ': '__', '<': '_LT', '>': '_GT', '.': '_', ':': '-' }[c]; }) } }
JavaScript
class Conference extends Emitter { constructor(name, uuid, endpoint, opts) { super() ; debug('Conference#ctor'); opts = opts || {} ; this._endpoint = endpoint ; /** * conference name * @type {string} */ this.name = name ; /** * conference unique id * @type {string} */ this.uuid = uuid ; /** * file that conference is currently being recorded to * @type {String} */ this.recordFile = null ; /** * conference state * @type {Number} */ this.state = State.CREATED ; /** * true if conference is locked * @type {Boolean} */ this.locked = false ; /** * member ID of the conference control leg * @type {Number} */ this.memberId = this.endpoint.conf.memberId ; /** * current participants in the conference, keyed by member ID * @type {Map} */ this.participants = new Map() ; /** * max number of members allowed (-1 means no limit) * @type {Number} */ this.maxMembers = -1 ; // used to track play commands in progress this._playCommands = {} ; this.endpoint.filter('Conference-Unique-ID', this.uuid); this.endpoint.conn.on('esl::event::CUSTOM::*', this.__onConferenceEvent.bind(this)) ; if (opts.maxMembers) { this.endpoint.api('conference', `${name} set max_members ${opts.maxMembers}`) ; this.maxMembers = opts.maxMembers ; } } get endpoint() { return this._endpoint ; } get mediaserver() { return this.endpoint.mediaserver ; } /** * destroy the conference, releasing all legs * @param {Conference~operationCallback} callback - callback invoked when conference has been destroyed * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ destroy(callback) { debug(`Conference#destroy - destroying conference ${this.name}`); const __x = (callback) => { this.endpoint.destroy(callback) ; }; if (callback) { __x(callback) ; return this ; } return new Promise((resolve, reject) => { __x((err) => { if (err) return reject(err); resolve(); }); }); } /** * retrieve the current number of participants in the conference * @return {Promise} promise that resolves with the count of participants (including control leg) */ getSize() { return this.list('count') .then((evt) => { try { return parseInt(evt.getBody()) ; } catch (err) { throw new Error(`unexpected (non-integer) response to conference list summary: ${err}`); } }); } /** * get a conference parameter value * @param {String} param - parameter to retrieve * @param {Conference~mediaOperationCallback} [callback] - callback invoked when operation completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ get(...args) { return confOperations.get(this, ...args); } /** * set a conference parameter value * @param {String} param - parameter to set * @param {String} value - value * @param {Conference~mediaOperationCallback} [callback] - callback invoked when operation completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ set(...args) { return confOperations.set(this, ...args); } /** * adjust the automatic gain control for the conference * @param {Number|String} level - 'on', 'off', or a numeric level * @param {Conference~mediaOperationCallback} [callback] - callback invoked when operation completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ agc(...args) { return confOperations.agc(this, ...args); } /** * check the status of the conference recording * @param {Conference~mediaOperationsCallback} [callback] - callback invoked when media operations completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ chkRecord(...args) { return confOperations.chkRecord(this, ...args); } /** * deaf all the non-moderators in the conference * @param {Conference~mediaOperationsCallback} [callback] - callback invoked when media operations completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ deaf(...args) { return confOperations.deaf(this, ...args); } /** * undeaf all the non-moderators in the conference * @param {Conference~mediaOperationsCallback} [callback] - callback invoked when media operations completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ undeaf(...args) { return confOperations.undeaf(this, ...args); } /** * mute all the non-moderators in the conference * @param {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ mute(...args) { return confOperations.mute(this, ...args); } /** * unmute all the non-moderators in the conference * @param {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ unmute(...args) { return confOperations.unmute(this, ...args); } /** * lock the conference * @param {Conference~mediaOperationsCallback} [callback] - callback invoked when media operations completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ lock(...args) { return confOperations.lock(this, ...args); } /** * unlock the conference * @param {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ unlock(...args) { return confOperations.unlock(this, ...args); } /** * list members * @param {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ list(...args) { return confOperations.list(this, ...args); } /** * start recording the conference * @param {String} file - filepath to record to * @param {Conference~mediaOperationsCallback} [callback] - callback invoked when media operations completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ startRecording(file, callback) { assert.ok(typeof file === 'string', '\'file\' parameter must be provided') ; const __x = (callback) => { this.recordFile = file ; this.endpoint.api('conference ', `${this.name} recording start ${file}`, (err, evt) => { if (err) return callback(err, evt); const body = evt.getBody() ; const regexp = new RegExp(`Record file ${file}`); if (regexp.test(body)) { return callback(null, body); } callback(new Error(body)); }) ; }; if (callback) { __x(callback) ; return this ; } return new Promise((resolve, reject) => { __x((err, ...results) => { if (err) return reject(err); resolve(...results); }); }); } /** * pause the recording * @param {Conference~mediaOperationsCallback} [callback] - callback invoked when media operations completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ pauseRecording(file, callback) { const __x = (callback) => { this.recordFile = file ; this.endpoint.api('conference ', `${this.name} recording pause ${this.recordFile}`, (err, evt) => { if (err) return callback(err, evt); const body = evt.getBody() ; const regexp = new RegExp(`Pause recording file ${file}\n$`); if (regexp.test(body)) { return callback(null, body); } callback(new Error(body)); }) ; }; if (callback) { __x(callback) ; return this ; } return new Promise((resolve, reject) => { __x((err, ...results) => { if (err) return reject(err); resolve(...results); }); }); } /** * resume the recording * @param {Conference~mediaOperationsCallback} [callback] - callback invoked when media operations completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ resumeRecording(file, callback) { const __x = (callback) => { this.recordFile = file ; this.endpoint.api('conference ', `${this.name} recording resume ${this.recordFile}`, (err, evt) => { if (err) return callback(err, evt); const body = evt.getBody() ; const regexp = new RegExp(`Resume recording file ${file}\n$`); if (regexp.test(body)) { return callback(null, body); } callback(new Error(body)); }); }; if (callback) { __x(callback) ; return this ; } return new Promise((resolve, reject) => { __x((err, ...results) => { if (err) return reject(err); resolve(...results); }); }); } /** * stop the conference recording * @param {Conference~mediaOperationsCallback} [callback] - callback invoked when media operations completes * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ stopRecording(file, callback) { const __x = (callback) => { this.endpoint.api('conference ', `${this.name} recording stop ${this.recordFile}`, (err, evt) => { if (err) return callback(err, evt); const body = evt.getBody() ; const regexp = new RegExp(`Stopped recording file ${file}`); if (regexp.test(body)) { return callback(null, body); } callback(new Error(body)); }) ; this.recordFile = null ; }; if (callback) { __x(callback) ; return this ; } return new Promise((resolve, reject) => { __x((err, ...results) => { if (err) return reject(err); resolve(...results); }); }); } /** * play an audio file or files into the conference * @param {string|Array} file file (or array of files) to play * @param {Conference~playOperationCallback} [callback] - callback invoked when the files have completed playing * @return {Promise|Conference} returns a Promise if no callback supplied; otherwise * a reference to the Conference object */ play(file, callback) { assert.ok('string' === typeof file || _.isArray(file), 'file param is required and must be a string or array') ; const __x = (callback) => { const files = typeof file === 'string' ? [file] : file ; // each call to conference play queues the file up; // i.e. the callback returns immediately upon successful queueing, // not when the file has finished playing const queued = [] ; async.eachSeries(files, (f, callback) => { this.endpoint.api('conference', `${this.name} play ${f}`, (err, result) => { if (err) return callback(err); if (result && result.body && -1 !== result.body.indexOf(' not found.')) { debug(`file ${f} was not queued because it was not found, or conference is empty`); } else { queued.push(f) ; } callback(null) ; }) ; }, () => { debug(`files have been queued for playback into conference: ${queued}`) ; if (queued.length > 0) { const firstFile = queued[0] ; const obj = { remainingFiles: queued.slice(1), seconds: 0, milliseconds: 0, samples: 0, done: callback }; this._playCommands[firstFile] = this._playCommands[firstFile] || [] ; this._playCommands[firstFile].push(obj) ; } else { // no files actually got queued, so execute the callback debug('Conference#play: no files were queued for callback, so invoking callback immediately') ; callback(null, { seconds: 0, milliseconds: 0, samples: 0 }) ; } }) ; }; if (callback) { __x(callback) ; return this ; } return new Promise((resolve, reject) => { __x((err, ...results) => { if (err) return reject(err); resolve(...results); }); }); } _onAddMember(evt) { debug(`Conference#_onAddMember: ${JSON.stringify(this)}`) ; const size = parseInt(evt.getHeader('Conference-Size')); //includes control leg const newMemberId = parseInt(evt.getHeader('Member-ID')) ; const memberType = evt.getHeader('Member-Type') ; const memberGhost = evt.getHeader('Member-Ghost') ; const channelUuid = evt.getHeader('Channel-Call-UUID') ; const obj = { memberId: newMemberId, type: memberType, ghost: memberGhost, channelUuid: channelUuid } ; this.participants.set(newMemberId, obj) ; debug(`Conference#_onAddMember: added member ${newMemberId} to ${this.name} size is ${size}`) ; } _onDelMember(evt) { const memberId = parseInt(evt.getHeader('Member-ID')) ; const size = parseInt(evt.getHeader('Conference-Size')); // includes control leg this.participants.delete(memberId) ; debug(`Conference#_onDelMember: removed member ${memberId} from ${this.name} size is ${size}`) ; } _onStartTalking(evt) { debug(`Conf ${this.name}:${this.uuid} member ${evt.getHeader('Member-ID')} started talking`) ; } _onStopTalking(evt) { debug(`Conf ${this.name}:${this.uuid} member ${evt.getHeader('Member-ID')} stopped talking`) ; } _onMuteDetect(evt) { debug(`Conf ${this.name}:${this.uuid} muted member ${evt.getHeader('Member-ID')} is talking`) ; } _onUnmuteMember(evt) { debug(`Conf ${this.name}:${this.uuid} member ${evt.getHeader('Member-ID')} has been unmuted`) ; } _onMuteMember(evt) { debug(`Conf ${this.name}:${this.uuid} member ${evt.getHeader('Member-ID')} has been muted`) ; } _onKickMember(evt) { debug(`Conf ${this.name}:${this.uuid} member ${evt.getHeader('Member-ID')} has been kicked`) ; } _onDtmfMember(evt) { debug(`Conf ${this.name}:${this.uuid} member ${evt.getHeader('Member-ID')} has entered DTMF`) ; } _onStartRecording(evt) { debug(`Conference#_onStartRecording: ${this.name}:${this.uuid} ${JSON.stringify(evt)}`); const err = evt.getHeader('Error'); if (err) { const path = evt.getHeader('Path'); console.log(`Conference#_onStartRecording: failed to start recording to ${path}: ${err}`); } } _onStopRecording(evt) { debug(`Conference#_onStopRecording: ${this.name}:${this.uuid} ${JSON.stringify(evt)}`); } _onPlayFile(evt) { const confName = evt.getHeader('Conference-Name') ; const file = evt.getHeader('File') ; debug(`conference-level play has started: ${confName}: ${file}`); } _onPlayFileMember(evt) { debug(`member-level play for member ${evt.getHeader('Member-ID')} has completed`) ; } _onPlayFileDone(evt) { const confName = evt.getHeader('Conference-Name') ; const file = evt.getHeader('File') ; const seconds = parseInt(evt.getHeader('seconds')) ; const milliseconds = parseInt(evt.getHeader('milliseconds')) ; const samples = parseInt(evt.getHeader('samples')) ; debug(`conference-level play has completed: ${confName}: ${file} ${seconds} seconds, ${milliseconds} milliseconds, ${samples} samples`); // check if the caller registered a callback for this play done const el = this._playCommands[file] ; if (el) { assert(_.isArray(el), 'Conference#onPlayFileDone: this._playCommands must be an array') ; const obj = el[0] ; obj.seconds += seconds ; obj.milliseconds += milliseconds ; obj.samples += samples ; if (0 === obj.remainingFiles.length) { // done playing all files in this request obj.done(null, { seconds: obj.seconds, milliseconds: obj.milliseconds, samples: obj.samples }) ; } else { const firstFile = obj.remainingFiles[0] ; obj.remainingFiles = obj.remainingFiles.slice(1) ; this._playCommands[firstFile] = this._playCommands[firstFile] || [] ; this._playCommands[firstFile].push(obj) ; } this._playCommands[file] = this._playCommands[file].slice(1) ; if (0 === this._playCommands[file].length) { //done with all queued requests for this file delete this._playCommands[file] ; } } } _onLock(evt) { debug(`conference has been locked: ${JSON.stringify(evt)}`) ; } _onUnlock(evt) { debug(`conference has been unlocked: ${JSON.stringify(evt)}`) ; } _onTransfer(evt) { debug(`member has been transferred to another conference: ${JSON.stringify(evt)}`) ; } _onRecord(evt) { debug(`conference record has started or stopped: ${evt}`) ; } __onConferenceEvent(evt) { const eventName = evt.getHeader('Event-Subclass') ; if (eventName === 'conference::maintenance') { const action = evt.getHeader('Action') ; debug(`Conference#__onConferenceEvent: conference event action: ${action}`) ; //invoke a handler for this action, if we have defined one const eventName = _.camelCase(action); this.emit(eventName, evt); (Conference.prototype[`_on${_.upperFirst(_.camelCase(action))}`] || unhandled).bind(this, evt)() ; } else { debug(`Conference#__onConferenceEvent: got unhandled custom event: ${eventName}`) ; } } toJSON() { return only(this, 'name state uuid memberId confConn endpoint maxMembers locked recordFile') ; } toString() { return this.toJSON().toString() ; } }
JavaScript
class ProcessDataSource extends DataSource { constructor(refreshDelay) { super(refreshDelay); this.previousTimestamp = Date.now(); this.previousCpuUsage = process.cpuUsage(); } doRefresh(callback) { const currentTimestamp = Date.now(); let cpuUsageDiff; if (currentTimestamp <= this.previousTimestamp + 50) { // This can happen when the source is activated directly after being created. We skip the first measurement when // the time delta is too small. cpuUsageDiff = {}; } else { cpuUsageDiff = process.cpuUsage(this.previousCpuUsage); } const previousTimestamp = this.previousTimestamp; this.previousTimestamp = currentTimestamp; this.previousCpuUsage = process.cpuUsage(); process.nextTick(() => { callback(null, { cpuUsageDiff, timeDelta: currentTimestamp - previousTimestamp }); }); } }
JavaScript
class CaseSegregation extends Component { constructor(props) { super(props); this.state = { auth: this.props.auth, variant: this.props.variant, interpretation: this.props.interpretation, curatedEvidences: this.props.curatedEvidences, allCaseSegregationEvidences: [], interpretationCaseSegEvidences: [], interpretationCaseSegOldArticleEvidences: [] }; } componentDidMount = () => { // Get case segregation evidences and store in state const allCaseSegregationEvidences = this.getAllCaseSegEvidences(); const interpretationCaseSegEvidences = this.getInterpretaionCuratedEvidences(); const interpretationCaseSegOldArticleEvidences = this.getInterpretationOldArticleEvidences(); this.setState({ allCaseSegregationEvidences, interpretationCaseSegEvidences, interpretationCaseSegOldArticleEvidences, }); }; componentDidUpdate = (prevProps) => { // Reset case segregation evidences if things changed if ((this.props.interpretation !== prevProps.interpretation) || (this.props.curatedEvidences !== prevProps.curatedEvidences)) { const allCaseSegregationEvidences = this.getAllCaseSegEvidences(); const interpretationCaseSegEvidences = this.getInterpretaionCuratedEvidences(); const interpretationCaseSegOldArticleEvidences = this.getInterpretationOldArticleEvidences(); this.setState({ allCaseSegregationEvidences, interpretationCaseSegEvidences, interpretationCaseSegOldArticleEvidences, }); } }; componentWillUnmount = () => { }; getAllCaseSegEvidences = () => { // get the list of case segregation curated evidences in all interpretations of current variant // but only include evidences that are curated in new format with sourceInfo data const caseSegCuratedEvidences = ( this.props.curatedEvidences.byCategory["case-segregation"] || [] ) .map((PK) => this.props.curatedEvidences.byPK[PK]) .filter((curatedEvidence) => curatedEvidenceHasSourceInfo(curatedEvidence)); const relevantEvidenceList = lodashOrderBy( caseSegCuratedEvidences, ["date_created"], "desc" ); return relevantEvidenceList; }; getInterpretaionCuratedEvidences = () => { // Get the list of case segregation curated evidences in current interpretation // but only include evidences that are curated in new format with sourceInfo data if (!isEmpty(this.props.interpretation)) { const curatedEvidenceList = ( this.props.interpretation.curated_evidence_list || [] ) .map((PK) => this.props.curatedEvidences.byPK[PK]) .filter((curatedEvidence) => (curatedEvidence && 'category' in curatedEvidence) && (curatedEvidence.category === "case-segregation")) .filter((curatedEvidence) => curatedEvidenceHasSourceInfo(curatedEvidence)); return curatedEvidenceList; } return []; }; getInterpretationOldArticleEvidences = () => { // Get the list of case segregation old article evidences in current interpretation // include evidences that has no sourceInfo data if (!isEmpty(this.props.interpretation)) { const articleEvidenceList = ( this.props.interpretation.curated_evidence_list || [] ) .map((PK) => this.props.curatedEvidences.byPK[PK]) .filter((curatedEvidence) => (curatedEvidence && 'category' in curatedEvidence) && curatedEvidence.category === "case-segregation") .filter((curatedEvidence) => !curatedEvidenceHasSourceInfo(curatedEvidence)); return articleEvidenceList; } return []; }; hasOldArticleEvidence = (subcategory) => { const articleEvidences = ( this.state.interpretationCaseSegOldArticleEvidences || [] ) .filter((articleEvidence) => articleEvidence.subcategory === subcategory); return articleEvidences.length; }; renderMasterTable = () => { return ( <MasterEvidenceTable allCaseSegEvidences = {this.state.allCaseSegregationEvidences} readOnly={this.props.variant && isEmpty(this.props.interpretation)} auth={this.props.auth} /> ); }; render = () => { const { view, selectChange, textChange, alert, loading, evaluations, cspecCriteria, onSubmitEval } = this.props; const infoText = 'The evidence shown in this table was added in a format that has now been retired. To include retired format evidence in the new granular format then you will have to re-add each one manually. You can start this process by clicking the "Add in New Format" button next to each evidence. Once you have transferred a retired format evidence to the new format and it appears in the new table, then please go ahead and delete the retired format version.'; const infoPopover = <Popover triggerComponent={<FontAwesomeIcon className="text-info" icon={faInfoCircle}/>} content={infoText} placement="top" /> const panel_data = [ { title: 'Observed in healthy adult(s)', key: 1, bodyClassName: 'panel-wide-content', panelClassName: 'tab-segegration-panel-observed-in-healthy', criteria: ['BS2'], loadingId: 'BS2', curatedEvidence: { subcategory: 'observed-in-healthy', tableName: <span>Curated Evidence (Observed in healthy adult(s))</span>, oldTableName: <span>Curated Literature Evidence (Observed in healthy adult(s)) - Retired Format - {infoPopover}</span> } }, { title: 'Case-control', key: 2, bodyClassName: 'panel-wide-content', panelClassName: 'tab-segegration-panel-case-control', criteria: ['PS4'], loadingId: 'PS4', curatedEvidence: { subcategory: 'case-control', tableName: <span>Curated Evidence (Case-control)</span>, oldTableName: <span>Curated Literature Evidence (Case-control) - Retired Format - {infoPopover}</span> } }, { title: 'Segregation data', key: 3, bodyClassName: 'panel-wide-content', panelClassName: 'tab-segegration-panel-segregation-data', criteria: ['BS4', 'PP1'], criteriaCrossCheck: [['BS4'], ['PP1']], loadingId: 'BS4', curatedEvidence: { subcategory: 'segregation-data', tableName: <span>Curated Evidence (Segregation data)</span>, oldTableName: <span>Curated Literature Evidence (Segregation data) - Retired Format - {infoPopover}</span> } }, { title: <span><i>de novo</i> occurrence</span>, key: 4, bodyClassName: 'panel-wide-content', panelClassName: 'tab-segegration-panel-de-novo', criteria: ['PM6', 'PS2'], criteriaCrossCheck: [['PM6'], ['PS2']], loadingId: 'PM6', curatedEvidence: { subcategory: 'de-novo', tableName: <span>Curated Evidence (<i>de novo</i> occurrence)</span>, oldTableName: <span>Curated Literature Evidence (<i>de novo</i> occurrence) - Retired Format - {infoPopover}</span> } }, { title: <span>Allele data (<i>cis/trans</i>)</span>, key: 5, bodyClassName: 'panel-wide-content', panelClassName: 'tab-segegration-panel-allele-data', criteria: ['BP2', 'PM3'], criteriaCrossCheck: [['BP2'], ['PM3']], loadingId: 'BP2', curatedEvidence: { subcategory: 'allele-data', tableName: <span>Curated Evidence (Allele Data (<i>cis/trans</i>))</span>, oldTableName: <span>Curated Literature Evidence (Allele Data (<i>cis/trans</i>)) - Retired Format - {infoPopover}</span> } }, { title: 'Alternate mechanism for disease', key: 6, bodyClassName: 'panel-wide-content', panelClassName: 'tab-segegration-panel-alternate-mechanism', criteria: ['BP5'], loadingId: 'BP5', curatedEvidence: { subcategory: 'alternate-mechanism', tableName: <span>Curated Evidence (Alternate mechanism for disease)</span>, oldTableName: <span>Curated Literature Evidence (Alternate mechanism for disease) - Retired Format - {infoPopover}</span> } }, { title: 'Specificity of phenotype', key: 7, bodyClassName: 'panel-wide-content', panelClassName: 'tab-segegration-panel-specificity-of-phenotype', criteria: ['PP4'], loadingId: 'PP4', curatedEvidence: { subcategory: 'specificity-of-phenotype', tableName: <span>Curated Evidence (Specificity of phenotype)</span>, oldTableName: <span>Curated Literature Evidence (Specificity of phenotype) - Retired Format - {infoPopover}</span> } } ]; // Props to pass to every Evaluation Form const formProps = { textChange: textChange, selectChange: selectChange, onSubmitEval: onSubmitEval, }; const panelsWithCuratedEvidences = panel_data.map(panel => { const criteriaArray = []; criteriaArray.push(panel.criteria); let evaluationForm = null; if (view === "Interpretation") { const criteriaArray = []; criteriaArray.push(panel.criteria); evaluationForm = <EvaluationForm {...formProps} evaluations={evaluationsByGroup(criteriaArray, evaluations)} criteria={filterCodeStripObjects(panel.criteria)} criteriaGroups={criteriaArray} cspecCriteria={cspecCriteria} criteriaCrossCheck={panel.criteriaCrossCheck} loading={loading[panel.loadingId]} alert={alert && alert.id === panel.loadingId ? alert : {}} /> } const addCuratedEvidenceTable = <AddCuratedEvidenceTable tableName={panel.curatedEvidence.tableName} category="case-segregation" subcategory={panel.curatedEvidence.subcategory} criteriaList={panel.criteria} readOnly={this.props.variant && isEmpty(this.props.interpretation)} allCaseSegEvidences = {this.state.allCaseSegregationEvidences} interpretationCaseSegEvidences = {this.state.interpretationCaseSegEvidences} auth={this.props.auth} /> // need to add old evidence table to support old case segregation evidences const oldEvidenceTable = <CardPanel title={panel.curatedEvidence.oldTableName}> <AddArticleEvidenceTableView category="case-segregation" subcategory={panel.curatedEvidence.subcategory} criteriaList={panel.criteria} /> </CardPanel> return ( <CardPanel key={panel.key} title={panel.title} > {evaluationForm} {addCuratedEvidenceTable} {this.hasOldArticleEvidence(panel.curatedEvidence.subcategory) > 0 && ( oldEvidenceTable )} </CardPanel> ); }); return ( <> {view === "Interpretation" && ( <p className="alert alert-warning"> All information entered and accessed in the ClinGen curation interfaces should be considered publicly accessible, and may not include <a className="external-link" target="_blank" rel="noopener noreferrer" href="//www.hipaajournal.com/considered-phi-hipaa/">protected health information (PHI)</a> or equivalent identifiable information as defined by regulations in your country or region. For more information about ClinGen policies on data sharing, please refer to the <a className="external-link" target="_blank" href="/terms-of-use">Terms of Use</a>. </p> )} {this.renderMasterTable()} {panelsWithCuratedEvidences} <CardPanel key="reputable-section" title="Reputable source"> {view === "Interpretation" && ( <Row> <Col sm="12"> <p className="alert alert-warning">ClinGen has determined that the following rules should not be applied in any context.</p> <EvaluationForm {...formProps} evaluations = {evaluationsByGroup([['BP6', 'PP5']], evaluations)} criteria = {filterCodeStripObjects(['BP6', 'PP5'])} criteriaGroups = {[['BP6', 'PP5']]} cspecCriteria={cspecCriteria} disabled /> </Col> </Row> )} </CardPanel> {view === "Interpretation" && ( <CompleteSection tabName="segregation-case" updateTab={this.props.updateTab} /> )} </> ); } }
JavaScript
class FirestoreClient { /** * Construct an instance of FirestoreClient. * * @param {object} [options] - The configuration object. See the subsequent * parameters for more details. * @param {object} [options.credentials] - Credentials object. * @param {string} [options.credentials.client_email] * @param {string} [options.credentials.private_key] * @param {string} [options.email] - Account email address. Required when * using a .pem or .p12 keyFilename. * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or * .p12 key downloaded from the Google Developers Console. If you provide * a path to a JSON file, the projectId option below is not necessary. * NOTE: .pem and .p12 require you to specify options.email as well. * @param {number} [options.port] - The port on which to connect to * the remote host. * @param {string} [options.projectId] - The project ID from the Google * Developer's Console, e.g. 'grape-spaceship-123'. We will also check * the environment variable GCLOUD_PROJECT for your project ID. If your * app is running in an environment which supports * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. * @param {function} [options.promise] - Custom promise module to use instead * of native Promises. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. */ constructor(opts) { this._descriptors = { page: {}, stream: {}, longrunning: {} }; this._terminated = false; // Ensure that options include the service address and port. const staticMembers = this.constructor; const servicePath = opts && opts.servicePath ? opts.servicePath : opts && opts.apiEndpoint ? opts.apiEndpoint : staticMembers.servicePath; const port = opts && opts.port ? opts.port : staticMembers.port; if (!opts) { opts = { servicePath, port }; } opts.servicePath = opts.servicePath || servicePath; opts.port = opts.port || port; opts.clientConfig = opts.clientConfig || {}; const isBrowser = typeof window !== 'undefined'; if (isBrowser) { opts.fallback = true; } // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = this.constructor.scopes; const gaxGrpc = new gaxModule.GrpcClient(opts); // Save the auth object to the client, for use by other methods. this.auth = gaxGrpc.auth; // Determine the client header string. const clientHeader = [`gax/${gaxModule.version}`, `gapic/${version}`]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { clientHeader.push(`gl-web/${gaxModule.version}`); } if (!opts.fallback) { clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); } // Load the applicable protos. // For Node.js, pass the path to JSON proto file. // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); const protos = gaxGrpc.loadProto(opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this._descriptors.page = { listDocuments: new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'documents'), listCollectionIds: new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'collectionIds'), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this._descriptors.stream = { batchGetDocuments: new gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING), runQuery: new gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING), write: new gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING), listen: new gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING), }; // Put together the default options sent with requests. const defaults = gaxGrpc.constructSettings('google.firestore.v1.Firestore', gapicConfig, opts.clientConfig || {}, { 'x-goog-api-client': clientHeader.join(' ') }); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; // Put together the "service stub" for // google.firestore.v1.Firestore. this.firestoreStub = gaxGrpc.createStub(opts.fallback ? protos.lookupService('google.firestore.v1.Firestore') : // tslint:disable-next-line no-any protos.google.firestore.v1.Firestore, opts); // Iterate over each of the methods that the service provides // and create an API call method for each. const firestoreStubMethods = [ 'getDocument', 'listDocuments', 'createDocument', 'updateDocument', 'deleteDocument', 'batchGetDocuments', 'beginTransaction', 'commit', 'rollback', 'runQuery', 'write', 'listen', 'listCollectionIds', ]; for (const methodName of firestoreStubMethods) { const innerCallPromise = this.firestoreStub.then(stub => (...args) => { if (this._terminated) { return Promise.reject('The client has already been closed.'); } return stub[methodName].apply(stub, args); }, (err) => () => { throw err; }); const apiCall = gaxModule.createApiCall(innerCallPromise, defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName]); this._innerApiCalls[methodName] = (argument, callOptions, callback) => { return apiCall(argument, callOptions, callback); }; } } /** * The DNS address for this API service. */ static get servicePath() { return 'firestore.googleapis.com'; } /** * The DNS address for this API service - same as servicePath(), * exists for compatibility reasons. */ static get apiEndpoint() { return 'firestore.googleapis.com'; } /** * The port for this API service. */ static get port() { return 443; } /** * The scopes needed to make gRPC calls for every method defined * in this service. */ static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/datastore', ]; } /** * Return the project ID used by this class. * @param {function(Error, string)} callback - the callback to * be called with the current project Id. */ getProjectId(callback) { if (callback) { this.auth.getProjectId(callback); return; } return this.auth.getProjectId(); } /** * Gets a single document. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The resource name of the Document to get. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * @param {google.firestore.v1.DocumentMask} request.mask * The fields to return. If not set, returns all fields. * * If the document has a field that is not present in this mask, that field * will not be returned in the response. * @param {Buffer} request.transaction * Reads the document in a transaction. * @param {google.protobuf.Timestamp} request.readTime * Reads the version of the document at the given time. * This may not be older than 60 seconds. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Document]{@link google.firestore.v1.Document}. * The promise has a method named "cancel" which cancels the ongoing API call. */ getDocument(request, optionsOrCallback, callback) { request = request || {}; let options; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); return this._innerApiCalls.getDocument(request, options, callback); } /** * Creates a new document. * * @param {Object} request * The request object that will be sent. * @param {string} request.parent * Required. The parent resource. For example: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` * @param {string} request.collectionId * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`. * @param {string} request.documentId * The client-assigned document ID to use for this document. * * Optional. If not specified, an ID will be assigned by the service. * @param {google.firestore.v1.Document} request.document * Required. The document to create. `name` must not be set. * @param {google.firestore.v1.DocumentMask} request.mask * The fields to return. If not set, returns all fields. * * If the document has a field that is not present in this mask, that field * will not be returned in the response. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Document]{@link google.firestore.v1.Document}. * The promise has a method named "cancel" which cancels the ongoing API call. */ createDocument(request, optionsOrCallback, callback) { request = request || {}; let options; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ parent: request.parent || '', }); return this._innerApiCalls.createDocument(request, options, callback); } /** * Updates or inserts a document. * * @param {Object} request * The request object that will be sent. * @param {google.firestore.v1.Document} request.document * Required. The updated document. * Creates the document if it does not already exist. * @param {google.firestore.v1.DocumentMask} request.updateMask * The fields to update. * None of the field paths in the mask may contain a reserved name. * * If the document exists on the server and has fields not referenced in the * mask, they are left unchanged. * Fields referenced in the mask, but not present in the input document, are * deleted from the document on the server. * @param {google.firestore.v1.DocumentMask} request.mask * The fields to return. If not set, returns all fields. * * If the document has a field that is not present in this mask, that field * will not be returned in the response. * @param {google.firestore.v1.Precondition} request.currentDocument * An optional precondition on the document. * The request will fail if this is set and not met by the target document. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Document]{@link google.firestore.v1.Document}. * The promise has a method named "cancel" which cancels the ongoing API call. */ updateDocument(request, optionsOrCallback, callback) { request = request || {}; let options; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ 'document.name': request.document.name || '', }); return this._innerApiCalls.updateDocument(request, options, callback); } /** * Deletes a document. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The resource name of the Document to delete. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * @param {google.firestore.v1.Precondition} request.currentDocument * An optional precondition on the document. * The request will fail if this is set and not met by the target document. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}. * The promise has a method named "cancel" which cancels the ongoing API call. */ deleteDocument(request, optionsOrCallback, callback) { request = request || {}; let options; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); return this._innerApiCalls.deleteDocument(request, options, callback); } /** * Starts a new transaction. * * @param {Object} request * The request object that will be sent. * @param {string} request.database * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. * @param {google.firestore.v1.TransactionOptions} request.options * The options for the transaction. * Defaults to a read-write transaction. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [BeginTransactionResponse]{@link google.firestore.v1.BeginTransactionResponse}. * The promise has a method named "cancel" which cancels the ongoing API call. */ beginTransaction(request, optionsOrCallback, callback) { request = request || {}; let options; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ database: request.database || '', }); return this._innerApiCalls.beginTransaction(request, options, callback); } /** * Commits a transaction, while optionally updating documents. * * @param {Object} request * The request object that will be sent. * @param {string} request.database * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. * @param {number[]} request.writes * The writes to apply. * * Always executed atomically and in order. * @param {Buffer} request.transaction * If set, applies all writes in this transaction, and commits it. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [CommitResponse]{@link google.firestore.v1.CommitResponse}. * The promise has a method named "cancel" which cancels the ongoing API call. */ commit(request, optionsOrCallback, callback) { request = request || {}; let options; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ database: request.database || '', }); return this._innerApiCalls.commit(request, options, callback); } /** * Rolls back a transaction. * * @param {Object} request * The request object that will be sent. * @param {string} request.database * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. * @param {Buffer} request.transaction * Required. The transaction to roll back. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}. * The promise has a method named "cancel" which cancels the ongoing API call. */ rollback(request, optionsOrCallback, callback) { request = request || {}; let options; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ database: request.database || '', }); return this._innerApiCalls.rollback(request, options, callback); } /** * Gets multiple documents. * * Documents returned by this method are not guaranteed to be returned in the * same order that they were requested. * * @param {Object} request * The request object that will be sent. * @param {string} request.database * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. * @param {string[]} request.documents * The names of the documents to retrieve. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * The request will fail if any of the document is not a child resource of the * given `database`. Duplicate names will be elided. * @param {google.firestore.v1.DocumentMask} request.mask * The fields to return. If not set, returns all fields. * * If a document has a field that is not present in this mask, that field will * not be returned in the response. * @param {Buffer} request.transaction * Reads documents in a transaction. * @param {google.firestore.v1.TransactionOptions} request.newTransaction * Starts a new transaction and reads the documents. * Defaults to a read-only transaction. * The new transaction ID will be returned as the first response in the * stream. * @param {google.protobuf.Timestamp} request.readTime * Reads documents as they were at the given time. * This may not be older than 60 seconds. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which emits [BatchGetDocumentsResponse]{@link google.firestore.v1.BatchGetDocumentsResponse} on 'data' event. */ batchGetDocuments(request, options) { request = request || {}; options = options || {}; return this._innerApiCalls.batchGetDocuments(request, options); } /** * Runs a query. * * @param {Object} request * The request object that will be sent. * @param {string} request.parent * Required. The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` * @param {google.firestore.v1.StructuredQuery} request.structuredQuery * A structured query. * @param {Buffer} request.transaction * Reads documents in a transaction. * @param {google.firestore.v1.TransactionOptions} request.newTransaction * Starts a new transaction and reads the documents. * Defaults to a read-only transaction. * The new transaction ID will be returned as the first response in the * stream. * @param {google.protobuf.Timestamp} request.readTime * Reads documents as they were at the given time. * This may not be older than 60 seconds. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which emits [RunQueryResponse]{@link google.firestore.v1.RunQueryResponse} on 'data' event. */ runQuery(request, options) { request = request || {}; options = options || {}; return this._innerApiCalls.runQuery(request, options); } /** * Streams batches of document updates and deletes, in order. * * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which is both readable and writable. It accepts objects * representing [WriteRequest]{@link google.firestore.v1.WriteRequest} for write() method, and * will emit objects representing [WriteResponse]{@link google.firestore.v1.WriteResponse} on 'data' event asynchronously. */ write(options) { options = options || {}; return this._innerApiCalls.write(options); } /** * Listens to changes. * * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which is both readable and writable. It accepts objects * representing [ListenRequest]{@link google.firestore.v1.ListenRequest} for write() method, and * will emit objects representing [ListenResponse]{@link google.firestore.v1.ListenResponse} on 'data' event asynchronously. */ listen(options) { options = options || {}; return this._innerApiCalls.listen({}, options); } /** * Lists documents. * * @param {Object} request * The request object that will be sent. * @param {string} request.parent * Required. The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` * @param {string} request.collectionId * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` * or `messages`. * @param {number} request.pageSize * The maximum number of documents to return. * @param {string} request.pageToken * The `next_page_token` value returned from a previous List request, if any. * @param {string} request.orderBy * The order to sort results by. For example: `priority desc, name`. * @param {google.firestore.v1.DocumentMask} request.mask * The fields to return. If not set, returns all fields. * * If a document has a field that is not present in this mask, that field * will not be returned in the response. * @param {Buffer} request.transaction * Reads documents in a transaction. * @param {google.protobuf.Timestamp} request.readTime * Reads documents as they were at the given time. * This may not be older than 60 seconds. * @param {boolean} request.showMissing * If the list should show missing documents. A missing document is a * document that does not exist but has sub-documents. These documents will * be returned with a key but will not have fields, [Document.create_time][google.firestore.v1.Document.create_time], * or [Document.update_time][google.firestore.v1.Document.update_time] set. * * Requests with `show_missing` may not specify `where` or * `order_by`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is Array of [Document]{@link google.firestore.v1.Document}. * The client library support auto-pagination by default: it will call the API as many * times as needed and will merge results from all the pages into this array. * * When autoPaginate: false is specified through options, the array has three elements. * The first element is Array of [Document]{@link google.firestore.v1.Document} that corresponds to * the one page received from the API server. * If the second element is not null it contains the request object of type [ListDocumentsRequest]{@link google.firestore.v1.ListDocumentsRequest} * that can be used to obtain the next page of the results. * If it is null, the next page does not exist. * The third element contains the raw response received from the API server. Its type is * [ListDocumentsResponse]{@link google.firestore.v1.ListDocumentsResponse}. * * The promise has a method named "cancel" which cancels the ongoing API call. */ listDocuments(request, optionsOrCallback, callback) { request = request || {}; let options; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ parent: request.parent || '', }); return this._innerApiCalls.listDocuments(request, options, callback); } /** * Equivalent to {@link listDocuments}, but returns a NodeJS Stream object. * * This fetches the paged responses for {@link listDocuments} continuously * and invokes the callback registered for 'data' event for each element in the * responses. * * The returned object has 'end' method when no more elements are required. * * autoPaginate option will be ignored. * * @see {@link https://nodejs.org/api/stream.html} * * @param {Object} request * The request object that will be sent. * @param {string} request.parent * Required. The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` * @param {string} request.collectionId * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` * or `messages`. * @param {number} request.pageSize * The maximum number of documents to return. * @param {string} request.pageToken * The `next_page_token` value returned from a previous List request, if any. * @param {string} request.orderBy * The order to sort results by. For example: `priority desc, name`. * @param {google.firestore.v1.DocumentMask} request.mask * The fields to return. If not set, returns all fields. * * If a document has a field that is not present in this mask, that field * will not be returned in the response. * @param {Buffer} request.transaction * Reads documents in a transaction. * @param {google.protobuf.Timestamp} request.readTime * Reads documents as they were at the given time. * This may not be older than 60 seconds. * @param {boolean} request.showMissing * If the list should show missing documents. A missing document is a * document that does not exist but has sub-documents. These documents will * be returned with a key but will not have fields, [Document.create_time][google.firestore.v1.Document.create_time], * or [Document.update_time][google.firestore.v1.Document.update_time] set. * * Requests with `show_missing` may not specify `where` or * `order_by`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which emits an object representing [Document]{@link google.firestore.v1.Document} on 'data' event. */ listDocumentsStream(request, options) { request = request || {}; const callSettings = new gax.CallSettings(options); return this._descriptors.page.listDocuments.createStream(this._innerApiCalls.listDocuments, request, callSettings); } /** * Lists all the collection IDs underneath a document. * * @param {Object} request * The request object that will be sent. * @param {string} request.parent * Required. The parent document. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` * @param {number} request.pageSize * The maximum number of results to return. * @param {string} request.pageToken * A page token. Must be a value from * [ListCollectionIdsResponse][google.firestore.v1.ListCollectionIdsResponse]. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is Array of string. * The client library support auto-pagination by default: it will call the API as many * times as needed and will merge results from all the pages into this array. * * When autoPaginate: false is specified through options, the array has three elements. * The first element is Array of string that corresponds to * the one page received from the API server. * If the second element is not null it contains the request object of type [ListCollectionIdsRequest]{@link google.firestore.v1.ListCollectionIdsRequest} * that can be used to obtain the next page of the results. * If it is null, the next page does not exist. * The third element contains the raw response received from the API server. Its type is * [ListCollectionIdsResponse]{@link google.firestore.v1.ListCollectionIdsResponse}. * * The promise has a method named "cancel" which cancels the ongoing API call. */ listCollectionIds(request, optionsOrCallback, callback) { request = request || {}; let options; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ parent: request.parent || '', }); return this._innerApiCalls.listCollectionIds(request, options, callback); } /** * Equivalent to {@link listCollectionIds}, but returns a NodeJS Stream object. * * This fetches the paged responses for {@link listCollectionIds} continuously * and invokes the callback registered for 'data' event for each element in the * responses. * * The returned object has 'end' method when no more elements are required. * * autoPaginate option will be ignored. * * @see {@link https://nodejs.org/api/stream.html} * * @param {Object} request * The request object that will be sent. * @param {string} request.parent * Required. The parent document. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` * @param {number} request.pageSize * The maximum number of results to return. * @param {string} request.pageToken * A page token. Must be a value from * [ListCollectionIdsResponse][google.firestore.v1.ListCollectionIdsResponse]. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which emits an object representing string on 'data' event. */ listCollectionIdsStream(request, options) { request = request || {}; const callSettings = new gax.CallSettings(options); return this._descriptors.page.listCollectionIds.createStream(this._innerApiCalls.listCollectionIds, request, callSettings); } /** * Terminate the GRPC channel and close the client. * * The client will no longer be usable and all future behavior is undefined. */ close() { if (!this._terminated) { return this.firestoreStub.then(stub => { this._terminated = true; stub.close(); }); } return Promise.resolve(); } }
JavaScript
class Collection extends Map { /** * Returns an ordered array of the values of this collection. * @returns {array} * @example * // identical to: * Array.from(collection.values()); */ array() { return Array.from(this.values()); } /** * Returns the first item in this collection. * @returns {*} * @example * // identical to: * Array.from(collection.values())[0]; */ first() { return this.values().next().value; } /** * Returns the last item in this collection. This is a relatively slow operation, * since an array copy of the values must be made to find the last element. * @returns {*} */ last() { const arr = this.array(); return arr[arr.length - 1]; } /** * Returns a random item from this collection. This is a relatively slow operation, * since an array copy of the values must be made to find a random element. * @returns {*} */ random() { const arr = this.array(); return arr[Math.floor(Math.random() * arr.length)]; } /** * If the items in this collection have a delete method (e.g. messages), invoke * the delete method. Returns an array of promises * @returns {Promise[]} */ deleteAll() { const returns = []; for (const item of this.values()) { if (item.delete) returns.push(item.delete()); } return returns; } /** * Returns an array of items where `item[key] === value` of the collection * @param {string} key The key to filter by * @param {*} value The expected value * @returns {array} * @example * collection.getAll('username', 'Bob'); */ findAll(key, value) { if (typeof key !== 'string') throw new TypeError('key must be a string'); if (typeof value === 'undefined') throw new Error('value must be specified'); const results = []; for (const item of this.values()) { if (item[key] === value) results.push(item); } return results; } /** * Returns a single item where `item[key] === value` * @param {string} key The key to filter by * @param {*} value The expected value * @returns {*} * @example * collection.get('id', '123123...'); */ find(key, value) { if (typeof key !== 'string') throw new TypeError('key must be a string'); if (typeof value === 'undefined') throw new Error('value must be specified'); for (const item of this.values()) { if (item[key] === value) return item; } return null; } /** * Returns true if the collection has an item where `item[key] === value` * @param {string} key The key to filter by * @param {*} value The expected value * @returns {boolean} * @example * if (collection.exists('id', '123123...')) { * console.log('user here!'); * } */ exists(key, value) { return Boolean(this.find(key, value)); } /** * Identical to * [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), * but returns a Collection instead of an Array. * @param {function} callback Function used to filter (should return a boolean) * @param {Object} [thisArg] Value to set as this when filtering * @returns {Collection} */ filter(...args) { const newArray = this.array().filter(...args); const collection = new Collection(); for (const item of newArray) collection.set(item.id, item); return collection; } /** * Functionally identical shortcut to `collection.array().map(...)`. * @param {function} callback Function that produces an element of the new Array, taking three arguments * @param {*} [thisArg] Optional. Value to use as this when executing callback. * @returns {array} */ map(...args) { return this.array().map(...args); } }
JavaScript
class V1CertificateSigningRequestSpec { static getAttributeTypeMap() { return V1CertificateSigningRequestSpec.attributeTypeMap; } }
JavaScript
class ActorSheetSeaDangerpoints extends ActorSheet { /** @override */ static get defaultOptions() { return mergeObject(super.defaultOptions, { classes: ["sea", "sheet", "actor", "sea-dangerpoints"], template: "systems/sea/templates/actors/dangerpoints.html", width: 450, height: 200, tabs: [{ navSelector: ".nav", contentSelector: ".body", initial: "skills" }] }); } /* -------------------------------------------- */ /** @override */ getData() { const data = super.getData(); data.actor = data.entity; data.data = data.entity.data; return data; } /* -------------------------------------------- */ /** @override */ activateListeners(html) { super.activateListeners(html); html.find('.inc').click(ev => { const actor = this.actor; var inc = $(ev.currentTarget).attr("data-inc") * 1; var value = $(ev.currentTarget).attr("data-value") * 1 + inc; actor.update({ "data.value": value }); }); html.find('.dec').click(ev => { const actor = this.actor; var dec = $(ev.currentTarget).attr("data-dec") * 1; var value = this._notNegative($(ev.currentTarget).attr("data-value") * 1 - dec); actor.update({ "data.value": value }); }); } _notNegative(value) { if (value < 0) { return 0; } else { return value; } } }
JavaScript
class ZoneGroupTopology extends Service { constructor (host, port) { super() this.name = 'ZoneGroupTopology' this.host = host this.port = port || 1400 this.controlURL = '/ZoneGroupTopology/Control' this.eventSubURL = '/ZoneGroupTopology/Event' this.SCPDURL = '/xml/ZoneGroupTopology1.xml' } async CheckForUpdate (options) { return this._request('CheckForUpdate', options) } async BeginSoftwareUpdate (options) { return this._request('BeginSoftwareUpdate', options) } async ReportUnresponsiveDevice (options) { return this._request('ReportUnresponsiveDevice', options) } async ReportAlarmStartedRunning (options) { return this._request('ReportAlarmStartedRunning', options) } async SubmitDiagnostics (options) { return this._request('SubmitDiagnostics', options) } async RegisterMobileDevice (options) { return this._request('RegisterMobileDevice', options) } async GetZoneGroupAttributes () { return this._request('GetZoneGroupAttributes', {}) } /** * Get all the information about the ZoneGroups * @returns {Object} Object with one property, 'ZoneGroupState' */ async GetZoneGroupState () { return this._request('GetZoneGroupState', {}) } /** * Get all the ZoneGroups */ async AllZoneGroups () { return this.GetZoneGroupState().then(async state => { let zoneGroupState = await Helpers.ParseXml(state.ZoneGroupState) if (zoneGroupState.ZoneGroupState) { zoneGroupState = zoneGroupState.ZoneGroupState } let groups = zoneGroupState.ZoneGroups.ZoneGroup if (!Array.isArray(groups)) { groups = [groups] } for (let i = 0; i < groups.length; i++) { if (!Array.isArray(groups[i].ZoneGroupMember)) { groups[i].ZoneGroupMember = [groups[i].ZoneGroupMember] } } return groups }) } }
JavaScript
class Siema { /** * Create a Siema. * @param {Object} options - Optional settings object. */ constructor(options) { // Merge defaults with user's settings this.config = Siema.mergeSettings(options); // Resolve selector's type this.selector = typeof this.config.selector === 'string' ? document.querySelector(this.config.selector) : this.config.selector; // Early throw if selector doesn't exists if (this.selector === null) { throw new Error('Something wrong with your selector 😭'); } // update perPage number dependable of user value this.resolveSlidesNumber(); // Create global references this.selectorWidth = this.selector.offsetWidth; this.innerElements = [].slice.call(this.selector.children); this.currentSlide = this.config.loop ? this.config.startIndex % this.innerElements.length : Math.max(0, Math.min(this.config.startIndex, this.innerElements.length - this.perPage)); this.transformProperty = Siema.webkitOrNot(); // Bind all event handlers for referencability ['resizeHandler', 'touchstartHandler', 'touchendHandler', 'touchmoveHandler', 'mousedownHandler', 'mouseupHandler', 'mouseleaveHandler', 'mousemoveHandler', 'clickHandler'].forEach(method => { this[method] = this[method].bind(this); }); // Build markup and apply required styling to elements this.init(); } /** * Overrides default settings with custom ones. * @param {Object} options - Optional settings object. * @returns {Object} - Custom Siema settings. */ static mergeSettings(options) { const settings = { selector: '.siema', duration: 200, easing: 'ease-out', perPage: 1, startIndex: 0, draggable: true, multipleDrag: true, threshold: 20, loop: false, rtl: false, onInit: () => {}, onChange: () => {}, }; const userSttings = options; for (const attrname in userSttings) { settings[attrname] = userSttings[attrname]; } return settings; } /** * Determine if browser supports unprefixed transform property. * Google Chrome since version 26 supports prefix-less transform * @returns {string} - Transform property supported by client. */ static webkitOrNot() { const style = document.documentElement.style; if (typeof style.transform === 'string') { return 'transform'; } return 'WebkitTransform'; } /** * Attaches listeners to required events. */ attachEvents() { // Resize element on window resize window.addEventListener('resize', this.resizeHandler); // If element is draggable / swipable, add event handlers if (this.config.draggable) { // Keep track pointer hold and dragging distance this.pointerDown = false; this.drag = { startX: 0, endX: 0, startY: 0, letItGo: null, preventClick: false, }; // Touch events this.selector.addEventListener('touchstart', this.touchstartHandler); this.selector.addEventListener('touchend', this.touchendHandler); this.selector.addEventListener('touchmove', this.touchmoveHandler); // Mouse events this.selector.addEventListener('mousedown', this.mousedownHandler); this.selector.addEventListener('mouseup', this.mouseupHandler); this.selector.addEventListener('mouseleave', this.mouseleaveHandler); this.selector.addEventListener('mousemove', this.mousemoveHandler); // Click this.selector.addEventListener('click', this.clickHandler); } } /** * Detaches listeners from required events. */ detachEvents() { window.removeEventListener('resize', this.resizeHandler); this.selector.removeEventListener('touchstart', this.touchstartHandler); this.selector.removeEventListener('touchend', this.touchendHandler); this.selector.removeEventListener('touchmove', this.touchmoveHandler); this.selector.removeEventListener('mousedown', this.mousedownHandler); this.selector.removeEventListener('mouseup', this.mouseupHandler); this.selector.removeEventListener('mouseleave', this.mouseleaveHandler); this.selector.removeEventListener('mousemove', this.mousemoveHandler); this.selector.removeEventListener('click', this.clickHandler); } /** * Builds the markup and attaches listeners to required events. */ init() { this.attachEvents(); // hide everything out of selector's boundaries this.selector.style.overflow = 'hidden'; // rtl or ltr this.selector.style.direction = this.config.rtl ? 'rtl' : 'ltr'; // build a frame and slide to a currentSlide this.buildSliderFrame(); this.config.onInit.call(this); } /** * Build a sliderFrame and slide to a current item. */ buildSliderFrame() { const widthItem = this.selectorWidth / this.perPage; const itemsToBuild = this.config.loop ? this.innerElements.length + (2 * this.perPage) : this.innerElements.length; // Create frame and apply styling this.sliderFrame = document.createElement('div'); this.sliderFrame.style.width = `${widthItem * itemsToBuild}px`; this.enableTransition(); if (this.config.draggable) { this.selector.style.cursor = '-webkit-grab'; } // Create a document fragment to put slides into it const docFragment = document.createDocumentFragment(); // Loop through the slides, add styling and add them to document fragment if (this.config.loop) { for (let i = this.innerElements.length - this.perPage; i < this.innerElements.length; i++) { const element = this.buildSliderFrameItem(this.innerElements[i].cloneNode(true)); docFragment.appendChild(element); } } for (let i = 0; i < this.innerElements.length; i++) { const element = this.buildSliderFrameItem(this.innerElements[i]); docFragment.appendChild(element); } if (this.config.loop) { for (let i = 0; i < this.perPage; i++) { const element = this.buildSliderFrameItem(this.innerElements[i].cloneNode(true)); docFragment.appendChild(element); } } // Add fragment to the frame this.sliderFrame.appendChild(docFragment); // Clear selector (just in case something is there) and insert a frame this.selector.innerHTML = ''; this.selector.appendChild(this.sliderFrame); // Go to currently active slide after initial build this.slideToCurrent(); } buildSliderFrameItem(elm) { const elementContainer = document.createElement('div'); elementContainer.style.cssFloat = this.config.rtl ? 'right' : 'left'; elementContainer.style.float = this.config.rtl ? 'right' : 'left'; elementContainer.style.width = `${this.config.loop ? 100 / (this.innerElements.length + (this.perPage * 2)) : 100 / (this.innerElements.length)}%`; elementContainer.appendChild(elm); return elementContainer; } /** * Determinates slides number accordingly to clients viewport. */ resolveSlidesNumber() { if (typeof this.config.perPage === 'number') { this.perPage = this.config.perPage; } else if (typeof this.config.perPage === 'object') { this.perPage = 1; for (const viewport in this.config.perPage) { if (window.innerWidth >= viewport) { this.perPage = this.config.perPage[viewport]; } } } } /** * Go to previous slide. * @param {number} [howManySlides=1] - How many items to slide backward. * @param {function} callback - Optional callback function. */ prev(howManySlides = 1, callback) { // early return when there is nothing to slide if (this.innerElements.length <= this.perPage) { return; } const beforeChange = this.currentSlide; if (this.config.loop) { const isNewIndexClone = this.currentSlide - howManySlides < 0; if (isNewIndexClone) { this.disableTransition(); const mirrorSlideIndex = this.currentSlide + this.innerElements.length; const mirrorSlideIndexOffset = this.perPage; const moveTo = mirrorSlideIndex + mirrorSlideIndexOffset; const offset = (this.config.rtl ? 1 : -1) * moveTo * (this.selectorWidth / this.perPage); const dragDistance = this.config.draggable ? this.drag.endX - this.drag.startX : 0; this.sliderFrame.style[this.transformProperty] = `translate3d(${offset + dragDistance}px, 0, 0)`; this.currentSlide = mirrorSlideIndex - howManySlides; } else { this.currentSlide = this.currentSlide - howManySlides; } } else { this.currentSlide = Math.max(this.currentSlide - howManySlides, 0); } if (beforeChange !== this.currentSlide) { this.slideToCurrent(this.config.loop); this.config.onChange.call(this); if (callback) { callback.call(this); } } } /** * Go to next slide. * @param {number} [howManySlides=1] - How many items to slide forward. * @param {function} callback - Optional callback function. */ next(howManySlides = 1, callback) { // early return when there is nothing to slide if (this.innerElements.length <= this.perPage) { return; } const beforeChange = this.currentSlide; if (this.config.loop) { const isNewIndexClone = this.currentSlide + howManySlides > this.innerElements.length - this.perPage; if (isNewIndexClone) { this.disableTransition(); const mirrorSlideIndex = this.currentSlide - this.innerElements.length; const mirrorSlideIndexOffset = this.perPage; const moveTo = mirrorSlideIndex + mirrorSlideIndexOffset; const offset = (this.config.rtl ? 1 : -1) * moveTo * (this.selectorWidth / this.perPage); const dragDistance = this.config.draggable ? this.drag.endX - this.drag.startX : 0; this.sliderFrame.style[this.transformProperty] = `translate3d(${offset + dragDistance}px, 0, 0)`; this.currentSlide = mirrorSlideIndex + howManySlides; } else { this.currentSlide = this.currentSlide + howManySlides; } } else { this.currentSlide = Math.min(this.currentSlide + howManySlides, this.innerElements.length - this.perPage); } if (beforeChange !== this.currentSlide) { this.slideToCurrent(this.config.loop); this.config.onChange.call(this); if (callback) { callback.call(this); } } } /** * Disable transition on sliderFrame. */ disableTransition() { this.sliderFrame.style.webkitTransition = `all 0ms ${this.config.easing}`; this.sliderFrame.style.transition = `all 0ms ${this.config.easing}`; } /** * Enable transition on sliderFrame. */ enableTransition() { this.sliderFrame.style.webkitTransition = `all ${this.config.duration}ms ${this.config.easing}`; this.sliderFrame.style.transition = `all ${this.config.duration}ms ${this.config.easing}`; } /** * Go to slide with particular index * @param {number} index - Item index to slide to. * @param {function} callback - Optional callback function. */ goTo(index, callback) { if (this.innerElements.length <= this.perPage) { return; } const beforeChange = this.currentSlide; this.currentSlide = this.config.loop ? index % this.innerElements.length : Math.min(Math.max(index, 0), this.innerElements.length - this.perPage); if (beforeChange !== this.currentSlide) { this.slideToCurrent(); this.config.onChange.call(this); if (callback) { callback.call(this); } } } /** * Moves sliders frame to position of currently active slide */ slideToCurrent(enableTransition) { const currentSlide = this.config.loop ? this.currentSlide + this.perPage : this.currentSlide; const offset = (this.config.rtl ? 1 : -1) * currentSlide * (this.selectorWidth / this.perPage); if (enableTransition) { // This one is tricky, I know but this is a perfect explanation: // https://youtu.be/cCOL7MC4Pl0 requestAnimationFrame(() => { requestAnimationFrame(() => { this.enableTransition(); this.sliderFrame.style[this.transformProperty] = `translate3d(${offset}px, 0, 0)`; }); }); } else { this.sliderFrame.style[this.transformProperty] = `translate3d(${offset}px, 0, 0)`; } } /** * Recalculate drag /swipe event and reposition the frame of a slider */ updateAfterDrag() { const movement = (this.config.rtl ? -1 : 1) * (this.drag.endX - this.drag.startX); const movementDistance = Math.abs(movement); const howManySliderToSlide = this.config.multipleDrag ? Math.ceil(movementDistance / (this.selectorWidth / this.perPage)) : 1; const slideToNegativeClone = movement > 0 && this.currentSlide - howManySliderToSlide < 0; const slideToPositiveClone = movement < 0 && this.currentSlide + howManySliderToSlide > this.innerElements.length - this.perPage; if (movement > 0 && movementDistance > this.config.threshold && this.innerElements.length > this.perPage) { this.prev(howManySliderToSlide); } else if (movement < 0 && movementDistance > this.config.threshold && this.innerElements.length > this.perPage) { this.next(howManySliderToSlide); } this.slideToCurrent(slideToNegativeClone || slideToPositiveClone); } /** * When window resizes, resize slider components as well */ resizeHandler() { // update perPage number dependable of user value this.resolveSlidesNumber(); // relcalculate currentSlide // prevent hiding items when browser width increases if (this.currentSlide + this.perPage > this.innerElements.length) { this.currentSlide = this.innerElements.length <= this.perPage ? 0 : this.innerElements.length - this.perPage; } this.selectorWidth = this.selector.offsetWidth; this.buildSliderFrame(); } /** * Clear drag after touchend and mouseup event */ clearDrag() { this.drag = { startX: 0, endX: 0, startY: 0, letItGo: null, preventClick: this.drag.preventClick }; } /** * touchstart event handler */ touchstartHandler(e) { // Prevent dragging / swiping on inputs, selects and textareas const ignoreSiema = ['TEXTAREA', 'OPTION', 'INPUT', 'SELECT'].indexOf(e.target.nodeName) !== -1; if (ignoreSiema) { return; } e.stopPropagation(); this.pointerDown = true; this.drag.startX = e.touches[0].pageX; this.drag.startY = e.touches[0].pageY; } /** * touchend event handler */ touchendHandler(e) { e.stopPropagation(); this.pointerDown = false; this.enableTransition(); if (this.drag.endX) { this.updateAfterDrag(); } this.clearDrag(); } /** * touchmove event handler */ touchmoveHandler(e) { e.stopPropagation(); if (this.drag.letItGo === null) { this.drag.letItGo = Math.abs(this.drag.startY - e.touches[0].pageY) < Math.abs(this.drag.startX - e.touches[0].pageX); } if (this.pointerDown && this.drag.letItGo) { e.preventDefault(); this.drag.endX = e.touches[0].pageX; this.sliderFrame.style.webkitTransition = `all 0ms ${this.config.easing}`; this.sliderFrame.style.transition = `all 0ms ${this.config.easing}`; const currentSlide = this.config.loop ? this.currentSlide + this.perPage : this.currentSlide; const currentOffset = currentSlide * (this.selectorWidth / this.perPage); const dragOffset = (this.drag.endX - this.drag.startX); const offset = this.config.rtl ? currentOffset + dragOffset : currentOffset - dragOffset; this.sliderFrame.style[this.transformProperty] = `translate3d(${(this.config.rtl ? 1 : -1) * offset}px, 0, 0)`; } } /** * mousedown event handler */ mousedownHandler(e) { // Prevent dragging / swiping on inputs, selects and textareas const ignoreSiema = ['TEXTAREA', 'OPTION', 'INPUT', 'SELECT'].indexOf(e.target.nodeName) !== -1; if (ignoreSiema) { return; } e.preventDefault(); e.stopPropagation(); this.pointerDown = true; this.drag.startX = e.pageX; } /** * mouseup event handler */ mouseupHandler(e) { e.stopPropagation(); this.pointerDown = false; this.selector.style.cursor = '-webkit-grab'; this.enableTransition(); if (this.drag.endX) { this.updateAfterDrag(); } this.clearDrag(); } /** * mousemove event handler */ mousemoveHandler(e) { e.preventDefault(); if (this.pointerDown) { // if dragged element is a link // mark preventClick prop as a true // to detemine about browser redirection later on if (e.target.nodeName === 'A') { this.drag.preventClick = true; } this.drag.endX = e.pageX; this.selector.style.cursor = '-webkit-grabbing'; this.sliderFrame.style.webkitTransition = `all 0ms ${this.config.easing}`; this.sliderFrame.style.transition = `all 0ms ${this.config.easing}`; const currentSlide = this.config.loop ? this.currentSlide + this.perPage : this.currentSlide; const currentOffset = currentSlide * (this.selectorWidth / this.perPage); const dragOffset = (this.drag.endX - this.drag.startX); const offset = this.config.rtl ? currentOffset + dragOffset : currentOffset - dragOffset; this.sliderFrame.style[this.transformProperty] = `translate3d(${(this.config.rtl ? 1 : -1) * offset}px, 0, 0)`; } } /** * mouseleave event handler */ mouseleaveHandler(e) { if (this.pointerDown) { this.pointerDown = false; this.selector.style.cursor = '-webkit-grab'; this.drag.endX = e.pageX; this.drag.preventClick = false; this.enableTransition(); this.updateAfterDrag(); this.clearDrag(); } } /** * click event handler */ clickHandler(e) { // if the dragged element is a link // prevent browsers from folowing the link if (this.drag.preventClick) { e.preventDefault(); } this.drag.preventClick = false; } /** * Remove item from carousel. * @param {number} index - Item index to remove. * @param {function} callback - Optional callback to call after remove. */ remove(index, callback) { if (index < 0 || index >= this.innerElements.length) { throw new Error('Item to remove doesn\'t exist 😭'); } // Shift sliderFrame back by one item when: // 1. Item with lower index than currenSlide is removed. // 2. Last item is removed. const lowerIndex = index < this.currentSlide; const lastItem = this.currentSlide + this.perPage - 1 === index; if (lowerIndex || lastItem) { this.currentSlide--; } this.innerElements.splice(index, 1); // build a frame and slide to a currentSlide this.buildSliderFrame(); if (callback) { callback.call(this); } } /** * Insert item to carousel at particular index. * @param {HTMLElement} item - Item to insert. * @param {number} index - Index of new new item insertion. * @param {function} callback - Optional callback to call after insert. */ insert(item, index, callback) { if (index < 0 || index > this.innerElements.length + 1) { throw new Error('Unable to inset it at this index 😭'); } if (this.innerElements.indexOf(item) !== -1) { throw new Error('The same item in a carousel? Really? Nope 😭'); } // Avoid shifting content const shouldItShift = index <= this.currentSlide > 0 && this.innerElements.length; this.currentSlide = shouldItShift ? this.currentSlide + 1 : this.currentSlide; this.innerElements.splice(index, 0, item); // build a frame and slide to a currentSlide this.buildSliderFrame(); if (callback) { callback.call(this); } } /** * Prepernd item to carousel. * @param {HTMLElement} item - Item to prepend. * @param {function} callback - Optional callback to call after prepend. */ prepend(item, callback) { this.insert(item, 0); if (callback) { callback.call(this); } } /** * Append item to carousel. * @param {HTMLElement} item - Item to append. * @param {function} callback - Optional callback to call after append. */ append(item, callback) { this.insert(item, this.innerElements.length + 1); if (callback) { callback.call(this); } } /** * Removes listeners and optionally restores to initial markup * @param {boolean} restoreMarkup - Determinants about restoring an initial markup. * @param {function} callback - Optional callback function. */ destroy(restoreMarkup = false, callback) { this.detachEvents(); this.selector.style.cursor = 'auto'; if (restoreMarkup) { const slides = document.createDocumentFragment(); for (let i = 0; i < this.innerElements.length; i++) { slides.appendChild(this.innerElements[i]); } this.selector.innerHTML = ''; this.selector.appendChild(slides); this.selector.removeAttribute('style'); } if (callback) { callback.call(this); } } }
JavaScript
class Region { constructor(params, ws) { this.wavesurfer = ws; this.wrapper = ws.drawer.wrapper; this.util = ws.util; this.style = this.util.style; this.id = params.id == null ? ws.util.getId() : params.id; this.start = Number(params.start) || 0; this.end = params.end == null ? // small marker-like region this.start + (4 / this.wrapper.scrollWidth) * this.wavesurfer.getDuration() : Number(params.end); this.resize = params.resize === undefined ? true : Boolean(params.resize); this.drag = params.drag === undefined ? true : Boolean(params.drag); // reflect resize and drag state of region for region-updated listener this.isResizing = false; this.isDragging = false; this.loop = Boolean(params.loop); this.color = params.color || 'rgba(0, 0, 0, 0.1)'; this.handleStyle = params.handleStyle || { left: { backgroundColor: 'rgba(0, 0, 0, 1)' }, right: { backgroundColor: 'rgba(0, 0, 0, 1)' } }; this.data = params.data || {}; this.attributes = params.attributes || {}; this.maxLength = params.maxLength; this.minLength = params.minLength; this._onRedraw = () => this.updateRender(); this.scroll = params.scroll !== false && ws.params.scrollParent; this.scrollSpeed = params.scrollSpeed || 1; this.scrollThreshold = params.scrollThreshold || 10; this.bindInOut(); this.render(); this.wavesurfer.on('zoom', this._onRedraw); this.wavesurfer.on('redraw', this._onRedraw); this.wavesurfer.fireEvent('region-created', this); } /* Update region params. */ update(params) { if (null != params.start) { this.start = Number(params.start); } if (null != params.end) { this.end = Number(params.end); } if (null != params.loop) { this.loop = Boolean(params.loop); } if (null != params.color) { this.color = params.color; } if (null != params.handleStyle) { this.handleStyle = params.handleStyle; } if (null != params.data) { this.data = params.data; } if (null != params.resize) { this.resize = Boolean(params.resize); } if (null != params.drag) { this.drag = Boolean(params.drag); } if (null != params.maxLength) { this.maxLength = Number(params.maxLength); } if (null != params.minLength) { this.minLength = Number(params.minLength); } if (null != params.attributes) { this.attributes = params.attributes; } this.updateRender(); this.fireEvent('update'); this.wavesurfer.fireEvent('region-updated', this); } /* Remove a single region. */ remove() { if (this.element) { this.wrapper.removeChild(this.element); this.element = null; this.fireEvent('remove'); this.wavesurfer.un('zoom', this._onRedraw); this.wavesurfer.un('redraw', this._onRedraw); this.wavesurfer.fireEvent('region-removed', this); } } /** * Play the audio region. * @param {number} start Optional offset to start playing at */ play(start) { const s = start || this.start; this.wavesurfer.play(s, this.end); this.fireEvent('play'); this.wavesurfer.fireEvent('region-play', this); } /** * Play the audio region in a loop. * @param {number} start Optional offset to start playing at * */ playLoop(start) { this.play(start); this.once('out', () => this.playLoop()); } /* Render a region as a DOM element. */ render() { const regionEl = document.createElement('region'); const handleLeft = regionEl.appendChild( document.createElement('handle') ); const handleRight = regionEl.appendChild( document.createElement('handle') ); regionEl.className = 'wavesurfer-region'; regionEl.title = this.formatTime(this.start, this.end); regionEl.setAttribute('data-id', this.id); for (const attrname in this.attributes) { regionEl.setAttribute( 'data-region-' + attrname, this.attributes[attrname] ); } this.style(regionEl, { position: 'absolute', zIndex: 2, height: '100%', top: '0px' }); /* Allows the user to set the handlecolor dynamically, both handle colors must be set */ if (!this.handleStyle.left) { handleLeft.style.backgroundColor = 'rgba(0, 0, 0, 1)'; } else { handleLeft.style.backgroundColor = this.handleStyle.left.backgroundColor; } if (!this.handleStyle.right) { handleRight.style.backgroundColor = 'rgba(0, 0, 0, 1)'; } else { handleRight.style.backgroundColor = this.handleStyle.right.backgroundColor; } /* Resize handles */ if (this.resize) { handleLeft.className = 'wavesurfer-handle wavesurfer-handle-start'; handleRight.className = 'wavesurfer-handle wavesurfer-handle-end'; const css = { cursor: 'col-resize', position: 'absolute', top: '0px', width: '1%', maxWidth: '4px', height: '100%' }; this.style(handleLeft, css); this.style(handleLeft, { left: '0px' }); this.style(handleRight, css); this.style(handleRight, { right: '0px' }); } this.element = this.wrapper.appendChild(regionEl); this.updateRender(); this.bindEvents(regionEl); } formatTime(start, end) { return (start == end ? [start] : [start, end]) .map(time => [ Math.floor((time % 3600) / 60), // minutes ('00' + Math.floor(time % 60)).slice(-2) // seconds ].join(':') ) .join('-'); } getWidth() { return this.wavesurfer.drawer.width / this.wavesurfer.params.pixelRatio; } /* Update element's position, width, color. */ updateRender() { // duration varies during loading process, so don't overwrite important data const dur = this.wavesurfer.getDuration(); const width = this.getWidth(); var startLimited = this.start; var endLimited = this.end; if (startLimited < 0) { startLimited = 0; endLimited = endLimited - startLimited; } if (endLimited > dur) { endLimited = dur; startLimited = dur - (endLimited - startLimited); } if (this.minLength != null) { endLimited = Math.max(startLimited + this.minLength, endLimited); } if (this.maxLength != null) { endLimited = Math.min(startLimited + this.maxLength, endLimited); } if (this.element != null) { // Calculate the left and width values of the region such that // no gaps appear between regions. const left = Math.round((startLimited / dur) * width); const regionWidth = Math.round((endLimited / dur) * width) - left; this.style(this.element, { left: left + 'px', width: regionWidth + 'px', backgroundColor: this.color, cursor: this.drag ? 'move' : 'default' }); for (const attrname in this.attributes) { this.element.setAttribute( 'data-region-' + attrname, this.attributes[attrname] ); } this.element.title = this.formatTime(this.start, this.end); } } /* Bind audio events. */ bindInOut() { this.firedIn = false; this.firedOut = false; const onProcess = time => { let start = Math.round(this.start * 10) / 10; let end = Math.round(this.end * 10) / 10; time = Math.round(time * 10) / 10; if ( !this.firedOut && this.firedIn && (start > time || end <= time) ) { this.firedOut = true; this.firedIn = false; this.fireEvent('out'); this.wavesurfer.fireEvent('region-out', this); } if (!this.firedIn && start <= time && end > time) { this.firedIn = true; this.firedOut = false; this.fireEvent('in'); this.wavesurfer.fireEvent('region-in', this); } }; this.wavesurfer.backend.on('audioprocess', onProcess); this.on('remove', () => { this.wavesurfer.backend.un('audioprocess', onProcess); }); /* Loop playback. */ this.on('out', () => { if (this.loop) { this.wavesurfer.play(this.start); } }); } /* Bind DOM events. */ bindEvents() { this.element.addEventListener('mouseenter', e => { this.fireEvent('mouseenter', e); this.wavesurfer.fireEvent('region-mouseenter', this, e); }); this.element.addEventListener('mouseleave', e => { this.fireEvent('mouseleave', e); this.wavesurfer.fireEvent('region-mouseleave', this, e); }); this.element.addEventListener('click', e => { e.preventDefault(); this.fireEvent('click', e); this.wavesurfer.fireEvent('region-click', this, e); }); this.element.addEventListener('dblclick', e => { e.stopPropagation(); e.preventDefault(); this.fireEvent('dblclick', e); this.wavesurfer.fireEvent('region-dblclick', this, e); }); /* Drag or resize on mousemove. */ (this.drag || this.resize) && (() => { const container = this.wavesurfer.drawer.container; const scrollSpeed = this.scrollSpeed; const scrollThreshold = this.scrollThreshold; let startTime; let touchId; let drag; let maxScroll; let resize; let updated = false; let scrollDirection; let wrapperRect; // Scroll when the user is dragging within the threshold const edgeScroll = e => { const duration = this.wavesurfer.getDuration(); if (!scrollDirection || (!drag && !resize)) { return; } // Update scroll position let scrollLeft = this.wrapper.scrollLeft + scrollSpeed * scrollDirection; this.wrapper.scrollLeft = scrollLeft = Math.min( maxScroll, Math.max(0, scrollLeft) ); // Get the currently selected time according to the mouse position const time = this.wavesurfer.regions.util.getRegionSnapToGridValue( this.wavesurfer.drawer.handleEvent(e) * duration ); const delta = time - startTime; startTime = time; // Continue dragging or resizing drag ? this.onDrag(delta) : this.onResize(delta, resize); // Repeat window.requestAnimationFrame(() => { edgeScroll(e); }); }; const onDown = e => { const duration = this.wavesurfer.getDuration(); if (e.touches && e.touches.length > 1) { return; } touchId = e.targetTouches ? e.targetTouches[0].identifier : null; // stop the event propagation, if this region is resizable or draggable // and the event is therefore handled here. if (this.drag || this.resize) { e.stopPropagation(); } // Store the selected startTime we begun dragging or resizing startTime = this.wavesurfer.regions.util.getRegionSnapToGridValue( this.wavesurfer.drawer.handleEvent(e, true) * duration ); // Store for scroll calculations maxScroll = this.wrapper.scrollWidth - this.wrapper.clientWidth; wrapperRect = this.wrapper.getBoundingClientRect(); this.isResizing = false; this.isDragging = false; if (e.target.tagName.toLowerCase() === 'handle') { this.isResizing = true; if ( e.target.classList.contains( 'wavesurfer-handle-start' ) ) { resize = 'start'; } else { resize = 'end'; } } else { this.isDragging = true; drag = true; resize = false; } }; const onUp = e => { if (e.touches && e.touches.length > 1) { return; } if (drag || resize) { this.isDragging = false; this.isResizing = false; drag = false; scrollDirection = null; resize = false; } if (updated) { updated = false; this.util.preventClick(); this.fireEvent('update-end', e); this.wavesurfer.fireEvent('region-update-end', this, e); } }; const onMove = e => { const duration = this.wavesurfer.getDuration(); if (e.touches && e.touches.length > 1) { return; } if ( e.targetTouches && e.targetTouches[0].identifier != touchId ) { return; } if (drag || resize) { const oldTime = startTime; const time = this.wavesurfer.regions.util.getRegionSnapToGridValue( this.wavesurfer.drawer.handleEvent(e) * duration ); const delta = time - startTime; startTime = time; // Drag if (this.drag && drag) { updated = updated || !!delta; this.onDrag(delta); } // Resize if (this.resize && resize) { updated = updated || !!delta; this.onResize(delta, resize); } if ( this.scroll && container.clientWidth < this.wrapper.scrollWidth ) { if (drag) { // The threshold is not between the mouse and the container edge // but is between the region and the container edge const regionRect = this.element.getBoundingClientRect(); let x = regionRect.left - wrapperRect.left; // Check direction if (time < oldTime && x >= 0) { scrollDirection = -1; } else if ( time > oldTime && x + regionRect.width <= wrapperRect.right ) { scrollDirection = 1; } // Check that we are still beyond the threshold if ( (scrollDirection === -1 && x > scrollThreshold) || (scrollDirection === 1 && x + regionRect.width < wrapperRect.right - scrollThreshold) ) { scrollDirection = null; } } else { // Mouse based threshold let x = e.clientX - wrapperRect.left; // Check direction if (x <= scrollThreshold) { scrollDirection = -1; } else if ( x >= wrapperRect.right - scrollThreshold ) { scrollDirection = 1; } else { scrollDirection = null; } } scrollDirection && edgeScroll(e); } } }; this.element.addEventListener('mousedown', onDown); this.element.addEventListener('touchstart', onDown); this.wrapper.addEventListener('mousemove', onMove); this.wrapper.addEventListener('touchmove', onMove); document.body.addEventListener('mouseup', onUp); document.body.addEventListener('touchend', onUp); this.on('remove', () => { document.body.removeEventListener('mouseup', onUp); document.body.removeEventListener('touchend', onUp); this.wrapper.removeEventListener('mousemove', onMove); this.wrapper.removeEventListener('touchmove', onMove); }); this.wavesurfer.on('destroy', () => { document.body.removeEventListener('mouseup', onUp); document.body.removeEventListener('touchend', onUp); }); })(); } onDrag(delta) { const maxEnd = this.wavesurfer.getDuration(); if (this.end + delta > maxEnd || this.start + delta < 0) { return; } this.update({ start: this.start + delta, end: this.end + delta }); } onResize(delta, direction) { if (direction === 'start') { this.update({ start: Math.min(this.start + delta, this.end), end: Math.max(this.start + delta, this.end) }); } else { this.update({ start: Math.min(this.end + delta, this.start), end: Math.max(this.end + delta, this.start) }); } } }
JavaScript
class RegionsPlugin { /** * Regions plugin definition factory * * This function must be used to create a plugin definition which can be * used by wavesurfer to correctly instantiate the plugin. * * @param {RegionsPluginParams} params parameters use to initialise the plugin * @return {PluginDefinition} an object representing the plugin */ static create(params) { return { name: 'regions', deferInit: params && params.deferInit ? params.deferInit : false, params: params, staticProps: { addRegion(options) { if (!this.initialisedPluginList.regions) { this.initPlugin('regions'); } return this.regions.add(options); }, clearRegions() { this.regions && this.regions.clear(); }, enableDragSelection(options) { if (!this.initialisedPluginList.regions) { this.initPlugin('regions'); } this.regions.enableDragSelection(options); }, disableDragSelection() { this.regions.disableDragSelection(); } }, instance: RegionsPlugin }; } constructor(params, ws) { this.params = params; this.wavesurfer = ws; this.util = { ...ws.util, getRegionSnapToGridValue: value => { return this.getRegionSnapToGridValue(value, params); } }; this.maxRegions = params.maxRegions; // turn the plugin instance into an observer const observerPrototypeKeys = Object.getOwnPropertyNames( this.util.Observer.prototype ); observerPrototypeKeys.forEach(key => { Region.prototype[key] = this.util.Observer.prototype[key]; }); this.wavesurfer.Region = Region; this._onBackendCreated = () => { this.wrapper = this.wavesurfer.drawer.wrapper; if (this.params.regions) { this.params.regions.forEach(region => { this.add(region); }); } }; // Id-based hash of regions this.list = {}; this._onReady = () => { this.wrapper = this.wavesurfer.drawer.wrapper; if (this.params.dragSelection) { this.enableDragSelection(this.params); } Object.keys(this.list).forEach(id => { this.list[id].updateRender(); }); }; } init() { // Check if ws is ready if (this.wavesurfer.isReady) { this._onBackendCreated(); this._onReady(); } else { this.wavesurfer.once('ready', this._onReady); this.wavesurfer.once('backend-created', this._onBackendCreated); } } destroy() { this.wavesurfer.un('ready', this._onReady); this.wavesurfer.un('backend-created', this._onBackendCreated); this.disableDragSelection(); this.clear(); } /** * check to see if adding a new region would exceed maxRegions * @return {boolean} whether we should proceed and create a region * @private */ wouldExceedMaxRegions() { return ( this.maxRegions && Object.keys(this.list).length >= this.maxRegions ); } /** * Add a region * * @param {object} params Region parameters * @return {Region} The created region */ add(params) { if (this.wouldExceedMaxRegions()) return null; const region = new this.wavesurfer.Region(params, this.wavesurfer); this.list[region.id] = region; region.on('remove', () => { delete this.list[region.id]; }); return region; } /** * Remove all regions */ clear() { Object.keys(this.list).forEach(id => { this.list[id].remove(); }); } enableDragSelection(params) { const slop = params.slop || 2; const container = this.wavesurfer.drawer.container; const scroll = params.scroll !== false && this.wavesurfer.params.scrollParent; const scrollSpeed = params.scrollSpeed || 1; const scrollThreshold = params.scrollThreshold || 10; let drag; let duration = this.wavesurfer.getDuration(); let maxScroll; let start; let region; let touchId; let pxMove = 0; let scrollDirection; let wrapperRect; // Scroll when the user is dragging within the threshold const edgeScroll = e => { if (!region || !scrollDirection) { return; } // Update scroll position let scrollLeft = this.wrapper.scrollLeft + scrollSpeed * scrollDirection; this.wrapper.scrollLeft = scrollLeft = Math.min( maxScroll, Math.max(0, scrollLeft) ); // Update range const end = this.wavesurfer.drawer.handleEvent(e); region.update({ start: Math.min(end * duration, start * duration), end: Math.max(end * duration, start * duration) }); // Check that there is more to scroll and repeat if (scrollLeft < maxScroll && scrollLeft > 0) { window.requestAnimationFrame(() => { edgeScroll(e); }); } }; const eventDown = e => { if (e.touches && e.touches.length > 1) { return; } duration = this.wavesurfer.getDuration(); touchId = e.targetTouches ? e.targetTouches[0].identifier : null; // Store for scroll calculations maxScroll = this.wrapper.scrollWidth - this.wrapper.clientWidth; wrapperRect = this.wrapper.getBoundingClientRect(); drag = true; start = this.wavesurfer.drawer.handleEvent(e, true); region = null; scrollDirection = null; }; this.wrapper.addEventListener('mousedown', eventDown); this.wrapper.addEventListener('touchstart', eventDown); this.on('disable-drag-selection', () => { this.wrapper.removeEventListener('touchstart', eventDown); this.wrapper.removeEventListener('mousedown', eventDown); }); const eventUp = e => { if (e.touches && e.touches.length > 1) { return; } drag = false; pxMove = 0; scrollDirection = null; if (region) { this.util.preventClick(); region.fireEvent('update-end', e); this.wavesurfer.fireEvent('region-update-end', region, e); } region = null; }; this.wrapper.addEventListener('mouseup', eventUp); this.wrapper.addEventListener('touchend', eventUp); document.body.addEventListener('mouseup', eventUp); document.body.addEventListener('touchend', eventUp); this.on('disable-drag-selection', () => { document.body.removeEventListener('mouseup', eventUp); document.body.removeEventListener('touchend', eventUp); this.wrapper.removeEventListener('touchend', eventUp); this.wrapper.removeEventListener('mouseup', eventUp); }); const eventMove = e => { if (!drag) { return; } if (++pxMove <= slop) { return; } if (e.touches && e.touches.length > 1) { return; } if (e.targetTouches && e.targetTouches[0].identifier != touchId) { return; } // auto-create a region during mouse drag, unless region-count would exceed "maxRegions" if (!region) { region = this.add(params || {}); if (!region) return; } const end = this.wavesurfer.drawer.handleEvent(e); const startUpdate = this.wavesurfer.regions.util.getRegionSnapToGridValue( start * duration ); const endUpdate = this.wavesurfer.regions.util.getRegionSnapToGridValue( end * duration ); region.update({ start: Math.min(endUpdate, startUpdate), end: Math.max(endUpdate, startUpdate) }); // If scrolling is enabled if (scroll && container.clientWidth < this.wrapper.scrollWidth) { // Check threshold based on mouse const x = e.clientX - wrapperRect.left; if (x <= scrollThreshold) { scrollDirection = -1; } else if (x >= wrapperRect.right - scrollThreshold) { scrollDirection = 1; } else { scrollDirection = null; } scrollDirection && edgeScroll(e); } }; this.wrapper.addEventListener('mousemove', eventMove); this.wrapper.addEventListener('touchmove', eventMove); this.on('disable-drag-selection', () => { this.wrapper.removeEventListener('touchmove', eventMove); this.wrapper.removeEventListener('mousemove', eventMove); }); } disableDragSelection() { this.fireEvent('disable-drag-selection'); } /** * Get current region * * The smallest region that contains the current time. If several such * regions exist, take the first. Return `null` if none exist. * * @returns {Region} The current region */ getCurrentRegion() { const time = this.wavesurfer.getCurrentTime(); let min = null; Object.keys(this.list).forEach(id => { const cur = this.list[id]; if (cur.start <= time && cur.end >= time) { if (!min || cur.end - cur.start < min.end - min.start) { min = cur; } } }); return min; } /** * Match the value to the grid, if required * * If the regions plugin params have a snapToGridInterval set, return the * value matching the nearest grid interval. If no snapToGridInterval is set, * the passed value will be returned without modification. * * @param {number} value the value to snap to the grid, if needed * @param {Object} params the regions plugin params * @returns {number} value */ getRegionSnapToGridValue(value, params) { if (params.snapToGridInterval) { // the regions should snap to a grid const offset = params.snapToGridOffset || 0; return ( Math.round((value - offset) / params.snapToGridInterval) * params.snapToGridInterval + offset ); } // no snap-to-grid return value; } }
JavaScript
class SummaryResults { /** * Create a SummaryResults. * @member {string} [queryResultsUri] HTTP POST URI for queryResults action * on Microsoft.PolicyInsights to retrieve raw results for the non-compliance * summary. * @member {number} [nonCompliantResources] Number of non-compliant * resources. * @member {number} [nonCompliantPolicies] Number of non-compliant policies. */ constructor() { } /** * Defines the metadata of SummaryResults * * @returns {object} metadata of SummaryResults * */ mapper() { return { required: false, serializedName: 'SummaryResults', type: { name: 'Composite', className: 'SummaryResults', modelProperties: { queryResultsUri: { required: false, serializedName: 'queryResultsUri', type: { name: 'String' } }, nonCompliantResources: { required: false, serializedName: 'nonCompliantResources', constraints: { InclusiveMinimum: 0 }, type: { name: 'Number' } }, nonCompliantPolicies: { required: false, serializedName: 'nonCompliantPolicies', constraints: { InclusiveMinimum: 0 }, type: { name: 'Number' } } } } }; } }
JavaScript
class DiscordClient extends EventEmitter { constructor(options = {}) { super(); if (!options || !(options instanceof Object)) return console.error("An Object is required to create the discord.io client."); applyProperties(this, [ ["_ws", null], ["_uIDToDM", {}], ["_ready", false], ["_vChannels", {}], ["_messageCache", {}], ["_connecting", false], ["_mainKeepAlive", null], ["_req", APIRequest.bind(this)], ["_shard", this.validateShard(options.shard)], ["_messageCacheLimit", typeof(options.messageCacheLimit) === 'number' ? options.messageCacheLimit : 50], ]); this.presenceStatus = "offline"; this.connected = false; this.inviteURL = null; //this.connect = this.connect.bind(this, options); if (options.autorun === true) this.connect(options); } /* - DiscordClient - Methods - */ /** * Manually initiate the WebSocket connection to Discord. */ connect(opts) { if (!this.connected && !this._connecting) return setTimeout(function() { this.init(opts); CONNECT_WHEN = Math.max(CONNECT_WHEN, Date.now()) + 6000; }.bind(this), Math.max( 0, CONNECT_WHEN - Date.now() )); } /** * Disconnect the WebSocket connection to Discord. */ disconnect() { if (this._ws) return this._ws.close(1000, "Manual disconnect"), log(this, "Manual disconnect called, websocket closed"); return log(this, Discord.LogLevels.Warn, "Manual disconnect called with no WebSocket active, ignored"); } /** * Retrieve a user object from Discord, Bot only endpoint. You don't have to share a server with this user. * @arg {Object} input * @arg {Snowflake} input.userID */ getUser(input, callback) { if (!this.bot) return handleErrCB("[getUser] This account is a 'user' type account, and cannot use 'getUser'. Only bots can use this endpoint.", callback); this._req('get', Endpoints.USER(input.userID), function(err, res) { handleResCB("Could not get user", err, res, callback); }); } /** * Edit the client's user information. * @arg {Object} input * @arg {String<Base64>} input.avatar - The last part of a Base64 Data URI. `fs.readFileSync('image.jpg', 'base64')` is enough. * @arg {String} input.username - A username. * @arg {String} input.email - [User only] An email. * @arg {String} input.password - [User only] Your current password. * @arg {String} input.new_password - [User only] A new password. */ editUserInfo(input, callback) { var payload = { avatar: this.avatar, email: this.email, new_password: null, password: null, username: this.username }, plArr = Object.keys(payload); for (var key in input) { if (plArr.indexOf(key) < 0) return handleErrCB(("[editUserInfo] '" + key + "' is not a valid key. Valid keys are: " + plArr.join(", ")), callback); payload[key] = input[key]; } if (input.avatar) payload.avatar = "data:image/jpg;base64," + input.avatar; this._req('patch', Endpoints.ME, payload, function(err, res) { handleResCB("Unable to edit user information", err, res, callback); }); } /** * Change the client's presence. * @arg {Object} input * @arg {String|null} input.status - Used to set the status. online, idle, dnd, invisible, and offline are the possible states. * @arg {Number|null} input.since - Optional, use a Number before the current point in time. * @arg {Boolean|null} input.afk - Optional, changes how Discord handles push notifications. * @arg {Object|null} input.game - Used to set game information. * @arg {String|null} input.game.name - The name of the game. * @arg {Number|null} input.game.type - Activity type, 0 for game, 1 for Twitch. * @arg {String|null} input.game.url - A URL matching the streaming service you've selected. */ setPresence(input) { var payload = Payloads.STATUS(input); send(this._ws, payload); this.presenceStatus = payload.d.status; } /** * Receive OAuth information for the current client. */ getOauthInfo(callback) { this._req('get', Endpoints.OAUTH, (err, res) => { handleResCB("Error GETing OAuth information", err, res, callback); }); } /** * Receive account settings information for the current client. */ getAccountSettings(callback) { if (this.bot) { return void(handleErrCB("[getAccountSettings] illegal to use on bot clients", callback)); } this._req('get', Endpoints.SETTINGS, (err, res) => { handleResCB("Error GETing client settings", err, res, callback); }); } /* - DiscordClient - Methods - Content - */ /** * Upload a file to a channel. * @arg {Object} input * @arg {Snowflake} input.to - The target Channel or User ID. * @arg {Buffer|String} input.file - A Buffer containing the file data, or a String that's a path to the file. * @arg {String|null} input.filename - A filename for the uploaded file, required if you provide a Buffer. * @arg {String|null} input.message - An optional message to provide. */ uploadFile(input, callback) { /* After like 15 minutes of fighting with Request, turns out Discord doesn't allow multiple files in one message... despite having an attachments array.*/ var file, multi, message, isBuffer, isString; multi = new Multipart(); message = Message.generate(input.message || ""); isBuffer = (input.file instanceof Buffer); isString = (type(input.file) === 'string'); if (!isBuffer && !isString) return handleErrCB("uploadFile requires a String or Buffer as the 'file' value", callback); if (isBuffer) { if (!input.filename) return handleErrCB("uploadFile requires a 'filename' value to be set if using a Buffer", callback); file = input.file; } if (isString) try { file = FS.readFileSync(input.file); } catch(e) { return handleErrCB("File does not exist: " + input.file, callback); } [ ["content", message.content], ["mentions", ""], ["tts", false], ["nonce", message.nonce], ["file", file, input.filename || BN(input.file)] ].forEach(multi.append, multi); multi.finalize(); this.resolveID(input.to, channelID => { this._req('post', Endpoints.MESSAGES(channelID), multi, (err, res) => { handleResCB("Unable to upload file", err, res, callback); }); }); } /** * Send a message to a channel. * @arg {Object} input * @arg {Snowflake} input.to - The target Channel or User ID. * @arg {String} input.message - The message content. * @arg {Object} [input.embed] - An embed object to include * @arg {Boolean} [input.tts] - Enable Text-to-Speech for this message. * @arg {Number} [input.nonce] - Number-used-only-ONCE. The Discord client uses this to change the message color from grey to white. * @arg {Boolean} [input.typing] - Indicates whether the message should be sent with simulated typing. Based on message length. */ sendMessage(input, callback) { var message = Message.generate(input.message, input.embed); message.tts = (input.tts === true); message.nonce = input.nonce || message.nonce; if (input.typing) { var duration = typeof input.typing === 'number' ? input.typing : Math.max((message.content.length * 0.12) * 1000, 1000); return this.simulateTyping(input.to, duration, () => { delete(input.typing); this.sendMessage(input, callback); }); } this.resolveID(input.to, channelID => { this._req('post', Endpoints.MESSAGES(channelID), message, (err, res) => { handleResCB("Unable to send messages", err, res, callback); }); }); } /** * Pull a message object from Discord. * @arg {Object} input * @arg {Snowflake} input.channelID - The channel ID that the message is from. * @arg {Snowflake} input.messageID - The ID of the message. */ getMessage(input, callback) { this._req('get', Endpoints.MESSAGES(input.channelID, input.messageID), (err, res) => { handleResCB("Unable to get message", err, res, callback); }); } /** * Pull an array of message objects from Discord. * @arg {Object} input * @arg {Snowflake} input.channelID - The channel ID to pull the messages from. * @arg {Number} [input.limit] - How many messages to pull, defaults to 50. * @arg {Snowflake} [input.before] - Pull messages before this message ID. * @arg {Snowflake} [input.after] - Pull messages after this message ID. */ getMessages(input, callback) { var client = this, qs = {}, messages = [], lastMessageID = ""; var total = typeof(input.limit) !== 'number' ? 50 : input.limit; if (input.before) qs.before = input.before; if (input.after) qs.after = input.after; (function getMessages() { if (total > 100) { qs.limit = 100; total = total - 100; } else { qs.limit = total; } if (messages.length >= input.limit) return call(callback, [null, messages]); client._req('get', Endpoints.MESSAGES(input.channelID) + qstringify(qs), (err, res) => { if (err) return handleErrCB("Unable to get messages", callback); messages = messages.concat(res.body); lastMessageID = messages[messages.length - 1] && messages[messages.length - 1].id; if (lastMessageID) qs.before = lastMessageID; if (!res.body.length < qs.limit) return call(callback, [null, messages]); return setTimeout(getMessages, 1000); }); })(); } /** * Edit a previously sent message. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {Snowflake} input.messageID * @arg {String} input.message - The new message content * @arg {Object} [input.embed] - The new Discord Embed object */ editMessage(input, callback) { this._req('patch', Endpoints.MESSAGES(input.channelID, input.messageID), Message.generate(input.message, input.embed), (err, res) => { handleResCB("Unable to edit message", err, res, callback); }); } /** * Delete a posted message. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {Snowflake} input.messageID */ deleteMessage(input, callback) { this._req('delete', Endpoints.MESSAGES(input.channelID, input.messageID), (err, res) => { handleResCB("Unable to delete message", err, res, callback); }); } /** * Delete a batch of messages. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {Array<Snowflake>} input.messageIDs - An Array of message IDs, with a maximum of 100 indexes. */ deleteMessages(input, callback) { this._req('post', Endpoints.BULK_DELETE(input.channelID), {messages: input.messageIDs.slice(0, 100)}, (err, res) => { handleResCB("Unable to delete messages", err, res, callback); }); } /** * Pin a message to the channel. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {Snowflake} input.messageID */ pinMessage(input, callback) { this._req('put', Endpoints.PINNED_MESSAGES(input.channelID, input.messageID), (err, res) => { handleResCB("Unable to pin message", err, res, callback); }); } /** * Get an array of pinned messages from a channel. * @arg {Object} input * @arg {Snowflake} input.channelID */ getPinnedMessages(input, callback) { this._req('get', Endpoints.PINNED_MESSAGES(input.channelID), (err, res) => { handleResCB("Unable to get pinned messages", err, res, callback); }); } /** * Delete a pinned message from a channel. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {Snowflake} input.messageID */ deletePinnedMessage(input, callback) { this._req('delete', Endpoints.PINNED_MESSAGES(input.channelID, input.messageID), (err, res) => { handleResCB("Unable to delete pinned message", err, res, callback); }); } /** * Send 'typing...' status to a channel * @arg {Snowflake} channelID */ simulateTyping(channelID, time, callback) { if (time <= 0) return callback && callback(); this._req('post', Endpoints.TYPING(channelID), (err, res) => { handleResCB("Unable to simulate typing", err, res, () => { setTimeout(this.simulateTyping.bind(this), Math.min(time, 5000), channelID, time - 5000, callback); }); }); } /** * Replace Snowflakes with the names if applicable. * @arg {String} message - The message to fix. * @arg {Snowflake|null} serverID - Optional, the ID of the message's server of origin, used for nickname lookup */ fixMessage(message, serverID) { var client = this; return message.replace(/<@&(\d*)>|<@!(\d*)>|<@(\d*)>|<#(\d*)>/g, function(match, RID, NID, UID, CID) { var k, i; if (UID || CID) { if (client.users[UID]) return "@" + client.users[UID].username; if (client.channels[CID]) return "#" + client.channels[CID].name; } if (RID || NID) { k = Object.keys(client.servers); for (i=0; i<k.length; i++) { if (client.servers[k[i]].roles[RID]) return "@" + client.servers[k[i]].roles[RID].name; if (client.servers[k[i]].members[NID]) return "@" + client.servers[k[i]].members[NID].nick; } } }); } /** * Add an emoji reaction to a message. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {Snowflake} input.messageID * @arg {String} input.reaction - Either the emoji unicode or the emoji name:id/object. */ addReaction(input, callback) { // validate: is this.resolveID(input.channelID, channelID => {...}) needed? this._req('put', Endpoints.USER_REACTIONS(input.channelID, input.messageID, stringifyEmoji(input.reaction)), (err, res) => { handleResCB("Unable to add reaction", err, res, callback); }); } /** * Get an emoji reaction of a message. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {Snowflake} input.messageID * @arg {String} input.reaction - Either the emoji unicode or the emoji name:id/object. * @arg {String} [input.limit] */ getReaction(input, callback) { var qs = { limit: (typeof(input.limit) !== 'number' ? 100 : input.limit) }; this._req('get', Endpoints.MESSAGE_REACTIONS(input.channelID, input.messageID, stringifyEmoji(input.reaction)) + qstringify(qs), (err, res) => { handleResCB("Unable to get reaction", err, res, callback); }); } /** * Remove an emoji reaction from a message. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {Snowflake} input.messageID * @arg {Snowflake} [input.userID] * @arg {String} input.reaction - Either the emoji unicode or the emoji name:id/object. */ removeReaction(input, callback) { this._req('delete', Endpoints.USER_REACTIONS(input.channelID, input.messageID, stringifyEmoji(input.reaction), input.userID), (err, res) => { handleResCB("Unable to remove reaction", err, res, callback); }); } /** * Remove all emoji reactions from a message. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {Snowflake} input.messageID */ removeAllReactions(input, callback) { this._req('delete', Endpoints.MESSAGE_REACTIONS(input.channelID, input.messageID), (err, res) => { handleResCB("Unable to remove reactions", err, res, callback); }); } /* - DiscordClient - Methods - Guild Management - */ /** * Remove a user from a server. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.userID */ kick(input, callback) { this._req('delete', Endpoints.MEMBERS(input.serverID, input.userID), (err, res) => { handleResCB("Could not kick user", err, res, callback); }); } /** * Remove and ban a user from a server. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.userID * @arg {String} input.reason * @arg {Number} [input.lastDays] - Removes their messages up until this point, either 1 or 7 days. */ ban(input, callback) { var url = Endpoints.BANS(input.serverID, input.userID); var opts = {}; if (input.lastDays) { input.lastDays = Number(input.lastDays); input.lastDays = Math.min(input.lastDays, 7); input.lastDays = Math.max(input.lastDays, 1); opts["delete-message-days"] = input.lastDays; } if (input.reason) opts.reason = input.reason; url += qstringify(opts); this._req('put', url, (err, res) => { handleResCB("Could not ban user", err, res, callback); }); } /** * Unban a user from a server. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.userID */ unban(input, callback) { this._req('delete', Endpoints.BANS(input.serverID, input.userID), (err, res) => { handleResCB("Could not unban user", err, res, callback); }); } /** * Move a user between voice channels. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.userID * @arg {Snowflake} input.channelID */ moveUserTo(input, callback) { this._req('patch', Endpoints.MEMBERS(input.serverID, input.userID), {channel_id: input.channelID}, (err, res) => { handleResCB("Could not move the user", err, res, callback); }); } /** * Guild-mute the user from speaking in all voice channels. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.userID */ mute(input, callback) { this._req('patch', Endpoints.MEMBERS(input.serverID, input.userID), {mute: true}, (err, res) => { handleResCB("Could not mute user", err, res, callback); }); } /** * Remove the server-mute from a user. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.userID */ unmute(input, callback) { this._req('patch', Endpoints.MEMBERS(input.serverID, input.userID), {mute: false}, (err, res) => { handleResCB("Could not unmute user", err, res, callback); }); } /** * Guild-deafen a user. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.userID */ deafen(input, callback) { this._req('patch', Endpoints.MEMBERS(input.serverID, input.userID), {deaf: true}, (err, res) => { handleResCB("Could not deafen user", err, res, callback); }); } /** * Remove the server-deafen from a user. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.userID */ undeafen(input, callback) { this._req('patch', Endpoints.MEMBERS(input.serverID, input.userID), {deaf: false}, (err, res) => { handleResCB("Could not undeafen user", err, res, callback); }); } /** * Self-mute the client from speaking in all voice channels. * @arg {Snowflake} serverID */ muteSelf(serverID, callback) { var server = this.servers[serverID], channelID, voiceSession; if (!server) return handleErrCB(("Cannot find the server provided: " + serverID), callback); server.self_mute = true; if (!server.voiceSession) return call(callback, [null]); voiceSession = server.voiceSession; voiceSession.self_mute = true; channelID = voiceSession.channelID; if (!channelID) return call(callback, [null]); return call(callback, [send(this._ws, Payloads.UPDATE_VOICE(serverID, channelID, true, server.self_deaf))]); } /** * Remove the self-mute from the client. * @arg {Snowflake} serverID */ unmuteSelf(serverID, callback) { var server = this.servers[serverID], channelID, voiceSession; if (!server) return handleErrCB(("Cannot find the server provided: " + serverID), callback); server.self_mute = false; if (!server.voiceSession) return call(callback, [null]); voiceSession = server.voiceSession; voiceSession.self_mute = false; channelID = voiceSession.channelID; if (!channelID) return call(callback, [null]); return call(callback, [send(this._ws, Payloads.UPDATE_VOICE(serverID, channelID, false, server.self_deaf))]); } /** * Self-deafen the client. * @arg {Snowflake} serverID */ deafenSelf(serverID, callback) { var server = this.servers[serverID], channelID, voiceSession; if (!server) return handleErrCB(("Cannot find the server provided: " + serverID), callback); server.self_deaf = true; if (!server.voiceSession) return call(callback, [null]); voiceSession = server.voiceSession; voiceSession.self_deaf = true; channelID = voiceSession.channelID; if (!channelID) return call(callback, [null]); return call(callback, [send(this._ws, Payloads.UPDATE_VOICE(serverID, channelID, server.self_mute, true))]); } /** * Remove the self-deafen from the client. * @arg {Snowflake} serverID */ undeafenSelf(serverID, callback) { var server = this.servers[serverID], channelID, voiceSession; if (!server) return handleErrCB(("Cannot find the server provided: " + serverID), callback); server.self_deaf = false; if (!server.voiceSession) return call(callback, [null]); voiceSession = server.voiceSession; voiceSession.self_deaf = false; channelID = voiceSession.channelID; if (!channelID) return call(callback, [null]); return call(callback, [send(this._ws, Payloads.UPDATE_VOICE(serverID, channelID, server.self_mute, false))]); } /* Bot server management actions */ /** * Create a server [User only]. * @arg {Object} input * @arg {String} input.name - The server's name * @arg {String} [input.region] - The server's region code, check the Gitbook documentation for all of them. * @arg {String<Base64>} [input.icon] - The last part of a Base64 Data URI. `fs.readFileSync('image.jpg', 'base64')` is enough. */ createServer(input, callback) { var payload = {icon: null, name: null, region: null}; for (var key in input) { if (Object.keys(payload).indexOf(key) < 0) continue; payload[key] = input[key]; } if (input.icon) payload.icon = "data:image/jpg;base64," + input.icon; this._req('post', Endpoints.SERVERS(), payload, (err, res) => { try { this.servers[res.body.id] = {}; copyKeys(res.body, this.servers[res.body.id]); } catch(e) {} handleResCB("Could not create server", err, res, callback); }); } /** * Edit server information. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {String} [input.name] * @arg {String} [input.icon] * @arg {String} [input.region] * @arg {Snowflake} [input.afk_channel_id] - The ID of the voice channel to move a user to after the afk period. * @arg {Number} [input.afk_timeout] - Time in seconds until a user is moved to the afk channel. 60, 300, 900, 1800, or 3600. */ editServer(input, callback) { var payload, serverID = input.serverID, server; if (!this.servers[serverID]) return handleErrCB(("[editServer] Guild " + serverID + " not found."), callback); server = this.servers[serverID]; payload = { name: server.name, icon: server.icon, region: server.region, afk_channel_id: server.afk_channel_id, afk_timeout: server.afk_timeout }; for (var key in input) { if (Object.keys(payload).indexOf(key) < 0) continue; if (key === 'afk_channel_id') { if (server.channels[input[key]] && server.channels[input[key]].type === 'voice') payload[key] = input[key]; continue; } if (key === 'afk_timeout') { if ([60, 300, 900, 1800, 3600].indexOf(Number(input[key])) > -1) payload[key] = input[key]; continue; } payload[key] = input[key]; } if (input.icon) payload.icon = "data:image/jpg;base64," + input.icon; this._req('patch', Endpoints.SERVERS(input.serverID), payload, (err, res) => { handleResCB("Unable to edit server", err, res, callback); }); } /** * Edit the widget information for a server. * @arg {Object} input * @arg {Snowflake} input.serverID - The ID of the server whose widget you want to edit. * @arg {Boolean} [input.enabled] - Whether or not you want the widget to be enabled. * @arg {Snowflake} [input.channelID] - [Important] The ID of the channel you want the instant invite to point to. */ editServerWidget(input, callback) { var payload, url = Endpoints.SERVERS(input.serverID) + "/embed"; this._req('get', url, (err, res) => { if (err) return handleResCB("Unable to GET server widget settings. Can not edit without retrieving first.", err, res, callback); payload = { enabled: ('enabled' in input ? input.enabled : res.body.enabled), channel_id: ('channelID' in input ? input.channelID : res.body.channel_id) }; this._req('patch', url, payload, (err, res) => { handleResCB("Unable to edit server widget", err, res, callback); }); }); } /** * [User Account] Add an emoji to a server * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {String} input.name - The emoji's name * @arg {String<Base64>} input.image - The emoji's image data in Base64 */ addServerEmoji(input, callback) { var payload = { name: input.name, image: "data:image/png;base64," + input.image }; this._req('post', Endpoints.SERVER_EMOJIS(input.serverID), payload, (err, res) => { handleResCB("Unable to add emoji to the server", err, res, callback); }); } /** * [User Account] Edit a server emoji data (name only, currently) * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.emojiID - The emoji's ID * @arg {String} [input.name] * @arg {Array<Snowflake>} [input.roles] - An array of role IDs you want to limit the emoji's usage to */ editServerEmoji(input, callback) { var emoji, payload = {}; if ( !this.servers[input.serverID] ) return handleErrCB(("[editServerEmoji] Guild not available: " + input.serverID), callback); if ( !this.servers[input.serverID].emojis[input.emojiID]) return handleErrCB(("[editServerEmoji] Emoji not available: " + input.emojiID), callback); emoji = this.servers[input.serverID].emojis[input.emojiID]; payload.name = input.name || emoji.name; payload.roles = input.roles || emoji.roles; this._req('patch', Endpoints.SERVER_EMOJIS(input.serverID, input.emojiID), payload, (err, res) => { handleResCB("[editServerEmoji] Could not edit server emoji", err, res, callback); }); } /** * [User Account] Remove an emoji from a server * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.emojiID */ deleteServerEmoji(input, callback) { this._req('delete', Endpoints.SERVER_EMOJIS(input.serverID, input.emojiID), (err, res) => { handleResCB("[deleteServerEmoji] Could not delete server emoji", err, res, callback); }); } /** * Leave a server. * @arg {Snowflake} serverID */ leaveServer(serverID, callback) { this._req('delete', Endpoints.SERVERS_PERSONAL(serverID), (err, res) => { handleResCB("Could not leave server", err, res, callback); }); } /** * Delete a server owned by the client. * @arg {Snowflake} serverID */ deleteServer(serverID, callback) { this._req('delete', Endpoints.SERVERS(serverID), (err, res) => { handleResCB("Could not delete server", err, res, callback); }); } /** * Transfer ownership of a server to another user. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.userID */ transferOwnership(input, callback) { this._req('patch', Endpoints.SERVERS(input.serverID), {owner_id: input.userID}, (err, res) => { handleResCB("Could not transfer server ownership", err, res, callback); }); } /** * (Used to) Accept an invite to a server [User Only]. Can no longer be used. * @deprecated */ acceptInvite(NUL, callback) { return handleErrCB("acceptInvite can no longer be used", callback); } /** * (Used to) Generate an invite URL for a channel. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {Number} input.max_age * @arg {Number} input.max_uses * @arg {Boolean} input.temporary * @arg {Boolean} input.unique * * * @deprecated */ createInvite(input, callback) { var payload, allowed = ["channelID", "max_age", "max_uses", "temporary", "unique"]; if (Object.keys(input).length === 1 && input.channelID) { payload = { validate: client.internals.lastInviteCode || null }; } else { payload = { max_age: 0, max_uses: 0, // users? uses? temporary: false }; } allowed.forEach(function(name) { if (input[name]) payload[name] = input[name]; }); this._req('post', Endpoints.CHANNEL(payload.channelID) + "/invites", payload, (err, res) => { handleResCB('Unable to create invite', err, res, callback); }); } /** * Delete an invite code. * @arg {String} inviteCode */ deleteInvite(inviteCode, callback) { this._req('delete', Endpoints.INVITES(inviteCode), (err, res) => { handleResCB('Unable to delete invite', err, res, callback); }); } /** * Get information on an invite. * @arg {String} inviteCode */ queryInvite(inviteCode, callback) { this._req('get', Endpoints.INVITES(inviteCode), (err, res) => { handleResCB('Unable to get information about invite', err, res, callback); }); } /** * Get all invites for a server. * @arg {Snowflake} serverID */ getServerInvites(serverID, callback) { this._req('get', Endpoints.SERVERS(serverID) + "/invites", (err, res) => { handleResCB('Unable to get invite list for server' + serverID, err, res, callback); }); } /** * Get all invites for a channel. * @arg {Snowflake} channelID */ getChannelInvites(channelID, callback) { this._req('get', Endpoints.CHANNEL(channelID) + "/invites", (err, res) => { handleResCB('Unable to get invite list for channel' + channelID, err, res, callback); }); } /** * Create a channel. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {String} input.name * @arg {String} [input.type] - 'text' or 'voice', defaults to 'text. * @arg {Snowflake} [input.parentID] - category ID? */ createChannel(input, callback) { var payload = { name: input.name, type: (['text', 'voice'].indexOf(input.type) < 0) ? 'text' : input.type, parent_id: input.parentID }; this._req('post', Endpoints.SERVERS(input.serverID) + "/channels", payload, (err, res) => { try { Channel.create(this, res.body); } catch(e) {} handleResCB('Unable to create channel', err, res, callback); }); } /** * Create a Direct Message channel. * @arg {Snowflake} userID */ createDMChannel(userID, callback) { this._req('post', Endpoints.USER(this.id) + "/channels", {recipient_id: userID}, (err, res) => { if (!err && goodResponse(res)) DMChannel.create(this, res.body); handleResCB("Unable to create DM Channel", err, res, callback); }); } /** * Delete a channel. * @arg {Snowflake} channelID */ deleteChannel(channelID, callback) { this._req('delete', Endpoints.CHANNEL(channelID), (err, res) => { handleResCB("Unable to delete channel", err, res, callback); }); } /** * Edit a channel's information. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {String} [input.name] * @arg {String} [input.topic] - The topic of the channel. * @arg {Number} [input.bitrate] - [Voice Only] The bitrate for the channel. * @arg {Number} [input.position] - The channel's position on the list. * @arg {Number} [input.user_limit] - [Voice Only] Imposes a user limit on a voice channel. */ editChannelInfo(input, callback) { var channel, payload; try { channel = this.channels[input.channelID]; payload = { name: channel.name, topic: channel.topic, bitrate: channel.bitrate, position: channel.position, user_limit: channel.user_limit, nsfw: channel.nsfw, parent_id: (input.parentID === undefined ? channel.parent_id : input.parentID) }; for (var key in input) { if (Object.keys(payload).indexOf(key) < 0) continue; if (+input[key]) { if (key === 'bitrate') { payload.bitrate = Math.min( Math.max( input.bitrate, 8000), 96000); continue; } if (key === 'user_limit') { payload.user_limit = Math.min( Math.max( input.user_limit, 0), 99); continue; } } payload[key] = input[key]; } this._req('patch', Endpoints.CHANNEL(input.channelID), payload, (err, res) => { handleResCB("Unable to edit channel", err, res, callback); }); } catch(e) {return handleErrCB(e, callback);} } /** * Edit (or creates) a permission override for a channel. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {Snowflake} [input.userID] * @arg {Snowflake} [input.roleID] * @arg {Array<Number>} input.allow - An array of permissions to allow. Discord.Permissions.XXXXXX. * @arg {Array<Number>} input.deny - An array of permissions to deny, same as above. * @arg {Array<Number>} input.default - An array of permissions that cancels out allowed and denied permissions. */ editChannelPermissions(input, callback) { //Will shrink this up later var payload, pType, ID, channel, permissions, allowed_values; if (!input.userID && !input.roleID) return handleErrCB("[editChannelPermissions] No userID or roleID provided", callback); if (!this.channels[input.channelID]) return handleErrCB(("[editChannelPermissions] No channel found for ID: " + input.channelID), callback); if (!input.allow && !input.deny && !input.default) return handleErrCB("[editChannelPermissions] No allow, deny or default array provided.", callback); pType = input.userID ? 'user' : 'role'; ID = input[pType + "ID"]; channel = this.channels[ input.channelID ]; permissions = channel.permissions[pType][ID] || { allow: 0, deny: 0 }; allowed_values = [0, 4, 28, 29]; if (channel.type === 'text' || channel.type == Discord.ChannelTypes.GUILD_TEXT || channel.type == Discord.ChannelTypes.GUILD_CATEGORY) { allowed_values = allowed_values.concat([6, 10, 11, 12, 13, 14, 15, 16, 17, 18]); } if (channel.type === 'voice' || channel.type == Discord.ChannelTypes.GUILD_VOICE || channel.type == Discord.ChannelTypes.GUILD_CATEGORY) { allowed_values = allowed_values.concat([8, 10, 20, 21, 22, 23, 24, 25]); } //Take care of allow first if (type(input.allow) === 'array') { input.allow.forEach(function(perm) { if (allowed_values.indexOf(perm) < 0) return; if (hasPermission(perm, permissions.deny)) { permissions.deny = removePermission(perm, permissions.deny); } permissions.allow = givePermission(perm, permissions.allow); }); } else if (typeof input.allow === 'number') { //If people want to be a smartass and calculate their permission number themselves. permissions.allow = input.allow; } //Take care of deny second if (type(input.deny) === 'array') { input.deny.forEach(function(perm) { if (allowed_values.indexOf(perm) < 0) return; if (hasPermission(perm, permissions.allow)) { permissions.allow = removePermission(perm, permissions.allow); } permissions.deny = givePermission(perm, permissions.deny); }); } else if (typeof input.deny === 'number') { permissions.deny = input.deny; } //Take care of defaulting last if (type(input.default) === 'array') { input.default.forEach(function(perm) { if (allowed_values.indexOf(perm) < 0) return; permissions.allow = removePermission(perm, permissions.allow); permissions.deny = removePermission(perm, permissions.deny); }); } else if (typeof input.default === 'number') { permissions.default = input.default } payload = { type: (pType === 'user' ? 'member' : 'role'), id: ID, deny: permissions.deny, allow: permissions.allow }; this._req('put', Endpoints.CHANNEL(input.channelID) + "/permissions/" + ID, payload, (err, res) => { handleResCB('Unable to edit permission', err, res, callback); }); } /** * Delete a permission override for a channel. * @arg {Object} input * @arg {Snowflake} input.channelID * @arg {Snowflake} [input.userID] * @arg {Snowflake} [input.roleID] */ deleteChannelPermission(input, callback) { var payload, pType, ID; if (!input.userID && !input.roleID) return handleErrCB("[deleteChannelPermission] No userID or roleID provided", callback); if (!this.channels[input.channelID]) return handleErrCB(("[deleteChannelPermission] No channel found for ID: " + input.channelID), callback); pType = input.userID ? 'user' : 'role'; ID = input[pType + "ID"]; payload = { type: (pType === 'user' ? 'member' : 'role'), id: ID }; this._req('delete', Endpoints.CHANNEL(input.channelID) + "/permissions/" + ID, payload, (err, res) => { handleResCB('Unable to delete permission', err, res, callback); }); } /** * Create a role for a server. * @arg {Snowflake} serverID */ createRole(serverID, callback) { this._req('post', Endpoints.ROLES(serverID), (err, res) => { try { Role.create(this, res.body); } catch(e) {} handleResCB("Unable to create role", err, res, callback); }); } /** * Edit a role. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.roleID - The ID of the role. * @arg {String} [input.name] * @arg {String} [input.color] - A color value as a number. Recommend using Hex numbers, as they can map to HTML colors (0xF35353 === #F35353). * @arg {Boolean} [input.hoist] - Separates the users in this role from the normal online users. * @arg {Object} [input.permissions] - An Object containing the permission as a key, and `true` or `false` as its value. Read the Permissions doc. * @arg {Boolean} [input.mentionable] - Toggles if users can @Mention this role. */ editRole(input, callback) { var role, payload; try { role = new Role(this.servers[input.serverID].roles[input.roleID]); payload = { name: role.name, color: role.color, hoist: role.hoist, permissions: role._permissions, mentionable: role.mentionable, position: role.position }; for (var key in input) { if (Object.keys(payload).indexOf(key) < 0) continue; if (key === 'permissions') { for (var perm in input[key]) { role[perm] = input[key][perm]; payload.permissions = role._permissions; } continue; } if (key === 'color') { if (String(input[key])[0] === '#') payload.color = parseInt(String(input[key]).replace('#', '0x'), 16); if (Discord.Colors[input[key]]) payload.color = Discord.Colors[input[key]]; if (type(input[key]) === 'number') payload.color = input[key]; continue; } payload[key] = input[key]; } this._req('patch', Endpoints.ROLES(input.serverID, input.roleID), payload, (err, res) => { handleResCB("Unable to edit role", err, res, callback); }); } catch(e) {return handleErrCB(('[editRole] ' + e), callback);} } /** * Move a role up or down relative to it's current position. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.roleID - The ID of the role. * @arg {Number} input.position - A relative number to move the role up or down. */ moveRole(input, callback) { if (input.position === 0) return handleErrCB("Desired role position is same as current", callback); // Don't do anything if they don't want it to move try { var server = this.servers[input.serverID]; var role = server.roles[input.roleID]; var curPos = role.position; var newPos = curPos + input.position; newPos = Math.max(newPos, 1); newPos = Math.min(newPos, Object.keys(server.roles).length - 1); var currentOrder = []; for (var roleID in server.roles) { if (roleID == input.serverID) continue; // skip @everyone currentOrder.push(server.roles[roleID]); } currentOrder.splice(newPos - 1, 0, role); var payload = currentOrder.map((role,idx) => ({id: role.id, position: idx+1})); this._req('patch', Endpoints.ROLES(input.serverID), payload, (err, res) => { handleResCB("Unable to move role", err, res, callback); }); } catch (e) {return handleErrCB(e, callback);} } /** * Delete a role. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.roleID */ deleteRole(input, callback) { this._req('delete', Endpoints.ROLES(input.serverID, input.roleID), (err, res) => { handleResCB("Could not remove role", err, res, callback); }); } /** * Add a user to a role. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.roleID * @arg {Snowflake} input.userID */ addToRole(input, callback) { this._req('put', Endpoints.MEMBER_ROLES(input.serverID, input.userID, input.roleID), (err, res) => { handleResCB("Could not add role", err, res, callback); }); } /** * Remove a user from a role. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.roleID * @arg {Snowflake} input.userID */ removeFromRole(input, callback) { this._req('delete', Endpoints.MEMBER_ROLES(input.serverID, input.userID, input.roleID), (err, res) => { handleResCB("Could not remove role", err, res, callback); }); } /** * Edit a user's nickname. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.userID * @arg {String} input.nick - The nickname you'd like displayed. */ editNickname(input, callback) { var payload = {nick: String( input.nick ? input.nick : "" )}; var url = input.userID === this.id ? Endpoints.MEMBERS(input.serverID) + "/@me/nick" : Endpoints.MEMBERS(input.serverID, input.userID); this._req('patch', url, payload, (err, res) => { handleResCB("Could not change nickname", err, res, callback); }); } /** * Edit a user's note. * @arg {Object} input * @arg {Snowflake} input.userID * @arg {String} input.note - The note content that you want to use. */ editNote(input, callback) { this._req('put', Endpoints.NOTE(input.userID), {note: input.note}, (err, res) => { handleResCB("Could not edit note", err, res, callback); }); } /** * Retrieve a user object from Discord, the library already caches users, however. * @arg {Object} input * @arg {Snowflake} input.serverID * @arg {Snowflake} input.userID */ getMember(input, callback) { this._req('get', Endpoints.MEMBERS(input.serverID, input.userID), (err, res) => { handleResCB("Could not get member", err, res, callback); }); } /** * Retrieve a group of user objects from Discord. * @arg {Object} input * @arg {Number} [input.limit] - The amount of users to pull, defaults to 50. * @arg {Snowflake} [input.after] - The offset using a user ID. */ getMembers(input, callback) { var qs = {}; qs.limit = (typeof(input.limit) !== 'number' ? 50 : input.limit); if (input.after) qs.after = input.after; this._req('get', Endpoints.MEMBERS(input.serverID) + qstringify(qs), (err, res) => { handleResCB("Could not get members", err, res, callback); }); } /** * Get the ban list from a server * @arg {Snowflake} serverID */ getBans(serverID, callback) { this._req('get', Endpoints.BANS(serverID), (err, res) => { handleResCB("Could not get ban list", err, res, callback); }); } /** * Get all webhooks for a server * @arg {Snowflake} serverID */ getServerWebhooks(serverID, callback) { this._req('get', Endpoints.SERVER_WEBHOOKS(serverID), (err, res) => { handleResCB("Could not get server Webhooks", err, res, callback); }); } /** * Get webhooks from a channel * @arg {Snowflake} channelID */ getChannelWebhooks(channelID, callback) { this._req('get', Endpoints.CHANNEL_WEBHOOKS(channelID), (err, res) => { handleResCB("Could not get channel Webhooks", err, res, callback); }); } /** * Create a webhook for a server * @arg {Snowflake} serverID */ createWebhook(serverID, callback) { this._req('post', Endpoints.SERVER_WEBHOOKS(serverID), (err, res) => { handleResCB("Could not create a Webhook", err, res, callback); }); } /** * Edit a webhook * @arg {Object} input * @arg {Snowflake} input.webhookID - The Webhook's ID * @arg {String} [input.name] * @arg {String<Base64>} [input.avatar] * @arg {String} [input.channelID] */ editWebhook(input, callback) { var payload = {}, allowed = ['avatar', 'name']; this._req('get', Endpoints.WEBHOOKS(input.webhookID), (err, res) => { if (err || !goodResponse(res)) return handleResCB("Couldn't get webhook, do you have permissions to access it?", err, res, callback); allowed.forEach(function(key) { payload[key] = (key in input ? input[key] : res.body[key]); }); payload.channel_id = input.channelID || res.body.channel_id; this._req('patch', Endpoints.WEBHOOKS(input.webhookID), payload, (err, res) => { return handleResCB("Couldn't update webhook", err, res, callback); }); }); } /* --- Voice --- */ /** * Join a voice channel. * @arg {Snowflake} channelID */ joinVoiceChannel(channelID, callback) { var serverID, server, channel, voiceSession; try { serverID = this.channels[channelID].guild_id; server = this.servers[serverID]; channel = server.channels[channelID]; } catch(e) {} if (!serverID) return handleErrCB(("Cannot find the server related to the channel provided: " + channelID), callback); if (channel.type !== 'voice' && channel.type !== 2) return handleErrCB(("Selected channel is not a voice channel: " + channelID), callback); if (this._vChannels[channelID]) return handleErrCB(("Voice channel already active: " + channelID), callback); voiceSession = this.getVoiceSession(channelID, server); voiceSession.self_mute = server.self_mute; voiceSession.self_deaf = server.self_deaf; this.checkVoiceReady(voiceSession, callback); return send(this._ws, Payloads.UPDATE_VOICE(serverID, channelID, server.self_mute, server.self_deaf)); } /** * Leave a voice channel. * @arg {Snowflake} channelID */ leaveVoiceChannel(channelID, callback) { if (!this._vChannels[channelID]) return handleErrCB(("Not in the voice channel: " + channelID), callback); return this._leaveVoiceChannel(channelID, callback); } /** * Prepare the client for sending/receiving audio. * @arg {Snowflake|Object} channelObj - Either the channel ID, or an Object with `channelID` as a key and the ID as the value. * @arg {Number} [channelObj.maxStreamSize] - The size in KB that you wish to receive before pushing out earlier data. Required if you want to store or receive incoming audio. * @arg {Boolean} [channelObj.stereo] - Sets the audio to be either stereo or mono. Defaults to true. */ getAudioContext(channelObj, callback) { // #q/qeled gave a proper timing solution. Credit where it's due. if (!isNode) return handleErrCB("Using audio in the browser is currently not supported.", callback); var channelID = channelObj.channelID || channelObj, voiceSession = this._vChannels[channelID], encoder = this.chooseAudioEncoder(['ffmpeg', 'avconv']); if (!voiceSession) return handleErrCB(("You have not joined the voice channel: " + channelID), callback); if (voiceSession.ready !== true) return handleErrCB(("The connection to the voice channel " + channelID + " has not been initialized yet."), callback); if (!encoder) return handleErrCB("You need either 'ffmpeg' or 'avconv' and they need to be added to PATH", callback); voiceSession.audio = voiceSession.audio || new AudioCB( voiceSession, channelObj.stereo === false ? 1 : 2, encoder, Math.abs(Number(channelObj.maxStreamSize))); return call(callback, [null, voiceSession.audio]); } /* --- Misc --- */ /** * Retrieves all offline (and online, if using a user account) users, fires the `allUsers` event when done. */ getAllUsers(callback) { var servers = Object.keys(this.servers).filter(function(s) { s = this.servers[s]; if (s.members) return s.member_count !== Object.keys(s.members).length && (this.bot ? s.large : true); }, this); if (!servers[0]) { this.emit('allUsers'); return handleErrCB("There are no users to be collected", callback); } if (!this.bot) send(this._ws, Payloads.ALL_USERS(this)); return this.getOfflineUsers(servers, callback); } resolveID(ID, callback) { /*Get channel from ServerID, ChannelID or UserID. Only really used for sendMessage and uploadFile.*/ //Callback used instead of return because requesting seems necessary. if (this._uIDToDM[ID]) return callback(this._uIDToDM[ID]); //If it's a UserID, and it's in the UserID : ChannelID cache, use the found ChannelID //If the ID isn't in the UserID : ChannelID cache, let's try seeing if it belongs to a user. if (this.users[ID]) return this.createDMChannel(ID, function(err, res) { if (err) return console.log("Internal ID resolver error: " + JSON.stringify(err)); callback(res.id); }); return callback(ID); //Finally, the ID must not belong to a User, so send the message directly to it, as it must be a Channel's. } checkForAllServers(ready, message) { var all = Object.keys(this.servers).every(s => !this.servers[s].unavailable); if (all || ready[0]) return void(this._ready = true && this.emit('ready', message)); return setTimeout(this.checkForAllServers.bind(this), 0, ready, message); } cacheMessage(message) { var cache = this._messageCache, limit = this._messageCacheLimit, channelID = message.channel_id; if (!cache[channelID]) cache[channelID] = {}; if (limit !== -1) { var k = Object.keys(cache[channelID]); if (k.length > limit) delete(cache[channelID][k[0]]); } cache[channelID][message.id] = message; } getCacheMessage(channelID, messageID) { var cache = this._messageCache; if (!cache[channelID]) return null; return cache[channelID][messageID] || null; } /* --- Initializing --- */ init(options = {}) { this.servers = {}; this.channels = {}; this.users = {}; this.directMessages = {}; this.internals = { oauth: {}, version: CURRENT_VERSION, settings: {} }; this._connecting = true; this.setupPing(); return this.getToken(options); } getToken(options = {}) { if (options.token) return this.getGateway(options.token); if (!isNode) { //Read from localStorage? Sounds like a bad idea, but I'll leave this here. } } getGateway(token) { this.internals.token = token; return APIRequest('get', Endpoints.GATEWAY, (err, res) => { if (err || !goodResponse(res)) { this._connecting = false; return this.emit("disconnect", "Error GETing gateway:\n" + stringifyError(res), 0); } return this.startConnection(res.body.url + "/?encoding=json&v=" + GATEWAY_VERSION); }); } startConnection(gateway) { this._ws = new Websocket(gateway); this.internals.gatewayUrl = gateway; this._ws.once('close', this.handleWSClose.bind(this)); this._ws.once('error', this.handleWSClose.bind(this)); this._ws.on('message', this.handleWSMessage.bind(this)); } getOfflineUsers(servArr, callback) { if (!servArr[0]) return call(callback); send(this._ws, Payloads.OFFLINE_USERS(servArr)); return setTimeout( this.getOfflineUsers.bind(this), 0, servArr, callback ); } setupPing() { var obj = this.internals; applyProperties(obj, [ ["_pings", []], ["_lastHB", 0] ]); Object.defineProperty(obj, 'ping', { get() { return ((obj._pings.reduce(function(p, c) { return p + c; }, 0) / obj._pings.length) || 0) | 0; }, set() {} }); } validateShard(shard) { return ( type(shard) === 'array' && shard.length === 2 && shard[0] <= shard[1] && shard[1] > 1 ) ? shard : null; } identifyOrResume() { var payload, internals = this.internals; if (internals.sequence && internals.token && internals.sessionID) { payload = Payloads.RESUME(this); } else { payload = Payloads.IDENTIFY(this); if (this._shard) payload.d.shard = this._shard; } this._connecting = false; return send(this._ws, payload); } /* - Functions - Websocket Handling - */ handleWSMessage(data, flags) { var message = decompressWSMessage(data, flags); switch (message.op) { case Discord.Codes.Gateway.DISPATCH: //Event dispatched - update our sequence number this.internals.sequence = message.s; break; case Discord.Codes.Gateway.HEARTBEAT: //Heartbeat requested by Discord - send one immediately send(this._ws, Payloads.HEARTBEAT(this)); break; case Discord.Codes.Gateway.RECONNECT: //Reconnect requested by discord clearTimeout(this.internals.heartbeat); this._ws.close(1000, 'Reconnect requested by Discord'); break; case Disord.Codes.Gateway.INVALID_SESSION: //Disconnect after an Invalid Session //Disconnect the client if the client has received an invalid session id if(!message.d) { delete(this.internals.sequence); delete(this.internals.sessionID); //Send new identify after 1-5 seconds, chosen randomly (per Gateway docs) setTimeout(() => this.identifyOrResume(), Math.random()*4000+1000); } else this.identifyOrResume(); break; case Discord.Codes.Gateway.HELLO: //Start keep-alive interval //Disconnect the client if no ping has been received //in 15 seconds (I think that's a decent duration) //Since v3 you send the IDENTIFY/RESUME payload here. this.identifyOrResume(); //if (!this.presence) this.presence = { status: "online", since: Date.now() }; client.presenceStatus = 'online'; this.connected = true; this._mainKeepAlive = setInterval(() => { this.internals.heartbeat = setTimeout(() => { this._ws && this._ws.close(1001, "No heartbeat received"); }, message.d.heartbeat_interval); this.internals._lastHB = Date.now(); send(this._ws, Payloads.HEARTBEAT(this)); }, message.d.heartbeat_interval); break; case Discord.Codes.Gateway.HEARTBEAK_ACK: clearTimeout(this.internals.heartbeat); this.internals._pings.unshift(Date.now() - this.internals._lastHB); this.internals._pings = this.internals._pings.slice(0, 10); break; } //Events this.emit('any', message); //TODO: Remove in v3 this.emit('debug', message); try { let evt = Discord.Events[message.t]; console.log(evt); return this['handleWS'+evt](message, message.d); } catch (e) {} } handleWSready(message, data) { copyKeys(data.user, this); this.internals.sessionID = data.session_id; // get Server Info for (let server of data.guilds) { Guild.create(this, server); } // get Direct Messages for (let DM of data.private_channels) { DMChannel.create(this, DM); } if (this.bot) this.getOauthInfo((err, res) => { if (err) return console.log(err); this.internals.oauth = res; this.inviteURL = "https://discordapp.com/oauth2/authorize?client_id=" + res.id + "&scope=bot"; }); if (!this.bot) this.getAccountSettings((err, res) => { if (err) return console.log(err); this.internals.settings = res; }); return (function() { if (this._ready) return; var ready = [false]; setTimeout(function() { ready[0] = true; }, 3500); this.checkForAllServers(ready, message); }).call(this); } handleWSmessageCreate(message, data) { this.emit('message', data.author.username, data.author.id, data.channel_id, data.content, message); emit(this, message, data.author.username, data.author.id, data.channel_id, data.content); return this.cacheMessage(data); } handleWSmessageUpdate(message, data) { try { // if a message that existed before the client went online gets updated/edited, // then this will not have a cached version of the message var old = copy(this.getCacheMessage(data.channel_id, data.id)); emit(this, message, old, data); } catch (e) { emit(this, message, undefined, data); } return this.cacheMessage(data); } handleWSpresenceUpdate(message, data) { if (!data.guild_id) return; var serverID = data.guild_id; var userID = data.user.id; if (!this.users[userID]) User.create(this, data.user); var user = this.users[userID]; var member = this.servers[serverID].members[userID] || {}; copyKeys(data.user, user); user.game = data.game; copyKeys(data, member, ['user', 'guild_id', 'game']); this.emit('presence', user.username, user.id, member.status, user.game, message); return emit(this, message); } handleWSuserUpdate(message, data) { User.update(this, data); return emit(this, message); } handleWSuserSettingsUpdate(message, data) { copyKeys(data, this.internals); return emit(this, message); } handleWSguildCreate(message, data) { return emit(this, message, Guild.create(this, data)); } handleWSguildUpdate(message, data) { var old = copy(this.servers[data.id]); return emit(this, message, old, Guild.update(this, data)); } handleWSguildDelete(message, data) { return emit(this, message, Guild.delete(this, data)); } handleWSguildMemberAdd(message, data) { // Add or replace User object. User.create(this, data.user); return emit(this, message, Member.create(this, data)); } handleWSguildMemberUpdate(message, data) { var server = this.servers[data.guild_id]; var old = copy(server.members[data.user.id]); return emit(this, message, old, Member.update(this, data)); } handleWSguildMemberRemove(message, data) { if (data.user && data.user.id === this.id) return; return emit(this, message, Member.delete(this, data)); } handleWSguildRoleCreate(message, data) { return emit(this, message, Role.create(this, data)); } handleWSguildRoleUpdate(message, data) { var server = this.servers[data.guild_id]; var old = copy(server.roles[data.role.id]); return emit(this, message, old, Role.update(this, data)); } handleWSguildRoleDelete(message, data) { var server = this.servers[data.guild_id]; return emit(this, message, Role.delete(this, data)); //return emit(this, message); } handleWSchannelCreate(message, data) { var channel; if (data.is_private || data.type == Discord.ChannelTypes.DM) { if (this.directMessages[data.id]) return; // already have this channel = DMChannel.create(this, data); } else { if (this.channels[data.id]) return; channel = Channel.create(this, data); } return emit(this, message, channel); } handleWSchannelUpdate(message, data) { var old = copy(this.channels[data.id]); return emit(this, message, old, Channel.update(this, data)); } handleWSchannelDelete(message, data) { if (data.is_private || data.type == Discord.ChannelTypes.DM) { return emit(this, message, DMChannel.delete(this, data)); } return emit(this, message, Channel.delete(this, data)); } handleWSguildEmojisUpdate(message, data) { var server = this.servers[data.guild_id]; var old = copy(server.emojis); return emit(this, message, old, Emoji.update(client, data.emojis)); } handleWSvoiceStateUpdate(message, data) { var serverID = data.guild_id, channelID = data.channel_id, userID = data.user_id, server = this.servers[serverID], mute = !!data.mute, self_mute = !!data.self_mute, deaf = !!data.deaf, self_deaf = !!data.self_deaf; try { currentVCID = server.members[userID].voice_channel_id; if (currentVCID) delete( server.channels[currentVCID].members[userID] ); if (channelID) server.channels[channelID].members[userID] = data; server.members[userID].mute = (mute || self_mute); server.members[userID].deaf = (deaf || self_deaf); server.members[userID].voice_channel_id = channelID; } catch(e) {} if (userID === this.id) { server.self_mute = self_mute; server.self_deaf = self_deaf; if (channelID === null) { if (server.voiceSession) this._leaveVoiceChannel(server.voiceSession.channelID); server.voiceSession = null; } else { if (!server.voiceSession) { server.voiceSession = this.getVoiceSession(channelID, server); } if (channelID !== server.voiceSession.channelID) { delete( this._vChannels[server.voiceSession.channelID] ); this.getVoiceSession(channelID, server).channelID = channelID; } server.voiceSession.session = data.session_id; server.voiceSession.self_mute = self_mute; server.voiceSession.self_deaf = self_deaf; } } return emit(this, message); } handleWSvoiceServerUpdate(message, data) { var serverID = data.guild_id; var server = this.servers[serverID]; server.voiceSession.token = data.token; server.voiceSession.serverID = serverID; server.voiceSession.endpoint = data.endpoint; this.joinVoiceChannel(server.voiceSession); return emit(this, message); } handleWSguildMembersChunk(message, data) { Guild.sync(this, data); // tally up the number of existing members and compare with the expected member count var all = Object.keys(this.servers).every(function(serverID) { var server = client.servers[serverID]; return server.member_count === Object.keys(server.members).length; }); if (all) return this.emit("allUsers"); return emit(this, message); } handleWSguildSync(message, data) { Guild.sync(this, data); return emit(this, message); } handleWSClose(code, data) { var eMsg = Discord.Codes.WebSocket[code] || data; clearInterval(this._mainKeepAlive); this.connected = false; removeAllListeners(this._ws, 'message'); if ([1001, 1006].indexOf(code) > -1) return this.getGateway(this.internals.token); this._ready = false; this._ws = null; this.emit("disconnect", eMsg, code); } /* - Functions - Voice - */ _joinVoiceChannel(voiceSession) { var vWS, vUDP, endpoint = voiceSession.endpoint.split(":")[0]; //this.handleVoiceChannelChange(voiceSession); voiceSession.ws = {}; voiceSession.udp = {}; voiceSession.members = {}; voiceSession.error = null; voiceSession.ready = false; voiceSession.joined = false; voiceSession.translator = {}; voiceSession.wsKeepAlive = null; voiceSession.udpKeepAlive = null; voiceSession.keepAlivePackets = 0; voiceSession.emitter = new EventEmitter(); if (isNode) voiceSession.keepAliveBuffer = new Buffer(8).fill(0); vWS = voiceSession.ws.connection = new Websocket("wss://" + endpoint); if (isNode) return DNS.lookup(endpoint, (err, address) => { if (err) return void(voiceSession.error = err); voiceSession.address = address; vUDP = voiceSession.udp.connection = UDP.createSocket("udp4"); vUDP.bind({exclusive: true}); vUDP.once('message', handleUDPMessage.bind(this, voiceSession)); vWS.once('open', this.handlevWSOpen.bind(this, voiceSession)); vWS.on('message', this.handlevWSMessage.bind(this, voiceSession)); vWS.once('close', this.handlevWSClose.bind(this, voiceSession)); }); vWS.once('open', this.handlevWSOpen.bind(this, voiceSession)); vWS.on('message', this.handlevWSMessage.bind(this, voiceSession)); vWS.once('close', this.handlevWSClose.bind(this, voiceSession)); return void(voiceSession.joined = true); } _leaveVoiceChannel(channelID, callback) { if (!this._vChannels[channelID]) return; try { this._vChannels[channelID].ws.connection.close(); this._vChannels[channelID].udp.connection.close(); } catch(e) {} send(this._ws, Payloads.UPDATE_VOICE(this.channels[channelID].guild_id, null, false, false)); return call(callback, [null]); } getVoiceSession(channelID, server) { if (!channelID) return null; return this._vChannels[channelID] ? this._vChannels[channelID] : this._vChannels[channelID] = (server && server.voiceSession) || new VoiceSession(server, channelID); } checkVoiceReady(voiceSession, callback) { return setTimeout(() => { if (voiceSession.error) return call(callback, [voiceSession.error]); if (voiceSession.joined) return call(callback, [null, voiceSession.emitter]); return this.checkVoiceReady(voiceSession, callback); }, 1); } /* - Functions - Voice - Handling - */ handlevWSOpen(voiceSession) { return send(voiceSession.ws.connection, Payloads.VOICE_IDENTIFY(this.id, voiceSession)); } handlevWSMessage(voiceSession, vMessage, vFlags) { var vData = decompressWSMessage(vMessage, vFlags); switch (vData.op) { case Discord.Voice.READY: //Ready (Actually means you're READY to initiate the UDP connection) this.handlevWSready(voiceSession, vData); break; case Discord.Voice.SESSION_DESCRIPTION: //Session Description (Actually means you're ready to send audio... stupid Discord Devs :I) this.handlevWSsessionDescription(voiceSession, vData); break; case Discord.Voice.SPEAKING: //Speaking (At least this isn't confusing!) this.handlevWSspeaking(voiceSession, vData); break; } } handlevWSready(voiceSession, vData) { copyKeys(vData.d, voiceSession.ws); voiceSession.initKeepAlive(vData); if (!isNode) return; var udpDiscPacket = new Buffer(70); udpDiscPacket.writeUIntBE(vData.d.ssrc, 0, 4); voiceSession.udp.connection.send( udpDiscPacket, 0, udpDiscPacket.length, vData.d.port, voiceSession.address, err => { if (err) { this._leaveVoiceChannel(voiceSession.channelID); handleErrCB("UDP discovery error", callback); } }); return void(voiceSession.udpKeepAlive = setInterval(keepUDPAlive, 5000, voiceSession)); } handlevWSsessionDescription(voiceSession, vData) { voiceSession.prepareToSend(vData); } handlevWSspeaking(voiceSession, vData) { voiceSession.receiveSpeaking(vData); } handlevWSClose(voiceSession) { //Emit the disconnect event first voiceSession.emitter.emit("disconnect", voiceSession.channelID); voiceSession.emitter = null //Kill encoder and decoders var audio = voiceSession.audio, members = voiceSession.members; if (audio) { if (audio._systemEncoder) audio._systemEncoder.kill(); if (audio._mixedDecoder) audio._mixedDecoder.destroy(); } Object.keys(members).forEach(function(ID) { var member = members[ID]; if (member.decoder) member.decoder.destroy(); }); //Clear intervals and remove listeners clearInterval(voiceSession.wsKeepAlive); clearInterval(voiceSession.udpKeepAlive); removeAllListeners(voiceSession.emitter); removeAllListeners(voiceSession.udp.connection, 'message'); removeAllListeners(voiceSession.ws.connection, 'message'); return delete(this._vChannels[voiceSession.channelID]); } handleUDPMessage(voiceSession, msg, rinfo) { var buffArr = JSON.parse(JSON.stringify(msg)).data, vDiscIP = "", vDiscPort; for (var i=4; i<buffArr.indexOf(0, i); i++) { vDiscIP += String.fromCharCode(buffArr[i]); } vDiscPort = msg.readUIntLE(msg.length - 2, 2).toString(10); return send(voiceSession.ws.connection, Payloads.VOICE_DISCOVERY(vDiscIP, vDiscPort, 'xsalsa20_poly1305')); } }
JavaScript
class Request { constructor(config = {}, reqInterceptor = null, resInterceptor = null, successHandler = null, failHandler = null, completeHandler = null) { // base this.baseUrl = config.baseUrl this.header = config.header || { "Content-Type": "application/json;charset=UTF-8" }, // global callback for success/fail/complete. They are also response interceptors. this.success = successHandler this.fail = failHandler this.complete = completeHandler // interceptors this.requestInterceptor = reqInterceptor this.responseInterceptor = resInterceptor } // type: request/upload/download. // the success/fail/complete handler will not override the global, it will just call after global async request(options, successHandler = null, failHandler = null, completeHandler = null) { const task = options.task || false const type = options.type || "request" // delete options.task let config = null try { config = await requestConfig(this, options, successHandler, failHandler, completeHandler) } catch (e) { // reject the error return Promise.reject(e) } if (!config || typeof config != 'object') { // reject a blank object, if we do not reject it, it will be resolved return Promise.reject({}) } const that = this if (task) { config["success"] = (response) => { if (that.responseInterceptor) { that.responseInterceptor(response, config) } that.success && that.success(response) successHandler && successHandler(response) } config["fail"] = (response) => { that.fail && that.fail(response) failHandler && failHandler(response) } config["complete"] = (response) => { that.complete && that.complete(response) completeHandler && completeHandler(response) } if (type === "request") { return uni.request(config) } else if (type === "upload") { return uni.uploadFile(config) } else { return uni.downloadFile(config) } return } return new Promise((resolve, reject) => { config["success"] = (response) => { let _res = null if (that.responseInterceptor) { _res = that.responseInterceptor(response, config) } that.success && that.success(response) successHandler && successHandler(response) // use wakaryReqToReject to judge if reject or resolve // now we can reject and resolve any what we want if (_res.wakaryReqToReject) { delete _res.wakaryReqToReject reject(_res) } else { resolve(_res) } } config["fail"] = (error) => { that.fail && that.fail(error) failHandler && failHandler(error) // it just return the fail error // you could change it into your style reject(error) } config["complete"] = (response) => { that.complete && that.complete(response) completeHandler && completeHandler(response) } if (type === "request") { uni.request(config) } else if (type === "upload") { uni.uploadFile(config) } else { uni.downloadFile(config) } }) } }
JavaScript
class ObservablePool { constructor(concurrency) { this._requests = new _RxMin.Subject(); this._responseListeners = new Map(); this._subscription = this._handleEvents(concurrency); } schedule(executor) { return _RxMin.Observable.create(observer => { const unsubscribed = new _RxMin.Subject(); const tag = {}; // Just a unique object. this._responseListeners.set(tag, { observer, unsubscribed }); this._requests.next({ tag, executor }); return () => { this._responseListeners.delete(tag); unsubscribed.next(); }; }); } /** * Warning: calling dispose() will error all executing requests. */ dispose() { this._responseListeners.forEach(({ observer }) => { observer.error(Error('ObservablePool was disposed')); }); this._subscription.unsubscribe(); } _handleEvents(concurrency) { return this._requests.mergeMap(event => { const { executor, tag } = event; const listener = this._responseListeners.get(tag); // unsubscribed before we could even get to it! if (listener == null) { return _RxMin.Observable.empty(); } const { observer, unsubscribed } = listener; let result; if (executor instanceof _RxMin.Observable) { result = executor; } else { try { result = executor(); } catch (err) { // Catch errors from executor(). observer.error(err); return _RxMin.Observable.empty(); } } if (result instanceof _RxMin.Observable) { // We can safely forward unsubscriptions! return result.takeUntil(unsubscribed) // $FlowFixMe: Flow doesn't like this. .do(observer).catch(() => _RxMin.Observable.empty()); } else { // In the absence of cancellation, assume the worst. return _RxMin.Observable.from(result) // $FlowFixMe: Flow doesn't like this. .do(observer).catch(() => _RxMin.Observable.empty()); } }, concurrency).subscribe(); } }
JavaScript
class SignUpModal extends Modal { oninit(vnode) { super.oninit(vnode); /** * The value of the username input. * * @type {Function} */ this.username = Stream(this.attrs.username || ''); /** * The value of the email input. * * @type {Function} */ this.email = Stream(this.attrs.email || ''); /** * The value of the password input. * * @type {Function} */ this.password = Stream(this.attrs.password || ''); } className() { return 'Modal--small SignUpModal'; } title() { return app.translator.trans('core.forum.sign_up.title'); } content() { return [<div className="Modal-body">{this.body()}</div>, <div className="Modal-footer">{this.footer()}</div>]; } isProvided(field) { return this.attrs.provided && this.attrs.provided.indexOf(field) !== -1; } body() { return [this.attrs.token ? '' : <LogInButtons />, <div className="Form Form--centered">{this.fields().toArray()}</div>]; } fields() { const items = new ItemList(); items.add( 'username', <div className="Form-group"> <input className="FormControl" name="username" type="text" placeholder={extractText(app.translator.trans('core.forum.sign_up.username_placeholder'))} bidi={this.username} disabled={this.loading || this.isProvided('username')} /> </div>, 30 ); items.add( 'email', <div className="Form-group"> <input className="FormControl" name="email" type="email" placeholder={extractText(app.translator.trans('core.forum.sign_up.email_placeholder'))} bidi={this.email} disabled={this.loading || this.isProvided('email')} /> </div>, 20 ); if (!this.attrs.token) { items.add( 'password', <div className="Form-group"> <input className="FormControl" name="password" type="password" placeholder={extractText(app.translator.trans('core.forum.sign_up.password_placeholder'))} bidi={this.password} disabled={this.loading} /> </div>, 10 ); } items.add( 'submit', <div className="Form-group"> <Button className="Button Button--primary Button--block" type="submit" loading={this.loading}> {app.translator.trans('core.forum.sign_up.submit_button')} </Button> </div>, -10 ); return items; } footer() { return [ <p className="SignUpModal-logIn">{app.translator.trans('core.forum.sign_up.log_in_text', { a: <a onclick={this.logIn.bind(this)} /> })}</p>, ]; } /** * Open the log in modal, prefilling it with an email/username/password if * the user has entered one. * * @public */ logIn() { const attrs = { identification: this.email() || this.username(), password: this.password(), }; app.modal.show(LogInModal, attrs); } onready() { if (this.attrs.username && !this.attrs.email) { this.$('[name=email]').select(); } else { this.$('[name=username]').select(); } } onsubmit(e) { e.preventDefault(); this.loading = true; const body = this.submitData(); app .request({ url: app.forum.attribute('baseUrl') + '/register', method: 'POST', body, errorHandler: this.onerror.bind(this), }) .then(() => window.location.reload(), this.loaded.bind(this)); } /** * Get the data that should be submitted in the sign-up request. * * @return {Object} * @protected */ submitData() { const data = { username: this.username(), email: this.email(), }; if (this.attrs.token) { data.token = this.attrs.token; } else { data.password = this.password(); } return data; } }
JavaScript
class PushedScreen extends Component { static navigatorStyle = { statusBarColor: '#303F9F', toolBarColor: '#3F51B5', navigationBarColor: '#303F9F', tabSelectedTextColor: '#FFA000', tabNormalTextColor: '#FFC107', tabIndicatorColor: '#FF4081' }; static navigatorButtons = { leftButton: { id: 'back', color: '#00ff00' }, fab: { collapsedId: 'home', collapsedIcon: require('../../img/ic_home.png'), backgroundColor: '#607D8B' } }; constructor(props) { super(props); console.log('PushedScreen', 'constructor'); this.bgColor = this.getRandomColor(); console.log(`constructor ${this.bgColor}`); this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this)); this.currentBackButton = 0; } componentWillUnmount() { console.log('PushedScreen', `componentWillUnmount ${this.bgColor}`); } componentWillMount() { console.log('PushedScreen', 'componentWillMount'); } getRandomColor() { var letters = '0123456789ABCDEF'.split(''); var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } onNavigatorEvent(event) { switch (event.id) { case 'cancel': Alert.alert('NavBar', 'Cancel button pressed'); break; case 'accept': Alert.alert('NavBar', 'Accept button pressed'); break; case 'backPress': this.handleBackPress(); break; case 'tabSelected': this.onTabSelected(); break; default: console.log('PushedScreen', 'Unknown event ' + event.id); } } onTabSelected() { console.log('PushedScreen', 'onTabSelected'); this.props.navigator.setButtons({ rightButtons: [ { id: 'account', icon: require('../../img/ic_add_alert.png') } ] }); } handleBackPress() { Alert.alert( 'Back button press!', 'Handling back press in JS', [ {text: 'Pop', onPress: () => this.props.navigator.pop()} ] ) } render() { return ( <ScrollView style={{flex: 1, padding: 20, backgroundColor: this.bgColor}}> <Text style={styles.text}> <Text style={{fontWeight: '500'}}>Counter: </Text> {this.props.counter.count} </Text> <TouchableOpacity onPress={ this.onIncrementPress.bind(this) }> <Text style={styles.button}>Increment Counter</Text> </TouchableOpacity> <TouchableOpacity onPress={ this.onPushPress.bind(this) }> <Text style={styles.button}>Push Another</Text> </TouchableOpacity> <TouchableOpacity onPress={ this.onPopPress.bind(this) }> <Text style={styles.button}>Pop Screen</Text> </TouchableOpacity> <TouchableOpacity onPress={ this.onShowModalPress.bind(this) }> <Text style={styles.button}>Modal Screen</Text> </TouchableOpacity> <TouchableOpacity onPress={ this.onDismissModal.bind(this) }> <Text style={styles.button}>Dismiss modal</Text> </TouchableOpacity> <TouchableOpacity onPress={ this.onDismissAllModalsPress.bind(this) }> <Text style={styles.button}>Dismiss all modals</Text> </TouchableOpacity> <TouchableOpacity onPress={ this.onPopToRootPress.bind(this) }> <Text style={styles.button}>Pop to root</Text> </TouchableOpacity> <TouchableOpacity onPress={ this.onNewStackPress.bind(this) }> <Text style={styles.button}>New Stack</Text> </TouchableOpacity> <TouchableOpacity onPress={ this.onChangeLeftButtonPress.bind(this) }> <Text style={styles.button}>Change Left Button</Text> </TouchableOpacity> <TouchableOpacity onPress={ this.onToggleBottomTabsPress.bind(this) }> <Text style={styles.button}>Toggle BottomTabs</Text> </TouchableOpacity> <TextInput style={{height: 40, borderColor: 'gray', borderWidth: 1}}/> <Text style={{fontWeight: '500'}}>String prop: {this.props.str}</Text> <Text style={{fontWeight: '500'}}>Number prop: {this.props.num}</Text> {this.props.obj ? <Text style={{fontWeight: '500'}}>Object prop: {this.props.obj.str}</Text> : false} {this.props.obj && this.props.obj.arr ? <Text style={{fontWeight: '500'}}>Array prop: {this.props.obj.arr[0].str}</Text> : false} </ScrollView> ); } onIncrementPress() { this.props.dispatch(counterActions.increment()); } onPushPress() { this.props.navigator.push({ title: "List", screen: "example.ListScreen", passProps: { passed: 'This is a prop passed in \'navigator.push()\'!', obj: { str: 'This is a prop passed in an object!', arr: [ { str: 'This is a prop in an object in an array in an object!' } ] }, num: 1234 } }); } onPopPress() { this.props.navigator.pop(); } onShowModalPress() { this.props.navigator.showModal({ title: "Modal Screen", screen: "example.PushedScreen", passProps: { passed: 'This is a prop passed in \'navigator.showModal()\'!', obj: { str: 'This is a prop passed in an object!', arr: [ { str: 'This is a prop in an object in an array in an object!' } ] }, num: 1234 } }); } onDismissAllModalsPress() { this.props.navigator.dismissAllModals(); } onDismissModal() { this.props.navigator.dismissModal(); } onPopToRootPress() { this.props.navigator.popToRoot(); } onNewStackPress() { this.props.navigator.resetTo({ title: "NEW STACK", screen: "example.PushedScreen", passProps: { passed: 'This is a prop passed in \'navigator.push()\'!', obj: { str: 'This is a prop passed in an object!', arr: [ { str: 'This is a prop in an object in an array in an object!' } ] }, num: 1234 } }); } onChangeLeftButtonPress() { this.props.navigator.setButtons({ leftButton: { id: leftButtons[this.currentBackButton] } }); this.currentBackButton += 1; this.currentBackButton = this.currentBackButton % 4; } onToggleBottomTabsPress() { this.props.navigator.toggleTabs({ to: bottomTabsVisible ? 'shown' : 'hidden', animated: true }); bottomTabsVisible = !bottomTabsVisible; } }
JavaScript
class Row { constructor(...widgets) { /** * Relative position of each widget inside this row */ this.offsets = []; this.widgets = widgets; this.width = 0; this.height = 0; let x = 0; let y = 0; for (const widget of widgets) { // See if we need to horizontally wrap to add this widget if (x + widget.width > widget_1.GRID_WIDTH) { y = this.height; x = 0; } this.offsets.push({ x, y }); this.width = Math.max(this.width, x + widget.width); this.height = Math.max(this.height, y + widget.height); x += widget.width; } } position(x, y) { for (let i = 0; i < this.widgets.length; i++) { this.widgets[i].position(x + this.offsets[i].x, y + this.offsets[i].y); } } toJson() { const ret = []; for (const widget of this.widgets) { ret.push(...widget.toJson()); } return ret; } }
JavaScript
class Column { constructor(...widgets) { this.widgets = widgets; // There's no vertical wrapping so this one's a lot easier this.width = Math.max(...this.widgets.map(w => w.width)); this.height = sum(...this.widgets.map(w => w.height)); } position(x, y) { let widgetY = y; for (const widget of this.widgets) { widget.position(x, widgetY); widgetY += widget.height; } } toJson() { const ret = []; for (const widget of this.widgets) { ret.push(...widget.toJson()); } return ret; } }
JavaScript
class Spacer { constructor(props = {}) { this.width = props.width || 1; this.height = props.height || 1; } position(_x, _y) { // Don't need to do anything, not a physical widget } toJson() { return []; } }
JavaScript
class BaseAI { update() { if (this.character === undefined) { console.error('Character is undefined.'); return false; } } updateCharacter(timeStep) { this.character.charState.update(timeStep); } }
JavaScript
class AccountValidator { /** * @method createAccountValidator * @description Method to validates signup details * @param {object} req - The request object * @param {object} res - The res response object * @param {function} next - The next() Function * @returns {object} response object if validation fails or next() function when it passes */ static async createAccountValidator(req, res, next) { const client = req.body; const clientProperties = { firstname: 'required|alpha|min:2|max:50', lastname: 'required|alpha|min:2|max:50', email: 'required|email|max:50', password: 'required|alpha_dash|min:6|max:20', address: 'required|min:10|max:50', }; try { await validate(res, next, client, clientProperties); } catch (error) { return error; } } /** * @method loginValidator * @description Method to validates user login details * @param {object} req - The request object * @param {object} res - The res response object * @param {function} next - The next() Function * @returns {object} response object if validation fails or next() function when it passes */ static async loginValidator(req, res, next) { const user = req.body; const userProperties = { email: 'required|email|max:50', password: 'required|alpha_dash|min:6|max:20', }; try { await validate(res, next, user, userProperties); } catch (error) { return error; } } /** * @method userEmail * @description Method to validates user email param * @param {object} req - The request object * @param {object} res - The res response object * @param {function} next - The next() Function * @returns {object} response object if validation fails or next() function when it passes */ static async userEmail(req, res, next) { const email = req.params; const emailProperties = { userEmail: 'required|email|max:50', }; try { await validate(res, next, email, emailProperties); } catch (error) { return error; } } }
JavaScript
class Scene extends Events { constructor () { super(); /** * Wether or not this scene is the active scene and it is being rendered. Best not to set directly. Use [engine.switchScene]{@link module:core~Engine#switchScene} instead. * @type {boolean} * @default false */ this.active = false; /** * Information about the actual size of the viewport and canvas. * @type {object} * @property {number} width - The actual width of the viewport or canvas. Not the one set in the game config. * @property {number} height - The actual height of the viewport or canvas. Not the one set in the game config. * @property {number} zoom - The actual zoom. Not the one set in the game config. */ this.viewport = {width: 320, height: 180, zoom: 1}; /** * An array that holds the scene plugins. * @type {module:core~ScenePlugin[]} */ this.plugins = []; this.offset = {x: 0, y: 0}; } /** * Internal function for starting the scene again. Use `init` to do your own setup. */ setup() { this.plugins.forEach((plugin) => { plugin.init(); }); /** * The children that are added to the scene. Children will be rendered on top of each other. So a child with a lower index will be behind children with a higher index. * @type {module:gameobjects~GameObject[]} */ this.children = []; this.init(); this.active = true; } /** * Adds a child to this scene. * @param {module:gameobjects~GameObject} - The GameObject instance to be added. * @returns {module:gameobjects~GameObject} - Returns the child again. */ add(child) { child.scene = this; this.children.push(child); /** * Notifies when a child is added to this scene. Passes the child that was added. * * @event module:core~Scene#addedchild * @type {module:gameobjects~GameObject} */ this.emit('addedchild', child); return child; } /** * Removes a child from this scene. If the child has a body, the body will be removed from the world. * @param {module:gameobjects~GameObject} - The GameObject to be removed. */ remove(child) { /** * Notifies when a child is removed from this scene. Passes the child that was removed. * * @event module:core~Scene#removedchild * @type {module:gameobjects~GameObject} */ this.emit('removedchild', child); child.scene = undefined; this.children.splice(this.children.indexOf(child), 1); } /** * Automatically called when the scene starts again. Can be used in your own Scene classes to setup the scene. No need to call `super.init()`. * @abstract */ init () { } /** * Automatically called every frame. Can be used in your own Scene classes to do game logic. No need to call `super.update()`. * @abstract * @param {number} time - The total time (in milliesconds) since the start of the game. * @param {number} delta - The time elapsed (in milliseconds) since the last frame. */ update (time, delta) { } /** * Automatically called when the browser resizes. Can be used in your own Scene classes to resposition stuff. No need to call `super.resize()`. * @abstract * @param {number} w - The new width of the game canvas. * @param {number} h - The new height of the game canvas. */ resize(w, h) { } /** * Internal function. Automatically called every frame. Can be overriden, but it is best to call `super.render(context, time, delta)`. Using `update` is the preferred way to go to game logic. * @param {CanvasRenderingContext2D} context - The canvas render context. * @param {number} time - The total time (in milliesconds) since the start of the game. * @param {number} delta - The time elapsed (in milliseconds) since the last frame. */ render (context, time, delta) { let toRemove = []; this.children.forEach((child) => { if (child.lifespan !== undefined) { child.lifespan -= delta; if (child.lifespan < 0) { toRemove.push(child); return; } } if (child.body) { child.x = child.body.midX + child.offsetX; child.y = child.body.midY + child.offsetY; } // cull child // check if child is in viewport first // left if (child.x - child.width / 2 + child.width < this.offset.x * child.scrollFactorX) { return; } // right if (child.x - child.width / 2 > this.offset.x * child.scrollFactorX + this.viewport.width) { return; } // top if (child.y - child.height / 2 + child.height < this.offset.y * child.scrollFactorY) { return; } // bottom if (child.y - child.height / 2 > this.offset.y * child.scrollFactorY + this.viewport.height) { return; } // all okay render child child.render(context, this.offset); }); toRemove.forEach((child) => { this.remove(child); }); } /** * Simply restart this scene. */ restart() { this.shutdown(); this.setup(); } /** * Internal function for stopping the scene and removing everything. Can be overridden, but you must call `super.shutdown()` or it can lead to pretty bad erros and memory leaks. */ shutdown() { this.children.forEach((child) => { child.destroy(); child.scene = undefined; }); this.children = []; this.plugins.forEach((plugin) => { plugin.shutdown(); }); this.active = false; this.off(); } }
JavaScript
class FileSystemEngineHostBase { constructor() { this._transforms = []; } /** * @deprecated Use `listSchematicNames`. */ listSchematics(collection) { return this.listSchematicNames(collection.description); } listSchematicNames(collection) { const schematics = []; for (const key of Object.keys(collection.schematics)) { const schematic = collection.schematics[key]; // If extends is present without a factory it is an alias, do not return it // unless it is from another collection. if (!schematic.extends || schematic.factory) { schematics.push(key); } else if (schematic.extends && schematic.extends.indexOf(':') !== -1) { schematics.push(key); } } return schematics; } registerOptionsTransform(t) { this._transforms.push(t); } /** * * @param name * @return {{path: string}} */ createCollectionDescription(name) { const path = this._resolveCollectionPath(name); const jsonValue = file_system_utility_1.readJsonFile(path); if (!jsonValue || typeof jsonValue != 'object' || Array.isArray(jsonValue)) { throw new InvalidCollectionJsonException(name, path); } const description = this._transformCollectionDescription(name, Object.assign({}, jsonValue, { path })); if (!description || !description.name) { throw new InvalidCollectionJsonException(name, path); } // Validate aliases. const allNames = Object.keys(description.schematics); for (const schematicName of Object.keys(description.schematics)) { const aliases = description.schematics[schematicName].aliases || []; for (const alias of aliases) { if (allNames.indexOf(alias) != -1) { throw new SchematicNameCollisionException(alias); } allNames.push(...aliases); } } return description; } createSchematicDescription(name, collection) { // Resolve aliases first. for (const schematicName of Object.keys(collection.schematics)) { const schematicDescription = collection.schematics[schematicName]; if (schematicDescription.aliases && schematicDescription.aliases.indexOf(name) != -1) { name = schematicName; break; } } if (!(name in collection.schematics)) { throw new schematics_1.UnknownSchematicException(name, collection); } const collectionPath = path_1.dirname(collection.path); const partialDesc = collection.schematics[name]; if (!partialDesc) { throw new schematics_1.UnknownSchematicException(name, collection); } if (partialDesc.extends) { const index = partialDesc.extends.indexOf(':'); const collectionName = index !== -1 ? partialDesc.extends.substr(0, index) : null; const schematicName = index === -1 ? partialDesc.extends : partialDesc.extends.substr(index + 1); if (collectionName !== null) { const extendCollection = this.createCollectionDescription(collectionName); return this.createSchematicDescription(schematicName, extendCollection); } else { return this.createSchematicDescription(schematicName, collection); } } // Use any on this ref as we don't have the OptionT here, but we don't need it (we only need // the path). if (!partialDesc.factory) { throw new SchematicMissingFactoryException(name); } const resolvedRef = this._resolveReferenceString(partialDesc.factory, collectionPath); if (!resolvedRef) { throw new FactoryCannotBeResolvedException(name); } const { path } = resolvedRef; let schema = partialDesc.schema; let schemaJson = undefined; if (schema) { if (!path_1.isAbsolute(schema)) { schema = path_1.join(collectionPath, schema); } schemaJson = file_system_utility_1.readJsonFile(schema); } return this._transformSchematicDescription(name, collection, Object.assign({}, partialDesc, { schema, schemaJson, name, path, factoryFn: resolvedRef.ref, collection })); } createSourceFromUrl(url) { switch (url.protocol) { case null: case 'file:': return (context) => { // Resolve all file:///a/b/c/d from the schematic's own path, and not the current // path. const root = path_1.resolve(path_1.dirname(context.schematic.description.path), url.path || ''); return new schematics_1.FileSystemCreateTree(new file_system_host_1.FileSystemHost(root)); }; } return null; } transformOptions(schematic, options) { return (of_1.of(options) .pipe(...this._transforms.map(tFn => mergeMap_1.mergeMap(opt => { const newOptions = tFn(schematic, opt); if (Symbol.observable in newOptions) { return newOptions; } else { return of_1.of(newOptions); } })))); } getSchematicRuleFactory(schematic, _collection) { return schematic.factoryFn; } }
JavaScript
class InterfaceWrapper extends EventEmitter { constructor(iface) { super(); this.objectPath = iface.objectPath; this._iface = iface; this._boundSignalHandlers = []; // export all DBus methods that aren't overridden, and auto-unwrap // all InterfaceWrapper arguments passed to their corresponding object paths // TODO: translate args and returns based on declared signature for (let name in iface.object.method) { // TODO: check this, working from memory of structures here // TODO: similar autotranslation of properties? let methodInfo = iface.object.method[name]; let transformArgs = this._transformMethodArgs.bind(this, name, methodInfo.in); let transformRet = this._transformMethodReturn.bind(this, name, methodInfo.out); if (!this[name]) this[name] = async function (...args) { return transformRet(await iface[name](...(await transformArgs(args)))); }; } // expose the properties interface this.getProperties = iface.getProperties.bind(iface); this.getProperty = iface.getProperty.bind(iface); this.setProperty = iface.setProperty.bind(iface); // expose the signals interface in a way that allows subclasses // to alter the signal contents (for example, to convert object // paths to higher level wrappers for the objects they represent) this.on('newListener', function (e) { if (!this.listenerCount(e) && e in iface.object.signal) { this._iface.addListener(e, this._boundSignalHandler(e)); } }); this.on('removeListener', function (e) { if (!this.listenerCount(e) && e in iface.object.signal) { this._iface.removeListener(e, this._boundSignalHandler(e)); } }); } get methods() { return Object.keys(this._iface.object.method).sort(); } get properties() { return Object.keys(this._iface.object.property).sort(); } get signals() { return Object.keys(this._iface.object.signal).sort(); } _transformMethodArgs(method, sig, args) { return args.map(unwrapInterface); } _transformMethodReturn(method, sig, ret) { // TODO: auto-wrap returned object paths? return ret; } async _interpretSignal(signal, args) { return args; } async _onSignal(signal, ...args) { this.emit(signal, ...(await this._interpretSignal(signal, args))) } _boundSignalHandler(e) { if (!this._boundSignalHandlers[e]) { this._boundSignalHandlers[e] = this._onSignal.bind(this, e); } return this._boundSignalHandlers[e]; } }
JavaScript
class Domains extends CloudControllerBase { /** * @param {String} endPoint [CC endpoint] * @constructor * @returns {void} */ constructor(endPoint) { super(endPoint); } /** * Get Domains * {@link http://apidocs.cloudfoundry.org/214/domains_(deprecated)/list_all_domains_(deprecated).html} * * @return {JSON} [return a JSON response] */ getDomains () { const url = `${this.API_URL}/v2/domains`; const options = { method: "GET", url: url, headers: { Authorization: `${this.UAA_TOKEN.token_type} ${this.UAA_TOKEN.access_token}` } }; return this.REST.request(options, this.HttpStatus.OK, true); } /** * Get shared domains * {@link http://apidocs.cloudfoundry.org/214/shared_domains/list_all_shared_domains.html} * * @return {JSON} [return a JSON response] */ getSharedDomains () { const url = `${this.API_URL}/v2/shared_domains`; const options = { method: "GET", url: url, headers: { Authorization: `${this.UAA_TOKEN.token_type} ${this.UAA_TOKEN.access_token}` } }; return this.REST.request(options, this.HttpStatus.OK, true); } }
JavaScript
class Covid19 { constructor() { this.covid19Tag = () => exports.covid19Tag; // "COVID-19" /** Alert Communications */ this.createCovid19DiseaseAlertCommunication = (priorityCode) => createCovid19DiseaseAlertCommunication(priorityCode); this.createCovid19SuspectedAlertCommunication = (priorityCode) => createCovid19SuspectedAlertCommunication(priorityCode); this.createCovid19ExposureAlertCommunication = (priorityCode) => createCovid19ExposureAlertCommunication(priorityCode); this.isCovid19DiseaseAlertCommunication = (communication) => isCovid19DiseaseAlertCommunication(communication); this.isCovid19SuspectedAlertCommunication = (communication) => isCovid19SuspectedAlertCommunication(communication); this.isCovid19ExposureAlertCommunication = (communication) => isCovid19ExposureAlertCommunication(communication); /** Get specific codes by CVX coding system */ this.vaccineProphylaxisCodesCVX = () => vaccineProphylaxisCodesCVX(); /** Get specific codes by WHO's ATC coding system*/ this.vaccineProphylaxisCodeATC = () => exports.vaccineProphylaxisCodeATC; /** Get specific vaccine prophylaxis codes (no vaccine product codes) by SNOMED coding system */ this.vaccineProphylaxisCodesSNOMED = () => Snomed_1.covid19VaccineProphylaxisCodesSNOMED(); /** Get LOINC laboratory test group code: serology or naat group code */ this.naatTestsGroupCodeLOINC = () => naatTestsGroupCodeLOINC(); this.serologyTestsGroupCodeLOINC = () => serologyTestsGroupCodeLOINC(); this.healthCertificateLaboratoryTests = () => Loinc_1.getCovid19HealthCertificateLaboratoryTests(); /** Get all or specific LOINC laboratory tests */ this.laboratoryTestsCodesLOINC = () => laboratoryTestsCodesLOINC(); this.activeLaboratoryTestsLOINC = () => Loinc_1.getActiveLaboratoryTestsCovid19(); this.naatTestsCodesLOINC = () => Loinc_1.getFullNaatTestCovid19LOINC(); this.serologyTestsCodesLOINC = () => Loinc_1.getFullSerologyTestCovid19LOINC(); /** Get specific codes by system SNOMED */ this.laboratoryOriginSampleCodesSNOMED = () => Snomed_1.covid19LaboratoryOriginSamples(); this.naatResultsCodesSNOMED = () => naatResultsCodesSNOMED(); this.serologyResultsCodesSNOMED = () => serologyResultsCodesSNOMED(); this.positiveOrDetectedCodesSNOMED = () => Snomed_1.positiveOrDetectedCodesSNOMED(); this.negativeOrNotDetectedCodesSNOMED = () => Snomed_1.negativeOrNotDetectedCodesSNOMED(); this.suspectedOrInconclusiveCodesSNOMED = () => Snomed_1.suspectedOrInconclusiveCodesSNOMED(); this.probablyNotPresentCodesSNOMED = () => Snomed_1.probablyNotPresentCodesSNOMED(); this.vaccinationProcedureCodesInternationalSNOMED = () => vaccinationProcedureCodesInternationalSNOMED(); this.vaccinationProcedureCodesSpainSNOMED = () => vaccinationProcedureCodesSpainSNOMED(); this.confirmedDiseaseSNOMED = () => confirmedDiseaseSNOMED(); this.suspectedDiseaseSNOMED = () => suspectedDiseaseSNOMED(); this.exposureToDiseaseSNOMED = () => exposureToDiseaseSNOMED(); /** Get specific codes by system ICD10 and ICD11 */ this.confirmedDiseaseICD10 = () => confirmedDiseaseICD10(); this.suspectedDiseaseICD10 = () => suspectedDiseaseICD10(); this.confirmedDiseaseICD11 = () => confirmedDiseaseICD11(); this.suspectedDiseaseICD11 = () => suspectedDiseaseICD11(); /** Manufacturers by system */ this.getCovid19OfficialManufacturerCodesEMA = () => Ema_1.getCovid19OfficialManufacturerCodesEMA(); // for clinical trials this.getCovid19TempManufacturerCodesEMA = () => Ema_1.getCovid19TempManufacturerCodesEMA(); /** Merge codes from distinct systems (if several ones, e.g. for searching) */ this.vaccineProphylaxisCodesGlobal = () => exports.covid19VaccineProphylaxisCodesGlobal(); this.vaccineProphylaxisCodesEMA = () => exports.covid19VaccineProphylaxisCodesEMA(); this.laboratoryTestCodes = () => exports.covid19LaboratoryTestsCodes(); this.laboratoryTestAndGroupsCodes = () => exports.covid19LaboratoryTestsAndGroupsCodes(); this.vaccinationProcedureCodes = () => exports.vaccinationProcedureCodes(); this.diseaseCodes = () => exports.diseaseCodes(); this.diseaseOrSuspectedDiseaseCodes = () => exports.diseaseOrSuspectedDiseaseCodes(); this.suspectedDiseaseCodes = () => exports.suspectedDiseaseCodes(); this.isCovid19VaccineProphylaxis = (code) => isCovid19VaccineProphylaxis(code); this.isCovid19Disease = (code) => isCovid19Disease(code); this.isSuspectedDisease = (code) => isSuspectedDisease(code); this.isCovid19OrSuspectedDisease = (code) => isCovid19OrSuspectedDisease(code); /** Get COVID-19 specific resoruces */ this.getCovid19DiagnosticReportsInDocument = (bundleDocument) => getCovid19DiagnosticReportsInDocument(bundleDocument); this.getCovid19ImmunizationsInDocument = (bundleDocument) => getCovid19ImmunizationsInDocument(bundleDocument); } }
JavaScript
class PushGroupsScreen extends Component { static propTypes = { // All push groups for the app groups: arrayOf(pushGroupShape).isRequired, // Fetches push groups fetchGroups: func, // Tags of push groups that the user is subscribed to selectedGroups: arrayOf(string).isRequired, // Used to subscribe and unsubscribe from groups selectPushNotificationGroups: func.isRequired, // Used to invalidate notifications after a change in subscribed groups invalidateNotifications: func.isRequired, }; constructor(props) { super(props); this.onToggleGroupSubscription = this.onToggleGroupSubscription.bind(this); this.renderRow = this.renderRow.bind(this); this.state = { areNotificationsEnabled: false }; } componentDidMount() { const { fetchGroups } = this.props; fetchGroups(); // Push groups and notifications are not enabled when there are no certificates set up. // They are usually set up only in production environments if (!isProduction()) { showPreviewModeNotification(); return; } this.checkIfNotificationsAreEnabled(); } onToggleGroupSubscription(tag, value) { const { selectPushNotificationGroups, invalidateNotifications, } = this.props; const added = value ? [tag] : []; const removed = value ? [] : [tag]; selectPushNotificationGroups({ added, removed }); invalidateNotifications(); } checkIfNotificationsAreEnabled() { Permissions.arePushNotificationsEnabled((result) => { if (!result) { showSuggestionToEnableNotifications(); } }); } renderRow(group) { const { tag, name } = group; const { selectedGroups } = this.props; const prefixedTag = `${GROUP_PREFIX + tag}`; return ( <View> <Row styleName="small space-between"> <Subtitle>{name}</Subtitle> <Switch value={_.includes(selectedGroups, prefixedTag)} onValueChange={value => this.onToggleGroupSubscription(prefixedTag, value)} /> </Row> <Divider styleName="line" /> </View> ); } render() { const { groups } = this.props; if (_.isEmpty(groups)) { return renderEmptyScreen(); } return ( <Screen> <NavigationBar title={I18n.t(ext('pushGroupsSettingsNavBarTitle'))} /> <View styleName="md-gutter solid"> <Subtitle styleName="h-center">{I18n.t(ext('subscribeToPushGroups'))}</Subtitle> </View> <ListView data={[...groups]} renderRow={this.renderRow} /> </Screen> ); } }
JavaScript
class InternalProtocol extends Protocol { constructor () { super('internal'); this.connection = new ClientConnection(this.name, ['127.0.0.1']); /** * List of channel IDs * @type {Set<string>} */ this.channels = new Set(); } async init (entryPoint) { await super.init(null, entryPoint); debug('initializing InternalProtocol'); this.entryPoint.newConnection(this.connection); /** * Returns the internal connection ID used by the protocol. * * @returns {string} connectionId */ global.kuzzle.onAsk('core:network:internal:connectionId:get', () => ( this.connection.id )); } joinChannel (channel, connectionId) { debug('joinChannel: %s', channel, connectionId); this.channels.add(channel); } leaveChannel (channel, connectionId) { debug('leaveChannel: %s', channel, connectionId); this.channels.delete(channel); } disconnect (connectionId) { debug('disconnect: %s', connectionId); // Never happens, the InternalProtocol always keep his only connection open } broadcast (data) { debug('broadcast: %a', data); this._send(data); } notify (data) { debug('notify: %a', data); this._send(data); } _send (data) { for (let i = 0; i < data.channels.length; i++) { const message = { ...data.payload, room: data.channels[i] }; global.kuzzle.emit('core:network:internal:message', message); } } }
JavaScript
class Slice extends PlugInBlock { /** * Validate a parent * return {Boolean} true if the parent is a potential parent for a * Slice Block, false otherwise */ static validate (parent) { return ( parent.tetraArray !== undefined && parent._meshes[0].material._transformNodes.length === 0 ); } /** * Constructor for slice block * @param {PlugInBlock} parentBlock - The block before this slice * one * @param {number[]} sliceNormal - normal vector to the slice * @param {number} slicePosition - position of the slice */ constructor (parentBlock, sliceNormal = [1.0, 0.0, 0.0], slicePosition = 0) { let setters = { 'sliceNormal': () => { if (this._sliceNormal[0] + this._sliceNormal[1] + this._sliceNormal[2] == 0) { this._sliceNormal = [1.0, 0.0, 0.0]; } this.updateGeometry(); // Get normalized normal this._sliceNormal = this._sliceUtils.abc; // Get min and max values (unused but useful to // know bounds of the mesh) this.min = this._sliceUtils.posMin; this.max = this._sliceUtils.posMax; }, 'slicePosition': () => { this.updateGeometry(); } }; super(parentBlock, setters); this._sliceNormal = sliceNormal; this._slicePosition = slicePosition; this._sliceUtils = undefined; this._sliceIndex = undefined; } _process () { // Creation of slice this._sliceUtils = new SliceUtils(this); // Remove all meshes from scene this.removeMeshes(); // Add mesh to scene and get its position in the array let slice = this._sliceUtils.createSlice( this._sliceNormal[0], this._sliceNormal[1], this._sliceNormal[2], this._slicePosition, true ); this._sliceIndex = this.addMesh(slice.mesh); // Update coordArray, facesArray, data and tetrasArray this.data = slice.data; this.coordArray = slice.coordArray; this.facesArray = slice.facesArray; this.tetraArray = undefined; // Get normalized normal this._sliceNormal = this._sliceUtils.abc; // Get min and max values (unused but useful to // know bounds of the mesh for slicePosition) this.min = this._sliceUtils.posMin; this.max = this._sliceUtils.posMax; // Promise of process is rejected if the slice can't be computed return this._sliceUtils._enableSlice; } _updateGeometry(){ let slice = this._sliceUtils.createSlice( this._sliceNormal[0], this._sliceNormal[1], this._sliceNormal[2], this._slicePosition ); let sliceGeometry = slice.mesh.geometry; // Update coordArray, facesArray, data this.data = slice.data; this.coordArray = slice.coordArray; this.facesArray = slice.facesArray; if (this._sliceIndex != -1){ this._meshes[this._sliceIndex].geometry.copy(sliceGeometry); } } }
JavaScript
class FileService { /** * @constructor */ constructor() { /** * @type {Object.<*>} * the cloud explorer instance */ this.cloudExplorer = window.ce.api.CloudExplorer.get("ce-js"); /** * @type {string|null} * the current opened file */ this.currentBlob = null; } /** * open a file * returns a promise * @return {Promise} * @export */ open() { return new Promise((resolve, reject) => { this.cloudExplorer.pick( (blob) => { console.log("my Blob: " + JSON.stringify(blob)); this.currentBlob = blob; resolve(blob.url); }, (e) => { console.log("error " + JSON.stringify(e)); reject(e); }); }); } /** * save a file * returns a promise * @param {string} html * @return {Promise} * @export */ save(html) { return new Promise((resolve, reject) => { console.log('fileService save', html, this.currentBlob); this.cloudExplorer.write(this.currentBlob, html, (blob) => { console.log("my Blob: " + JSON.stringify(blob)); this.currentBlob = blob; resolve(blob.url); }, (e) => { console.log("error " + JSON.stringify(e)); reject(e); }); }); } }
JavaScript
class OwnerDialog extends Component { constructor(props) { super(props); this.state = { actions: [ <FlatButton label="Add Owner" primary={true} keyboardFocused={true} onClick={this.props.onAddOwner} aria-label="Owner add button" />, <FlatButton label="Cancel" primary={true} onClick={this.props.handleCloseOwner} aria-label="Cancel button" /> ] } this.state.inputText = ""; this.state.inputNumb = 1; } render() { const customContentStyle = { width: '20%', maxWidth: 'none', }; return ( <MuiThemeProvider> <Dialog actions={this.state.actions} modal={false} open={this.props.open} onRequestClose={this.props.handleCloseOwner} contentStyle={customContentStyle}> <label htmlFor="textInput">Owners (separated by comma)</label><input id="textInput" type="text" onChange={this.props.onTextChange}/> </Dialog> </MuiThemeProvider> ); } }
JavaScript
class IColumnActionModel { /** * Get the column title * @return {string} */ getTitle() {} /** * Get the name of the dataField supporting the column. * @return {string} */ getDataField() {} }
JavaScript
class GivenTree { constructor(givenPushTest, name) { this.givenPushTest = givenPushTest; this.name = name; } /** * Perform computation before continuing. * Typically used to set values that will be used in predicate expressions. * @param {(t: this) => any} f * @return {any} */ compute(f) { f(this); return this; } /** * Set the resolution value of this tree * @param {V} value * @return {PushMapping<V>} */ set(value) { return { name: this.name, mapping: () => __awaiter(this, void 0, void 0, function* () { return value; }), }; } /** * Enter a subtree of a number of mappings. Can be use * to nest trees to arbitrary depth. * @param {PushMapping<V>} pushMappings * @return {PushMapping<V>} */ then(...pushMappings) { const rules = new PushRules_1.PushRules(this.name, pushMappings); return { name: this.name, mapping: (pli) => __awaiter(this, void 0, void 0, function* () { const eligible = yield this.givenPushTest.mapping(pli); return eligible ? rules.mapping(pli) : undefined; }), }; } }
JavaScript
class FirestoreBackup{ /** *Creates an instance of Firestore Backup. * @param {JSON} credentials * @param {string} databaseURL * @memberof FirestoreBackup */ constructor(credentials, databaseURL){ this.app = new FirebaseAdmin(credentials, databaseURL) this.exportObj = new Exports(this.app) this.importObj = new Imports(this.app) } /** * Create a complete backup of firestore * @returns Object * @memberof FirestoreBackup */ exportAll(){ return new Promise(async (resolve, reject) => { try { const data = await this.exportObj.exportAll() resolve(data) } catch (error) { reject(new Error(error)) } }) } /** * Create a custom backup of firestore. * Send an Array with the names of collections * that will be part of the backup * @param {Array<string>} collectionList * @returns Object * @memberof FirestoreBackup */ exportCustom(collectionList){ return new Promise(async (resolve, reject) => { try { const data = await this.exportObj.exportCustom(collectionList) resolve(data) } catch (error) { reject(new Error(error)) } }) } /** * Import backup to firestore from any object * that meets the import structure * @param {Object} data * @returns Batch result * @memberof FirestoreBackup */ importData(data){ return new Promise(async (resolve, reject) => { try { const result = await this.importObj.importData(data) resolve(result) } catch (error) { reject(new Error(error)) } }) } /** * Import backup to firestore from a JSON file * @param {string} pathFile * @returns Batch result * @memberof FirestoreBackup */ importDataFromFile(pathFile){ return new Promise(async (resolve, reject) => { try { const result = await this.importObj.importDataFromFile(pathFile) resolve(result) } catch (error) { reject(new Error(error)) } }) } /** * Create a JSON file with a exported information from firestore * @param {Object} data * @param {Object} { path, name } * @returns Promise<void> * @memberof FirestoreBackup */ saveFile(data, { path, name }){ return this.exportObj.saveFile(data, { path, name }) } }
JavaScript
class FlexContainer extends Default { /** * Range of validators that can be used to make sure the data you receive is valid * @type {Object} */ static propTypes = { ...Default.propTypes, } /** * Default values for props property * @type {Object} */ static defaultProps = { ...Default.defaultProps, } /** * React method. * Return a single React element. * This element can be either a representation of a native DOM component, * such as <div />, or another composite component that you've defined yourself. * You can also return null or false to indicate that you don't want anything rendered. * When returning null or false, ReactDOM.findDOMNode(this) will return null. * @method render * @return {Mixed} A representation of a native DOM component */ render() { const { children, style, ...other } = this.props; return ( <div style={{ display: 'flex', ...style, }} {...other} > {children} </div> ); } }
JavaScript
class TextureManager { constructor(gl) { this.registry = []; this._needsResample = []; this._activeTexture = 0; this._boundTexture = null; this._checkerboard = createCheckerBoard(); this.gl = gl; } /** * Update function used by WebGLRenderer to queue resamples on * registered textures. * * @method * * @param {Number} time Time in milliseconds according to the compositor. * @return {undefined} undefined */ update(time) { var registryLength = this.registry.length; for (var i = 1; i < registryLength; i++) { var texture = this.registry[i]; if (texture && texture.isLoaded && texture.resampleRate) { if (!texture.lastResample || time - texture.lastResample > texture.resampleRate) { if (!this._needsResample[texture.id]) { this._needsResample[texture.id] = true; texture.lastResample = time; } } } } }; /** * Creates a spec and creates a texture based on given texture data. * Handles loading assets if necessary. * * @method * * @param {Object} input Object containing texture id, texture data * and options used to draw texture. * @param {Number} slot Texture slot to bind generated texture to. * @return {undefined} undefined */ register(input, slot) { var _this = this; var source = input.data; var textureId = input.id; var options = input.options || {}; var texture = this.registry[textureId]; var spec; if (!texture) { texture = new Texture(this.gl, options); texture.setImage(this._checkerboard); // Add texture to registry spec = this.registry[textureId] = { resampleRate: options.resampleRate || null, lastResample: null, isLoaded: false, texture: texture, source: source, id: textureId, slot: slot }; // Handle array if (Array.isArray(source) || source instanceof Uint8Array || source instanceof Float32Array) { this.bindTexture(textureId); texture.setArray(source); spec.isLoaded = true; } // Handle video else if (source instanceof HTMLVideoElement) { source.addEventListener('loadeddata', function() { _this.bindTexture(textureId); texture.setImage(source); spec.isLoaded = true; spec.source = source; }); } // Handle image url else if (typeof source === 'string') { loadImage(source, function(img) { _this.bindTexture(textureId); texture.setImage(img); spec.isLoaded = true; spec.source = img; }); } } return textureId; }; /** * Sets active texture slot and binds target texture. Also handles * resampling when necessary. * * @method * * @param {Number} id Identifier used to retreive texture spec * * @return {undefined} undefined */ bindTexture(id) { var spec = this.registry[id]; if (this._activeTexture !== spec.slot) { this.gl.activeTexture(this.gl.TEXTURE0 + spec.slot); this._activeTexture = spec.slot; } if (this._boundTexture !== id) { this._boundTexture = id; spec.texture.bind(); } if (this._needsResample[spec.id]) { // TODO: Account for resampling of arrays. spec.texture.setImage(spec.source); this._needsResample[spec.id] = false; } }; }
JavaScript
class Welcome_Bot { constructor(configAndskillid, csds = process.env.LP_CSDS) { this.accountId = process.env.accountID; this.username = process.env.username; this.password = process.env.password; this.config = JSON.parse(configAndskillid[0]); // to use later to set the current node to the root node this.node = JSON.parse(configAndskillid[0]); this.skillid = JSON.parse(configAndskillid[1]); this.isConnected = false; this.myAgent = new Agent({ accountId: this.accountId, username: this.username, password: this.password, csdsDomain: csds });//initialize the new Bot this.openConversations = {}; this.init(); } //Initialized the event handler. init() { this.myAgent.on('connected', () => { this.isConnected = true; }); // in case the bot crashes, restart it automatically this.myAgent.on('closed', data => { console.log('socket closed', data); this.myAgent.reconnect();//regenerate token for reasons of authorization (data === 4401 || data === 4407) }); this.myAgent.on('error', err => { this.isConnected = false; console.error('Connection to UMS closed with err', err.message); }); // get in here when the Bot joins the conversation this.myAgent.on('cqm.ExConversationChangeNotification', body => { body.changes .forEach(change => { if (change.type === 'UPSERT' && !this.openConversations[change.result.convId]) { this.openConversations[change.result.convId] = change.result.conversationDetails; this.joinConversation(change.result.convId, 'MANAGER'); this.sendMessage(change.result.convId, initialBotMessage()); } else if (change.type === 'DELETE' && this.openConversations[change.result.convId]) { delete this.openConversations[change.result.convId]; console.log("conversation was closed\n"); setNodeToRoot(); } }); }); //This function is used to find out what the user wants to send and send the right message this.myAgent.on('ms.MessagingEventNotification', body => { body.changes // .filter(change => change.type === 'UPSERT' && this.openConversations[change.result.convId]) .forEach(change => { // react only when the sends a message, i mean , a message , so don't enter here anytime if (change.event.type === 'ContentEvent' && this.openConversations[body.dialogId]) { var conversationId = body.dialogId; if (body.changes[0].__isMe === false && body.changes[0].originatorMetadata.role !== "ASSIGNED_AGENT" && this.openConversations[conversationId].skillId == this.skillid) { // don't send answer forever and only answer when skillid ='-1' if (body.changes[0].event.message !== NaN && body.changes[0].event.message < myBot.node.children.length + 1 && body.changes[0].event.message > 0) { // the user entered one of the suggested bots this.sendMessage(conversationId, nextBotMessage(body.changes[0].event.message)); // check each time whether the current children array contains end if (myBot.node.end !== '') { // do the transfer console.log("transfer started!") console.log("abc " + myBot.node.end) const transferBody = { conversationId: conversationId, conversationField: [ { field: 'Skill', type: 'UPDATE', skill: myBot.node.end } , { field: 'ParticipantsChange', type: 'REMOVE', role: 'MANAGER', userId: this.myAgent.__oldAgentId } ] }; this.myAgent.updateConversationField(transferBody, (err, res) => { // Handle potential error if (err) { console.log("transfer failed with the following erro : \n"); console.log(err); this.sendMessage(conversationId, "sorry, the corresponding Bot isn't available"); setNodeToRoot(); this.openConversations[conversationId].skillId = this.skillid; // reset the skillid to -1 } else { console.log("transfer successful!") this.openConversations[conversationId].skillId = myBot.node.end; console.log("the new skill id : " + this.openConversations[conversationId].skillId); //this.leaveConversation(conversationId); } }); } // end of the transfer block } else { this.sendMessage(conversationId, initialBotMessage()); } } } }); // }); this.promisifyFunctions(); } // end of the init() method //Utility function which transforms the used SDK functions into promise-based ones, which later get consumed by other functions. promisifyFunctions() { this.subscribeExConversations = promisify(this.myAgent.subscribeExConversations); this.publishEvent = promisify(this.myAgent.publishEvent); this.setAgentState = promisify(this.myAgent.setAgentState); this.updateConversationField = promisify(this.myAgent.updateConversationField); } // to start the Bot async start() { if (!this.myAgent) this.myAgent = new Agent({ accountId: this.accountId, username: this.username, password: this.password, 'csdsDomain': this.csds }); while (!this.isConnected) { // make the server answer await timeout(3000); } let response; response = await this.setStateOfAgent('AWAY'); response = await this.subscribeToConversations(); } //Shutsdown the bot stop() { this.isConnected = false; this.myAgent.dispose(); this.myAgent.removeAllListeners(); this.myAgent = null; } //This functions allows the agent to subscribe to conversation. // convState is the conversation state for which should be subscribed // agentOnly if set it will only subscribe to conversation in which the agent is or which are suitable for his skills async subscribeToConversations(convState = 'OPEN', agentOnly = true) { if (!this.isConnected) return; return await this.myAgent.subscribeExConversations({ 'convState': [convState] }); } //This functions allows to set the state of the agent, this is important for the routing of incomming messages. // state is the state of the agent (ONLINE,OFFLINE,AWAY) async setStateOfAgent(state = 'ONLINE') { if (!this.isConnected) return; return await this.myAgent.setAgentState({ availability: state }); } // This function is used to join a conversation. // conversationId is the id of the conversation which should be joined // role is the role of the agent (AGENT, MANAGER) async joinConversation(conversationId, role = 'AGENT') { if (!this.isConnected) return; return await this.myAgent.updateConversationField({ 'conversationId': conversationId, 'conversationField': [{ 'field': 'ParticipantsChange', 'type': 'ADD', 'role': role }] }); } // to delete all temporary data of the conversation and leave it. async leaveConversation(conversationId) { delete this.openConversations[conversationId]; console.log("conversation left"); this.openConversations[conversationId] = null; return; } //conversationId is id of the conversation which should be joined //message is the message which will be sent to the user async sendMessage(conversationId, message) { if (!this.isConnected) return; return await this.myAgent.publishEvent({ dialogId: conversationId, event: { type: 'ContentEvent', contentType: 'text/plain', message: message } }); } } // end of the class
JavaScript
class DropboxBase { constructor(options) { options = options || {}; this.accessToken = options.accessToken; this.clientId = options.clientId; this.selectUser = options.selectUser; } /** * Set the access token used to authenticate requests to the API. * @arg {String} accessToken - An access token * @returns {undefined} */ setAccessToken(accessToken) { this.accessToken = accessToken; } /** * Get the access token * @returns {String} Access token */ getAccessToken() { return this.accessToken; } /** * Set the client id, which is used to help gain an access token. * @arg {String} clientId - Your apps client id * @returns {undefined} */ setClientId(clientId) { this.clientId = clientId; } /** * Get the client id * @returns {String} Client id */ getClientId() { return this.clientId; } /** * Get a URL that can be used to authenticate users for the Dropbox API. * @arg {String} redirectUri - A URL to redirect the user to after * authenticating. This must be added to your app through the admin interface. * @arg {String} [state] - State that will be returned in the redirect URL to help * prevent cross site scripting attacks. * @returns {String} Url to send user to for Dropbox API authentication */ getAuthenticationUrl(redirectUri, state) { const clientId = this.getClientId(); const baseUrl = 'https://www.dropbox.com/oauth2/authorize'; if (!clientId) { throw new Error('A client id is required. You can set the client id using .setClientId().'); } if (!redirectUri) { throw new Error('A redirect uri is required.'); } let authUrl = `${baseUrl}?response_type=token&client_id=${clientId}`; if (redirectUri) { authUrl += `&redirect_uri=${redirectUri}`; } if (state) { authUrl += `&state=${state}`; } return authUrl; } /** * Called when the authentication succeed * @callback successCallback * @param {string} access_token The application's access token */ /** * Called when the authentication failed. * @callback errorCallback */ /** * An authentication process that works with cordova applications. * @param {successCallback} successCallback * @param {errorCallback} errorCallback */ authenticateWithCordova(successCallback, errorCallback) { const redirectUrl = 'https://www.dropbox.com/1/oauth2/redirect_receiver'; const url = this.getAuthenticationUrl(redirectUrl); let removed = false; const browser = window.open(url, '_blank'); function onLoadError() { // Try to avoid a browser crash on browser.close(). window.setTimeout(() => { browser.close(); }, 10); errorCallback(); } function onLoadStop(event) { const errorLabel = '&error='; const errorIndex = event.url.indexOf(errorLabel); if (errorIndex > -1) { // Try to avoid a browser crash on browser.close(). window.setTimeout(() => { browser.close(); }, 10); errorCallback(); } else { const tokenLabel = '#access_token='; let tokenIndex = event.url.indexOf(tokenLabel); const tokenTypeIndex = event.url.indexOf('&token_type='); if (tokenIndex > -1) { tokenIndex += tokenLabel.length; // Try to avoid a browser crash on browser.close(). window.setTimeout(() => { browser.close(); }, 10); const accessToken = event.url.substring(tokenIndex, tokenTypeIndex); successCallback(accessToken); } } } function onExit() { if (removed) { return; } browser.removeEventListener('loaderror', onLoadError); browser.removeEventListener('loadstop', onLoadStop); browser.removeEventListener('exit', onExit); removed = true; } browser.addEventListener('loaderror', onLoadError); browser.addEventListener('loadstop', onLoadStop); browser.addEventListener('exit', onExit); } request(path, args, auth, host, style) { let request = null; switch (style) { case RPC: request = this.getRpcRequest(); break; case DOWNLOAD: request = this.getDownloadRequest(); break; case UPLOAD: request = this.getUploadRequest(); break; default: throw new Error(`Invalid request style: ${style}`); } return request(path, args, auth, host, this.getAccessToken(), this.selectUser); } setRpcRequest(newRpcRequest) { this.rpcRequest = newRpcRequest; } getRpcRequest() { if (this.rpcRequest === undefined) { this.rpcRequest = rpcRequest; } return this.rpcRequest; } setDownloadRequest(newDownloadRequest) { this.downloadRequest = newDownloadRequest; } getDownloadRequest() { if (this.downloadRequest === undefined) { this.downloadRequest = downloadRequest; } return this.downloadRequest; } setUploadRequest(newUploadRequest) { this.uploadRequest = newUploadRequest; } getUploadRequest() { if (this.uploadRequest === undefined) { this.uploadRequest = uploadRequest; } return this.uploadRequest; } }
JavaScript
class NavPush { constructor() { this.push = () => { return navLink(this.el, 'forward', this.component, this.componentProps); }; } componentDidLoad() { console.warn('[DEPRECATED][ion-nav-push] `<ion-nav-push component="MyComponent">` is deprecated. Use `<ion-nav-link component="MyComponent">` instead.'); } render() { return (h(Host, { onClick: this.push })); } static get is() { return "ion-nav-push"; } static get properties() { return { "component": { "type": "string", "mutable": false, "complexType": { "original": "NavComponent", "resolved": "Function | HTMLElement | ViewController | null | string | undefined", "references": { "NavComponent": { "location": "import", "path": "../../interface" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Component to navigate to" }, "attribute": "component", "reflect": false }, "componentProps": { "type": "unknown", "mutable": false, "complexType": { "original": "ComponentProps", "resolved": "undefined | { [key: string]: any; }", "references": { "ComponentProps": { "location": "import", "path": "../../interface" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Data you want to pass to the component as props" } } }; } static get elementRef() { return "el"; } }
JavaScript
class PBNfile { // ================================================================ // Constructor constructor() { // ---------------------------------------------------------------- // Info // Version this.version = null, // Type - EXPORT/IMPORT this.type = null, // Games this.games = [] } // ================================================================ // gameCnt - Number of Games in File get gameCnt() { return this.games.length; } // ================================================================ // File : Read async fileRead(fileName) { return new Promise((resolve, reject) => { fs.readFile(fileName, (err, data) => { if (err) return reject(err); let fileString = data.toString(); let fileSplit = fileString.split("\r\n"); let gameCnt = 0; let gamesString = [[]]; for (var i = 3; i < fileSplit.length - 1; i++) { if (fileSplit[i] === "") { gamesString.push([]); gameCnt += 1; continue; } gamesString[gameCnt].push(fileSplit[i]); } this.version = fileSplit[0].slice(2,fileSplit[0].length); this.type = fileSplit[1].slice(2,fileSplit[1].length); // All Games for (var gs = 0; gs < gamesString.length; gs++) { let game = new PBNfile; // For Each Game for (var g = 0; g < gamesString[gs].length; g++) { let item = gamesString[gs][g].replace('[', '').replace(']', '').replace(/"/g, ''); let key = item.substr(0,item.indexOf(' ')); let value = item.substr(item.indexOf(' ')+1); switch(key) { // 1 - Event case ("Event"): game.event = value; break; // 2 - Site case ("Site"): game.site = value; break; // 3 - Date case ("Date"): game.date = value; break; // 4 - Board case ("Board"): game.board = value; break; // 5 - West case ("West"): game.west = value; break; // 6 - Nord case ("North"): game.north = value; break; // 7 - East case ("East"): game.east = value; break; // 8 - South case ("South"): game.south = value; break; // 9 - Dealer case ("Dealer"): game.dealer = value; break; // 10 - Vulnerable case ("Vulnerable"): game.vulnerable = value; break; // 11 - Deal case ("Deal"): game.deal = value; break; // 12 - Scoring case ("Score"): game.score = value; break; // 13 - Declarer case ("Declarer"): game.declarer = value; break; // 14 - Contract case ("Contract"): game.contract = value; break; // 15 - Result case ("Result"): game.result = value; break; case ("HomeTeam"): game.hometeam = value; break; case ("Room"): game.room = value; break; case ("Round"): game.round = value; break; case ("VisitTeam"): game.visitteam = value; break; case ("Table"): game.table = value; break; case ("Auction"): game.auction = value; break; case ("*"): game.comment = value; break; } } this.games.push(game); } resolve(); }) }); } // ================================================================ // File : Write fileWrite() { // ToDo } // ================================================================ // File : Validate fileValidate() { // ToDo } }
JavaScript
class PBNgame { // ================================================================ // Constructor constructor() { // ---------------------------------------------------------------- // Mandetory Tags // 1 : Event this.event = null, // 2 : Site this.site = null, // 3 : Date this.date = null, // 4 : Board this.board = null, // 5 : West this.west = null, // 6 : North this.north = null, // 7 : East this.east = null, // 8 : South this.south = null, // 9 : Dealer this.dealer = null, // 10 : Vulnerable this.vulnerable = null, // 11 : Deal this.deal = null, // 12 : Score this.score = null, // 13 : Declarer this.declarer = null, // 14 : Contract this.contract = null, // 15 : Result this.result = null // ---------------------------------------------------------------- // Other Tags // HomeTeam this.hometeam = null, // VisitTeam this.visitteam = null, // Table this.table = null, // Round this.round = null, // Room this.room = null, // Auction this.auction = null, // Comment this.comment = null } }
JavaScript
class DiagramBase extends BaseContainer { /** * Make base document structure. * @returns {Selection} Div container to contain SVG. * @protected */ makeDiagramContainer() { // add div to keep compatibility with topology visualizer return select('body') .select('div#visualizer') .append('div') .attr('class', 'network-layer') } /** * Make SVG to visualize network diagram. * @param {string} svgId - `id` attribute of SVG. * @param {string} svgClass - `class` attribute of SVG. * @param {string} svgGroupId - `id` attribute of group in SVG. * @protected */ makeRootSVG(svgId, svgClass, svgGroupId) { /** @type {Selection} */ this.diagramContainerSelection = this.makeDiagramContainer() // Keep tooltip before at svg. // In topology viewer, // add inline-block div container (info-table) after svg. /** @type {TooltipCreator} */ this.tooltip = this._makeTooltipCreator(this.diagramContainerSelection) /** @type {Selection} */ this.rootSVGSelection = this.diagramContainerSelection .append('svg') .attr('width', this.width) .attr('height', this.height) .attr('id', svgId) .attr('class', svgClass) /** @type {Selection} */ this.rootSVGGroupSelection = this.rootSVGSelection .append('g') .attr('id', svgGroupId) } /** * Resize SVG width/height. * @param {number} width - Width of SVG. * @param {number} height - Height of SVG. * @public */ resizeRootSVG(width, height) { this.width = width this.height = height this.rootSVGSelection.attr('width', width).attr('height', height) } /** * Check target node is aggregated node. * @param {AllNodeData} node - Target node. * @returns {boolean} True if target node is aggregated node. * @protected */ isAggregated(node) { // check each: `node` itself will be null/undefined return Boolean(node?.attribute?.class === 'AggregatedNodeAttribute') } /** * Check target node is aggregated node and it has family relation attribute. * @param {AllNodeData} node - Target node. * @returns {boolean} True if target node is aggregated and has family. * @protected */ isFamilyAggregated(node) { return Boolean(this.isAggregated(node) && node?.family?.relation) } /** * Check target node is aggregated and parents (not children). * @param {AllNodeData} node - Target node. * @returns {boolean} True if target node is aggregated and parents. * @private */ isParentsAggregated(node) { return ( this.isFamilyAggregated(node) && node?.family?.relation !== 'children' ) } /** * HTML class string with diff-state. * @param {AllNodeData} nodeData - Target node that has diff-state. * @returns {string} Class string of diff-state in target.f * @private */ _classOfDiffState(nodeData) { if (nodeData?.diffState) { const diffState = new DiffState(nodeData.diffState) return diffState.detect() } console.warn( `object ${nodeData.type}: ${nodeData.path} does not have diffState` ) return '' } /** * Check diff-state is visible (active) or not. * (The visualizer can toggle visibility of object according to its diff-state.) * @param {string} diffState - String by diff-state. * @returns {string} Class string for SVG element. * @private */ _classOfInactive(diffState) { // `currentInactive` is diff state to be inactive (toggled). return diffState === this.currentInactive ? 'inactive' : '' } /** * HTML class string with aggregated node. * @param {AllNodeData} nodeData - Target node. * @returns {string} Class string of target node. * @private */ _classOfAggregated(nodeData) { if (this.isParentsAggregated(nodeData)) { // selected2 : target exists in children. (indirect node highlight) return 'aggregated selected2' } else if (this.isAggregated(nodeData)) { return 'aggregated' } return '' } /** * Class string of target diagram element. * @param {AllNodeData|ForceSimulationNetwork} elementData - Target component. * @param {string} classString - Class string to set SVG. * @returns {string} Class storing including classes by node state. * @protected */ classStringFrom(elementData, classString) { const diffState = this._classOfDiffState(elementData) const nodeBaseClasses = [ diffState, this._classOfInactive(diffState), this._classOfAggregated(elementData) ] return classString.split(' ').concat(nodeBaseClasses).join(' ') } /** * Clear (remove) root-SVG. * @protected */ clearDiagramContainer() { // clear graphs select('div#visualizer') // clear all graphs .selectAll('div.network-layer') .remove() } /** * Clear (remove) tooltip. * @param {Selection} originSelection - Parent element of tooltip. * @private */ _clearTooltip(originSelection) { originSelection.select('div.tooltip').remove() } /** * Make tooltip creator. * @param {Selection} originSelection - Parent element of tooltip. * @returns {TooltipCreator} Tooltip creator. * @private */ _makeTooltipCreator(originSelection) { this._clearTooltip(originSelection) return new TooltipCreator(originSelection) } /** * Make "clear highlight" text (button) in SVG. * @private */ _makeClearHighlightButton() { const clearButtonFontSize = 12 this.rootSVGSelection .append('text') .attr('id', 'clear-button') .attr('class', 'control-button') .attr('x', clearButtonFontSize / 2) .attr('y', clearButtonFontSize) .text('[Clear Highlight]') } /** * Make "Toggle Diff ..." text 8button) in SVG. * @private */ _makeToggleDiffButton() { const clearButtonFontSize = 12 this.rootSVGSelection .append('text') .attr('id', 'diff-toggle-button') .attr('class', 'control-button') .attr('x', clearButtonFontSize / 2) .attr('y', clearButtonFontSize * 2.2) .text('[Toggle Diff Added/Deleted]') } /** * Make control texts (buttons) in SVG. * @public */ makeDiagramControlButtons() { this._makeClearHighlightButton() this._makeToggleDiffButton() } /** * Get mouse-over event handler. (to set `select-ready`) * @param {string} selector - Selector string. * @returns {function} Event handler function. * @protected */ controlButtonMouseOverCallback(selector) { return () => this.rootSVGSelection.select(selector).classed('select-ready', true) } /** * Get mouse-out event handler. (to remove `select-ready`) * @param selector - Selector string. * @returns {function} Event handler function * @protected */ controlButtonMouseOutCallback(selector) { return () => this.rootSVGSelection.select(selector).classed('select-ready', false) } /** * Set click event handler to "clear highlight" button. * @param {function} clickCallback - Click event handler. * @private */ _setClearHighlightButtonHandler(clickCallback) { const selector = 'text#clear-button' this.rootSVGSelection .select(selector) .on('click', clickCallback) .on('mouseover', this.controlButtonMouseOverCallback(selector)) .on('mouseout', this.controlButtonMouseOutCallback(selector)) } /** * Event handler for "Toggle Diff ..." button. * @private */ _toggleActiveDiff() { const visualizer = selectAll('div#visualizer') visualizer .selectAll(`.${this.currentInactive}`) .classed('inactive', false) .classed('active', true) this.currentInactive = this.currentInactive === 'deleted' ? 'added' : 'deleted' visualizer .selectAll(`.${this.currentInactive}`) .classed('inactive', true) .classed('active', false) } /** * Set click event handler to "Toggle Diff ..." button. * @private */ _setToggleDiffButtonHandler() { const selector = 'text#diff-toggle-button' this.rootSVGSelection .select(selector) .on('click', this._toggleActiveDiff) .on('mouseover', this.controlButtonMouseOverCallback(selector)) .on('mouseout', this.controlButtonMouseOutCallback(selector)) } /** * Set click event handler to control texts (button) in SVG. * @param {function} clearHighlightClickCallback - Callback function for 'Clear highlight' button. * @protected */ setDiagramControlButtonsHandler(clearHighlightClickCallback) { this._setClearHighlightButtonHandler(clearHighlightClickCallback) this._setToggleDiffButtonHandler() } /** * Clear (remove) warning message in SVG. * @public */ clearWarningMessage() { this.rootSVGSelection.selectAll('text.warning').remove() } /** * make warning message in SVG. * @param message * @public */ makeWarningMessage(message) { this.rootSVGSelection .selectAll('text.warning') .data([{ message, x: 150, y: 12 }]) .enter() .append('text') .attr('class', 'warning') .attr('x', (d) => d.x) .attr('y', (d) => d.y) .text((d) => d.message) } /** * Get regexp which matches children of path. * @param {string} path - Node path. * @returns {RegExp} Regexp matches children path. * @private */ _childPathRegexp(path) { return new RegExp(`${path}__.*`) } /** * Check target path is children path format of parent path. * @param {string} parentPath - Path of parent node. * @param {string} targetPath - path of target node. * @returns {boolean} True if target path is children format of parent path. * @protected */ matchChildPath(parentPath, targetPath) { return Boolean(targetPath.match(this._childPathRegexp(parentPath))) } /** * Get type of node by path format. * @param {string} path - Path to check. * @returns {string} Type of path. * @protected */ typeOfPath(path) { const length = path.split('__').length if (length === 3) { return 'tp' } else if (length === 2) { return 'node' } else if (length === 1) { return 'network' } return 'error' } /** * Get network name from path. * @param {string} path - Path. * @returns {string} * @protected */ networkPathOf(path) { return path.split('__').shift() // head of path string } /** * Get parent path from path. * @param {string} path - Path. * @returns {string} Parent path. * @protected */ parentPathOf(path) { const paths = path.split('__') paths.pop() // remove latest path return paths.join('__') } }
JavaScript
class IdentityProvider { /** * * @param {String} id ID of the provider. * @param {Object} oauthConfig OAuth2 configuration. */ constructor(id, oauthConfig) { /** * Generated ID of the provider. * * @type {String} */ this.id = id; this.oauthConfig = oauthConfig; // Cached token data this.tokenInfo = undefined; this.cacheKey = '_oauth_cache_' + this.id; // Latest generated state parameter for the request. this.lastState = undefined; } /** * Gets either cached authorization token or request for new one. * * If the `interactive` flag is false the authorization prompt * window will never be opened and if the authorization scope had * changed or user did not authorizaed the application this will * result in Promise error. * * @param {Object} opts Authorization options * - `interactive` {Boolean} If the interactive flag is `true`, `getAuthToken` * will prompt the user as necessary. When the flag is `false` or omitted, * `getAuthToken` will return failure any time a prompt would be required. * - `scopes` {Array<String>} List of scopes to authorize * @return {Promise} A promise resulted to the auth token. It return undefined * if the app is not authorized. The promise will result with error (reject) * if there's an authorization error. */ getAuthToken(opts) { return this.getTokenInfo() .then((info) => { if (info && this.isTokenAuthorized(info, opts.scopes || this.oauthConfig.scopes)) { return info; } this.requestOptions = opts; return this.launchWebAuthFlow(opts); }) .catch((cause) => { if (!opts.interactive) { return; } let err = new Error(cause.message); err.code = cause.code; throw err; }); } /** * Runs the web authorization flow. * @param {Object} opts Authorization options * - `interactive` {Boolean} If the interactive flag is `true`, * `launchWebAuthFlow` will prompt the user as necessary. * When the flag is `false` or omitted, `launchWebAuthFlow` * will return failure any time a prompt would be required. * - `scopes` {Array<String>} List of scopes to authorize * - `login_hint` - If your application knows which user is trying * to authenticate, it can use this parameter to provide * a hint to the Authentication Server. * The server uses the hint to simplify the login flow either by prefilling * the email field in the sign-in form or by selecting the appropriate * multi-login session. Set the parameter value to an email address or `sub` * identifier. * @return {Promise} A promise with auth result. */ launchWebAuthFlow(opts) { try { this.assertOAuthOptions(opts); } catch (e) { return Promise.reject('OAuth2: ' + e.message); } this.requestOptions = opts; const url = this.computeAuthorizationUrl(opts); const params = Object.assign({}, windowParams); params.webPreferences.session = session.fromPartition('persist:oauth2-win'); if (!opts.interactive) { params.show = false; } const win = new BrowserWindow(params); win.loadURL(url); this.observeAuthWindowNavigation(win, opts.interactive); this.currentOAuthWindow = win; return new Promise((resolve, reject) => { this.__lastPromise = { resolve: resolve, reject: reject }; }); } /** * Adds listeners to a window object. * * @param {BrowserWindow} win Window object to observe events on. */ observeAuthWindowNavigation(win, interactive) { // win.webContents.on('did-fail-load', this._authWindowFailLoadHandler.bind(this)); win.webContents.on('did-get-response-details', this._authWindowResponseDetailHandler.bind(this, interactive)); // win.webContents.on('did-get-redirect-request', (e, old, newUrl) => { // if (old.indexOf('google-analytics') !== -1) { // return; // } // console.log('REDIRECT FROM', old, 'TO' , newUrl); // }); // win.webContents.on('did-navigate', (e, url) => { // console.log('NAVIGATE EVENT TO: ', url); // }); win.on('close', this._authWindowCloseHandler.bind(this)); } /** * Removes event listeners, closes the window and cleans the property. */ unobserveAuthWindow() { const win = this.currentOAuthWindow; if (!win) { return; } // win.webContents.removeAllListeners('did-fail-load'); win.webContents.removeAllListeners('did-get-response-details'); win.removeAllListeners('close'); win.destroy(); delete this.currentOAuthWindow; } /** * Reports authorization error back to the application. * * This operation clears the promise object. * * @param {Object} details Error details to report to the app. * It should contain `code` and `message` properties. */ _reportOAuthError(details) { this.unobserveAuthWindow(); if (!this.__lastPromise) { return; } this.__lastPromise.reject(details); delete this.__lastPromise; } /** * Parses response URL and reports the result of the request. * * @param {Strinig} url Redirected response URL */ _reportOAuthResult(url) { this.unobserveAuthWindow(); let params = ''; if (this.oauthConfig.response_type === 'token') { params = url.substr(url.indexOf('#') + 1); } else { params = url.substr(url.indexOf('?') + 1); } let oauthParams = new URLSearchParams(params); if (oauthParams.has('error')) { this._reportOAuthError(this._createResponseError(oauthParams)); return; } this._processResponseData(oauthParams); } /** * Processes OAuth2 server query string response. * * @param {URLSearchParams} oauthParams Created from parameters params. */ _processResponseData(oauthParams) { const state = oauthParams.get('state'); if (state !== this.lastState) { this._reportOAuthError({ state: this.requestOptions.state, code: 'invalid_state', message: 'The state value returned by the authorization server is invalid' }); return; } if (this.oauthConfig.response_type === 'code') { this._exchangeCodeValue = oauthParams.get('code'); this._exchangeCode(this._exchangeCodeValue); return; } let tokenInfo = { access_token: oauthParams.get('access_token'), token_type: oauthParams.get('token_type'), expires_in: oauthParams.get('expires_in') }; Object.keys(tokenInfo).forEach((key) => { let camelName = this._camel(key); if (camelName) { tokenInfo[camelName] = tokenInfo[key]; } }); let scope = oauthParams.get('scope'); let requestedScopes = this.requestOptions.scopes || this.oauthConfig.scopes; if (scope) { scope = scope.split(' '); if (requestedScopes) { scope = requestedScopes.concat(scope); } } else if (requestedScopes) { scope = requestedScopes; } tokenInfo.scopes = scope; tokenInfo.expires_at = this.computeExpires(tokenInfo); this.tokenInfo = tokenInfo; this.storeToken(this.tokenInfo); tokenInfo.state = this.requestOptions.state; if (!this.__lastPromise) { return; } this.__lastPromise.resolve(Object.assign({}, tokenInfo)); delete this.__lastPromise; } /** * Exchange code for token. * * @param {String} code Returned code from the authorization endpoint. */ _exchangeCode(code) { const url = this.requestOptions.token_uri; const body = this._getCodeEchangeBody(this.requestOptions, code); this._tokenCodeRequest(url, body) .then((tokenInfo) => { this._exchangeCodeValue = undefined; this.tokenInfo = tokenInfo; this.storeToken(this.tokenInfo); if (!this.__lastPromise) { return; } this.__lastPromise.resolve(Object.assign({}, tokenInfo)); delete this.__lastPromise; }) .catch((cause) => { this._exchangeCodeValue = undefined; const detail = { message: cause.message, code: cause.code || 'unknown_error', state: this.requestOptions.state }; this._reportOAuthError(detail); }); } /** * Creates code exchange request body. * * @param {Object} settings Initial settings * @param {String} code The code to exchange * @return {String} Body to send to the server. */ _getCodeEchangeBody(settings, code) { let url = 'grant_type=authorization_code&'; url += 'client_id=' + encodeURIComponent(settings.client_id) + '&'; if (settings.redirect_uri) { url += 'redirect_uri=' + encodeURIComponent(settings.redirect_uri) + '&'; } url += 'code=' + encodeURIComponent(code) + '&'; url += 'client_secret=' + settings.client_secret; return url; } /** * Camel case given name. * * @param {String} name Value to camel case. * @return {String} Camel cased name */ _camel(name) { let i = 0; let l; let changed = false; while ((l = name[i])) { if ((l === '_' || l === '-') && i + 1 < name.length) { name = name.substr(0, i) + name[i + 1].toUpperCase() + name.substr(i + 2); changed = true; } i++; } return changed ? name : undefined; } /** * Makes a request to authorization server to exchange code to access token. * * @param {String} url Token exchange URL * @param {String} body Payload to send to the server. * @return {Promise} Promise resolved when the response is received and * processed. */ _tokenCodeRequest(url, body) { const init = { method: 'POST', body: body, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; let responseContentType; return _fetch(url, init) .then((response) => { let status = response.status; if (status === 404) { let err = new Error('Authorization URI is invalid (Error 404).'); err.code = 'invalid_uri'; throw err; } else if (status >= 400 && status < 500) { let err = new Error('Server does not support this method. ' + 'Response code is ' + status); err.code = 'method_not_supported'; throw err; } else if (status >= 500) { let err = new Error('Authorization server error. Response code is ' + status); err.code = 'server_error'; throw err; } responseContentType = response.headers.get('content-type'); return response.text(); }) .then((text) => this._processTokenCodeResponse(text, responseContentType)); } /** * Processes code exchange data. * * @param {String} data Data returned from the auth server. * @param {String} contentType Response content type. * @return {Object} tokenInfo object */ _processTokenCodeResponse(data, contentType) { contentType = contentType || ''; let tokenInfo; if (contentType.indexOf('json') !== -1) { try { tokenInfo = JSON.parse(data); Object.keys(tokenInfo).forEach((key) => { let camelName = this._camel(key); if (camelName) { tokenInfo[camelName] = tokenInfo[key]; } }); } catch (e) { let err = new Error('The response could not be parsed. ' + e.message); err.code = 'response_parse'; throw err; } } else { tokenInfo = {}; data.split('&').forEach((p) => { let item = p.split('='); let name = item[0]; let camelName = this._camel(name); let value = decodeURIComponent(item[1]); tokenInfo[name] = value; tokenInfo[camelName] = value; }); } if ('error' in tokenInfo) { let err = new Error(tokenInfo.errorDescription || 'The request is invalid.'); err.code = tokenInfo.error; throw err; } tokenInfo.scopes = this.requestOptions.scopes; tokenInfo.expires_at = this.computeExpires(tokenInfo); return tokenInfo; } /** * Creates an error object to be reported back to the app. * @param {Object} oauthParams Map of oauth response parameteres * @return {Object} Error message: * - code {String} - The `error` property returned by the server. * - message {String} - Error message returned by the server. */ _createResponseError(oauthParams) { let detail = { state: this.requestOptions.state, code: oauthParams.get('error') }; let message; if (oauthParams.has('error_description')) { message = oauthParams.get('error_description'); } else { switch (detail.code) { case 'interaction_required': message = 'The request requires user interaction.'; break; case 'invalid_request': message = 'The request is missing a required parameter.'; break; case 'invalid_client': message = 'Client authentication failed.'; break; case 'invalid_grant': message = 'The provided authorization grant or refresh token is'; message += ' invalid, expired, revoked, does not match the '; message += 'redirection URI used in the authorization request, '; message += 'or was issued to another client.'; break; case 'unauthorized_client': message = 'The authenticated client is not authorized to use this'; message += ' authorization grant type.'; break; case 'unsupported_grant_type': message = 'The authorization grant type is not supported by the'; message += ' authorization server.'; break; case 'invalid_scope': message = 'The requested scope is invalid, unknown, malformed, or'; message += ' exceeds the scope granted by the resource owner.'; break; } } detail.message = message; return detail; } // /** // * Handler for the BrowserWindow load error. // * @param {Event} event // * @param {Number} errorCode // * @param {String} errorDescription // * @param {String} validatedURL // * @param {Boolean} isMainFrame // */ // _authWindowFailLoadHandler(event, errorCode, errorDescription, // validatedURL, isMainFrame) { // if (!isMainFrame) { // return; // } // if (validatedURL.indexOf(this.oauthConfig.redirect_uri) === 0) { // this._reportOAuthResult(validatedURL); // } else { // this._reportOAuthError({ // state: this.requestOptions.state, // code: 'auth_error', // message: // 'Unexpected auth response. Make sure the OAuth2 config is valid' // }); // } // } /** * Handler for the auth window close event. * If the response wasn't reported so far it reports error. */ _authWindowCloseHandler() { if (this.__lastPromise) { this._reportOAuthError({ state: this.requestOptions.state, code: 'user_interrupted', message: 'The request has been canceled by the user.' }); } } /** * Handler for the `did-get-response-details` event fired by the auth window. * * @param {Event} event * @param {Number} status * @param {String} newURL * @param {String} originalURL * @param {Number} httpResponseCode * @param {String} requestMethod * @param {String} referrer * @param {Object} headers * @param {String} resourceType */ _authWindowResponseDetailHandler(interactive, event, status, newURL, originalURL, httpResponseCode, requestMethod, referrer, headers, resourceType) { if (resourceType !== 'mainFrame') { return; } if (httpResponseCode >= 400) { // This is an error. Redirect URL can be fake and this should catch // valid response in 400 status code. if (newURL.indexOf(this.oauthConfig.redirect_uri) !== 0) { let msg = 'Unable to run authorization flow. Make sure the OAuth2 '; msg += 'config is valid.'; this._reportOAuthError({ state: this.requestOptions.state, code: 'url_error', message: msg }); return; } } if (newURL.indexOf(this.oauthConfig.redirect_uri) === 0) { if (this.__loadPopupTimeout) { clearTimeout(this.__loadPopupTimeout); } this._reportOAuthResult(newURL); } else { if (interactive === false) { this.__loadPopupTimeout = setTimeout(() => { this._reportOAuthError({ state: this.requestOptions.state, code: 'auth_error', message: 'No response from the server.' }); }, 1000); } } } /** * Computes authorization URL * @param {Object} opts See options for `launchWebAuthFlow` * @return {String} Complete authorization URL. */ computeAuthorizationUrl(opts) { let cnf = this.oauthConfig; let url = cnf.auth_uri + '?'; url += 'client_id=' + encodeURIComponent(cnf.client_id); url += '&redirect_uri=' + encodeURIComponent(cnf.redirect_uri); url += '&response_type=' + cnf.response_type; let scopes = opts.scopes || this.oauthConfig.scopes; if (scopes) { url += '&scope=' + this.computeScope(scopes); } url += '&state=' + this.setStateParameter(opts.state); if (cnf.include_granted_scopes) { url += '&include_granted_scopes=true'; } if (opts.login_hint) { url += '&login_hint=' + encodeURIComponent(opts.login_hint); } if (!opts.interactive) { url += '&prompt=none'; } return url; } /** * Computes `scope` URL parameter from scopes array. * * @param {Array<String>} scopes List of scopes to use with the request. * @return {String} Computed scope value. */ computeScope(scopes) { if (!scopes) { return ''; } let scope = scopes.join(' '); return encodeURIComponent(scope); } /** * Asserts that the OAuth configuration is valid. * * This throws an error when configuration is invalid with error message. */ assertOAuthOptions() { let cnf = this.oauthConfig; let messages = []; if (!cnf.client_id) { messages.push('"client_id" is required but is missing.'); } if (!cnf.auth_uri) { messages.push('"auth_uri" is required but is missing.'); } if (!cnf.redirect_uri) { messages.push('"redirect_uri" is required but is missing.'); } if (cnf.response_type === 'code') { if (!cnf.client_secret) { messages.push( '"code" response type requires "client_secret" to be set.' ); } if (!cnf.token_uri) { messages.push('"code" response type requires "token_uri" to be set.'); } } if (messages.length) { throw new Error(messages.join(' ')); } } /** * Checks if current token is authorized for given list of scopes. * * @param {Object} tokenInfo A token info object. * @param {Array<String>} scopes List of scopes to authorize. * @return {Boolean} True if requested scope is already authorized with this * token. */ isTokenAuthorized(tokenInfo, scopes) { let grantedScopes = tokenInfo.scopes; if (!grantedScopes || !grantedScopes.length) { return true; } if (!scopes || !scopes.length) { return true; } grantedScopes = grantedScopes.map((scope) => scope.trim()); scopes = scopes.map((scope) => scope.trim()); let missing = scopes.find((scope) => { return grantedScopes.indexOf(scope) === -1; }); return !missing; } /** * Returns cached token info. * * @return {Object} Token info ibject or undefined if there's no cached token * or cached token expired. */ getTokenInfo() { let promise; if (!this.tokenInfo) { promise = this.restoreTokenInfo(); } else { promise = Promise.resolve(this.tokenInfo); } return promise .then((info) => { this.tokenInfo = info; if (!this.tokenInfo) { return; } if (this.isExpired(this.tokenInfo)) { this.tokenInfo = undefined; return; } return this.tokenInfo; }); } /** * Restores authorization token information from the local store. * * @return {Object} Token info object or undefined if not set or expired. */ restoreTokenInfo() { let bw = BrowserWindow.getAllWindows()[0]; // All schare the same session. let str = `localStorage.getItem('${this.cacheKey}')`; return bw.webContents.executeJavaScript(str) .then((data) => { if (!data) { return; } try { let tokenInfo = JSON.parse(data); if (this.isExpired(tokenInfo)) { str = `localStorage.removeItem('${this.cacheKey}')`; return bw.webContents.executeJavaScript(str); } return tokenInfo; } catch (e) {} }); } /** * Casches token data in local storage. * * @param {Object} tokenInfo * @return {Promise} Resolved promise when code is executed */ storeToken(tokenInfo) { let bw = BrowserWindow.getAllWindows()[0]; let str = `localStorage.setItem('${this.cacheKey}','`; str += JSON.stringify(tokenInfo); str += '\')'; return bw.webContents.executeJavaScript(str); } /** * Checks if the token already expired. * * @param {Object} tokenInfo Token info object * @return {Boolean} True if the token is already expired and should be * reneved. */ isExpired(tokenInfo) { if (!tokenInfo || !tokenInfo.expires_at) { return true; } if (Date.now() > tokenInfo.expires_at) { return true; } return false; } /** * Computes token expiration time. * * @param {Object} tokenInfo Token info object * @return {Number} Time in the future when when the token expires. */ computeExpires(tokenInfo) { let expiresIn = tokenInfo.expires_in || 3600; if (typeof expiresIn !== 'number') { expiresIn = Number(expiresIn); if (expiresIn !== expiresIn) { expiresIn = 3600; } } expiresIn = Date.now() + (expiresIn * 1000); return expiresIn; } /** * Generates a random string to be used as a `state` parameter, sets the * `lastState` property to generated text and returns the value. * @param {?String} state A state property if set. * @return {String} Generated state parameter. */ setStateParameter(state) { if (!state) { state = ''; let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; possible += '0123456789'; for (let i = 0; i < 12; i++) { state += possible.charAt(Math.floor(Math.random() * possible.length)); } } this.lastState = state; return state; } }
JavaScript
class ArcIdentity { /** * Listens for the renderer process events related to OAuth provider. */ static listen() { ipcMain.on('oauth-2-get-token', ArcIdentity._getTokenHandler); ipcMain.on('oauth-2-launch-web-flow', ArcIdentity._launchWebFlowHandler); } /** * Handler for the `oauth-2-get-token` event from the render process. * Lunches the default OAuth flow with properties read from the manifest file. * * @param {Object} event * @param {Object} options Oauth options. See `ArcIdentity.getAuthToken` * for description */ static _getTokenHandler(event, options) { ArcIdentity.getAuthToken(options) .then((token) => { event.sender.send('oauth-2-token-ready', token); }) .catch((cause) => { event.sender.send('oauth-2-token-error', cause); }); } /** * Handler for the `oauth-2-launch-web-flow` event from the render process. * Lunches OAuth flow in browser window. * * @param {Object} event * @param {Object} options Oauth options. See `ArcIdentity.launchWebAuthFlow` * for description * @param {String} id Id generated in the renderer to recognize the request. */ static _launchWebFlowHandler(event, options, id) { ArcIdentity.launchWebAuthFlow(options) .then((token) => { event.sender.send('oauth-2-token-ready', token, id); }) .catch((cause) => { event.sender.send('oauth-2-token-error', cause, id); }); } /** * Generates a provider ID as an identifier for an identity * * @param {String} authUrl User authorization URI * @param {String} clientId Client ID * @return {String} An ID to be used to identity a provider. */ static _generateProviderId(authUrl, clientId) { return encodeURIComponent(authUrl) + '/' + encodeURIComponent(clientId); } /** * Adds a provider to the list of existing (cached) providers. * * @param {IdentityProvider} provider Provider to cache. */ static _setProvider(provider) { if (!ArcIdentity.__providers) { ArcIdentity.__providers = []; } ArcIdentity.__providers.push(provider); } /** * Looks for existing OAuth provider with (possibly) cached auth data. * * @param {String} authUrl Authorization URL * @param {String} clientId Client ID used to authenticate. * @return {IdentityProvider} An identity provider or `undefined` if * not exists. */ static _getProvider(authUrl, clientId) { if (!ArcIdentity.__providers) { return; } const id = ArcIdentity._generateProviderId(authUrl, clientId); return ArcIdentity.__providers.find((item) => item.id === id); } /** * Runs the web authorization flow. * @param {Object} opts Authorization options * - `interactive` {Boolean} If the interactive flag is `true`, * `launchWebAuthFlow` will prompt the user as necessary. When the flag * is `false` or omitted, * `launchWebAuthFlow` will return failure any time a prompt would be * required. * - `response_type` {String} `code` or `token`. * - `scopes` {Array<String>} List of scopes to authorize * - `client_id` {String} The client ID used for authorization * - `auth_uri` {String} Authorization URI * - `token_uri` {String} Optional, required if `response_type` is code * - `redirect_uri` {String} Auth redirect URI * - `client_secret` {String} Optional, required if `response_type` is code * - `include_granted_scopes` {Boolean} Optional. * - `login_hint` {String} Optional, user email * @return {Promise} A promise with auth result. */ static launchWebAuthFlow(opts) { let provider = ArcIdentity._getOrCreateProvider(opts); return provider.launchWebAuthFlow(opts); } /** * A method to call to authorize the user in Google authorization services. * * @param {Object} opts Authorization options * - `interactive` {Boolean} If the interactive flag is `true`, `getAuthToken` * will prompt the user as necessary. When the flag is `false` or omitted, * `getAuthToken` will return failure any time a prompt would be required. * - `scopes` {Array<String>} List of scopes to authorize * @return {Promise} A promise resulted to the auth token. */ static getAuthToken(opts) { return ArcIdentity.getOAuthConfig() .then((config) => ArcIdentity._getOrCreateProvider(config)) .then((provider) => provider.getAuthToken(opts)); } /** * Reads the default OAuth configuration for the app from package file. * * @return {Promise} A promise resolved to OAuth2 configuration object */ static getOAuthConfig() { if (ArcIdentity.__oauthConfig) { return Promise.resolve(ArcIdentity.__oauthConfig); } return fs.readJson(path.join(__dirname, '..', '..', 'package.json')) .then((packageInfo) => packageInfo.oauth2) .then((config) => { ArcIdentity.__oauthConfig = config; return config; }); } /** * Returns chached provider or creates new provider based on the oauth * configuration. * * @param {Object} oauthConfig OAuth2 configuration object. * @return {IdentityProvider} Identity provider for given config. */ static _getOrCreateProvider(oauthConfig) { let provider = ArcIdentity._getProvider( oauthConfig.auth_uri, oauthConfig.client_id); if (!provider) { const id = ArcIdentity._generateProviderId(oauthConfig.auth_uri, oauthConfig.client_id); const cnf = Object.assign({}, oauthConfig); if (!cnf.response_type) { cnf.response_type = 'token'; cnf.include_granted_scopes = true; } provider = new IdentityProvider(id, cnf); ArcIdentity._setProvider(provider); } return provider; } }
JavaScript
class Stepper extends BaseComponent { static displayName = 'Stepper'; static propTypes = { /** * Text to show next to the current number */ label: React.PropTypes.string, /** * Minimum value */ min: React.PropTypes.number.isRequired, /** * Maximum value */ max: React.PropTypes.number, /** * Additional styles for the top container */ containerStyle: React.PropTypes.object, /** * Handler function to receive updates when the value changes */ onValueChange: React.PropTypes.func, /** * the initial value */ initialValue: React.PropTypes.number.isRequired, }; constructor(props) { super(props); this.state = { value: props.initialValue, }; } generateStyles() { this.styles = createStyles(this.props.size); } getLabel() { return [this.state.value, this.props.label].join(' '); } getDisabledState() { const minusDisabled = this.state.value === this.props.min; const plusDisabled = this.state.value === this.props.max; return {minusDisabled, plusDisabled}; } updateValue(value) { let newValue = _.max([value, this.props.min]); newValue = _.min([newValue, this.props.max]); if (this.state.value !== newValue) { this.setState({ value: newValue, }, () => { if (this.props.onValueChange) { this.props.onValueChange(newValue); } }); } } render() { const {minusDisabled, plusDisabled} = this.getDisabledState(); return ( <View style={[this.styles.container, this.props.containerStyle]}> <View style={this.styles.title}> <Text testID={'label'} style={this.styles.titleText}>{this.getLabel()}</Text> </View> <View style={this.styles.buttons}> <StepperButton label="-" testId={'decrease'} styles={this.styles} disabled={minusDisabled} onPress={() => this.updateValue(this.state.value - 1)} /> <View style={this.styles.separator}/> <StepperButton label="+" testId={'increase'} styles={this.styles} disabled={plusDisabled} onPress={() => this.updateValue(this.state.value + 1)} /> </View> </View> ); } }
JavaScript
class VigenereCipheringMachine { directMachine = true; constructor(isDirect) { if (arguments.length == 0) { this.directMachine = true; } else { this.directMachine = isDirect; } } encrypt(str, key) { const argErrorMessage = 'Incorrect arguments!'; function tabulaRectaEncodeChar(charY,charX) { let Y=charY.toUpperCase().charCodeAt(0); let X=charX.toUpperCase().charCodeAt(0); if (X+Y-65 > 90 ) { return String.fromCharCode(X+Y-65-26) } else { return String.fromCharCode(X+Y-65) } } if (arguments.length < 2) {throw new Error(argErrorMessage)} if (arguments[0] === undefined || arguments[1] === undefined ) {throw new Error(argErrorMessage)} let stringToEncode = ('' + str).toUpperCase(); let symbolsToEncode = ''; for (let i=0; i < stringToEncode.length; i++) { if (stringToEncode.charCodeAt(i)>=65 && stringToEncode.charCodeAt(i) <= 90) { symbolsToEncode = symbolsToEncode + stringToEncode[i]; } } let adjustedKey = (''+ key).repeat(Math.trunc(symbolsToEncode.length / key.length)).toUpperCase() + (''+ key).substring(0,symbolsToEncode.length % key.length).toUpperCase(); let encodedString = ''; let k =0; for (let i = 0; i < stringToEncode.length; i++) { if (stringToEncode.charCodeAt(i)>=65 && stringToEncode.charCodeAt(i) <= 90) { encodedString = encodedString + tabulaRectaEncodeChar(stringToEncode[i],adjustedKey[k]); k++; } else { encodedString = encodedString + stringToEncode[i]; } } if (!this.directMachine) {encodedString = encodedString.split('').reverse().join('')} // console.log(encodedString);//todo - remove return encodedString; } decrypt(str, key) { const argErrorMessage = `Incorrect arguments!`; function tabulaRectaDecodeChar(charEncoded,charKey) { let C=charEncoded.toUpperCase().charCodeAt(0); let X=charKey.toUpperCase().charCodeAt(0); let decodedCharCode = 65 + C - X; if (decodedCharCode < 65) {decodedCharCode += 26} return String.fromCharCode(decodedCharCode) } if (arguments.length < 2) {throw new Error(argErrorMessage)} if (arguments[0] === undefined || arguments[1] === undefined ) {throw new Error(argErrorMessage)} let stringToDecode = ('' + str).toUpperCase(); let symbolsToDecode = ''; for (let i=0; i < stringToDecode.length; i++) { if (stringToDecode.charCodeAt(i)>=65 && stringToDecode.charCodeAt(i) <= 90) { symbolsToDecode = symbolsToDecode + stringToDecode[i]; } } let adjustedKey = (''+ key).repeat(Math.trunc(symbolsToDecode.length / key.length)).toUpperCase() + (''+ key).substring(0,symbolsToDecode.length % key.length).toUpperCase(); let decodedString = ''; let k =0; for (let i = 0; i < stringToDecode.length; i++) { if (stringToDecode.charCodeAt(i)>=65 && stringToDecode.charCodeAt(i) <= 90) { decodedString = decodedString + tabulaRectaDecodeChar(stringToDecode[i],adjustedKey[k]); k++; } else { decodedString = decodedString + stringToDecode[i]; } } if (!this.directMachine) {decodedString = decodedString.split('').reverse().join('')} //console.log(decodedString);//todo - remove return decodedString; } }