diff --git a/electron_app/src/electron-main.js b/electron_app/src/electron-main.js index b8201070a0..7b854a3657 100644 --- a/electron_app/src/electron-main.js +++ b/electron_app/src/electron-main.js @@ -32,6 +32,7 @@ const tray = require('./tray'); const vectorMenu = require('./vectormenu'); const webContentsHandler = require('./webcontents-handler'); const updater = require('./updater'); +const { migrateFromOldOrigin } = require('./originMigrator'); const windowStateKeeper = require('electron-window-state'); @@ -110,7 +111,7 @@ autoUpdater.on('update-downloaded', (ev, releaseNotes, releaseName, releaseDate, }); }); -ipcMain.on('ipcCall', function(ev, payload) { +ipcMain.on('ipcCall', async function(ev, payload) { if (!mainWindow) return; const args = payload.args || []; @@ -141,10 +142,13 @@ ipcMain.on('ipcCall', function(ev, payload) { } else { mainWindow.focus(); } + case 'origin_migrate': + await migrateFromOldOrigin(); + break; default: mainWindow.webContents.send('ipcReply', { id: payload.id, - error: new Error("Unknown IPC Call: "+payload.name), + error: "Unknown IPC Call: " + payload.name, }); return; } @@ -210,19 +214,42 @@ app.on('ready', () => { } const target = parsedUrl.pathname.split('/'); + + // path starts with a '/' + if (target[0] !== '') { + callback({error: -6}); // FILE_NOT_FOUND + return; + } + if (target[target.length - 1] == '') { target[target.length - 1] = 'index.html'; } + let baseDir; + // first part of the path determines where we serve from + if (target[1] === 'origin_migrator_dest') { + // the origin migrator destination page + // (only the destination script needs to come from the + // custom protocol: the source part is loaded from a + // file:// as that's the origin we're migrating from). + baseDir = __dirname + "/../../origin_migrator/dest"; + } else if (target[1] === 'webapp') { + baseDir = __dirname + "/../../webapp"; + } else { + callback({error: -6}); // FILE_NOT_FOUND + return; + } + // Normalise the base dir and the target path separately, then make sure // the target path isn't trying to back out beyond its root - const appBaseDir = path.normalize(__dirname + "/../../webapp"); - const relTarget = path.normalize(path.join(...target)); + baseDir = path.normalize(baseDir); + + const relTarget = path.normalize(path.join(...target.slice(2))); if (relTarget.startsWith('..')) { callback({error: -6}); // FILE_NOT_FOUND return; } - const absTarget = path.join(appBaseDir, relTarget); + const absTarget = path.join(baseDir, relTarget); callback({ path: absTarget, @@ -231,8 +258,6 @@ app.on('ready', () => { if (error) console.error('Failed to register protocol') }); - - if (vectorConfig['update_base_url']) { console.log(`Starting auto update with base URL: ${vectorConfig['update_base_url']}`); updater.start(vectorConfig['update_base_url']); @@ -271,7 +296,7 @@ app.on('ready', () => { webgl: false, }, }); - mainWindow.loadURL('vector://vector/'); + mainWindow.loadURL('vector://vector/webapp/'); Menu.setApplicationMenu(vectorMenu); // explicitly hide because setApplicationMenu on Linux otherwise shows... diff --git a/electron_app/src/originMigrator.js b/electron_app/src/originMigrator.js new file mode 100644 index 0000000000..58bb0feb99 --- /dev/null +++ b/electron_app/src/originMigrator.js @@ -0,0 +1,62 @@ +/* +Copyright 2018 New Vector Ltd + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +const { BrowserWindow, ipcMain } = require('electron'); +const path = require('path'); + +async function migrateFromOldOrigin() { + console.log("Attempting to migrate data between origins"); + + // We can use the same preload script: we just need ipcRenderer exposed + const preloadScript = path.normalize(`${__dirname}/preload.js`); + await new Promise(resolve => { + const migrateWindow = new BrowserWindow({ + show: false, + webPreferences: { + preload: preloadScript, + nodeIntegration: false, + sandbox: true, + enableRemoteModule: false, + webgl: false, + }, + }); + ipcMain.on('origin_migration_complete', (e, success, sentSummary, storedSummary) => { + if (success) { + console.log("Origin migration completed successfully!"); + } else { + console.error("Origin migration failed!"); + } + console.error("Data sent", sentSummary); + console.error("Data stored", storedSummary); + migrateWindow.close(); + resolve(); + }); + ipcMain.on('origin_migration_nodata', (e) => { + console.log("No session to migrate from old origin"); + migrateWindow.close(); + resolve(); + }); + // Normalise the path because in the distribution, __dirname will be inside the + // electron asar. + const sourcePagePath = path.normalize(__dirname + '/../../origin_migrator/source.html'); + console.log("Loading path: " + sourcePagePath); + migrateWindow.loadURL('file://' + sourcePagePath); + }); +} + +module.exports = { + migrateFromOldOrigin, +}; diff --git a/origin_migrator/dest/browser-matrix.min.js b/origin_migrator/dest/browser-matrix.min.js new file mode 100644 index 0000000000..131dc4afcb --- /dev/null +++ b/origin_migrator/dest/browser-matrix.min.js @@ -0,0 +1,19 @@ +!function(){function e(t,r,n){function o(s,a){if(!r[s]){if(!t[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=r[s]={exports:{}};t[s][0].call(l.exports,function(e){return o(t[s][1][e]||e)},l,l.exports,e,t,r,n)}return r[s].exports}for(var i="function"==typeof require&&require,s=0;s1?r-1:0),o=1;o0&&void 0!==arguments[0]&&arguments[0]&&(this.idBaseUrl.startsWith("http://")||this.idBaseUrl.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl},o.prototype.getAccessToken=function(){return this._http.opts.accessToken||null},o.prototype.isLoggedIn=function(){return void 0!==this._http.opts.accessToken},o.prototype.makeTxnId=function(){return"m"+(new Date).getTime()+"."+this._txnCtr++},o.prototype.isUsernameAvailable=function(e){return this._http.authedRequest(void 0,"GET","/register/available",{username:e}).then(function(e){return e.available})},o.prototype.register=function(e,t,r,n,o,i,s){!0===o?o={email:!0}:null!==o&&void 0!==o||(o={}),void 0!==n&&null!==n||(n={}),r&&(n.session=r);var a={auth:n};return void 0!==e&&null!==e&&(a.username=e),void 0!==t&&null!==t&&(a.password=t),o.email&&(a.bind_email=!0),o.msisdn&&(a.bind_msisdn=!0),void 0!==i&&null!==i&&(a.guest_access_token=i),void 0!==t&&null!==t&&(a.x_show_msisdn=!0),this.registerRequest(a,void 0,s)},o.prototype.registerGuest=function(e,t){return e=e||{},e.body=e.body||{},this.registerRequest(e.body,"guest",t)},o.prototype.registerRequest=function(e,t,r){var n={};return t&&(n.kind=t),this._http.request(r,"POST","/register",n,e)},o.prototype.loginFlows=function(e){return this._http.request(e,"GET","/login")},o.prototype.login=function(e,t,r){var n=this,o={type:e};return l.extend(o,t),this._http.authedRequest(function(t,o){"m.login.password"===e&&o&&o.access_token&&o.user_id&&(n._http.opts.accessToken=o.access_token,n.credentials={userId:o.user_id}),r&&r(t,o)},"POST","/login",void 0,o)},o.prototype.loginWithPassword=function(e,t,r){return this.login("m.login.password",{user:e,password:t},r)},o.prototype.loginWithSAML2=function(e,t){return this.login("m.login.saml2",{relay_state:e},t)},o.prototype.getCasLoginUrl=function(e){return this.getSsoLoginUrl(e,"cas")},o.prototype.getSsoLoginUrl=function(e,t){return void 0===t&&(t="sso"),this._http.getUrl("/login/"+t+"/redirect",{redirectUrl:e},c.PREFIX_R0)},o.prototype.loginWithToken=function(e,t){return this.login("m.login.token",{token:e},t)},o.prototype.logout=function(e){return this._http.authedRequest(e,"POST","/logout")},o.prototype.deactivateAccount=function(e,t){if("function"==typeof t)throw new Error("deactivateAccount no longer accepts a callback parameter");var r={};return e&&(r.auth=e),void 0!==t&&(r.erase=t),this._http.authedRequestWithPrefix(void 0,"POST","/account/deactivate",void 0,r,c.PREFIX_R0)},o.prototype.getFallbackAuthUrl=function(e,t){var r=l.encodeUri("/auth/$loginType/fallback/web",{$loginType:e});return this._http.getUrl(r,{session:t},c.PREFIX_R0)},o.prototype.createRoom=function(e,t){return this._http.authedRequest(t,"POST","/createRoom",void 0,e)},o.prototype.roomState=function(e,t){var r=l.encodeUri("/rooms/$roomId/state",{$roomId:e});return this._http.authedRequest(t,"GET",r)},o.prototype.fetchRoomEvent=function(e,t,r){var n=l.encodeUri("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this._http.authedRequest(r,"GET",n)},o.prototype.members=function(e,t,r,n,o){var i={};t&&(i.membership=t),r&&(i.not_membership=r),n&&(i.at=n);var s=l.encodeParams(i),a=l.encodeUri("/rooms/$roomId/members?"+s,{$roomId:e});return this._http.authedRequest(o,"GET",a)},o.prototype.upgradeRoom=function(e,t){var r=l.encodeUri("/rooms/$roomId/upgrade",{$roomId:e});return this._http.authedRequest(void 0,"POST",r,void 0,{new_version:t})},o.prototype.getGroupSummary=function(e){var t=l.encodeUri("/groups/$groupId/summary",{$groupId:e});return this._http.authedRequest(void 0,"GET",t)},o.prototype.getGroupProfile=function(e){var t=l.encodeUri("/groups/$groupId/profile",{$groupId:e});return this._http.authedRequest(void 0,"GET",t)},o.prototype.setGroupProfile=function(e,t){var r=l.encodeUri("/groups/$groupId/profile",{$groupId:e});return this._http.authedRequest(void 0,"POST",r,void 0,t)},o.prototype.setGroupJoinPolicy=function(e,t){var r=l.encodeUri("/groups/$groupId/settings/m.join_policy",{$groupId:e});return this._http.authedRequest(void 0,"PUT",r,void 0,{"m.join_policy":t})},o.prototype.getGroupUsers=function(e){var t=l.encodeUri("/groups/$groupId/users",{$groupId:e});return this._http.authedRequest(void 0,"GET",t)},o.prototype.getGroupInvitedUsers=function(e){var t=l.encodeUri("/groups/$groupId/invited_users",{$groupId:e});return this._http.authedRequest(void 0,"GET",t)},o.prototype.getGroupRooms=function(e){var t=l.encodeUri("/groups/$groupId/rooms",{$groupId:e});return this._http.authedRequest(void 0,"GET",t)},o.prototype.inviteUserToGroup=function(e,t){var r=l.encodeUri("/groups/$groupId/admin/users/invite/$userId",{$groupId:e,$userId:t});return this._http.authedRequest(void 0,"PUT",r,void 0,{})},o.prototype.removeUserFromGroup=function(e,t){var r=l.encodeUri("/groups/$groupId/admin/users/remove/$userId",{$groupId:e,$userId:t});return this._http.authedRequest(void 0,"PUT",r,void 0,{})},o.prototype.addUserToGroupSummary=function(e,t,r){var n=l.encodeUri(r?"/groups/$groupId/summary/$roleId/users/$userId":"/groups/$groupId/summary/users/$userId",{$groupId:e,$roleId:r,$userId:t});return this._http.authedRequest(void 0,"PUT",n,void 0,{})},o.prototype.removeUserFromGroupSummary=function(e,t){var r=l.encodeUri("/groups/$groupId/summary/users/$userId",{$groupId:e,$userId:t});return this._http.authedRequest(void 0,"DELETE",r,void 0,{})},o.prototype.addRoomToGroupSummary=function(e,t,r){var n=l.encodeUri(r?"/groups/$groupId/summary/$categoryId/rooms/$roomId":"/groups/$groupId/summary/rooms/$roomId",{$groupId:e,$categoryId:r,$roomId:t});return this._http.authedRequest(void 0,"PUT",n,void 0,{})},o.prototype.removeRoomFromGroupSummary=function(e,t){var r=l.encodeUri("/groups/$groupId/summary/rooms/$roomId",{$groupId:e,$roomId:t});return this._http.authedRequest(void 0,"DELETE",r,void 0,{})},o.prototype.addRoomToGroup=function(e,t,r){void 0===r&&(r=!0);var n=l.encodeUri("/groups/$groupId/admin/rooms/$roomId",{$groupId:e,$roomId:t});return this._http.authedRequest(void 0,"PUT",n,void 0,{"m.visibility":{type:r?"public":"private"}})},o.prototype.updateGroupRoomVisibility=function(e,t,r){var n=l.encodeUri("/groups/$groupId/admin/rooms/$roomId/config/m.visibility",{$groupId:e,$roomId:t});return this._http.authedRequest(void 0,"PUT",n,void 0,{type:r?"public":"private"})},o.prototype.removeRoomFromGroup=function(e,t){var r=l.encodeUri("/groups/$groupId/admin/rooms/$roomId",{$groupId:e,$roomId:t});return this._http.authedRequest(void 0,"DELETE",r,void 0,{})},o.prototype.acceptGroupInvite=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=l.encodeUri("/groups/$groupId/self/accept_invite",{$groupId:e});return this._http.authedRequest(void 0,"PUT",r,void 0,t||{})},o.prototype.joinGroup=function(e){var t=l.encodeUri("/groups/$groupId/self/join",{$groupId:e});return this._http.authedRequest(void 0,"PUT",t,void 0,{})},o.prototype.leaveGroup=function(e){var t=l.encodeUri("/groups/$groupId/self/leave",{$groupId:e});return this._http.authedRequest(void 0,"PUT",t,void 0,{})},o.prototype.getJoinedGroups=function(){var e=l.encodeUri("/joined_groups");return this._http.authedRequest(void 0,"GET",e)},o.prototype.createGroup=function(e){var t=l.encodeUri("/create_group");return this._http.authedRequest(void 0,"POST",t,void 0,e)},o.prototype.getPublicisedGroups=function(e){var t=l.encodeUri("/publicised_groups");return this._http.authedRequest(void 0,"POST",t,void 0,{user_ids:e})},o.prototype.setGroupPublicity=function(e,t){var r=l.encodeUri("/groups/$groupId/self/update_publicity",{$groupId:e});return this._http.authedRequest(void 0,"PUT",r,void 0,{publicise:t})},o.prototype.getStateEvent=function(e,t,r,n){var o={$roomId:e,$eventType:t,$stateKey:r},i=l.encodeUri("/rooms/$roomId/state/$eventType",o);return void 0!==r&&(i=l.encodeUri(i+"/$stateKey",o)),this._http.authedRequest(n,"GET",i)},o.prototype.sendStateEvent=function(e,t,r,n,o){var i={$roomId:e,$eventType:t,$stateKey:n},s=l.encodeUri("/rooms/$roomId/state/$eventType",i);return void 0!==n&&(s=l.encodeUri(s+"/$stateKey",i)),this._http.authedRequest(o,"PUT",s,void 0,r)},o.prototype.redactEvent=function(e,t,r){var n=l.encodeUri("/rooms/$roomId/redact/$eventId",{$roomId:e,$eventId:t});return this._http.authedRequest(r,"POST",n,void 0,{})},o.prototype.roomInitialSync=function(e,t,r){l.isFunction(t)&&(r=t,t=void 0);var n=l.encodeUri("/rooms/$roomId/initialSync",{$roomId:e});return t||(t=30),this._http.authedRequest(r,"GET",n,{limit:t})},o.prototype.setRoomReadMarkersHttpRequest=function(e,t,r){var n=l.encodeUri("/rooms/$roomId/read_markers",{$roomId:e}),o={"m.fully_read":t,"m.read":r};return this._http.authedRequest(void 0,"POST",n,void 0,o)},o.prototype.getJoinedRooms=function(){var e=l.encodeUri("/joined_rooms");return this._http.authedRequest(void 0,"GET",e)},o.prototype.getJoinedRoomMembers=function(e){var t=l.encodeUri("/rooms/$roomId/joined_members",{$roomId:e});return this._http.authedRequest(void 0,"GET",t)},o.prototype.publicRooms=function(e,t){"function"==typeof e&&(t=e,e={}),void 0===e&&(e={});var r={};return e.server&&(r.server=e.server,delete e.server),0===(0,u.default)(e).length&&0===(0,u.default)(r).length?this._http.authedRequest(t,"GET","/publicRooms"):this._http.authedRequest(t,"POST","/publicRooms",r,e)},o.prototype.createAlias=function(e,t,r){var n=l.encodeUri("/directory/room/$alias",{$alias:e}),o={room_id:t};return this._http.authedRequest(r,"PUT",n,void 0,o)},o.prototype.deleteAlias=function(e,t){var r=l.encodeUri("/directory/room/$alias",{$alias:e});return this._http.authedRequest(t,"DELETE",r,void 0,void 0)},o.prototype.getRoomIdForAlias=function(e,t){var r=l.encodeUri("/directory/room/$alias",{$alias:e});return this._http.authedRequest(t,"GET",r)},o.prototype.resolveRoomAlias=function(e,t){var r=l.encodeUri("/directory/room/$alias",{$alias:e});return this._http.request(t,"GET",r)},o.prototype.getRoomDirectoryVisibility=function(e,t){var r=l.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this._http.authedRequest(t,"GET",r)},o.prototype.setRoomDirectoryVisibility=function(e,t,r){var n=l.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this._http.authedRequest(r,"PUT",n,void 0,{visibility:t})},o.prototype.setRoomDirectoryVisibilityAppService=function(e,t,r,n){var o=l.encodeUri("/directory/list/appservice/$networkId/$roomId",{$networkId:e,$roomId:t});return this._http.authedRequest(n,"PUT",o,void 0,{visibility:r})},o.prototype.searchUserDirectory=function(e){var t={search_term:e.term};return void 0!==e.limit&&(t.limit=e.limit),this._http.authedRequest(void 0,"POST","/user_directory/search",void 0,t)},o.prototype.uploadContent=function(e,t){return this._http.uploadContent(e,t)},o.prototype.cancelUpload=function(e){return this._http.cancelUpload(e)},o.prototype.getCurrentUploads=function(){return this._http.getCurrentUploads()},o.prototype.getProfileInfo=function(e,t,r){l.isFunction(t)&&(r=t,t=void 0);var n=t?l.encodeUri("/profile/$userId/$info",{$userId:e,$info:t}):l.encodeUri("/profile/$userId",{$userId:e});return this._http.authedRequest(r,"GET",n)},o.prototype.getThreePids=function(e){return this._http.authedRequest(e,"GET","/account/3pid",void 0,void 0)},o.prototype.addThreePid=function(e,t,r){var n={threePidCreds:e,bind:t};return this._http.authedRequest(r,"POST","/account/3pid",null,n)},o.prototype.deleteThreePid=function(e,t){var r={medium:e,address:t};return this._http.authedRequestWithPrefix(void 0,"POST","/account/3pid/delete",null,r,c.PREFIX_UNSTABLE)},o.prototype.setPassword=function(e,t,r){var n={auth:e,new_password:t};return this._http.authedRequest(r,"POST","/account/password",null,n)},o.prototype.getDevices=function(){return this._http.authedRequestWithPrefix(void 0,"GET","/devices",void 0,void 0,c.PREFIX_UNSTABLE)},o.prototype.setDeviceDetails=function(e,t){var r=l.encodeUri("/devices/$device_id",{$device_id:e});return this._http.authedRequestWithPrefix(void 0,"PUT",r,void 0,t,c.PREFIX_UNSTABLE)},o.prototype.deleteDevice=function(e,t){var r=l.encodeUri("/devices/$device_id",{$device_id:e}),n={};return t&&(n.auth=t),this._http.authedRequestWithPrefix(void 0,"DELETE",r,void 0,n,c.PREFIX_UNSTABLE)},o.prototype.deleteMultipleDevices=function(e,t){var r={devices:e};return t&&(r.auth=t),this._http.authedRequestWithPrefix(void 0,"POST","/delete_devices",void 0,r,c.PREFIX_UNSTABLE)},o.prototype.getPushers=function(e){return this._http.authedRequest(e,"GET","/pushers",void 0,void 0)},o.prototype.setPusher=function(e,t){return this._http.authedRequest(t,"POST","/pushers/set",null,e)},o.prototype.getPushRules=function(e){return this._http.authedRequest(e,"GET","/pushrules/")},o.prototype.addPushRule=function(e,t,r,n,o){var i=l.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:r});return this._http.authedRequest(o,"PUT",i,void 0,n)},o.prototype.deletePushRule=function(e,t,r,n){var o=l.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:r});return this._http.authedRequest(n,"DELETE",o)},o.prototype.setPushRuleEnabled=function(e,t,r,n,o){var i=l.encodeUri("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:r});return this._http.authedRequest(o,"PUT",i,void 0,{enabled:n})},o.prototype.setPushRuleActions=function(e,t,r,n,o){var i=l.encodeUri("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:r});return this._http.authedRequest(o,"PUT",i,void 0,{actions:n})},o.prototype.search=function(e,t){var r={};return e.next_batch&&(r.next_batch=e.next_batch),this._http.authedRequest(t,"POST","/search",r,e.body)},o.prototype.uploadKeysRequest=function(e,t,r){t=t||{};var n=t.device_id,o=void 0;return o=n?l.encodeUri("/keys/upload/$deviceId",{$deviceId:n}):"/keys/upload",this._http.authedRequestWithPrefix(r,"POST",o,void 0,e,c.PREFIX_UNSTABLE)},o.prototype.downloadKeysForUsers=function(e,t){if(l.isFunction(t))throw new Error("downloadKeysForUsers no longer accepts a callback parameter");t=t||{};var r={device_keys:{}};return"token"in t&&(r.token=t.token),e.forEach(function(e){r.device_keys[e]={}}),this._http.authedRequestWithPrefix(void 0,"POST","/keys/query",void 0,r,c.PREFIX_UNSTABLE)},o.prototype.claimOneTimeKeys=function(e,t){var r={};void 0===t&&(t="signed_curve25519");for(var n=0;n1&&c(t,r,ee.QUEUED),n||(n=l(e,r)),n}).then(function(e){return t&&t.updatePendingEvent(r,ee.SENT,e.event_id),n&&n(null,e),e},function(e){console.error("Error sending event",e.stack||e);try{r.error=e,c(t,r,ee.NOT_SENT),e.event=r,n&&n(e)}catch(t){console.error("Exception in error handler!",t.stack||e)}throw e})}function u(e,t,r){if(t.isEncrypted())return null;if(!e.isRoomEncrypted(t.getRoomId()))return null;if(!e._crypto)throw new Error("This room is configured to use encryption, but your client does not support encryption.");return e._crypto.encryptEvent(t,r)}function c(e,t,r){e?e.updatePendingEvent(t,r):t.status=r}function l(e,t){var r=t._txnId?t._txnId:e.makeTxnId(),n={$roomId:t.getRoomId(),$eventType:t.getWireType(),$stateKey:t.getStateKey(),$txnId:r},o=void 0;if(t.isState()){var i="/rooms/$roomId/state/$eventType";t.getStateKey()&&t.getStateKey().length>0&&(i="/rooms/$roomId/state/$eventType/$stateKey"),o=ie.encodeUri(i,n)}else o=ie.encodeUri("/rooms/$roomId/send/$eventType/$txnId",n);return e._http.authedRequest(void 0,"PUT",o,void 0,t.getWireContent()).then(function(e){return console.log("Event sent to "+t.getRoomId()+" with event id "+e.event_id),e})}function d(e,t,r,n,o,i){ie.isFunction(o)&&(i=o,o=void 0);var s=ie.encodeUri("/rooms/$roomId/state/m.room.member/$userId",{$roomId:t,$userId:r});return e._http.authedRequest(i,"PUT",s,void 0,{membership:n,reason:o})}function f(e,t,r,n,o,i){ie.isFunction(o)&&(i=o,o=void 0);var s=ie.encodeUri("/rooms/$room_id/$membership",{$room_id:t,$membership:n});return e._http.authedRequest(i,"POST",s,void 0,{user_id:r,reason:o})}function p(e,t,r,n){var o=ie.encodeUri("/presence/list/$userId",{$userId:t.credentials.userId});return t._http.authedRequest(e,n,o,void 0,r)}function h(e){function t(e){return 0!==e.getType().indexOf("m.call.")?void((e.isBeingDecrypted()||e.isDecryptionFailure())&&e.once("Event.decrypted",t)):i?void r(e):void o.push(e)}function r(t){var r=t.getContent(),o=r.call_id?e.callList[r.call_id]:void 0,i=void 0;if("m.call.invite"===t.getType()){if(t.getSender()===e.credentials.userId)return;if(t.getAge()>r.lifetime)return;if(o&&"ended"===o.state)return;if(o&&console.log("WARN: Already have a MatrixCall with id %s but got an invite. Clobbering.",r.call_id),!(o=oe.createNewMatrixCall(e,t.getRoomId(),{forceTURN:e._forceTURN})))return void console.log("Incoming call ID "+r.call_id+" but this client doesn't support WebRTC");if(o.callId=r.call_id,o._initWithInvite(t),e.callList[o.callId]=o,n[o.callId])for(i=0;io.callId?(console.log("Glare detected: answering incoming call "+o.callId+" and canceling outgoing call "+s.callId),s._replacedBy(o),o.answer()):(console.log("Glare detected: rejecting incoming call "+o.callId+" and keeping outgoing call "+s.callId),o.hangup()):e.emit("Call.incoming",o)}else if("m.call.answer"===t.getType()){if(!o)return;t.getSender()===e.credentials.userId?"ringing"===o.state&&o._onAnsweredElsewhere(r):o._receivedAnswer(r)}else if("m.call.candidates"===t.getType()){if(t.getSender()===e.credentials.userId)return;if(o)for(i=0;i=0;n--){var s=o[n];"m.call.answer"!==s.getType()&&"m.call.hangup"!==s.getType()||(t[s.getContent().call_id]="yep")}o.forEach(function(e){t[e.getContent().call_id]||r(e)}),o=[]}}),e.on("event",t)}function v(e){e._supportsVoip&&(e.isGuest()||e.turnServer().done(function(t){if(t.uris){console.log("Got TURN URIs: "+t.uris+" refresh in "+t.ttl+" secs");var r={urls:t.uris,username:t.username,credential:t.password};e._turnServers=[r],e._checkTurnServersTimeoutID=setTimeout(function(){v(e)},1e3*(t.ttl||3600)*.9)}},function(t){console.error("Failed to get TURN URIs"),e._checkTurnServersTimeoutID=setTimeout(function(){v(e)},6e4)}))}function m(e,t,r){e&&e(r),t.reject(r)}function y(e,t,r){e&&e(null,r),t.resolve(r)}function _(e){function t(t){var r=new Z(t);return r.isEncrypted()&&(e.reEmitter.reEmit(r,["Event.decrypted"]),r.attemptDecryption(e._crypto)),r}return t}var g=e("babel-runtime/core-js/object/assign"),b=n(g),E=e("babel-runtime/core-js/json/stringify"),w=n(E),S=e("babel-runtime/core-js/set"),k=n(S),T=e("babel-runtime/core-js/object/keys"),x=n(T),R=e("babel-runtime/helpers/typeof"),I=n(R),C=e("bluebird"),j=n(C),O=e("babel-runtime/regenerator"),A=n(O),D=e("babel-runtime/helpers/slicedToArray"),M=n(D),P=e("babel-runtime/core-js/object/entries"),L=n(P),U=e("babel-runtime/core-js/get-iterator"),N=n(U),F=function(){var e=(0,C.coroutine)(A.default.mark(function e(t,r,n,o,i,s){var a;return A.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t._crypto){e.next=2;break}throw new Error("End-to-End encryption disabled");case 2:return e.next=4,(0,C.resolve)(t._crypto.setDeviceVerification(r,n,o,i,s));case 4:a=e.sent,t.emit("deviceVerificationChanged",r,n,a);case 6:case"end":return e.stop()}},e,this)}));return function(t,r,n,o,i,s){return e.apply(this,arguments)}}(),q=e("./ReEmitter"),B=n(q),K=e("./crypto/RoomList"),G=n(K),$=e("./crypto"),V=n($),W=e("./crypto/recoverykey"),H=e("./crypto/backup_password"),z=e("./randomstring"),Q=e("./pushprocessor"),J=e("events").EventEmitter,Y=e("url"),X=e("./http-api"),Z=e("./models/event").MatrixEvent,ee=e("./models/event").EventStatus,te=e("./models/event-timeline"),re=e("./models/search-result"),ne=e("./store/stub"),oe=e("./webrtc/call"),ie=e("./utils"),se=e("./content-repo"),ae=e("./filter"),ue=e("./sync"),ce=e("./base-apis"),le=X.MatrixError,de=e("./content-helpers"),fe=e("./crypto/olmlib");j.default.config({warnings:!1});var pe=(0,$.isCryptoAvailable)();ie.inherits(s,J),ie.extend(s.prototype,ce.prototype),s.prototype.clearStores=function(){if(this._clientRunning)throw new Error("Cannot clear stores while client is running");var e=[];return e.push(this.store.deleteAllData()),this._cryptoStore&&e.push(this._cryptoStore.deleteAllData()),j.default.all(e)},s.prototype.getUserId=function(){return this.credentials&&this.credentials.userId?this.credentials.userId:null},s.prototype.getDomain=function(){return this.credentials&&this.credentials.userId?this.credentials.userId.replace(/^.*?:/,""):null},s.prototype.getUserIdLocalpart=function(){return this.credentials&&this.credentials.userId?this.credentials.userId.split(":")[0].substring(1):null},s.prototype.getDeviceId=function(){return this.deviceId},s.prototype.supportsVoip=function(){return this._supportsVoip},s.prototype.setForceTURN=function(e){this._forceTURN=e},s.prototype.getSyncState=function(){return this._syncApi?this._syncApi.getSyncState():null},s.prototype.getSyncStateData=function(){return this._syncApi?this._syncApi.getSyncStateData():null},s.prototype.isGuest=function(){return this._isGuest},s.prototype.getScheduler=function(){return this.scheduler},s.prototype.setGuest=function(e){this._isGuest=e},s.prototype.retryImmediately=function(){return this._syncApi.retryImmediately()},s.prototype.getNotifTimelineSet=function(){return this._notifTimelineSet},s.prototype.setNotifTimelineSet=function(e){this._notifTimelineSet=e},s.prototype.initCrypto=(0,C.coroutine)(A.default.mark(function e(){var t,r;return A.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if((0,$.isCryptoAvailable)()){e.next=2;break}throw new Error("End-to-end encryption not supported in this js-sdk build: did you remember to load the olm library?");case 2:if(!this._crypto){e.next=5;break}return console.warn("Attempt to re-initialise e2e encryption on MatrixClient"),e.abrupt("return");case 5:if(this._sessionStore){e.next=7;break}throw new Error("Cannot enable encryption: no sessionStore provided");case 7:if(this._cryptoStore){e.next=9;break}throw new Error("Cannot enable encryption: no cryptoStore provided");case 9:return e.next=11,(0,C.resolve)(this._roomList.init());case 11:if(null!==(t=this.getUserId())){e.next=14;break}throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");case 14:if(null!==this.deviceId){e.next=16;break}throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");case 16:return r=new V.default(this,this._sessionStore,t,this.deviceId,this.store,this._cryptoStore,this._roomList),this.reEmitter.reEmit(r,["crypto.roomKeyRequest","crypto.roomKeyRequestCancellation","crypto.warning"]),e.next=20,(0,C.resolve)(r.init());case 20:this.olmVersion=V.default.getOlmVersion(),r.registerEventHandlers(this),this._crypto=r;case 23:case"end":return e.stop()}},e,this)})),s.prototype.isCryptoEnabled=function(){return null!==this._crypto},s.prototype.getDeviceEd25519Key=function(){return this._crypto?this._crypto.getDeviceEd25519Key():null},s.prototype.uploadKeys=function(){if(null===this._crypto)throw new Error("End-to-end encryption disabled");return this._crypto.uploadDeviceKeys()},s.prototype.downloadKeys=function(e,t){return null===this._crypto?j.default.reject(new Error("End-to-end encryption disabled")):this._crypto.downloadKeys(e,t)},s.prototype.getStoredDevicesForUser=function(){var e=(0,C.method)(function(e){if(null===this._crypto)throw new Error("End-to-end encryption disabled");return this._crypto.getStoredDevicesForUser(e)||[]});return function(t){return e.apply(this,arguments)}}(),s.prototype.getStoredDevice=function(){var e=(0,C.method)(function(e,t){if(null===this._crypto)throw new Error("End-to-end encryption disabled");return this._crypto.getStoredDevice(e,t)||null});return function(t,r){return e.apply(this,arguments)}}(),s.prototype.setDeviceVerified=function(e,t,r){void 0===r&&(r=!0);var n=F(this,e,t,r,null);return e==this.credentials.userId&&this._crypto.checkKeyBackup(),n},s.prototype.setDeviceBlocked=function(e,t,r){return void 0===r&&(r=!0),F(this,e,t,null,r)},s.prototype.setDeviceKnown=function(e,t,r){return void 0===r&&(r=!0),F(this,e,t,null,null,r)},s.prototype.setGlobalBlacklistUnverifiedDevices=function(e){if(null===this._crypto)throw new Error("End-to-end encryption disabled");this._crypto.setGlobalBlacklistUnverifiedDevices(e)},s.prototype.getGlobalBlacklistUnverifiedDevices=function(){if(null===this._crypto)throw new Error("End-to-end encryption disabled");return this._crypto.getGlobalBlacklistUnverifiedDevices()},s.prototype.getEventSenderDeviceInfo=function(){var e=(0,C.method)(function(e){return this._crypto?this._crypto.getEventSenderDeviceInfo(e):null});return function(t){return e.apply(this,arguments)}}(),s.prototype.isEventSenderVerified=function(){var e=(0,C.coroutine)(A.default.mark(function e(t){var r;return A.default.wrap(function(e){ +for(;;)switch(e.prev=e.next){case 0:return e.next=2,(0,C.resolve)(this.getEventSenderDeviceInfo(t));case 2:if(r=e.sent){e.next=5;break}return e.abrupt("return",!1);case 5:return e.abrupt("return",r.isVerified());case 6:case"end":return e.stop()}},e,this)}));return function(t){return e.apply(this,arguments)}}(),s.prototype.cancelAndResendEventRoomKeyRequest=function(e){e.cancelAndResendKeyRequest(this._crypto)},s.prototype.setRoomEncryption=function(e,t){if(!this._crypto)throw new Error("End-to-End encryption disabled");return this._crypto.setRoomEncryption(e,t)},s.prototype.isRoomEncrypted=function(e){var t=this.getRoom(e);return!!t&&(!!t.currentState.getStateEvents("m.room.encryption","")||this._roomList.isRoomEncrypted(e))},s.prototype.forceDiscardSession=function(e){if(!this._crypto)throw new Error("End-to-End encryption disabled");this._crypto.forceDiscardSession(e)},s.prototype.exportRoomKeys=function(){return this._crypto?this._crypto.exportRoomKeys():j.default.reject(new Error("End-to-end encryption disabled"))},s.prototype.importRoomKeys=function(e){if(!this._crypto)throw new Error("End-to-end encryption disabled");return this._crypto.importRoomKeys(e)},s.prototype.getKeyBackupVersion=function(){return this._http.authedRequest(void 0,"GET","/room_keys/version").then(function(e){if(e.algorithm!==fe.MEGOLM_BACKUP_ALGORITHM){var t="Unknown backup algorithm: "+e.algorithm;return j.default.reject(t)}if("object"===(0,I.default)(e.auth_data)&&e.auth_data.public_key)return e;return j.default.reject("Invalid backup data returned")}).catch(function(e){if("M_NOT_FOUND"===e.errcode)return null;throw e})},s.prototype.isKeyBackupTrusted=function(e){return this._crypto.isKeyBackupTrusted(e)},s.prototype.getKeyBackupEnabled=function(){if(null===this._crypto)throw new Error("End-to-end encryption disabled");return Boolean(this._crypto.backupKey)},s.prototype.enableKeyBackup=function(e){if(null===this._crypto)throw new Error("End-to-end encryption disabled");this._crypto.backupInfo=e,this._crypto.backupKey&&this._crypto.backupKey.free(),this._crypto.backupKey=new r.Olm.PkEncryption,this._crypto.backupKey.set_recipient_key(e.auth_data.public_key),this.emit("crypto.keyBackupStatus",!0)},s.prototype.disableKeyBackup=function(){if(null===this._crypto)throw new Error("End-to-end encryption disabled");this._crypto.backupInfo=null,this._crypto.backupKey&&this._crypto.backupKey.free(),this._crypto.backupKey=null,this.emit("crypto.keyBackupStatus",!1)},s.prototype.prepareKeyBackupVersion=function(){var e=(0,C.coroutine)(A.default.mark(function e(t){var n,o,i,s;return A.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(null!==this._crypto){e.next=2;break}throw new Error("End-to-end encryption disabled");case 2:if(n=new r.Olm.PkDecryption,e.prev=3,o=void 0,i={},!t){e.next=15;break}return e.next=9,(0,C.resolve)((0,H.keyForNewBackup)(t));case 9:s=e.sent,o=n.init_with_private_key(s.key),i.private_key_salt=s.salt,i.private_key_iterations=s.iterations,e.next=16;break;case 15:o=n.generate_key();case 16:return i.public_key=o,e.abrupt("return",{algorithm:fe.MEGOLM_BACKUP_ALGORITHM,auth_data:i,recovery_key:(0,W.encodeRecoveryKey)(n.get_private_key())});case 18:return e.prev=18,n.free(),e.finish(18);case 21:case"end":return e.stop()}},e,this,[[3,,18,21]])}));return function(t){return e.apply(this,arguments)}}(),s.prototype.createKeyBackupVersion=function(e){var t=this;if(null===this._crypto)throw new Error("End-to-end encryption disabled");var r={algorithm:e.algorithm,auth_data:e.auth_data};return this._crypto._signObject(r.auth_data).then(function(){return t._http.authedRequest(void 0,"POST","/room_keys/version",void 0,r)}).then(function(r){return t.enableKeyBackup({algorithm:e.algorithm,auth_data:e.auth_data,version:r.version}),r})},s.prototype.deleteKeyBackupVersion=function(e){if(null===this._crypto)throw new Error("End-to-end encryption disabled");this._crypto.backupInfo&&this._crypto.backupInfo.version===e&&this.disableKeyBackup();var t=ie.encodeUri("/room_keys/version/$version",{$version:e});return this._http.authedRequest(void 0,"DELETE",t,void 0,void 0)},s.prototype._makeKeyBackupPath=function(e,t,r){var n=void 0;return n=void 0!==t?ie.encodeUri("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):void 0!==e?ie.encodeUri("/room_keys/keys/$roomId",{$roomId:e}):"/room_keys/keys",{path:n,queryData:void 0===r?void 0:{version:r}}},s.prototype.sendKeyBackup=function(e,t,r,n){if(null===this._crypto)throw new Error("End-to-end encryption disabled");var o=this._makeKeyBackupPath(e,t,r);return this._http.authedRequest(void 0,"PUT",o.path,o.queryData,n)},s.prototype.backupAllGroupSessions=function(e){if(null===this._crypto)throw new Error("End-to-end encryption disabled");return this._crypto.backupAllGroupSessions(e)},s.prototype.isValidRecoveryKey=function(e){try{return(0,W.decodeRecoveryKey)(e),!0}catch(e){return!1}},s.prototype.restoreKeyBackupWithPassword=function(){var e=(0,C.coroutine)(A.default.mark(function e(t,r,n,o){var i,s;return A.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,(0,C.resolve)(this.getKeyBackupVersion());case 2:return i=e.sent,e.next=5,(0,C.resolve)((0,H.keyForExistingBackup)(i,t));case 5:return s=e.sent,e.abrupt("return",this._restoreKeyBackup(s,r,n,o));case 7:case"end":return e.stop()}},e,this)}));return function(t,r,n,o){return e.apply(this,arguments)}}(),s.prototype.restoreKeyBackupWithRecoveryKey=function(e,t,r,n){var o=(0,W.decodeRecoveryKey)(e);return this._restoreKeyBackup(o,t,r,n)},s.prototype._restoreKeyBackup=function(e,t,n,s){var a=this;if(null===this._crypto)throw new Error("End-to-end encryption disabled");var u=0,c=[],l=this._makeKeyBackupPath(t,n,s),d=new r.Olm.PkDecryption;try{d.init_with_private_key(e)}catch(e){throw d.free(),e}return this._http.authedRequest(void 0,"GET",l.path,l.queryData).then(function(e){if(e.rooms){var r=!0,s=!1,l=void 0;try{for(var f,p=(0,N.default)((0,L.default)(e.rooms));!(r=(f=p.next()).done);r=!0){var h=(0,M.default)(f.value,2),v=h[0],m=h[1];if(m.sessions){u+=(0,x.default)(m.sessions).length;var y=o(m.sessions,d,v),_=!0,g=!1,b=void 0;try{for(var E,w=(0,N.default)(y);!(_=(E=w.next()).done);_=!0){var S=E.value;S.room_id=v,c.push(S)}}catch(e){g=!0,b=e}finally{try{!_&&w.return&&w.return()}finally{if(g)throw b}}}}}catch(e){s=!0,l=e}finally{try{!r&&p.return&&p.return()}finally{if(s)throw l}}}else if(e.sessions)u=(0,x.default)(e.sessions).length,c=o(e.sessions,d,t);else{u=1;try{var k=i(e,d);k.room_id=t,k.session_id=n,c.push(k)}catch(e){console.log("Failed to decrypt session from backup")}}return a.importRoomKeys(c)}).then(function(){return{total:u,imported:c.length}}).finally(function(){d.free()})},s.prototype.deleteKeysFromBackup=function(e,t,r){if(null===this._crypto)throw new Error("End-to-end encryption disabled");var n=this._makeKeyBackupPath(e,t,r);return this._http.authedRequest(void 0,"DELETE",n.path,n.queryData)},s.prototype.getGroup=function(e){return this.store.getGroup(e)},s.prototype.getGroups=function(){return this.store.getGroups()},s.prototype.getMediaConfig=function(e){return this._http.authedRequestWithPrefix(e,"GET","/config",void 0,void 0,X.PREFIX_MEDIA_R0)},s.prototype.getRoom=function(e){return this.store.getRoom(e)},s.prototype.getRooms=function(){return this.store.getRooms()},s.prototype.getVisibleRooms=function(){var e=this.store.getRooms(),t=new k.default,r=!0,n=!1,o=void 0;try{for(var i,s=(0,N.default)(e);!(r=(i=s.next()).done);r=!0){var a=i.value,u=a.currentState.getStateEvents("m.room.create","");if(u){var c=u.getContent().predecessor;c&&c.room_id&&t.add(c.room_id)}}}catch(e){n=!0,o=e}finally{try{!r&&s.return&&s.return()}finally{if(n)throw o}}return e.filter(function(e){return!e.currentState.getStateEvents("m.room.tombstone","")||!t.has(e.roomId)})},s.prototype.getUser=function(e){return this.store.getUser(e)},s.prototype.getUsers=function(){return this.store.getUsers()},s.prototype.setAccountData=function(e,t,r){var n=ie.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return this._http.authedRequest(r,"PUT",n,void 0,t)},s.prototype.getAccountData=function(e){return this.store.getAccountData(e)},s.prototype.getIgnoredUsers=function(){var e=this.getAccountData("m.ignored_user_list");return e&&e.getContent()&&e.getContent().ignored_users?(0,x.default)(e.getContent().ignored_users):[]},s.prototype.setIgnoredUsers=function(e,t){var r={ignored_users:{}};return e.map(function(e){return r.ignored_users[e]={}}),this.setAccountData("m.ignored_user_list",r,t)},s.prototype.isUserIgnored=function(e){return-1!==this.getIgnoredUsers().indexOf(e)},s.prototype.joinRoom=function(e,t,r){if(ie.isFunction(t))throw new Error("Expected 'opts' object, got function.");t=t||{},void 0===t.syncRoom&&(t.syncRoom=!0);var n=this.getRoom(e);if(n&&n.hasMembershipState(this.credentials.userId,"join"))return j.default.resolve(n);var o=j.default.resolve();t.inviteSignUrl&&(o=this._http.requestOtherUrl(void 0,"POST",t.inviteSignUrl,{mxid:this.credentials.userId}));var i={};t.viaServers&&(i.server_name=t.viaServers);var s={qsStringifyOptions:{arrayFormat:"repeat"}},a=j.default.defer(),u=this;return o.then(function(t){var r={};t&&(r.third_party_signed=t);var n=ie.encodeUri("/join/$roomid",{$roomid:e});return u._http.authedRequest(void 0,"POST",n,i,r,s)}).then(function(e){var r=e.room_id,n=new ue(u,u._clientOpts),o=n.createRoom(r);return t.syncRoom,j.default.resolve(o)}).done(function(e){y(r,a,e)},function(e){m(r,a,e)}),a.promise},s.prototype.resendEvent=function(e,t){return c(t,e,ee.SENDING),a(this,t,e)},s.prototype.cancelPendingEvent=function(e){if([ee.QUEUED,ee.NOT_SENT].indexOf(e.status)<0)throw new Error("cannot cancel an event with status "+e.status);this.scheduler&&this.scheduler.removeEventFromQueue(e),c(this.getRoom(e.getRoomId()),e,ee.CANCELLED)},s.prototype.setRoomName=function(e,t,r){return this.sendStateEvent(e,"m.room.name",{name:t},void 0,r)},s.prototype.setRoomTopic=function(e,t,r){return this.sendStateEvent(e,"m.room.topic",{topic:t},void 0,r)},s.prototype.getRoomTags=function(e,t){var r=ie.encodeUri("/user/$userId/rooms/$roomId/tags/",{$userId:this.credentials.userId,$roomId:e});return this._http.authedRequest(t,"GET",r,void 0)},s.prototype.setRoomTag=function(e,t,r,n){var o=ie.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this._http.authedRequest(n,"PUT",o,void 0,r)},s.prototype.deleteRoomTag=function(e,t,r){var n=ie.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this._http.authedRequest(r,"DELETE",n,void 0,void 0)},s.prototype.setRoomAccountData=function(e,t,r,n){var o=ie.encodeUri("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this._http.authedRequest(n,"PUT",o,void 0,r)},s.prototype.setPowerLevel=function(e,t,r,n,o){var i={users:{}};n&&"m.room.power_levels"===n.getType()&&(i=ie.deepCopy(n.getContent())),i.users[t]=r;var s=ie.encodeUri("/rooms/$roomId/state/m.room.power_levels",{$roomId:e});return this._http.authedRequest(o,"PUT",s,void 0,i)},s.prototype.sendEvent=function(e,t,r,n,o){ie.isFunction(n)&&(o=n,n=void 0),n||(n=this.makeTxnId()),console.log("sendEvent of type "+t+" in "+e+" with txnId "+n);var i=this.getRoom(e),s=new Z({event_id:"~"+e+":"+n,user_id:this.credentials.userId,room_id:e,type:t,origin_server_ts:(new Date).getTime(),content:r});return s._txnId=n,s.status=ee.SENDING,i&&i.addPendingEvent(s,n),s.status===ee.NOT_SENT?j.default.reject(new Error("Event blocked by other events not yet sent")):a(this,i,s,o)},s.prototype.sendMessage=function(e,t,r,n){return ie.isFunction(r)&&(n=r,r=void 0),this.sendEvent(e,"m.room.message",t,r,n)},s.prototype.sendTextMessage=function(e,t,r,n){var o=de.makeTextMessage(t);return this.sendMessage(e,o,r,n)},s.prototype.sendNotice=function(e,t,r,n){var o=de.makeNotice(t);return this.sendMessage(e,o,r,n)},s.prototype.sendEmoteMessage=function(e,t,r,n){var o=de.makeEmoteMessage(t);return this.sendMessage(e,o,r,n)},s.prototype.sendImageMessage=function(e,t,r,n,o){ie.isFunction(n)&&(o=n,n=void 0),n||(n="Image");var i={msgtype:"m.image",url:t,info:r,body:n};return this.sendMessage(e,i,o)},s.prototype.sendStickerMessage=function(e,t,r,n,o){ie.isFunction(n)&&(o=n,n=void 0),n||(n="Sticker");var i={url:t,info:r,body:n};return this.sendEvent(e,"m.sticker",i,o,void 0)},s.prototype.sendHtmlMessage=function(e,t,r,n){var o=de.makeHtmlMessage(t,r);return this.sendMessage(e,o,n)},s.prototype.sendHtmlNotice=function(e,t,r,n){var o=de.makeHtmlNotice(t,r);return this.sendMessage(e,o,n)},s.prototype.sendHtmlEmote=function(e,t,r,n){var o=de.makeHtmlEmote(t,r);return this.sendMessage(e,o,n)},s.prototype.sendReceipt=function(e,t,r){if(this.isGuest())return j.default.resolve({});var n=ie.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()}),o=this._http.authedRequest(r,"POST",n,void 0,{}),i=this.getRoom(e.getRoomId());return i&&i._addLocalEchoReceipt(this.credentials.userId,e,t),o},s.prototype.sendReadReceipt=function(e,t){return this.sendReceipt(e,"m.read",t)},s.prototype.setRoomReadMarkers=function(e,t,r){var n=t,o=void 0;if(r){o=r.getId();var i=this.getRoom(e);i&&i._addLocalEchoReceipt(this.credentials.userId,r,"m.read")}return this.setRoomReadMarkersHttpRequest(e,n,o)},s.prototype.getUrlPreview=function(e,t,r){var n=t+"_"+e,o=this.urlPreviewCache[n];if(o)return j.default.resolve(o);var i=this;return this._http.authedRequestWithPrefix(r,"GET","/preview_url",{url:e,ts:t},void 0,X.PREFIX_MEDIA_R0).then(function(e){return i.urlPreviewCache[n]=e,e})},s.prototype.sendTyping=function(e,t,r,n){if(this.isGuest())return j.default.resolve({});var o=ie.encodeUri("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.credentials.userId}),i={typing:t};return t&&(i.timeout=r||2e4),this._http.authedRequest(n,"PUT",o,void 0,i)},s.prototype.invite=function(e,t,r){return f(this,e,t,"invite",void 0,r)},s.prototype.inviteByEmail=function(e,t,r){return this.inviteByThreePid(e,"email",t,r)},s.prototype.inviteByThreePid=function(e,t,r,n){var o=ie.encodeUri("/rooms/$roomId/invite",{$roomId:e}),i=this.getIdentityServerUrl(!0);return i?this._http.authedRequest(n,"POST",o,void 0,{id_server:i,medium:t,address:r}):j.default.reject(new le({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}))},s.prototype.leave=function(e,t){return f(this,e,void 0,"leave",void 0,t)},s.prototype.ban=function(e,t,r,n){return f(this,e,t,"ban",r,n)},s.prototype.forget=function(e,t,r){void 0===t&&(t=!0);var n=f(this,e,void 0,"forget",void 0,r);if(!t)return n;var o=this;return n.then(function(t){return o.store.removeRoom(e),o.emit("deleteRoom",e),t})},s.prototype.unban=function(e,t,r){var n=ie.encodeUri("/rooms/$roomId/unban",{$roomId:e}),o={user_id:t};return this._http.authedRequest(r,"POST",n,void 0,o)},s.prototype.kick=function(e,t,r,n){return d(this,e,t,"leave",r,n)},s.prototype.getPushActionsForEvent=function(e){return e.getPushActions()||e.setPushActions(this._pushProcessor.actionsForEvent(e)),e.getPushActions()},s.prototype.setProfileInfo=function(e,t,r){var n=ie.encodeUri("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this._http.authedRequest(r,"PUT",n,void 0,t)},s.prototype.setDisplayName=function(e,t){return this.setProfileInfo("displayname",{displayname:e},t)},s.prototype.setAvatarUrl=function(e,t){return this.setProfileInfo("avatar_url",{avatar_url:e},t)},s.prototype.mxcUrlToHttp=function(e,t,r,n,o){return se.getHttpUriForMxc(this.baseUrl,e,t,r,n,o)},s.prototype.setPresence=function(e,t){var r=ie.encodeUri("/presence/$userId/status",{$userId:this.credentials.userId});if("string"==typeof e&&(e={presence:e}),-1==["offline","online","unavailable"].indexOf(e.presence))throw new Error("Bad presence value: "+e.presence);return this._http.authedRequest(t,"PUT",r,void 0,e)},s.prototype.getPresenceList=function(e){return p(e,this,void 0,"GET")},s.prototype.inviteToPresenceList=function(e,t){return p(e,this,{invite:t},"POST")},s.prototype.dropFromPresenceList=function(e,t){return p(e,this,{drop:t},"POST")},s.prototype.scrollback=function(e,t,r){ie.isFunction(t)&&(r=t,t=void 0),t=t||30;var n=0,o=this._ongoingScrollbacks[e.roomId]||{};if(o.promise)return o.promise;if(o.errorTs){var i=Date.now()-o.errorTs;n=Math.max(3e3-i,0)}if(null===e.oldState.paginationToken)return j.default.resolve(e);var s=this.store.scrollback(e,t).length;if(s===t)return j.default.resolve(e);t-=s;var a=j.default.defer();o={promise:a.promise,errorTs:null};var u=this;return j.default.delay(n).then(function(){return u._createMessagesRequest(e.roomId,e.oldState.paginationToken,t,"b")}).done(function(t){var n=ie.map(t.chunk,_(u));if(t.state){var o=ie.map(t.state,_(u));e.currentState.setUnknownStateEvents(o)}e.addEventsToTimeline(n,!0,e.getLiveTimeline()),e.oldState.paginationToken=t.end,0===t.chunk.length&&(e.oldState.paginationToken=null),u.store.storeEvents(e,n,t.end,!0),u._ongoingScrollbacks[e.roomId]=null,y(r,a,e)},function(t){u._ongoingScrollbacks[e.roomId]={errorTs:Date.now()},m(r,a,t)}),this._ongoingScrollbacks[e.roomId]=o,a.promise},s.prototype.getEventTimeline=function(e,t){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(e.getTimelineForEvent(t))return j.default.resolve(e.getTimelineForEvent(t));var r=ie.encodeUri("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),n=void 0;this._clientOpts.lazyLoadMembers&&(n={filter:(0,w.default)(ae.LAZY_LOADING_MESSAGES_FILTER)});var o=this;return o._http.authedRequest(void 0,"GET",r,n).then(function(r){if(!r.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);r.events_after.reverse();var n=r.events_after.concat([r.event]).concat(r.events_before),i=ie.map(n,o.getEventMapper()),s=e.getTimelineForEvent(i[0].getId());if(s){var a=ie.map(r.state,o.getEventMapper());s.getState(te.BACKWARDS).setUnknownStateEvents(a)}else s=e.addTimeline(),s.initialiseState(ie.map(r.state,o.getEventMapper())),s.getState(te.FORWARDS).paginationToken=r.end;return e.addEventsToTimeline(i,!0,s,r.start),e.getTimelineForEvent(t)||s})},s.prototype._createMessagesRequest=function(e,t,r,n){var o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:void 0,i=ie.encodeUri("/rooms/$roomId/messages",{$roomId:e});void 0===r&&(r=30);var s={from:t,limit:r,dir:n},a=null;return this._clientOpts.lazyLoadMembers&&(a=(0,b.default)({},ae.LAZY_LOADING_MESSAGES_FILTER)),o&&(a=a||{},(0,b.default)(a,o.getRoomTimelineFilterComponent())),a&&(s.filter=(0,w.default)(a)),this._http.authedRequest(void 0,"GET",i,s)},s.prototype.paginateEventTimeline=function(e,t){var r=e.getTimelineSet()===this._notifTimelineSet;t=t||{};var n=t.backwards||!1;if(r&&!n)throw new Error("paginateNotifTimeline can only paginate backwards");var o=n?te.BACKWARDS:te.FORWARDS,i=e.getPaginationToken(o);if(!i)return j.default.resolve(!1);var s=e._paginationRequests[o];if(s)return s;var a=void 0,u=void 0,c=void 0,l=this;if(r)a="/notifications",u={limit:"limit"in t?t.limit:30,only:"highlight"},i&&"end"!==i&&(u.from=i),c=this._http.authedRequestWithPrefix(void 0,"GET",a,u,void 0,X.PREFIX_UNSTABLE).then(function(t){for(var r=t.next_token,i=[],s=0;s0&&(u="/_matrix/media/v1/thumbnail/");var l=a.indexOf("#"),d="";return l>=0&&(d=a.substr(l),a=a.substr(0,l)),e+u+a+(0===n.keys(c).length?"":"?"+n.encodeParams(c))+d},getIdenticonUri:function(e,t,r,o){if(!t)return null;r||(r=96),o||(o=96);var i={width:r,height:o};return e+n.encodeUri("/_matrix/media/v1/identicon/$ident",{$ident:t})+(0===n.keys(i).length?"":"?"+n.encodeParams(i))}}},{"./utils":55}],7:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(r,"__esModule",{value:!0});var o=e("babel-runtime/helpers/slicedToArray"),i=n(o),s=e("babel-runtime/core-js/object/entries"),a=n(s),u=e("bluebird"),c=n(u),l=e("babel-runtime/regenerator"),d=n(l),f=e("babel-runtime/core-js/object/keys"),p=n(f),h=e("babel-runtime/core-js/get-iterator"),v=n(h),m=e("babel-runtime/helpers/classCallCheck"),y=n(m),_=e("babel-runtime/helpers/createClass"),g=n(_),b=function(){var e=(0,u.coroutine)(d.default.mark(function e(t,r,n,o){var i,s,a,c;return d.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:i=!1,e.t0=d.default.keys(n);case 2:if((e.t1=e.t0()).done){e.next=9;break}if(s=e.t1.value,n.hasOwnProperty(s)){e.next=6;break}return e.abrupt("continue",2);case 6: +s in o||(S.default.log("Device "+r+":"+s+" has been removed"),delete n[s],i=!0),e.next=2;break;case 9:e.t2=d.default.keys(o);case 10:if((e.t3=e.t2()).done){e.next=27;break}if(a=e.t3.value,o.hasOwnProperty(a)){e.next=14;break}return e.abrupt("continue",10);case 14:if(c=o[a],c.user_id===r){e.next=18;break}return S.default.warn("Mismatched user_id "+c.user_id+" in keys from "+r+":"+a),e.abrupt("continue",10);case 18:if(c.device_id===a){e.next=21;break}return S.default.warn("Mismatched device_id "+c.device_id+" in keys from "+r+":"+a),e.abrupt("continue",10);case 21:return e.next=23,(0,u.resolve)(E(t,n,c));case 23:if(!e.sent){e.next=25;break}i=!0;case 25:e.next=10;break;case 27:return e.abrupt("return",i);case 28:case"end":return e.stop()}},e,this)}));return function(t,r,n,o){return e.apply(this,arguments)}}(),E=function(){var e=(0,u.coroutine)(d.default.mark(function e(t,r,n){var o,i,s,a,c,l;return d.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(n.keys){e.next=2;break}return e.abrupt("return",!1);case 2:if(o=n.device_id,i=n.user_id,s="ed25519:"+o,a=n.keys[s]){e.next=9;break}return S.default.warn("Device "+i+":"+o+" has no ed25519 key"),e.abrupt("return",!1);case 9:return c=n.unsigned||{},e.prev=10,e.next=13,(0,u.resolve)(R.default.verifySignature(t,n,i,o,a));case 13:e.next=19;break;case 15:return e.prev=15,e.t0=e.catch(10),S.default.warn("Unable to verify signature on device "+i+":"+o+":"+e.t0),e.abrupt("return",!1);case 19:if(l=void 0,!(o in r)){e.next=27;break}if(l=r[o],l.getFingerprint()==a){e.next=25;break}return S.default.warn("Ed25519 key for device "+i+":"+o+" has changed"),e.abrupt("return",!1);case 25:e.next=28;break;case 27:r[o]=l=new T.default(o);case 28:return l.keys=n.keys||{},l.algorithms=n.algorithms||[],l.unsigned=c,e.abrupt("return",!0);case 32:case"end":return e.stop()}},e,this,[[10,15]])}));return function(t,r,n){return e.apply(this,arguments)}}(),w=e("../logger"),S=n(w),k=e("./deviceinfo"),T=n(k),x=e("./olmlib"),R=n(x),I=e("./store/indexeddb-crypto-store"),C=n(I),j=function(){function e(t,r,n,o){(0,y.default)(this,e),this._cryptoStore=r,this._sessionStore=n,this._devices={},this._userByIdentityKey={},this._deviceTrackingStatus={},this._syncToken=null,this._serialiser=new O(t,o,this),this._keyDownloadsInProgressByUser={},this._dirty=!1,this._savePromise=null,this._resolveSavePromise=null,this._savePromiseTime=null,this._saveTimer=null}return(0,g.default)(e,[{key:"load",value:function(){function e(){return t.apply(this,arguments)}var t=(0,u.coroutine)(d.default.mark(function e(){var t,r,n,o,i,s,a,c=this;return d.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=!1,e.next=3,(0,u.resolve)(this._cryptoStore.doTxn("readwrite",[C.default.STORE_DEVICE_DATA],function(e){c._cryptoStore.getEndToEndDeviceData(e,function(r){null===r?(S.default.log("Migrating e2e device data..."),c._devices=c._sessionStore.getAllEndToEndDevices()||{},c._deviceTrackingStatus=c._sessionStore.getEndToEndDeviceTrackingStatus()||{},c._syncToken=c._sessionStore.getEndToEndDeviceSyncToken(),c._cryptoStore.storeEndToEndDeviceData({devices:c._devices,trackingStatus:c._deviceTrackingStatus,syncToken:c._syncToken},e),t=!0):(c._devices=r?r.devices:{},c._deviceTrackingStatus=r?r.trackingStatus:{},c._syncToken=r?r.syncToken:null),c._userByIdentityKey={};var n=!0,o=!1,i=void 0;try{for(var s,a=(0,v.default)((0,p.default)(c._devices));!(n=(s=a.next()).done);n=!0){var u=s.value,l=c._devices[u],d=!0,f=!1,h=void 0;try{for(var m,y=(0,v.default)((0,p.default)(l));!(d=(m=y.next()).done);d=!0){var _=m.value,g=l[_].keys["curve25519:"+_];void 0!==g&&(c._userByIdentityKey[g]=u)}}catch(e){f=!0,h=e}finally{try{!d&&y.return&&y.return()}finally{if(f)throw h}}}}catch(e){o=!0,i=e}finally{try{!n&&a.return&&a.return()}finally{if(o)throw i}}})}));case 3:for(t&&this._sessionStore.removeEndToEndDeviceData(),r=!0,n=!1,o=void 0,e.prev=7,i=(0,v.default)((0,p.default)(this._deviceTrackingStatus));!(r=(s=i.next()).done);r=!0)a=s.value,2==this._deviceTrackingStatus[a]&&(this._deviceTrackingStatus[a]=1);e.next=15;break;case 11:e.prev=11,e.t0=e.catch(7),n=!0,o=e.t0;case 15:e.prev=15,e.prev=16,!r&&i.return&&i.return();case 18:if(e.prev=18,!n){e.next=21;break}throw o;case 21:return e.finish(18);case 22:return e.finish(15);case 23:case"end":return e.stop()}},e,this,[[7,11,15,23],[16,,18,22]])}));return e}()},{key:"stop",value:function(){null!==this._saveTimer&&clearTimeout(this._saveTimer)}},{key:"saveIfDirty",value:function(){function e(e){return t.apply(this,arguments)}var t=(0,u.method)(function(e){var t=this;if(!this._dirty)return c.default.resolve(!1);void 0===e&&(e=500);var r=Date.now+e;this._savePromiseTime&&rb)throw new Error("Message too long ("+e.length+" bytes). The maximum for an encrypted message is "+b+" bytes.")}function i(e,t){this._sessionStore=e,this._cryptoStore=t,this._pickleKey="DEFAULT_KEY",this.deviceCurve25519Key=null,this.deviceEd25519Key=null,this._maxOneTimeKeys=null,this._outboundGroupSessionStore={},this._inboundGroupSessionMessageIndexes={}}var s=e("babel-runtime/core-js/object/assign"),a=n(s),u=e("babel-runtime/core-js/get-iterator"),c=n(u),l=e("babel-runtime/core-js/object/keys"),d=n(l),f=e("babel-runtime/regenerator"),p=n(f),h=e("bluebird"),v=function(){var e=(0,h.coroutine)(p.default.mark(function e(t,r,n,o){return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,(0,h.resolve)(r.doTxn("readwrite",[g.default.STORE_ACCOUNT],function(e){r.getAccount(e,function(t){null!==t?o.unpickle(n,t):(o.create(),t=o.pickle(n),r.storeAccount(e,t))})}));case 2:case"end":return e.stop()}},e,this)}));return function(t,r,n,o){return e.apply(this,arguments)}}(),m=e("../logger"),y=n(m),_=e("./store/indexeddb-crypto-store"),g=n(_),b=49152;i.prototype.init=(0,h.coroutine)(p.default.mark(function e(){var t,n;return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,(0,h.resolve)(this._migrateFromSessionStore());case 2:return t=void 0,n=new r.Olm.Account,e.prev=4,e.next=7,(0,h.resolve)(v(this._sessionStore,this._cryptoStore,this._pickleKey,n));case 7:t=JSON.parse(n.identity_keys()),this._maxOneTimeKeys=n.max_number_of_one_time_keys();case 9:return e.prev=9,n.free(),e.finish(9);case 12:this.deviceCurve25519Key=t.curve25519,this.deviceEd25519Key=t.ed25519;case 14:case"end":return e.stop()}},e,this,[[4,,9,12]])})),i.getOlmVersion=function(){return r.Olm.get_library_version()},i.prototype._migrateFromSessionStore=(0,h.coroutine)(p.default.mark(function e(){var t,r,n,o=this;return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,(0,h.resolve)(this._cryptoStore.doTxn("readwrite",[g.default.STORE_ACCOUNT],function(e){o._cryptoStore.getAccount(e,function(t){null===t&&null!==(t=o._sessionStore.getEndToEndAccount())&&(y.default.log("Migrating account from session store"),o._cryptoStore.storeAccount(e,t))})}));case 2:if(this._sessionStore.removeEndToEndAccount(),t=this._sessionStore.getAllEndToEndSessions(),!((0,d.default)(t).length>0)){e.next=8;break}return e.next=7,(0,h.resolve)(this._cryptoStore.doTxn("readwrite",[g.default.STORE_SESSIONS],function(e){o._cryptoStore.countEndToEndSessions(e,function(r){if(r)return void y.default.log("Crypto store already has sessions: not migrating");var n=0,i=!0,s=!1,a=void 0;try{for(var u,l=(0,c.default)((0,d.default)(t));!(i=(u=l.next()).done);i=!0){var f=u.value,p=!0,h=!1,v=void 0;try{for(var m,_=(0,c.default)((0,d.default)(t[f]));!(p=(m=_.next()).done);p=!0){var g=m.value;n++,o._cryptoStore.storeEndToEndSession(f,g,t[f][g],e)}}catch(e){h=!0,v=e}finally{try{!p&&_.return&&_.return()}finally{if(h)throw v}}}}catch(e){s=!0,a=e}finally{try{!i&&l.return&&l.return()}finally{if(s)throw a}}y.default.log("Migrating "+n+" sessions from session store")})}));case 7:this._sessionStore.removeAllEndToEndSessions();case 8:if(r=this._sessionStore.getAllEndToEndInboundGroupSessionKeys(),!((0,d.default)(r).length>0)){e.next=14;break}return n=0,e.next=13,(0,h.resolve)(this._cryptoStore.doTxn("readwrite",[g.default.STORE_INBOUND_GROUP_SESSIONS],function(e){var t=!0,i=!1,s=void 0;try{for(var a,u=(0,c.default)(r);!(t=(a=u.next()).done);t=!0){var l=a.value;try{o._cryptoStore.addEndToEndInboundGroupSession(l.senderKey,l.sessionId,JSON.parse(o._sessionStore.getEndToEndInboundGroupSession(l.senderKey,l.sessionId)),e)}catch(e){y.default.warn("Failed to migrate session "+l.senderKey+"/"+l.sessionId+": "+e.stack||e)}++n}}catch(e){i=!0,s=e}finally{try{!t&&u.return&&u.return()}finally{if(i)throw s}}y.default.log("Migrated "+n+" inbound group sessions from session store")}));case 13:this._sessionStore.removeAllEndToEndInboundGroupSessions();case 14:case"end":return e.stop()}},e,this)})),i.prototype._getAccount=function(e,t){var n=this;this._cryptoStore.getAccount(e,function(e){var o=new r.Olm.Account;try{o.unpickle(n._pickleKey,e),t(o)}finally{o.free()}})},i.prototype._storeAccount=function(e,t){this._cryptoStore.storeAccount(e,t.pickle(this._pickleKey))},i.prototype._getSession=function(e,t,r,n){var o=this;this._cryptoStore.getEndToEndSession(e,t,r,function(e){o._unpickleSession(e,n)})},i.prototype._unpickleSession=function(e,t){var n=new r.Olm.Session;try{n.unpickle(this._pickleKey,e.session);t((0,a.default)({},e,{session:n}))}finally{n.free()}},i.prototype._saveSession=function(e,t,r){var n=t.session.session_id(),o=(0,a.default)(t,{session:t.session.pickle(this._pickleKey)});this._cryptoStore.storeEndToEndSession(e,n,o,r)},i.prototype._getUtility=function(e){var t=new r.Olm.Utility;try{return e(t)}finally{t.free()}},i.prototype.sign=function(){var e=(0,h.coroutine)(p.default.mark(function e(t){var r,n=this;return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=void 0,e.next=3,(0,h.resolve)(this._cryptoStore.doTxn("readonly",[g.default.STORE_ACCOUNT],function(e){n._getAccount(e,function(e){r=e.sign(t)})}));case 3:return e.abrupt("return",r);case 4:case"end":return e.stop()}},e,this)}));return function(t){return e.apply(this,arguments)}}(),i.prototype.getOneTimeKeys=(0,h.coroutine)(p.default.mark(function e(){var t,r=this;return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=void 0,e.next=3,(0,h.resolve)(this._cryptoStore.doTxn("readonly",[g.default.STORE_ACCOUNT],function(e){r._getAccount(e,function(e){t=JSON.parse(e.one_time_keys())})}));case 3:return e.abrupt("return",t);case 4:case"end":return e.stop()}},e,this)})),i.prototype.maxNumberOfOneTimeKeys=function(){return this._maxOneTimeKeys},i.prototype.markKeysAsPublished=(0,h.coroutine)(p.default.mark(function e(){var t=this;return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,(0,h.resolve)(this._cryptoStore.doTxn("readwrite",[g.default.STORE_ACCOUNT],function(e){t._getAccount(e,function(r){r.mark_keys_as_published(),t._storeAccount(e,r)})}));case 2:case"end":return e.stop()}},e,this)})),i.prototype.generateOneTimeKeys=function(e){var t=this;return this._cryptoStore.doTxn("readwrite",[g.default.STORE_ACCOUNT],function(r){t._getAccount(r,function(n){n.generate_one_time_keys(e),t._storeAccount(r,n)})})},i.prototype.createOutboundSession=function(){var e=(0,h.coroutine)(p.default.mark(function e(t,n){var o,i=this;return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return o=void 0,e.next=3,(0,h.resolve)(this._cryptoStore.doTxn("readwrite",[g.default.STORE_ACCOUNT,g.default.STORE_SESSIONS],function(e){i._getAccount(e,function(s){var a=new r.Olm.Session;try{a.create_outbound(s,t,n),o=a.session_id(),i._storeAccount(e,s);var u={session:a,lastReceivedMessageTs:Date.now()};i._saveSession(t,u,e)}finally{a.free()}})}));case 3:return e.abrupt("return",o);case 4:case"end":return e.stop()}},e,this)}));return function(t,r){return e.apply(this,arguments)}}(),i.prototype.createInboundSession=function(){var e=(0,h.coroutine)(p.default.mark(function e(t,n,o){var i,s=this;return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(0===n){e.next=2;break}throw new Error("Need messageType == 0 to create inbound session");case 2:return i=void 0,e.next=5,(0,h.resolve)(this._cryptoStore.doTxn("readwrite",[g.default.STORE_ACCOUNT,g.default.STORE_SESSIONS],function(e){s._getAccount(e,function(a){var u=new r.Olm.Session;try{u.create_inbound_from(a,t,o),a.remove_one_time_keys(u),s._storeAccount(e,a);var c=u.decrypt(n,o),l={session:u,lastReceivedMessageTs:Date.now()};s._saveSession(t,l,e),i={payload:c,session_id:u.session_id()}}finally{u.free()}})}));case 5:return e.abrupt("return",i);case 6:case"end":return e.stop()}},e,this)}));return function(t,r,n){return e.apply(this,arguments)}}(),i.prototype.getSessionIdsForDevice=function(){var e=(0,h.coroutine)(p.default.mark(function e(t){var r,n=this;return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=void 0,e.next=3,(0,h.resolve)(this._cryptoStore.doTxn("readonly",[g.default.STORE_SESSIONS],function(e){n._cryptoStore.getEndToEndSessions(t,e,function(e){r=(0,d.default)(e)})}));case 3:return e.abrupt("return",r);case 4:case"end":return e.stop()}},e,this)}));return function(t){return e.apply(this,arguments)}}(),i.prototype.getSessionIdForDevice=function(){var e=(0,h.coroutine)(p.default.mark(function e(t){var r,n,o,i,s,a,u;return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,(0,h.resolve)(this.getSessionInfoForDevice(t));case 2:if(r=e.sent,0!==r.length){e.next=5;break}return e.abrupt("return",null);case 5:for(n=0,o=1;ou||s===u&&i.sessionId1&&void 0!==arguments[1]&&arguments[1];return this._cryptoStore.getOutgoingRoomKeyRequest(e).then(function(n){if(n)switch(n.state){case _.CANCELLATION_PENDING:case _.CANCELLATION_PENDING_AND_WILL_RESEND:return;case _.UNSENT:return v.default.log("deleting unnecessary room key request for "+o(e)),t._cryptoStore.deleteOutgoingRoomKeyRequest(n.requestId,_.UNSENT);case _.SENT:var i=r?_.CANCELLATION_PENDING_AND_WILL_RESEND:_.CANCELLATION_PENDING;return t._cryptoStore.updateOutgoingRoomKeyRequest(n.requestId,_.SENT,{state:i,cancellationTxnId:t._baseApis.makeTxnId()}).then(function(n){if(!n)return void v.default.log("Tried to cancel room key request for "+o(e)+" but it was already cancelled in another tab");t._sendOutgoingRoomKeyRequestCancellation(n,r).catch(function(e){v.default.error("Error sending room key request cancellation; will retry later.",e),t._startTimer()}).then(function(){r&&t._startTimer()})});default:throw new Error("unhandled state: "+n.state)}})}},{key:"getOutgoingSentRoomKeyRequest",value:function(e,t){return this._cryptoStore.getOutgoingRoomKeyRequestsByTarget(e,t,[_.SENT])}},{key:"_startTimer",value:function(){var e=this;if(!this._sendOutgoingRoomKeyRequestsTimer){var r=function(){if(e._sendOutgoingRoomKeyRequestsRunning)throw new Error("RoomKeyRequestSend already in progress!");e._sendOutgoingRoomKeyRequestsRunning=!0,e._sendOutgoingRoomKeyRequests().finally(function(){e._sendOutgoingRoomKeyRequestsRunning=!1}).catch(function(e){v.default.warn("error in OutgoingRoomKeyRequestManager: "+e)}).done()};this._sendOutgoingRoomKeyRequestsTimer=t.setTimeout(r,500)}}},{key:"_sendOutgoingRoomKeyRequests",value:function(){var e=this;return this._clientRunning?(v.default.log("Looking for queued outgoing room key requests"),this._cryptoStore.getOutgoingRoomKeyRequestByState([_.CANCELLATION_PENDING,_.CANCELLATION_PENDING_AND_WILL_RESEND,_.UNSENT]).then(function(t){if(!t)return v.default.log("No more outgoing room key requests"),void(e._sendOutgoingRoomKeyRequestsTimer=null);var r=void 0;switch(t.state){case _.UNSENT:r=e._sendOutgoingRoomKeyRequest(t);break;case _.CANCELLATION_PENDING:r=e._sendOutgoingRoomKeyRequestCancellation(t);break;case _.CANCELLATION_PENDING_AND_WILL_RESEND:r=e._sendOutgoingRoomKeyRequestCancellation(t,!0)}return r.then(function(){return e._sendOutgoingRoomKeyRequests()}).catch(function(t){v.default.error("Error sending room key request; will retry later.",t),e._sendOutgoingRoomKeyRequestsTimer=null,e._startTimer()}).done()})):(this._sendOutgoingRoomKeyRequestsTimer=null,p.default.resolve())}},{key:"_sendOutgoingRoomKeyRequest",value:function(e){var t=this;v.default.log("Requesting keys for "+o(e.requestBody)+" from "+i(e.recipients)+"(id "+e.requestId+")");var r={action:"request",requesting_device_id:this._deviceId,request_id:e.requestId,body:e.requestBody};return this._sendMessageToDevices(r,e.recipients,e.requestId).then(function(){return t._cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,_.UNSENT,{state:_.SENT})})}},{key:"_sendOutgoingRoomKeyRequestCancellation",value:function(e,t){var r=this;v.default.log("Sending cancellation for key request for "+o(e.requestBody)+" to "+i(e.recipients)+" (cancellation id "+e.cancellationTxnId+")");var n={action:"request_cancellation",requesting_device_id:this._deviceId,request_id:e.requestId};return this._sendMessageToDevices(n,e.recipients,e.cancellationTxnId).then(function(){return t?r._cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,_.CANCELLATION_PENDING_AND_WILL_RESEND,{state:_.UNSENT}):r._cryptoStore.deleteOutgoingRoomKeyRequest(e.requestId,_.CANCELLATION_PENDING)})}},{key:"_sendMessageToDevices",value:function(e,t,r){var n={},o=!0,i=!1,s=void 0;try{for(var u,c=(0,a.default)(t);!(o=(u=c.next()).done);o=!0){var l=u.value;n[l.userId]||(n[l.userId]={}),n[l.userId][l.deviceId]=e}}catch(e){i=!0,s=e}finally{try{!o&&c.return&&c.return()}finally{if(i)throw s}}return this._baseApis.sendToDevice("m.room_key_request",n,r)}}]),e}();r.default=g}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../logger":29,"../utils":55,"babel-runtime/core-js/get-iterator":58,"babel-runtime/helpers/classCallCheck":79,"babel-runtime/helpers/createClass":80,bluebird:89}],10:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(r,"__esModule",{value:!0});var o=e("babel-runtime/regenerator"),i=n(o),s=e("babel-runtime/core-js/get-iterator"),a=n(s),u=e("babel-runtime/core-js/object/keys"),c=n(u),l=e("bluebird"),d=e("babel-runtime/helpers/classCallCheck"),f=n(d),p=e("babel-runtime/helpers/createClass"),h=n(p),v=e("./store/indexeddb-crypto-store"),m=n(v),y=function(){function e(t,r){(0,f.default)(this,e),this._cryptoStore=t,this._sessionStore=r,this._roomEncryption={}}return(0,h.default)(e,[{key:"init",value:function(){function e(){return t.apply(this,arguments)}var t=(0,l.coroutine)(i.default.mark(function e(){var t,r=this;return i.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=!1,e.next=3,(0,l.resolve)(this._cryptoStore.doTxn("readwrite",[m.default.STORE_ROOMS],function(e){r._cryptoStore.getEndToEndRooms(e,function(n){if(null===n||0===(0,c.default)(n).length){var o=r._sessionStore.getAllEndToEndRooms();if(null!==o){var i=!0,s=!1,u=void 0;try{for(var l,d=(0,a.default)((0,c.default)(o));!(i=(l=d.next()).done);i=!0){var f=l.value;r._cryptoStore.storeEndToEndRoom(f,o[f],e)}}catch(e){s=!0,u=e}finally{try{!i&&d.return&&d.return()}finally{if(s)throw u}}}r._roomEncryption=o,t=!0}else r._roomEncryption=n})}));case 3:t&&this._sessionStore.removeAllEndToEndRooms();case 4:case"end":return e.stop()}},e,this)}));return e}()},{key:"getRoomEncryption",value:function(e){return this._roomEncryption[e]||null}},{key:"isRoomEncrypted",value:function(e){return Boolean(this.getRoomEncryption(e))}},{key:"setRoomEncryption",value:function(){function e(e,r){return t.apply(this,arguments)}var t=(0,l.coroutine)(i.default.mark(function e(t,r){var n=this;return i.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this._roomEncryption[t]=r,e.next=3,(0,l.resolve)(this._cryptoStore.doTxn("readwrite",[m.default.STORE_ROOMS],function(e){n._cryptoStore.storeEndToEndRoom(t,r,e)}));case 3:case"end":return e.stop()}},e,this)}));return e}()}]),e}();r.default=y},{"./store/indexeddb-crypto-store":21,"babel-runtime/core-js/get-iterator":58,"babel-runtime/core-js/object/keys":69,"babel-runtime/helpers/classCallCheck":79,"babel-runtime/helpers/createClass":80,"babel-runtime/regenerator":86,bluebird:89}],11:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r=e.name+"[msg: "+e.message;return t&&(r+=", "+(0,a.default)(t).map(function(e){return e+": "+t[e]}).join(", ")),r+="]"}function i(e,t,r){b[e]=t,E[e]=r}Object.defineProperty(r,"__esModule",{value:!0}),r.UnknownDeviceError=r.DecryptionError=r.DecryptionAlgorithm=r.EncryptionAlgorithm=r.DECRYPTION_CLASSES=r.ENCRYPTION_CLASSES=void 0;var s=e("babel-runtime/core-js/object/keys"),a=n(s),u=e("babel-runtime/core-js/object/get-prototype-of"),c=n(u),l=e("babel-runtime/helpers/possibleConstructorReturn"),d=n(l),f=e("babel-runtime/helpers/inherits"),p=n(f),h=e("babel-runtime/helpers/classCallCheck"),v=n(h),m=e("babel-runtime/helpers/createClass"),y=n(m);r.registerAlgorithm=i;var _=e("bluebird"),g=n(_),b=r.ENCRYPTION_CLASSES={},E=r.DECRYPTION_CLASSES={},w=function(){function e(t){(0,v.default)(this,e),this._userId=t.userId,this._deviceId=t.deviceId,this._crypto=t.crypto,this._olmDevice=t.olmDevice,this._baseApis=t.baseApis,this._roomId=t.roomId}return(0,y.default)(e,[{key:"onRoomMembership",value:function(e,t,r){}}]),e}();r.EncryptionAlgorithm=w;var S=function(){function e(t){(0,v.default)(this,e),this._userId=t.userId,this._crypto=t.crypto,this._olmDevice=t.olmDevice,this._baseApis=t.baseApis,this._roomId=t.roomId}return(0,y.default)(e,[{key:"onRoomKeyEvent",value:function(e){}},{key:"importRoomKey",value:function(e){}},{key:"hasKeysForKeyRequest",value:function(e){return g.default.resolve(!1)}},{key:"shareKeysWithDevice",value:function(e){throw new Error("shareKeysWithDevice not supported for this DecryptionAlgorithm")}}]),e}();r.DecryptionAlgorithm=S;var k=function(e){function t(e,r,n){(0,v.default)(this,t);var i=(0,d.default)(this,(t.__proto__||(0,c.default)(t)).call(this,r));return i.code=e,i.name="DecryptionError",i.detailedString=o(i,n),i}return(0,p.default)(t,e),t}(Error);r.DecryptionError=k;r.UnknownDeviceError=function(e){function t(e,r){(0,v.default)(this,t);var n=(0,d.default)(this,(t.__proto__||(0,c.default)(t)).call(this,e));return n.name="UnknownDeviceError",n.devices=r,n}return(0,p.default)(t,e),t}(Error)},{"babel-runtime/core-js/object/get-prototype-of":68,"babel-runtime/core-js/object/keys":69,"babel-runtime/helpers/classCallCheck":79,"babel-runtime/helpers/createClass":80,"babel-runtime/helpers/inherits":82,"babel-runtime/helpers/possibleConstructorReturn":83,bluebird:89}],12:[function(e,t,r){"use strict";var n=e("./base");e("./olm"),e("./megolm"),t.exports.ENCRYPTION_CLASSES=n.ENCRYPTION_CLASSES,t.exports.DECRYPTION_CLASSES=n.DECRYPTION_CLASSES,t.exports.DecryptionError=n.DecryptionError},{"./base":11,"./megolm":13,"./olm":14}],13:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){this.sessionId=e,this.useCount=0,this.creationTime=(new Date).getTime(),this.sharedWithDevices={}}function i(e){k.EncryptionAlgorithm.call(this,e),this._setupPromise=b.default.resolve(),this._outboundSessions={},this._sessionRotationPeriodMsgs=100,this._sessionRotationPeriodMs=6048e5,void 0!==e.config.rotation_period_ms&&(this._sessionRotationPeriodMs=e.config.rotation_period_ms),void 0!==e.config.rotation_period_msgs&&(this._sessionRotationPeriodMsgs=e.config.rotation_period_msgs)}function s(e){k.DecryptionAlgorithm.call(this,e),this._pendingEvents={},this.olmlib=S}var a=e("babel-runtime/core-js/set"),u=n(a),c=e("babel-runtime/core-js/json/stringify"),l=n(c),d=e("babel-runtime/helpers/defineProperty"),f=n(d),p=e("babel-runtime/core-js/object/keys"),h=n(p),v=e("babel-runtime/core-js/get-iterator"),m=n(v),y=e("babel-runtime/regenerator"),_=n(y),g=e("bluebird"),b=n(g),E=e("../../logger"),w=e("../../utils"),S=e("../olmlib"),k=e("./base");o.prototype.needsRotation=function(e,t){var r=(new Date).getTime()-this.creationTime;return(this.useCount>=e||r>=t)&&(E.log("Rotating megolm session after "+this.useCount+" messages, "+r+"ms"),!0)},o.prototype.markSharedWithDevice=function(e,t,r){this.sharedWithDevices[e]||(this.sharedWithDevices[e]={}),this.sharedWithDevices[e][t]=r},o.prototype.sharedWithTooManyDevices=function(e){for(var t in this.sharedWithDevices)if(this.sharedWithDevices.hasOwnProperty(t)){if(!e.hasOwnProperty(t))return E.log("Starting new session because we shared with "+t),!0;for(var r in this.sharedWithDevices[t])if(this.sharedWithDevices[t].hasOwnProperty(r)&&!e[t].hasOwnProperty(r))return E.log("Starting new session because we shared with "+t+":"+r),!0}},w.inherits(i,k.EncryptionAlgorithm),i.prototype._ensureOutboundSession=function(e){function t(){return o}var r=function(){var t=(0,g.coroutine)(_.default.mark(function t(r){var i,s,a,u,c,l;return _.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(o=r,o&&o.needsRotation(n._sessionRotationPeriodMsgs,n._sessionRotationPeriodMs)&&(E.log("Starting new megolm session because we need to rotate."),o=null),o&&o.sharedWithTooManyDevices(e)&&(o=null),o){t.next=9;break}return E.log("Starting new megolm session for room "+n._roomId),t.next=7,(0,g.resolve)(n._prepareNewSession());case 7:o=t.sent,n._outboundSessions[o.sessionId]=o;case 9:i={},t.t0=_.default.keys(e);case 11:if((t.t1=t.t0()).done){t.next=30;break}if(s=t.t1.value,e.hasOwnProperty(s)){t.next=15;break}return t.abrupt("continue",11);case 15:a=e[s],t.t2=_.default.keys(a);case 17:if((t.t3=t.t2()).done){t.next=28;break}if(u=t.t3.value,a.hasOwnProperty(u)){t.next=21;break}return t.abrupt("continue",17);case 21:if(c=a[u],(l=c.getIdentityKey())!=n._olmDevice.deviceCurve25519Key){t.next=25;break}return t.abrupt("continue",17);case 25:o.sharedWithDevices[s]&&void 0!==o.sharedWithDevices[s][u]||(i[s]=i[s]||[],i[s].push(c)),t.next=17;break;case 28:t.next=11;break;case 30:return t.abrupt("return",n._shareKeyWithDevices(o,i));case 31:case"end":return t.stop()}},t,this)}));return function(e){return t.apply(this,arguments)}}(),n=this,o=void 0,i=this._setupPromise.then(r);return this._setupPromise=i.then(t,t),i.then(t)},i.prototype._prepareNewSession=(0,g.coroutine)(_.default.mark(function e(){var t,r;return _.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=this._olmDevice.createOutboundGroupSession(),r=this._olmDevice.getOutboundGroupSessionKey(t),e.next=4,(0,g.resolve)(this._olmDevice.addInboundGroupSession(this._roomId,this._olmDevice.deviceCurve25519Key,[],t,r.key,{ed25519:this._olmDevice.deviceEd25519Key}));case 4:return this._crypto.backupInfo&&this._crypto.backupGroupSession(this._roomId,this._olmDevice.deviceCurve25519Key,[],t,r.key).catch(function(e){console.log("Failed to back up group session",e)}),e.abrupt("return",new o(t));case 6:case"end":return e.stop()}},e,this)})),i.prototype._splitUserDeviceMap=function(e,t,r,n){var o=[],i=0,s=0,a=!0,u=!1,c=void 0;try{for(var l,d=(0,m.default)((0,h.default)(n));!(a=(l=d.next()).done);a=!0)for(var f=l.value,p=n[f],v=r[f],y=0;y20&&(s=0,i++),o[i]||(o[i]=[]),o[i].push({userId:f,deviceInfo:_}),s++):e.markSharedWithDevice(f,g,t)}}catch(e){u=!0,c=e}finally{try{!a&&d.return&&d.return()}finally{if(u)throw c}}return o},i.prototype._encryptAndSendKeysToDevices=function(e,t,r,n){for(var o=this,i={algorithm:S.OLM_ALGORITHM,sender_key:this._olmDevice.deviceCurve25519Key,ciphertext:{}},s={},a=[],u=0;u0)return null;var n=this._deviceList.getDeviceByIdentityKey(r,t);if(null===n)return null;var o=e.getClaimedEd25519Key();return o?o!==n.getFingerprint()?(M.warn("Event "+e.getId()+" claims ed25519 key "+o+"but sender device has key "+n.getFingerprint()),null):n:(M.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),null)},i.prototype.forceDiscardSession=function(e){var t=this._roomEncryptors[e];if(void 0===t)throw new Error("Room not encrypted");if(void 0===t.forceDiscardSession)throw new Error("Room encryption algorithm doesn't support session discarding");t.forceDiscardSession()},i.prototype.setRoomEncryption=function(){var e=(0,g.coroutine)(x.default.mark(function e(t,r,n){var o,i,s,a,u;return x.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!(o=this._roomList.getRoomEncryption(t))){e.next=5;break}if((0,_.default)(o)==(0,_.default)(r)){e.next=5;break}return M.error("Ignoring m.room.encryption event which requests a change of config in "+t),e.abrupt("return");case 5:if(!(i=this._roomEncryptors[t])){e.next=8;break}return e.abrupt("return");case 8:if(s=null,o||(s=this._roomList.setRoomEncryption(t,r)),a=N.ENCRYPTION_CLASSES[r.algorithm]){e.next=13;break}throw new Error("Unable to encrypt with "+r.algorithm);case 13:if(u=new a({userId:this._userId,deviceId:this._deviceId,crypto:this,olmDevice:this._olmDevice,baseApis:this._baseApis,roomId:t,config:r}),this._roomEncryptors[t]=u,!s){e.next=18;break}return e.next=18,(0,g.resolve)(s);case 18:if(this._lazyLoadMembers){e.next=25;break}return M.log("Enabling encryption in "+t+"; starting to track device lists for all users therein"),e.next=22,(0,g.resolve)(this.trackRoomDevices(t));case 22:this.inhibitDeviceQuery||this._deviceList.refreshOutdatedDeviceLists(),e.next=26;break;case 25:M.log("Enabling encryption in "+t);case 26:case"end":return e.stop()}},e,this)}));return function(t,r,n){return e.apply(this,arguments)}}(),i.prototype.trackRoomDevices=function(e){var t=this,r=function(){var r=(0,g.coroutine)(x.default.mark(function r(){var n,o;return x.default.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:if(t._roomEncryptors[e]){r.next=2;break}return r.abrupt("return");case 2:if(n=t._clientStore.getRoom(e)){r.next=5;break}throw new Error("Unable to start tracking devices in unknown room "+e);case 5:return M.log("Starting to track devices for room "+e+" ..."),r.next=8,(0,g.resolve)(n.getEncryptionTargetMembers());case 8:o=r.sent,o.forEach(function(e){t._deviceList.startTrackingDeviceList(e.userId)});case 10:case"end":return r.stop()}},r,t)}));return function(){return r.apply(this,arguments)}}(),n=this._roomDeviceTrackingState[e];return n||(n=r(),this._roomDeviceTrackingState[e]=n),n},i.prototype.ensureOlmSessionsForUsers=function(e){for(var t={},r=0;rDate.now())){e.next=11;break}return M.debug("New session already forced with device "+n+":"+i+" at "+s+": not forcing another"),e.abrupt("return");case 11:if(a=this._deviceList.getDeviceByIdentityKey(o,i)){e.next=15;break}return M.info("Couldn't find device for identity key "+i+": not re-establishing session"),e.abrupt("return");case 15:return u={},u[n]=[a],e.next=19,(0,g.resolve)(U.ensureOlmSessionsForDevices(this._olmDevice,this._baseApis,u,!0));case 19:return this._lastNewSessionForced[n][i]=Date.now(),c={algorithm:U.OLM_ALGORITHM,sender_key:this._olmDevice.deviceCurve25519Key,ciphertext:{}},e.next=23,(0,g.resolve)(U.encryptMessageForDevice(c.ciphertext,this._userId,this._deviceId,this._olmDevice,n,a,{type:"m.dummy"}));case 23:return e.next=25,(0,g.resolve)(this._baseApis.sendToDevice("m.room.encrypted",(0,l.default)({},n,(0,l.default)({},a.deviceId,c))));case 25:return e.next=27,(0,g.resolve)(this._outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(n,a.deviceId));case 27:for(d=e.sent,f=!0,p=!1,h=void 0,e.prev=31,v=(0,k.default)(d);!(f=(m=v.next()).done);f=!0)y=m.value,this.cancelRoomKeyRequest(y.requestBody,!0);e.next=39;break;case 35:e.prev=35,e.t0=e.catch(31),p=!0,h=e.t0;case 39:e.prev=39,e.prev=40,!f&&v.return&&v.return();case 42:if(e.prev=42,!p){e.next=45;break}throw h;case 45:return e.finish(42);case 46:return e.finish(39);case 47:case"end":return e.stop()}},e,this,[[31,35,39,47],[40,,42,46]])}));return function(t){return e.apply(this,arguments)}}(),i.prototype._onRoomMembership=function(e,t,r){var n=t.roomId,o=this._roomEncryptors[n];o&&(this._roomDeviceTrackingState[n]&&("join"==t.membership?(M.log("Join event for "+t.userId+" in "+n),this._deviceList.startTrackingDeviceList(t.userId)):"invite"==t.membership&&this._clientStore.getRoom(n).shouldEncryptForInvitedMembers()&&(M.log("Invite event for "+t.userId+" in "+n),this._deviceList.startTrackingDeviceList(t.userId))),o.onRoomMembership(e,t,r))},i.prototype._onRoomKeyRequestEvent=function(e){var t=e.getContent();if("request"===t.action){var r=new K(e);this._receivedRoomKeyRequests.push(r)}else if("request_cancellation"===t.action){var n=new G(e);this._receivedRoomKeyRequestCancellations.push(n)}},i.prototype._processReceivedRoomKeyRequests=(0,g.coroutine)(x.default.mark(function e(){var t,r,n=this;return x.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this._processingRoomKeyRequests){e.next=2;break}return e.abrupt("return");case 2:return this._processingRoomKeyRequests=!0,e.prev=3,t=this._receivedRoomKeyRequests,this._receivedRoomKeyRequests=[],r=this._receivedRoomKeyRequestCancellations,this._receivedRoomKeyRequestCancellations=[],e.next=10,(0,g.resolve)(b.default.map(t,function(e){return n._processReceivedRoomKeyRequest(e)}));case 10:return e.next=12,(0,g.resolve)(b.default.map(r,function(e){return n._processReceivedRoomKeyRequestCancellation(e)}));case 12:e.next=17;break;case 14:e.prev=14,e.t0=e.catch(3),M.error("Error processing room key requsts: "+e.t0);case 17:return e.prev=17,this._processingRoomKeyRequests=!1,e.finish(17);case 20:case"end":return e.stop()}},e,this,[[3,14,17,20]])})),i.prototype._processReceivedRoomKeyRequest=function(){var e=(0,g.coroutine)(x.default.mark(function e(t){var r,n,o,i,s,a,u,c,l;return x.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t.userId,n=t.deviceId,o=t.requestBody,i=o.room_id,s=o.algorithm,M.log("m.room_key_request from "+r+":"+n+" for "+i+" / "+o.session_id+" (id "+t.requestId+")"),r===this._userId){e.next=24;break}if(this._roomEncryptors[i]){e.next=10;break}return M.debug("room key request for unencrypted room "+i),e.abrupt("return");case 10:if(a=this._roomEncryptors[i],u=this._deviceList.getStoredDevice(r,n)){e.next=15;break}return M.debug("Ignoring keyshare for unknown device "+r+":"+n),e.abrupt("return");case 15:return e.prev=15,e.next=18,(0,g.resolve)(a.reshareKeyWithDevice(o.sender_key,o.session_id,r,u));case 18:e.next=23;break;case 20:e.prev=20, +e.t0=e.catch(15),M.warn("Failed to re-share keys for session "+o.session_id+" with device "+r+":"+u.deviceId,e.t0);case 23:return e.abrupt("return");case 24:if(this._roomDecryptors[i]){e.next=27;break}return M.log("room key request for unencrypted room "+i),e.abrupt("return");case 27:if(c=this._roomDecryptors[i][s]){e.next=31;break}return M.log("room key request for unknown alg "+s+" in room "+i),e.abrupt("return");case 31:return e.next=33,(0,g.resolve)(c.hasKeysForKeyRequest(t));case 33:if(e.sent){e.next=36;break}return M.log("room key request for unknown session "+i+" / "+o.session_id),e.abrupt("return");case 36:if(t.share=function(){c.shareKeysWithDevice(t)},!(l=this._deviceList.getStoredDevice(r,n))||!l.isVerified()){e.next=42;break}return M.log("device is already verified: sharing keys"),t.share(),e.abrupt("return");case 42:this.emit("crypto.roomKeyRequest",t);case 43:case"end":return e.stop()}},e,this,[[15,20]])}));return function(t){return e.apply(this,arguments)}}(),i.prototype._processReceivedRoomKeyRequestCancellation=function(){var e=(0,g.method)(function(e){M.log("m.room_key_request cancellation for "+e.userId+":"+e.deviceId+" (id "+e.requestId+")"),this.emit("crypto.roomKeyRequestCancellation",e)});return function(t){return e.apply(this,arguments)}}(),i.prototype._getRoomDecryptor=function(e,t){var r=void 0,n=void 0;if((e=e||null)&&(r=this._roomDecryptors[e],r||(this._roomDecryptors[e]=r={}),n=r[t]))return n;var o=N.DECRYPTION_CLASSES[t];if(!o)throw new N.DecryptionError("UNKNOWN_ENCRYPTION_ALGORITHM",'Unknown encryption algorithm "'+t+'".');return n=new o({userId:this._userId,crypto:this,olmDevice:this._olmDevice,baseApis:this._baseApis,roomId:e}),r&&(r[t]=n),n},i.prototype._signObject=function(){var e=(0,g.coroutine)(x.default.mark(function e(t){var r;return x.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r={},r[this._userId]={},e.next=4,(0,g.resolve)(this._olmDevice.sign(D.stringify(t)));case 4:r[this._userId]["ed25519:"+this._deviceId]=e.sent,t.signatures=r;case 6:case"end":return e.stop()}},e,this)}));return function(t){return e.apply(this,arguments)}}();var K=function e(t){(0,u.default)(this,e);var r=t.getContent();this.userId=t.getSender(),this.deviceId=r.requesting_device_id,this.requestId=r.request_id,this.requestBody=r.body||{},this.share=function(){throw new Error("don't know how to share keys for this request yet")}},G=function e(t){(0,u.default)(this,e);var r=t.getContent();this.userId=t.getSender(),this.deviceId=r.requesting_device_id,this.requestId=r.request_id}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../logger":29,"../utils":55,"./DeviceList":7,"./OlmDevice":8,"./OutgoingRoomKeyRequestManager":9,"./algorithms":12,"./deviceinfo":16,"./olmlib":18,"./store/indexeddb-crypto-store":21,"another-json":57,"babel-runtime/core-js/get-iterator":58,"babel-runtime/core-js/json/stringify":60,"babel-runtime/core-js/object/assign":63,"babel-runtime/core-js/object/keys":69,"babel-runtime/core-js/set":76,"babel-runtime/helpers/classCallCheck":79,"babel-runtime/helpers/defineProperty":81,"babel-runtime/helpers/typeof":85,"babel-runtime/regenerator":86,bluebird:89,events:234}],18:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}var o=e("bluebird"),i=n(o),s=e("babel-runtime/regenerator"),a=n(s),u=e("babel-runtime/core-js/json/stringify"),c=n(u),l=function(){var e=(0,o.coroutine)(a.default.mark(function e(t,r,n,i){var s,u;return a.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return s=i.deviceId,e.prev=1,e.next=4,(0,o.resolve)(h(t,r,n,s,i.getFingerprint()));case 4:e.next=10;break;case 6:return e.prev=6,e.t0=e.catch(1),f.error("Unable to verify signature on one-time key for device "+n+":"+s+":",e.t0),e.abrupt("return",null);case 10:return u=void 0,e.prev=11,e.next=14,(0,o.resolve)(t.createOutboundSession(i.getIdentityKey(),r.key));case 14:u=e.sent,e.next=21;break;case 17:return e.prev=17,e.t1=e.catch(11),f.error("Error starting session with device "+n+":"+s+": "+e.t1),e.abrupt("return",null);case 21:return f.log("Started new sessionid "+u+" for device "+n+":"+s),e.abrupt("return",u);case 23:case"end":return e.stop()}},e,this,[[1,6],[11,17]])}));return function(t,r,n,o){return e.apply(this,arguments)}}(),d=e("another-json"),f=e("../logger"),p=e("../utils");t.exports.OLM_ALGORITHM="m.olm.v1.curve25519-aes-sha2",t.exports.MEGOLM_ALGORITHM="m.megolm.v1.aes-sha2",t.exports.MEGOLM_BACKUP_ALGORITHM="m.megolm_backup.v1.curve25519-aes-sha2",t.exports.encryptMessageForDevice=function(){var e=(0,o.coroutine)(a.default.mark(function e(t,r,n,i,s,u,l){var d,h,v;return a.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return d=u.getIdentityKey(),e.next=3,(0,o.resolve)(i.getSessionIdForDevice(d));case 3:if(null!==(h=e.sent)){e.next=6;break}return e.abrupt("return");case 6:return f.log("Using sessionid "+h+" for device "+s+":"+u.deviceId),v={sender:r,sender_device:n,keys:{ed25519:i.deviceEd25519Key},recipient:s,recipient_keys:{ed25519:u.getFingerprint()}},p.extend(v,l),e.next=11,(0,o.resolve)(i.encryptMessage(d,h,(0,c.default)(v)));case 11:t[d]=e.sent;case 12:case"end":return e.stop()}},e,this)}));return function(t,r,n,o,i,s,a){return e.apply(this,arguments)}}(),t.exports.ensureOlmSessionsForDevices=function(){var e=(0,o.coroutine)(a.default.mark(function e(t,r,n,s){var u,c,d,p,h,v,m,y,_,g,b,E,w,S,k,T;return a.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:u=[],c={},e.t0=a.default.keys(n);case 3:if((e.t1=e.t0()).done){e.next=24;break}if(d=e.t1.value,n.hasOwnProperty(d)){e.next=7;break}return e.abrupt("continue",3);case 7:c[d]={},p=n[d],h=0;case 10:if(!(h=e.length)){var s=e[r];o.target.source.openCursor(s).onsuccess=t}}if(0===e.length)return v.default.resolve(null);var r=0,n=void 0,o=this._db.transaction("outgoingRoomKeyRequests","readonly"),i=o.objectStore("outgoingRoomKeyRequests"),s=e[r];return i.index("state").openCursor(s).onsuccess=t,a(o).then(function(){return n})}},{key:"getOutgoingRoomKeyRequestsByTarget",value:function(e,t,r){function n(s){var a=s.target.result;if(a){var u=a.value;u.recipients.includes({userId:e,deviceId:t})&&i.push(u),a.continue()}else{if(++o>=r.length)return;var c=r[o];s.target.source.openCursor(c).onsuccess=n}}var o=0,i=[],s=this._db.transaction("outgoingRoomKeyRequests","readonly"),u=s.objectStore("outgoingRoomKeyRequests"),c=r[o];return u.index("state").openCursor(c).onsuccess=n,a(s).then(function(){return i})}},{key:"updateOutgoingRoomKeyRequest",value:function(e,t,r){function n(e){var n=e.target.result;if(n){var i=n.value;if(i.state!=t)return void y.default.warn("Cannot update room key request from "+t+" as it was already updated to "+i.state);(0,c.default)(i,r),n.update(i),o=i}}var o=null,i=this._db.transaction("outgoingRoomKeyRequests","readwrite");return i.objectStore("outgoingRoomKeyRequests").openCursor(e).onsuccess=n,a(i).then(function(){return o})}},{key:"deleteOutgoingRoomKeyRequest",value:function(e,t){var r=this._db.transaction("outgoingRoomKeyRequests","readwrite");return r.objectStore("outgoingRoomKeyRequests").openCursor(e).onsuccess=function(e){var r=e.target.result;if(r){var n=r.value;if(n.state!=t)return void y.default.warn("Cannot delete room key request in state "+n.state+" (expected "+t+")");r.delete()}},a(r)}},{key:"getAccount",value:function(e,t){var r=e.objectStore("account"),n=r.get("-");n.onsuccess=function(){try{t(n.result||null)}catch(t){s(e,t)}}}},{key:"storeAccount",value:function(e,t){e.objectStore("account").put(t,"-")}},{key:"countEndToEndSessions",value:function(e,t){var r=e.objectStore("sessions"),n=r.count();n.onsuccess=function(){t(n.result)}}},{key:"getEndToEndSessions",value:function(e,t,r){var n=t.objectStore("sessions"),o=n.index("deviceKey"),i=o.openCursor(e),a={};i.onsuccess=function(){var e=i.result;if(e)a[e.value.sessionId]={session:e.value.session,lastReceivedMessageTs:e.value.lastReceivedMessageTs},e.continue();else try{r(a)}catch(e){s(t,e)}}}},{key:"getEndToEndSession",value:function(e,t,r,n){var o=r.objectStore("sessions"),i=o.get([e,t]);i.onsuccess=function(){try{n(i.result?{session:i.result.session,lastReceivedMessageTs:i.result.lastReceivedMessageTs}:null)}catch(e){s(r,e)}}}},{key:"getAllEndToEndSessions",value:function(e,t){var r=e.objectStore("sessions"),n=r.openCursor();n.onsuccess=function(){var r=n.result;if(r)t(r.value),r.continue();else try{t(null)}catch(t){s(e,t)}}}},{key:"storeEndToEndSession",value:function(e,t,r,n){n.objectStore("sessions").put({deviceKey:e,sessionId:t,session:r.session,lastReceivedMessageTs:r.lastReceivedMessageTs})}},{key:"getEndToEndInboundGroupSession",value:function(e,t,r,n){var o=r.objectStore("inbound_group_sessions"),i=o.get([e,t]);i.onsuccess=function(){try{n(i.result?i.result.session:null)}catch(e){s(r,e)}}}},{key:"getAllEndToEndInboundGroupSessions",value:function(e,t){var r=e.objectStore("inbound_group_sessions"),n=r.openCursor();n.onsuccess=function(){var r=n.result;if(r){try{t({senderKey:r.value.senderCurve25519Key,sessionId:r.value.sessionId,sessionData:r.value.session})}catch(t){s(e,t)}r.continue()}else try{t(null)}catch(t){s(e,t)}}}},{key:"addEndToEndInboundGroupSession",value:function(e,t,r,n){var o=n.objectStore("inbound_group_sessions"),i=o.add({senderCurve25519Key:e,sessionId:t,session:r});i.onerror=function(r){"ConstraintError"===i.error.name?(r.stopPropagation(),r.preventDefault(),y.default.log("Ignoring duplicate inbound group session: "+e+" / "+t)):s(n,new Error("Failed to add inbound group session: "+i.error))}}},{key:"storeEndToEndInboundGroupSession",value:function(e,t,r,n){n.objectStore("inbound_group_sessions").put({senderCurve25519Key:e,sessionId:t,session:r})}},{key:"getEndToEndDeviceData",value:function(e,t){var r=e.objectStore("device_data"),n=r.get("-");n.onsuccess=function(){try{t(n.result||null)}catch(t){s(e,t)}}}},{key:"storeEndToEndDeviceData",value:function(e,t){t.objectStore("device_data").put(e,"-")}},{key:"storeEndToEndRoom",value:function(e,t,r){r.objectStore("rooms").put(t,e)}},{key:"getEndToEndRooms",value:function(e,t){var r={},n=e.objectStore("rooms"),o=n.openCursor();o.onsuccess=function(){var n=o.result;if(n)r[n.key]=n.value,n.continue();else try{t(r)}catch(t){s(e,t)}}}},{key:"getSessionsNeedingBackup",value:function(e){var t=this;return new v.default(function(r,n){var o=[],i=t._db.transaction(["sessions_needing_backup","inbound_group_sessions"],"readonly");i.onerror=n,i.oncomplete=function(){r(o)};var s=i.objectStore("sessions_needing_backup"),a=i.objectStore("inbound_group_sessions"),u=s.openCursor();u.onsuccess=function(){var t=u.result;if(t){var r=a.get(t.key);r.onsuccess=function(){o.push({senderKey:r.result.senderCurve25519Key,sessionId:r.result.sessionId,sessionData:r.result.session})},(!e||o.length=e)return"break"}();if("break"===i)break}return I.default.resolve(n)}},{key:"unmarkSessionsNeedingBackup",value:function(e){var t=a(this.store,N)||{},r=!0,n=!1,o=void 0;try{for(var i,s=(0,m.default)(e);!(r=(i=s.next()).done);r=!0){var c=i.value;delete t[c.senderKey+"/"+c.sessionId]}}catch(e){n=!0,o=e}finally{try{!r&&s.return&&s.return()}finally{if(n)throw o}}return u(this.store,N,t),I.default.resolve()}},{key:"markSessionsNeedingBackup",value:function(e){var t=a(this.store,N)||{},r=!0,n=!1,o=void 0;try{for(var i,s=(0,m.default)(e);!(r=(i=s.next()).done);r=!0){var c=i.value;t[c.senderKey+"/"+c.sessionId]=!0}}catch(e){n=!0,o=e}finally{try{!r&&s.return&&s.return()}finally{if(n)throw o}}return u(this.store,N,t),I.default.resolve()}},{key:"deleteAllData",value:function(){return this.store.removeItem(M),I.default.resolve()}},{key:"getAccount",value:function(e,t){t(a(this.store,M))}},{key:"storeAccount",value:function(e,t){u(this.store,M,t)}},{key:"doTxn",value:function(e,t,r){return I.default.resolve(r(null))}}]),t}(A.default);r.default=F},{"../../logger":29,"./memory-crypto-store.js":23,"babel-runtime/core-js/get-iterator":58,"babel-runtime/core-js/json/stringify":60,"babel-runtime/core-js/object/entries":66,"babel-runtime/core-js/object/get-prototype-of":68,"babel-runtime/helpers/classCallCheck":79,"babel-runtime/helpers/createClass":80,"babel-runtime/helpers/inherits":82,"babel-runtime/helpers/possibleConstructorReturn":83,"babel-runtime/helpers/slicedToArray":84,bluebird:89}],23:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(r,"__esModule",{value:!0});var o=e("babel-runtime/core-js/object/keys"),i=n(o),s=e("babel-runtime/core-js/object/assign"),a=n(s),u=e("babel-runtime/core-js/get-iterator"),c=n(u),l=e("babel-runtime/helpers/classCallCheck"),d=n(l),f=e("babel-runtime/helpers/createClass"),p=n(f),h=e("bluebird"),v=n(h),m=e("../../logger"),y=n(m),_=e("../../utils"),g=n(_),b=function(){function e(){(0,d.default)(this,e),this._outgoingRoomKeyRequests=[],this._account=null,this._sessions={},this._inboundGroupSessions={},this._deviceData=null,this._rooms={},this._sessionsNeedingBackup={}}return(0,p.default)(e,[{key:"deleteAllData",value:function(){return v.default.resolve()}},{key:"getOrAddOutgoingRoomKeyRequest",value:function(e){var t=this,r=e.requestBody;return v.default.try(function(){var n=t._getOutgoingRoomKeyRequest(r);return n?(y.default.log("already have key request outstanding for "+r.room_id+" / "+r.session_id+": not sending another"),n):(y.default.log("enqueueing key request for "+r.room_id+" / "+r.session_id),t._outgoingRoomKeyRequests.push(e),e)})}},{key:"getOutgoingRoomKeyRequest",value:function(e){return v.default.resolve(this._getOutgoingRoomKeyRequest(e))}},{key:"_getOutgoingRoomKeyRequest",value:function(e){var t=!0,r=!1,n=void 0;try{for(var o,i=(0,c.default)(this._outgoingRoomKeyRequests);!(t=(o=i.next()).done);t=!0){var s=o.value;if(g.default.deepCompare(s.requestBody,e))return s}}catch(e){r=!0,n=e}finally{try{!t&&i.return&&i.return()}finally{if(r)throw n}}return null}},{key:"getOutgoingRoomKeyRequestByState",value:function(e){var t=!0,r=!1,n=void 0;try{for(var o,i=(0,c.default)(this._outgoingRoomKeyRequests);!(t=(o=i.next()).done);t=!0){var s=o.value,a=!0,u=!1,l=void 0;try{for(var d,f=(0,c.default)(e);!(a=(d=f.next()).done);a=!0){var p=d.value;if(s.state===p)return v.default.resolve(s)}}catch(e){u=!0,l=e}finally{try{!a&&f.return&&f.return()}finally{if(u)throw l}}}}catch(e){r=!0,n=e}finally{try{!t&&i.return&&i.return()}finally{if(r)throw n}}return v.default.resolve(null)}},{key:"getOutgoingRoomKeyRequestsByTarget",value:function(e,t,r){var n=[],o=!0,i=!1,s=void 0;try{for(var a,u=(0,c.default)(this._outgoingRoomKeyRequests);!(o=(a=u.next()).done);o=!0){var l=a.value,d=!0,f=!1,p=void 0;try{for(var h,m=(0,c.default)(r);!(d=(h=m.next()).done);d=!0){var y=h.value;l.state===y&&l.recipients.includes({userId:e,deviceId:t})&&n.push(l)}}catch(e){f=!0,p=e}finally{try{!d&&m.return&&m.return()}finally{if(f)throw p}}}}catch(e){i=!0,s=e}finally{try{!o&&u.return&&u.return()}finally{if(i)throw s}}return v.default.resolve(n)}},{key:"updateOutgoingRoomKeyRequest",value:function(e,t,r){var n=!0,o=!1,i=void 0;try{for(var s,u=(0,c.default)(this._outgoingRoomKeyRequests);!(n=(s=u.next()).done);n=!0){var l=s.value;if(l.requestId===e)return l.state!=t?(y.default.warn("Cannot update room key request from "+t+" as it was already updated to "+l.state),v.default.resolve(null)):((0,a.default)(l,r),v.default.resolve(l))}}catch(e){o=!0,i=e}finally{try{!n&&u.return&&u.return()}finally{if(o)throw i}}return v.default.resolve(null)}},{key:"deleteOutgoingRoomKeyRequest",value:function(e,t){for(var r=0;r=e))break;return v.default.resolve(t)}},{key:"unmarkSessionsNeedingBackup",value:function(e){var t=!0,r=!1,n=void 0;try{for(var o,i=(0,c.default)(e);!(t=(o=i.next()).done);t=!0){var s=o.value,a=s.senderKey+"/"+s.sessionId;delete this._sessionsNeedingBackup[a]}}catch(e){r=!0,n=e}finally{try{!t&&i.return&&i.return()}finally{if(r)throw n}}return v.default.resolve()}},{key:"markSessionsNeedingBackup",value:function(e){var t=!0,r=!1,n=void 0;try{for(var o,i=(0,c.default)(e);!(t=(o=i.next()).done);t=!0){var s=o.value,a=s.senderKey+"/"+s.sessionId;this._sessionsNeedingBackup[a]=!0}}catch(e){r=!0,n=e}finally{try{!t&&i.return&&i.return()}finally{if(r)throw n}}return v.default.resolve()}},{key:"doTxn",value:function(e,t,r){return v.default.resolve(r(null))}}]),e}();r.default=b},{"../../logger":29,"../../utils":55,"babel-runtime/core-js/get-iterator":58,"babel-runtime/core-js/object/assign":63,"babel-runtime/core-js/object/keys":69,"babel-runtime/helpers/classCallCheck":79,"babel-runtime/helpers/createClass":80,bluebird:89}],24:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r="Store is invalid because "+e+", please stop the client, delete all data and start the client again",n=(0,p.default)(Error,[r]);return(0,d.default)(n,(0,c.default)(this)),n.reason=e,n.value=t,n}function i(e){var t="Crypto store is invalid because "+e+", please stop the client, delete all data and start the client again",r=(0,p.default)(Error,[t]);return(0,d.default)(r,(0,c.default)(this)),r.reason=e,r.name="InvalidCryptoStoreError",r}Object.defineProperty(r,"__esModule",{value:!0});var s=e("babel-runtime/core-js/object/create"),a=n(s),u=e("babel-runtime/core-js/reflect/get-prototype-of"),c=n(u),l=e("babel-runtime/core-js/reflect/set-prototype-of"),d=n(l),f=e("babel-runtime/core-js/reflect/construct"),p=n(f);r.InvalidStoreError=o,r.InvalidCryptoStoreError=i,o.TOGGLED_LAZY_LOADING="TOGGLED_LAZY_LOADING",o.prototype=(0,a.default)(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}}),(0,d.default)(o,Error),i.TOO_NEW="TOO_NEW",i.prototype=(0,a.default)(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}}),(0,d.default)(i,Error)},{"babel-runtime/core-js/object/create":64,"babel-runtime/core-js/reflect/construct":73,"babel-runtime/core-js/reflect/get-prototype-of":74,"babel-runtime/core-js/reflect/set-prototype-of":75}],25:[function(e,t,r){"use strict";function n(e,t){if(t.endsWith("*")){var r=t.slice(0,-1);return e.substr(0,r.length)===r}return e===t}function o(e){this.filter_json=e,this.types=e.types||null,this.not_types=e.not_types||[],this.rooms=e.rooms||null,this.not_rooms=e.not_rooms||[],this.senders=e.senders||null,this.not_senders=e.not_senders||[],this.contains_url=e.contains_url||null}var i=e("babel-runtime/core-js/object/keys"),s=function(e){return e&&e.__esModule?e:{default:e}}(i);o.prototype.check=function(e){return this._checkFields(e.getRoomId(),e.getSender(),e.getType(),!!e.getContent()&&void 0!==e.getContent().url)},o.prototype._checkFields=function(e,t,r,o){for(var i={rooms:function(t){return e===t},senders:function(e){return t===e},types:function(e){return n(r,e)}},a=this,u=0;u<(0,s.default)(i).length;u++){var c=(0,s.default)(i)[u],l=i[c];if(a["not_"+c].filter(l).length>0)return!1;var d=a[c];if(d&&!d.map(l))return!1}var f=this.filter_json.contains_url;return void 0===f||f===o},o.prototype.filter=function(e){return e.filter(this.check,this)},o.prototype.limit=function(){return void 0!==this.filter_json.limit?this.filter_json.limit:10},t.exports=o},{"babel-runtime/core-js/object/keys":69}],26:[function(e,t,r){"use strict";function n(e,t,r){for(var n=t.split("."),o=e,i=0;i0&&(b+="?"+E.join("&")),h.open("POST",b),this.useAuthorizationHeader&&h.setRequestHeader("Authorization","Bearer "+this.opts.accessToken),h.setRequestHeader("Content-Type",o),h.send(s),l=f.promise,l.abort=h.abort.bind(h)}else{var w={};n&&i&&(w.filename=i),l=this.authedRequest(t.callback,"POST","/upload",w,s,{prefix:"/_matrix/media/v1",headers:{"Content-Type":o},json:!1,bodyParser:d})}var S=this,k=l.finally(function(){for(var e=0;e=400?i=o(s,a):n&&(a=n(a))}catch(e){i=new Error("Error parsing server response: "+e)}if(i)e.reject(i),t(i);else{var u={code:s.statusCode,headers:s.headers,data:a};e.resolve(r?a:u),t(null,r?a:u)}}};t.exports.MatrixError=function(e){e=e||{},this.errcode=e.errcode,this.name=e.errcode||"Unknown error code",this.message=e.error||"Unknown message",this.data=e},t.exports.MatrixError.prototype=(0,a.default)(Error.prototype),t.exports.MatrixError.prototype.constructor=t.exports.MatrixError}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./realtime-callbacks":44,"./utils":55,"babel-runtime/core-js/json/stringify":60,"babel-runtime/core-js/object/create":64,"babel-runtime/helpers/typeof":85,bluebird:89,"content-type":94}],28:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){this._matrixClient=e.matrixClient,this._data=e.authData||{},this._requestCallback=e.doRequest,this._stateUpdatedCallback=e.stateUpdated||e.startAuthStage,this._completionDeferred=null,this._inputs=e.inputs||{},e.sessionId&&(this._data.session=e.sessionId),this._clientSecret=e.clientSecret||this._matrixClient.generateClientSecret(),this._emailSid=e.emailSid,void 0===this._emailSid&&(this._emailSid=null),this._currentStage=null}var i=e("babel-runtime/core-js/get-iterator"),s=n(i),a=e("babel-runtime/core-js/json/stringify"),u=n(a),c=e("bluebird"),l=n(c),d=e("url"),f=e("./utils");o.prototype={attemptAuth:function(){var e=this;return this._completionDeferred=l.default.defer(),l.default.resolve().then(function(){return e._data.flows?e._startNextAuthStage():e._doRequest(e._data),e._completionDeferred.promise})},poll:function(){if(this._data.session){var e={};if("m.login.email.identity"==this._currentStage&&this._emailSid){var t=d.parse(this._matrixClient.getIdentityServerUrl());e={type:"m.login.email.identity",threepid_creds:{sid:this._emailSid,client_secret:this._clientSecret,id_server:t.host}}}this.submitAuthDict(e,!0)}},getSessionId:function(){return this._data?this._data.session:void 0},getClientSecret:function(){return this._clientSecret},getStageParams:function(e){var t={};return this._data&&this._data.params&&(t=this._data.params),t[e]},submitAuthDict:function(e,t){if(!this._completionDeferred)throw new Error("submitAuthDict() called before attemptAuth()");var r={session:this._data.session};f.extend(r,e),this._doRequest(r,t)},getEmailSid:function(){return this._emailSid},setEmailSid:function(e){this._emailSid=e},_doRequest:function(e,t){var r=this,n=this,o=void 0;try{o=this._requestCallback(e,t)}catch(e){o=l.default.reject(e)}o=o.then(function(e){console.log("result from request: ",e),n._completionDeferred.resolve(e)},function(e){var t=e.data?e.data.flows:null,r=Boolean(n._data.flows)||Boolean(t);if(401!==e.httpStatus||!e.data||!r)throw e;e.data.flows||e.data.completed||e.data.session||(e.data.flows=n._data.flows,e.data.completed=n._data.completed,e.data.session=n._data.session),n._data=e.data,n._startNextAuthStage()}),o=t?o.catch(function(e){console.log("Ignoring error from UI auth: "+e)}):o.catch(function(e){r._completionDeferred.reject(e)}),o.done()},_startNextAuthStage:function(){var e=this._chooseStage();if(!e)throw new Error("No incomplete flows from the server");if(this._currentStage=e,"m.login.dummy"==e)return void this.submitAuthDict({type:"m.login.dummy"});if(this._data.errcode||this._data.error)return void this._stateUpdatedCallback(e,{errcode:this._data.errcode||"",error:this._data.error||""});var t={};"m.login.email.identity"==e&&(t.emailSid=this._emailSid),this._stateUpdatedCallback(e,t)},_chooseStage:function(){var e=this._chooseFlow();console.log("Active flow => %s",(0,u.default)(e));var t=this._firstUncompletedStage(e);return console.log("Next stage: %s",t),t},_chooseFlow:function(){var e=this._data.flows||[],t=Boolean(this._inputs.emailAddress)||Boolean(this._emailSid),r=Boolean(this._inputs.phoneCountry)&&Boolean(this._inputs.phoneNumber),n=!0,o=!1,i=void 0;try{for(var a,u=(0,s.default)(e);!(n=(a=u.next()).done);n=!0){var c=a.value,l=!1,d=!1,f=!0,p=!1,h=void 0;try{for(var v,m=(0,s.default)(c.stages);!(f=(v=m.next()).done);f=!0){var y=v.value;"m.login.email.identity"===y?l=!0:"m.login.msisdn"==y&&(d=!0)}}catch(_){p=!0,h=_}finally{try{!f&&m.return&&m.return()}finally{if(p)throw h}}if(l==t&&d==r)return c}}catch(_){o=!0,i=_}finally{try{!n&&u.return&&u.return()}finally{if(o)throw i}}var _=new Error("No appropriate authentication flow found");throw _.name="NoAuthFlowFoundError",_.required_stages=[],t&&_.required_stages.push("m.login.email.identity"),r&&_.required_stages.push("m.login.msisdn"),_.available_flows=e,_},_firstUncompletedStage:function(e){for(var t=(this._data||{}).completed||[],r=0;r0)throw new Error("Cannot initialise state after events are added");var t=!0,r=!1,n=void 0;try{for(var o,i=(0,u.default)(e);!(t=(o=i.next()).done);t=!0){var a=o.value;(0,s.default)(a)}}catch(e){r=!0,n=e}finally{try{!t&&i.return&&i.return()}finally{if(r)throw n}}this._startState.setStateEvents(e),this._endState.setStateEvents(e)},o.prototype.forkLive=function(e){var t=this.getState(e),r=new o(this._eventTimelineSet);return r._startState=t.clone(),r._endState=t,this._endState=t.clone(),r},o.prototype.fork=function(e){var t=this.getState(e),r=new o(this._eventTimelineSet);return r._startState=t.clone(),r._endState=t.clone(),r},o.prototype.getRoomId=function(){return this._roomId},o.prototype.getFilter=function(){return this._eventTimelineSet.getFilter()},o.prototype.getTimelineSet=function(){return this._eventTimelineSet},o.prototype.getBaseIndex=function(){return this._baseIndex},o.prototype.getEvents=function(){return this._events},o.prototype.getState=function(e){if(e==o.BACKWARDS)return this._startState;if(e==o.FORWARDS)return this._endState;throw new Error("Invalid direction '"+e+"'")},o.prototype.getPaginationToken=function(e){return this.getState(e).paginationToken},o.prototype.setPaginationToken=function(e,t){this.getState(t).paginationToken=e},o.prototype.getNeighbouringTimeline=function(e){if(e==o.BACKWARDS)return this._prevTimeline;if(e==o.FORWARDS)return this._nextTimeline;throw new Error("Invalid direction '"+e+"'")},o.prototype.setNeighbouringTimeline=function(e,t){if(this.getNeighbouringTimeline(t))throw new Error("timeline already has a neighbouring timeline - cannot reset neighbour");if(t==o.BACKWARDS)this._prevTimeline=e;else{if(t!=o.FORWARDS)throw new Error("Invalid direction '"+t+"'");this._nextTimeline=e}this.setPaginationToken(null,t)},o.prototype.addEvent=function(e,t){var r=t?this._startState:this._endState,n=this.getTimelineSet();n.room&&n.room.getUnfilteredTimelineSet()===n&&(o.setEventMetadata(e,r,t),e.isState()&&(r.setStateEvents([e]),e.sender&&("m.room.member"!==e.getType()||t)||o.setEventMetadata(e,r,t)));var i=void 0;i=t?0:this._events.length,this._events.splice(i,0,e),t&&this._baseIndex++},o.setEventMetadata=function(e,t,r){e.sender=t.getSentinelMember(e.getSender()),"m.room.member"===e.getType()&&(e.target=t.getSentinelMember(e.getStateKey())),e.isState()&&r&&(e.forwardLooking=!1)},o.prototype.removeEvent=function(e){for(var t=this._events.length-1;t>=0;t--){var r=this._events[t];if(r.getId()==e)return this._events.splice(t,1),t0&&(this.powerLevelNorm=100*this.powerLevel/r),n===this.powerLevel&&o===this.powerLevelNorm||(this._updateModifiedTime(),this.emit("RoomMember.powerLevel",e,this))}},n.prototype.setTypingEvent=function(e){if("m.typing"===e.getType()){var t=this.typing;this.typing=!1;var r=e.getContent().user_ids;a.isArray(r)&&(-1!==r.indexOf(this.userId)&&(this.typing=!0),t!==this.typing&&(this._updateModifiedTime(),this.emit("RoomMember.typing",e,this)))}},n.prototype._updateModifiedTime=function(){this._modified=Date.now()},n.prototype.getLastModifiedTime=function(){return this._modified},n.prototype.isKicked=function(){return"leave"===this.membership&&this.events.member.getSender()!==this.events.member.getStateKey()},n.prototype.getDMInviter=function(){if(this.events.member){var e=this.events.member,t=e.getContent(),r=e.getSender();if("join"===t.membership&&(t=e.getPrevContent(),r=e.getUnsigned().prev_sender),"invite"===t.membership&&t.is_direct)return r}},n.prototype.getAvatarUrl=function(e,t,r,n,o,i){void 0===o&&(o=!0);var a=this.getMxcAvatarUrl();if(!a&&!o)return null;var u=s.getHttpUriForMxc(e,a,t,r,n,i);return u||(o?s.getIdenticonUri(e,this.userId,t,r):null)},n.prototype.getMxcAvatarUrl=function(){return this.events.member?this.events.member.getDirectionalContent().avatar_url:this.user?this.user.avatarUrl:null},t.exports=n},{"../content-repo":6,"../utils":55,events:234}],37:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;this.roomId=e,this.members={},this.events={},this.paginationToken=null,this._sentinels={},this._updateModifiedTime(),this._displayNameToUserIds={},this._userIdsToDisplayNames={},this._tokenToInvite={},this._joinedMemberCount=null,this._summaryJoinedMemberCount=null,this._invitedMemberCount=null,this._summaryInvitedMemberCount=null,t||(t={status:m}),this._oobMemberFlags=t}function i(e,t){if(t.getContent().third_party_invite){var r=(t.getContent().third_party_invite.signed||{}).token;if(r){e.getStateEvents("m.room.third_party_invite",r)&&(e._tokenToInvite[r]=t)}}}function s(e,t,r){var n=e._userIdsToDisplayNames[t];if(delete e._userIdsToDisplayNames[t],n){var o=h.removeHiddenChars(n),i=e._displayNameToUserIds[o];if(i){var s=i.filter(function(e){return e!==t});e._displayNameToUserIds[o]=s}}e._userIdsToDisplayNames[t]=r;var a=r&&h.removeHiddenChars(r);a&&(e._displayNameToUserIds[a]||(e._displayNameToUserIds[a]=[]),e._displayNameToUserIds[a].push(t))}var a=e("babel-runtime/core-js/number/is-finite"),u=n(a),c=e("babel-runtime/core-js/object/keys"),l=n(c),d=e("babel-runtime/core-js/object/values"),f=n(d),p=e("events").EventEmitter,h=e("../utils"),v=e("./room-member"),m=1;h.inherits(o,p),o.prototype.getJoinedMemberCount=function(){return null!==this._summaryJoinedMemberCount?this._summaryJoinedMemberCount:(null===this._joinedMemberCount&&(this._joinedMemberCount=this.getMembers().reduce(function(e,t){return"join"===t.membership?e+1:e},0)),this._joinedMemberCount)},o.prototype.setJoinedMemberCount=function(e){this._summaryJoinedMemberCount=e},o.prototype.getInvitedMemberCount=function(){return null!==this._summaryInvitedMemberCount?this._summaryInvitedMemberCount:(null===this._invitedMemberCount&&(this._invitedMemberCount=this.getMembers().reduce(function(e,t){return"invite"===t.membership?e+1:e},0)),this._invitedMemberCount)},o.prototype.setInvitedMemberCount=function(e){this._summaryInvitedMemberCount=e},o.prototype.getMembers=function(){return h.values(this.members)},o.prototype.getMember=function(e){return this.members[e]||null},o.prototype.getSentinelMember=function(e){if(!e)return null;var t=this._sentinels[e];if(void 0===t){t=new v(this.roomId,e);var r=this.members[e];r&&t.setMembershipEvent(r.events.member,this),this._sentinels[e]=t}return t},o.prototype.getStateEvents=function(e,t){if(!this.events[e])return void 0===t?[]:null;if(void 0===t)return h.values(this.events[e]);var r=this.events[e][t];return r||null},o.prototype.clone=function(){var e=new o(this.roomId,this._oobMemberFlags),t=this._oobMemberFlags.status;return this._oobMemberFlags.status=m,(0,f.default)(this.events).forEach(function(t){var r=(0,f.default)(t);e.setStateEvents(r)}),this._oobMemberFlags.status=t,null!==this._summaryInvitedMemberCount&&e.setInvitedMemberCount(this.getInvitedMemberCount()),null!==this._summaryJoinedMemberCount&&e.setJoinedMemberCount(this.getJoinedMemberCount()),3==this._oobMemberFlags.status&&this.getMembers().forEach(function(t){if(t.isOutOfBand()){e.getMember(t.userId).markOutOfBand()}}),e},o.prototype.setUnknownStateEvents=function(e){var t=this,r=e.filter(function(e){return void 0===t.events[e.getType()]||void 0===t.events[e.getType()][e.getStateKey()]});this.setStateEvents(r)},o.prototype.setStateEvents=function(e){var t=this;this._updateModifiedTime(),h.forEach(e,function(e){e.getRoomId()===t.roomId&&e.isState()&&(t._setStateEvent(e),"m.room.member"===e.getType()&&(s(t,e.getStateKey(),e.getContent().displayname),i(t,e)),t.emit("RoomState.events",e,t))}),h.forEach(e,function(e){if(e.getRoomId()===t.roomId&&e.isState())if("m.room.member"===e.getType()){var r=e.getStateKey();"leave"!==e.getContent().membership&&"ban"!==e.getContent().membership||(e.getContent().avatar_url=e.getContent().avatar_url||e.getPrevContent().avatar_url,e.getContent().displayname=e.getContent().displayname||e.getPrevContent().displayname);var n=t._getOrCreateMember(r,e);n.setMembershipEvent(e,t),t._updateMember(n),t.emit("RoomState.members",e,t,n)}else if("m.room.power_levels"===e.getType()){var o=h.values(t.members);h.forEach(o,function(r){r.setPowerLevelEvent(e),t.emit("RoomState.members",e,t,r)}),t._sentinels={}}})},o.prototype._getOrCreateMember=function(e,t){var r=this.members[e];return r||(r=new v(this.roomId,e),this.members[e]=r,this.emit("RoomState.newMember",t,this,r)),r},o.prototype._setStateEvent=function(e){void 0===this.events[e.getType()]&&(this.events[e.getType()]={}),this.events[e.getType()][e.getStateKey()]=e},o.prototype._updateMember=function(e){var t=this.getStateEvents("m.room.power_levels","");t&&e.setPowerLevelEvent(t),delete this._sentinels[e.userId],this.members[e.userId]=e,this._joinedMemberCount=null,this._invitedMemberCount=null},o.prototype.needsOutOfBandMembers=function(){return this._oobMemberFlags.status===m},o.prototype.markOutOfBandMembersStarted=function(){this._oobMemberFlags.status===m&&(this._oobMemberFlags.status=2)},o.prototype.markOutOfBandMembersFailed=function(){2===this._oobMemberFlags.status&&(this._oobMemberFlags.status=m)},o.prototype.clearOutOfBandMembers=function(){var e=this,t=0;(0,l.default)(this.members).forEach(function(r){e.members[r].isOutOfBand()&&(++t,delete e.members[r])}),console.log("LL: RoomState removed "+t+" members..."),this._oobMemberFlags.status=m},o.prototype.setOutOfBandMembers=function(e){var t=this;console.log("LL: RoomState about to set "+e.length+" OOB members ..."),2===this._oobMemberFlags.status&&(console.log("LL: RoomState put in OOB_STATUS_FINISHED state ..."),this._oobMemberFlags.status=3,e.forEach(function(e){return t._setOutOfBandMember(e)}))},o.prototype._setOutOfBandMember=function(e){if("m.room.member"===e.getType()){var t=e.getStateKey(),r=this.getMember(t);if(!r||r.isOutOfBand()){var n=this._getOrCreateMember(t,e);n.setMembershipEvent(e,this),n.markOutOfBand(),s(this,n.userId,n.name),this._setStateEvent(e),this._updateMember(n),this.emit("RoomState.members",e,this,n)}}},o.prototype.setTypingEvent=function(e){h.forEach(h.values(this.members),function(t){t.setTypingEvent(e)})},o.prototype.getInviteForThreePidToken=function(e){return this._tokenToInvite[e]||null},o.prototype._updateModifiedTime=function(){this._modified=Date.now()},o.prototype.getLastModifiedTime=function(){return this._modified},o.prototype.getUserIdsWithDisplayName=function(e){return this._displayNameToUserIds[e]||[]},o.prototype.maySendRedactionForEvent=function(e,t){var r=this.getMember(t);if(!r||"leave"===r.membership)return!1;if(e.status||e.isRedacted())return!1;var n=this.maySendEvent("m.room.redaction",t);return e.getSender()===t?n:this._hasSufficientPowerLevelFor("redact",r.powerLevel)},o.prototype._hasSufficientPowerLevelFor=function(e,t){var r=this.getStateEvents("m.room.power_levels",""),n={};r&&(n=r.getContent());var o=50;return h.isNumber(n[e])&&(o=n[e]),t>=o},o.prototype.maySendMessage=function(e){return this._maySendEventOfType("m.room.message",e,!1)},o.prototype.maySendEvent=function(e,t){return this._maySendEventOfType(e,t,!1)},o.prototype.mayClientSendStateEvent=function(e,t){return!t.isGuest()&&this.maySendStateEvent(e,t.credentials.userId)},o.prototype.maySendStateEvent=function(e,t){return this._maySendEventOfType(e,t,!0)},o.prototype._maySendEventOfType=function(e,t,r){var n=this.getStateEvents("m.room.power_levels",""),o=void 0,i={},s=0,a=0,c=0;if(n){o=n.getContent(),i=o.events||{},s=(0,u.default)(o.state_default)?o.state_default:50;var l=o.users&&o.users[t];(0,u.default)(l)?c=l:(0,u.default)(o.users_default)&&(c=o.users_default),(0,u.default)(o.events_default)&&(a=o.events_default)}var d=r?s:a;return(0,u.default)(i[e])&&(d=i[e]),c>=d},o.prototype.mayTriggerNotifOfType=function(e,t){var r=this.getMember(t);if(!r)return!1;var n=this.getStateEvents("m.room.power_levels",""),o=50;return n&&n.getContent()&&n.getContent().notifications&&h.isNumber(n.getContent().notifications[e])&&(o=n.getContent().notifications[e]),r.powerLevel>=o},t.exports=o},{"../utils":55,"./room-member":36,"babel-runtime/core-js/number/is-finite":61,"babel-runtime/core-js/object/keys":69,"babel-runtime/core-js/object/values":71,events:234}],38:[function(e,t,r){"use strict";function n(e,t){this.roomId=e,this.info=t}t.exports=n},{}],39:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t,r){var n={content:{},type:"m.receipt",room_id:t.getRoomId()};return n.content[t.getId()]={},n.content[t.getId()][r]={},n.content[t.getId()][r][e]={ts:t.getTs()},new S(n)}function i(e,t,r,n){if(n=n||{},n.pendingEventOrdering=n.pendingEventOrdering||"chronological",this.reEmitter=new _.default(this),-1===["chronological","detached"].indexOf(n.pendingEventOrdering))throw new Error("opts.pendingEventOrdering MUST be either 'chronological' or 'detached'. Got: '"+n.pendingEventOrdering+"'");this.myUserId=r,this.roomId=e,this.name=e,this.tags={},this.accountData={},this.summary=null,this.storageToken=n.storageToken,this._opts=n,this._txnToEvent={},this._receipts={},this._receiptCacheByEventId={},this._realReceipts={},this._notificationCounts={},this._timelineSets=[new R(this,n)],this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),["Room.timeline","Room.timelineReset"]),this._fixUpLegacyTimelineFields(),this._filteredTimelineSets={},"detached"==this._opts.pendingEventOrdering&&(this._pendingEventList=[]),this._blacklistUnverifiedDevices=null,this._selfMembership=null,this._summaryHeroes=null,this._client=t,this._opts.lazyLoadMembers?this._membersPromise=null:this._membersPromise=m.default.resolve()}function s(e,t,r){if(!r){var n=e.currentState.getStateEvents("m.room.name","");if(n&&n.getContent()&&n.getContent().name)return n.getContent().name}var o=e.getCanonicalAlias();if(!o){var i=e.getAliases();i.length&&(o=i[0])}if(o)return o;var s=e.currentState.getJoinedMemberCount(),u=e.currentState.getInvitedMemberCount(),c=s+u-1,l=null;if(e._summaryHeroes)l=e._summaryHeroes.map(function(t){var r=e.getMember(t);return r?r.name:t});else{var d=e.currentState.getMembers().filter(function(e){return e.userId!==t&&("invite"===e.membership||"join"===e.membership)});d.sort(function(e,t){return e.userId.localeCompare(t.userId)}),d=d.slice(0,5),l=d.map(function(e){return e.name})}if(c)return a(l,c);if("join"==e.getMyMembership()){var f=e.currentState.getStateEvents("m.room.third_party_invite");if(f&&f.length)return"Inviting "+a(f.map(function(e){return e.getContent().display_name}))}var p=l;return p.length||(p=e.currentState.getMembers().filter(function(e){return e.userId!==t&&"invite"!==e.membership&&"join"!==e.membership}).map(function(e){return e.name})),p.length?"Empty room (was "+a(p)+")":"Empty room"}function a(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.length+1,r=t-1;if(e.length){if(1===e.length&&r<=1)return e[0];if(2===e.length&&r<=2)return e[0]+" and "+e[1];return r>1?e[0]+" and "+r+" others":e[0]+" and 1 other"}return"Empty room"}var u=e("babel-runtime/core-js/object/assign"),c=n(u),l=e("babel-runtime/core-js/number/is-integer"),d=n(l),f=e("babel-runtime/regenerator"),p=n(f),h=e("bluebird"),v=e("babel-runtime/core-js/promise"),m=n(v),y=e("../ReEmitter"),_=n(y),g=e("events").EventEmitter,b=e("./event").EventStatus,E=e("./room-summary"),w=e("./room-member"),S=e("./event").MatrixEvent,k=e("../utils"),T=e("../content-repo"),x=e("./event-timeline"),R=e("./event-timeline-set");k.inherits(i,g),i.prototype.getVersion=function(){var e=this.currentState.getStateEvents("m.room.create","");if(!e)return console.warn("Room "+this.room_id+" does not have an m.room.create event"),"1";var t=e.getContent().room_version;return void 0===t?"1":t},i.prototype.shouldUpgradeToVersion=function(){return"1"===this.getVersion()?null:"1"},i.prototype.userMayUpgradeRoom=function(e){return this.currentState.maySendStateEvent("m.room.tombstone",e)},i.prototype.getPendingEvents=function(){if("detached"!==this._opts.pendingEventOrdering)throw new Error("Cannot call getPendingEventList with pendingEventOrdering == "+this._opts.pendingEventOrdering);return this._pendingEventList},i.prototype.getLiveTimeline=function(){return this.getUnfilteredTimelineSet().getLiveTimeline()},i.prototype.getMyMembership=function(){return this._selfMembership},i.prototype.getDMInviter=function(){if(this.myUserId){var e=this.getMember(this.myUserId);if(e)return e.getDMInviter()}if("invite"===this._selfMembership){if(2==this.getInvitedAndJoinedMemberCount()&&this._summaryHeroes.length)return this._summaryHeroes[0]}},i.prototype.guessDMUserId=function(){var e=this,t=this.getMember(this.myUserId);if(t){var r=t.getDMInviter();if(r)return r}if(Array.isArray(this._summaryHeroes)&&this._summaryHeroes.length)return this._summaryHeroes[0];var n=this.currentState.getMembers(),o=n.find(function(t){return t.userId!==e.myUserId});return o?o.userId:this.myUserId},i.prototype.getAvatarFallbackMember=function(){var e=this;if(!(this.getInvitedAndJoinedMemberCount()>2)){var t=Array.isArray(this._summaryHeroes)&&this._summaryHeroes.length;if(t){var r=this._summaryHeroes.map(function(t){return e.getMember(t)}).find(function(e){return!!e});if(r)return r}var n=this.currentState.getMembers();if(n.length<=2){var o=n.find(function(t){return t.userId!==e.myUserId});if(o)return o}if(t){var i=this._summaryHeroes.map(function(t){return e._client.getUser(t)}).find(function(e){return!!e});if(i){var s=new w(this.roomId,i.userId);return s.user=i,s}}}},i.prototype.updateMyMembership=function(e){var t=this._selfMembership;this._selfMembership=e,t!==e&&("leave"===e&&this._cleanupAfterLeaving(),this.emit("Room.myMembership",this,e,t))},i.prototype._loadMembersFromServer=(0,h.coroutine)(p.default.mark(function e(){var t,r,n,o,i;return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=this._client.store.getSyncToken(),r=k.encodeParams({not_membership:"leave",at:t}),n=k.encodeUri("/rooms/$roomId/members?"+r,{$roomId:this.roomId}),o=this._client._http,e.next=6,(0,h.resolve)(o.authedRequest(void 0,"GET",n));case 6:return i=e.sent,e.abrupt("return",i.chunk);case 8:case"end":return e.stop()}},e,this)})),i.prototype._loadMembers=(0,h.coroutine)(p.default.mark(function e(){var t,r,n;return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=!1,e.next=3,(0,h.resolve)(this._client.store.getOutOfBandMembers(this.roomId));case 3:if(null!==(r=e.sent)){e.next=10;break}return t=!0,e.next=8,(0,h.resolve)(this._loadMembersFromServer());case 8:r=e.sent,console.log("LL: got "+r.length+" members from server for room "+this.roomId);case 10:return n=r.map(this._client.getEventMapper()),e.abrupt("return",{memberEvents:n,fromServer:t});case 12:case"end":return e.stop()}},e,this)})),i.prototype.loadMembersIfNeeded=function(){var e=this;if(this._membersPromise)return this._membersPromise;this.currentState.markOutOfBandMembersStarted();var t=this._loadMembers().then(function(t){return e.currentState.setOutOfBandMembers(t.memberEvents),e._client.isRoomEncrypted(e.roomId)&&e._client._crypto.trackRoomDevices(e.roomId),t.fromServer}).catch(function(t){throw e._membersPromise=null,e.currentState.markOutOfBandMembersFailed(),t});return t.then(function(t){if(t){var r=e.currentState.getMembers().filter(function(e){return e.isOutOfBand()}).map(function(e){return e.events.member.event});console.log("LL: telling store to write "+r.length+" members for room "+e.roomId);return e._client.store.setOutOfBandMembers(e.roomId,r).catch(function(e){console.log("LL: storing OOB room members failed, oh well",e)})}}).catch(function(e){console.error(e)}),this._membersPromise=t,this._membersPromise},i.prototype.clearLoadedMembersIfNeeded=(0,h.coroutine)(p.default.mark(function e(){return p.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this._opts.lazyLoadMembers||!this._membersPromise){e.next=7;break}return e.next=3,(0,h.resolve)(this.loadMembersIfNeeded());case 3:return e.next=5,(0,h.resolve)(this._client.store.clearOutOfBandMembers(this.roomId));case 5:this.currentState.clearOutOfBandMembers(),this._membersPromise=null;case 7:case"end":return e.stop()}},e,this)})),i.prototype._cleanupAfterLeaving=function(){var e=this;this.clearLoadedMembersIfNeeded().catch(function(t){console.error("error after clearing loaded members from room "+e.roomId+" after leaving"),console.dir(t)})},i.prototype.resetLiveTimeline=function(e,t){for(var r=0;r-1&&this._timelineSets.splice(r,1)},i.prototype._addLiveEvent=function(e,t){var r=void 0;if("m.room.redaction"===e.getType()){var n=e.event.redacts,i=this.getUnfilteredTimelineSet().findEventById(n);i&&(i.makeRedacted(e),this.emit("Room.redaction",e,this))}if(e.getUnsigned().transaction_id){var s=this._txnToEvent[e.getUnsigned().transaction_id];if(s)return void this._handleRemoteEcho(e,s)}for(r=0;r"+t);if(e.status=t,t==b.SENT){e.event.event_id=r +;for(var s=0;s=0)return}else t[o][i]={};t[o][i]={eventId:n,data:s}})})})},i.prototype._buildReceiptCache=function(e){var t={};return k.keys(e).forEach(function(r){k.keys(e[r]).forEach(function(n){var o=e[r][n];t[o.eventId]||(t[o.eventId]=[]),t[o.eventId].push({userId:n,type:r,data:o.data})})}),t},i.prototype._addLocalEchoReceipt=function(e,t,r){this.addReceipt(o(e,t,r),!0)},i.prototype.addTags=function(e){this.tags=e.getContent().tags||{},this.emit("Room.tags",e,this)},i.prototype.addAccountData=function(e){for(var t=0;t]*)([0-9]*)$/);if(!i)return!1;var s=i[1],a=parseInt(i[2]);if(isNaN(a))return!1;switch(s){case"":case"==":return o==a;case"<":return o":return o>a;case"<=":return o<=a;case">=":return o>=a;default:return!1}},p=function(t,r){var n=r.getContent();if(!n||!n.body||"string"!=typeof n.body)return!1;var o=e.getRoom(r.getRoomId());if(!(o&&o.currentState&&o.currentState.members&&o.currentState.getMember(e.credentials.userId)))return!1;var i=o.currentState.getMember(e.credentials.userId).name,s=new RegExp("(^|\\W)"+(0,d.escapeRegExp)(i)+"(\\W|$)","i");return n.body.search(s)>-1},h=function(e,t){return!1},v=function(e,t){if(!e.key)return!1;var r=y(e.key,t);if(!r||"string"!=typeof r)return!1;if(e.value)return e.value===r;var n=void 0;return n="content.body"==e.key?m("(^|\\W)",e.pattern,"(\\W|$)"):m("^",e.pattern,"$"),!!r.match(n)},m=function(e,t,n){return r[t]?r[t]:(r[t]=new RegExp(e+(0,d.globToRegexp)(t)+n,"i"),r[t])},y=function(e,t){var r=e.split("."),n=void 0,o=r[0];for("content"==o?(n=t.getContent(),r.shift()):"type"==o?(n=t.getType(),r.shift()):n=t.event;r.length>0;){var i=r.shift();if(!n[i])return null;n=n[i]}return n},_=function(t,r){if(!r||!r.device)return null;if(t.getSender()==e.credentials.userId)return null;for(var o=(0,l.default)(r.device),i=0;in)break;t=u.shift(),c("_runCallbacks: popping",t.key),o.push(t)}r();for(var s=0;s>1;t(e[o])>0?n=o:r=o+1}return r}var i=1e3,s=0,a=void 0,u=[],c=function(){};t.exports.setNow=function(e){l=e||Date.now};var l=Date.now;t.exports.setTimeout=function(e,t){(t=t||0)<0&&(t=0);var n=Array.prototype.slice.call(arguments,2),i=l()+t,a=s++;c("setTimeout: scheduling cb",a,"at",i,"(delay",t,")");var d={runAt:i,func:e,params:n,key:a},f=o(u,function(e){return e.runAt-i});return u.splice(f,0,d),r(),a},t.exports.clearTimeout=function(e){if(0!==u.length){var t=void 0;for(t=0;t0}),function(t){e._activeQueues.push(t),u("Spinning up queue: '%s'",t),i(e,t)})}function i(e,t){var r=s(e,t);if(!r){var n=e._activeQueues.indexOf(t);return n>=0&&e._activeQueues.splice(n,1),void u("Stopping queue '%s' as it is now empty",t)}u("Queue '%s' has %s pending events",t,e._queues[t].length),e._procFn(r.event).done(function(n){a(e,t),u("Queue '%s' sent event %s",t,r.event.getId()),r.defer.resolve(n),i(e,t)},function(n){r.attempts+=1;var o=e.retryAlgorithm(r.event,r.attempts,n);u("retry(%s) err=%s event_id=%s waitTime=%s",r.attempts,n,r.event.getId(),o),-1===o?(u("Queue '%s' giving up on event %s",t,r.event.getId()),a(e,t),r.defer.reject(n),i(e,t)):setTimeout(function(){i(e,t)},o)})}function s(e,t){var r=e._queues[t];return d.isArray(r)?r[0]:null}function a(e,t){var r=e._queues[t];return d.isArray(r)?r.shift():null}function u(){if(f){var e;(e=console).log.apply(e,arguments)}}var c=e("bluebird"),l=function(e){return e&&e.__esModule?e:{default:e}}(c),d=e("./utils"),f=!1;n.prototype.getQueueForEvent=function(e){var t=this.queueAlgorithm(e);return t&&this._queues[t]?d.map(this._queues[t],function(e){return e.event}):null},n.prototype.removeEventFromQueue=function(e){var t=this.queueAlgorithm(e);if(!t||!this._queues[t])return!1;var r=!1;return d.removeElement(this._queues[t],function(t){if(t.event.getId()===e.getId())return r=!0,!0}),r},n.prototype.setProcessFunction=function(e){this._procFn=e,o(this)},n.prototype.queueEvent=function(e){var t=this.queueAlgorithm(e);if(!t)return null;this._queues[t]||(this._queues[t]=[]);var r=l.default.defer();return this._queues[t].push({event:e,defer:r,attempts:0}),u("Queue algorithm dumped event %s into queue '%s'",e.getId(),t),o(this),r.promise},n.RETRY_BACKOFF_RATELIMIT=function(e,t,r){if(400===r.httpStatus||403===r.httpStatus||401===r.httpStatus)return-1;if("rejected"===r.cors)return-1;if("M_LIMIT_EXCEEDED"===r.name){var n=r.data.retry_after_ms;if(n)return n}return t>4?-1:1e3*Math.pow(2,t)},n.QUEUE_MESSAGES=function(e){return"m.room.message"===e.getType()?"message":null},t.exports=n},{"./utils":55,bluebird:89}],46:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){e.createObjectStore("users",{keyPath:["userId"]}),e.createObjectStore("accountData",{keyPath:["type"]}),e.createObjectStore("sync",{keyPath:["clobber"]})}function i(e){e.createObjectStore("oob_membership_events",{keyPath:["room_id","state_key"]}).createIndex("room","room_id")}function s(e){e.createObjectStore("client_options",{keyPath:["clobber"]})}function a(e,t,r){var n=e.openCursor(t);return new y.default(function(e,t){var o=[];n.onerror=function(e){t(new Error("Query failed: "+e.target.errorCode))},n.onsuccess=function(t){var n=t.target.result;if(!n)return void e(o);o.push(r(n)),n.continue()}})}function u(e){return new y.default(function(t,r){e.oncomplete=function(e){t(e)},e.onerror=function(e){r(e.target.error)}})}function c(e){return new y.default(function(t,r){e.onsuccess=function(e){t(e)},e.onerror=function(e){r(e.target.error)}})}function l(e){return new y.default(function(t,r){e.onsuccess=function(){return t(e)},e.onerror=function(e){return r(e)}})}function d(e){return c(e).then(function(e){return e.target.result})}Object.defineProperty(r,"__esModule",{value:!0});var f=e("babel-runtime/core-js/get-iterator"),p=n(f),h=e("babel-runtime/regenerator"),v=n(h),m=e("bluebird"),y=n(m),_=e("babel-runtime/helpers/slicedToArray"),g=n(_),b=e("../sync-accumulator"),E=n(b),w=e("../utils"),S=n(w),k=function(e,t){this.indexedDB=e,this._dbName="matrix-js-sdk:"+(t||"default"),this.db=null,this._disconnected=!0,this._syncAccumulator=new E.default,this._isNewlyCreated=!1};k.prototype={connect:function(){var e=this;if(!this._disconnected)return console.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),y.default.resolve();this._disconnected=!1,console.log("LocalIndexedDBStoreBackend.connect: connecting...");var t=this.indexedDB.open(this._dbName,3);return t.onupgradeneeded=function(t){var r=t.target.result,n=t.oldVersion;console.log("LocalIndexedDBStoreBackend.connect: upgrading from "+n),n<1&&(e._isNewlyCreated=!0,o(r)),n<2&&i(r),n<3&&s(r)},t.onblocked=function(){console.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},console.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),c(t).then(function(t){return console.log("LocalIndexedDBStoreBackend.connect: connected"),e.db=t.target.result,e.db.onversionchange=function(){e.db.close()},e._init()})},isNewlyCreated:function(){return y.default.resolve(this._isNewlyCreated)},_init:function(){var e=this;return y.default.all([this._loadAccountData(),this._loadSyncData()]).then(function(t){var r=(0,g.default)(t,2),n=r[0],o=r[1];console.log("LocalIndexedDBStoreBackend: loaded initial data"),e._syncAccumulator.accumulate({next_batch:o.nextBatch,rooms:o.roomsData,groups:o.groupsData,account_data:{events:n}})})},getOutOfBandMembers:function(e){var t=this;return new y.default(function(r,n){var o=t.db.transaction(["oob_membership_events"],"readonly"),i=o.objectStore("oob_membership_events"),s=i.index("room"),a=IDBKeyRange.only(e),u=s.openCursor(a),c=[],l=!1;u.onsuccess=function(e){var t=e.target.result;if(!t)return r(c.length||l?c:null);var n=t.value;n.oob_written?l=!0:c.push(n),t.continue()},u.onerror=function(e){n(e)}}).then(function(t){return console.log("LL: got "+(t&&t.length)+" membershipEvents from storage for room "+e+" ..."),t})},setOutOfBandMembers:function(){function e(e,r){return t.apply(this,arguments)}var t=(0,m.coroutine)(v.default.mark(function e(t,r){var n,o,i;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return console.log("LL: backend about to store "+r.length+" members for "+t),n=this.db.transaction(["oob_membership_events"],"readwrite"),o=n.objectStore("oob_membership_events"),r.forEach(function(e){o.put(e)}),i={room_id:t,oob_written:!0,state_key:0},o.put(i),e.next=8,(0,m.resolve)(u(n));case 8:console.log("LL: backend done storing for "+t+"!");case 9:case"end":return e.stop()}},e,this)}));return e}(),clearOutOfBandMembers:function(){function e(e){return t.apply(this,arguments)}var t=(0,m.coroutine)(v.default.mark(function e(t){var r,n,o,i,s,a,u,c,f,p,h,_,b;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.db.transaction(["oob_membership_events"],"readonly"),n=r.objectStore("oob_membership_events"),o=n.index("room"),i=IDBKeyRange.only(t),s=d(o.openKeyCursor(i,"next")).then(function(e){return e&&e.primaryKey[1]}),a=d(o.openKeyCursor(i,"prev")).then(function(e){return e&&e.primaryKey[1]}),e.next=8,(0,m.resolve)(y.default.all([s,a]));case 8:return u=e.sent,c=(0,g.default)(u,2),f=c[0],p=c[1],h=this.db.transaction(["oob_membership_events"],"readwrite"),_=h.objectStore("oob_membership_events"),b=IDBKeyRange.bound([t,f],[t,p]),console.log("LL: Deleting all users + marker in storage for room "+t+", with key range:",[t,f],[t,p]),e.next=18,(0,m.resolve)(l(_.delete(b)));case 18:case"end":return e.stop()}},e,this)}));return e}(),clearDatabase:function(){var e=this;return new y.default(function(t,r){console.log("Removing indexeddb instance: "+e._dbName);var n=e.indexedDB.deleteDatabase(e._dbName);n.onblocked=function(){console.log("can't yet delete indexeddb "+e._dbName+" because it is open elsewhere")},n.onerror=function(e){console.warn("unable to delete js-sdk store indexeddb: "+e.target.error),t()},n.onsuccess=function(){console.log("Removed indexeddb instance: "+e._dbName),t()}})},getSavedSync:function(e){void 0===e&&(e=!0);var t=this._syncAccumulator.getJSON();return t.nextBatch?e?y.default.resolve(S.default.deepCopy(t)):y.default.resolve(t):y.default.resolve(null)},getNextBatchToken:function(){return y.default.resolve(this._syncAccumulator.getNextBatchToken())},setSyncData:function(e){var t=this;return y.default.resolve().then(function(){t._syncAccumulator.accumulate(e)})},syncToDatabase:function(e){var t=this._syncAccumulator.getJSON();return y.default.all([this._persistUserPresenceEvents(e),this._persistAccountData(t.accountData),this._persistSyncData(t.nextBatch,t.roomsData,t.groupsData)])},_persistSyncData:function(e,t,r){var n=this;return console.log("Persisting sync data up to ",e),y.default.try(function(){var o=n.db.transaction(["sync"],"readwrite");return o.objectStore("sync").put({clobber:"-",nextBatch:e,roomsData:t,groupsData:r}),u(o)})},_persistAccountData:function(e){var t=this;return y.default.try(function(){for(var r=t.db.transaction(["accountData"],"readwrite"),n=r.objectStore("accountData"),o=0;o1&&console.warn("loadSyncData: More than 1 sync row found."),e.length>0?e[0]:{}})})},getClientOptions:function(){var e=this;return y.default.resolve().then(function(){return a(e.db.transaction(["client_options"],"readonly").objectStore("client_options"),void 0,function(e){if(e.value&&e.value&&e.value.options)return e.value.options}).then(function(e){return e[0]})})},storeClientOptions:function(){function e(e){return t.apply(this,arguments)}var t=(0,m.coroutine)(v.default.mark(function e(t){var r,n;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.db.transaction(["client_options"],"readwrite"),n=r.objectStore("client_options"),n.put({clobber:"-",options:t}),e.next=5,(0,m.resolve)(u(r));case 5:case"end":return e.stop()}},e,this)}));return e}()},r.default=k},{"../sync-accumulator":52,"../utils":55,"babel-runtime/core-js/get-iterator":58,"babel-runtime/helpers/slicedToArray":84,"babel-runtime/regenerator":86,bluebird:89}],47:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("bluebird"),o=function(e){return e&&e.__esModule?e:{default:e}}(n),i=function(e,t,r){this._workerScript=e,this._dbName=t,this._workerApi=r,this._worker=null,this._nextSeq=0,this._inFlight={},this._startPromise=null};i.prototype={connect:function(){var e=this;return this._ensureStarted().then(function(){return e._doCmd("connect")})},clearDatabase:function(){var e=this;return this._ensureStarted().then(function(){return e._doCmd("clearDatabase")})},isNewlyCreated:function(){return this._doCmd("isNewlyCreated")},getSavedSync:function(){return this._doCmd("getSavedSync")},getNextBatchToken:function(){return this._doCmd("getNextBatchToken")},setSyncData:function(e){return this._doCmd("setSyncData",[e])},syncToDatabase:function(e){return this._doCmd("syncToDatabase",[e])},getOutOfBandMembers:function(e){return this._doCmd("getOutOfBandMembers",[e])},setOutOfBandMembers:function(e,t){return this._doCmd("setOutOfBandMembers",[e,t])},clearOutOfBandMembers:function(e){return this._doCmd("clearOutOfBandMembers",[e])},getClientOptions:function(){return this._doCmd("getClientOptions")},storeClientOptions:function(e){return this._doCmd("storeClientOptions",[e])},getUserPresenceEvents:function(){return this._doCmd("getUserPresenceEvents")},_ensureStarted:function(){return null===this._startPromise&&(this._worker=new this._workerApi(this._workerScript),this._worker.onmessage=this._onWorkerMessage.bind(this),this._startPromise=this._doCmd("_setupWorker",[this._dbName]).then(function(){console.log("IndexedDB worker is ready")})),this._startPromise},_doCmd:function(e,t){var r=this;return o.default.resolve().then(function(){var n=r._nextSeq++,i=o.default.defer();return r._inFlight[n]=i,r._worker.postMessage({command:e,seq:n,args:t}),i.promise})},_onWorkerMessage:function(e){var t=e.data;if("cmd_success"==t.command||"cmd_fail"==t.command){if(void 0===t.seq)return void console.error("Got reply from worker with no seq");var r=this._inFlight[t.seq];if(void 0===r)return void console.error("Got reply for unknown seq "+t.seq);if(delete this._inFlight[t.seq],"cmd_success"==t.command)r.resolve(t.result);else{var n=new Error(t.error.message);n.name=t.error.name,r.reject(n)}}else console.warn("Unrecognised message from worker: "+t)}},r.default=i},{bluebird:89}],48:[function(e,t,r){(function(r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}var o=e("babel-runtime/core-js/get-iterator"),i=n(o),s=e("babel-runtime/helpers/slicedToArray"),a=n(s),u=e("bluebird"),c=n(u),l=e("./memory"),d=e("../utils"),f=n(d),p=e("./indexeddb-local-backend.js"),h=n(p),v=e("./indexeddb-remote-backend.js"),m=n(v),y=e("../models/user"),_=n(y),g=e("../models/event"),b=function(e){if(l.MatrixInMemoryStore.call(this,e),!e.indexedDB)throw new Error("Missing required option: indexedDB");if(e.workerScript){var t=e.workerApi;t||(t=r.Worker),this.backend=new m.default(e.workerScript,e.dbName,t)}else this.backend=new h.default(e.indexedDB,e.dbName);this.startedUp=!1,this._syncTs=0,this._userModifiedMap={}};f.default.inherits(b,l.MatrixInMemoryStore),b.prototype.startup=function(){var e=this;return this.startedUp?(console.log("IndexedDBStore.startup: already started"),c.default.resolve()):(console.log("IndexedDBStore.startup: connecting to backend"),this.backend.connect().then(function(){return console.log("IndexedDBStore.startup: loading presence events"),e.backend.getUserPresenceEvents()}).then(function(t){console.log("IndexedDBStore.startup: processing presence events"),t.forEach(function(t){var r=(0,a.default)(t,2),n=r[0],o=r[1],i=new _.default(n);o&&i.setPresenceEvent(new g.MatrixEvent(o)),e._userModifiedMap[i.userId]=i.getLastModifiedTime(),e.storeUser(i)})}))},b.prototype.getSavedSync=function(){return this.backend.getSavedSync()},b.prototype.isNewlyCreated=function(){return this.backend.isNewlyCreated()},b.prototype.getSavedSyncToken=function(){return this.backend.getNextBatchToken()},b.prototype.deleteAllData=function(){return l.MatrixInMemoryStore.prototype.deleteAllData.call(this),this.backend.clearDatabase().then(function(){console.log("Deleted indexeddb data.")},function(e){throw console.error("Failed to delete indexeddb data: "+e),e})},b.prototype.wantsSave=function(){return Date.now()-this._syncTs>3e5},b.prototype.save=function(){return this.wantsSave()?this._reallySave():c.default.resolve()},b.prototype._reallySave=function(){this._syncTs=Date.now();var e=[],t=!0,r=!1,n=void 0;try{for(var o,s=(0,i.default)(this.getUsers());!(t=(o=s.next()).done);t=!0){var a=o.value;this._userModifiedMap[a.userId]!==a.getLastModifiedTime()&&(a.events.presence&&(e.push([a.userId,a.events.presence.event]),this._userModifiedMap[a.userId]=a.getLastModifiedTime()))}}catch(e){r=!0,n=e}finally{try{!t&&s.return&&s.return()}finally{if(r)throw n}}return this.backend.syncToDatabase(e).catch(function(e){console.error("sync fail:",e)})},b.prototype.setSyncData=function(e){return this.backend.setSyncData(e)},b.prototype.getOutOfBandMembers=function(e){return this.backend.getOutOfBandMembers(e)},b.prototype.setOutOfBandMembers=function(e,t){return this.backend.setOutOfBandMembers(e,t)},b.prototype.clearOutOfBandMembers=function(e){return this.backend.clearOutOfBandMembers(e)},b.prototype.getClientOptions=function(){return this.backend.getClientOptions()},b.prototype.storeClientOptions=function(e){return this.backend.storeClientOptions(e)},t.exports.IndexedDBStore=b}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../models/event":34,"../models/user":41,"../utils":55,"./indexeddb-local-backend.js":46,"./indexeddb-remote-backend.js":47,"./memory":49,"babel-runtime/core-js/get-iterator":58,"babel-runtime/helpers/slicedToArray":84,bluebird:89}],49:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}var o=e("babel-runtime/core-js/object/assign"),i=n(o),s=e("bluebird"),a=n(s),u=e("../utils"),c=e("../models/user");t.exports.MatrixInMemoryStore=function(e){e=e||{},this.rooms={},this.groups={},this.users={},this.syncToken=null,this.filters={},this.accountData={},this.localStorage=e.localStorage,this._oobMembers={},this._clientOptions={}},t.exports.MatrixInMemoryStore.prototype={getSyncToken:function(){return this.syncToken},isNewlyCreated:function(){return a.default.resolve(!0)},setSyncToken:function(e){this.syncToken=e},storeGroup:function(e){this.groups[e.groupId]=e},getGroup:function(e){return this.groups[e]||null},getGroups:function(){return u.values(this.groups)},storeRoom:function(e){this.rooms[e.roomId]=e,e.currentState.on("RoomState.members",this._onRoomMember.bind(this));var t=this;e.currentState.getMembers().forEach(function(r){t._onRoomMember(null,e.currentState,r)})},_onRoomMember:function(e,t,r){if("invite"!==r.membership){var n=this.users[r.userId]||new c(r.userId);r.name&&(n.setDisplayName(r.name),r.events.member&&n.setRawDisplayName(r.events.member.getDirectionalContent().displayname)),r.events.member&&r.events.member.getContent().avatar_url&&n.setAvatarUrl(r.events.member.getContent().avatar_url),this.users[n.userId]=n}},getRoom:function(e){return this.rooms[e]||null},getRooms:function(){return u.values(this.rooms)},removeRoom:function(e){this.rooms[e]&&this.rooms[e].removeListener("RoomState.members",this._onRoomMember),delete this.rooms[e]},getRoomSummaries:function(){return u.map(u.values(this.rooms),function(e){return e.summary})},storeUser:function(e){this.users[e.userId]=e},getUser:function(e){return this.users[e]||null},getUsers:function(){return u.values(this.users)},scrollback:function(e,t){return[]},storeEvents:function(e,t,r,n){},storeFilter:function(e){e&&(this.filters[e.userId]||(this.filters[e.userId]={}),this.filters[e.userId][e.filterId]=e)},getFilter:function(e,t){return this.filters[e]&&this.filters[e][t]?this.filters[e][t]:null},getFilterIdByName:function(e){if(!this.localStorage)return null;try{return this.localStorage.getItem("mxjssdk_memory_filter_"+e)}catch(e){}return null},setFilterIdByName:function(e,t){if(this.localStorage)try{this.localStorage.setItem("mxjssdk_memory_filter_"+e,t)}catch(e){}},storeAccountDataEvents:function(e){var t=this;e.forEach(function(e){t.accountData[e.getType()]=e})},getAccountData:function(e){return this.accountData[e]},setSyncData:function(e){return a.default.resolve()},wantsSave:function(){return!1},save:function(){},startup:function(){return a.default.resolve()},getSavedSync:function(){return a.default.resolve(null)},getSavedSyncToken:function(){ +return a.default.resolve(null)},deleteAllData:function(){return this.rooms={},this.users={},this.syncToken=null,this.filters={},this.accountData={},a.default.resolve()},getOutOfBandMembers:function(e){return a.default.resolve(this._oobMembers[e]||null)},setOutOfBandMembers:function(e,t){return this._oobMembers[e]=t,a.default.resolve()},getClientOptions:function(){return a.default.resolve(this._clientOptions)},storeClientOptions:function(e){return this._clientOptions=(0,i.default)({},e),a.default.resolve()}}},{"../models/user":41,"../utils":55,"babel-runtime/core-js/object/assign":63,bluebird:89}],50:[function(e,t,r){"use strict";function n(e){if(this.store=e,!(h.isFunction(e.getItem)&&h.isFunction(e.setItem)&&h.isFunction(e.removeItem)&&h.isFunction(e.key)&&"number"==typeof e.length))throw new Error("Supplied webStore does not meet the WebStorage API interface")}function o(e){return m+"devices/"+e}function i(e){return m+"sessions/"+e}function s(e,t){return m+"inboundgroupsessions/"+e+"/"+t}function a(e){return m+"rooms/"+e}function u(e,t){try{return JSON.parse(e.getItem(t))}catch(e){d("Failed to get key %s: %s",t,e),d(e.stack)}return null}function c(e,t){for(var r=[],n=0;nthis.opts.maxTimelineEntries)for(var a=r._timeline.length-this.opts.maxTimelineEntries,c=a;c0&&i.ephemeral.events.push(a),n._timeline.forEach(function(e){if(!i.timeline.prev_batch){if(!e.token)return;i.timeline.prev_batch=e.token}i.timeline.events.push(e.event)});for(var c=(0,s.default)(null),l=i.timeline.events.length-1;l>=0;l--){var d=i.timeline.events[l];if(null!==d.state_key&&void 0!==d.state_key){var f=h.default.deepCopy(d);f.unsigned&&(f.unsigned.prev_content&&(f.content=f.unsigned.prev_content),f.unsigned.prev_sender&&(f.sender=f.unsigned.prev_sender)),o(c,f)}}(0,u.default)(n._currentState).forEach(function(e){(0,u.default)(n._currentState[e]).forEach(function(t){var r=n._currentState[e][t];c[e]&&c[e][t]&&(r=c[e][t]),i.state.events.push(r)})}),t.join[r]=i});var r=[];return(0,u.default)(this.accountData).forEach(function(t){r.push(e.accountData[t])}),{nextBatch:this.nextBatch,roomsData:t,groupsData:this.groups,accountData:r}}},{key:"getNextBatchToken",value:function(){return this.nextBatch}}]),e}();t.exports=v},{"./utils":55,"babel-runtime/core-js/object/create":64,"babel-runtime/core-js/object/keys":69,"babel-runtime/helpers/classCallCheck":79,"babel-runtime/helpers/createClass":80}],53:[function(e,t,r){(function(r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){return"FILTER_SYNC_"+e+(t?"_"+t:"")}function i(){var e;T&&(e=console).log.apply(e,arguments)}function s(e,t){this.client=e,t=t||{},t.initialSyncLimit=void 0===t.initialSyncLimit?8:t.initialSyncLimit,t.resolveInvitesToProfiles=t.resolveInvitesToProfiles||!1,t.pollTimeout=t.pollTimeout||3e4,t.pendingEventOrdering=t.pendingEventOrdering||"chronological",t.canResetEntireTimeline||(t.canResetEntireTimeline=function(e){return!1}),this.opts=t,this._peekRoomId=null,this._currentSyncRequest=null,this._syncState=null,this._syncStateData=null,this._catchingUp=!1,this._running=!1,this._keepAliveTimer=null,this._connectionReturnedDefer=null,this._notifEvents=[],this._failedSyncCount=0,this._storeIsInvalid=!1,e.getNotifTimelineSet()&&e.reEmitter.reEmit(e.getNotifTimelineSet(),["Room.timeline","Room.timelineReset"])}function a(e,t){var r=new g(t);return e.reEmitter.reEmit(r,["User.avatarUrl","User.displayName","User.presence","User.currentlyActive","User.lastPresenceTs"]),r}var u=e("babel-runtime/core-js/json/stringify"),c=n(u),l=e("babel-runtime/core-js/object/keys"),d=n(l),f=e("babel-runtime/core-js/get-iterator"),p=n(f),h=e("babel-runtime/regenerator"),v=n(h),m=e("bluebird"),y=n(m),_=e("./errors"),g=e("./models/user"),b=e("./models/room"),E=e("./models/group"),w=e("./utils"),S=e("./filter"),k=e("./models/event-timeline"),T=!0;s.prototype.createRoom=function(e){var t=this.client,r=new b(e,t,t.getUserId(),{lazyLoadMembers:this.opts.lazyLoadMembers,pendingEventOrdering:this.opts.pendingEventOrdering,timelineSupport:t.timelineSupport});return t.reEmitter.reEmit(r,["Room.name","Room.timeline","Room.redaction","Room.receipt","Room.tags","Room.timelineReset","Room.localEchoUpdated","Room.accountData","Room.myMembership"]),this._registerStateListeners(r),r},s.prototype.createGroup=function(e){var t=this.client,r=new E(e);return t.reEmitter.reEmit(r,["Group.profile","Group.myMembership"]),t.store.storeGroup(r),r},s.prototype._registerStateListeners=function(e){var t=this.client;t.reEmitter.reEmit(e.currentState,["RoomState.events","RoomState.members","RoomState.newMember"]),e.currentState.on("RoomState.newMember",function(e,r,n){n.user=t.getUser(n.userId),t.reEmitter.reEmit(n,["RoomMember.name","RoomMember.typing","RoomMember.powerLevel","RoomMember.membership"])})},s.prototype._deregisterStateListeners=function(e){e.currentState.removeAllListeners("RoomState.events"),e.currentState.removeAllListeners("RoomState.members"),e.currentState.removeAllListeners("RoomState.newMember")},s.prototype.syncLeftRooms=function(){var e=this.client,t=this,r=new S(this.client.credentials.userId);r.setTimelineLimit(1),r.setIncludeLeaveRooms(!0);var n=this.opts.pollTimeout+8e4,i={timeout:0};return e.getOrCreateFilter(o(e.credentials.userId,"LEFT_ROOMS"),r).then(function(t){return i.filter=t,e._http.authedRequest(void 0,"GET","/sync",i,void 0,n)}).then(function(r){var n=[];r.rooms&&r.rooms.leave&&(n=t._mapSyncResponseToRoomArray(r.rooms.leave));var o=[];return n.forEach(function(r){var n=r.room;if(o.push(n),r.isBrandNewRoom){r.timeline=r.timeline||{};var i=t._mapSyncEventsFormat(r.timeline,n),s=t._mapSyncEventsFormat(r.state,n);n.getLiveTimeline().setPaginationToken(r.timeline.prev_batch,k.BACKWARDS),t._processRoomEvents(n,s,i),n.recalculate(),e.store.storeRoom(n),e.emit("Room",n),t._processEventsForNotifs(n,i)}}),o})},s.prototype.peek=function(e){var t=this,r=this.client;return this._peekRoomId=e,this.client.roomInitialSync(e,20).then(function(n){n.messages=n.messages||{},n.messages.chunk=n.messages.chunk||[],n.state=n.state||[];var o=t.createRoom(e),i=w.map(w.deepCopy(n.state),r.getEventMapper()),s=w.map(n.state,r.getEventMapper()),u=w.map(n.messages.chunk,r.getEventMapper());return n.presence&&w.isArray(n.presence)&&n.presence.map(r.getEventMapper()).forEach(function(e){var t=r.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=a(r,e.getContent().user_id),t.setPresenceEvent(e),r.store.storeUser(t)),r.emit("event",e)}),n.messages.start&&(o.oldState.paginationToken=n.messages.start),o.oldState.setStateEvents(i),o.currentState.setStateEvents(s),t._resolveInvites(o),o.recalculate(),o.addEventsToTimeline(u.reverse(),!0,o.getLiveTimeline(),n.messages.start),r.store.storeRoom(o),r.emit("Room",o),t._peekPoll(o),o})},s.prototype.stopPeeking=function(){this._peekRoomId=null},s.prototype._peekPoll=function(e,t){if(this._peekRoomId!==e.roomId)return void i("Stopped peeking in room %s",e.roomId);var r=this;this.client._http.authedRequest(void 0,"GET","/events",{room_id:e.roomId,timeout:3e4,from:t},void 0,5e4).done(function(t){if(r._peekRoomId!==e.roomId)return void i("Stopped peeking in room %s",e.roomId);t.chunk.filter(function(e){return"m.presence"===e.type}).map(r.client.getEventMapper()).forEach(function(e){var t=r.client.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=a(r.client,e.getContent().user_id),t.setPresenceEvent(e),r.client.store.storeUser(t)),r.client.emit("event",e)});var n=t.chunk.filter(function(t){return t.room_id===e.roomId}).map(r.client.getEventMapper());e.addLiveEvents(n),r._peekPoll(e,t.end)},function(n){console.error("[%s] Peek poll failed: %s",e.roomId,n),setTimeout(function(){r._peekPoll(e,t)},3e4)})},s.prototype.getSyncState=function(){return this._syncState},s.prototype.getSyncStateData=function(){return this._syncStateData},s.prototype.recoverFromSyncStartupError=function(){var e=(0,m.coroutine)(v.default.mark(function e(t,r){var n;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,(0,m.resolve)(t);case 2:return n=this._startKeepAlives(),this._updateSyncState("ERROR",{error:r}),e.next=6,(0,m.resolve)(n);case 6:case"end":return e.stop()}},e,this)}));return function(t,r){return e.apply(this,arguments)}}(),s.prototype._wasLazyLoadingToggled=function(){var e=(0,m.coroutine)(v.default.mark(function e(t){var r,n,o;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=!!t,r=!1,e.next=4,(0,m.resolve)(this.client.store.isNewlyCreated());case 4:if(n=e.sent){e.next=11;break}return e.next=8,(0,m.resolve)(this.client.store.getClientOptions());case 8:return o=e.sent,o&&(r=!!o.lazyLoadMembers),e.abrupt("return",r!==t);case 11:return e.abrupt("return",!1);case 12:case"end":return e.stop()}},e,this)}));return function(t){return e.apply(this,arguments)}}(),s.prototype.sync=function(){var e=this,t=function(){var e=(0,m.coroutine)(v.default.mark(function e(){var r;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,(0,m.resolve)(s.getPushRules());case 3:r=e.sent,i("Got push rules"),s.pushRules=r,e.next=14;break;case 8:return e.prev=8,e.t0=e.catch(0),e.next=12,(0,m.resolve)(a.recoverFromSyncStartupError(u,e.t0));case 12:return t(),e.abrupt("return");case 14:l();case 15:case"end":return e.stop()}},e,this,[[0,8]])}));return function(){return e.apply(this,arguments)}}(),n=function(){var e=(0,m.coroutine)(v.default.mark(function e(){var t,r;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=void 0,a.opts.filter?t=a.opts.filter:(t=new S(s.credentials.userId),t.setTimelineLimit(a.opts.initialSyncLimit)),r=void 0,e.prev=3,e.next=6,(0,m.resolve)(s.getOrCreateFilter(o(s.credentials.userId),t));case 6:r=e.sent,e.next=15;break;case 9:return e.prev=9,e.t0=e.catch(3),e.next=13,(0,m.resolve)(a.recoverFromSyncStartupError(u,e.t0));case 13:return n(),e.abrupt("return");case 15:return s.resetNotifTimelineSet(),null===a._currentSyncRequest&&(console.log("Sending first sync request..."),a._currentSyncRequest=a._doSyncRequest({filterId:r},c)),e.next=19,(0,m.resolve)(u);case 19:a._sync({filterId:r});case 20:case"end":return e.stop()}},e,this,[[3,9]])}));return function(){return e.apply(this,arguments)}}(),s=this.client,a=this;this._running=!0,r.document&&(this._onOnlineBound=this._onOnline.bind(this),r.document.addEventListener("online",this._onOnlineBound,!1));var u=y.default.resolve(),c=null,l=function(){var t=(0,m.coroutine)(v.default.mark(function t(){var r,o,i,a;return v.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(e.opts.lazyLoadMembers&&s.isGuest()&&(e.opts.lazyLoadMembers=!1),!e.opts.lazyLoadMembers){t.next=13;break}return t.next=4,(0,m.resolve)(s.doesServerSupportLazyLoading());case 4:if(!(r=t.sent)){t.next=11;break}return t.next=8,(0,m.resolve)(s.createFilter(S.LAZY_LOADING_SYNC_FILTER));case 8:e.opts.filter=t.sent,t.next=13;break;case 11:console.log("LL: lazy loading requested but not supported by server, so disabling"),e.opts.lazyLoadMembers=!1;case 13:return t.next=15,(0,m.resolve)(e._wasLazyLoadingToggled(e.opts.lazyLoadMembers));case 15:if(!(o=t.sent)){t.next=23;break}return e._storeIsInvalid=!0,i=_.InvalidStoreError.TOGGLED_LAZY_LOADING,a=new _.InvalidStoreError(i,!!e.opts.lazyLoadMembers),e._updateSyncState("ERROR",{error:a}),console.warn("InvalidStoreError: store is not usable: stopping sync."),t.abrupt("return");case 23:return e.opts.lazyLoadMembers&&e.opts.crypto&&e.opts.crypto.enableLazyLoading(),t.next=26,(0,m.resolve)(e.client._storeClientOptions());case 26:n();case 27:case"end":return t.stop()}},t,e)}));return function(){return t.apply(this,arguments)}}();s.isGuest()?a._sync({}):(u=s.store.getSavedSyncToken().then(function(e){return c=e,s.store.getSavedSync()}).then(function(e){if(e)return a._syncFromCache(e)}),t())},s.prototype.stop=function(){i("SyncApi.stop"),r.document&&(r.document.removeEventListener("online",this._onOnlineBound,!1),this._onOnlineBound=void 0),this._running=!1,this._currentSyncRequest&&this._currentSyncRequest.abort(),this._keepAliveTimer&&(clearTimeout(this._keepAliveTimer),this._keepAliveTimer=null)},s.prototype.retryImmediately=function(){return!!this._connectionReturnedDefer&&(this._startKeepAlives(0),!0)},s.prototype._syncFromCache=function(){var e=(0,m.coroutine)(v.default.mark(function e(t){var r,n,o;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i("sync(): not doing HTTP hit, instead returning stored /sync data"),r=t.nextBatch,this.client.store.setSyncToken(r),n={oldSyncToken:null,nextSyncToken:r,catchingUp:!1},o={next_batch:r,rooms:t.roomsData,groups:t.groupsData,account_data:{events:t.accountData}},e.prev=5,e.next=8,(0,m.resolve)(this._processSyncResponse(n,o));case 8:e.next=13;break;case 10:e.prev=10,e.t0=e.catch(5),console.error("Error processing cached sync",e.t0.stack||e.t0);case 13:this._storeIsInvalid||this._updateSyncState("PREPARED",n);case 14:case"end":return e.stop()}},e,this,[[5,10]])}));return function(t){return e.apply(this,arguments)}}(),s.prototype._sync=function(){var e=(0,m.coroutine)(v.default.mark(function e(t){var r,n,o,s;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=this.client,this._running){e.next=6;break}return i("Sync no longer running: exiting."),this._connectionReturnedDefer&&(this._connectionReturnedDefer.reject(),this._connectionReturnedDefer=null),this._updateSyncState("STOPPED"),e.abrupt("return");case 6:return n=r.store.getSyncToken(),o=void 0,e.prev=8,null===this._currentSyncRequest&&(this._currentSyncRequest=this._doSyncRequest(t,n)),e.next=12,(0,m.resolve)(this._currentSyncRequest);case 12:o=e.sent,e.next=19;break;case 15:return e.prev=15,e.t0=e.catch(8),this._onSyncError(e.t0,t),e.abrupt("return");case 19:return e.prev=19,this._currentSyncRequest=null,e.finish(19);case 22:return r.store.setSyncToken(o.next_batch),this._failedSyncCount=0,e.next=26,(0,m.resolve)(r.store.setSyncData(o));case 26:if(s={oldSyncToken:n,nextSyncToken:o.next_batch,catchingUp:this._catchingUp},!this.opts.crypto){e.next=30;break}return e.next=30,(0,m.resolve)(this.opts.crypto.onSyncWillProcess(s));case 30:return e.prev=30,e.next=33,(0,m.resolve)(this._processSyncResponse(s,o));case 33:e.next=38;break;case 35:e.prev=35,e.t1=e.catch(30),console.error("Caught /sync error",e.t1.stack||e.t1);case 38:if(s.catchingUp=this._catchingUp,t.hasSyncedBefore||(this._updateSyncState("PREPARED",s),t.hasSyncedBefore=!0),!this.opts.crypto){e.next=43;break}return e.next=43,(0,m.resolve)(this.opts.crypto.onSyncCompleted(s));case 43:if(this._updateSyncState("SYNCING",s),!r.store.wantsSave()){e.next=49;break}if(!this.opts.crypto){e.next=48;break}return e.next=48,(0,m.resolve)(this.opts.crypto.saveDeviceList(0));case 48:r.store.save();case 49:this._sync(t);case 50:case"end":return e.stop()}},e,this,[[8,15,19,22],[30,35]])}));return function(t){return e.apply(this,arguments)}}(),s.prototype._doSyncRequest=function(e,t){var r=this._getSyncParams(e,t);return this.client._http.authedRequest(void 0,"GET","/sync",r,void 0,r.timeout+8e4)},s.prototype._getSyncParams=function(e,t){var r=this.opts.pollTimeout;("SYNCING"!==this.getSyncState()||this._catchingUp)&&(this._catchingUp=!0,r=0);var n=e.filterId;this.client.isGuest()&&!n&&(n=this._getGuestFilter());var o={filter:n,timeout:r};return this.opts.disablePresence&&(o.set_presence="offline"),t?o.since=t:o._cacheBuster=Date.now(),"ERROR"!=this.getSyncState()&&"RECONNECTING"!=this.getSyncState()||(o.timeout=0),o},s.prototype._onSyncError=function(e,t){var r=this;if(!this._running)return i("Sync no longer running: exiting"),this._connectionReturnedDefer&&(this._connectionReturnedDefer.reject(),this._connectionReturnedDefer=null),void this._updateSyncState("STOPPED");console.error("/sync error %s",e),console.error(e),this._failedSyncCount++,console.log("Number of consecutive failed sync requests:",this._failedSyncCount),i("Starting keep-alive"),this._startKeepAlives().then(function(e){e&&"ERROR"===r.getSyncState()&&r._updateSyncState("CATCHUP",{oldSyncToken:null,nextSyncToken:null,catchingUp:!0}),r._sync(t)}),this._currentSyncRequest=null,this._updateSyncState(this._failedSyncCount>=3?"ERROR":"RECONNECTING",{error:e})},s.prototype._processSyncResponse=function(){var e=(0,m.coroutine)(v.default.mark(function e(t,r){var n,o,s,u,c,l,d;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.client,o=this,r.presence&&w.isArray(r.presence.events)&&r.presence.events.map(n.getEventMapper()).forEach(function(e){var t=n.store.getUser(e.getSender());t?t.setPresenceEvent(e):(t=a(n,e.getSender()),t.setPresenceEvent(e),n.store.storeUser(t)),n.emit("event",e)}),r.account_data&&w.isArray(r.account_data.events)&&(s=r.account_data.events.map(n.getEventMapper()),n.store.storeAccountDataEvents(s),s.forEach(function(e){return"m.push_rules"==e.getType()&&(n.pushRules=e.getContent()),n.emit("accountData",e),e})),r.to_device&&w.isArray(r.to_device.events)&&r.to_device.events.length>0?r.to_device.events.map(n.getEventMapper()).forEach(function(e){var t=e.getContent();if("m.room.message"==e.getType()&&"m.bad.encrypted"==t.msgtype)return void console.log("Ignoring undecryptable to-device event from "+e.getSender());n.emit("toDeviceEvent",e)}):this._catchingUp=!1,r.groups&&(r.groups.invite&&this._processGroupSyncEntry(r.groups.invite,"invite"),r.groups.join&&this._processGroupSyncEntry(r.groups.join,"join"),r.groups.leave&&this._processGroupSyncEntry(r.groups.leave,"leave")),u=[],c=[],l=[],r.rooms&&(r.rooms.invite&&(u=this._mapSyncResponseToRoomArray(r.rooms.invite)),r.rooms.join&&(c=this._mapSyncResponseToRoomArray(r.rooms.join)),r.rooms.leave&&(l=this._mapSyncResponseToRoomArray(r.rooms.leave))),this._notifEvents=[],u.forEach(function(e){var t=e.room,r=o._mapSyncEventsFormat(e.invite_state,t);t.updateMyMembership("invite"),o._processRoomEvents(t,r),e.isBrandNewRoom&&(t.recalculate(),n.store.storeRoom(t),n.emit("Room",t)),r.forEach(function(e){n.emit("event",e)})}),e.next=14,(0,m.resolve)(y.default.mapSeries(c,function(){var e=(0,m.coroutine)(v.default.mark(function e(r){var s,a,u,c,l,d,f,p,h=function(){var e=(0,m.coroutine)(v.default.mark(function e(t){return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(n.emit("event",t),!t.isState()||"m.room.encryption"!=t.getType()||!o.opts.crypto){e.next=4;break}return e.next=4,(0,m.resolve)(o.opts.crypto.onCryptoEvent(t));case 4:case"end":return e.stop()}},e,this)}));return function(t){return e.apply(this,arguments)}}();return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(s=r.room,a=o._mapSyncEventsFormat(r.state,s),u=o._mapSyncEventsFormat(r.timeline,s),c=o._mapSyncEventsFormat(r.ephemeral),l=o._mapSyncEventsFormat(r.account_data),r.unread_notifications&&(s.setUnreadNotificationCount("total",r.unread_notifications.notification_count),s.setUnreadNotificationCount("highlight",r.unread_notifications.highlight_count)),s.updateMyMembership("join"),r.timeline=r.timeline||{},!r.isBrandNewRoom){e.next=12;break}s.getLiveTimeline().setPaginationToken(r.timeline.prev_batch,k.BACKWARDS),e.next=26;break;case 12:if(!r.timeline.limited){e.next=26;break}d=!0,f=u.length-1;case 15:if(!(f>=0)){e.next=25;break}if(p=u[f].getId(),!s.getTimelineForEvent(p)){e.next=22;break}return i("Already have event "+p+" in limited sync - not resetting"),d=!1,u.splice(0,f),e.abrupt("break",25);case 22:f--,e.next=15;break;case 25:d&&(o._deregisterStateListeners(s),s.resetLiveTimeline(r.timeline.prev_batch,o.opts.canResetEntireTimeline(s.roomId)?null:t.oldSyncToken),n.resetNotifTimelineSet(),o._registerStateListeners(s));case 26:return o._processRoomEvents(s,a,u),r.summary&&s.setSummary(r.summary),s.addLiveEvents(c),s.addAccountData(l),s.recalculate(),r.isBrandNewRoom&&(n.store.storeRoom(s),n.emit("Room",s)),o._processEventsForNotifs(s,u),e.next=35,(0,m.resolve)(y.default.mapSeries(a,h));case 35:return e.next=37,(0,m.resolve)(y.default.mapSeries(u,h));case 37:c.forEach(function(e){n.emit("event",e)}),l.forEach(function(e){n.emit("event",e)});case 39:case"end":return e.stop()}},e,this)}));return function(t){return e.apply(this,arguments)}}()));case 14:if(l.forEach(function(e){var t=e.room,r=o._mapSyncEventsFormat(e.state,t),i=o._mapSyncEventsFormat(e.timeline,t),s=o._mapSyncEventsFormat(e.account_data);t.updateMyMembership("leave"),o._processRoomEvents(t,r,i),t.addAccountData(s),t.recalculate(),e.isBrandNewRoom&&(n.store.storeRoom(t),n.emit("Room",t)),o._processEventsForNotifs(t,i),r.forEach(function(e){n.emit("event",e)}),i.forEach(function(e){n.emit("event",e)}),s.forEach(function(e){n.emit("event",e)})}),t.oldSyncToken&&this._notifEvents.length&&(this._notifEvents.sort(function(e,t){return e.getTs()-t.getTs()}),this._notifEvents.forEach(function(e){n.getNotifTimelineSet().addLiveEvent(e)})),!r.device_lists){e.next=22;break}if(!this.opts.crypto){e.next=22;break}return e.next=20,(0,m.resolve)(this.opts.crypto.handleDeviceListChanges(t,r.device_lists));case 20:e.next=22;break;case 22:this.opts.crypto&&r.device_one_time_keys_count&&(d=r.device_one_time_keys_count.signed_curve25519||0,this.opts.crypto.updateOneTimeKeyCount(d));case 23:case"end":return e.stop()}},e,this)}));return function(t,r){return e.apply(this,arguments)}}(),s.prototype._startKeepAlives=function(e){void 0===e&&(e=2e3+Math.floor(5e3*Math.random())),null!==this._keepAliveTimer&&clearTimeout(this._keepAliveTimer);var t=this;return e>0?t._keepAliveTimer=setTimeout(t._pokeKeepAlive.bind(t),e):t._pokeKeepAlive(),this._connectionReturnedDefer||(this._connectionReturnedDefer=y.default.defer()),this._connectionReturnedDefer.promise},s.prototype._pokeKeepAlive=function(e){function t(){clearTimeout(r._keepAliveTimer),r._connectionReturnedDefer&&(r._connectionReturnedDefer.resolve(e),r._connectionReturnedDefer=null)}void 0===e&&(e=!1);var r=this;this.client._http.request(void 0,"GET","/_matrix/client/versions",void 0,void 0,{prefix:"",localTimeoutMs:15e3}).done(function(){t()},function(n){400==n.httpStatus||404==n.httpStatus?r._keepAliveTimer=setTimeout(t,2e3):(e=!0,r._keepAliveTimer=setTimeout(r._pokeKeepAlive.bind(r,e),5e3+Math.floor(5e3*Math.random())),r._updateSyncState("ERROR",{error:n}))})},s.prototype._processGroupSyncEntry=function(e,t){var r=!0,n=!1,o=void 0;try{for(var i,s=(0,p.default)((0,d.default)(e));!(r=(i=s.next()).done);r=!0){var a=i.value,u=e[a],c=this.client.store.getGroup(a),l=null===c;null===c&&(c=this.createGroup(a)),u.profile&&c.setProfile(u.profile.name,u.profile.avatar_url),u.inviter&&c.setInviter({userId:u.inviter}),c.setMyMembership(t),l&&this.client.emit("Group",c)}}catch(e){n=!0,o=e}finally{try{!r&&s.return&&s.return()}finally{if(n)throw o}}},s.prototype._mapSyncResponseToRoomArray=function(e){var t=this.client,r=this;return w.keys(e).map(function(n){var o=e[n],i=t.store.getRoom(n),s=!1;return i||(i=r.createRoom(n),s=!0),o.room=i,o.isBrandNewRoom=s,o})},s.prototype._mapSyncEventsFormat=function(e,t){if(!e||!w.isArray(e.events))return[];var r=this.client.getEventMapper();return e.events.map(function(e){return t&&(e.room_id=t.roomId),r(e) +})},s.prototype._resolveInvites=function(e){if(e&&this.opts.resolveInvitesToProfiles){var t=this.client;e.getMembersWithMembership("invite").forEach(function(r){if(!r._requestedProfileInfo){r._requestedProfileInfo=!0;var n=t.getUser(r.userId),o=void 0;o=n?y.default.resolve({avatar_url:n.avatarUrl,displayname:n.displayName}):t.getProfileInfo(r.userId),o.done(function(t){var n=r.events.member;"invite"===n.getContent().membership&&(n.getContent().avatar_url=t.avatar_url,n.getContent().displayname=t.displayname,r.setMembershipEvent(n,e.currentState))},function(e){})}})}},s.prototype._processRoomEvents=function(e,t,r){var n=e.getLiveTimeline(),o=0==n.getEvents().length;if(o){var i=!0,s=!1,a=void 0;try{for(var u,c=(0,p.default)(t);!(i=(u=c.next()).done);i=!0){var l=u.value;this.client.getPushActionsForEvent(l)}}catch(e){s=!0,a=e}finally{try{!i&&c.return&&c.return()}finally{if(s)throw a}}n.initialiseState(t)}this._resolveInvites(e),e.recalculate(),o||(e.oldState.setStateEvents(t||[]),e.currentState.setStateEvents(t||[])),e.addLiveEvents(r||[])},s.prototype._processEventsForNotifs=function(e,t){if(this.client.getNotifTimelineSet())for(var r=0;rt.minIndex())return!0}else if(t.index0&&this.unpaginate(c,e!=a.BACKWARDS),s.default.resolve(!0)}if(!r||0===n)return s.default.resolve(!1);if(!o.timeline.getPaginationToken(e))return u("TimelineWindow: no token"),s.default.resolve(!1);u("TimelineWindow: starting request");var l=this,d=this._client.paginateEventTimeline(o.timeline,{backwards:e==a.BACKWARDS,limit:t}).finally(function(){o.pendingPaginate=null}).then(function(r){return u("TimelineWindow: request completed with result "+r),!!r&&l.paginate(e,t,!0,n-1)});return o.pendingPaginate=d,d},n.prototype.unpaginate=function(e,t){var r=t?this._start:this._end;if(e>this._eventCount||e<0)throw new Error("Attemting to unpaginate "+e+" events, but only have "+this._eventCount+" in the timeline");for(;e>0;){var n=t?r.advance(e):r.retreat(e);if(n<=0)throw new Error("Unable to unpaginate any further, but still have "+this._eventCount+" events");e-=n,this._eventCount-=n,u("TimelineWindow.unpaginate: dropped "+n+" (now "+this._eventCount+")")}},n.prototype.getEvents=function(){if(!this._start)return[];for(var e=[],t=this._start.timeline;;){var r=t.getEvents(),n=0,o=r.length;t===this._start.timeline&&(n=this._start.index+t.getBaseIndex()),t===this._end.timeline&&(o=this._end.index+t.getBaseIndex());for(var i=n;i0)return this.index+=t,t;var r=this.timeline.getNeighbouringTimeline(e<0?a.BACKWARDS:a.FORWARDS);return r?(this.timeline=r,this.index=e<0?this.maxIndex():this.minIndex(),u("paginate: switched to new neighbour"),this.advance(e)):0},o.prototype.retreat=function(e){return-1*this.advance(-1*e)},t.exports.TimelineWindow=n,t.exports.TimelineIndex=o},{"./models/event-timeline":33,bluebird:89}],55:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var i=e("babel-runtime/core-js/object/create"),s=n(i),a=e("babel-runtime/helpers/typeof"),u=n(a),c=e("babel-runtime/core-js/json/stringify"),l=n(c);t.exports.encodeParams=function(e){var t="";for(var r in e)e.hasOwnProperty(r)&&(t+="&"+encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t.substring(1)},t.exports.encodeUri=function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e=e.replace(r,encodeURIComponent(t[r])));return e},t.exports.map=function(e,t){for(var r=new Array(e.length),n=0;n=0;n--)if(t(e[n],n,e))return e[n]}else for(n=0;n=0;n--)if(t(e[n],n,e))return o=e[n],e.splice(n,1),o}else for(n=0;n>>0;if("function"!=typeof e)throw new TypeError;for(var n=[],o=arguments.length>=2?arguments[1]:void 0,i=0;i>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");arguments.length>1&&(r=t);var s=new Array(i);for(n=0;n>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(arguments.length>1&&(r=t),n=0;n1){var o=Object(arguments[1]);for(var i in o)t.call(o,i)&&(n[i]=o[i])}return n}}()),e.super_=t,e.prototype=(0,s.default)(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})},t.exports.isNumber=function(e){return"number"==typeof e&&isFinite(e)},t.exports.removeHiddenChars=function(e){return e.normalize("NFD").replace(f,"")};var f=/[\u200B-\u200D\u0300-\u036f\uFEFF\s]/g;t.exports.escapeRegExp=o,t.exports.globToRegexp=function(e,t){t="boolean"!=typeof t||t;var r=o(e);return r=r.replace(/\\\*/g,".*"),r=r.replace(/\?/g,"."),t&&(r=r.replace(/\\\[(!|)(.*)\\]/g,function(e,t,r,n,o){return"["+(t&&"^"||"")+r.replace(/\\\-/,"-")+"]"})),r}},{"babel-runtime/core-js/json/stringify":60,"babel-runtime/core-js/object/create":64,"babel-runtime/helpers/typeof":85}],56:[function(e,t,r){(function(r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){this.roomId=e.roomId,this.client=e.client,this.webRtc=e.webRtc,this.forceTURN=e.forceTURN,this.URL=e.URL,this.turnServers=e.turnServers||[],0===this.turnServers.length&&this.turnServers.push({urls:[o.FALLBACK_STUN_SERVER]}),l.forEach(this.turnServers,function(e){l.checkObjectHasKeys(e,["urls"])}),this.callId="c"+(new Date).getTime()+Math.random(),this.state="fledgling",this.didConnect=!1,this.candidateSendQueue=[],this.candidateSendTries=0,this.mediaPromises=(0,c.default)(null),this.screenSharingStream=null,this._answerContent=null}var i=e("babel-runtime/regenerator"),s=n(i),a=e("bluebird"),u=e("babel-runtime/core-js/object/create"),c=n(u),l=e("../utils"),d=e("events").EventEmitter;o.CALL_TIMEOUT_MS=6e4,o.FALLBACK_STUN_SERVER="stun:stun.l.google.com:19302",o.ERR_LOCAL_OFFER_FAILED="local_offer_failed",o.ERR_NO_USER_MEDIA="no_user_media",o.ERR_UNKNOWN_DEVICES="unknown_devices",o.ERR_SEND_INVITE="send_invite",o.ERR_SEND_ANSWER="send_answer",l.inherits(o,d),o.prototype.placeVoiceCall=function(){S("placeVoiceCall"),E(this),T(this,I("voice")),this.type="voice"},o.prototype.placeVideoCall=function(e,t){S("placeVideoCall"),E(this),this.localVideoElement=t,this.remoteVideoElement=e,T(this,I("video")),this.type="video",g(this)},o.prototype.placeScreenSharingCall=function(e,t){S("placeScreenSharingCall"),E(this);var r=R(this);if(r){this.localVideoElement=t,this.remoteVideoElement=e;var n=this;this.webRtc.getUserMedia(r,function(e){n.screenSharingStream=e,S("Got screen stream, requesting audio stream...");var t=I("voice");T(n,t)},function(e){n.emit("error",w(o.ERR_NO_USER_MEDIA,"Failed to get screen-sharing stream: "+e))}),this.type="video",g(this)}},o.prototype.playElement=function(e,t){console.log("queuing play on "+t+" and element "+e),this.mediaPromises[t]?this.mediaPromises[t]=this.mediaPromises[t].then(function(){return console.log("previous promise completed for "+t),e.play()},function(){return console.log("previous promise failed for "+t),e.play()}):this.mediaPromises[t]=e.play()},o.prototype.pauseElement=function(e,t){console.log("queuing pause on "+t+" and element "+e),this.mediaPromises[t]?this.mediaPromises[t]=this.mediaPromises[t].then(function(){return console.log("previous promise completed for "+t),e.pause()},function(){return console.log("previous promise failed for "+t),e.pause()}):this.mediaPromises[t]=e.pause()},o.prototype.assignElement=function(e,t,r){console.log("queuing assign on "+r+" element "+e+" for "+t),this.mediaPromises[r]?this.mediaPromises[r]=this.mediaPromises[r].then(function(){console.log("previous promise completed for "+r),e.srcObject=t},function(){console.log("previous promise failed for "+r),e.srcObject=t}):e.srcObject=t},o.prototype.getLocalVideoElement=function(){return this.localVideoElement},o.prototype.getRemoteVideoElement=function(){return this.remoteVideoElement},o.prototype.getRemoteAudioElement=function(){return this.remoteAudioElement},o.prototype.setLocalVideoElement=function(e){if(this.localVideoElement=e,e&&this.localAVStream&&"video"===this.type){e.autoplay=!0,this.assignElement(e,this.localAVStream,"localVideo"),e.muted=!0;var t=this;setTimeout(function(){var e=t.getLocalVideoElement();e.play&&t.playElement(e,"localVideo")},0)}},o.prototype.setRemoteVideoElement=function(e){this.remoteVideoElement=e,g(this)},o.prototype.setRemoteAudioElement=function(e){this.remoteVideoElement.muted=!0,this.remoteAudioElement=e,this.remoteAudioElement.muted=!1,b(this)},o.prototype._initWithInvite=function(e){this.msg=e.getContent(),this.peerConn=x(this);var t=this;this.peerConn&&this.peerConn.setRemoteDescription(new this.webRtc.RtcSessionDescription(this.msg.offer),C(t,t._onSetRemoteDescriptionSuccess),C(t,t._onSetRemoteDescriptionError)),h(this,"ringing"),this.direction="inbound",this.msg.offer&&this.msg.offer.sdp&&this.msg.offer.sdp.indexOf("m=video")>-1?this.type="video":this.type="voice",e.getAge()&&setTimeout(function(){"ringing"==t.state&&(S("Call invite has expired. Hanging up."),t.hangupParty="remote",h(t,"ended"),_(t),"closed"!=t.peerConn.signalingState&&t.peerConn.close(),t.emit("hangup",t))},this.msg.lifetime-e.getAge())},o.prototype._initWithHangup=function(e){this.msg=e.getContent(),h(this,"ended")},o.prototype.answer=function(){S("Answering call %s of type %s",this.callId,this.type);var e=this;if(e._answerContent)return void e._sendAnswer();this.localAVStream||this.waitForLocalAVStream?this.localAVStream?this._maybeGotUserMediaForAnswer(this.localAVStream):this.waitForLocalAVStream&&h(this,"wait_local_media"):(this.webRtc.getUserMedia(I(this.type),C(e,e._maybeGotUserMediaForAnswer),C(e,e._maybeGotUserMediaForAnswer)),h(this,"wait_local_media"))},o.prototype._replacedBy=function(e){S(this.callId+" being replaced by "+e.callId),"wait_local_media"==this.state?(S("Telling new call to wait for local media"),e.waitForLocalAVStream=!0):"create_offer"==this.state?(S("Handing local stream to new call"),e._maybeGotUserMediaForAnswer(this.localAVStream),delete this.localAVStream):"invite_sent"==this.state&&(S("Handing local stream to new call"),e._maybeGotUserMediaForAnswer(this.localAVStream),delete this.localAVStream),e.localVideoElement=this.localVideoElement,e.remoteVideoElement=this.remoteVideoElement,e.remoteAudioElement=this.remoteAudioElement,this.successor=e,this.emit("replaced",e),this.hangup(!0)},o.prototype.hangup=function(e,t){if("ended"!=this.state){S("Ending call "+this.callId),y(this,"local",e,!t);var r={version:0,call_id:this.callId,reason:e};v(this,"m.call.hangup",r)}},o.prototype.setLocalVideoMuted=function(e){this.localAVStream&&f(this.localAVStream.getVideoTracks(),!e)},o.prototype.isLocalVideoMuted=function(){return!!this.localAVStream&&!p(this.localAVStream.getVideoTracks())},o.prototype.setMicrophoneMuted=function(e){this.localAVStream&&f(this.localAVStream.getAudioTracks(),!e)},o.prototype.isMicrophoneMuted=function(){return!!this.localAVStream&&!p(this.localAVStream.getAudioTracks())},o.prototype._maybeGotUserMediaForInvite=function(e){if(this.successor)return void this.successor._maybeGotUserMediaForAnswer(e);if("ended"!=this.state){S("_maybeGotUserMediaForInvite -> "+this.type);var t=this,r=e,n={mandatory:{OfferToReceiveAudio:!0,OfferToReceiveVideo:"video"===t.type}};if(e instanceof MediaStream){var o=this.getLocalVideoElement();o&&"video"==this.type&&(o.autoplay=!0,this.screenSharingStream?(S("Setting screen sharing stream to the local video element"),this.assignElement(o,this.screenSharingStream,"localVideo")):this.assignElement(o,e,"localVideo"),o.muted=!0,setTimeout(function(){var e=t.getLocalVideoElement();e.play&&t.playElement(e,"localVideo")},0)),this.screenSharingStream&&(this.screenSharingStream.addTrack(e.getAudioTracks()[0]),e=this.screenSharingStream),this.localAVStream=e,f(e.getAudioTracks(),!0),this.peerConn=x(this),this.peerConn.addStream(e)}else{if("PermissionDeniedError"!==r.name)return S("Failed to getUserMedia."),void this._getUserMediaFailed(r);S("User denied access to camera/microphone. Or possibly you are using an insecure domain. Receiving only."),this.peerConn=x(this)}this.peerConn.createOffer(C(t,t._gotLocalOffer),C(t,t._getLocalOfferFailed),n),h(t,"create_offer")}},o.prototype._sendAnswer=function(e){var t=this;v(this,"m.call.answer",this._answerContent).then(function(){h(t,"connecting"),k(t)}).catch(function(e){h(t,"ringing"),t.client.cancelPendingEvent(e.event);var r=o.ERR_SEND_ANSWER,n="Failed to send answer";throw"UnknownDeviceError"==e.name&&(r=o.ERR_UNKNOWN_DEVICES,n="Unknown devices present in the room"),t.emit("error",w(r,n)),e})},o.prototype._maybeGotUserMediaForAnswer=function(e){var t=this;if("ended"!=t.state){var r=e;if(e instanceof MediaStream){var n=t.getLocalVideoElement();n&&"video"==t.type&&(n.autoplay=!0,this.assignElement(n,e,"localVideo"),n.muted=!0,setTimeout(function(){var e=t.getLocalVideoElement();e.play&&t.playElement(e,"localVideo")},0)),t.localAVStream=e,f(e.getAudioTracks(),!0),t.peerConn.addStream(e)}else{if("PermissionDeniedError"!==r.name)return S("Failed to getUserMedia."),void this._getUserMediaFailed(r);S("User denied access to camera/microphone. Or possibly you are using an insecure domain. Receiving only.")}var o={mandatory:{OfferToReceiveAudio:!0,OfferToReceiveVideo:"video"===t.type}};t.peerConn.createAnswer(function(e){S("Created answer: "+e),t.peerConn.setLocalDescription(e,function(){t._answerContent={version:0,call_id:t.callId,answer:{sdp:t.peerConn.localDescription.sdp,type:t.peerConn.localDescription.type}},t._sendAnswer()},function(){S("Error setting local description!")},o)},function(e){S("Failed to create answer: "+e)}),h(t,"create_answer")}},o.prototype._gotLocalIceCandidate=function(e){if(e.candidate){if(S("Got local ICE "+e.candidate.sdpMid+" candidate: "+e.candidate.candidate),"ended"==this.state)return;var t={candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex};m(this,t)}},o.prototype._gotRemoteIceCandidate=function(e){"ended"!=this.state&&(S("Got remote ICE "+e.sdpMid+" candidate: "+e.candidate),this.peerConn.addIceCandidate(new this.webRtc.RtcIceCandidate(e),function(){},function(e){}))},o.prototype._receivedAnswer=function(e){if("ended"!=this.state){var t=this;this.peerConn.setRemoteDescription(new this.webRtc.RtcSessionDescription(e.answer),C(t,t._onSetRemoteDescriptionSuccess),C(t,t._onSetRemoteDescriptionError)),h(t,"connecting")}},o.prototype._gotLocalOffer=function(e){var t=this;if(S("Created offer: "+e),"ended"==t.state)return void S("Ignoring newly created offer on call ID "+t.callId+" because the call has ended");t.peerConn.setLocalDescription(e,function(){var e={version:0,call_id:t.callId,offer:{sdp:t.peerConn.localDescription.sdp,type:t.peerConn.localDescription.type},lifetime:o.CALL_TIMEOUT_MS};v(t,"m.call.invite",e).then(function(){h(t,"invite_sent"),setTimeout(function(){"invite_sent"==t.state&&t.hangup("invite_timeout")},o.CALL_TIMEOUT_MS)}).catch(function(e){var r=o.ERR_SEND_INVITE,n="Failed to send invite";throw"UnknownDeviceError"==e.name&&(r=o.ERR_UNKNOWN_DEVICES,n="Unknown devices present in the room"),t.client.cancelPendingEvent(e.event),y(t,"local",r,!1),t.emit("error",w(r,n)),e})},function(){S("Error setting local description!")})},o.prototype._getLocalOfferFailed=function(e){this.emit("error",w(o.ERR_LOCAL_OFFER_FAILED,"Failed to start audio for call!"))},o.prototype._getUserMediaFailed=function(e){y(this,"local","user_media_failed",!1),this.emit("error",w(o.ERR_NO_USER_MEDIA,"Couldn't start capturing media! Is your microphone set up and does this app have permission?"))},o.prototype._onIceConnectionStateChanged=function(){"ended"!=this.state&&(S("Ice connection state changed to: "+this.peerConn.iceConnectionState),"completed"==this.peerConn.iceConnectionState||"connected"==this.peerConn.iceConnectionState?(h(this,"connected"),this.didConnect=!0):"failed"==this.peerConn.iceConnectionState&&this.hangup("ice_failed"))},o.prototype._onSignallingStateChanged=function(){S("call "+this.callId+": Signalling state changed to: "+this.peerConn.signalingState)},o.prototype._onSetRemoteDescriptionSuccess=function(){S("Set remote description")},o.prototype._onSetRemoteDescriptionError=function(e){S("Failed to set remote description"+e)},o.prototype._onAddStream=function(e){S("Stream id "+e.stream.id+" added");var t=e.stream;t.getVideoTracks().length>0?(this.type="video",this.remoteAVStream=t,this.remoteAStream=t):(this.type="voice",this.remoteAStream=t);var r=this;A(t,function(e){S("Track id "+e.id+" added"),e.onstarted=C(r,r._onRemoteStreamTrackStarted)}),void 0!==e.stream.oninactive?e.stream.oninactive=C(r,r._onRemoteStreamEnded):e.stream.onended=C(r,r._onRemoteStreamEnded),e.stream.onstarted=C(r,r._onRemoteStreamStarted),"video"===this.type?(g(this),b(this)):b(this)},o.prototype._onRemoteStreamStarted=function(e){h(this,"connected")},o.prototype._onRemoteStreamEnded=function(e){S("Remote stream ended"),this.hangupParty="remote",h(this,"ended"),_(this),"closed"!=this.peerConn.signalingState&&this.peerConn.close(),this.emit("hangup",this)},o.prototype._onRemoteStreamTrackStarted=function(e){h(this,"connected")},o.prototype._onHangupReceived=function(e){S("Hangup received"),y(this,"remote",e.reason,!0)},o.prototype._onAnsweredElsewhere=function(e){S("Answered elsewhere"),y(this,"remote","answered_elsewhere",!0)};var f=function(e,t){for(var r=0;r5)return S("Failed to send candidates on attempt %s. Giving up for now.",t.candidateSendTries),void(t.candidateSendTries=0);var i=500*Math.pow(2,t.candidateSendTries);++t.candidateSendTries,S("Failed to send candidates. Retrying in "+i+"ms"),setTimeout(function(){e(t)},i)})}},T=function(e,t){e.client.callList[e.callId]=e,e.webRtc.getUserMedia(t,C(e,e._maybeGotUserMediaForInvite),C(e,e._maybeGotUserMediaForInvite)),h(e,"wait_local_media"),e.direction="outbound",e.config=t},x=function(e){var t=e.turnServers;if("mozilla"===e.webRtc.vendor){t=[];for(var r=0;r-1)return!0;return!1};var u=i.navigator.getUserMedia||i.navigator.webkitGetUserMedia||i.navigator.mozGetUserMedia;if(u&&(a.getUserMedia=function(){return u.apply(i.navigator,arguments)}),a.RtcPeerConnection=i.RTCPeerConnection||i.webkitRTCPeerConnection||i.mozRTCPeerConnection,a.RtcSessionDescription=i.RTCSessionDescription||i.webkitRTCSessionDescription||i.mozRTCSessionDescription,a.RtcIceCandidate=i.RTCIceCandidate||i.webkitRTCIceCandidate||i.mozRTCIceCandidate,a.vendor=null,i.mozRTCPeerConnection?a.vendor="mozilla":i.webkitRTCPeerConnection?a.vendor="webkit":i.RTCPeerConnection&&(a.vendor="generic"),!(a.RtcIceCandidate&&a.RtcSessionDescription&&a.RtcPeerConnection&&a.getUserMedia))return null;var c=!!n&&n.forceTURN;return new o({webRtc:a,client:e,URL:i.URL,roomId:t,turnServers:e.getTurnServers(),forceTURN:e._forceTURN||c})}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../utils":55,"babel-runtime/core-js/object/create":64,"babel-runtime/regenerator":86,bluebird:89,events:234}],57:[function(e,t,r){"use strict";function n(e){return a.lastIndex=0,e.replace(a,function(e){return u[e]})}function o(e){switch(typeof e){case"string":return'"'+n(e)+'"';case"number":return isFinite(e)?e:"null";case"boolean":return e;case"object":return null===e?"null":Array.isArray(e)?i(e):s(e);default:throw new Error("Cannot stringify: "+typeof e)}}function i(e){for(var t="[",r="",n=0;n0;)r.push(i%s),i=i/s|0}for(var u="",c=0;0===t[c]&&c=0;--l)u+=e[r[l]];return u}function r(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return n.allocUnsafe(0);for(var t=[0],r=0;r>=8;for(;c>0;)t.push(255&c),c>>=8}for(var l=0;e[l]===a&&l0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function o(e){var t=n(e),r=t[0],o=t[1];return 3*(r+o)/4-o}function i(e,t,r){return 3*(t+r)/4-r}function s(e){for(var t,r=n(e),o=r[0],s=r[1],a=new f(i(e,o,s)),u=0,c=s>0?o-4:o,l=0;l>16&255,a[u++]=t>>8&255,a[u++]=255&t;return 2===s&&(t=d[e.charCodeAt(l)]<<2|d[e.charCodeAt(l+1)]>>4,a[u++]=255&t),1===s&&(t=d[e.charCodeAt(l)]<<10|d[e.charCodeAt(l+1)]<<4|d[e.charCodeAt(l+2)]>>2,a[u++]=t>>8&255,a[u++]=255&t),a}function a(e){return l[e>>18&63]+l[e>>12&63]+l[e>>6&63]+l[63&e]}function u(e,t,r){for(var n,o=[],i=t;is?s:i+16383));return 1===n?(t=e[r-1],o.push(l[t>>2]+l[t<<4&63]+"==")):2===n&&(t=(e[r-2]<<8)+e[r-1],o.push(l[t>>10]+l[t>>4&63]+l[t<<2&63]+"=")),o.join("")}r.byteLength=o,r.toByteArray=s,r.fromByteArray=c;for(var l=[],d=[],f="undefined"!=typeof Uint8Array?Uint8Array:Array,p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=0,v=p.length;h0;)c(e)}function c(e){var t=e.shift();if("function"!=typeof t)t._settlePromises();else{var r=e.shift(),n=e.shift();t.call(r,n)}}var l;try{throw new Error}catch(e){l=e}var d=t("./schedule"),f=t("./queue"),p=t("./util");o.prototype.setScheduler=function(e){var t=this._schedule;return this._schedule=e,this._customScheduler=!0,t},o.prototype.hasCustomScheduler=function(){return this._customScheduler},o.prototype.enableTrampoline=function(){this._trampolineEnabled=!0},o.prototype.disableTrampolineIfNecessary=function(){p.hasDevTools&&(this._trampolineEnabled=!1)},o.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues},o.prototype.fatalError=function(t,r){r?(e.stderr.write("Fatal "+(t instanceof Error?t.stack:t)+"\n"),e.exit(2)):this.throwLater(t)},o.prototype.throwLater=function(e,t){if(1===arguments.length&&(t=e,e=function(){throw t}),"undefined"!=typeof setTimeout)setTimeout(function(){e(t)},0);else try{this._schedule(function(){e(t)})}catch(e){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}},p.hasDevTools?(o.prototype.invokeLater=function(e,t,r){this._trampolineEnabled?i.call(this,e,t,r):this._schedule(function(){setTimeout(function(){e.call(t,r)},100)})},o.prototype.invoke=function(e,t,r){this._trampolineEnabled?s.call(this,e,t,r):this._schedule(function(){e.call(t,r)})},o.prototype.settlePromises=function(e){this._trampolineEnabled?a.call(this,e):this._schedule(function(){e._settlePromises()})}):(o.prototype.invokeLater=i,o.prototype.invoke=s,o.prototype.settlePromises=a),o.prototype._drainQueues=function(){u(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,u(this._lateQueue)},o.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},o.prototype._reset=function(){this._isTickUsed=!1},r.exports=o,r.exports.firstLineError=l},{"./queue":26,"./schedule":29,"./util":36}],3:[function(e,t,r){"use strict";t.exports=function(e,t,r,n){var o=!1,i=function(e,t){this._reject(t)},s=function(e,t){t.promiseRejectionQueued=!0,t.bindingPromise._then(i,i,null,this,e)},a=function(e,t){0==(50397184&this._bitField)&&this._resolveCallback(t.target)},u=function(e,t){t.promiseRejectionQueued||this._reject(e)};e.prototype.bind=function(i){o||(o=!0,e.prototype._propagateFrom=n.propagateFromFunction(),e.prototype._boundValue=n.boundValueFunction());var c=r(i),l=new e(t);l._propagateFrom(this,1);var d=this._target();if(l._setBoundTo(c),c instanceof e){var f={promiseRejectionQueued:!1,promise:l,target:d,bindingPromise:c};d._then(t,s,void 0,l,f),c._then(a,u,void 0,l,f),l._setOnCancel(c)}else l._resolveCallback(d);return l},e.prototype._setBoundTo=function(e){void 0!==e?(this._bitField=2097152|this._bitField,this._boundTo=e):this._bitField=-2097153&this._bitField},e.prototype._isBound=function(){return 2097152==(2097152&this._bitField)},e.bind=function(t,r){return e.resolve(r).bind(t)}}},{}],4:[function(e,t,r){"use strict";function n(){try{Promise===i&&(Promise=o)}catch(e){}return i}var o;"undefined"!=typeof Promise&&(o=Promise);var i=e("./promise")();i.noConflict=n,t.exports=i},{"./promise":22}],5:[function(e,t,r){"use strict";var n=Object.create;if(n){var o=n(null),i=n(null);o[" size"]=i[" size"]=0}t.exports=function(t){function r(e,r){var n;if(null!=e&&(n=e[r]),"function"!=typeof n){var o="Object "+a.classString(e)+" has no method '"+a.toString(r)+"'";throw new t.TypeError(o)}return n}function n(e){return r(e,this.pop()).apply(e,this)}function o(e){return e[this]}function i(e){var t=+this;return t<0&&(t=Math.max(0,t+e.length)),e[t]}var s,a=e("./util"),u=a.canEvaluate;a.isIdentifier;t.prototype.call=function(e){var t=[].slice.call(arguments,1);return t.push(e),this._then(n,void 0,void 0,t,void 0)},t.prototype.get=function(e){var t,r="number"==typeof e;if(r)t=i;else if(u){var n=s(e);t=null!==n?n:o}else t=o;return this._then(t,void 0,void 0,e,void 0)}}},{"./util":36}],6:[function(e,t,r){"use strict";t.exports=function(t,r,n,o){var i=e("./util"),s=i.tryCatch,a=i.errorObj,u=t._async;t.prototype.break=t.prototype.cancel=function(){if(!o.cancellation())return this._warn("cancellation is disabled");for(var e=this,t=e;e._isCancellable();){if(!e._cancelBy(t)){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}var r=e._cancellationParent;if(null==r||!r._isCancellable()){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}e._isFollowing()&&e._followee().cancel(),e._setWillBeCancelled(),t=e,e=r}},t.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},t.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},t.prototype._cancelBy=function(e){return e===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},t.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},t.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),u.invoke(this._cancelPromises,this,void 0))},t.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},t.prototype._unsetOnCancel=function(){this._onCancelField=void 0},t.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},t.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},t.prototype._doInvokeOnCancel=function(e,t){if(i.isArray(e))for(var r=0;r=0)return i[e]}var o=!1,i=[];return e.prototype._promiseCreated=function(){},e.prototype._pushContext=function(){},e.prototype._popContext=function(){return null},e._peekContext=e.prototype._peekContext=function(){},t.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,i.push(this._trace))},t.prototype._popContext=function(){if(void 0!==this._trace){var e=i.pop(),t=e._promiseCreated;return e._promiseCreated=null,t}return null},t.CapturedTrace=null,t.create=r,t.deactivateLongStackTraces=function(){},t.activateLongStackTraces=function(){var r=e.prototype._pushContext,i=e.prototype._popContext,s=e._peekContext,a=e.prototype._peekContext,u=e.prototype._promiseCreated;t.deactivateLongStackTraces=function(){e.prototype._pushContext=r,e.prototype._popContext=i,e._peekContext=s,e.prototype._peekContext=a,e.prototype._promiseCreated=u,o=!1},o=!0,e.prototype._pushContext=t.prototype._pushContext,e.prototype._popContext=t.prototype._popContext,e._peekContext=e.prototype._peekContext=n,e.prototype._promiseCreated=function(){var e=this._peekContext();e&&null==e._promiseCreated&&(e._promiseCreated=this)}},t}},{}],9:[function(t,r,n){"use strict";r.exports=function(r,n){function o(e,t){return{promise:t}}function i(){return!1}function s(e,t,r){var n=this;try{e(t,r,function(e){if("function"!=typeof e)throw new TypeError("onCancel must be a function, got: "+q.toString(e));n._attachCancellationCallback(e)})}catch(e){return e}}function a(e){if(!this._isCancellable())return this;var t=this._onCancel();void 0!==t?q.isArray(t)?t.push(e):this._setOnCancel([t,e]):this._setOnCancel(e)}function u(){return this._onCancelField}function c(e){this._onCancelField=e}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function d(e,t){if(0!=(1&t)){this._cancellationParent=e;var r=e._branchesRemainingToCancel;void 0===r&&(r=0),e._branchesRemainingToCancel=r+1}0!=(2&t)&&e._isBound()&&this._setBoundTo(e._boundTo)}function f(e,t){0!=(2&t)&&e._isBound()&&this._setBoundTo(e._boundTo)}function p(){var e=this._boundTo;return void 0!==e&&e instanceof r?e.isFulfilled()?e.value():void 0:e}function h(){this._trace=new D(this._peekContext())}function v(e,t){if(K(e)){var r=this._trace;if(void 0!==r&&t&&(r=r._parent),void 0!==r)r.attachExtraTrace(e);else if(!e.__stackCleaned__){var n=T(e);q.notEnumerableProp(e,"stack",n.message+"\n"+n.stack.join("\n")),q.notEnumerableProp(e,"__stackCleaned__",!0)}}}function m(){this._trace=void 0}function y(e,t,r,n,o){if(void 0===e&&null!==t&&X){if(void 0!==o&&o._returnedNonUndefined())return;if(0==(65535&n._bitField))return;r&&(r+=" ");var i="",s="";if(t._trace){for(var a=t._trace.stack.split("\n"),u=S(a),c=u.length-1;c>=0;--c){var l=u[c];if(!$.test(l)){var d=l.match(V);d&&(i="at "+d[1]+":"+d[2]+":"+d[3]+" ");break}}if(u.length>0)for(var f=u[0],c=0;c0&&(s="\n"+a[c-1]);break}}var p="a promise was created in a "+r+"handler "+i+"but was not returned from it, see http://goo.gl/rRqMUw"+s;n._warn(p,!0,t)}}function _(e,t){var r=e+" is deprecated and will be removed in a future version.";return t&&(r+=" Use "+t+" instead."),g(r)}function g(e,t,n){if(ue.warnings){var o,i=new F(e);if(t)n._attachExtraTrace(i);else if(ue.longStackTraces&&(o=r._peekContext()))o.attachExtraTrace(i);else{var s=T(i);i.stack=s.message+"\n"+s.stack.join("\n")}ne("warning",i)||x(i,"",!0)}}function b(e,t){for(var r=0;r=0;--a)if(n[a]===i){s=a;break}for(var a=s;a>=0;--a){var u=n[a];if(t[o]!==u)break;t.pop(),o--}t=n}}function S(e){for(var t=[],r=0;r0&&"SyntaxError"!=e.name&&(t=t.slice(r)),t}function T(e){var t=e.stack,r=e.toString();return t="string"==typeof t&&t.length>0?k(e):[" (No stack trace)"],{message:r,stack:"SyntaxError"==e.name?t:S(t)}}function x(e,t,r){if("undefined"!=typeof console){var n;if(q.isObject(e)){var o=e.stack;n=t+H(o,e)}else n=t+String(e);"function"==typeof L?L(n,r):"function"!=typeof console.log&&"object"!=typeof console.log||console.log(n)}}function R(e,t,r,n){var o=!1;try{"function"==typeof t&&(o=!0,"rejectionHandled"===e?t(n):t(r,n))}catch(e){N.throwLater(e)}"unhandledRejection"===e?ne(e,r,n)||o||x(r,"Unhandled rejection "):ne(e,n)}function I(e){var t;if("function"==typeof e)t="[function "+(e.name||"anonymous")+"]";else{t=e&&"function"==typeof e.toString?e.toString():q.toString(e);if(/\[object [a-zA-Z0-9$_]+\]/.test(t))try{t=JSON.stringify(e)}catch(e){}0===t.length&&(t="(empty array)")}return"(<"+C(t)+">, no stack trace)"}function C(e){return e.length<41?e:e.substr(0,38)+"..."}function j(){return"function"==typeof ae}function O(e){var t=e.match(se);if(t)return{fileName:t[1],line:parseInt(t[2],10)}}function A(e,t){if(j()){for(var r,n,o=e.stack.split("\n"),i=t.stack.split("\n"),s=-1,a=-1,u=0;u=a||(ie=function(e){if(G.test(e))return!0;var t=O(e);return!!(t&&t.fileName===r&&s<=t.line&&t.line<=a)})}}function D(e){this._parent=e,this._promisesCreated=0;var t=this._length=1+(void 0===e?0:e._length);ae(this,D),t>32&&this.uncycle()}var M,P,L,U=r._getDomain,N=r._async,F=t("./errors").Warning,q=t("./util"),B=t("./es5"),K=q.canAttachTrace,G=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,$=/\((?:timers\.js):\d+:\d+\)/,V=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,W=null,H=null,z=!1,Q=!(0==q.env("BLUEBIRD_DEBUG")),J=!(0==q.env("BLUEBIRD_WARNINGS")||!Q&&!q.env("BLUEBIRD_WARNINGS")),Y=!(0==q.env("BLUEBIRD_LONG_STACK_TRACES")||!Q&&!q.env("BLUEBIRD_LONG_STACK_TRACES")),X=0!=q.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(J||!!q.env("BLUEBIRD_W_FORGOTTEN_RETURN"));r.prototype.suppressUnhandledRejections=function(){var e=this._target();e._bitField=-1048577&e._bitField|524288},r.prototype._ensurePossibleRejectionHandled=function(){if(0==(524288&this._bitField)){this._setRejectionIsUnhandled();var e=this;setTimeout(function(){e._notifyUnhandledRejection()},1)}},r.prototype._notifyUnhandledRejectionIsHandled=function(){R("rejectionHandled",M,void 0,this)},r.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},r.prototype._returnedNonUndefined=function(){return 0!=(268435456&this._bitField)},r.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var e=this._settledValue();this._setUnhandledRejectionIsNotified(),R("unhandledRejection",P,e,this)}},r.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},r.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},r.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},r.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},r.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},r.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},r.prototype._warn=function(e,t,r){return g(e,t,r||this)},r.onPossiblyUnhandledRejection=function(e){var t=U();P="function"==typeof e?null===t?e:q.domainBind(t,e):void 0},r.onUnhandledRejectionHandled=function(e){var t=U();M="function"==typeof e?null===t?e:q.domainBind(t,e):void 0};var Z=function(){};r.longStackTraces=function(){if(N.haveItemsQueued()&&!ue.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ue.longStackTraces&&j()){var e=r.prototype._captureStackTrace,t=r.prototype._attachExtraTrace,o=r.prototype._dereferenceTrace;ue.longStackTraces=!0,Z=function(){if(N.haveItemsQueued()&&!ue.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");r.prototype._captureStackTrace=e,r.prototype._attachExtraTrace=t,r.prototype._dereferenceTrace=o,n.deactivateLongStackTraces(),N.enableTrampoline(),ue.longStackTraces=!1},r.prototype._captureStackTrace=h,r.prototype._attachExtraTrace=v,r.prototype._dereferenceTrace=m,n.activateLongStackTraces(),N.disableTrampolineIfNecessary()}},r.hasLongStackTraces=function(){return ue.longStackTraces&&j()};var ee=function(){try{if("function"==typeof CustomEvent){var e=new CustomEvent("CustomEvent");return q.global.dispatchEvent(e),function(e,t){var r={detail:t,cancelable:!0};B.defineProperty(r,"promise",{value:t.promise}),B.defineProperty(r,"reason",{value:t.reason});var n=new CustomEvent(e.toLowerCase(),r);return!q.global.dispatchEvent(n)}}if("function"==typeof Event){var e=new Event("CustomEvent");return q.global.dispatchEvent(e),function(e,t){var r=new Event(e.toLowerCase(),{cancelable:!0});return r.detail=t,B.defineProperty(r,"promise",{value:t.promise}),B.defineProperty(r,"reason",{value:t.reason}),!q.global.dispatchEvent(r)}}var e=document.createEvent("CustomEvent");return e.initCustomEvent("testingtheevent",!1,!0,{}),q.global.dispatchEvent(e),function(e,t){var r=document.createEvent("CustomEvent");return r.initCustomEvent(e.toLowerCase(),!1,!0,t),!q.global.dispatchEvent(r)}}catch(e){}return function(){return!1}}(),te=function(){return q.isNode?function(){return e.emit.apply(e,arguments)}:q.global?function(e){var t="on"+e.toLowerCase(),r=q.global[t];return!!r&&(r.apply(q.global,[].slice.call(arguments,1)),!0)}:function(){return!1}}(),re={promiseCreated:o,promiseFulfilled:o,promiseRejected:o,promiseResolved:o,promiseCancelled:o,promiseChained:function(e,t,r){return{promise:t,child:r}},warning:function(e,t){return{warning:t}},unhandledRejection:function(e,t,r){return{reason:t,promise:r}},rejectionHandled:o},ne=function(e){var t=!1;try{t=te.apply(null,arguments)}catch(e){N.throwLater(e),t=!0}var r=!1;try{r=ee(e,re[e].apply(null,arguments))}catch(e){N.throwLater(e),r=!0}return r||t};r.config=function(e){if(e=Object(e),"longStackTraces"in e&&(e.longStackTraces?r.longStackTraces():!e.longStackTraces&&r.hasLongStackTraces()&&Z()),"warnings"in e){var t=e.warnings;ue.warnings=!!t,X=ue.warnings,q.isObject(t)&&"wForgottenReturn"in t&&(X=!!t.wForgottenReturn)}if("cancellation"in e&&e.cancellation&&!ue.cancellation){if(N.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");r.prototype._clearCancellationData=l,r.prototype._propagateFrom=d,r.prototype._onCancel=u,r.prototype._setOnCancel=c,r.prototype._attachCancellationCallback=a,r.prototype._execute=s,oe=d,ue.cancellation=!0}return"monitoring"in e&&(e.monitoring&&!ue.monitoring?(ue.monitoring=!0,r.prototype._fireEvent=ne):!e.monitoring&&ue.monitoring&&(ue.monitoring=!1,r.prototype._fireEvent=i)),r},r.prototype._fireEvent=i,r.prototype._execute=function(e,t,r){try{e(t,r)}catch(e){return e}},r.prototype._onCancel=function(){},r.prototype._setOnCancel=function(e){},r.prototype._attachCancellationCallback=function(e){},r.prototype._captureStackTrace=function(){},r.prototype._attachExtraTrace=function(){},r.prototype._dereferenceTrace=function(){},r.prototype._clearCancellationData=function(){},r.prototype._propagateFrom=function(e,t){};var oe=f,ie=function(){return!1},se=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;q.inherits(D,Error),n.CapturedTrace=D,D.prototype.uncycle=function(){var e=this._length;if(!(e<2)){for(var t=[],r={},n=0,o=this;void 0!==o;++n)t.push(o),o=o._parent;e=this._length=n;for(var n=e-1;n>=0;--n){var i=t[n].stack;void 0===r[i]&&(r[i]=n)}for(var n=0;n0&&(t[a-1]._parent=void 0,t[a-1]._length=1),t[n]._parent=void 0,t[n]._length=1;var u=n>0?t[n-1]:this;a=0;--l)t[l]._length=c,c++;return}}}},D.prototype.attachExtraTrace=function(e){if(!e.__stackCleaned__){this.uncycle();for(var t=T(e),r=t.message,n=[t.stack],o=this;void 0!==o;)n.push(S(o.stack.split("\n"))),o=o._parent;w(n),E(n),q.notEnumerableProp(e,"stack",b(r,n)),q.notEnumerableProp(e,"__stackCleaned__",!0)}};var ae=function(){var e=/^\s*at\s*/,t=function(e,t){return"string"==typeof e?e:void 0!==t.name&&void 0!==t.message?t.toString():I(t)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,W=e,H=t;var r=Error.captureStackTrace;return ie=function(e){return G.test(e)},function(e,t){Error.stackTraceLimit+=6,r(e,t),Error.stackTraceLimit-=6}}var n=new Error;if("string"==typeof n.stack&&n.stack.split("\n")[0].indexOf("stackDetection@")>=0)return W=/@/,H=t,z=!0,function(e){e.stack=(new Error).stack};var o;try{throw new Error}catch(e){o="stack"in e}return"stack"in n||!o||"number"!=typeof Error.stackTraceLimit?(H=function(e,t){return"string"==typeof e?e:"object"!=typeof t&&"function"!=typeof t||void 0===t.name||void 0===t.message?I(t):t.toString()},null):(W=e,H=t,function(e){Error.stackTraceLimit+=6;try{throw new Error}catch(t){e.stack=t.stack}Error.stackTraceLimit-=6})}();"undefined"!=typeof console&&void 0!==console.warn&&(L=function(e){console.warn(e)},q.isNode&&e.stderr.isTTY?L=function(e,t){var r=t?"":"";console.warn(r+e+"\n")}:q.isNode||"string"!=typeof(new Error).stack||(L=function(e,t){console.warn("%c"+e,t?"color: darkorange":"color: red")}));var ue={warnings:J,longStackTraces:!1,cancellation:!1,monitoring:!1};return Y&&r.longStackTraces(),{longStackTraces:function(){return ue.longStackTraces},warnings:function(){return ue.warnings},cancellation:function(){return ue.cancellation},monitoring:function(){return ue.monitoring},propagateFromFunction:function(){return oe},boundValueFunction:function(){return p},checkForgottenReturns:y,setBounds:A,warn:g,deprecated:_,CapturedTrace:D,fireDomEvent:ee,fireGlobalEvent:te}}},{"./errors":12,"./es5":13,"./util":36}],10:[function(e,t,r){"use strict";t.exports=function(e){function t(){return this.value}function r(){throw this.reason}e.prototype.return=e.prototype.thenReturn=function(r){return r instanceof e&&r.suppressUnhandledRejections(),this._then(t,void 0,void 0,{value:r},void 0)},e.prototype.throw=e.prototype.thenThrow=function(e){return this._then(r,void 0,void 0,{reason:e},void 0)},e.prototype.catchThrow=function(e){if(arguments.length<=1)return this._then(void 0,r,void 0,{reason:e},void 0);var t=arguments[1],n=function(){throw t};return this.caught(e,n)},e.prototype.catchReturn=function(r){if(arguments.length<=1)return r instanceof e&&r.suppressUnhandledRejections(),this._then(void 0,t,void 0,{value:r},void 0);var n=arguments[1];n instanceof e&&n.suppressUnhandledRejections();var o=function(){return n};return this.caught(r,o)}}},{}],11:[function(e,t,r){"use strict";t.exports=function(e,t){function r(){return i(this)}function n(e,r){return o(e,r,t,t)}var o=e.reduce,i=e.all;e.prototype.each=function(e){return o(this,e,t,0)._then(r,void 0,void 0,this,void 0)},e.prototype.mapSeries=function(e){return o(this,e,t,t)},e.each=function(e,n){return o(e,n,t,0)._then(r,void 0,void 0,e,void 0)},e.mapSeries=n}},{}],12:[function(e,t,r){"use strict";function n(e,t){function r(n){if(!(this instanceof r))return new r(n);d(this,"message","string"==typeof n?n:t),d(this,"name",e),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return l(r,Error),r}function o(e){if(!(this instanceof o))return new o(e);d(this,"name","OperationalError"),d(this,"message",e),this.cause=e,this.isOperational=!0, +e instanceof Error?(d(this,"message",e.message),d(this,"stack",e.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}var i,s,a=e("./es5"),u=a.freeze,c=e("./util"),l=c.inherits,d=c.notEnumerableProp,f=n("Warning","warning"),p=n("CancellationError","cancellation error"),h=n("TimeoutError","timeout error"),v=n("AggregateError","aggregate error");try{i=TypeError,s=RangeError}catch(e){i=n("TypeError","type error"),s=n("RangeError","range error")}for(var m="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),y=0;y1?e.cancelPromise._reject(t):e.cancelPromise._cancel(),e.cancelPromise=null,!0)}function a(){return c.call(this,this.promise._target()._settledValue())}function u(e){if(!s(this,e))return f.e=e,f}function c(e){var o=this.promise,c=this.handler;if(!this.called){this.called=!0;var l=this.isFinallyHandler()?c.call(o._boundValue()):c.call(o._boundValue(),e);if(l===n)return l;if(void 0!==l){o._setReturnedNonUndefined();var p=r(l,o);if(p instanceof t){if(null!=this.cancelPromise){if(p._isCancelled()){var h=new d("late cancellation observer");return o._attachExtraTrace(h),f.e=h,f}p.isPending()&&p._attachCancellationCallback(new i(this))}return p._then(a,u,void 0,this,void 0)}}}return o.isRejected()?(s(this),f.e=e,f):(s(this),e)}var l=e("./util"),d=t.CancellationError,f=l.errorObj,p=e("./catch_filter")(n);return o.prototype.isFinallyHandler=function(){return 0===this.type},i.prototype._resultCancelled=function(){s(this.finallyHandler)},t.prototype._passThrough=function(e,t,r,n){return"function"!=typeof e?this.then():this._then(r,n,void 0,new o(this,t,e),void 0)},t.prototype.lastly=t.prototype.finally=function(e){return this._passThrough(e,0,c,c)},t.prototype.tap=function(e){return this._passThrough(e,1,c)},t.prototype.tapCatch=function(e){var r=arguments.length;if(1===r)return this._passThrough(e,1,void 0,c);var n,o=new Array(r-1),i=0;for(n=0;n0&&"function"==typeof arguments[t]){e=arguments[t];var n}var o=[].slice.call(arguments);e&&o.pop();var n=new r(o).promise();return void 0!==e?n.spread(e):n}}},{"./util":36}],18:[function(e,t,r){"use strict";t.exports=function(t,r,n,o,i,s){function a(e,t,r,n){this.constructor$(e),this._promise._captureStackTrace();var o=c();this._callback=null===o?t:l.domainBind(o,t),this._preservedValues=n===i?new Array(this.length()):null,this._limit=r,this._inFlight=0,this._queue=[],p.invoke(this._asyncInit,this,void 0)}function u(e,r,o,i){if("function"!=typeof r)return n("expecting a function but got "+l.classString(r));var s=0;if(void 0!==o){if("object"!=typeof o||null===o)return t.reject(new TypeError("options argument must be an object but it is "+l.classString(o)));if("number"!=typeof o.concurrency)return t.reject(new TypeError("'concurrency' must be a number but it is "+l.classString(o.concurrency)));s=o.concurrency}return s="number"==typeof s&&isFinite(s)&&s>=1?s:0,new a(e,r,s,i).promise()}var c=t._getDomain,l=e("./util"),d=l.tryCatch,f=l.errorObj,p=t._async;l.inherits(a,r),a.prototype._asyncInit=function(){this._init$(void 0,-2)},a.prototype._init=function(){},a.prototype._promiseFulfilled=function(e,r){var n=this._values,i=this.length(),a=this._preservedValues,u=this._limit;if(r<0){if(r=-1*r-1,n[r]=e,u>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(u>=1&&this._inFlight>=u)return n[r]=e,this._queue.push(r),!1;null!==a&&(a[r]=e);var c=this._promise,l=this._callback,p=c._boundValue();c._pushContext();var h=d(l).call(p,e,r,i),v=c._popContext();if(s.checkForgottenReturns(h,v,null!==a?"Promise.filter":"Promise.map",c),h===f)return this._reject(h.e),!0;var m=o(h,this._promise);if(m instanceof t){m=m._target();var y=m._bitField;if(0==(50397184&y))return u>=1&&this._inFlight++,n[r]=m,m._proxy(this,-1*(r+1)),!1;if(0==(33554432&y))return 0!=(16777216&y)?(this._reject(m._reason()),!0):(this._cancel(),!0);h=m._value()}n[r]=h}return++this._totalResolved>=i&&(null!==a?this._filter(n,a):this._resolve(n),!0)},a.prototype._drainQueue=function(){for(var e=this._queue,t=this._limit,r=this._values;e.length>0&&this._inFlight1){i.deprecated("calling Promise.try with more than 1 argument");var c=arguments[1],l=arguments[2];u=s.isArray(c)?a(e).apply(l,c):a(e).call(l,c)}else u=a(e)();var d=n._popContext();return i.checkForgottenReturns(u,d,"Promise.try",n),n._resolveFromSyncValue(u),n},t.prototype._resolveFromSyncValue=function(e){e===s.errorObj?this._rejectCallback(e.e,!1):this._resolveCallback(e,!0)}}},{"./util":36}],20:[function(e,t,r){"use strict";function n(e){return e instanceof Error&&l.getPrototypeOf(e)===Error.prototype}function o(e){var t;if(n(e)){t=new c(e),t.name=e.name,t.message=e.message,t.stack=e.stack;for(var r=l.keys(e),o=0;o1){var r,n=new Array(t-1),o=0;for(r=0;r0&&"function"!=typeof e&&"function"!=typeof t){var r=".then() only accepts functions but was passed: "+h.classString(e);arguments.length>1&&(r+=", "+h.classString(t)),this._warn(r)}return this._then(e,t,void 0,void 0,void 0)},i.prototype.done=function(e,t){this._then(e,t,void 0,void 0,void 0)._setIsFinal()},i.prototype.spread=function(e){return"function"!=typeof e?f("expecting a function but got "+h.classString(e)):this.all()._then(e,void 0,void 0,w,void 0)},i.prototype.toJSON=function(){var e={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(e.fulfillmentValue=this.value(),e.isFulfilled=!0):this.isRejected()&&(e.rejectionReason=this.reason(),e.isRejected=!0),e},i.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new T(this).promise()},i.prototype.error=function(e){return this.caught(h.originatesFromRejection,e)},i.getNewLibraryCopy=r.exports,i.is=function(e){return e instanceof i},i.fromNode=i.fromCallback=function(e){var t=new i(E);t._captureStackTrace();var r=arguments.length>1&&!!Object(arguments[1]).multiArgs,n=D(e)(O(t,r));return n===A&&t._rejectCallback(n.e,!0),t._isFateSealed()||t._setAsyncGuaranteed(),t},i.all=function(e){return new T(e).promise()},i.cast=function(e){var t=k(e);return t instanceof i||(t=new i(E),t._captureStackTrace(),t._setFulfilled(),t._rejectionHandler0=e),t},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(e){var t=new i(E);return t._captureStackTrace(),t._rejectCallback(e,!0),t},i.setScheduler=function(e){if("function"!=typeof e)throw new g("expecting a function but got "+h.classString(e));return y.setScheduler(e)},i.prototype._then=function(e,t,r,n,o){var s=void 0!==o,a=s?o:new i(E),u=this._target(),l=u._bitField;s||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===n&&0!=(2097152&this._bitField)&&(n=0!=(50397184&l)?this._boundValue():u===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,a));var d=c();if(0!=(50397184&l)){var f,p,v=u._settlePromiseCtx;0!=(33554432&l)?(p=u._rejectionHandler0,f=e):0!=(16777216&l)?(p=u._fulfillmentHandler0,f=t,u._unsetRejectionIsUnhandled()):(v=u._settlePromiseLateCancellationObserver,p=new b("late cancellation observer"),u._attachExtraTrace(p),f=t),y.invoke(v,u,{handler:null===d?f:"function"==typeof f&&h.domainBind(d,f),promise:a,receiver:n,value:p})}else u._addCallbacks(e,t,a,n,d);return a},i.prototype._length=function(){return 65535&this._bitField},i.prototype._isFateSealed=function(){return 0!=(117506048&this._bitField)},i.prototype._isFollowing=function(){return 67108864==(67108864&this._bitField)},i.prototype._setLength=function(e){this._bitField=-65536&this._bitField|65535&e},i.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},i.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},i.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},i.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},i.prototype._isFinal=function(){return(4194304&this._bitField)>0},i.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},i.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},i.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},i.prototype._setAsyncGuaranteed=function(){y.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},i.prototype._receiverAt=function(e){var t=0===e?this._receiver0:this[4*e-4+3];if(t!==p)return void 0===t&&this._isBound()?this._boundValue():t},i.prototype._promiseAt=function(e){return this[4*e-4+2]},i.prototype._fulfillmentHandlerAt=function(e){return this[4*e-4+0]},i.prototype._rejectionHandlerAt=function(e){return this[4*e-4+1]},i.prototype._boundValue=function(){},i.prototype._migrateCallback0=function(e){var t=(e._bitField,e._fulfillmentHandler0),r=e._rejectionHandler0,n=e._promise0,o=e._receiverAt(0);void 0===o&&(o=p),this._addCallbacks(t,r,n,o,null)},i.prototype._migrateCallbackAt=function(e,t){var r=e._fulfillmentHandlerAt(t),n=e._rejectionHandlerAt(t),o=e._promiseAt(t),i=e._receiverAt(t);void 0===i&&(i=p),this._addCallbacks(r,n,o,i,null)},i.prototype._addCallbacks=function(e,t,r,n,o){var i=this._length();if(i>=65531&&(i=0,this._setLength(0)),0===i)this._promise0=r,this._receiver0=n,"function"==typeof e&&(this._fulfillmentHandler0=null===o?e:h.domainBind(o,e)),"function"==typeof t&&(this._rejectionHandler0=null===o?t:h.domainBind(o,t));else{var s=4*i-4;this[s+2]=r,this[s+3]=n,"function"==typeof e&&(this[s+0]=null===o?e:h.domainBind(o,e)),"function"==typeof t&&(this[s+1]=null===o?t:h.domainBind(o,t))}return this._setLength(i+1),i},i.prototype._proxy=function(e,t){this._addCallbacks(void 0,void 0,t,e,null)},i.prototype._resolveCallback=function(e,t){if(0==(117506048&this._bitField)){if(e===this)return this._rejectCallback(l(),!1);var r=k(e,this);if(!(r instanceof i))return this._fulfill(e);t&&this._propagateFrom(r,2);var n=r._target();if(n===this)return void this._reject(l());var o=n._bitField;if(0==(50397184&o)){var s=this._length();s>0&&n._migrateCallback0(this);for(var a=1;a>>16)){if(e===this){var r=l();return this._attachExtraTrace(r),this._reject(r)}this._setFulfilled(),this._rejectionHandler0=e,(65535&t)>0&&(0!=(134217728&t)?this._settlePromises():y.settlePromises(this),this._dereferenceTrace())}},i.prototype._reject=function(e){var t=this._bitField;if(!((117506048&t)>>>16)){if(this._setRejected(),this._fulfillmentHandler0=e,this._isFinal())return y.fatalError(e,h.isNode);(65535&t)>0?y.settlePromises(this):this._ensurePossibleRejectionHandled()}},i.prototype._fulfillPromises=function(e,t){for(var r=1;r0){if(0!=(16842752&e)){var r=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,r,e),this._rejectPromises(t,r)}else{var n=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,n,e),this._fulfillPromises(t,n)}this._setLength(0)}this._clearCancellationData()},i.prototype._settledValue=function(){var e=this._bitField;return 0!=(33554432&e)?this._rejectionHandler0:0!=(16777216&e)?this._fulfillmentHandler0:void 0},i.defer=i.pending=function(){return I.deprecated("Promise.defer","new Promise"),{promise:new i(E),resolve:s,reject:a}},h.notEnumerableProp(i,"_makeSelfResolutionError",l),t("./method")(i,E,k,f,I),t("./bind")(i,E,k,I),t("./cancel")(i,T,f,I),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,T,k,E,y,c),i.Promise=i,i.version="3.5.3",t("./map.js")(i,T,f,k,E,I),t("./call_get.js")(i),t("./using.js")(i,f,k,R,E,I),t("./timers.js")(i,E,I),t("./generators.js")(i,f,E,k,n,I),t("./nodeify.js")(i),t("./promisify.js")(i,E),t("./props.js")(i,T,k,f),t("./race.js")(i,E,k,f),t("./reduce.js")(i,T,f,k,E,I),t("./settle.js")(i,T,I),t("./some.js")(i,T,f),t("./filter.js")(i,E),t("./each.js")(i,E),t("./any.js")(i),h.toFastProperties(i),h.toFastProperties(i.prototype),u({a:1}),u({b:2}),u({c:3}),u(1),u(function(){}),u(void 0),u(!1),u(new i(E)),I.setBounds(m.firstLineError,h.lastLineError),i}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(e,t,r){"use strict";t.exports=function(t,r,n,o,i){function s(e){switch(e){case-2:return[];case-3:return{};case-6:return new Map}}function a(e){var n=this._promise=new t(r);e instanceof t&&n._propagateFrom(e,3),n._setOnCancel(this),this._values=e,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var u=e("./util");u.isArray;return u.inherits(a,i),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function e(r,i){var a=n(this._values,this._promise);if(a instanceof t){a=a._target();var c=a._bitField;if(this._values=a,0==(50397184&c))return this._promise._setAsyncGuaranteed(),a._then(e,this._reject,void 0,this,i);if(0==(33554432&c))return 0!=(16777216&c)?this._reject(a._reason()):this._cancel();a=a._value()}if(null===(a=u.asArray(a))){var l=o("expecting an array or an iterable object but got "+u.classString(a)).reason();return void this._promise._rejectCallback(l,!1)}if(0===a.length)return void(-5===i?this._resolveEmptyArray():this._resolve(s(i)));this._iterate(a)},a.prototype._iterate=function(e){var r=this.getActualLength(e.length);this._length=r,this._values=this.shouldCopyValues()?new Array(r):this._values;for(var o=this._promise,i=!1,s=null,a=0;a=this._length&&(this._resolve(this._values),!0)},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(e){return this._totalResolved++,this._reject(e),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var e=this._values;if(this._cancel(),e instanceof t)e.cancel();else for(var r=0;r=this._length){var r;if(this._isMap)r=f(this._values);else{r={};for(var n=this.length(),o=0,i=this.length();o>1},t.prototype.props=function(){return s(this)},t.props=function(e){return s(e)}}},{"./es5":13,"./util":36}],26:[function(e,t,r){"use strict";function n(e,t,r,n,o){for(var i=0;i=this._length&&(this._resolve(this._values),!0)},o.prototype._promiseFulfilled=function(e,t){var r=new i;return r._bitField=33554432,r._settledValueField=e,this._promiseResolved(t,r)},o.prototype._promiseRejected=function(e,t){var r=new i;return r._bitField=16777216,r._settledValueField=e,this._promiseResolved(t,r)},t.settle=function(e){return n.deprecated(".settle()",".reflect()"),new o(e).promise()},t.prototype.settle=function(){return t.settle(this)}}},{"./util":36}],31:[function(e,t,r){"use strict";t.exports=function(t,r,n){function o(e){this.constructor$(e),this._howMany=0,this._unwrap=!1,this._initialized=!1}function i(e,t){if((0|t)!==t||t<0)return n("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var r=new o(e),i=r.promise();return r.setHowMany(t),r.init(),i}var s=e("./util"),a=e("./errors").RangeError,u=e("./errors").AggregateError,c=s.isArray,l={};s.inherits(o,r),o.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var e=c(this._values);!this._isResolved()&&e&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},o.prototype.init=function(){this._initialized=!0,this._init()},o.prototype.setUnwrap=function(){this._unwrap=!0},o.prototype.howMany=function(){return this._howMany},o.prototype.setHowMany=function(e){this._howMany=e},o.prototype._promiseFulfilled=function(e){return this._addFulfilled(e),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},o.prototype._promiseRejected=function(e){return this._addRejected(e),this._checkOutcome()},o.prototype._promiseCancelled=function(){return this._values instanceof t||null==this._values?this._cancel():(this._addRejected(l),this._checkOutcome())},o.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var e=new u,t=this.length();t0?this._reject(e):this._cancel(),!0}return!1},o.prototype._fulfilled=function(){return this._totalResolved},o.prototype._rejected=function(){return this._values.length-this.length()},o.prototype._addRejected=function(e){this._values.push(e)},o.prototype._addFulfilled=function(e){this._values[this._totalResolved++]=e},o.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},o.prototype._getRangeError=function(e){var t="Input array must contain at least "+this._howMany+" items but contains only "+e+" items";return new a(t)},o.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},t.some=function(e,t){return i(e,t)},t.prototype.some=function(e){return i(this,e)},t._SomePromiseArray=o}},{"./errors":12,"./util":36}],32:[function(e,t,r){"use strict";t.exports=function(e){function t(e){void 0!==e?(e=e._target(),this._bitField=e._bitField,this._settledValueField=e._isFateSealed()?e._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}t.prototype._settledValue=function(){return this._settledValueField};var r=t.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},n=t.prototype.error=t.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},o=t.prototype.isFulfilled=function(){return 0!=(33554432&this._bitField)},i=t.prototype.isRejected=function(){return 0!=(16777216&this._bitField)},s=t.prototype.isPending=function(){return 0==(50397184&this._bitField)},a=t.prototype.isResolved=function(){return 0!=(50331648&this._bitField)};t.prototype.isCancelled=function(){return 0!=(8454144&this._bitField)},e.prototype.__isCancelled=function(){return 65536==(65536&this._bitField)},e.prototype._isCancelled=function(){return this._target().__isCancelled()},e.prototype.isCancelled=function(){return 0!=(8454144&this._target()._bitField)},e.prototype.isPending=function(){return s.call(this._target())},e.prototype.isRejected=function(){return i.call(this._target())},e.prototype.isFulfilled=function(){return o.call(this._target())},e.prototype.isResolved=function(){return a.call(this._target())},e.prototype.value=function(){return r.call(this._target())},e.prototype.reason=function(){var e=this._target();return e._unsetRejectionIsUnhandled(),n.call(e)},e.prototype._value=function(){return this._settledValue()},e.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},e.PromiseInspection=t}},{}],33:[function(e,t,r){"use strict";t.exports=function(t,r){function n(e,n){if(l(e)){if(e instanceof t)return e;var o=i(e);if(o===c){n&&n._pushContext();var u=t.reject(o.e);return n&&n._popContext(),u}if("function"==typeof o){if(s(e)){var u=new t(r);return e._then(u._fulfill,u._reject,void 0,u,null),u}return a(e,o,n)}}return e}function o(e){return e.then}function i(e){try{return o(e)}catch(e){return c.e=e,c}}function s(e){try{return d.call(e,"_promise0")}catch(e){return!1}}function a(e,n,o){function i(e){a&&(a._resolveCallback(e),a=null)}function s(e){a&&(a._rejectCallback(e,d,!0),a=null)}var a=new t(r),l=a;o&&o._pushContext(),a._captureStackTrace(),o&&o._popContext();var d=!0,f=u.tryCatch(n).call(e,i,s);return d=!1,a&&f===c&&(a._rejectCallback(f.e,!0,!0),a=null),l}var u=e("./util"),c=u.errorObj,l=u.isObject,d={}.hasOwnProperty;return n}},{"./util":36}],34:[function(e,t,r){"use strict";t.exports=function(t,r,n){function o(e){this.handle=e}function i(e){return clearTimeout(this.handle),e}function s(e){throw clearTimeout(this.handle),e}var a=e("./util"),u=t.TimeoutError;o.prototype._resultCancelled=function(){clearTimeout(this.handle)};var c=function(e){return l(+this).thenReturn(e)},l=t.delay=function(e,i){var s,a;return void 0!==i?(s=t.resolve(i)._then(c,null,null,e,void 0),n.cancellation()&&i instanceof t&&s._setOnCancel(i)):(s=new t(r),a=setTimeout(function(){s._fulfill()},+e),n.cancellation()&&s._setOnCancel(new o(a)),s._captureStackTrace()),s._setAsyncGuaranteed(),s};t.prototype.delay=function(e){return l(e,this)};var d=function(e,t,r){var n;n="string"!=typeof t?t instanceof Error?t:new u("operation timed out"):new u(t),a.markAsOriginatingFromRejection(n),e._attachExtraTrace(n),e._reject(n),null!=r&&r.cancel()};t.prototype.timeout=function(e,t){e=+e;var r,a,u=new o(setTimeout(function(){r.isPending()&&d(r,t,a)},e));return n.cancellation()?(a=this.then(),r=a._then(i,s,void 0,u,void 0),r._setOnCancel(u)):r=this._then(i,s,void 0,u,void 0),r}}},{"./util":36}],35:[function(e,t,r){"use strict";t.exports=function(t,r,n,o,i,s){function a(e){setTimeout(function(){throw e},0)}function u(e){var t=n(e);return t!==e&&"function"==typeof e._isDisposable&&"function"==typeof e._getDisposer&&e._isDisposable()&&t._setDisposable(e._getDisposer()),t}function c(e,r){function o(){if(s>=c)return l._fulfill();var i=u(e[s++]);if(i instanceof t&&i._isDisposable()){try{i=n(i._getDisposer().tryDispose(r),e.promise)}catch(e){return a(e)}if(i instanceof t)return i._then(o,a,null,null,null)}o()}var s=0,c=e.length,l=new t(i);return o(),l}function l(e,t,r){this._data=e,this._promise=t,this._context=r}function d(e,t,r){this.constructor$(e,t,r)}function f(e){return l.isDisposer(e)?(this.resources[this.index]._setDisposable(e),e.promise()):e}function p(e){this.length=e,this.promise=null,this[e-1]=null}var h=e("./util"),v=e("./errors").TypeError,m=e("./util").inherits,y=h.errorObj,_=h.tryCatch,g={};l.prototype.data=function(){return this._data},l.prototype.promise=function(){return this._promise},l.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():g},l.prototype.tryDispose=function(e){var t=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=t!==g?this.doDispose(t,e):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},l.isDisposer=function(e){return null!=e&&"function"==typeof e.resource&&"function"==typeof e.tryDispose},m(d,l),d.prototype.doDispose=function(e,t){return this.data().call(e,e,t)},p.prototype._resultCancelled=function(){for(var e=this.length,r=0;r0},t.prototype._getDisposer=function(){return this._disposer},t.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},t.prototype.disposer=function(e){if("function"==typeof e)return new d(e,this,o());throw new v}}},{"./errors":12,"./util":36}],36:[function(t,r,o){"use strict";function i(){try{var e=O;return O=null,e.apply(this,arguments)}catch(e){return j.e=e,j}}function s(e){return O=e,i}function a(e){return null==e||!0===e||!1===e||"string"==typeof e||"number"==typeof e}function u(e){return"function"==typeof e||"object"==typeof e&&null!==e}function c(e){return a(e)?new Error(_(e)):e}function l(e,t){var r,n=e.length,o=new Array(n+1);for(r=0;r1,n=t.length>0&&!(1===t.length&&"constructor"===t[0]),o=P.test(e+"")&&I.names(e).length>0;if(r||n||o)return!0}return!1}catch(e){return!1}}function v(e){function t(){}function r(){return typeof n.foo}t.prototype=e;var n=new t;return r(),r(),e}function m(e){return L.test(e)}function y(e,t,r){for(var n=new Array(e),o=0;o10||t[0]>0}(),K.isNode&&K.toFastProperties(e);try{throw new Error}catch(e){K.lastLineError=e}r.exports=K},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("timers").setImmediate)},{_process:237,timers:249}],90:[function(e,t,r){!function(e,n){"function"==typeof define&&define.amd?define([],n):"object"==typeof r?t.exports=n():e.returnExports=n()}(this,function(){function e(o,i){if("function"!=typeof i)throw new Error("Bad callback given: "+i);if(!o)throw new Error("No options given");var a=o.onResponse;if(o="string"==typeof o?{uri:o}:JSON.parse(JSON.stringify(o)),o.onResponse=a,o.verbose&&(e.log=n()),o.url&&(o.uri=o.url,delete o.url),!o.uri&&""!==o.uri)throw new Error("options.uri is a required argument");if("string"!=typeof o.uri)throw new Error("options.uri must be a string");for(var u=["proxy","_redirectsFollowed","maxRedirects","followRedirect"],c=0;c>18&63,i=u>>12&63,s=u>>6&63,a=63&u,p[d++]=c.charAt(o)+c.charAt(i)+c.charAt(s)+c.charAt(a)}while(l299)&&r.error){e=new Error("CouchDB error: "+(r.error.reason||r.error.error));for(var o in r)e[o]=r[o];return n(e,t,r)}return n(e,t,r)}return"string"==typeof t&&(t={uri:t}),t.json=!0,t.body&&(t.json=t.body),delete t.body,n=n||r,e(t,o)},e})},{}],91:[function(e,t,r){(function(e){!function(n){function o(e){throw new RangeError(D[e])}function i(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function s(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),e=e.replace(A,"."),n+i(e.split("."),t).join(".")}function a(e){for(var t,r,n=[],o=0,i=e.length;o=55296&&t<=56319&&o65535&&(e-=65536,t+=L(e>>>10&1023|55296),e=56320|1023&e),t+=L(e)}).join("")}function c(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:w}function l(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function d(e,t,r){var n=0;for(e=r?P(e/x):e>>1,e+=P(e/t);e>M*k>>1;n+=w)e=P(e/M);return P(n+(M+1)*e/(e+T))}function f(e){var t,r,n,i,s,a,l,f,p,h,v=[],m=e.length,y=0,_=I,g=R;for(r=e.lastIndexOf(C),r<0&&(r=0),n=0;n=128&&o("not-basic"),v.push(e.charCodeAt(n));for(i=r>0?r+1:0;i=m&&o("invalid-input"),f=c(e.charCodeAt(i++)),(f>=w||f>P((E-y)/a))&&o("overflow"),y+=f*a,p=l<=g?S:l>=g+k?k:l-g,!(fP(E/h)&&o("overflow"),a*=h;t=v.length+1,g=d(y-s,t,0==s),P(y/t)>E-_&&o("overflow"),_+=P(y/t),y%=t,v.splice(y++,0,_)}return u(v)}function p(e){var t,r,n,i,s,u,c,f,p,h,v,m,y,_,g,b=[];for(e=a(e),m=e.length,t=I,r=0,s=R,u=0;u=t&&vP((E-r)/y)&&o("overflow"),r+=(c-t)*y,t=c,u=0;uE&&o("overflow"),v==t){for(f=r,p=w;h=p<=s?S:p>=s+k?k:p-s,!(f= 0x80 (not a basic code point)","invalid-input":"Invalid input"},M=w-S,P=Math.floor,L=String.fromCharCode;if(g={version:"1.4.1",ucs2:{decode:a,encode:u},decode:f,encode:p,toASCII:v,toUnicode:h},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return g});else if(m&&y)if(t.exports==m)y.exports=g;else for(b in g)g.hasOwnProperty(b)&&(m[b]=g[b]);else n.punycode=g}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],92:[function(e,t,r){var n=e("base-x");t.exports=n("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},{"base-x":87}],93:[function(e,t,r){"use strict";function n(e){if(e>Q)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=o.prototype,t}function o(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return i(e,t,r)}function i(e,t,r){if("string"==typeof e)return c(e,t);if(ArrayBuffer.isView(e))return l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(V(e,ArrayBuffer)||e&&V(e.buffer,ArrayBuffer))return d(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return o.from(n,t,r);var i=f(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,r) +;throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function s(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function a(e,t,r){return s(e),e<=0?n(e):void 0!==t?"string"==typeof r?n(e).fill(t,r):n(e).fill(t):n(e)}function u(e){return s(e),n(e<0?0:0|p(e))}function c(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!o.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var r=0|v(e,t),i=n(r),s=i.write(e,t);return s!==r&&(i=i.slice(0,s)),i}function l(e){for(var t=e.length<0?0:0|p(e.length),r=n(t),o=0;o=Q)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Q.toString(16)+" bytes");return 0|e}function h(e){return+e!=e&&(e=0),o.alloc(+e)}function v(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||V(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return q(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(i)return n?-1:q(e).length;t=(""+t).toLowerCase(),i=!0}}function m(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,t>>>=0,r<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return O(this,t,r);case"utf8":case"utf-8":return R(this,t,r);case"ascii":return C(this,t,r);case"latin1":case"binary":return j(this,t,r);case"base64":return x(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function y(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function _(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,W(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=o.from(t,n)),o.isBuffer(t))return 0===t.length?-1:g(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):g(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function g(e,t,r,n,o){function i(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}var s=1,a=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,u/=2,r/=2}var c;if(o){var l=-1;for(c=r;ca&&(r=a-u),c=r;c>=0;c--){for(var d=!0,f=0;fo&&(n=o):n=o;var i=t.length;n>i/2&&(n=i/2);for(var s=0;s239?4:i>223?3:i>191?2:1;if(o+a<=r){var u,c,l,d;switch(a){case 1:i<128&&(s=i);break;case 2:u=e[o+1],128==(192&u)&&(d=(31&i)<<6|63&u)>127&&(s=d);break;case 3:u=e[o+1],c=e[o+2],128==(192&u)&&128==(192&c)&&(d=(15&i)<<12|(63&u)<<6|63&c)>2047&&(d<55296||d>57343)&&(s=d);break;case 4:u=e[o+1],c=e[o+2],l=e[o+3],128==(192&u)&&128==(192&c)&&128==(192&l)&&(d=(15&i)<<18|(63&u)<<12|(63&c)<<6|63&l)>65535&&d<1114112&&(s=d)}}null===s?(s=65533,a=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),o+=a}return I(n)}function I(e){var t=e.length;if(t<=J)return String.fromCharCode.apply(String,e);for(var r="",n=0;nn)&&(r=n);for(var o="",i=t;ir)throw new RangeError("Trying to access beyond buffer length")}function M(e,t,r,n,i,s){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function P(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(e,t,r,n,o){return t=+t,r>>>=0,o||P(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38),z.write(e,t,r,n,23,4),r+4}function U(e,t,r,n,o){return t=+t,r>>>=0,o||P(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308),z.write(e,t,r,n,52,8),r+8}function N(e){if(e=e.split("=")[0],e=e.trim().replace(Y,""),e.length<2)return"";for(;e.length%4!=0;)e+="=";return e}function F(e){return e<16?"0"+e.toString(16):e.toString(16)}function q(e,t){t=t||1/0;for(var r,n=e.length,o=null,i=[],s=0;s55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function B(e){for(var t=[],r=0;r>8,o=r%256,i.push(o),i.push(n);return i}function G(e){return H.toByteArray(N(e))}function $(e,t,r,n){for(var o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function V(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function W(e){return e!==e}var H=e("base64-js"),z=e("ieee754");r.Buffer=o,r.SlowBuffer=h,r.INSPECT_MAX_BYTES=50;var Q=2147483647;r.kMaxLength=Q,o.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),o.poolSize=8192,o.from=function(e,t,r){return i(e,t,r)},o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,o.alloc=function(e,t,r){return a(e,t,r)},o.allocUnsafe=function(e){return u(e)},o.allocUnsafeSlow=function(e){return u(e)},o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.compare=function(e,t){if(V(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),V(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var r=e.length,n=t.length,i=0,s=Math.min(r,n);it&&(e+=" ... "),""},o.prototype.compare=function(e,t,r,n,i){if(V(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;for(var s=i-n,a=r-t,u=Math.min(s,a),c=this.slice(n,i),l=e.slice(t,r),d=0;d>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return b(this,e,t,r);case"utf8":case"utf-8":return E(this,e,t,r);case"ascii":return w(this,e,t,r);case"latin1":case"binary":return S(this,e,t,r);case"base64":return k(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var J=4096;o.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||D(e,t,this.length);for(var n=this[e],o=1,i=0;++i>>=0,t>>>=0,r||D(e,t,this.length);for(var n=this[e+--t],o=1;t>0&&(o*=256);)n+=this[e+--t]*o;return n},o.prototype.readUInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||D(e,t,this.length);for(var n=this[e],o=1,i=0;++i=o&&(n-=Math.pow(2,8*t)),n},o.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||D(e,t,this.length);for(var n=t,o=1,i=this[e+--n];n>0&&(o*=256);)i+=this[e+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},o.prototype.readInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||D(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt16BE=function(e,t){e>>>=0,t||D(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return e>>>=0,t||D(e,4,this.length),z.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||D(e,4,this.length),z.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||D(e,8,this.length),z.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||D(e,8,this.length),z.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){M(this,e,t,r,Math.pow(2,8*r)-1,0)}var o=1,i=0;for(this[t]=255&e;++i>>=0,r>>>=0,!n){M(this,e,t,r,Math.pow(2,8*r)-1,0)}var o=r-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+r},o.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var o=Math.pow(2,8*r-1);M(this,e,t,r,o-1,-o)}var i=0,s=1,a=0;for(this[t]=255&e;++i>0)-a&255;return t+r},o.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var o=Math.pow(2,8*r-1);M(this,e,t,r,o-1,-o)}var i=r-1,s=1,a=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/s>>0)-a&255;return t+r},o.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeFloatLE=function(e,t,r){return L(this,e,t,!0,r)},o.prototype.writeFloatBE=function(e,t,r){return L(this,e,t,!1,r)},o.prototype.writeDoubleLE=function(e,t,r){return U(this,e,t,!0,r)},o.prototype.writeDoubleBE=function(e,t,r){return U(this,e,t,!1,r)},o.prototype.copy=function(e,t,r,n){if(!o.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--s)e[s+t]=this[s+r];else Uint8Array.prototype.set.call(e,this.subarray(r,n),t);return i},o.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!o.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){var i=e.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(e=i)}}else"number"==typeof e&&(e&=255);if(t<0||this.length>>=0,r=void 0===r?this.length:r>>>0,e||(e=0);var s;if("number"==typeof e)for(s=t;s0&&!c.test(t))throw new TypeError("invalid parameter value");return'"'+t.replace(f,"\\$1")+'"'}function a(e){this.parameters=Object.create(null),this.type=e}var u=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,c=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,l=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,d=/\\([\u000b\u0020-\u00ff])/g,f=/([\\"])/g,p=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;r.format=n,r.parse=o},{}],95:[function(e,t,r){e("../modules/web.dom.iterable"),e("../modules/es6.string.iterator"),t.exports=e("../modules/core.get-iterator")},{"../modules/core.get-iterator":204,"../modules/es6.string.iterator":222,"../modules/web.dom.iterable":233}],96:[function(e,t,r){e("../modules/web.dom.iterable"),e("../modules/es6.string.iterator"),t.exports=e("../modules/core.is-iterable")},{"../modules/core.is-iterable":205,"../modules/es6.string.iterator":222,"../modules/web.dom.iterable":233}],97:[function(e,t,r){var n=e("../../modules/_core"),o=n.JSON||(n.JSON={stringify:JSON.stringify});t.exports=function(e){return o.stringify.apply(o,arguments)}},{"../../modules/_core":131}],98:[function(e,t,r){e("../../modules/es6.number.is-finite"),t.exports=e("../../modules/_core").Number.isFinite},{"../../modules/_core":131,"../../modules/es6.number.is-finite":207}],99:[function(e,t,r){e("../../modules/es6.number.is-integer"),t.exports=e("../../modules/_core").Number.isInteger},{"../../modules/_core":131,"../../modules/es6.number.is-integer":208}],100:[function(e,t,r){e("../../modules/es6.object.assign"),t.exports=e("../../modules/_core").Object.assign},{"../../modules/_core":131,"../../modules/es6.object.assign":209}],101:[function(e,t,r){e("../../modules/es6.object.create");var n=e("../../modules/_core").Object;t.exports=function(e,t){return n.create(e,t)}},{"../../modules/_core":131,"../../modules/es6.object.create":210}],102:[function(e,t,r){e("../../modules/es6.object.define-property");var n=e("../../modules/_core").Object;t.exports=function(e,t,r){return n.defineProperty(e,t,r)}},{"../../modules/_core":131,"../../modules/es6.object.define-property":211}],103:[function(e,t,r){e("../../modules/es7.object.entries"),t.exports=e("../../modules/_core").Object.entries},{"../../modules/_core":131,"../../modules/es7.object.entries":224}],104:[function(e,t,r){e("../../modules/es6.object.freeze"),t.exports=e("../../modules/_core").Object.freeze},{"../../modules/_core":131,"../../modules/es6.object.freeze":212}],105:[function(e,t,r){e("../../modules/es6.object.get-prototype-of"),t.exports=e("../../modules/_core").Object.getPrototypeOf},{"../../modules/_core":131,"../../modules/es6.object.get-prototype-of":213}],106:[function(e,t,r){e("../../modules/es6.object.keys"),t.exports=e("../../modules/_core").Object.keys},{"../../modules/_core":131,"../../modules/es6.object.keys":214}],107:[function(e,t,r){e("../../modules/es6.object.set-prototype-of"),t.exports=e("../../modules/_core").Object.setPrototypeOf},{"../../modules/_core":131,"../../modules/es6.object.set-prototype-of":215}],108:[function(e,t,r){e("../../modules/es7.object.values"),t.exports=e("../../modules/_core").Object.values},{"../../modules/_core":131,"../../modules/es7.object.values":225}],109:[function(e,t,r){e("../modules/es6.object.to-string"),e("../modules/es6.string.iterator"),e("../modules/web.dom.iterable"),e("../modules/es6.promise"),e("../modules/es7.promise.finally"),e("../modules/es7.promise.try"),t.exports=e("../modules/_core").Promise},{"../modules/_core":131,"../modules/es6.object.to-string":216,"../modules/es6.promise":217,"../modules/es6.string.iterator":222,"../modules/es7.promise.finally":226,"../modules/es7.promise.try":227,"../modules/web.dom.iterable":233}],110:[function(e,t,r){e("../../modules/es6.reflect.construct"),t.exports=e("../../modules/_core").Reflect.construct},{"../../modules/_core":131,"../../modules/es6.reflect.construct":218}],111:[function(e,t,r){e("../../modules/es6.reflect.get-prototype-of"),t.exports=e("../../modules/_core").Reflect.getPrototypeOf},{"../../modules/_core":131,"../../modules/es6.reflect.get-prototype-of":219}],112:[function(e,t,r){e("../../modules/es6.reflect.set-prototype-of"),t.exports=e("../../modules/_core").Reflect.setPrototypeOf},{"../../modules/_core":131,"../../modules/es6.reflect.set-prototype-of":220}],113:[function(e,t,r){e("../modules/es6.object.to-string"),e("../modules/es6.string.iterator"),e("../modules/web.dom.iterable"),e("../modules/es6.set"),e("../modules/es7.set.to-json"),e("../modules/es7.set.of"),e("../modules/es7.set.from"),t.exports=e("../modules/_core").Set},{"../modules/_core":131,"../modules/es6.object.to-string":216,"../modules/es6.set":221,"../modules/es6.string.iterator":222,"../modules/es7.set.from":228,"../modules/es7.set.of":229,"../modules/es7.set.to-json":230,"../modules/web.dom.iterable":233}],114:[function(e,t,r){e("../../modules/es6.symbol"),e("../../modules/es6.object.to-string"),e("../../modules/es7.symbol.async-iterator"),e("../../modules/es7.symbol.observable"),t.exports=e("../../modules/_core").Symbol},{"../../modules/_core":131,"../../modules/es6.object.to-string":216,"../../modules/es6.symbol":223,"../../modules/es7.symbol.async-iterator":231,"../../modules/es7.symbol.observable":232}],115:[function(e,t,r){e("../../modules/es6.string.iterator"),e("../../modules/web.dom.iterable"),t.exports=e("../../modules/_wks-ext").f("iterator")},{"../../modules/_wks-ext":201,"../../modules/es6.string.iterator":222,"../../modules/web.dom.iterable":233}],116:[function(e,t,r){t.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},{}],117:[function(e,t,r){t.exports=function(){}},{}],118:[function(e,t,r){t.exports=function(e,t,r,n){if(!(e instanceof t)||void 0!==n&&n in e)throw TypeError(r+": incorrect invocation!");return e}},{}],119:[function(e,t,r){var n=e("./_is-object");t.exports=function(e){if(!n(e))throw TypeError(e+" is not an object!");return e}},{"./_is-object":151}],120:[function(e,t,r){var n=e("./_for-of");t.exports=function(e,t){var r=[];return n(e,!1,r.push,r,t),r}},{"./_for-of":140}],121:[function(e,t,r){var n=e("./_to-iobject"),o=e("./_to-length"),i=e("./_to-absolute-index");t.exports=function(e){return function(t,r,s){var a,u=n(t),c=o(u.length),l=i(s,c);if(e&&r!=r){for(;c>l;)if((a=u[l++])!=a)return!0}else for(;c>l;l++)if((e||l in u)&&u[l]===r)return e||l||0;return!e&&-1}}},{"./_to-absolute-index":191,"./_to-iobject":193,"./_to-length":194}],122:[function(e,t,r){var n=e("./_ctx"),o=e("./_iobject"),i=e("./_to-object"),s=e("./_to-length"),a=e("./_array-species-create");t.exports=function(e,t){var r=1==e,u=2==e,c=3==e,l=4==e,d=6==e,f=5==e||d,p=t||a;return function(t,a,h){for(var v,m,y=i(t),_=o(y),g=n(a,h,3),b=s(_.length),E=0,w=r?p(t,b):u?p(t,0):void 0;b>E;E++)if((f||E in _)&&(v=_[E],m=g(v,E,y),e))if(r)w[E]=m;else if(m)switch(e){case 3:return!0;case 5:return v;case 6:return E;case 2:w.push(v)}else if(l)return!1;return d?-1:c||l?l:w}}},{"./_array-species-create":124,"./_ctx":132,"./_iobject":147,"./_to-length":194,"./_to-object":195}],123:[function(e,t,r){var n=e("./_is-object"),o=e("./_is-array"),i=e("./_wks")("species");t.exports=function(e){var t;return o(e)&&(t=e.constructor,"function"!=typeof t||t!==Array&&!o(t.prototype)||(t=void 0),n(t)&&null===(t=t[i])&&(t=void 0)),void 0===t?Array:t}},{"./_is-array":149,"./_is-object":151,"./_wks":202}],124:[function(e,t,r){var n=e("./_array-species-constructor");t.exports=function(e,t){return new(n(e))(t)}},{"./_array-species-constructor":123}],125:[function(e,t,r){"use strict";var n=e("./_a-function"),o=e("./_is-object"),i=e("./_invoke"),s=[].slice,a={},u=function(e,t,r){if(!(t in a)){for(var n=[],o=0;o1?arguments[1]:void 0,3);r=r?r.n:this._f;)for(n(r.v,r.k,this);r&&r.r;)r=r.p},has:function(e){return!!m(h(this,t),e)}}),f&&n(l.prototype,"size",{get:function(){return h(this,t)[v]}}),l},def:function(e,t,r){var n,o,i=m(e,t);return i?i.v=r:(e._l=i={i:o=p(t,!0),k:t,v:r,p:n=e._l,n:void 0,r:!1},e._f||(e._f=i),n&&(n.n=i),e[v]++,"F"!==o&&(e._i[o]=i)),e},getEntry:m,setStrong:function(e,t,r){c(e,t,function(e,r){this._t=h(e,t),this._k=r,this._l=void 0},function(){for(var e=this,t=e._k,r=e._l;r&&r.r;)r=r.p;return e._t&&(e._l=r=r?r.n:e._t._f)?"keys"==t?l(0,r.k):"values"==t?l(0,r.v):l(0,[r.k,r.v]):(e._t=void 0,l(1))},r?"entries":"values",!r,!0),d(t)}}},{"./_an-instance":118,"./_ctx":132,"./_descriptors":134,"./_for-of":140,"./_iter-define":154,"./_iter-step":156,"./_meta":159,"./_object-create":163,"./_object-dp":164,"./_redefine-all":179,"./_set-species":184,"./_validate-collection":199}],129:[function(e,t,r){var n=e("./_classof"),o=e("./_array-from-iterable");t.exports=function(e){return function(){if(n(this)!=e)throw TypeError(e+"#toJSON isn't generic");return o(this)}}},{"./_array-from-iterable":120,"./_classof":126}],130:[function(e,t,r){"use strict";var n=e("./_global"),o=e("./_export"),i=e("./_meta"),s=e("./_fails"),a=e("./_hide"),u=e("./_redefine-all"),c=e("./_for-of"),l=e("./_an-instance"),d=e("./_is-object"),f=e("./_set-to-string-tag"),p=e("./_object-dp").f,h=e("./_array-methods")(0),v=e("./_descriptors");t.exports=function(e,t,r,m,y,_){var g=n[e],b=g,E=y?"set":"add",w=b&&b.prototype,S={};return v&&"function"==typeof b&&(_||w.forEach&&!s(function(){(new b).entries().next()}))?(b=t(function(t,r){l(t,b,e,"_c"),t._c=new g,void 0!=r&&c(r,y,t[E],t)}), +h("add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON".split(","),function(e){var t="add"==e||"set"==e;e in w&&(!_||"clear"!=e)&&a(b.prototype,e,function(r,n){if(l(this,b,e),!t&&_&&!d(r))return"get"==e&&void 0;var o=this._c[e](0===r?0:r,n);return t?this:o})}),_||p(b.prototype,"size",{get:function(){return this._c.size}})):(b=m.getConstructor(t,e,y,E),u(b.prototype,r),i.NEED=!0),f(b,e),S[e]=b,o(o.G+o.W+o.F,S),_||m.setStrong(b,e,y),b}},{"./_an-instance":118,"./_array-methods":122,"./_descriptors":134,"./_export":138,"./_fails":139,"./_for-of":140,"./_global":141,"./_hide":143,"./_is-object":151,"./_meta":159,"./_object-dp":164,"./_redefine-all":179,"./_set-to-string-tag":185}],131:[function(e,t,r){var n=t.exports={version:"2.5.7"};"number"==typeof __e&&(__e=n)},{}],132:[function(e,t,r){var n=e("./_a-function");t.exports=function(e,t,r){if(n(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,n){return e.call(t,r,n)};case 3:return function(r,n,o){return e.call(t,r,n,o)}}return function(){return e.apply(t,arguments)}}},{"./_a-function":116}],133:[function(e,t,r){t.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},{}],134:[function(e,t,r){t.exports=!e("./_fails")(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},{"./_fails":139}],135:[function(e,t,r){var n=e("./_is-object"),o=e("./_global").document,i=n(o)&&n(o.createElement);t.exports=function(e){return i?o.createElement(e):{}}},{"./_global":141,"./_is-object":151}],136:[function(e,t,r){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},{}],137:[function(e,t,r){var n=e("./_object-keys"),o=e("./_object-gops"),i=e("./_object-pie");t.exports=function(e){var t=n(e),r=o.f;if(r)for(var s,a=r(e),u=i.f,c=0;a.length>c;)u.call(e,s=a[c++])&&t.push(s);return t}},{"./_object-gops":169,"./_object-keys":172,"./_object-pie":173}],138:[function(e,t,r){var n=e("./_global"),o=e("./_core"),i=e("./_ctx"),s=e("./_hide"),a=e("./_has"),u=function(e,t,r){var c,l,d,f=e&u.F,p=e&u.G,h=e&u.S,v=e&u.P,m=e&u.B,y=e&u.W,_=p?o:o[t]||(o[t]={}),g=_.prototype,b=p?n:h?n[t]:(n[t]||{}).prototype;p&&(r=t);for(c in r)(l=!f&&b&&void 0!==b[c])&&a(_,c)||(d=l?b[c]:r[c],_[c]=p&&"function"!=typeof b[c]?r[c]:m&&l?i(d,n):y&&b[c]==d?function(e){var t=function(t,r,n){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,r)}return new e(t,r,n)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(d):v&&"function"==typeof d?i(Function.call,d):d,v&&((_.virtual||(_.virtual={}))[c]=d,e&u.R&&g&&!g[c]&&s(g,c,d)))};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,t.exports=u},{"./_core":131,"./_ctx":132,"./_global":141,"./_has":142,"./_hide":143}],139:[function(e,t,r){t.exports=function(e){try{return!!e()}catch(e){return!0}}},{}],140:[function(e,t,r){var n=e("./_ctx"),o=e("./_iter-call"),i=e("./_is-array-iter"),s=e("./_an-object"),a=e("./_to-length"),u=e("./core.get-iterator-method"),c={},l={},r=t.exports=function(e,t,r,d,f){var p,h,v,m,y=f?function(){return e}:u(e),_=n(r,d,t?2:1),g=0;if("function"!=typeof y)throw TypeError(e+" is not iterable!");if(i(y)){for(p=a(e.length);p>g;g++)if((m=t?_(s(h=e[g])[0],h[1]):_(e[g]))===c||m===l)return m}else for(v=y.call(e);!(h=v.next()).done;)if((m=o(v,_,h.value,t))===c||m===l)return m};r.BREAK=c,r.RETURN=l},{"./_an-object":119,"./_ctx":132,"./_is-array-iter":148,"./_iter-call":152,"./_to-length":194,"./core.get-iterator-method":203}],141:[function(e,t,r){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},{}],142:[function(e,t,r){var n={}.hasOwnProperty;t.exports=function(e,t){return n.call(e,t)}},{}],143:[function(e,t,r){var n=e("./_object-dp"),o=e("./_property-desc");t.exports=e("./_descriptors")?function(e,t,r){return n.f(e,t,o(1,r))}:function(e,t,r){return e[t]=r,e}},{"./_descriptors":134,"./_object-dp":164,"./_property-desc":178}],144:[function(e,t,r){var n=e("./_global").document;t.exports=n&&n.documentElement},{"./_global":141}],145:[function(e,t,r){t.exports=!e("./_descriptors")&&!e("./_fails")(function(){return 7!=Object.defineProperty(e("./_dom-create")("div"),"a",{get:function(){return 7}}).a})},{"./_descriptors":134,"./_dom-create":135,"./_fails":139}],146:[function(e,t,r){t.exports=function(e,t,r){var n=void 0===r;switch(t.length){case 0:return n?e():e.call(r);case 1:return n?e(t[0]):e.call(r,t[0]);case 2:return n?e(t[0],t[1]):e.call(r,t[0],t[1]);case 3:return n?e(t[0],t[1],t[2]):e.call(r,t[0],t[1],t[2]);case 4:return n?e(t[0],t[1],t[2],t[3]):e.call(r,t[0],t[1],t[2],t[3])}return e.apply(r,t)}},{}],147:[function(e,t,r){var n=e("./_cof");t.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==n(e)?e.split(""):Object(e)}},{"./_cof":127}],148:[function(e,t,r){var n=e("./_iterators"),o=e("./_wks")("iterator"),i=Array.prototype;t.exports=function(e){return void 0!==e&&(n.Array===e||i[o]===e)}},{"./_iterators":157,"./_wks":202}],149:[function(e,t,r){var n=e("./_cof");t.exports=Array.isArray||function(e){return"Array"==n(e)}},{"./_cof":127}],150:[function(e,t,r){var n=e("./_is-object"),o=Math.floor;t.exports=function(e){return!n(e)&&isFinite(e)&&o(e)===e}},{"./_is-object":151}],151:[function(e,t,r){t.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},{}],152:[function(e,t,r){var n=e("./_an-object");t.exports=function(e,t,r,o){try{return o?t(n(r)[0],r[1]):t(r)}catch(t){var i=e.return;throw void 0!==i&&n(i.call(e)),t}}},{"./_an-object":119}],153:[function(e,t,r){"use strict";var n=e("./_object-create"),o=e("./_property-desc"),i=e("./_set-to-string-tag"),s={};e("./_hide")(s,e("./_wks")("iterator"),function(){return this}),t.exports=function(e,t,r){e.prototype=n(s,{next:o(1,r)}),i(e,t+" Iterator")}},{"./_hide":143,"./_object-create":163,"./_property-desc":178,"./_set-to-string-tag":185,"./_wks":202}],154:[function(e,t,r){"use strict";var n=e("./_library"),o=e("./_export"),i=e("./_redefine"),s=e("./_hide"),a=e("./_iterators"),u=e("./_iter-create"),c=e("./_set-to-string-tag"),l=e("./_object-gpo"),d=e("./_wks")("iterator"),f=!([].keys&&"next"in[].keys()),p=function(){return this};t.exports=function(e,t,r,h,v,m,y){u(r,t,h);var _,g,b,E=function(e){if(!f&&e in T)return T[e];switch(e){case"keys":case"values":return function(){return new r(this,e)}}return function(){return new r(this,e)}},w=t+" Iterator",S="values"==v,k=!1,T=e.prototype,x=T[d]||T["@@iterator"]||v&&T[v],R=x||E(v),I=v?S?E("entries"):R:void 0,C="Array"==t?T.entries||x:x;if(C&&(b=l(C.call(new e)))!==Object.prototype&&b.next&&(c(b,w,!0),n||"function"==typeof b[d]||s(b,d,p)),S&&x&&"values"!==x.name&&(k=!0,R=function(){return x.call(this)}),n&&!y||!f&&!k&&T[d]||s(T,d,R),a[t]=R,a[w]=p,v)if(_={values:S?R:E("values"),keys:m?R:E("keys"),entries:I},y)for(g in _)g in T||i(T,g,_[g]);else o(o.P+o.F*(f||k),t,_);return _}},{"./_export":138,"./_hide":143,"./_iter-create":153,"./_iterators":157,"./_library":158,"./_object-gpo":170,"./_redefine":180,"./_set-to-string-tag":185,"./_wks":202}],155:[function(e,t,r){var n=e("./_wks")("iterator"),o=!1;try{var i=[7][n]();i.return=function(){o=!0},Array.from(i,function(){throw 2})}catch(e){}t.exports=function(e,t){if(!t&&!o)return!1;var r=!1;try{var i=[7],s=i[n]();s.next=function(){return{done:r=!0}},i[n]=function(){return s},e(i)}catch(e){}return r}},{"./_wks":202}],156:[function(e,t,r){t.exports=function(e,t){return{value:t,done:!!e}}},{}],157:[function(e,t,r){t.exports={}},{}],158:[function(e,t,r){t.exports=!0},{}],159:[function(e,t,r){var n=e("./_uid")("meta"),o=e("./_is-object"),i=e("./_has"),s=e("./_object-dp").f,a=0,u=Object.isExtensible||function(){return!0},c=!e("./_fails")(function(){return u(Object.preventExtensions({}))}),l=function(e){s(e,n,{value:{i:"O"+ ++a,w:{}}})},d=function(e,t){if(!o(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!i(e,n)){if(!u(e))return"F";if(!t)return"E";l(e)}return e[n].i},f=function(e,t){if(!i(e,n)){if(!u(e))return!0;if(!t)return!1;l(e)}return e[n].w},p=function(e){return c&&h.NEED&&u(e)&&!i(e,n)&&l(e),e},h=t.exports={KEY:n,NEED:!1,fastKey:d,getWeak:f,onFreeze:p}},{"./_fails":139,"./_has":142,"./_is-object":151,"./_object-dp":164,"./_uid":197}],160:[function(e,t,r){var n=e("./_global"),o=e("./_task").set,i=n.MutationObserver||n.WebKitMutationObserver,s=n.process,a=n.Promise,u="process"==e("./_cof")(s);t.exports=function(){var e,t,r,c=function(){var n,o;for(u&&(n=s.domain)&&n.exit();e;){o=e.fn,e=e.next;try{o()}catch(n){throw e?r():t=void 0,n}}t=void 0,n&&n.enter()};if(u)r=function(){s.nextTick(c)};else if(!i||n.navigator&&n.navigator.standalone)if(a&&a.resolve){var l=a.resolve(void 0);r=function(){l.then(c)}}else r=function(){o.call(n,c)};else{var d=!0,f=document.createTextNode("");new i(c).observe(f,{characterData:!0}),r=function(){f.data=d=!d}}return function(n){var o={fn:n,next:void 0};t&&(t.next=o),e||(e=o,r()),t=o}}},{"./_cof":127,"./_global":141,"./_task":190}],161:[function(e,t,r){"use strict";function n(e){var t,r;this.promise=new e(function(e,n){if(void 0!==t||void 0!==r)throw TypeError("Bad Promise constructor");t=e,r=n}),this.resolve=o(t),this.reject=o(r)}var o=e("./_a-function");t.exports.f=function(e){return new n(e)}},{"./_a-function":116}],162:[function(e,t,r){"use strict";var n=e("./_object-keys"),o=e("./_object-gops"),i=e("./_object-pie"),s=e("./_to-object"),a=e("./_iobject"),u=Object.assign;t.exports=!u||e("./_fails")(function(){var e={},t={},r=Symbol(),n="abcdefghijklmnopqrst";return e[r]=7,n.split("").forEach(function(e){t[e]=e}),7!=u({},e)[r]||Object.keys(u({},t)).join("")!=n})?function(e,t){for(var r=s(e),u=arguments.length,c=1,l=o.f,d=i.f;u>c;)for(var f,p=a(arguments[c++]),h=l?n(p).concat(l(p)):n(p),v=h.length,m=0;v>m;)d.call(p,f=h[m++])&&(r[f]=p[f]);return r}:u},{"./_fails":139,"./_iobject":147,"./_object-gops":169,"./_object-keys":172,"./_object-pie":173,"./_to-object":195}],163:[function(e,t,r){var n=e("./_an-object"),o=e("./_object-dps"),i=e("./_enum-bug-keys"),s=e("./_shared-key")("IE_PROTO"),a=function(){},u=function(){var t,r=e("./_dom-create")("iframe"),n=i.length;for(r.style.display="none",e("./_html").appendChild(r),r.src="javascript:",t=r.contentWindow.document,t.open(),t.write(" + + + diff --git a/origin_migrator/dest/dest.js b/origin_migrator/dest/dest.js new file mode 100644 index 0000000000..d5ffd42b85 --- /dev/null +++ b/origin_migrator/dest/dest.js @@ -0,0 +1,125 @@ +/* +Copyright 2018 New Vector Ltd + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +const SOURCE_ORIGIN = 'file://'; + +const IndexedDBCryptoStore = window.matrixcs.IndexedDBCryptoStore; +const cryptoStore = new IndexedDBCryptoStore(window.indexedDB, 'matrix-js-sdk:crypto'); + +let accountStored = 0; +let sessionsStored = 0; +let inboundGroupSessionsStored = 0; +let deviceDataStored = 0; +let roomsStored = 0; +let localStorageKeysStored = 0; + +const promises = []; + +async function onMessage(e) { + if (e.origin !== SOURCE_ORIGIN) return; + + const data = e.data.data; // bleh, naming clash + switch (e.data.cmd) { + case 'init': + // start with clean stores before we migrate data in + window.localStorage.clear(); + await cryptoStore.deleteAllData(); + + e.source.postMessage({ + cmd: 'initOK', + }, SOURCE_ORIGIN); + break; + case 'storeAccount': + promises.push(cryptoStore.doTxn( + 'readwrite', [IndexedDBCryptoStore.STORE_ACCOUNT], + (txn) => { + cryptoStore.storeAccount(txn, data); + }, + ).then(() => { + ++accountStored; + })); + break; + case 'storeSessions': + promises.push(cryptoStore.doTxn( + 'readwrite', [IndexedDBCryptoStore.STORE_SESSIONS], + (txn) => { + for (const sess of data) { + cryptoStore.storeEndToEndSession(sess.deviceKey, sess.sessionId, sess, txn); + } + }, + ).then(() => { + sessionsStored += data.length; + })); + break; + case 'storeInboundGroupSessions': + promises.push(cryptoStore.doTxn( + 'readwrite', [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], + (txn) => { + for (const sess of data) { + cryptoStore.addEndToEndInboundGroupSession( + sess.senderKey, sess.sessionId, sess.sessionData, txn, + ); + } + }, + ).then(() => { + inboundGroupSessionsStored += data.length; + })); + break; + case 'storeDeviceData': + promises.push(cryptoStore.doTxn( + 'readwrite', [IndexedDBCryptoStore.STORE_DEVICE_DATA], + (txn) => { + cryptoStore.storeEndToEndDeviceData(data, txn); + }, + ).then(() => { + ++deviceDataStored; + })); + break; + case 'storeRooms': + promises.push(cryptoStore.doTxn( + 'readwrite', [IndexedDBCryptoStore.STORE_ROOMS], + (txn) => { + for (const [roomId, roomInfo] of Object.entries(data)) { + cryptoStore.storeEndToEndRoom(roomId, roomInfo, txn); + } + }, + ).then(() => { + ++roomsStored; + })); + break; + case 'storeLocalStorage': + window.localStorage.setItem(data.key, data.val); + ++localStorageKeysStored; + break; + case 'getSummary': + await Promise.all(promises); + e.source.postMessage({ + cmd: 'summary', + data: { + accountStored, + sessionsStored, + inboundGroupSessionsStored, + deviceDataStored, + roomsStored, + localStorageKeysStored, + }, + }, SOURCE_ORIGIN); + break; + } +} + +window.addEventListener('message', onMessage); + diff --git a/origin_migrator/source.html b/origin_migrator/source.html new file mode 100644 index 0000000000..ade265c777 --- /dev/null +++ b/origin_migrator/source.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/origin_migrator/source.js b/origin_migrator/source.js new file mode 100644 index 0000000000..0cbee89f94 --- /dev/null +++ b/origin_migrator/source.js @@ -0,0 +1,210 @@ +/* +Copyright 2018 New Vector Ltd + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +const TARGET_ORIGIN = 'vector://vector'; +const BATCH_SIZE = 500; +let destFrame; + +let initResolver = null; +let getSummaryResolver = null; + +function onMessage(e) { + if (e.origin !== TARGET_ORIGIN) return; + + if (e.data.cmd === 'initOK' && initResolver) { + initResolver(); + initResolver = null; + } else if (e.data.cmd === 'summary' && getSummaryResolver) { + getSummaryResolver(e.data.data); + getSummaryResolver = null; + } +} + +async function initDestFrame() { + return new Promise(resolve => { + initResolver = resolve; + destFrame.postMessage({ + cmd: 'init', + }, TARGET_ORIGIN); + }); +} + +async function getSummary() { + return new Promise(resolve => { + getSummaryResolver = resolve; + destFrame.postMessage({ + cmd: 'getSummary', + }, TARGET_ORIGIN); + }); +} + +async function doMigrate() { + let accountSent = 0; + let sessionsSent = 0; + let inboundGroupSessionsSent = 0; + let deviceDataSent = 0; + let roomsSent = 0; + let localStorageKeysSent = 0; + + if (!window.ipcRenderer) { + console.error("ipcRenderer not found"); + return; + } + + if (window.localStorage.getItem('mx_user_id') === null) { + window.ipcRenderer.send("origin_migration_nodata"); + return; + } + + destFrame = window.parent.frames.dest; + + await initDestFrame(); + + const IndexedDBCryptoStore = window.matrixcs.IndexedDBCryptoStore; + + const cryptoStore = new IndexedDBCryptoStore(window.indexedDB, 'matrix-js-sdk:crypto'); + + await cryptoStore.doTxn( + 'readonly', [IndexedDBCryptoStore.STORE_ACCOUNT], + (txn) => { + cryptoStore.getAccount(txn, (account) => { + destFrame.postMessage({ + cmd: 'storeAccount', + data: account, + }, TARGET_ORIGIN); + ++accountSent; + }); + }, + ); + + await cryptoStore.doTxn( + 'readonly', [IndexedDBCryptoStore.STORE_SESSIONS], + (txn) => { + let sessBatch = []; + cryptoStore.getAllEndToEndSessions(txn, (sessInfo) => { + if (sessInfo) { + ++sessionsSent; + sessBatch.push(sessInfo); + } + if (sessBatch.length >= BATCH_SIZE || sessInfo === null) { + destFrame.postMessage({ + cmd: 'storeSessions', + data: sessBatch, + }, TARGET_ORIGIN); + sessBatch = []; + } + }); + }, + ); + + await cryptoStore.doTxn( + 'readonly', [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], + (txn) => { + let sessBatch = []; + cryptoStore.getAllEndToEndInboundGroupSessions(txn, (sessInfo) => { + if (sessInfo) { + ++inboundGroupSessionsSent; + sessBatch.push(sessInfo); + } + if (sessBatch.length >= BATCH_SIZE || sessInfo === null) { + destFrame.postMessage({ + cmd: 'storeInboundGroupSessions', + data: sessBatch, + }, TARGET_ORIGIN); + sessBatch = []; + } + }); + }, + ); + + await cryptoStore.doTxn( + 'readonly', [IndexedDBCryptoStore.STORE_DEVICE_DATA], + (txn) => { + cryptoStore.getEndToEndDeviceData(txn, (deviceData) => { + destFrame.postMessage({ + cmd: 'storeDeviceData', + data: deviceData, + }, TARGET_ORIGIN); + ++deviceDataSent; + }); + }, + ); + + await cryptoStore.doTxn( + 'readonly', [IndexedDBCryptoStore.STORE_ROOMS], + (txn) => { + cryptoStore.getEndToEndRooms(txn, (rooms) => { + destFrame.postMessage({ + cmd: 'storeRooms', + data: rooms, + }, TARGET_ORIGIN); + ++roomsSent; + }); + }, + ); + + // we don't bother migrating; + // * sync data (we can just initialsync again) + // * logs + // * key requests (worst case they'll just be re-sent) + // * sessions needing backup (feature isn't available on Electron) + + for (let i = 0; i < window.localStorage.length; ++i) { + const key = window.localStorage.key(i); + const val = window.localStorage.getItem(key); + + destFrame.postMessage({ + cmd: 'storeLocalStorage', + data: { key, val }, + }, TARGET_ORIGIN); + ++localStorageKeysSent; + } + + const summary = await getSummary(); + let success = false; + if ( + summary.accountStored === accountSent && + summary.sessionsStored === sessionsSent && + summary.inboundGroupSessionsStored === inboundGroupSessionsSent && + summary.deviceDataStored === deviceDataSent && + summary.roomsStored === roomsSent && + summary.localStorageKeysStored === localStorageKeysSent + ) { + success = true; + window.localStorage.clear(); + await cryptoStore.deleteAllData(); + + // we don't bother migrating them, but also blow away the sync & logs db, + // otherwise they'll just hang about taking up space + await new Promise(resolve => { + const req = window.indexedDB.deleteDatabase('matrix-js-sdk:riot-web-sync'); + req.onsuccess = resolve; + req.onerror = resolve; + }); + await new Promise(resolve => { + const req = window.indexedDB.deleteDatabase('logs'); + req.onsuccess = resolve; + req.onerror = resolve; + }); + } + + window.ipcRenderer.send("origin_migration_complete", success, { + accountSent, sessionsSent, inboundGroupSessionsSent, + deviceDataSent, roomsSent, localStorageKeysSent, + }, summary); +} + +window.addEventListener('message', onMessage); diff --git a/package.json b/package.json index 9a2db53501..6832e9ceb5 100644 --- a/package.json +++ b/package.json @@ -157,7 +157,8 @@ "img/**" ], "extraResources": [ - "webapp/**/*" + "webapp/**/*", + "origin_migrator/**/*" ], "linux": { "target": "deb", diff --git a/src/vector/index.js b/src/vector/index.js index 36ae067c63..b6fd5ce940 100644 --- a/src/vector/index.js +++ b/src/vector/index.js @@ -224,7 +224,16 @@ async function loadApp() { // set the platform for react sdk if (window.ipcRenderer) { console.log("Using Electron platform"); - PlatformPeg.set(new ElectronPlatform()); + const plaf = new ElectronPlatform(); + PlatformPeg.set(plaf); + + // Electron only: see if we need to do a one-time data + // migration + if (window.localStorage.getItem('mx_user_id') === null) { + console.log("Migrating session from old origin..."); + await plaf.migrateFromOldOrigin(); + console.log("Origin migration complete"); + } } else { console.log("Using Web platform"); PlatformPeg.set(new WebPlatform()); diff --git a/src/vector/platform/ElectronPlatform.js b/src/vector/platform/ElectronPlatform.js index 0bf0068a43..a20b331321 100644 --- a/src/vector/platform/ElectronPlatform.js +++ b/src/vector/platform/ElectronPlatform.js @@ -224,6 +224,10 @@ export default class ElectronPlatform extends VectorBasePlatform { window.location.reload(false); } + async migrateFromOldOrigin() { + return this._ipcCall('origin_migrate'); + } + async _ipcCall(name, ...args) { const ipcCallId = ++this._nextIpcCallId; return new Promise((resolve, reject) => { diff --git a/src/vector/platform/VectorBasePlatform.js b/src/vector/platform/VectorBasePlatform.js index 7523462cfc..602a0c27c9 100644 --- a/src/vector/platform/VectorBasePlatform.js +++ b/src/vector/platform/VectorBasePlatform.js @@ -149,4 +149,12 @@ export default class VectorBasePlatform extends BasePlatform { getDefaultDeviceDisplayName(): string { return _t("Unknown device"); } + + /** + * Migrate account data from a previous origin + * Used only for the electron app + */ + async migrateFromOldOrigin() { + return false; + } }