_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q22600
formatClassicOptions
train
function formatClassicOptions(options) { return alias(options, { forumId: 'forum_id', classicMode: 'mode', primaryColor: 'primary_color', tabPosition: 'tab_position', tabColor: 'tab_color', linkColor: 'link_color', defaultMode: 'default_mode', tabLabel: 'tab_label', tabInverted: 'tab_inverted' }); }
javascript
{ "resource": "" }
q22601
enqueue
train
function enqueue(fn) { window._vis_opt_queue = window._vis_opt_queue || []; window._vis_opt_queue.push(fn); }
javascript
{ "resource": "" }
q22602
variation
train
function variation(id) { var experiments = window._vwo_exp; if (!experiments) return null; var experiment = experiments[id]; var variationId = experiment.combination_chosen; return variationId ? experiment.comb_n[variationId] : null; }
javascript
{ "resource": "" }
q22603
push
train
function push(callback) { window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || []; window.yandex_metrika_callbacks.push(callback); }
javascript
{ "resource": "" }
q22604
chunkLength
train
function chunkLength (chunk, encoding) { if (!chunk) { return 0 } return !Buffer.isBuffer(chunk) ? Buffer.byteLength(chunk, encoding) : chunk.length }
javascript
{ "resource": "" }
q22605
shouldCompress
train
function shouldCompress (req, res) { var type = res.getHeader('Content-Type') if (type === undefined || !compressible(type)) { debug('%s not compressible', type) return false } return true }
javascript
{ "resource": "" }
q22606
shouldTransform
train
function shouldTransform (req, res) { var cacheControl = res.getHeader('Cache-Control') // Don't compress for Cache-Control: no-transform // https://tools.ietf.org/html/rfc7234#section-5.2.2.4 return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl) }
javascript
{ "resource": "" }
q22607
toBuffer
train
function toBuffer (chunk, encoding) { return !Buffer.isBuffer(chunk) ? Buffer.from(chunk, encoding) : chunk }
javascript
{ "resource": "" }
q22608
transform
train
function transform(hash, styles, settings = {}) { generator = settings.generator offset = settings.offset filename = settings.filename splitRules = [] stylis.set({ prefix: typeof settings.vendorPrefixes === 'boolean' ? settings.vendorPrefixes : true }) stylis(hash, styles) if (settings.splitRules) { return splitRules } return splitRules.join('') }
javascript
{ "resource": "" }
q22609
addClasses
train
function addClasses (el, classStr) { if (typeof classStr !== 'string' || classStr.length === 0) { return } var classes = classStr.split(' ') for (var i = 0; i < classes.length; i++) { var className = classes[i] if (className.length) { el.classList.add(className) } } }
javascript
{ "resource": "" }
q22610
close
train
function close (vexOrId) { var id if (vexOrId.id) { id = vexOrId.id } else if (typeof vexOrId === 'string') { id = vexOrId } else { throw new TypeError('close requires a vex object or id string') } if (!vexes[id]) { return false } return vexes[id].close() }
javascript
{ "resource": "" }
q22611
rollback
train
function rollback(newVersion) { if (strategy === 'stable') { // reset master shell.exec('git reset --hard origin/master'); shell.exec('git checkout develop'); } else { // remove last commit shell.exec('git reset --hard HEAD~1'); } // remove local created tag shell.exec(`git tag -d v${newVersion}`); process.exit(1); }
javascript
{ "resource": "" }
q22612
transformTemplates
train
function transformTemplates(templates) { const allTemplates = { ...templates, submit: templates.searchableSubmit, reset: templates.searchableReset, loadingIndicator: templates.searchableLoadingIndicator, }; const { searchableReset, searchableSubmit, searchableLoadingIndicator, ...transformedTemplates } = allTemplates; return transformedTemplates; }
javascript
{ "resource": "" }
q22613
clearRefinements
train
function clearRefinements({ helper, attributesToClear = [] }) { let finalState = helper.state; attributesToClear.forEach(attribute => { if (attribute === '_tags') { finalState = finalState.clearTags(); } else { finalState = finalState.clearRefinements(attribute); } }); if (attributesToClear.indexOf('query') !== -1) { finalState = finalState.setQuery(''); } return finalState; }
javascript
{ "resource": "" }
q22614
prepareTemplateProps
train
function prepareTemplateProps({ defaultTemplates, templates, templatesConfig, }) { const preparedTemplates = prepareTemplates(defaultTemplates, templates); return { templatesConfig, ...preparedTemplates, }; }
javascript
{ "resource": "" }
q22615
getDependencies
train
function getDependencies(bundleType, entry) { const packageJson = require(path.dirname(require.resolve(entry)) + "/package.json") // Both deps and peerDeps are assumed as accessible. return Array.from( new Set([ ...Object.keys(packageJson.dependencies || {}), ...Object.keys(packageJson.peerDependencies || {}) ]) ) }
javascript
{ "resource": "" }
q22616
inputSymbol
train
async function inputSymbol(symbol) { if (typeof symbol === 'undefined') { STSymbol = readlineSync.question(chalk.yellow(`Enter the symbol of a registered security token or press 'Enter' to exit: `)); } else { STSymbol = symbol; } if (STSymbol == "") process.exit(); STAddress = await securityTokenRegistry.methods.getSecurityTokenAddress(STSymbol).call(); if (STAddress == "0x0000000000000000000000000000000000000000") { console.log(`Token symbol provided is not a registered Security Token. Please enter another symbol.`); } else { let securityTokenABI = abis.securityToken(); securityToken = new web3.eth.Contract(securityTokenABI, STAddress); await showTokenInfo(); let gtmModule = await securityToken.methods.getModulesByName(web3.utils.toHex('GeneralTransferManager')).call(); let generalTransferManagerABI = abis.generalTransferManager(); generalTransferManager = new web3.eth.Contract(generalTransferManagerABI, gtmModule[0]); let stoModules = await securityToken.methods.getModulesByType(gbl.constants.MODULES_TYPES.STO).call(); if (stoModules.length == 0) { console.log(chalk.red(`There is no STO module attached to the ${STSymbol.toUpperCase()} Token. No further actions can be taken.`)); process.exit(0); } else { STOAddress = stoModules[0]; let stoModuleData = await securityToken.methods.getModule(STOAddress).call(); selectedSTO = web3.utils.toAscii(stoModuleData[0]).replace(/\u0000/g, ''); let interfaceSTOABI = abis.stoInterface(); currentSTO = new web3.eth.Contract(interfaceSTOABI, STOAddress); } } }
javascript
{ "resource": "" }
q22617
addModule
train
async function addModule() { let options = ['Permission Manager', 'Transfer Manager', 'Security Token Offering', 'Dividends', 'Burn']; let index = readlineSync.keyInSelect(options, 'What type of module would you like to add?', { cancel: 'Return' }); switch (options[index]) { case 'Permission Manager': console.log(chalk.red(` ********************************* This option is not yet available. *********************************`)); break; case 'Transfer Manager': await transferManager.addTransferManagerModule(tokenSymbol) break; case 'Security Token Offering': await stoManager.addSTOModule(tokenSymbol) break; case 'Dividends': console.log(chalk.red(` ********************************* This option is not yet available. *********************************`)); break; case 'Burn': console.log(chalk.red(` ********************************* This option is not yet available. *********************************`)); break; } }
javascript
{ "resource": "" }
q22618
cleanupOS
train
function cleanupOS(os, pattern, label) { // Platform tokens are defined at: // http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx // http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx var data = { '10.0': '10', '6.4': '10 Technical Preview', '6.3': '8.1', '6.2': '8', '6.1': 'Server 2008 R2 / 7', '6.0': 'Server 2008 / Vista', '5.2': 'Server 2003 / XP 64-bit', '5.1': 'XP', '5.01': '2000 SP1', '5.0': '2000', '4.0': 'NT', '4.90': 'ME' }; // Detect Windows version from platform tokens. if (pattern && label && /^Win/i.test(os) && !/^Windows Phone /i.test(os) && (data = data[/[\d.]+$/.exec(os)])) { os = 'Windows ' + data; } // Correct character case and cleanup string. os = String(os); if (pattern && label) { os = os.replace(RegExp(pattern, 'i'), label); } os = format( os.replace(/ ce$/i, ' CE') .replace(/\bhpw/i, 'web') .replace(/\bMacintosh\b/, 'Mac OS') .replace(/_PowerPC\b/i, ' OS') .replace(/\b(OS X) [^ \d]+/i, '$1') .replace(/\bMac (OS X)\b/, '$1') .replace(/\/(\d)/, ' $1') .replace(/_/g, '.') .replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '') .replace(/\bx86\.64\b/gi, 'x86_64') .replace(/\b(Windows Phone) OS\b/, '$1') .replace(/\b(Chrome OS \w+) [\d.]+\b/, '$1') .split(' on ')[0] ); return os; }
javascript
{ "resource": "" }
q22619
each
train
function each(object, callback) { var index = -1, length = object ? object.length : 0; if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) { while (++index < length) { callback(object[index], index, object); } } else { forOwn(object, callback); } }
javascript
{ "resource": "" }
q22620
format
train
function format(string) { string = trim(string); return /^(?:webOS|i(?:OS|P))/.test(string) ? string : capitalize(string); }
javascript
{ "resource": "" }
q22621
forOwn
train
function forOwn(object, callback) { for (var key in object) { if (hasOwnProperty.call(object, key)) { callback(object[key], key, object); } } }
javascript
{ "resource": "" }
q22622
getManufacturer
train
function getManufacturer(guesses) { return reduce(guesses, function(result, value, key) { // Lookup the manufacturer by product or scan the UA for the manufacturer. return result || ( value[product] || value[/^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] || RegExp('\\b' + qualify(key) + '(?:\\b|\\w*\\d)', 'i').exec(ua) ) && key; }); }
javascript
{ "resource": "" }
q22623
getOS
train
function getOS(guesses) { return reduce(guesses, function(result, guess) { var pattern = guess.pattern || qualify(guess); if (!result && (result = RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua) )) { result = cleanupOS(result, pattern, guess.label || guess); } return result; }); }
javascript
{ "resource": "" }
q22624
getProduct
train
function getProduct(guesses) { return reduce(guesses, function(result, guess) { var pattern = guess.pattern || qualify(guess); if (!result && (result = RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) || RegExp('\\b' + pattern + ' *\\w+-[\\w]*', 'i').exec(ua) || RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua) )) { // Split by forward slash and append product version if needed. if ((result = String((guess.label && !RegExp(pattern, 'i').test(guess.label)) ? guess.label : result).split('/'))[1] && !/[\d.]+/.test(result[0])) { result[0] += ' ' + result[1]; } // Correct character case and cleanup string. guess = guess.label || guess; result = format(result[0] .replace(RegExp(pattern, 'i'), guess) .replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ') .replace(RegExp('(' + guess + ')[-_.]?(\\w)', 'i'), '$1 $2')); } return result; }); }
javascript
{ "resource": "" }
q22625
getVersion
train
function getVersion(patterns) { return reduce(patterns, function(result, pattern) { return result || (RegExp(pattern + '(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null; }); }
javascript
{ "resource": "" }
q22626
Characteristic
train
function Characteristic(displayName, UUID, props) { this.displayName = displayName; this.UUID = UUID; this.iid = null; // assigned by our containing Service this.value = null; this.status = null; this.eventOnlyCharacteristic = false; this.props = props || { format: null, unit: null, minValue: null, maxValue: null, minStep: null, perms: [] }; this.subscriptions = 0; }
javascript
{ "resource": "" }
q22627
AccessoryInfo
train
function AccessoryInfo(username) { this.username = username; this.displayName = ""; this.category = ""; this.pincode = ""; this.signSk = bufferShim.alloc(0); this.signPk = bufferShim.alloc(0); this.pairedClients = {}; // pairedClients[clientUsername:string] = clientPublicKey:Buffer this.configVersion = 1; this.configHash = ""; this.setupID = ""; this.relayEnabled = false; this.relayState = 2; this.relayAccessoryID = ""; this.relayAdminID = ""; this.relayPairedControllers = {}; this.accessoryBagURL = ""; }
javascript
{ "resource": "" }
q22628
EventedHTTPServerConnection
train
function EventedHTTPServerConnection(clientSocket) { this.sessionID = uuid.generate(clientSocket.remoteAddress + ':' + clientSocket.remotePort); this._remoteAddress = clientSocket.remoteAddress; // cache because it becomes undefined in 'onClientSocketClose' this._pendingClientSocketData = bufferShim.alloc(0); // data received from client before HTTP proxy is fully setup this._fullySetup = false; // true when we are finished establishing connections this._writingResponse = false; // true while we are composing an HTTP response (so events can wait) this._pendingEventData = bufferShim.alloc(0); // event data waiting to be sent until after an in-progress HTTP response is being written // clientSocket is the socket connected to the actual iOS device this._clientSocket = clientSocket; this._clientSocket.on('data', this._onClientSocketData.bind(this)); this._clientSocket.on('close', this._onClientSocketClose.bind(this)); this._clientSocket.on('error', this._onClientSocketError.bind(this)); // we MUST register for this event, otherwise the error will bubble up to the top and crash the node process entirely. // serverSocket is our connection to our own internal httpServer this._serverSocket = null; // created after httpServer 'listening' event // create our internal HTTP server for this connection that we will proxy data to and from this._httpServer = http.createServer(); this._httpServer.timeout = 0; // clients expect to hold connections open as long as they want this._httpServer.keepAliveTimeout = 0; // workaround for https://github.com/nodejs/node/issues/13391 this._httpServer.on('listening', this._onHttpServerListening.bind(this)); this._httpServer.on('request', this._onHttpServerRequest.bind(this)); this._httpServer.on('error', this._onHttpServerError.bind(this)); this._httpServer.listen(0); // an arbitrary dict that users of this class can store values in to associate with this particular connection this._session = { sessionID: this.sessionID }; // a collection of event names subscribed to by this connection this._events = {}; // this._events[eventName] = true (value is arbitrary, but must be truthy) debug("[%s] New connection from client", this._remoteAddress); }
javascript
{ "resource": "" }
q22629
Service
train
function Service(displayName, UUID, subtype) { if (!UUID) throw new Error("Services must be created with a valid UUID."); this.displayName = displayName; this.UUID = UUID; this.subtype = subtype; this.iid = null; // assigned later by our containing Accessory this.characteristics = []; this.optionalCharacteristics = []; this.isHiddenService = false; this.isPrimaryService = false; this.linkedServices = []; // every service has an optional Characteristic.Name property - we'll set it to our displayName // if one was given // if you don't provide a display name, some HomeKit apps may choose to hide the device. if (displayName) { // create the characteristic if necessary var nameCharacteristic = this.getCharacteristic(Characteristic.Name) || this.addCharacteristic(Characteristic.Name); nameCharacteristic.setValue(displayName); } }
javascript
{ "resource": "" }
q22630
clone
train
function clone(object, extend) { var cloned = {}; for (var key in object) { cloned[key] = object[key]; } for (var key in extend) { cloned[key] = extend[key]; } return cloned; }
javascript
{ "resource": "" }
q22631
Accessory
train
function Accessory(displayName, UUID) { if (!displayName) throw new Error("Accessories must be created with a non-empty displayName."); if (!UUID) throw new Error("Accessories must be created with a valid UUID."); if (!uuid.isValid(UUID)) throw new Error("UUID '" + UUID + "' is not a valid UUID. Try using the provided 'generateUUID' function to create a valid UUID from any arbitrary string, like a serial number."); this.displayName = displayName; this.UUID = UUID; this.aid = null; // assigned by us in assignIDs() or by a Bridge this._isBridge = false; // true if we are a Bridge (creating a new instance of the Bridge subclass sets this to true) this.bridged = false; // true if we are hosted "behind" a Bridge Accessory this.bridgedAccessories = []; // If we are a Bridge, these are the Accessories we are bridging this.reachable = true; this.category = Accessory.Categories.OTHER; this.services = []; // of Service this.cameraSource = null; this.shouldPurgeUnusedIDs = true; // Purge unused ids by default // create our initial "Accessory Information" Service that all Accessories are expected to have this .addService(Service.AccessoryInformation) .setCharacteristic(Characteristic.Name, displayName) .setCharacteristic(Characteristic.Manufacturer, "Default-Manufacturer") .setCharacteristic(Characteristic.Model, "Default-Model") .setCharacteristic(Characteristic.SerialNumber, "Default-SerialNumber") .setCharacteristic(Characteristic.FirmwareRevision, "1.0"); // sign up for when iOS attempts to "set" the Identify characteristic - this means a paired device wishes // for us to identify ourselves (as opposed to an unpaired device - that case is handled by HAPServer 'identify' event) this .getService(Service.AccessoryInformation) .getCharacteristic(Characteristic.Identify) .on('set', function(value, callback) { if (value) { var paired = true; this._identificationRequest(paired, callback); } }.bind(this)); }
javascript
{ "resource": "" }
q22632
HAPServer
train
function HAPServer(accessoryInfo, relayServer) { this.accessoryInfo = accessoryInfo; this.allowInsecureRequest = false; // internal server that does all the actual communication this._httpServer = new EventedHTTPServer(); this._httpServer.on('listening', this._onListening.bind(this)); this._httpServer.on('request', this._onRequest.bind(this)); this._httpServer.on('encrypt', this._onEncrypt.bind(this)); this._httpServer.on('decrypt', this._onDecrypt.bind(this)); this._httpServer.on('session-close', this._onSessionClose.bind(this)); if (relayServer) { this._relayServer = relayServer; this._relayServer.on('request', this._onRemoteRequest.bind(this)); this._relayServer.on('encrypt', this._onEncrypt.bind(this)); this._relayServer.on('decrypt', this._onDecrypt.bind(this)); } // so iOS is very reluctant to actually disconnect HAP connections (as in, sending a FIN packet). // For instance, if you turn off wifi on your phone, it will not close the connection, instead // it will leave it open and hope that it's still valid when it returns to the network. And Node, // by itself, does not ever "discover" that the connection has been closed behind it, until a // potentially very long system-level socket timeout (like, days). To work around this, we have // invented a manual "keepalive" mechanism where we send "empty" events perodicially, such that // when Node attempts to write to the socket, it discovers that it's been disconnected after // an additional one-minute timeout (this timeout appears to be hardcoded). this._keepAliveTimerID = setInterval(this._onKeepAliveTimerTick.bind(this), 1000 * 60 * 10); // send keepalive every 10 minutes }
javascript
{ "resource": "" }
q22633
HAPEncryption
train
function HAPEncryption() { // initialize member vars with null-object values this.clientPublicKey = bufferShim.alloc(0); this.secretKey = bufferShim.alloc(0); this.publicKey = bufferShim.alloc(0); this.sharedSec = bufferShim.alloc(0); this.hkdfPairEncKey = bufferShim.alloc(0); this.accessoryToControllerCount = { value: 0 }; this.controllerToAccessoryCount = { value: 0 }; this.accessoryToControllerKey = bufferShim.alloc(0); this.controllerToAccessoryKey = bufferShim.alloc(0); this.extraInfo = {}; }
javascript
{ "resource": "" }
q22634
Advertiser
train
function Advertiser(accessoryInfo, mdnsConfig) { this.accessoryInfo = accessoryInfo; this._bonjourService = bonjour(mdnsConfig); this._advertisement = null; this._setupHash = this._computeSetupHash(); }
javascript
{ "resource": "" }
q22635
loadDirectory
train
function loadDirectory(dir) { // exported accessory objects loaded from this dir var accessories = []; fs.readdirSync(dir).forEach(function(file) { // "Accessories" are modules that export a single accessory. if (file.split('_').pop() === 'accessory.js') { debug('Parsing accessory: %s', file); var loadedAccessory = require(path.join(dir, file)).accessory; accessories.push(loadedAccessory); } // "Accessory Factories" are modules that export an array of accessories. else if (file.split('_').pop() === 'accfactory.js') { debug('Parsing accessory factory: %s', file); // should return an array of objects { accessory: accessory-json } var loadedAccessories = require(path.join(dir, file)); accessories = accessories.concat(loadedAccessories); } }); // now we need to coerce all accessory objects into instances of Accessory (some or all of them may // be object-literal JSON-style accessories) return accessories.map(function(accessory) { if(accessory === null || accessory === undefined) { //check if accessory is not empty console.log("Invalid accessory!"); return false; } else { return (accessory instanceof Accessory) ? accessory : parseAccessoryJSON(accessory); } }).filter(function(accessory) { return accessory ? true : false; }); }
javascript
{ "resource": "" }
q22636
TimelineWindow
train
function TimelineWindow(client, timelineSet, opts) { opts = opts || {}; this._client = client; this._timelineSet = timelineSet; // these will be TimelineIndex objects; they delineate the 'start' and // 'end' of the window. // // _start.index is inclusive; _end.index is exclusive. this._start = null; this._end = null; this._eventCount = 0; this._windowLimit = opts.windowLimit || 1000; }
javascript
{ "resource": "" }
q22637
train
function(timeline) { let eventIndex; const events = timeline.getEvents(); if (!initialEventId) { // we were looking for the live timeline: initialise to the end eventIndex = events.length; } else { for (let i = 0; i < events.length; i++) { if (events[i].getId() == initialEventId) { eventIndex = i; break; } } if (eventIndex === undefined) { throw new Error("getEventTimeline result didn't include requested event"); } } const endIndex = Math.min(events.length, eventIndex + Math.ceil(initialWindowSize / 2)); const startIndex = Math.max(0, endIndex - initialWindowSize); self._start = new TimelineIndex(timeline, startIndex - timeline.getBaseIndex()); self._end = new TimelineIndex(timeline, endIndex - timeline.getBaseIndex()); self._eventCount = endIndex - startIndex; }
javascript
{ "resource": "" }
q22638
createOlmSession
train
function createOlmSession(olmAccount, recipientTestClient) { return recipientTestClient.awaitOneTimeKeyUpload().then((keys) => { const otkId = utils.keys(keys)[0]; const otk = keys[otkId]; const session = new global.Olm.Session(); session.create_outbound( olmAccount, recipientTestClient.getDeviceKey(), otk.key, ); return session; }); }
javascript
{ "resource": "" }
q22639
encryptOlmEvent
train
function encryptOlmEvent(opts) { expect(opts.senderKey).toBeTruthy(); expect(opts.p2pSession).toBeTruthy(); expect(opts.recipient).toBeTruthy(); const plaintext = { content: opts.plaincontent || {}, recipient: opts.recipient.userId, recipient_keys: { ed25519: opts.recipient.getSigningKey(), }, sender: opts.sender || '@bob:xyz', type: opts.plaintype || 'm.test', }; const event = { content: { algorithm: 'm.olm.v1.curve25519-aes-sha2', ciphertext: {}, sender_key: opts.senderKey, }, sender: opts.sender || '@bob:xyz', type: 'm.room.encrypted', }; event.content.ciphertext[opts.recipient.getDeviceKey()] = opts.p2pSession.encrypt(JSON.stringify(plaintext)); return event; }
javascript
{ "resource": "" }
q22640
encryptMegolmEvent
train
function encryptMegolmEvent(opts) { expect(opts.senderKey).toBeTruthy(); expect(opts.groupSession).toBeTruthy(); const plaintext = opts.plaintext || {}; if (!plaintext.content) { plaintext.content = { body: '42', msgtype: "m.text", }; } if (!plaintext.type) { plaintext.type = "m.room.message"; } if (!plaintext.room_id) { expect(opts.room_id).toBeTruthy(); plaintext.room_id = opts.room_id; } return { event_id: 'test_megolm_event', content: { algorithm: "m.megolm.v1.aes-sha2", ciphertext: opts.groupSession.encrypt(JSON.stringify(plaintext)), device_id: "testDevice", sender_key: opts.senderKey, session_id: opts.groupSession.session_id(), }, type: "m.room.encrypted", }; }
javascript
{ "resource": "" }
q22641
encryptGroupSessionKey
train
function encryptGroupSessionKey(opts) { return encryptOlmEvent({ senderKey: opts.senderKey, recipient: opts.recipient, p2pSession: opts.p2pSession, plaincontent: { algorithm: 'm.megolm.v1.aes-sha2', room_id: opts.room_id, session_id: opts.groupSession.session_id(), session_key: opts.groupSession.session_key(), }, plaintype: 'm.room_key', }); }
javascript
{ "resource": "" }
q22642
WebStorageSessionStore
train
function WebStorageSessionStore(webStore) { this.store = webStore; if (!utils.isFunction(webStore.getItem) || !utils.isFunction(webStore.setItem) || !utils.isFunction(webStore.removeItem) || !utils.isFunction(webStore.key) || typeof(webStore.length) !== 'number' ) { throw new Error( "Supplied webStore does not meet the WebStorage API interface", ); } }
javascript
{ "resource": "" }
q22643
train
function() { const prefix = keyEndToEndDevicesForUser(''); const devices = {}; for (let i = 0; i < this.store.length; ++i) { const key = this.store.key(i); const userId = key.substr(prefix.length); if (key.startsWith(prefix)) devices[userId] = getJsonItem(this.store, key); } return devices; }
javascript
{ "resource": "" }
q22644
train
function() { const deviceKeys = getKeysWithPrefix(this.store, keyEndToEndSessions('')); const results = {}; for (const k of deviceKeys) { const unprefixedKey = k.substr(keyEndToEndSessions('').length); results[unprefixedKey] = getJsonItem(this.store, k); } return results; }
javascript
{ "resource": "" }
q22645
train
function() { const prefix = E2E_PREFIX + 'inboundgroupsessions/'; const result = []; for (let i = 0; i < this.store.length; i++) { const key = this.store.key(i); if (!key.startsWith(prefix)) { continue; } // we can't use split, as the components we are trying to split out // might themselves contain '/' characters. We rely on the // senderKey being a (32-byte) curve25519 key, base64-encoded // (hence 43 characters long). result.push({ senderKey: key.substr(prefix.length, 43), sessionId: key.substr(prefix.length + 44), }); } return result; }
javascript
{ "resource": "" }
q22646
train
function() { const roomKeys = getKeysWithPrefix(this.store, keyEndToEndRoom('')); const results = {}; for (const k of roomKeys) { const unprefixedKey = k.substr(keyEndToEndRoom('').length); results[unprefixedKey] = getJsonItem(this.store, k); } return results; }
javascript
{ "resource": "" }
q22647
IndexedDBStore
train
function IndexedDBStore(opts) { MemoryStore.call(this, opts); if (!opts.indexedDB) { throw new Error('Missing required option: indexedDB'); } if (opts.workerScript) { // try & find a webworker-compatible API let workerApi = opts.workerApi; if (!workerApi) { // default to the global Worker object (which is where it in a browser) workerApi = global.Worker; } this.backend = new RemoteIndexedDBStoreBackend( opts.workerScript, opts.dbName, workerApi, ); } else { this.backend = new LocalIndexedDBStoreBackend(opts.indexedDB, opts.dbName); } this.startedUp = false; this._syncTs = 0; // Records the last-modified-time of each user at the last point we saved // the database, such that we can derive the set if users that have been // modified since we last saved. this._userModifiedMap = { // user_id : timestamp }; }
javascript
{ "resource": "" }
q22648
degradable
train
function degradable(func, fallback) { return async function(...args) { try { return await func.call(this, ...args); } catch (e) { console.error("IndexedDBStore failure, degrading to MemoryStore", e); this.emit("degraded", e); try { // We try to delete IndexedDB after degrading since this store is only a // cache (the app will still function correctly without the data). // It's possible that deleting repair IndexedDB for the next app load, // potenially by making a little more space available. console.log("IndexedDBStore trying to delete degraded data"); await this.backend.clearDatabase(); console.log("IndexedDBStore delete after degrading succeeeded"); } catch (e) { console.warn("IndexedDBStore delete after degrading failed", e); } // Degrade the store from being an instance of `IndexedDBStore` to instead be // an instance of `MemoryStore` so that future API calls use the memory path // directly and skip IndexedDB entirely. This should be safe as // `IndexedDBStore` already extends from `MemoryStore`, so we are making the // store become its parent type in a way. The mutator methods of // `IndexedDBStore` also maintain the state that `MemoryStore` uses (many are // not overridden at all). Object.setPrototypeOf(this, MemoryStore.prototype); if (fallback) { return await MemoryStore.prototype[fallback].call(this, ...args); } } }; }
javascript
{ "resource": "" }
q22649
MatrixBaseApis
train
function MatrixBaseApis(opts) { utils.checkObjectHasKeys(opts, ["baseUrl", "request"]); this.baseUrl = opts.baseUrl; this.idBaseUrl = opts.idBaseUrl; const httpOpts = { baseUrl: opts.baseUrl, idBaseUrl: opts.idBaseUrl, accessToken: opts.accessToken, request: opts.request, prefix: httpApi.PREFIX_R0, onlyData: true, extraParams: opts.queryParams, localTimeoutMs: opts.localTimeoutMs, useAuthorizationHeader: opts.useAuthorizationHeader, }; this._http = new httpApi.MatrixHttpApi(this, httpOpts); this._txnCtr = 0; }
javascript
{ "resource": "" }
q22650
_scheduleRealCallback
train
function _scheduleRealCallback() { if (_realCallbackKey) { global.clearTimeout(_realCallbackKey); } const first = _callbackList[0]; if (!first) { debuglog("_scheduleRealCallback: no more callbacks, not rescheduling"); return; } const now = _now(); const delayMs = Math.min(first.runAt - now, TIMER_CHECK_PERIOD_MS); debuglog("_scheduleRealCallback: now:", now, "delay:", delayMs); _realCallbackKey = global.setTimeout(_runCallbacks, delayMs); }
javascript
{ "resource": "" }
q22651
Room
train
function Room(roomId, client, myUserId, opts) { opts = opts || {}; opts.pendingEventOrdering = opts.pendingEventOrdering || "chronological"; this.reEmitter = new ReEmitter(this); if (["chronological", "detached"].indexOf(opts.pendingEventOrdering) === -1) { throw new Error( "opts.pendingEventOrdering MUST be either 'chronological' or " + "'detached'. Got: '" + opts.pendingEventOrdering + "'", ); } this.myUserId = myUserId; this.roomId = roomId; this.name = roomId; this.tags = { // $tagName: { $metadata: $value }, // $tagName: { $metadata: $value }, }; this.accountData = { // $eventType: $event }; this.summary = null; this.storageToken = opts.storageToken; this._opts = opts; this._txnToEvent = {}; // Pending in-flight requests { string: MatrixEvent } // receipts should clobber based on receipt_type and user_id pairs hence // the form of this structure. This is sub-optimal for the exposed APIs // which pass in an event ID and get back some receipts, so we also store // a pre-cached list for this purpose. this._receipts = { // receipt_type: { // user_id: { // eventId: <event_id>, // data: <receipt_data> // } // } }; this._receiptCacheByEventId = { // $event_id: [{ // type: $type, // userId: $user_id, // data: <receipt data> // }] }; // only receipts that came from the server, not synthesized ones this._realReceipts = {}; this._notificationCounts = {}; // all our per-room timeline sets. the first one is the unfiltered ones; // the subsequent ones are the filtered ones in no particular order. this._timelineSets = [new EventTimelineSet(this, opts)]; this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), ["Room.timeline", "Room.timelineReset"]); this._fixUpLegacyTimelineFields(); // any filtered timeline sets we're maintaining for this room this._filteredTimelineSets = { // filter_id: timelineSet }; if (this._opts.pendingEventOrdering == "detached") { this._pendingEventList = []; } // read by megolm; boolean value - null indicates "use global value" this._blacklistUnverifiedDevices = null; this._selfMembership = null; this._summaryHeroes = null; // awaited by getEncryptionTargetMembers while room members are loading this._client = client; if (!this._opts.lazyLoadMembers) { this._membersPromise = Promise.resolve(); } else { this._membersPromise = null; } }
javascript
{ "resource": "" }
q22652
calculateRoomName
train
function calculateRoomName(room, userId, ignoreRoomNameEvent) { if (!ignoreRoomNameEvent) { // check for an alias, if any. for now, assume first alias is the // official one. const mRoomName = room.currentState.getStateEvents("m.room.name", ""); if (mRoomName && mRoomName.getContent() && mRoomName.getContent().name) { return mRoomName.getContent().name; } } let alias = room.getCanonicalAlias(); if (!alias) { const aliases = room.getAliases(); if (aliases.length) { alias = aliases[0]; } } if (alias) { return alias; } const joinedMemberCount = room.currentState.getJoinedMemberCount(); const invitedMemberCount = room.currentState.getInvitedMemberCount(); // -1 because these numbers include the syncing user const inviteJoinCount = joinedMemberCount + invitedMemberCount - 1; // get members that are NOT ourselves and are actually in the room. let otherNames = null; if (room._summaryHeroes) { // if we have a summary, the member state events // should be in the room state otherNames = room._summaryHeroes.map((userId) => { const member = room.getMember(userId); return member ? member.name : userId; }); } else { let otherMembers = room.currentState.getMembers().filter((m) => { return m.userId !== userId && (m.membership === "invite" || m.membership === "join"); }); // make sure members have stable order otherMembers.sort((a, b) => a.userId.localeCompare(b.userId)); // only 5 first members, immitate _summaryHeroes otherMembers = otherMembers.slice(0, 5); otherNames = otherMembers.map((m) => m.name); } if (inviteJoinCount) { return memberNamesToRoomName(otherNames, inviteJoinCount); } const myMembership = room.getMyMembership(); // if I have created a room and invited people throuh // 3rd party invites if (myMembership == 'join') { const thirdPartyInvites = room.currentState.getStateEvents("m.room.third_party_invite"); if (thirdPartyInvites && thirdPartyInvites.length) { const thirdPartyNames = thirdPartyInvites.map((i) => { return i.getContent().display_name; }); return `Inviting ${memberNamesToRoomName(thirdPartyNames)}`; } } // let's try to figure out who was here before let leftNames = otherNames; // if we didn't have heroes, try finding them in the room state if(!leftNames.length) { leftNames = room.currentState.getMembers().filter((m) => { return m.userId !== userId && m.membership !== "invite" && m.membership !== "join"; }).map((m) => m.name); } if(leftNames.length) { return `Empty room (was ${memberNamesToRoomName(leftNames)})`; } else { return "Empty room"; } }
javascript
{ "resource": "" }
q22653
InteractiveAuth
train
function InteractiveAuth(opts) { this._matrixClient = opts.matrixClient; this._data = opts.authData || {}; this._requestCallback = opts.doRequest; // startAuthStage included for backwards compat this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage; this._completionDeferred = null; this._inputs = opts.inputs || {}; if (opts.sessionId) this._data.session = opts.sessionId; this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret(); this._emailSid = opts.emailSid; if (this._emailSid === undefined) this._emailSid = null; this._currentStage = null; }
javascript
{ "resource": "" }
q22654
train
function() { this._completionDeferred = Promise.defer(); // wrap in a promise so that if _startNextAuthStage // throws, it rejects the promise in a consistent way return Promise.resolve().then(() => { // if we have no flows, try a request (we'll have // just a session ID in _data if resuming) if (!this._data.flows) { this._doRequest(this._data); } else { this._startNextAuthStage(); } return this._completionDeferred.promise; }); }
javascript
{ "resource": "" }
q22655
train
function() { if (!this._data.session) return; let authDict = {}; if (this._currentStage == EMAIL_STAGE_TYPE) { // The email can be validated out-of-band, but we need to provide the // creds so the HS can go & check it. if (this._emailSid) { const idServerParsedUrl = url.parse( this._matrixClient.getIdentityServerUrl(), ); authDict = { type: EMAIL_STAGE_TYPE, threepid_creds: { sid: this._emailSid, client_secret: this._clientSecret, id_server: idServerParsedUrl.host, }, }; } } this.submitAuthDict(authDict, true); }
javascript
{ "resource": "" }
q22656
train
function(loginType) { let params = {}; if (this._data && this._data.params) { params = this._data.params; } return params[loginType]; }
javascript
{ "resource": "" }
q22657
train
function(auth, background) { const self = this; // hackery to make sure that synchronous exceptions end up in the catch // handler (without the additional event loop entailed by q.fcall or an // extra Promise.resolve().then) let prom; try { prom = this._requestCallback(auth, background); } catch (e) { prom = Promise.reject(e); } prom = prom.then( function(result) { console.log("result from request: ", result); self._completionDeferred.resolve(result); }, function(error) { // sometimes UI auth errors don't come with flows const errorFlows = error.data ? error.data.flows : null; const haveFlows = Boolean(self._data.flows) || Boolean(errorFlows); if (error.httpStatus !== 401 || !error.data || !haveFlows) { // doesn't look like an interactive-auth failure. fail the whole lot. throw error; } // if the error didn't come with flows, completed flows or session ID, // copy over the ones we have. Synapse sometimes sends responses without // any UI auth data (eg. when polling for email validation, if the email // has not yet been validated). This appears to be a Synapse bug, which // we workaround here. if (!error.data.flows && !error.data.completed && !error.data.session) { error.data.flows = self._data.flows; error.data.completed = self._data.completed; error.data.session = self._data.session; } self._data = error.data; self._startNextAuthStage(); }, ); if (!background) { prom = prom.catch((e) => { this._completionDeferred.reject(e); }); } else { // We ignore all failures here (even non-UI auth related ones) // since we don't want to suddenly fail if the internet connection // had a blip whilst we were polling prom = prom.catch((error) => { console.log("Ignoring error from UI auth: " + error); }); } prom.done(); }
javascript
{ "resource": "" }
q22658
train
function() { const nextStage = this._chooseStage(); if (!nextStage) { throw new Error("No incomplete flows from the server"); } this._currentStage = nextStage; if (nextStage == 'm.login.dummy') { this.submitAuthDict({ type: 'm.login.dummy', }); return; } if (this._data.errcode || this._data.error) { this._stateUpdatedCallback(nextStage, { errcode: this._data.errcode || "", error: this._data.error || "", }); return; } const stageStatus = {}; if (nextStage == EMAIL_STAGE_TYPE) { stageStatus.emailSid = this._emailSid; } this._stateUpdatedCallback(nextStage, stageStatus); }
javascript
{ "resource": "" }
q22659
train
function() { const flow = this._chooseFlow(); console.log("Active flow => %s", JSON.stringify(flow)); const nextStage = this._firstUncompletedStage(flow); console.log("Next stage: %s", nextStage); return nextStage; }
javascript
{ "resource": "" }
q22660
train
function() { const flows = this._data.flows || []; // we've been given an email or we've already done an email part const haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid); const haveMsisdn = ( Boolean(this._inputs.phoneCountry) && Boolean(this._inputs.phoneNumber) ); for (const flow of flows) { let flowHasEmail = false; let flowHasMsisdn = false; for (const stage of flow.stages) { if (stage === EMAIL_STAGE_TYPE) { flowHasEmail = true; } else if (stage == MSISDN_STAGE_TYPE) { flowHasMsisdn = true; } } if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) { return flow; } } // Throw an error with a fairly generic description, but with more // information such that the app can give a better one if so desired. const err = new Error("No appropriate authentication flow found"); err.name = 'NoAuthFlowFoundError'; err.required_stages = []; if (haveEmail) err.required_stages.push(EMAIL_STAGE_TYPE); if (haveMsisdn) err.required_stages.push(MSISDN_STAGE_TYPE); err.available_flows = flows; throw err; }
javascript
{ "resource": "" }
q22661
train
function(flow) { const completed = (this._data || {}).completed || []; for (let i = 0; i < flow.stages.length; ++i) { const stageType = flow.stages[i]; if (completed.indexOf(stageType) === -1) { return stageType; } } }
javascript
{ "resource": "" }
q22662
RoomMember
train
function RoomMember(roomId, userId) { this.roomId = roomId; this.userId = userId; this.typing = false; this.name = userId; this.rawDisplayName = userId; this.powerLevel = 0; this.powerLevelNorm = 0; this.user = null; this.membership = null; this.events = { member: null, }; this._isOutOfBand = false; this._updateModifiedTime(); }
javascript
{ "resource": "" }
q22663
RoomState
train
function RoomState(roomId, oobMemberFlags = undefined) { this.roomId = roomId; this.members = { // userId: RoomMember }; this.events = { // eventType: { stateKey: MatrixEvent } }; this.paginationToken = null; this._sentinels = { // userId: RoomMember }; this._updateModifiedTime(); // stores fuzzy matches to a list of userIDs (applies utils.removeHiddenChars to keys) this._displayNameToUserIds = {}; this._userIdsToDisplayNames = {}; this._tokenToInvite = {}; // 3pid invite state_key to m.room.member invite this._joinedMemberCount = null; // cache of the number of joined members // joined members count from summary api // once set, we know the server supports the summary api // and we should only trust that // we could also only trust that before OOB members // are loaded but doesn't seem worth the hassle atm this._summaryJoinedMemberCount = null; // same for invited member count this._invitedMemberCount = null; this._summaryInvitedMemberCount = null; if (!oobMemberFlags) { oobMemberFlags = { status: OOB_STATUS_NOTSTARTED, }; } this._oobMemberFlags = oobMemberFlags; }
javascript
{ "resource": "" }
q22664
OlmEncryption
train
function OlmEncryption(params) { base.EncryptionAlgorithm.call(this, params); this._sessionPrepared = false; this._prepPromise = null; }
javascript
{ "resource": "" }
q22665
expectAliQueryKeys
train
function expectAliQueryKeys() { // can't query keys before bob has uploaded them expect(bobTestClient.deviceKeys).toBeTruthy(); const bobKeys = {}; bobKeys[bobDeviceId] = bobTestClient.deviceKeys; aliTestClient.httpBackend.when("POST", "/keys/query") .respond(200, function(path, content) { expect(content.device_keys[bobUserId]).toEqual( {}, "Expected Alice to key query for " + bobUserId + ", got " + Object.keys(content.device_keys), ); const result = {}; result[bobUserId] = bobKeys; return {device_keys: result}; }); return aliTestClient.httpBackend.flush("/keys/query", 1); }
javascript
{ "resource": "" }
q22666
expectBobQueryKeys
train
function expectBobQueryKeys() { // can't query keys before ali has uploaded them expect(aliTestClient.deviceKeys).toBeTruthy(); const aliKeys = {}; aliKeys[aliDeviceId] = aliTestClient.deviceKeys; console.log("query result will be", aliKeys); bobTestClient.httpBackend.when( "POST", "/keys/query", ).respond(200, function(path, content) { expect(content.device_keys[aliUserId]).toEqual( {}, "Expected Bob to key query for " + aliUserId + ", got " + Object.keys(content.device_keys), ); const result = {}; result[aliUserId] = aliKeys; return {device_keys: result}; }); return bobTestClient.httpBackend.flush("/keys/query", 1); }
javascript
{ "resource": "" }
q22667
expectAliClaimKeys
train
function expectAliClaimKeys() { return bobTestClient.awaitOneTimeKeyUpload().then((keys) => { aliTestClient.httpBackend.when( "POST", "/keys/claim", ).respond(200, function(path, content) { const claimType = content.one_time_keys[bobUserId][bobDeviceId]; expect(claimType).toEqual("signed_curve25519"); let keyId = null; for (keyId in keys) { if (bobTestClient.oneTimeKeys.hasOwnProperty(keyId)) { if (keyId.indexOf(claimType + ":") === 0) { break; } } } const result = {}; result[bobUserId] = {}; result[bobUserId][bobDeviceId] = {}; result[bobUserId][bobDeviceId][keyId] = keys[keyId]; return {one_time_keys: result}; }); }).then(() => { // it can take a while to process the key query, so give it some extra // time, and make sure the claim actually happens rather than ploughing on // confusingly. return aliTestClient.httpBackend.flush("/keys/claim", 1, 500).then((r) => { expect(r).toEqual(1, "Ali did not claim Bob's keys"); }); }); }
javascript
{ "resource": "" }
q22668
aliSendsFirstMessage
train
function aliSendsFirstMessage() { return Promise.all([ sendMessage(aliTestClient.client), expectAliQueryKeys() .then(expectAliClaimKeys) .then(expectAliSendMessageRequest), ]).spread(function(_, ciphertext) { return ciphertext; }); }
javascript
{ "resource": "" }
q22669
aliSendsMessage
train
function aliSendsMessage() { return Promise.all([ sendMessage(aliTestClient.client), expectAliSendMessageRequest(), ]).spread(function(_, ciphertext) { return ciphertext; }); }
javascript
{ "resource": "" }
q22670
expectAliSendMessageRequest
train
function expectAliSendMessageRequest() { return expectSendMessageRequest(aliTestClient.httpBackend).then(function(content) { aliMessages.push(content); expect(utils.keys(content.ciphertext)).toEqual([bobTestClient.getDeviceKey()]); const ciphertext = content.ciphertext[bobTestClient.getDeviceKey()]; expect(ciphertext).toBeTruthy(); return ciphertext; }); }
javascript
{ "resource": "" }
q22671
expectBobSendMessageRequest
train
function expectBobSendMessageRequest() { return expectSendMessageRequest(bobTestClient.httpBackend).then(function(content) { bobMessages.push(content); const aliKeyId = "curve25519:" + aliDeviceId; const aliDeviceCurve25519Key = aliTestClient.deviceKeys.keys[aliKeyId]; expect(utils.keys(content.ciphertext)).toEqual([aliDeviceCurve25519Key]); const ciphertext = content.ciphertext[aliDeviceCurve25519Key]; expect(ciphertext).toBeTruthy(); return ciphertext; }); }
javascript
{ "resource": "" }
q22672
OlmDevice
train
function OlmDevice(cryptoStore) { this._cryptoStore = cryptoStore; this._pickleKey = "DEFAULT_KEY"; // don't know these until we load the account from storage in init() this.deviceCurve25519Key = null; this.deviceEd25519Key = null; this._maxOneTimeKeys = null; // we don't bother stashing outboundgroupsessions in the cryptoStore - // instead we keep them here. this._outboundGroupSessionStore = {}; // Store a set of decrypted message indexes for each group session. // This partially mitigates a replay attack where a MITM resends a group // message into the room. // // When we decrypt a message and the message index matches a previously // decrypted message, one possible cause of that is that we are decrypting // the same event, and may not indicate an actual replay attack. For // example, this could happen if we receive events, forget about them, and // then re-fetch them when we backfill. So we store the event ID and // timestamp corresponding to each message index when we first decrypt it, // and compare these against the event ID and timestamp every time we use // that same index. If they match, then we're probably decrypting the same // event and we don't consider it a replay attack. // // Keys are strings of form "<senderKey>|<session_id>|<message_index>" // Values are objects of the form "{id: <event id>, timestamp: <ts>}" this._inboundGroupSessionMessageIndexes = {}; // Keep track of sessions that we're starting, so that we don't start // multiple sessions for the same device at the same time. this._sessionsInProgress = {}; }
javascript
{ "resource": "" }
q22673
MegolmEncryption
train
function MegolmEncryption(params) { base.EncryptionAlgorithm.call(this, params); // the most recent attempt to set up a session. This is used to serialise // the session setups, so that we have a race-free view of which session we // are using, and which devices we have shared the keys with. It resolves // with an OutboundSessionInfo (or undefined, for the first message in the // room). this._setupPromise = Promise.resolve(); // Map of outbound sessions by sessions ID. Used if we need a particular // session (the session we're currently using to send is always obtained // using _setupPromise). this._outboundSessions = {}; // default rotation periods this._sessionRotationPeriodMsgs = 100; this._sessionRotationPeriodMs = 7 * 24 * 3600 * 1000; if (params.config.rotation_period_ms !== undefined) { this._sessionRotationPeriodMs = params.config.rotation_period_ms; } if (params.config.rotation_period_msgs !== undefined) { this._sessionRotationPeriodMsgs = params.config.rotation_period_msgs; } }
javascript
{ "resource": "" }
q22674
Group
train
function Group(groupId) { this.groupId = groupId; this.name = null; this.avatarUrl = null; this.myMembership = null; this.inviter = null; }
javascript
{ "resource": "" }
q22675
User
train
function User(userId) { this.userId = userId; this.presence = "offline"; this.presenceStatusMsg = null; this._unstable_statusMessage = ""; this.displayName = userId; this.rawDisplayName = userId; this.avatarUrl = null; this.lastActiveAgo = 0; this.lastPresenceTs = 0; this.currentlyActive = false; this.events = { presence: null, profile: null, }; this._updateModifiedTime(); }
javascript
{ "resource": "" }
q22676
FilterComponent
train
function FilterComponent(filter_json) { this.filter_json = filter_json; this.types = filter_json.types || null; this.not_types = filter_json.not_types || []; this.rooms = filter_json.rooms || null; this.not_rooms = filter_json.not_rooms || []; this.senders = filter_json.senders || null; this.not_senders = filter_json.not_senders || []; this.contains_url = filter_json.contains_url || null; }
javascript
{ "resource": "" }
q22677
train
function() { const params = { access_token: this.opts.accessToken, }; return { base: this.opts.baseUrl, path: "/_matrix/media/v1/upload", params: params, }; }
javascript
{ "resource": "" }
q22678
train
function(path, queryParams, prefix) { let queryString = ""; if (queryParams) { queryString = "?" + utils.encodeParams(queryParams); } return this.opts.baseUrl + prefix + path + queryString; }
javascript
{ "resource": "" }
q22679
parseErrorResponse
train
function parseErrorResponse(response, body) { const httpStatus = response.statusCode; const contentType = getResponseContentType(response); let err; if (contentType) { if (contentType.type === 'application/json') { err = new module.exports.MatrixError(JSON.parse(body)); } else if (contentType.type === 'text/plain') { err = new Error(`Server returned ${httpStatus} error: ${body}`); } } if (!err) { err = new Error(`Server returned ${httpStatus} error`); } err.httpStatus = httpStatus; return err; }
javascript
{ "resource": "" }
q22680
keysFromRecoverySession
train
function keysFromRecoverySession(sessions, decryptionKey, roomId) { const keys = []; for (const [sessionId, sessionData] of Object.entries(sessions)) { try { const decrypted = keyFromRecoverySession(sessionData, decryptionKey); decrypted.session_id = sessionId; decrypted.room_id = roomId; keys.push(decrypted); } catch (e) { console.log("Failed to decrypt session from backup"); } } return keys; }
javascript
{ "resource": "" }
q22681
_encryptEventIfNeeded
train
function _encryptEventIfNeeded(client, event, room) { if (event.isEncrypted()) { // this event has already been encrypted; this happens if the // encryption step succeeded, but the send step failed on the first // attempt. return null; } if (!client.isRoomEncrypted(event.getRoomId())) { // looks like this room isn't encrypted. return null; } if (!client._crypto) { throw new Error( "This room is configured to use encryption, but your client does " + "not support encryption.", ); } return client._crypto.encryptEvent(event, room); }
javascript
{ "resource": "" }
q22682
_maybeUploadOneTimeKeys
train
function _maybeUploadOneTimeKeys(crypto) { // frequency with which to check & upload one-time keys const uploadPeriod = 1000 * 60; // one minute // max number of keys to upload at once // Creating keys can be an expensive operation so we limit the // number we generate in one go to avoid blocking the application // for too long. const maxKeysPerCycle = 5; if (crypto._oneTimeKeyCheckInProgress) { return; } const now = Date.now(); if (crypto._lastOneTimeKeyCheck !== null && now - crypto._lastOneTimeKeyCheck < uploadPeriod ) { // we've done a key upload recently. return; } crypto._lastOneTimeKeyCheck = now; // We need to keep a pool of one time public keys on the server so that // other devices can start conversations with us. But we can only store // a finite number of private keys in the olm Account object. // To complicate things further then can be a delay between a device // claiming a public one time key from the server and it sending us a // message. We need to keep the corresponding private key locally until // we receive the message. // But that message might never arrive leaving us stuck with duff // private keys clogging up our local storage. // So we need some kind of enginering compromise to balance all of // these factors. // Check how many keys we can store in the Account object. const maxOneTimeKeys = crypto._olmDevice.maxNumberOfOneTimeKeys(); // Try to keep at most half that number on the server. This leaves the // rest of the slots free to hold keys that have been claimed from the // server but we haven't recevied a message for. // If we run out of slots when generating new keys then olm will // discard the oldest private keys first. This will eventually clean // out stale private keys that won't receive a message. const keyLimit = Math.floor(maxOneTimeKeys / 2); function uploadLoop(keyCount) { if (keyLimit <= keyCount) { // If we don't need to generate any more keys then we are done. return Promise.resolve(); } const keysThisLoop = Math.min(keyLimit - keyCount, maxKeysPerCycle); // Ask olm to generate new one time keys, then upload them to synapse. return crypto._olmDevice.generateOneTimeKeys(keysThisLoop).then(() => { return _uploadOneTimeKeys(crypto); }).then((res) => { if (res.one_time_key_counts && res.one_time_key_counts.signed_curve25519) { // if the response contains a more up to date value use this // for the next loop return uploadLoop(res.one_time_key_counts.signed_curve25519); } else { throw new Error("response for uploading keys does not contain " + "one_time_key_counts.signed_curve25519"); } }); } crypto._oneTimeKeyCheckInProgress = true; Promise.resolve().then(() => { if (crypto._oneTimeKeyCount !== undefined) { // We already have the current one_time_key count from a /sync response. // Use this value instead of asking the server for the current key count. return Promise.resolve(crypto._oneTimeKeyCount); } // ask the server how many keys we have return crypto._baseApis.uploadKeysRequest({}, { device_id: crypto._deviceId, }).then((res) => { return res.one_time_key_counts.signed_curve25519 || 0; }); }).then((keyCount) => { // Start the uploadLoop with the current keyCount. The function checks if // we need to upload new keys or not. // If there are too many keys on the server then we don't need to // create any more keys. return uploadLoop(keyCount); }).catch((e) => { logger.error("Error uploading one-time keys", e.stack || e); }).finally(() => { // reset _oneTimeKeyCount to prevent start uploading based on old data. // it will be set again on the next /sync-response crypto._oneTimeKeyCount = undefined; crypto._oneTimeKeyCheckInProgress = false; }).done(); }
javascript
{ "resource": "" }
q22683
_uploadOneTimeKeys
train
async function _uploadOneTimeKeys(crypto) { const oneTimeKeys = await crypto._olmDevice.getOneTimeKeys(); const oneTimeJson = {}; const promises = []; for (const keyId in oneTimeKeys.curve25519) { if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) { const k = { key: oneTimeKeys.curve25519[keyId], }; oneTimeJson["signed_curve25519:" + keyId] = k; promises.push(crypto._signObject(k)); } } await Promise.all(promises); const res = await crypto._baseApis.uploadKeysRequest({ one_time_keys: oneTimeJson, }, { // for now, we set the device id explicitly, as we may not be using the // same one as used in login. device_id: crypto._deviceId, }); await crypto._olmDevice.markKeysAsPublished(); return res; }
javascript
{ "resource": "" }
q22684
EventTimelineSet
train
function EventTimelineSet(room, opts) { this.room = room; this._timelineSupport = Boolean(opts.timelineSupport); this._liveTimeline = new EventTimeline(this); // just a list - *not* ordered. this._timelines = [this._liveTimeline]; this._eventIdToTimeline = {}; this._filter = opts.filter || null; }
javascript
{ "resource": "" }
q22685
train
async function(crypto) { // start with a couple of sanity checks. if (!this.isEncrypted()) { throw new Error("Attempt to decrypt event which isn't encrypted"); } if ( this._clearEvent && this._clearEvent.content && this._clearEvent.content.msgtype !== "m.bad.encrypted" ) { // we may want to just ignore this? let's start with rejecting it. throw new Error( "Attempt to decrypt event which has already been encrypted", ); } // if we already have a decryption attempt in progress, then it may // fail because it was using outdated info. We now have reason to // succeed where it failed before, but we don't want to have multiple // attempts going at the same time, so just set a flag that says we have // new info. // if (this._decryptionPromise) { console.log( `Event ${this.getId()} already being decrypted; queueing a retry`, ); this._retryDecryption = true; return this._decryptionPromise; } this._decryptionPromise = this._decryptionLoop(crypto); return this._decryptionPromise; }
javascript
{ "resource": "" }
q22686
train
function(crypto, userId) { const wireContent = this.getWireContent(); return crypto.requestRoomKey({ algorithm: wireContent.algorithm, room_id: this.getRoomId(), session_id: wireContent.session_id, sender_key: wireContent.sender_key, }, this.getKeyRequestRecipients(userId), true); }
javascript
{ "resource": "" }
q22687
train
function(userId) { // send the request to all of our own devices, and the // original sending device if it wasn't us. const wireContent = this.getWireContent(); const recipients = [{ userId, deviceId: '*', }]; const sender = this.getSender(); if (sender !== userId) { recipients.push({ userId: sender, deviceId: wireContent.device_id, }); } return recipients; }
javascript
{ "resource": "" }
q22688
train
function(decryptionResult) { this._clearEvent = decryptionResult.clearEvent; this._senderCurve25519Key = decryptionResult.senderCurve25519Key || null; this._claimedEd25519Key = decryptionResult.claimedEd25519Key || null; this._forwardingCurve25519KeyChain = decryptionResult.forwardingCurve25519KeyChain || []; }
javascript
{ "resource": "" }
q22689
train
function(redaction_event) { // quick sanity-check if (!redaction_event.event) { throw new Error("invalid redaction_event in makeRedacted"); } // we attempt to replicate what we would see from the server if // the event had been redacted before we saw it. // // The server removes (most of) the content of the event, and adds a // "redacted_because" key to the unsigned section containing the // redacted event. if (!this.event.unsigned) { this.event.unsigned = {}; } this.event.unsigned.redacted_because = redaction_event.event; let key; for (key in this.event) { if (!this.event.hasOwnProperty(key)) { continue; } if (!_REDACT_KEEP_KEY_MAP[key]) { delete this.event[key]; } } const keeps = _REDACT_KEEP_CONTENT_MAP[this.getType()] || {}; const content = this.getContent(); for (key in content) { if (!content.hasOwnProperty(key)) { continue; } if (!keeps[key]) { delete content[key]; } } }
javascript
{ "resource": "" }
q22690
EventTimeline
train
function EventTimeline(eventTimelineSet) { this._eventTimelineSet = eventTimelineSet; this._roomId = eventTimelineSet.room ? eventTimelineSet.room.roomId : null; this._events = []; this._baseIndex = 0; this._startState = new RoomState(this._roomId); this._startState.paginationToken = null; this._endState = new RoomState(this._roomId); this._endState.paginationToken = null; this._prevTimeline = null; this._nextTimeline = null; // this is used by client.js this._paginationRequests = {'b': null, 'f': null}; this._name = this._roomId + ":" + new Date().toISOString(); }
javascript
{ "resource": "" }
q22691
train
function(baseUrl, mxc, width, height, resizeMethod, allowDirectLinks) { if (typeof mxc !== "string" || !mxc) { return ''; } if (mxc.indexOf("mxc://") !== 0) { if (allowDirectLinks) { return mxc; } else { return ''; } } let serverAndMediaId = mxc.slice(6); // strips mxc:// let prefix = "/_matrix/media/v1/download/"; const params = {}; if (width) { params.width = width; } if (height) { params.height = height; } if (resizeMethod) { params.method = resizeMethod; } if (utils.keys(params).length > 0) { // these are thumbnailing params so they probably want the // thumbnailing API... prefix = "/_matrix/media/v1/thumbnail/"; } const fragmentOffset = serverAndMediaId.indexOf("#"); let fragment = ""; if (fragmentOffset >= 0) { fragment = serverAndMediaId.substr(fragmentOffset); serverAndMediaId = serverAndMediaId.substr(0, fragmentOffset); } return baseUrl + prefix + serverAndMediaId + (utils.keys(params).length === 0 ? "" : ("?" + utils.encodeParams(params))) + fragment; }
javascript
{ "resource": "" }
q22692
train
function(baseUrl, identiconString, width, height) { if (!identiconString) { return null; } if (!width) { width = 96; } if (!height) { height = 96; } const params = { width: width, height: height, }; const path = utils.encodeUri("/_matrix/media/v1/identicon/$ident", { $ident: identiconString, }); return baseUrl + path + (utils.keys(params).length === 0 ? "" : ("?" + utils.encodeParams(params))); }
javascript
{ "resource": "" }
q22693
train
function(room) { this.rooms[room.roomId] = room; // add listeners for room member changes so we can keep the room member // map up-to-date. room.currentState.on("RoomState.members", this._onRoomMember.bind(this)); // add existing members const self = this; room.currentState.getMembers().forEach(function(m) { self._onRoomMember(null, room.currentState, m); }); }
javascript
{ "resource": "" }
q22694
train
function(event, state, member) { if (member.membership === "invite") { // We do NOT add invited members because people love to typo user IDs // which would then show up in these lists (!) return; } const user = this.users[member.userId] || new User(member.userId); if (member.name) { user.setDisplayName(member.name); if (member.events.member) { user.setRawDisplayName( member.events.member.getDirectionalContent().displayname, ); } } if (member.events.member && member.events.member.getContent().avatar_url) { user.setAvatarUrl(member.events.member.getContent().avatar_url); } this.users[user.userId] = user; }
javascript
{ "resource": "" }
q22695
train
function(filter) { if (!filter) { return; } if (!this.filters[filter.userId]) { this.filters[filter.userId] = {}; } this.filters[filter.userId][filter.filterId] = filter; }
javascript
{ "resource": "" }
q22696
train
function(userId, filterId) { if (!this.filters[userId] || !this.filters[userId][filterId]) { return null; } return this.filters[userId][filterId]; }
javascript
{ "resource": "" }
q22697
train
function(events) { const self = this; events.forEach(function(event) { self.accountData[event.getType()] = event; }); }
javascript
{ "resource": "" }
q22698
startClient
train
function startClient(httpBackend, client) { httpBackend.when("GET", "/pushrules").respond(200, {}); httpBackend.when("POST", "/filter").respond(200, { filter_id: "fid" }); httpBackend.when("GET", "/sync").respond(200, INITIAL_SYNC_DATA); client.startClient(); // set up a promise which will resolve once the client is initialised const deferred = Promise.defer(); client.on("sync", function(state) { console.log("sync", state); if (state != "SYNCING") { return; } deferred.resolve(); }); return Promise.all([ httpBackend.flushAllExpected(), deferred.promise, ]); }
javascript
{ "resource": "" }
q22699
selectQuery
train
function selectQuery(store, keyRange, resultMapper) { const query = store.openCursor(keyRange); return new Promise((resolve, reject) => { const results = []; query.onerror = (event) => { reject(new Error("Query failed: " + event.target.errorCode)); }; // collect results query.onsuccess = (event) => { const cursor = event.target.result; if (!cursor) { resolve(results); return; // end of results } results.push(resultMapper(cursor)); cursor.continue(); }; }); }
javascript
{ "resource": "" }